body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
e6dc51b7c0eac25e49ffee0983de262aaf26d68f151a7f3d6d698c6279fb1f13
def read_unicode_csv_fileobj(fileobj, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL, lineterminator='\n', encoding='utf-8', skiprows=0): 'fileobj can be a StringIO in Py3, but should be a BytesIO in Py2.' if (sys.version_info[0] >= 3): csv_reader = csv.reader(fileobj, delimiter=delimiter, quotechar=quotechar, quoting=quoting, lineterminator=lineterminator) for skip_ix in range(skiprows): next(csv_reader) for row in csv_reader: (yield row) else: csv_reader = csv.reader(fileobj, delimiter=delimiter.encode(encoding), quotechar=quotechar.encode(encoding), quoting=quoting, lineterminator=lineterminator) for skip_ix in range(skiprows): next(csv_reader) for row in csv_reader: (yield [cell.decode(encoding) for cell in row])
fileobj can be a StringIO in Py3, but should be a BytesIO in Py2.
indra/util/__init__.py
read_unicode_csv_fileobj
pupster90/indra
0
python
def read_unicode_csv_fileobj(fileobj, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL, lineterminator='\n', encoding='utf-8', skiprows=0): if (sys.version_info[0] >= 3): csv_reader = csv.reader(fileobj, delimiter=delimiter, quotechar=quotechar, quoting=quoting, lineterminator=lineterminator) for skip_ix in range(skiprows): next(csv_reader) for row in csv_reader: (yield row) else: csv_reader = csv.reader(fileobj, delimiter=delimiter.encode(encoding), quotechar=quotechar.encode(encoding), quoting=quoting, lineterminator=lineterminator) for skip_ix in range(skiprows): next(csv_reader) for row in csv_reader: (yield [cell.decode(encoding) for cell in row])
def read_unicode_csv_fileobj(fileobj, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL, lineterminator='\n', encoding='utf-8', skiprows=0): if (sys.version_info[0] >= 3): csv_reader = csv.reader(fileobj, delimiter=delimiter, quotechar=quotechar, quoting=quoting, lineterminator=lineterminator) for skip_ix in range(skiprows): next(csv_reader) for row in csv_reader: (yield row) else: csv_reader = csv.reader(fileobj, delimiter=delimiter.encode(encoding), quotechar=quotechar.encode(encoding), quoting=quoting, lineterminator=lineterminator) for skip_ix in range(skiprows): next(csv_reader) for row in csv_reader: (yield [cell.decode(encoding) for cell in row])<|docstring|>fileobj can be a StringIO in Py3, but should be a BytesIO in Py2.<|endoftext|>
b3149d1c76287116ce82ae7c62545b1856d4db0613b3be06406f869f4196b706
def fast_deepcopy(obj): 'This is a faster implementation of deepcopy via pickle.\n\n It is meant primarily for sets of Statements with complex hierarchies\n but can be used for any object.\n ' with BytesIO() as buf: pickle.dump(obj, buf) buf.seek(0) obj_new = pickle.load(buf) return obj_new
This is a faster implementation of deepcopy via pickle. It is meant primarily for sets of Statements with complex hierarchies but can be used for any object.
indra/util/__init__.py
fast_deepcopy
pupster90/indra
0
python
def fast_deepcopy(obj): 'This is a faster implementation of deepcopy via pickle.\n\n It is meant primarily for sets of Statements with complex hierarchies\n but can be used for any object.\n ' with BytesIO() as buf: pickle.dump(obj, buf) buf.seek(0) obj_new = pickle.load(buf) return obj_new
def fast_deepcopy(obj): 'This is a faster implementation of deepcopy via pickle.\n\n It is meant primarily for sets of Statements with complex hierarchies\n but can be used for any object.\n ' with BytesIO() as buf: pickle.dump(obj, buf) buf.seek(0) obj_new = pickle.load(buf) return obj_new<|docstring|>This is a faster implementation of deepcopy via pickle. It is meant primarily for sets of Statements with complex hierarchies but can be used for any object.<|endoftext|>
c78a8ea25b310168b46e9bbf1f397d1065e1413b6d9b5f525794abb7bfb4424e
def lmap(f, xs): 'A non-lazy version of map.' return list(map(f, xs))
A non-lazy version of map.
indra/util/__init__.py
lmap
pupster90/indra
0
python
def lmap(f, xs): return list(map(f, xs))
def lmap(f, xs): return list(map(f, xs))<|docstring|>A non-lazy version of map.<|endoftext|>
eb6f034f5f37f918633536f64523c73bd1ec6a5b3755fc0d968345680ab5fc59
def flatten(l): 'Flatten a nested list.' return (sum(map(flatten, l), []) if (isinstance(l, list) or isinstance(l, tuple)) else [l])
Flatten a nested list.
indra/util/__init__.py
flatten
pupster90/indra
0
python
def flatten(l): return (sum(map(flatten, l), []) if (isinstance(l, list) or isinstance(l, tuple)) else [l])
def flatten(l): return (sum(map(flatten, l), []) if (isinstance(l, list) or isinstance(l, tuple)) else [l])<|docstring|>Flatten a nested list.<|endoftext|>
0aecee92b413b931514195548bdef79e5aa7588ca0b404c46676b412f4bdbd6a
def flatMap(f, xs): 'Map a function onto an iterable and flatten the result.' return flatten(lmap(f, xs))
Map a function onto an iterable and flatten the result.
indra/util/__init__.py
flatMap
pupster90/indra
0
python
def flatMap(f, xs): return flatten(lmap(f, xs))
def flatMap(f, xs): return flatten(lmap(f, xs))<|docstring|>Map a function onto an iterable and flatten the result.<|endoftext|>
5d5c899b4cef6f2714806dd23889f74f192168d1925d881fcfaf526cb7b02b34
def get_list_arb(): 'Run the arb finder\n\n Returns:\n List: List sorted by % of all arb opportunities found.\n ' dict_price_raw = get_raw_price_async() dict_clean_price = get_clean_price(dict_price_raw) list_arb_price = compute_arb_opportunities(dict_clean_price) res = get_output(list_arb_price) sorted_list_arb = sorted(res.items(), key=(lambda i: i[1]['%']), reverse=True) pprint(sorted_list_arb) return sorted_list_arb
Run the arb finder Returns: List: List sorted by % of all arb opportunities found.
examples/python/oracle_arb_finder/app.py
get_list_arb
edd34/OrFeed
0
python
def get_list_arb(): 'Run the arb finder\n\n Returns:\n List: List sorted by % of all arb opportunities found.\n ' dict_price_raw = get_raw_price_async() dict_clean_price = get_clean_price(dict_price_raw) list_arb_price = compute_arb_opportunities(dict_clean_price) res = get_output(list_arb_price) sorted_list_arb = sorted(res.items(), key=(lambda i: i[1]['%']), reverse=True) pprint(sorted_list_arb) return sorted_list_arb
def get_list_arb(): 'Run the arb finder\n\n Returns:\n List: List sorted by % of all arb opportunities found.\n ' dict_price_raw = get_raw_price_async() dict_clean_price = get_clean_price(dict_price_raw) list_arb_price = compute_arb_opportunities(dict_clean_price) res = get_output(list_arb_price) sorted_list_arb = sorted(res.items(), key=(lambda i: i[1]['%']), reverse=True) pprint(sorted_list_arb) return sorted_list_arb<|docstring|>Run the arb finder Returns: List: List sorted by % of all arb opportunities found.<|endoftext|>
f52a7233349e3aad06943ba481ebfdf9ffb43ca04723a10073e6ae65ebbc1c91
def knn_purity(data, labels: np.ndarray, n_neighbors=30): 'Computes KNN Purity for ``data`` given the labels.\n Parameters\n ----------\n data:\n Numpy ndarray of data\n labels\n Numpy ndarray of labels\n n_neighbors: int\n Number of nearest neighbors.\n Returns\n -------\n score: float\n KNN purity score. A float between 0 and 1.\n ' labels = LabelEncoder().fit_transform(labels.ravel()) nbrs = NearestNeighbors(n_neighbors=(n_neighbors + 1)).fit(data) indices = nbrs.kneighbors(data, return_distance=False)[(:, 1:)] neighbors_labels = np.vectorize((lambda i: labels[i]))(indices) scores = ((neighbors_labels - labels.reshape((- 1), 1)) == 0).mean(axis=1) res = [np.mean(scores[(labels == i)]) for i in np.unique(labels)] return np.mean(res)
Computes KNN Purity for ``data`` given the labels. Parameters ---------- data: Numpy ndarray of data labels Numpy ndarray of labels n_neighbors: int Number of nearest neighbors. Returns ------- score: float KNN purity score. A float between 0 and 1.
cpa/_metrics.py
knn_purity
theislab/CPA
7
python
def knn_purity(data, labels: np.ndarray, n_neighbors=30): 'Computes KNN Purity for ``data`` given the labels.\n Parameters\n ----------\n data:\n Numpy ndarray of data\n labels\n Numpy ndarray of labels\n n_neighbors: int\n Number of nearest neighbors.\n Returns\n -------\n score: float\n KNN purity score. A float between 0 and 1.\n ' labels = LabelEncoder().fit_transform(labels.ravel()) nbrs = NearestNeighbors(n_neighbors=(n_neighbors + 1)).fit(data) indices = nbrs.kneighbors(data, return_distance=False)[(:, 1:)] neighbors_labels = np.vectorize((lambda i: labels[i]))(indices) scores = ((neighbors_labels - labels.reshape((- 1), 1)) == 0).mean(axis=1) res = [np.mean(scores[(labels == i)]) for i in np.unique(labels)] return np.mean(res)
def knn_purity(data, labels: np.ndarray, n_neighbors=30): 'Computes KNN Purity for ``data`` given the labels.\n Parameters\n ----------\n data:\n Numpy ndarray of data\n labels\n Numpy ndarray of labels\n n_neighbors: int\n Number of nearest neighbors.\n Returns\n -------\n score: float\n KNN purity score. A float between 0 and 1.\n ' labels = LabelEncoder().fit_transform(labels.ravel()) nbrs = NearestNeighbors(n_neighbors=(n_neighbors + 1)).fit(data) indices = nbrs.kneighbors(data, return_distance=False)[(:, 1:)] neighbors_labels = np.vectorize((lambda i: labels[i]))(indices) scores = ((neighbors_labels - labels.reshape((- 1), 1)) == 0).mean(axis=1) res = [np.mean(scores[(labels == i)]) for i in np.unique(labels)] return np.mean(res)<|docstring|>Computes KNN Purity for ``data`` given the labels. Parameters ---------- data: Numpy ndarray of data labels Numpy ndarray of labels n_neighbors: int Number of nearest neighbors. Returns ------- score: float KNN purity score. A float between 0 and 1.<|endoftext|>
b59e8e0c164d108be9e45d4f226c2c6678a697427b918c1e9b0b38207dc252a2
def entropy_batch_mixing(data, labels, n_neighbors=50, n_pools=50, n_samples_per_pool=100): 'Computes Entory of Batch mixing metric for ``adata`` given the batch column name.\n Parameters\n ----------\n data\n Numpy ndarray of data\n labels\n Numpy ndarray of labels\n n_neighbors: int\n Number of nearest neighbors.\n n_pools: int\n Number of EBM computation which will be averaged.\n n_samples_per_pool: int\n Number of samples to be used in each pool of execution.\n Returns\n -------\n score: float\n EBM score. A float between zero and one.\n ' def __entropy_from_indices(indices, n_cat): return entropy(np.array(itemfreq(indices)[(:, 1)].astype(np.int32)), base=n_cat) n_cat = len(np.unique(labels)) neighbors = NearestNeighbors(n_neighbors=(n_neighbors + 1)).fit(data) indices = neighbors.kneighbors(data, return_distance=False)[(:, 1:)] batch_indices = np.vectorize((lambda i: labels[i]))(indices) entropies = np.apply_along_axis(__entropy_from_indices, axis=1, arr=batch_indices, n_cat=n_cat) if (n_pools == 1): score = np.mean(entropies) else: score = np.mean([np.mean(entropies[np.random.choice(len(entropies), size=n_samples_per_pool)]) for _ in range(n_pools)]) return score
Computes Entory of Batch mixing metric for ``adata`` given the batch column name. Parameters ---------- data Numpy ndarray of data labels Numpy ndarray of labels n_neighbors: int Number of nearest neighbors. n_pools: int Number of EBM computation which will be averaged. n_samples_per_pool: int Number of samples to be used in each pool of execution. Returns ------- score: float EBM score. A float between zero and one.
cpa/_metrics.py
entropy_batch_mixing
theislab/CPA
7
python
def entropy_batch_mixing(data, labels, n_neighbors=50, n_pools=50, n_samples_per_pool=100): 'Computes Entory of Batch mixing metric for ``adata`` given the batch column name.\n Parameters\n ----------\n data\n Numpy ndarray of data\n labels\n Numpy ndarray of labels\n n_neighbors: int\n Number of nearest neighbors.\n n_pools: int\n Number of EBM computation which will be averaged.\n n_samples_per_pool: int\n Number of samples to be used in each pool of execution.\n Returns\n -------\n score: float\n EBM score. A float between zero and one.\n ' def __entropy_from_indices(indices, n_cat): return entropy(np.array(itemfreq(indices)[(:, 1)].astype(np.int32)), base=n_cat) n_cat = len(np.unique(labels)) neighbors = NearestNeighbors(n_neighbors=(n_neighbors + 1)).fit(data) indices = neighbors.kneighbors(data, return_distance=False)[(:, 1:)] batch_indices = np.vectorize((lambda i: labels[i]))(indices) entropies = np.apply_along_axis(__entropy_from_indices, axis=1, arr=batch_indices, n_cat=n_cat) if (n_pools == 1): score = np.mean(entropies) else: score = np.mean([np.mean(entropies[np.random.choice(len(entropies), size=n_samples_per_pool)]) for _ in range(n_pools)]) return score
def entropy_batch_mixing(data, labels, n_neighbors=50, n_pools=50, n_samples_per_pool=100): 'Computes Entory of Batch mixing metric for ``adata`` given the batch column name.\n Parameters\n ----------\n data\n Numpy ndarray of data\n labels\n Numpy ndarray of labels\n n_neighbors: int\n Number of nearest neighbors.\n n_pools: int\n Number of EBM computation which will be averaged.\n n_samples_per_pool: int\n Number of samples to be used in each pool of execution.\n Returns\n -------\n score: float\n EBM score. A float between zero and one.\n ' def __entropy_from_indices(indices, n_cat): return entropy(np.array(itemfreq(indices)[(:, 1)].astype(np.int32)), base=n_cat) n_cat = len(np.unique(labels)) neighbors = NearestNeighbors(n_neighbors=(n_neighbors + 1)).fit(data) indices = neighbors.kneighbors(data, return_distance=False)[(:, 1:)] batch_indices = np.vectorize((lambda i: labels[i]))(indices) entropies = np.apply_along_axis(__entropy_from_indices, axis=1, arr=batch_indices, n_cat=n_cat) if (n_pools == 1): score = np.mean(entropies) else: score = np.mean([np.mean(entropies[np.random.choice(len(entropies), size=n_samples_per_pool)]) for _ in range(n_pools)]) return score<|docstring|>Computes Entory of Batch mixing metric for ``adata`` given the batch column name. Parameters ---------- data Numpy ndarray of data labels Numpy ndarray of labels n_neighbors: int Number of nearest neighbors. n_pools: int Number of EBM computation which will be averaged. n_samples_per_pool: int Number of samples to be used in each pool of execution. Returns ------- score: float EBM score. A float between zero and one.<|endoftext|>
003c8d364a7eb5159af24d7b0055d5f3d71da622c5bf163c0a487d59c7305b26
def __init__(self, parent, inet): ' Initialize Panel class ' self.inet = inet wx.Panel.__init__(self, parent) DEFAULT_FONT = wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL) self.layout_main = wx.BoxSizer(wx.VERTICAL) self.layout = [wx.BoxSizer(wx.HORIZONTAL) for i in range(4)] label = wx.StaticText(self, id=wx.ID_ANY, label=u'Question : ') label.SetFont(DEFAULT_FONT) self.layout[0].Add(label, flag=((wx.EXPAND | wx.ALIGN_LEFT) | wx.ALL), border=8) self.text_question = wx.TextCtrl(self, id=wx.ID_ANY, size=(400, 32)) self.text_question.SetFont(DEFAULT_FONT) self.text_question.SetToolTipString(u'Qeustion') self.layout[0].Add(self.text_question, flag=((wx.EXPAND | wx.ALIGN_LEFT) | wx.ALL), border=0) self.button_add = wx.Button(self, id=wx.ID_ANY, label=u'New', size=(128, 32)) self.button_add.SetFont(DEFAULT_FONT) self.button_add.Bind(wx.EVT_BUTTON, self.new_choice) self.layout[1].Add(self.button_add, flag=((wx.EXPAND | wx.ALIGN_LEFT) | wx.ALL), border=8) self.button_delete = wx.Button(self, id=wx.ID_ANY, label=u'Delete', size=(128, 32)) self.button_delete.SetFont(DEFAULT_FONT) self.button_delete.Bind(wx.EVT_BUTTON, self.delete_choice) self.layout[1].Add(self.button_delete, flag=((wx.EXPAND | wx.ALIGN_LEFT) | wx.ALL), border=8) self.button_clear = wx.Button(self, id=wx.ID_ANY, label=u'Clear All', size=(128, 32)) self.button_clear.SetFont(DEFAULT_FONT) self.button_clear.Bind(wx.EVT_BUTTON, self.clear_choice) self.layout[1].Add(self.button_clear, flag=((wx.EXPAND | wx.ALIGN_LEFT) | wx.ALL), border=8) self.list_choice = wx.ListBox(self, wx.ID_ANY, choices=(), style=((wx.LB_SINGLE | wx.LB_HSCROLL) | wx.LB_NEEDED_SB)) self.list_choice.SetFont(DEFAULT_FONT) self.layout[2].Add(self.list_choice, proportion=1, flag=((wx.EXPAND | wx.ALIGN_LEFT) | wx.ALL), border=8) self.label_received = wx.StaticText(self, id=wx.ID_ANY, label='') self.label_received.SetFont(DEFAULT_FONT) self.layout[3].Add(self.label_received, flag=((wx.EXPAND | wx.ALIGN_RIGHT) | wx.ALL), border=8) self.button_post = wx.Button(self, id=wx.ID_ANY, label=u'Post', size=(128, 32)) self.button_post.SetFont(DEFAULT_FONT) self.button_post.Bind(wx.EVT_BUTTON, self.inet.post_questionnaire) self.layout[3].Add(self.button_post, flag=((wx.EXPAND | wx.ALIGN_RIGHT) | wx.ALL), border=8) self.layout_main.Add(self.layout[0], flag=wx.ALIGN_TOP) self.layout_main.Add(self.layout[1], flag=wx.ALIGN_LEFT) self.layout_main.Add(self.layout[2], proportion=1, flag=(wx.EXPAND | wx.ALIGN_CENTER)) self.layout_main.Add(self.layout[3], flag=(wx.ALIGN_BOTTOM | wx.ALIGN_RIGHT)) self.SetSizer(self.layout_main) return
Initialize Panel class
src/ltkit/panel/server/questionnaire.py
__init__
ptr-yudai/ltkit
1
python
def __init__(self, parent, inet): ' ' self.inet = inet wx.Panel.__init__(self, parent) DEFAULT_FONT = wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL) self.layout_main = wx.BoxSizer(wx.VERTICAL) self.layout = [wx.BoxSizer(wx.HORIZONTAL) for i in range(4)] label = wx.StaticText(self, id=wx.ID_ANY, label=u'Question : ') label.SetFont(DEFAULT_FONT) self.layout[0].Add(label, flag=((wx.EXPAND | wx.ALIGN_LEFT) | wx.ALL), border=8) self.text_question = wx.TextCtrl(self, id=wx.ID_ANY, size=(400, 32)) self.text_question.SetFont(DEFAULT_FONT) self.text_question.SetToolTipString(u'Qeustion') self.layout[0].Add(self.text_question, flag=((wx.EXPAND | wx.ALIGN_LEFT) | wx.ALL), border=0) self.button_add = wx.Button(self, id=wx.ID_ANY, label=u'New', size=(128, 32)) self.button_add.SetFont(DEFAULT_FONT) self.button_add.Bind(wx.EVT_BUTTON, self.new_choice) self.layout[1].Add(self.button_add, flag=((wx.EXPAND | wx.ALIGN_LEFT) | wx.ALL), border=8) self.button_delete = wx.Button(self, id=wx.ID_ANY, label=u'Delete', size=(128, 32)) self.button_delete.SetFont(DEFAULT_FONT) self.button_delete.Bind(wx.EVT_BUTTON, self.delete_choice) self.layout[1].Add(self.button_delete, flag=((wx.EXPAND | wx.ALIGN_LEFT) | wx.ALL), border=8) self.button_clear = wx.Button(self, id=wx.ID_ANY, label=u'Clear All', size=(128, 32)) self.button_clear.SetFont(DEFAULT_FONT) self.button_clear.Bind(wx.EVT_BUTTON, self.clear_choice) self.layout[1].Add(self.button_clear, flag=((wx.EXPAND | wx.ALIGN_LEFT) | wx.ALL), border=8) self.list_choice = wx.ListBox(self, wx.ID_ANY, choices=(), style=((wx.LB_SINGLE | wx.LB_HSCROLL) | wx.LB_NEEDED_SB)) self.list_choice.SetFont(DEFAULT_FONT) self.layout[2].Add(self.list_choice, proportion=1, flag=((wx.EXPAND | wx.ALIGN_LEFT) | wx.ALL), border=8) self.label_received = wx.StaticText(self, id=wx.ID_ANY, label=) self.label_received.SetFont(DEFAULT_FONT) self.layout[3].Add(self.label_received, flag=((wx.EXPAND | wx.ALIGN_RIGHT) | wx.ALL), border=8) self.button_post = wx.Button(self, id=wx.ID_ANY, label=u'Post', size=(128, 32)) self.button_post.SetFont(DEFAULT_FONT) self.button_post.Bind(wx.EVT_BUTTON, self.inet.post_questionnaire) self.layout[3].Add(self.button_post, flag=((wx.EXPAND | wx.ALIGN_RIGHT) | wx.ALL), border=8) self.layout_main.Add(self.layout[0], flag=wx.ALIGN_TOP) self.layout_main.Add(self.layout[1], flag=wx.ALIGN_LEFT) self.layout_main.Add(self.layout[2], proportion=1, flag=(wx.EXPAND | wx.ALIGN_CENTER)) self.layout_main.Add(self.layout[3], flag=(wx.ALIGN_BOTTOM | wx.ALIGN_RIGHT)) self.SetSizer(self.layout_main) return
def __init__(self, parent, inet): ' ' self.inet = inet wx.Panel.__init__(self, parent) DEFAULT_FONT = wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL) self.layout_main = wx.BoxSizer(wx.VERTICAL) self.layout = [wx.BoxSizer(wx.HORIZONTAL) for i in range(4)] label = wx.StaticText(self, id=wx.ID_ANY, label=u'Question : ') label.SetFont(DEFAULT_FONT) self.layout[0].Add(label, flag=((wx.EXPAND | wx.ALIGN_LEFT) | wx.ALL), border=8) self.text_question = wx.TextCtrl(self, id=wx.ID_ANY, size=(400, 32)) self.text_question.SetFont(DEFAULT_FONT) self.text_question.SetToolTipString(u'Qeustion') self.layout[0].Add(self.text_question, flag=((wx.EXPAND | wx.ALIGN_LEFT) | wx.ALL), border=0) self.button_add = wx.Button(self, id=wx.ID_ANY, label=u'New', size=(128, 32)) self.button_add.SetFont(DEFAULT_FONT) self.button_add.Bind(wx.EVT_BUTTON, self.new_choice) self.layout[1].Add(self.button_add, flag=((wx.EXPAND | wx.ALIGN_LEFT) | wx.ALL), border=8) self.button_delete = wx.Button(self, id=wx.ID_ANY, label=u'Delete', size=(128, 32)) self.button_delete.SetFont(DEFAULT_FONT) self.button_delete.Bind(wx.EVT_BUTTON, self.delete_choice) self.layout[1].Add(self.button_delete, flag=((wx.EXPAND | wx.ALIGN_LEFT) | wx.ALL), border=8) self.button_clear = wx.Button(self, id=wx.ID_ANY, label=u'Clear All', size=(128, 32)) self.button_clear.SetFont(DEFAULT_FONT) self.button_clear.Bind(wx.EVT_BUTTON, self.clear_choice) self.layout[1].Add(self.button_clear, flag=((wx.EXPAND | wx.ALIGN_LEFT) | wx.ALL), border=8) self.list_choice = wx.ListBox(self, wx.ID_ANY, choices=(), style=((wx.LB_SINGLE | wx.LB_HSCROLL) | wx.LB_NEEDED_SB)) self.list_choice.SetFont(DEFAULT_FONT) self.layout[2].Add(self.list_choice, proportion=1, flag=((wx.EXPAND | wx.ALIGN_LEFT) | wx.ALL), border=8) self.label_received = wx.StaticText(self, id=wx.ID_ANY, label=) self.label_received.SetFont(DEFAULT_FONT) self.layout[3].Add(self.label_received, flag=((wx.EXPAND | wx.ALIGN_RIGHT) | wx.ALL), border=8) self.button_post = wx.Button(self, id=wx.ID_ANY, label=u'Post', size=(128, 32)) self.button_post.SetFont(DEFAULT_FONT) self.button_post.Bind(wx.EVT_BUTTON, self.inet.post_questionnaire) self.layout[3].Add(self.button_post, flag=((wx.EXPAND | wx.ALIGN_RIGHT) | wx.ALL), border=8) self.layout_main.Add(self.layout[0], flag=wx.ALIGN_TOP) self.layout_main.Add(self.layout[1], flag=wx.ALIGN_LEFT) self.layout_main.Add(self.layout[2], proportion=1, flag=(wx.EXPAND | wx.ALIGN_CENTER)) self.layout_main.Add(self.layout[3], flag=(wx.ALIGN_BOTTOM | wx.ALIGN_RIGHT)) self.SetSizer(self.layout_main) return<|docstring|>Initialize Panel class<|endoftext|>
c7bfb100ddcfe4e67e30978ff2476f2c47cbc48e5f416982cc93d0b34f1e8e97
def new_choice(self, event): ' Add new choice ' dialog = wx.TextEntryDialog(self, message='Please enter the string of the choice.', caption='New choise') if (dialog.ShowModal() != wx.ID_OK): return self.list_choice.Append(dialog.GetValue()) return
Add new choice
src/ltkit/panel/server/questionnaire.py
new_choice
ptr-yudai/ltkit
1
python
def new_choice(self, event): ' ' dialog = wx.TextEntryDialog(self, message='Please enter the string of the choice.', caption='New choise') if (dialog.ShowModal() != wx.ID_OK): return self.list_choice.Append(dialog.GetValue()) return
def new_choice(self, event): ' ' dialog = wx.TextEntryDialog(self, message='Please enter the string of the choice.', caption='New choise') if (dialog.ShowModal() != wx.ID_OK): return self.list_choice.Append(dialog.GetValue()) return<|docstring|>Add new choice<|endoftext|>
51a90ec6259ecdf0681a86e9411c540799e79e958dd5c21eae57ca6b422fd159
def delete_choice(self, event): ' Delete the selected choice ' index = self.list_choice.GetSelection() if (index == wx.NOT_FOUND): wx.MessageBox(u'Please select an item to remove from the choice.', u'LT Toolkit', style=(wx.OK | wx.ICON_ERROR)) return self.list_choice.Delete(index) return
Delete the selected choice
src/ltkit/panel/server/questionnaire.py
delete_choice
ptr-yudai/ltkit
1
python
def delete_choice(self, event): ' ' index = self.list_choice.GetSelection() if (index == wx.NOT_FOUND): wx.MessageBox(u'Please select an item to remove from the choice.', u'LT Toolkit', style=(wx.OK | wx.ICON_ERROR)) return self.list_choice.Delete(index) return
def delete_choice(self, event): ' ' index = self.list_choice.GetSelection() if (index == wx.NOT_FOUND): wx.MessageBox(u'Please select an item to remove from the choice.', u'LT Toolkit', style=(wx.OK | wx.ICON_ERROR)) return self.list_choice.Delete(index) return<|docstring|>Delete the selected choice<|endoftext|>
cdb0e658a4c531738f999180b2b93d2c6d1c34bc2c97fa32b84ebca418d05c1e
def clear_choice(self, event): ' Clear all the choices ' dialog = wx.MessageDialog(None, 'Are you sure that you want to remove all the choices?', 'LT Toolkit', style=(wx.YES_NO | wx.ICON_QUESTION)) if (dialog.ShowModal() == wx.ID_YES): self.list_choice.Clear() return
Clear all the choices
src/ltkit/panel/server/questionnaire.py
clear_choice
ptr-yudai/ltkit
1
python
def clear_choice(self, event): ' ' dialog = wx.MessageDialog(None, 'Are you sure that you want to remove all the choices?', 'LT Toolkit', style=(wx.YES_NO | wx.ICON_QUESTION)) if (dialog.ShowModal() == wx.ID_YES): self.list_choice.Clear() return
def clear_choice(self, event): ' ' dialog = wx.MessageDialog(None, 'Are you sure that you want to remove all the choices?', 'LT Toolkit', style=(wx.YES_NO | wx.ICON_QUESTION)) if (dialog.ShowModal() == wx.ID_YES): self.list_choice.Clear() return<|docstring|>Clear all the choices<|endoftext|>
2e12f0920869e39a99f32c311de3a38d3ad489f96765205a1f806ea65778ebf6
def proc_new_answer(self, answer): ' Count up for new answer ' self.label_received.SetLabel('You have received {0} answer{1}.'.format(len(answer), ('s' if (len(answer) > 1) else ''))) self.layout[3].Layout() self.layout_main.Layout() return
Count up for new answer
src/ltkit/panel/server/questionnaire.py
proc_new_answer
ptr-yudai/ltkit
1
python
def proc_new_answer(self, answer): ' ' self.label_received.SetLabel('You have received {0} answer{1}.'.format(len(answer), ('s' if (len(answer) > 1) else ))) self.layout[3].Layout() self.layout_main.Layout() return
def proc_new_answer(self, answer): ' ' self.label_received.SetLabel('You have received {0} answer{1}.'.format(len(answer), ('s' if (len(answer) > 1) else ))) self.layout[3].Layout() self.layout_main.Layout() return<|docstring|>Count up for new answer<|endoftext|>
0592c11cb5c7be69674ebd2804145d8c677ad00d78320a9cb5975ec396f39463
def parse_line(line): 'parse a sentence with xml markup\n line - string from the file, contains the tab-separated sentence id, source sentence and target with error markup\n ' global cdec_home line = line[:(- 1)].decode('utf-8') chunks = line.split('\t') if (np.size(chunks) != 3): sys.stderr.write('Wrong format\n') return ('', '', [], []) sentence_id = chunks[0] src = chunks[1] trg = [] corrections = [] annotation = (('<?xml version="1.0" encoding="utf-8"?><mqm:translation xmlns:mqm="MQM">' + chunks[2].encode('utf-8')) + '</mqm:translation>') try: sentence = parseString(annotation) except UnicodeEncodeError as e: sys.stderr.write(("Sentence '%s' not parsed\n" % sentence_id)) print(e) print(annotation) return ('', '', [], []) except: print(sys.exc_info()[0]) print(annotation) return ('', '', [], []) if (not ('CDEC_HOME' in os.environ)): cdec_home = '/home/varvara/software/cdec' sys.stderr.write(('$CDEC_HOME variable not specified, using %s\n' % cdec_home)) else: cdec_home = os.environ['CDEC_HOME'] FNULL = open(os.devnull, 'w') p = Popen([(cdec_home + '/corpus/tokenize-anything.sh')], stdout=PIPE, stdin=PIPE, stderr=FNULL) tok = p.communicate(input=src.encode('utf-8'))[0].strip() src = tok.decode('utf-8') FNULL.close() curr_word = 0 opened_issues = {} for elem in sentence.documentElement.childNodes: if (elem.nodeType == 1): try: el_id = int(elem.attributes['id'].value) if (elem.nodeName == 'mqm:startIssue'): opened_issues[el_id] = (curr_word, elem.attributes['type'].value) elif (elem.nodeName == 'mqm:endIssue'): if (not opened_issues.has_key(el_id)): sys.stderr.write(('Inconsistent error %d\n' % el_id)) return ('', '', [], []) a_corr = Correction(opened_issues[el_id][0], curr_word, opened_issues[el_id][1], el_id) corrections.append(a_corr) del opened_issues[el_id] except KeyError as e: sys.stderr.write(('Missing attribute in sentence %s: %s\n' % (sentence_id, e.args[0]))) return ('', '', [], []) except: sys.stderr.write(sys.exc_info()) return ('', '', [], []) elif (elem.nodeType == 3): FNULL = open(os.devnull, 'w') p = Popen([(cdec_home + '/corpus/tokenize-anything.sh')], stdout=PIPE, stdin=PIPE, stderr=FNULL) tok = p.communicate(input=elem.nodeValue.encode('utf-8'))[0].strip() FNULL.close() words = [w.decode('utf-8') for w in tok.split()] trg.extend(words) curr_word += len(words) if len(opened_issues): sys.stderr.write(('Inconsistent error(s): %s\n' % ', '.join([str(x) for x in opened_issues.keys()]))) return ('', '', [], []) return (sentence_id, src, np.array(trg, dtype=object), np.array(corrections, dtype=object))
parse a sentence with xml markup line - string from the file, contains the tab-separated sentence id, source sentence and target with error markup
marmot/preprocessing/parse_xml.py
parse_line
qe-team/marmot
19
python
def parse_line(line): 'parse a sentence with xml markup\n line - string from the file, contains the tab-separated sentence id, source sentence and target with error markup\n ' global cdec_home line = line[:(- 1)].decode('utf-8') chunks = line.split('\t') if (np.size(chunks) != 3): sys.stderr.write('Wrong format\n') return (, , [], []) sentence_id = chunks[0] src = chunks[1] trg = [] corrections = [] annotation = (('<?xml version="1.0" encoding="utf-8"?><mqm:translation xmlns:mqm="MQM">' + chunks[2].encode('utf-8')) + '</mqm:translation>') try: sentence = parseString(annotation) except UnicodeEncodeError as e: sys.stderr.write(("Sentence '%s' not parsed\n" % sentence_id)) print(e) print(annotation) return (, , [], []) except: print(sys.exc_info()[0]) print(annotation) return (, , [], []) if (not ('CDEC_HOME' in os.environ)): cdec_home = '/home/varvara/software/cdec' sys.stderr.write(('$CDEC_HOME variable not specified, using %s\n' % cdec_home)) else: cdec_home = os.environ['CDEC_HOME'] FNULL = open(os.devnull, 'w') p = Popen([(cdec_home + '/corpus/tokenize-anything.sh')], stdout=PIPE, stdin=PIPE, stderr=FNULL) tok = p.communicate(input=src.encode('utf-8'))[0].strip() src = tok.decode('utf-8') FNULL.close() curr_word = 0 opened_issues = {} for elem in sentence.documentElement.childNodes: if (elem.nodeType == 1): try: el_id = int(elem.attributes['id'].value) if (elem.nodeName == 'mqm:startIssue'): opened_issues[el_id] = (curr_word, elem.attributes['type'].value) elif (elem.nodeName == 'mqm:endIssue'): if (not opened_issues.has_key(el_id)): sys.stderr.write(('Inconsistent error %d\n' % el_id)) return (, , [], []) a_corr = Correction(opened_issues[el_id][0], curr_word, opened_issues[el_id][1], el_id) corrections.append(a_corr) del opened_issues[el_id] except KeyError as e: sys.stderr.write(('Missing attribute in sentence %s: %s\n' % (sentence_id, e.args[0]))) return (, , [], []) except: sys.stderr.write(sys.exc_info()) return (, , [], []) elif (elem.nodeType == 3): FNULL = open(os.devnull, 'w') p = Popen([(cdec_home + '/corpus/tokenize-anything.sh')], stdout=PIPE, stdin=PIPE, stderr=FNULL) tok = p.communicate(input=elem.nodeValue.encode('utf-8'))[0].strip() FNULL.close() words = [w.decode('utf-8') for w in tok.split()] trg.extend(words) curr_word += len(words) if len(opened_issues): sys.stderr.write(('Inconsistent error(s): %s\n' % ', '.join([str(x) for x in opened_issues.keys()]))) return (, , [], []) return (sentence_id, src, np.array(trg, dtype=object), np.array(corrections, dtype=object))
def parse_line(line): 'parse a sentence with xml markup\n line - string from the file, contains the tab-separated sentence id, source sentence and target with error markup\n ' global cdec_home line = line[:(- 1)].decode('utf-8') chunks = line.split('\t') if (np.size(chunks) != 3): sys.stderr.write('Wrong format\n') return (, , [], []) sentence_id = chunks[0] src = chunks[1] trg = [] corrections = [] annotation = (('<?xml version="1.0" encoding="utf-8"?><mqm:translation xmlns:mqm="MQM">' + chunks[2].encode('utf-8')) + '</mqm:translation>') try: sentence = parseString(annotation) except UnicodeEncodeError as e: sys.stderr.write(("Sentence '%s' not parsed\n" % sentence_id)) print(e) print(annotation) return (, , [], []) except: print(sys.exc_info()[0]) print(annotation) return (, , [], []) if (not ('CDEC_HOME' in os.environ)): cdec_home = '/home/varvara/software/cdec' sys.stderr.write(('$CDEC_HOME variable not specified, using %s\n' % cdec_home)) else: cdec_home = os.environ['CDEC_HOME'] FNULL = open(os.devnull, 'w') p = Popen([(cdec_home + '/corpus/tokenize-anything.sh')], stdout=PIPE, stdin=PIPE, stderr=FNULL) tok = p.communicate(input=src.encode('utf-8'))[0].strip() src = tok.decode('utf-8') FNULL.close() curr_word = 0 opened_issues = {} for elem in sentence.documentElement.childNodes: if (elem.nodeType == 1): try: el_id = int(elem.attributes['id'].value) if (elem.nodeName == 'mqm:startIssue'): opened_issues[el_id] = (curr_word, elem.attributes['type'].value) elif (elem.nodeName == 'mqm:endIssue'): if (not opened_issues.has_key(el_id)): sys.stderr.write(('Inconsistent error %d\n' % el_id)) return (, , [], []) a_corr = Correction(opened_issues[el_id][0], curr_word, opened_issues[el_id][1], el_id) corrections.append(a_corr) del opened_issues[el_id] except KeyError as e: sys.stderr.write(('Missing attribute in sentence %s: %s\n' % (sentence_id, e.args[0]))) return (, , [], []) except: sys.stderr.write(sys.exc_info()) return (, , [], []) elif (elem.nodeType == 3): FNULL = open(os.devnull, 'w') p = Popen([(cdec_home + '/corpus/tokenize-anything.sh')], stdout=PIPE, stdin=PIPE, stderr=FNULL) tok = p.communicate(input=elem.nodeValue.encode('utf-8'))[0].strip() FNULL.close() words = [w.decode('utf-8') for w in tok.split()] trg.extend(words) curr_word += len(words) if len(opened_issues): sys.stderr.write(('Inconsistent error(s): %s\n' % ', '.join([str(x) for x in opened_issues.keys()]))) return (, , [], []) return (sentence_id, src, np.array(trg, dtype=object), np.array(corrections, dtype=object))<|docstring|>parse a sentence with xml markup line - string from the file, contains the tab-separated sentence id, source sentence and target with error markup<|endoftext|>
c7800ee8bfca49a4b174173e52b3edbbb0373625a5f5f7b589e0e2b8ad315e4a
async def open_connection_buffered(*args, get_buffer: GetBuffer=_get_buffer, loop=None, **kwargs) -> Tuple[(StreamReader, StreamWriter)]: '\n Open stream using BufferedStreamProtocol.\n ' loop = (loop or asyncio.get_running_loop()) proto = BufferedStreamProtocol(loop, None, get_buffer) (await loop.create_connection((lambda : proto), *args, **kwargs)) return (StreamReader(proto), StreamWriter(proto))
Open stream using BufferedStreamProtocol.
fstream/__init__.py
open_connection_buffered
33TU/fstream
0
python
async def open_connection_buffered(*args, get_buffer: GetBuffer=_get_buffer, loop=None, **kwargs) -> Tuple[(StreamReader, StreamWriter)]: '\n \n ' loop = (loop or asyncio.get_running_loop()) proto = BufferedStreamProtocol(loop, None, get_buffer) (await loop.create_connection((lambda : proto), *args, **kwargs)) return (StreamReader(proto), StreamWriter(proto))
async def open_connection_buffered(*args, get_buffer: GetBuffer=_get_buffer, loop=None, **kwargs) -> Tuple[(StreamReader, StreamWriter)]: '\n \n ' loop = (loop or asyncio.get_running_loop()) proto = BufferedStreamProtocol(loop, None, get_buffer) (await loop.create_connection((lambda : proto), *args, **kwargs)) return (StreamReader(proto), StreamWriter(proto))<|docstring|>Open stream using BufferedStreamProtocol.<|endoftext|>
672c4e4c1841478b70d334385dc18b780a3483c73d9881f49daadbeb8ff9f0cf
async def start_server_buffered(client_connected_cb: ConnectedCb, *args, get_buffer: GetBuffer=_get_buffer, loop=None, **kwargs) -> asyncio.AbstractServer: '\n Start server which uses BufferedStreamProtocol.\n ' loop = (loop or asyncio.get_running_loop()) return (await loop.create_server((lambda : BufferedStreamProtocol(loop, client_connected_cb, get_buffer)), *args, **kwargs))
Start server which uses BufferedStreamProtocol.
fstream/__init__.py
start_server_buffered
33TU/fstream
0
python
async def start_server_buffered(client_connected_cb: ConnectedCb, *args, get_buffer: GetBuffer=_get_buffer, loop=None, **kwargs) -> asyncio.AbstractServer: '\n \n ' loop = (loop or asyncio.get_running_loop()) return (await loop.create_server((lambda : BufferedStreamProtocol(loop, client_connected_cb, get_buffer)), *args, **kwargs))
async def start_server_buffered(client_connected_cb: ConnectedCb, *args, get_buffer: GetBuffer=_get_buffer, loop=None, **kwargs) -> asyncio.AbstractServer: '\n \n ' loop = (loop or asyncio.get_running_loop()) return (await loop.create_server((lambda : BufferedStreamProtocol(loop, client_connected_cb, get_buffer)), *args, **kwargs))<|docstring|>Start server which uses BufferedStreamProtocol.<|endoftext|>
d192cf8e54b557c834df62a265a204fc75f1d4228b2604ed0cf7631e4e7df8ae
async def open_connection_chunked(*args, loop=None, **kwargs) -> Tuple[(StreamReader, StreamWriter)]: '\n Open stream using ChunkedProtocol.\n ' loop = (loop or asyncio.get_running_loop()) proto = ChunkedStreamProtocol(loop, None) (await loop.create_connection((lambda : proto), *args, **kwargs)) return (StreamReader(proto), StreamWriter(proto))
Open stream using ChunkedProtocol.
fstream/__init__.py
open_connection_chunked
33TU/fstream
0
python
async def open_connection_chunked(*args, loop=None, **kwargs) -> Tuple[(StreamReader, StreamWriter)]: '\n \n ' loop = (loop or asyncio.get_running_loop()) proto = ChunkedStreamProtocol(loop, None) (await loop.create_connection((lambda : proto), *args, **kwargs)) return (StreamReader(proto), StreamWriter(proto))
async def open_connection_chunked(*args, loop=None, **kwargs) -> Tuple[(StreamReader, StreamWriter)]: '\n \n ' loop = (loop or asyncio.get_running_loop()) proto = ChunkedStreamProtocol(loop, None) (await loop.create_connection((lambda : proto), *args, **kwargs)) return (StreamReader(proto), StreamWriter(proto))<|docstring|>Open stream using ChunkedProtocol.<|endoftext|>
edb8b714d3252470d03259c8b6445dc29c84ffb89d8b32079ac55a5608de130b
async def start_server_chunked(client_connected_cb: ConnectedCb, *args, loop=None, **kwargs) -> asyncio.AbstractServer: '\n Start server which uses ChunkedStreamProtocol.\n ' loop = (loop or asyncio.get_running_loop()) return (await loop.create_server((lambda : ChunkedStreamProtocol(loop, client_connected_cb)), *args, **kwargs))
Start server which uses ChunkedStreamProtocol.
fstream/__init__.py
start_server_chunked
33TU/fstream
0
python
async def start_server_chunked(client_connected_cb: ConnectedCb, *args, loop=None, **kwargs) -> asyncio.AbstractServer: '\n \n ' loop = (loop or asyncio.get_running_loop()) return (await loop.create_server((lambda : ChunkedStreamProtocol(loop, client_connected_cb)), *args, **kwargs))
async def start_server_chunked(client_connected_cb: ConnectedCb, *args, loop=None, **kwargs) -> asyncio.AbstractServer: '\n \n ' loop = (loop or asyncio.get_running_loop()) return (await loop.create_server((lambda : ChunkedStreamProtocol(loop, client_connected_cb)), *args, **kwargs))<|docstring|>Start server which uses ChunkedStreamProtocol.<|endoftext|>
fdd675e6944ba2af15c7dfcb0611fe9aa6c94a47ae09e52b5d66136acbc1d576
def get_index_node(self, vx): ' return the meta graph to implement index calculation\n from input @p vx ' raise NotImplementedError
return the meta graph to implement index calculation from input @p vx
metalibm_core/core/indexing.py
get_index_node
kalray/metalibm
27
python
def get_index_node(self, vx): ' return the meta graph to implement index calculation\n from input @p vx ' raise NotImplementedError
def get_index_node(self, vx): ' return the meta graph to implement index calculation\n from input @p vx ' raise NotImplementedError<|docstring|>return the meta graph to implement index calculation from input @p vx<|endoftext|>
cd3025c65ad8b38a5915dee73d018646de6550da9e82c6e0472fa54c3bfa77cf
def get_sub_interval(self, index): ' return the sub-interval numbered @p index ' raise NotImplementedError
return the sub-interval numbered @p index
metalibm_core/core/indexing.py
get_sub_interval
kalray/metalibm
27
python
def get_sub_interval(self, index): ' ' raise NotImplementedError
def get_sub_interval(self, index): ' ' raise NotImplementedError<|docstring|>return the sub-interval numbered @p index<|endoftext|>
192859110cc8136d7e32b4f312e138a2c1be500cf0e40b62cb7073c641a79538
def get_sub_list(self): ' return the list of sub-intervals ordered by index ' raise NotImplementedError
return the list of sub-intervals ordered by index
metalibm_core/core/indexing.py
get_sub_list
kalray/metalibm
27
python
def get_sub_list(self): ' ' raise NotImplementedError
def get_sub_list(self): ' ' raise NotImplementedError<|docstring|>return the list of sub-intervals ordered by index<|endoftext|>
b606a478c8b0ab26e6ccb3717679f999a2101b2ce6a04441c01e16a73fb82d90
def get_index_node(self, vx): ' generation an operation sub-graph to compute the\n indexing from input vx\n\n :param vx: input operand\n :type vx: ML_Operation\n\n ' assert (vx.precision is self.precision) int_precision = vx.precision.get_integer_format() index_size = (self.exp_bits + self.field_bits) index_mask = Constant(((2 ** index_size) - 1), precision=int_precision) shift_amount = Constant((vx.get_precision().get_field_size() - self.field_bits), precision=int_precision) exp_offset = Constant(self.precision.get_integer_coding((S2 ** self.low_exp_value)), precision=int_precision) return BitLogicAnd(BitLogicRightShift(Subtraction(TypeCast(vx, precision=int_precision), exp_offset, precision=int_precision), shift_amount, precision=int_precision), index_mask, precision=int_precision)
generation an operation sub-graph to compute the indexing from input vx :param vx: input operand :type vx: ML_Operation
metalibm_core/core/indexing.py
get_index_node
kalray/metalibm
27
python
def get_index_node(self, vx): ' generation an operation sub-graph to compute the\n indexing from input vx\n\n :param vx: input operand\n :type vx: ML_Operation\n\n ' assert (vx.precision is self.precision) int_precision = vx.precision.get_integer_format() index_size = (self.exp_bits + self.field_bits) index_mask = Constant(((2 ** index_size) - 1), precision=int_precision) shift_amount = Constant((vx.get_precision().get_field_size() - self.field_bits), precision=int_precision) exp_offset = Constant(self.precision.get_integer_coding((S2 ** self.low_exp_value)), precision=int_precision) return BitLogicAnd(BitLogicRightShift(Subtraction(TypeCast(vx, precision=int_precision), exp_offset, precision=int_precision), shift_amount, precision=int_precision), index_mask, precision=int_precision)
def get_index_node(self, vx): ' generation an operation sub-graph to compute the\n indexing from input vx\n\n :param vx: input operand\n :type vx: ML_Operation\n\n ' assert (vx.precision is self.precision) int_precision = vx.precision.get_integer_format() index_size = (self.exp_bits + self.field_bits) index_mask = Constant(((2 ** index_size) - 1), precision=int_precision) shift_amount = Constant((vx.get_precision().get_field_size() - self.field_bits), precision=int_precision) exp_offset = Constant(self.precision.get_integer_coding((S2 ** self.low_exp_value)), precision=int_precision) return BitLogicAnd(BitLogicRightShift(Subtraction(TypeCast(vx, precision=int_precision), exp_offset, precision=int_precision), shift_amount, precision=int_precision), index_mask, precision=int_precision)<|docstring|>generation an operation sub-graph to compute the indexing from input vx :param vx: input operand :type vx: ML_Operation<|endoftext|>
2408a590ff87e4027eb5739eac756cda49bbf0c2cf6c29265b297c77cff18dac
def get_sub_lo_bound(self, index): ' return the lower bound of the sub-interval\n of index @p index ' assert ((index >= 0) and (index < self.split_num)) field_index = (index % (2 ** self.field_bits)) exp_index = int((index / (2 ** self.field_bits))) exp_value = (exp_index + self.low_exp_value) lo_bound = ((1.0 + (field_index * (2 ** (- self.field_bits)))) * (S2 ** exp_value)) return lo_bound
return the lower bound of the sub-interval of index @p index
metalibm_core/core/indexing.py
get_sub_lo_bound
kalray/metalibm
27
python
def get_sub_lo_bound(self, index): ' return the lower bound of the sub-interval\n of index @p index ' assert ((index >= 0) and (index < self.split_num)) field_index = (index % (2 ** self.field_bits)) exp_index = int((index / (2 ** self.field_bits))) exp_value = (exp_index + self.low_exp_value) lo_bound = ((1.0 + (field_index * (2 ** (- self.field_bits)))) * (S2 ** exp_value)) return lo_bound
def get_sub_lo_bound(self, index): ' return the lower bound of the sub-interval\n of index @p index ' assert ((index >= 0) and (index < self.split_num)) field_index = (index % (2 ** self.field_bits)) exp_index = int((index / (2 ** self.field_bits))) exp_value = (exp_index + self.low_exp_value) lo_bound = ((1.0 + (field_index * (2 ** (- self.field_bits)))) * (S2 ** exp_value)) return lo_bound<|docstring|>return the lower bound of the sub-interval of index @p index<|endoftext|>
cd829d96d9223e59cbe978eb79cc9d29137a43b3f621991d3cb5a67911e296c1
def get_sub_hi_bound(self, index): ' return the upper bound of the sub-interval\n of index @p index ' assert ((index >= 0) and (index < self.split_num)) field_index = (index % (2 ** self.field_bits)) exp_index = int((index / (2 ** self.field_bits))) exp_value = (exp_index + self.low_exp_value) hi_bound = ((1.0 + ((field_index + 1) * (2 ** (- self.field_bits)))) * (S2 ** exp_value)) return hi_bound
return the upper bound of the sub-interval of index @p index
metalibm_core/core/indexing.py
get_sub_hi_bound
kalray/metalibm
27
python
def get_sub_hi_bound(self, index): ' return the upper bound of the sub-interval\n of index @p index ' assert ((index >= 0) and (index < self.split_num)) field_index = (index % (2 ** self.field_bits)) exp_index = int((index / (2 ** self.field_bits))) exp_value = (exp_index + self.low_exp_value) hi_bound = ((1.0 + ((field_index + 1) * (2 ** (- self.field_bits)))) * (S2 ** exp_value)) return hi_bound
def get_sub_hi_bound(self, index): ' return the upper bound of the sub-interval\n of index @p index ' assert ((index >= 0) and (index < self.split_num)) field_index = (index % (2 ** self.field_bits)) exp_index = int((index / (2 ** self.field_bits))) exp_value = (exp_index + self.low_exp_value) hi_bound = ((1.0 + ((field_index + 1) * (2 ** (- self.field_bits)))) * (S2 ** exp_value)) return hi_bound<|docstring|>return the upper bound of the sub-interval of index @p index<|endoftext|>
f4e0eedf8eeafed70bca94a8090207a71b382694fbd8cb97c8f308d7f9d7b049
def get_offseted_sub_interval(self, index): ' return a pair (offset, [0; size]) ' assert ((index >= 0) and (index < self.split_num)) lo_bound = self.get_sub_lo_bound(index) hi_bound = self.get_sub_hi_bound(index) return (lo_bound, Interval(0, (hi_bound - lo_bound)))
return a pair (offset, [0; size])
metalibm_core/core/indexing.py
get_offseted_sub_interval
kalray/metalibm
27
python
def get_offseted_sub_interval(self, index): ' ' assert ((index >= 0) and (index < self.split_num)) lo_bound = self.get_sub_lo_bound(index) hi_bound = self.get_sub_hi_bound(index) return (lo_bound, Interval(0, (hi_bound - lo_bound)))
def get_offseted_sub_interval(self, index): ' ' assert ((index >= 0) and (index < self.split_num)) lo_bound = self.get_sub_lo_bound(index) hi_bound = self.get_sub_hi_bound(index) return (lo_bound, Interval(0, (hi_bound - lo_bound)))<|docstring|>return a pair (offset, [0; size])<|endoftext|>
bebb3e1b9193184c0116f79aa42dc5f276d266138118168e995c9e61643f7b2c
def get_index_node(self, vx): ' return the meta graph to implement index calculation\n from input @p vx ' precision = vx.get_precision() bound_low = inf(self.interval) bound_high = sup(self.interval) num_intervals = self.split_num int_prec = precision.get_integer_format() diff = Subtraction(vx, Constant(bound_low, precision=precision), tag='diff', precision=precision) delta_ratio = Constant((num_intervals / (bound_high - bound_low)), precision=precision) index = Max(0, Min(NearestInteger(Multiplication(diff, delta_ratio, precision=precision), precision=int_prec), (num_intervals - 1)), tag='index', precision=int_prec) return index
return the meta graph to implement index calculation from input @p vx
metalibm_core/core/indexing.py
get_index_node
kalray/metalibm
27
python
def get_index_node(self, vx): ' return the meta graph to implement index calculation\n from input @p vx ' precision = vx.get_precision() bound_low = inf(self.interval) bound_high = sup(self.interval) num_intervals = self.split_num int_prec = precision.get_integer_format() diff = Subtraction(vx, Constant(bound_low, precision=precision), tag='diff', precision=precision) delta_ratio = Constant((num_intervals / (bound_high - bound_low)), precision=precision) index = Max(0, Min(NearestInteger(Multiplication(diff, delta_ratio, precision=precision), precision=int_prec), (num_intervals - 1)), tag='index', precision=int_prec) return index
def get_index_node(self, vx): ' return the meta graph to implement index calculation\n from input @p vx ' precision = vx.get_precision() bound_low = inf(self.interval) bound_high = sup(self.interval) num_intervals = self.split_num int_prec = precision.get_integer_format() diff = Subtraction(vx, Constant(bound_low, precision=precision), tag='diff', precision=precision) delta_ratio = Constant((num_intervals / (bound_high - bound_low)), precision=precision) index = Max(0, Min(NearestInteger(Multiplication(diff, delta_ratio, precision=precision), precision=int_prec), (num_intervals - 1)), tag='index', precision=int_prec) return index<|docstring|>return the meta graph to implement index calculation from input @p vx<|endoftext|>
f8f5e25b4550cffe7745fc52428f1a578efc86ed360dd1865498ef7367bcff1b
def get_sub_interval(self, index): ' return the sub-interval numbered @p index ' subint_low = (self.bound_low + (i * interval_size)) subint_high = (self.bound_low + ((i + 1) * interval_size)) return Interval(subint_low, subint_high)
return the sub-interval numbered @p index
metalibm_core/core/indexing.py
get_sub_interval
kalray/metalibm
27
python
def get_sub_interval(self, index): ' ' subint_low = (self.bound_low + (i * interval_size)) subint_high = (self.bound_low + ((i + 1) * interval_size)) return Interval(subint_low, subint_high)
def get_sub_interval(self, index): ' ' subint_low = (self.bound_low + (i * interval_size)) subint_high = (self.bound_low + ((i + 1) * interval_size)) return Interval(subint_low, subint_high)<|docstring|>return the sub-interval numbered @p index<|endoftext|>
46e6c1224f04bdfef7fa5f446d3172a83295b4ae0c2213eec106a3651f43cc7e
def create_pending_command(command_id: str='command-id', command_type: str='command-type', params: Optional[BaseModel]=None) -> cmd.Command: 'Given command data, build a pending command model.' return cast(cmd.Command, cmd.BaseCommand(id=command_id, commandType=command_type, createdAt=datetime(year=2021, month=1, day=1), status=cmd.CommandStatus.QUEUED, params=(params or BaseModel())))
Given command data, build a pending command model.
api/tests/opentrons/protocol_engine/state/command_fixtures.py
create_pending_command
mrod0101/opentrons
0
python
def create_pending_command(command_id: str='command-id', command_type: str='command-type', params: Optional[BaseModel]=None) -> cmd.Command: return cast(cmd.Command, cmd.BaseCommand(id=command_id, commandType=command_type, createdAt=datetime(year=2021, month=1, day=1), status=cmd.CommandStatus.QUEUED, params=(params or BaseModel())))
def create_pending_command(command_id: str='command-id', command_type: str='command-type', params: Optional[BaseModel]=None) -> cmd.Command: return cast(cmd.Command, cmd.BaseCommand(id=command_id, commandType=command_type, createdAt=datetime(year=2021, month=1, day=1), status=cmd.CommandStatus.QUEUED, params=(params or BaseModel())))<|docstring|>Given command data, build a pending command model.<|endoftext|>
9948daa9a5bb8707603df89d23b7e7f6c11a152b767aae6b4726580b8e70f104
def create_running_command(command_id: str='command-id', command_type: str='command-type', params: Optional[BaseModel]=None) -> cmd.Command: 'Given command data, build a running command model.' return cast(cmd.Command, cmd.BaseCommand(id=command_id, createdAt=datetime(year=2021, month=1, day=1), commandType=command_type, status=cmd.CommandStatus.RUNNING, params=(params or BaseModel())))
Given command data, build a running command model.
api/tests/opentrons/protocol_engine/state/command_fixtures.py
create_running_command
mrod0101/opentrons
0
python
def create_running_command(command_id: str='command-id', command_type: str='command-type', params: Optional[BaseModel]=None) -> cmd.Command: return cast(cmd.Command, cmd.BaseCommand(id=command_id, createdAt=datetime(year=2021, month=1, day=1), commandType=command_type, status=cmd.CommandStatus.RUNNING, params=(params or BaseModel())))
def create_running_command(command_id: str='command-id', command_type: str='command-type', params: Optional[BaseModel]=None) -> cmd.Command: return cast(cmd.Command, cmd.BaseCommand(id=command_id, createdAt=datetime(year=2021, month=1, day=1), commandType=command_type, status=cmd.CommandStatus.RUNNING, params=(params or BaseModel())))<|docstring|>Given command data, build a running command model.<|endoftext|>
7491209d24d73526a034f1ccb19ab518664cb77437d56d995624ace458c39c99
def create_failed_command(command_id: str='command-id', command_type: str='command-type', error_id: str='error-id', completed_at: datetime=datetime(year=2022, month=2, day=2), params: Optional[BaseModel]=None) -> cmd.Command: 'Given command data, build a failed command model.' return cast(cmd.Command, cmd.BaseCommand(id=command_id, createdAt=datetime(year=2021, month=1, day=1), commandType=command_type, status=cmd.CommandStatus.FAILED, params=(params or BaseModel()), errorId=error_id, completedAt=completed_at))
Given command data, build a failed command model.
api/tests/opentrons/protocol_engine/state/command_fixtures.py
create_failed_command
mrod0101/opentrons
0
python
def create_failed_command(command_id: str='command-id', command_type: str='command-type', error_id: str='error-id', completed_at: datetime=datetime(year=2022, month=2, day=2), params: Optional[BaseModel]=None) -> cmd.Command: return cast(cmd.Command, cmd.BaseCommand(id=command_id, createdAt=datetime(year=2021, month=1, day=1), commandType=command_type, status=cmd.CommandStatus.FAILED, params=(params or BaseModel()), errorId=error_id, completedAt=completed_at))
def create_failed_command(command_id: str='command-id', command_type: str='command-type', error_id: str='error-id', completed_at: datetime=datetime(year=2022, month=2, day=2), params: Optional[BaseModel]=None) -> cmd.Command: return cast(cmd.Command, cmd.BaseCommand(id=command_id, createdAt=datetime(year=2021, month=1, day=1), commandType=command_type, status=cmd.CommandStatus.FAILED, params=(params or BaseModel()), errorId=error_id, completedAt=completed_at))<|docstring|>Given command data, build a failed command model.<|endoftext|>
f975a36930132f666dcdad2e5fd2c5de3da61b575a71c08115785b7cdd8a55fa
def create_completed_command(command_id: str='command-id', command_type: str='command-type', params: Optional[BaseModel]=None, result: Optional[BaseModel]=None) -> cmd.Command: 'Given command data and result, build a completed command model.' return cast(cmd.Command, cmd.BaseCommand(id=command_id, createdAt=datetime(year=2021, month=1, day=1), commandType=command_type, status=cmd.CommandStatus.SUCCEEDED, params=(params or BaseModel()), result=(result or BaseModel())))
Given command data and result, build a completed command model.
api/tests/opentrons/protocol_engine/state/command_fixtures.py
create_completed_command
mrod0101/opentrons
0
python
def create_completed_command(command_id: str='command-id', command_type: str='command-type', params: Optional[BaseModel]=None, result: Optional[BaseModel]=None) -> cmd.Command: return cast(cmd.Command, cmd.BaseCommand(id=command_id, createdAt=datetime(year=2021, month=1, day=1), commandType=command_type, status=cmd.CommandStatus.SUCCEEDED, params=(params or BaseModel()), result=(result or BaseModel())))
def create_completed_command(command_id: str='command-id', command_type: str='command-type', params: Optional[BaseModel]=None, result: Optional[BaseModel]=None) -> cmd.Command: return cast(cmd.Command, cmd.BaseCommand(id=command_id, createdAt=datetime(year=2021, month=1, day=1), commandType=command_type, status=cmd.CommandStatus.SUCCEEDED, params=(params or BaseModel()), result=(result or BaseModel())))<|docstring|>Given command data and result, build a completed command model.<|endoftext|>
1fda68e4d5160e8bdca2d81466a336eee10a0f45ba537890dbdf4f09c4a4fb39
def create_load_labware_command(labware_id: str, location: LabwareLocation, definition: LabwareDefinition, offset_id: Optional[str]) -> cmd.LoadLabware: 'Create a completed LoadLabware command.' params = cmd.LoadLabwareParams(loadName=definition.parameters.loadName, namespace=definition.namespace, version=definition.version, location=location, labwareId=None) result = cmd.LoadLabwareResult(labwareId=labware_id, definition=definition, offsetId=offset_id) return cmd.LoadLabware(id='command-id', status=cmd.CommandStatus.SUCCEEDED, createdAt=datetime.now(), params=params, result=result)
Create a completed LoadLabware command.
api/tests/opentrons/protocol_engine/state/command_fixtures.py
create_load_labware_command
mrod0101/opentrons
0
python
def create_load_labware_command(labware_id: str, location: LabwareLocation, definition: LabwareDefinition, offset_id: Optional[str]) -> cmd.LoadLabware: params = cmd.LoadLabwareParams(loadName=definition.parameters.loadName, namespace=definition.namespace, version=definition.version, location=location, labwareId=None) result = cmd.LoadLabwareResult(labwareId=labware_id, definition=definition, offsetId=offset_id) return cmd.LoadLabware(id='command-id', status=cmd.CommandStatus.SUCCEEDED, createdAt=datetime.now(), params=params, result=result)
def create_load_labware_command(labware_id: str, location: LabwareLocation, definition: LabwareDefinition, offset_id: Optional[str]) -> cmd.LoadLabware: params = cmd.LoadLabwareParams(loadName=definition.parameters.loadName, namespace=definition.namespace, version=definition.version, location=location, labwareId=None) result = cmd.LoadLabwareResult(labwareId=labware_id, definition=definition, offsetId=offset_id) return cmd.LoadLabware(id='command-id', status=cmd.CommandStatus.SUCCEEDED, createdAt=datetime.now(), params=params, result=result)<|docstring|>Create a completed LoadLabware command.<|endoftext|>
e5ce8d3f979f313c288ecd84e0419a26a1e35a3aac558d0d0ce0d83de719ff74
def create_add_definition_command(definition: LabwareDefinition) -> cmd.AddLabwareDefinition: 'Create a completed AddLabwareDefinition command.' params = cmd.AddLabwareDefinitionParams(definition=definition) result = cmd.AddLabwareDefinitionResult(loadName=definition.parameters.loadName, namespace=definition.namespace, version=definition.version) return cmd.AddLabwareDefinition(id='command-id', status=cmd.CommandStatus.SUCCEEDED, createdAt=datetime.now(), params=params, result=result)
Create a completed AddLabwareDefinition command.
api/tests/opentrons/protocol_engine/state/command_fixtures.py
create_add_definition_command
mrod0101/opentrons
0
python
def create_add_definition_command(definition: LabwareDefinition) -> cmd.AddLabwareDefinition: params = cmd.AddLabwareDefinitionParams(definition=definition) result = cmd.AddLabwareDefinitionResult(loadName=definition.parameters.loadName, namespace=definition.namespace, version=definition.version) return cmd.AddLabwareDefinition(id='command-id', status=cmd.CommandStatus.SUCCEEDED, createdAt=datetime.now(), params=params, result=result)
def create_add_definition_command(definition: LabwareDefinition) -> cmd.AddLabwareDefinition: params = cmd.AddLabwareDefinitionParams(definition=definition) result = cmd.AddLabwareDefinitionResult(loadName=definition.parameters.loadName, namespace=definition.namespace, version=definition.version) return cmd.AddLabwareDefinition(id='command-id', status=cmd.CommandStatus.SUCCEEDED, createdAt=datetime.now(), params=params, result=result)<|docstring|>Create a completed AddLabwareDefinition command.<|endoftext|>
73f4a4c60f8380ee5bcf252845d3983f22eef0daaeaffd41c14ba797dfae3dc0
def create_load_pipette_command(pipette_id: str, pipette_name: PipetteName, mount: MountType) -> cmd.LoadPipette: 'Get a completed LoadPipette command.' params = cmd.LoadPipetteParams(pipetteName=pipette_name, mount=mount) result = cmd.LoadPipetteResult(pipetteId=pipette_id) return cmd.LoadPipette(id='command-id', status=cmd.CommandStatus.SUCCEEDED, createdAt=datetime.now(), params=params, result=result)
Get a completed LoadPipette command.
api/tests/opentrons/protocol_engine/state/command_fixtures.py
create_load_pipette_command
mrod0101/opentrons
0
python
def create_load_pipette_command(pipette_id: str, pipette_name: PipetteName, mount: MountType) -> cmd.LoadPipette: params = cmd.LoadPipetteParams(pipetteName=pipette_name, mount=mount) result = cmd.LoadPipetteResult(pipetteId=pipette_id) return cmd.LoadPipette(id='command-id', status=cmd.CommandStatus.SUCCEEDED, createdAt=datetime.now(), params=params, result=result)
def create_load_pipette_command(pipette_id: str, pipette_name: PipetteName, mount: MountType) -> cmd.LoadPipette: params = cmd.LoadPipetteParams(pipetteName=pipette_name, mount=mount) result = cmd.LoadPipetteResult(pipetteId=pipette_id) return cmd.LoadPipette(id='command-id', status=cmd.CommandStatus.SUCCEEDED, createdAt=datetime.now(), params=params, result=result)<|docstring|>Get a completed LoadPipette command.<|endoftext|>
316cad4c7f09e459e14f2ff038977c77c5c11e805d10476c5915f54d75c2111e
def create_aspirate_command(pipette_id: str, volume: float, labware_id: str='labware-id', well_name: str='A1', well_location: Optional[WellLocation]=None) -> cmd.Aspirate: 'Get a completed Aspirate command.' params = cmd.AspirateParams(pipetteId=pipette_id, labwareId=labware_id, wellName=well_name, wellLocation=(well_location or WellLocation()), volume=volume) result = cmd.AspirateResult(volume=volume) return cmd.Aspirate(id='command-id', status=cmd.CommandStatus.SUCCEEDED, createdAt=datetime.now(), params=params, result=result)
Get a completed Aspirate command.
api/tests/opentrons/protocol_engine/state/command_fixtures.py
create_aspirate_command
mrod0101/opentrons
0
python
def create_aspirate_command(pipette_id: str, volume: float, labware_id: str='labware-id', well_name: str='A1', well_location: Optional[WellLocation]=None) -> cmd.Aspirate: params = cmd.AspirateParams(pipetteId=pipette_id, labwareId=labware_id, wellName=well_name, wellLocation=(well_location or WellLocation()), volume=volume) result = cmd.AspirateResult(volume=volume) return cmd.Aspirate(id='command-id', status=cmd.CommandStatus.SUCCEEDED, createdAt=datetime.now(), params=params, result=result)
def create_aspirate_command(pipette_id: str, volume: float, labware_id: str='labware-id', well_name: str='A1', well_location: Optional[WellLocation]=None) -> cmd.Aspirate: params = cmd.AspirateParams(pipetteId=pipette_id, labwareId=labware_id, wellName=well_name, wellLocation=(well_location or WellLocation()), volume=volume) result = cmd.AspirateResult(volume=volume) return cmd.Aspirate(id='command-id', status=cmd.CommandStatus.SUCCEEDED, createdAt=datetime.now(), params=params, result=result)<|docstring|>Get a completed Aspirate command.<|endoftext|>
6836d764672ee50a869725479570a5954a9dc3665843d6cdc5bb277eef98cca6
def create_dispense_command(pipette_id: str, volume: float, labware_id: str='labware-id', well_name: str='A1', well_location: Optional[WellLocation]=None) -> cmd.Dispense: 'Get a completed Dispense command.' params = cmd.DispenseParams(pipetteId=pipette_id, labwareId=labware_id, wellName=well_name, wellLocation=(well_location or WellLocation()), volume=volume) result = cmd.DispenseResult(volume=volume) return cmd.Dispense(id='command-id', status=cmd.CommandStatus.SUCCEEDED, createdAt=datetime.now(), params=params, result=result)
Get a completed Dispense command.
api/tests/opentrons/protocol_engine/state/command_fixtures.py
create_dispense_command
mrod0101/opentrons
0
python
def create_dispense_command(pipette_id: str, volume: float, labware_id: str='labware-id', well_name: str='A1', well_location: Optional[WellLocation]=None) -> cmd.Dispense: params = cmd.DispenseParams(pipetteId=pipette_id, labwareId=labware_id, wellName=well_name, wellLocation=(well_location or WellLocation()), volume=volume) result = cmd.DispenseResult(volume=volume) return cmd.Dispense(id='command-id', status=cmd.CommandStatus.SUCCEEDED, createdAt=datetime.now(), params=params, result=result)
def create_dispense_command(pipette_id: str, volume: float, labware_id: str='labware-id', well_name: str='A1', well_location: Optional[WellLocation]=None) -> cmd.Dispense: params = cmd.DispenseParams(pipetteId=pipette_id, labwareId=labware_id, wellName=well_name, wellLocation=(well_location or WellLocation()), volume=volume) result = cmd.DispenseResult(volume=volume) return cmd.Dispense(id='command-id', status=cmd.CommandStatus.SUCCEEDED, createdAt=datetime.now(), params=params, result=result)<|docstring|>Get a completed Dispense command.<|endoftext|>
6262bdc75750bda27cc70949ae5e6937b4684caaddba83e095ae8bd823dc33e4
def create_pick_up_tip_command(pipette_id: str, labware_id: str='labware-id', well_name: str='A1') -> cmd.PickUpTip: 'Get a completed PickUpTip command.' data = cmd.PickUpTipParams(pipetteId=pipette_id, labwareId=labware_id, wellName=well_name) result = cmd.PickUpTipResult() return cmd.PickUpTip(id='command-id', status=cmd.CommandStatus.SUCCEEDED, createdAt=datetime.now(), params=data, result=result)
Get a completed PickUpTip command.
api/tests/opentrons/protocol_engine/state/command_fixtures.py
create_pick_up_tip_command
mrod0101/opentrons
0
python
def create_pick_up_tip_command(pipette_id: str, labware_id: str='labware-id', well_name: str='A1') -> cmd.PickUpTip: data = cmd.PickUpTipParams(pipetteId=pipette_id, labwareId=labware_id, wellName=well_name) result = cmd.PickUpTipResult() return cmd.PickUpTip(id='command-id', status=cmd.CommandStatus.SUCCEEDED, createdAt=datetime.now(), params=data, result=result)
def create_pick_up_tip_command(pipette_id: str, labware_id: str='labware-id', well_name: str='A1') -> cmd.PickUpTip: data = cmd.PickUpTipParams(pipetteId=pipette_id, labwareId=labware_id, wellName=well_name) result = cmd.PickUpTipResult() return cmd.PickUpTip(id='command-id', status=cmd.CommandStatus.SUCCEEDED, createdAt=datetime.now(), params=data, result=result)<|docstring|>Get a completed PickUpTip command.<|endoftext|>
c20cd9818f6c45039d4c4f4eb6c6cfaf91057e7264ed614286ab4a7a12820045
def create_drop_tip_command(pipette_id: str, labware_id: str='labware-id', well_name: str='A1') -> cmd.DropTip: 'Get a completed DropTip command.' params = cmd.DropTipParams(pipetteId=pipette_id, labwareId=labware_id, wellName=well_name) result = cmd.DropTipResult() return cmd.DropTip(id='command-id', status=cmd.CommandStatus.SUCCEEDED, createdAt=datetime.now(), params=params, result=result)
Get a completed DropTip command.
api/tests/opentrons/protocol_engine/state/command_fixtures.py
create_drop_tip_command
mrod0101/opentrons
0
python
def create_drop_tip_command(pipette_id: str, labware_id: str='labware-id', well_name: str='A1') -> cmd.DropTip: params = cmd.DropTipParams(pipetteId=pipette_id, labwareId=labware_id, wellName=well_name) result = cmd.DropTipResult() return cmd.DropTip(id='command-id', status=cmd.CommandStatus.SUCCEEDED, createdAt=datetime.now(), params=params, result=result)
def create_drop_tip_command(pipette_id: str, labware_id: str='labware-id', well_name: str='A1') -> cmd.DropTip: params = cmd.DropTipParams(pipetteId=pipette_id, labwareId=labware_id, wellName=well_name) result = cmd.DropTipResult() return cmd.DropTip(id='command-id', status=cmd.CommandStatus.SUCCEEDED, createdAt=datetime.now(), params=params, result=result)<|docstring|>Get a completed DropTip command.<|endoftext|>
5812c0944134aedadd19909b651e162bbdf24a5dd358d1d3fec47c1dd229a1fa
def create_move_to_well_command(pipette_id: str, labware_id: str='labware-id', well_name: str='A1') -> cmd.MoveToWell: 'Get a completed MoveToWell command.' params = cmd.MoveToWellParams(pipetteId=pipette_id, labwareId=labware_id, wellName=well_name) result = cmd.MoveToWellResult() return cmd.MoveToWell(id='command-id', status=cmd.CommandStatus.SUCCEEDED, createdAt=datetime.now(), params=params, result=result)
Get a completed MoveToWell command.
api/tests/opentrons/protocol_engine/state/command_fixtures.py
create_move_to_well_command
mrod0101/opentrons
0
python
def create_move_to_well_command(pipette_id: str, labware_id: str='labware-id', well_name: str='A1') -> cmd.MoveToWell: params = cmd.MoveToWellParams(pipetteId=pipette_id, labwareId=labware_id, wellName=well_name) result = cmd.MoveToWellResult() return cmd.MoveToWell(id='command-id', status=cmd.CommandStatus.SUCCEEDED, createdAt=datetime.now(), params=params, result=result)
def create_move_to_well_command(pipette_id: str, labware_id: str='labware-id', well_name: str='A1') -> cmd.MoveToWell: params = cmd.MoveToWellParams(pipetteId=pipette_id, labwareId=labware_id, wellName=well_name) result = cmd.MoveToWellResult() return cmd.MoveToWell(id='command-id', status=cmd.CommandStatus.SUCCEEDED, createdAt=datetime.now(), params=params, result=result)<|docstring|>Get a completed MoveToWell command.<|endoftext|>
8d76cf9c82e0ab20a833eb6468143f0468f1bd39c5e30159c4b88da47a44be6a
def _get_results(self, hash_output=False): 'Digest info in the statepoint and return as a string.' sp = openmc.StatePoint(self._sp_name) self.mgxs_lib.load_from_statepoint(sp) self.mgxs_lib.build_hdf5_store(directory='.') with h5py.File('mgxs.h5', 'r') as f: outstr = '' for domain in self.mgxs_lib.domains: for mgxs_type in self.mgxs_lib.mgxs_types: outstr += 'domain={0} type={1}\n'.format(domain.id, mgxs_type) avg_key = 'mesh/{}/{}/average'.format(domain.id, mgxs_type) std_key = 'mesh/{}/{}/std. dev.'.format(domain.id, mgxs_type) outstr += '{}\n{}\n'.format(f[avg_key][...], f[std_key][...]) if hash_output: sha512 = hashlib.sha512() sha512.update(outstr.encode('utf-8')) outstr = sha512.hexdigest() return outstr
Digest info in the statepoint and return as a string.
tests/regression_tests/mgxs_library_hdf5/test.py
_get_results
MC-kit/openmc
262
python
def _get_results(self, hash_output=False): sp = openmc.StatePoint(self._sp_name) self.mgxs_lib.load_from_statepoint(sp) self.mgxs_lib.build_hdf5_store(directory='.') with h5py.File('mgxs.h5', 'r') as f: outstr = for domain in self.mgxs_lib.domains: for mgxs_type in self.mgxs_lib.mgxs_types: outstr += 'domain={0} type={1}\n'.format(domain.id, mgxs_type) avg_key = 'mesh/{}/{}/average'.format(domain.id, mgxs_type) std_key = 'mesh/{}/{}/std. dev.'.format(domain.id, mgxs_type) outstr += '{}\n{}\n'.format(f[avg_key][...], f[std_key][...]) if hash_output: sha512 = hashlib.sha512() sha512.update(outstr.encode('utf-8')) outstr = sha512.hexdigest() return outstr
def _get_results(self, hash_output=False): sp = openmc.StatePoint(self._sp_name) self.mgxs_lib.load_from_statepoint(sp) self.mgxs_lib.build_hdf5_store(directory='.') with h5py.File('mgxs.h5', 'r') as f: outstr = for domain in self.mgxs_lib.domains: for mgxs_type in self.mgxs_lib.mgxs_types: outstr += 'domain={0} type={1}\n'.format(domain.id, mgxs_type) avg_key = 'mesh/{}/{}/average'.format(domain.id, mgxs_type) std_key = 'mesh/{}/{}/std. dev.'.format(domain.id, mgxs_type) outstr += '{}\n{}\n'.format(f[avg_key][...], f[std_key][...]) if hash_output: sha512 = hashlib.sha512() sha512.update(outstr.encode('utf-8')) outstr = sha512.hexdigest() return outstr<|docstring|>Digest info in the statepoint and return as a string.<|endoftext|>
da462d22cc3444c0dde0fe31b9bf928cf30c7a09228f1de1b55c40b859e2ba1b
def configure(config): '\n | name | example | purpose |\n | ---- | ------- | ------- |\n | oblique_instance | https://oblique.sopel.chat/ | The Oblique instance to use when evaluating Python expressions (see <https://github.com/sopel-irc/oblique>) |\n ' config.define_section('py', PySection) config.py.configure_setting('oblique_instance', 'Enter the base URL of a custom Oblique instance (optional): ')
| name | example | purpose | | ---- | ------- | ------- | | oblique_instance | https://oblique.sopel.chat/ | The Oblique instance to use when evaluating Python expressions (see <https://github.com/sopel-irc/oblique>) |
sopel/modules/py.py
configure
adamus1red/sopel
555
python
def configure(config): '\n | name | example | purpose |\n | ---- | ------- | ------- |\n | oblique_instance | https://oblique.sopel.chat/ | The Oblique instance to use when evaluating Python expressions (see <https://github.com/sopel-irc/oblique>) |\n ' config.define_section('py', PySection) config.py.configure_setting('oblique_instance', 'Enter the base URL of a custom Oblique instance (optional): ')
def configure(config): '\n | name | example | purpose |\n | ---- | ------- | ------- |\n | oblique_instance | https://oblique.sopel.chat/ | The Oblique instance to use when evaluating Python expressions (see <https://github.com/sopel-irc/oblique>) |\n ' config.define_section('py', PySection) config.py.configure_setting('oblique_instance', 'Enter the base URL of a custom Oblique instance (optional): ')<|docstring|>| name | example | purpose | | ---- | ------- | ------- | | oblique_instance | https://oblique.sopel.chat/ | The Oblique instance to use when evaluating Python expressions (see <https://github.com/sopel-irc/oblique>) |<|endoftext|>
7ca53de1244e781cd2c65d386a9662ef4b114c984256e4afba1b3784c8225a39
@plugin.command('py') @plugin.output_prefix('[py] ') @plugin.example('.py len([1,2,3])', '3', online=True, vcr=True) def py(bot, trigger): 'Evaluate a Python expression.' query = trigger.group(2) if (not query): bot.reply('What expression do you want me to evaluate?') return uri = (bot.config.py.oblique_instance + 'py/') answer = get((uri + quote(query))).content.decode('utf-8') if answer: bot.say(answer) else: bot.reply('Sorry, no result.')
Evaluate a Python expression.
sopel/modules/py.py
py
adamus1red/sopel
555
python
@plugin.command('py') @plugin.output_prefix('[py] ') @plugin.example('.py len([1,2,3])', '3', online=True, vcr=True) def py(bot, trigger): query = trigger.group(2) if (not query): bot.reply('What expression do you want me to evaluate?') return uri = (bot.config.py.oblique_instance + 'py/') answer = get((uri + quote(query))).content.decode('utf-8') if answer: bot.say(answer) else: bot.reply('Sorry, no result.')
@plugin.command('py') @plugin.output_prefix('[py] ') @plugin.example('.py len([1,2,3])', '3', online=True, vcr=True) def py(bot, trigger): query = trigger.group(2) if (not query): bot.reply('What expression do you want me to evaluate?') return uri = (bot.config.py.oblique_instance + 'py/') answer = get((uri + quote(query))).content.decode('utf-8') if answer: bot.say(answer) else: bot.reply('Sorry, no result.')<|docstring|>Evaluate a Python expression.<|endoftext|>
e3eb378ae172c1c3d1ba9e23330b931a3b60a764e6d0cee5a5de558511fb4e28
def system_run() -> None: 'os.system ่ฟ่กŒ' print('os.system start!') os.system(bash_cmd)
os.system ่ฟ่กŒ
python_advance/ๅœจpython่„šๆœฌไธญ่ฟ่กŒ่„šๆœฌ็š„ๅ‡ ็งๆ–นๆณ•/run_bash.py
system_run
Dustyposa/goSpider
66
python
def system_run() -> None: print('os.system start!') os.system(bash_cmd)
def system_run() -> None: print('os.system start!') os.system(bash_cmd)<|docstring|>os.system ่ฟ่กŒ<|endoftext|>
b9c1dfcacbf8a071334ee0eba9d0fd0f7d7aba00986109b0a366a6bd670d71ee
def os_popen_run() -> None: 'ไฝฟ็”จos.popen ่ฟ่กŒๅญ่ฟ›็จ‹' print('Start') with os.popen(' '.join(python_cmd_list)) as pipe: for line in pipe.readlines(): print(line, end='') '\n with os.popen(bash_cmd) as pipe, open("bash_out.txt", "w", encoding="u8") as fp:\n for line in pipe.readlines():\n print(line, end="", file=fp)\n '
ไฝฟ็”จos.popen ่ฟ่กŒๅญ่ฟ›็จ‹
python_advance/ๅœจpython่„šๆœฌไธญ่ฟ่กŒ่„šๆœฌ็š„ๅ‡ ็งๆ–นๆณ•/run_bash.py
os_popen_run
Dustyposa/goSpider
66
python
def os_popen_run() -> None: print('Start') with os.popen(' '.join(python_cmd_list)) as pipe: for line in pipe.readlines(): print(line, end=) '\n with os.popen(bash_cmd) as pipe, open("bash_out.txt", "w", encoding="u8") as fp:\n for line in pipe.readlines():\n print(line, end=, file=fp)\n '
def os_popen_run() -> None: print('Start') with os.popen(' '.join(python_cmd_list)) as pipe: for line in pipe.readlines(): print(line, end=) '\n with os.popen(bash_cmd) as pipe, open("bash_out.txt", "w", encoding="u8") as fp:\n for line in pipe.readlines():\n print(line, end=, file=fp)\n '<|docstring|>ไฝฟ็”จos.popen ่ฟ่กŒๅญ่ฟ›็จ‹<|endoftext|>
99065a2a80a967db9a50ec611aa78f428763af1d89b7ae82926599c40ff73af4
def os_exec_run() -> None: 'ๆ›ฟไปฃๅฝ“ๅ‰่ฟ›็จ‹็š„่ฟ่กŒ' print('python ๆญฃๅœจ่ฟ่กŒ') time.sleep(5) print('python ่ฟ่กŒๅฎŒๆฏ•๏ผŒๆ‰ง่กŒ bash ่„šๆœฌ') os.execv(zsh_file, bash_cmd_list)
ๆ›ฟไปฃๅฝ“ๅ‰่ฟ›็จ‹็š„่ฟ่กŒ
python_advance/ๅœจpython่„šๆœฌไธญ่ฟ่กŒ่„šๆœฌ็š„ๅ‡ ็งๆ–นๆณ•/run_bash.py
os_exec_run
Dustyposa/goSpider
66
python
def os_exec_run() -> None: print('python ๆญฃๅœจ่ฟ่กŒ') time.sleep(5) print('python ่ฟ่กŒๅฎŒๆฏ•๏ผŒๆ‰ง่กŒ bash ่„šๆœฌ') os.execv(zsh_file, bash_cmd_list)
def os_exec_run() -> None: print('python ๆญฃๅœจ่ฟ่กŒ') time.sleep(5) print('python ่ฟ่กŒๅฎŒๆฏ•๏ผŒๆ‰ง่กŒ bash ่„šๆœฌ') os.execv(zsh_file, bash_cmd_list)<|docstring|>ๆ›ฟไปฃๅฝ“ๅ‰่ฟ›็จ‹็š„่ฟ่กŒ<|endoftext|>
c0d56ea2f4a75477710d2db05c6a5822c11a16a2225afd4791f8a63bcd2c1251
def receive_binary(self, algorithm: str) -> bytes: '\n Returns a list of 8-bit integer values.\n Each value being one color channel.\n 3 values representing one pixel\n ' self.sock.send(f'''STATE {algorithm} '''.encode('ASCII')) response = b'' while ((len(response) == 0) or (response[(- 1)] != 10)): response += self.sock.recv((1024 * 4)) response = response[:(- 1)] response = response.split(b' ', 2)[2] return base64.b64decode(response)
Returns a list of 8-bit integer values. Each value being one color channel. 3 values representing one pixel
frontend-python/src/pixelflut_client.py
receive_binary
ftsell/pixelflu
7
python
def receive_binary(self, algorithm: str) -> bytes: '\n Returns a list of 8-bit integer values.\n Each value being one color channel.\n 3 values representing one pixel\n ' self.sock.send(f'STATE {algorithm} '.encode('ASCII')) response = b while ((len(response) == 0) or (response[(- 1)] != 10)): response += self.sock.recv((1024 * 4)) response = response[:(- 1)] response = response.split(b' ', 2)[2] return base64.b64decode(response)
def receive_binary(self, algorithm: str) -> bytes: '\n Returns a list of 8-bit integer values.\n Each value being one color channel.\n 3 values representing one pixel\n ' self.sock.send(f'STATE {algorithm} '.encode('ASCII')) response = b while ((len(response) == 0) or (response[(- 1)] != 10)): response += self.sock.recv((1024 * 4)) response = response[:(- 1)] response = response.split(b' ', 2)[2] return base64.b64decode(response)<|docstring|>Returns a list of 8-bit integer values. Each value being one color channel. 3 values representing one pixel<|endoftext|>
d285f7e3ea99a00609640404b322005e309abb0b290a5f62b8bb91ff58eb3905
def __init__(__self__, *, namespace: str, default_action: Optional[str]=None, filter_action: Optional[str]=None, filter_source: Optional[str]=None): '\n :param str namespace: An AWS custom namespace having custom AWS metrics that you want to sync with SignalFx. See the AWS documentation on publishing metrics for more information.\n :param str default_action: Controls the SignalFx default behavior for processing data from an AWS namespace. If you do specify a filter, use this property to control how SignalFx treats data that doesn\'t match the filter. The available actions are one of `"Include"` or `"Exclude"`.\n :param str filter_action: Controls how SignalFx processes data from a custom AWS namespace. The available actions are one of `"Include"` or `"Exclude"`.\n :param str filter_source: Expression that selects the data that SignalFx should sync for the custom namespace associated with this sync rule. The expression uses the syntax defined for the SignalFlow `filter()` function; it can be any valid SignalFlow filter expression.\n ' pulumi.set(__self__, 'namespace', namespace) if (default_action is not None): pulumi.set(__self__, 'default_action', default_action) if (filter_action is not None): pulumi.set(__self__, 'filter_action', filter_action) if (filter_source is not None): pulumi.set(__self__, 'filter_source', filter_source)
:param str namespace: An AWS custom namespace having custom AWS metrics that you want to sync with SignalFx. See the AWS documentation on publishing metrics for more information. :param str default_action: Controls the SignalFx default behavior for processing data from an AWS namespace. If you do specify a filter, use this property to control how SignalFx treats data that doesn't match the filter. The available actions are one of `"Include"` or `"Exclude"`. :param str filter_action: Controls how SignalFx processes data from a custom AWS namespace. The available actions are one of `"Include"` or `"Exclude"`. :param str filter_source: Expression that selects the data that SignalFx should sync for the custom namespace associated with this sync rule. The expression uses the syntax defined for the SignalFlow `filter()` function; it can be any valid SignalFlow filter expression.
sdk/python/pulumi_signalfx/aws/outputs.py
__init__
pulumi/pulumi-signalfx
2
python
def __init__(__self__, *, namespace: str, default_action: Optional[str]=None, filter_action: Optional[str]=None, filter_source: Optional[str]=None): '\n :param str namespace: An AWS custom namespace having custom AWS metrics that you want to sync with SignalFx. See the AWS documentation on publishing metrics for more information.\n :param str default_action: Controls the SignalFx default behavior for processing data from an AWS namespace. If you do specify a filter, use this property to control how SignalFx treats data that doesn\'t match the filter. The available actions are one of `"Include"` or `"Exclude"`.\n :param str filter_action: Controls how SignalFx processes data from a custom AWS namespace. The available actions are one of `"Include"` or `"Exclude"`.\n :param str filter_source: Expression that selects the data that SignalFx should sync for the custom namespace associated with this sync rule. The expression uses the syntax defined for the SignalFlow `filter()` function; it can be any valid SignalFlow filter expression.\n ' pulumi.set(__self__, 'namespace', namespace) if (default_action is not None): pulumi.set(__self__, 'default_action', default_action) if (filter_action is not None): pulumi.set(__self__, 'filter_action', filter_action) if (filter_source is not None): pulumi.set(__self__, 'filter_source', filter_source)
def __init__(__self__, *, namespace: str, default_action: Optional[str]=None, filter_action: Optional[str]=None, filter_source: Optional[str]=None): '\n :param str namespace: An AWS custom namespace having custom AWS metrics that you want to sync with SignalFx. See the AWS documentation on publishing metrics for more information.\n :param str default_action: Controls the SignalFx default behavior for processing data from an AWS namespace. If you do specify a filter, use this property to control how SignalFx treats data that doesn\'t match the filter. The available actions are one of `"Include"` or `"Exclude"`.\n :param str filter_action: Controls how SignalFx processes data from a custom AWS namespace. The available actions are one of `"Include"` or `"Exclude"`.\n :param str filter_source: Expression that selects the data that SignalFx should sync for the custom namespace associated with this sync rule. The expression uses the syntax defined for the SignalFlow `filter()` function; it can be any valid SignalFlow filter expression.\n ' pulumi.set(__self__, 'namespace', namespace) if (default_action is not None): pulumi.set(__self__, 'default_action', default_action) if (filter_action is not None): pulumi.set(__self__, 'filter_action', filter_action) if (filter_source is not None): pulumi.set(__self__, 'filter_source', filter_source)<|docstring|>:param str namespace: An AWS custom namespace having custom AWS metrics that you want to sync with SignalFx. See the AWS documentation on publishing metrics for more information. :param str default_action: Controls the SignalFx default behavior for processing data from an AWS namespace. If you do specify a filter, use this property to control how SignalFx treats data that doesn't match the filter. The available actions are one of `"Include"` or `"Exclude"`. :param str filter_action: Controls how SignalFx processes data from a custom AWS namespace. The available actions are one of `"Include"` or `"Exclude"`. :param str filter_source: Expression that selects the data that SignalFx should sync for the custom namespace associated with this sync rule. The expression uses the syntax defined for the SignalFlow `filter()` function; it can be any valid SignalFlow filter expression.<|endoftext|>
06be44dbef1c56e4d7999dca4889f5f622779441a0a7ab21f444f10a02036ab0
@property @pulumi.getter def namespace(self) -> str: '\n An AWS custom namespace having custom AWS metrics that you want to sync with SignalFx. See the AWS documentation on publishing metrics for more information.\n ' return pulumi.get(self, 'namespace')
An AWS custom namespace having custom AWS metrics that you want to sync with SignalFx. See the AWS documentation on publishing metrics for more information.
sdk/python/pulumi_signalfx/aws/outputs.py
namespace
pulumi/pulumi-signalfx
2
python
@property @pulumi.getter def namespace(self) -> str: '\n \n ' return pulumi.get(self, 'namespace')
@property @pulumi.getter def namespace(self) -> str: '\n \n ' return pulumi.get(self, 'namespace')<|docstring|>An AWS custom namespace having custom AWS metrics that you want to sync with SignalFx. See the AWS documentation on publishing metrics for more information.<|endoftext|>
53d8c20776227ce43db617bc59eda02fd579879887c1ff8e67b99778854b64af
@property @pulumi.getter(name='defaultAction') def default_action(self) -> Optional[str]: '\n Controls the SignalFx default behavior for processing data from an AWS namespace. If you do specify a filter, use this property to control how SignalFx treats data that doesn\'t match the filter. The available actions are one of `"Include"` or `"Exclude"`.\n ' return pulumi.get(self, 'default_action')
Controls the SignalFx default behavior for processing data from an AWS namespace. If you do specify a filter, use this property to control how SignalFx treats data that doesn't match the filter. The available actions are one of `"Include"` or `"Exclude"`.
sdk/python/pulumi_signalfx/aws/outputs.py
default_action
pulumi/pulumi-signalfx
2
python
@property @pulumi.getter(name='defaultAction') def default_action(self) -> Optional[str]: '\n Controls the SignalFx default behavior for processing data from an AWS namespace. If you do specify a filter, use this property to control how SignalFx treats data that doesn\'t match the filter. The available actions are one of `"Include"` or `"Exclude"`.\n ' return pulumi.get(self, 'default_action')
@property @pulumi.getter(name='defaultAction') def default_action(self) -> Optional[str]: '\n Controls the SignalFx default behavior for processing data from an AWS namespace. If you do specify a filter, use this property to control how SignalFx treats data that doesn\'t match the filter. The available actions are one of `"Include"` or `"Exclude"`.\n ' return pulumi.get(self, 'default_action')<|docstring|>Controls the SignalFx default behavior for processing data from an AWS namespace. If you do specify a filter, use this property to control how SignalFx treats data that doesn't match the filter. The available actions are one of `"Include"` or `"Exclude"`.<|endoftext|>
74c1c268ff3a2abb288da840122c52b189f69fedbdbe838c3cc028763a76c92c
@property @pulumi.getter(name='filterAction') def filter_action(self) -> Optional[str]: '\n Controls how SignalFx processes data from a custom AWS namespace. The available actions are one of `"Include"` or `"Exclude"`.\n ' return pulumi.get(self, 'filter_action')
Controls how SignalFx processes data from a custom AWS namespace. The available actions are one of `"Include"` or `"Exclude"`.
sdk/python/pulumi_signalfx/aws/outputs.py
filter_action
pulumi/pulumi-signalfx
2
python
@property @pulumi.getter(name='filterAction') def filter_action(self) -> Optional[str]: '\n \n ' return pulumi.get(self, 'filter_action')
@property @pulumi.getter(name='filterAction') def filter_action(self) -> Optional[str]: '\n \n ' return pulumi.get(self, 'filter_action')<|docstring|>Controls how SignalFx processes data from a custom AWS namespace. The available actions are one of `"Include"` or `"Exclude"`.<|endoftext|>
06d30016a12ec6de0b3cbceffd14427bcc06c941cdda0330927d4295df4194c1
@property @pulumi.getter(name='filterSource') def filter_source(self) -> Optional[str]: '\n Expression that selects the data that SignalFx should sync for the custom namespace associated with this sync rule. The expression uses the syntax defined for the SignalFlow `filter()` function; it can be any valid SignalFlow filter expression.\n ' return pulumi.get(self, 'filter_source')
Expression that selects the data that SignalFx should sync for the custom namespace associated with this sync rule. The expression uses the syntax defined for the SignalFlow `filter()` function; it can be any valid SignalFlow filter expression.
sdk/python/pulumi_signalfx/aws/outputs.py
filter_source
pulumi/pulumi-signalfx
2
python
@property @pulumi.getter(name='filterSource') def filter_source(self) -> Optional[str]: '\n \n ' return pulumi.get(self, 'filter_source')
@property @pulumi.getter(name='filterSource') def filter_source(self) -> Optional[str]: '\n \n ' return pulumi.get(self, 'filter_source')<|docstring|>Expression that selects the data that SignalFx should sync for the custom namespace associated with this sync rule. The expression uses the syntax defined for the SignalFlow `filter()` function; it can be any valid SignalFlow filter expression.<|endoftext|>
d285f7e3ea99a00609640404b322005e309abb0b290a5f62b8bb91ff58eb3905
def __init__(__self__, *, namespace: str, default_action: Optional[str]=None, filter_action: Optional[str]=None, filter_source: Optional[str]=None): '\n :param str namespace: An AWS custom namespace having custom AWS metrics that you want to sync with SignalFx. See the AWS documentation on publishing metrics for more information.\n :param str default_action: Controls the SignalFx default behavior for processing data from an AWS namespace. If you do specify a filter, use this property to control how SignalFx treats data that doesn\'t match the filter. The available actions are one of `"Include"` or `"Exclude"`.\n :param str filter_action: Controls how SignalFx processes data from a custom AWS namespace. The available actions are one of `"Include"` or `"Exclude"`.\n :param str filter_source: Expression that selects the data that SignalFx should sync for the custom namespace associated with this sync rule. The expression uses the syntax defined for the SignalFlow `filter()` function; it can be any valid SignalFlow filter expression.\n ' pulumi.set(__self__, 'namespace', namespace) if (default_action is not None): pulumi.set(__self__, 'default_action', default_action) if (filter_action is not None): pulumi.set(__self__, 'filter_action', filter_action) if (filter_source is not None): pulumi.set(__self__, 'filter_source', filter_source)
:param str namespace: An AWS custom namespace having custom AWS metrics that you want to sync with SignalFx. See the AWS documentation on publishing metrics for more information. :param str default_action: Controls the SignalFx default behavior for processing data from an AWS namespace. If you do specify a filter, use this property to control how SignalFx treats data that doesn't match the filter. The available actions are one of `"Include"` or `"Exclude"`. :param str filter_action: Controls how SignalFx processes data from a custom AWS namespace. The available actions are one of `"Include"` or `"Exclude"`. :param str filter_source: Expression that selects the data that SignalFx should sync for the custom namespace associated with this sync rule. The expression uses the syntax defined for the SignalFlow `filter()` function; it can be any valid SignalFlow filter expression.
sdk/python/pulumi_signalfx/aws/outputs.py
__init__
pulumi/pulumi-signalfx
2
python
def __init__(__self__, *, namespace: str, default_action: Optional[str]=None, filter_action: Optional[str]=None, filter_source: Optional[str]=None): '\n :param str namespace: An AWS custom namespace having custom AWS metrics that you want to sync with SignalFx. See the AWS documentation on publishing metrics for more information.\n :param str default_action: Controls the SignalFx default behavior for processing data from an AWS namespace. If you do specify a filter, use this property to control how SignalFx treats data that doesn\'t match the filter. The available actions are one of `"Include"` or `"Exclude"`.\n :param str filter_action: Controls how SignalFx processes data from a custom AWS namespace. The available actions are one of `"Include"` or `"Exclude"`.\n :param str filter_source: Expression that selects the data that SignalFx should sync for the custom namespace associated with this sync rule. The expression uses the syntax defined for the SignalFlow `filter()` function; it can be any valid SignalFlow filter expression.\n ' pulumi.set(__self__, 'namespace', namespace) if (default_action is not None): pulumi.set(__self__, 'default_action', default_action) if (filter_action is not None): pulumi.set(__self__, 'filter_action', filter_action) if (filter_source is not None): pulumi.set(__self__, 'filter_source', filter_source)
def __init__(__self__, *, namespace: str, default_action: Optional[str]=None, filter_action: Optional[str]=None, filter_source: Optional[str]=None): '\n :param str namespace: An AWS custom namespace having custom AWS metrics that you want to sync with SignalFx. See the AWS documentation on publishing metrics for more information.\n :param str default_action: Controls the SignalFx default behavior for processing data from an AWS namespace. If you do specify a filter, use this property to control how SignalFx treats data that doesn\'t match the filter. The available actions are one of `"Include"` or `"Exclude"`.\n :param str filter_action: Controls how SignalFx processes data from a custom AWS namespace. The available actions are one of `"Include"` or `"Exclude"`.\n :param str filter_source: Expression that selects the data that SignalFx should sync for the custom namespace associated with this sync rule. The expression uses the syntax defined for the SignalFlow `filter()` function; it can be any valid SignalFlow filter expression.\n ' pulumi.set(__self__, 'namespace', namespace) if (default_action is not None): pulumi.set(__self__, 'default_action', default_action) if (filter_action is not None): pulumi.set(__self__, 'filter_action', filter_action) if (filter_source is not None): pulumi.set(__self__, 'filter_source', filter_source)<|docstring|>:param str namespace: An AWS custom namespace having custom AWS metrics that you want to sync with SignalFx. See the AWS documentation on publishing metrics for more information. :param str default_action: Controls the SignalFx default behavior for processing data from an AWS namespace. If you do specify a filter, use this property to control how SignalFx treats data that doesn't match the filter. The available actions are one of `"Include"` or `"Exclude"`. :param str filter_action: Controls how SignalFx processes data from a custom AWS namespace. The available actions are one of `"Include"` or `"Exclude"`. :param str filter_source: Expression that selects the data that SignalFx should sync for the custom namespace associated with this sync rule. The expression uses the syntax defined for the SignalFlow `filter()` function; it can be any valid SignalFlow filter expression.<|endoftext|>
06be44dbef1c56e4d7999dca4889f5f622779441a0a7ab21f444f10a02036ab0
@property @pulumi.getter def namespace(self) -> str: '\n An AWS custom namespace having custom AWS metrics that you want to sync with SignalFx. See the AWS documentation on publishing metrics for more information.\n ' return pulumi.get(self, 'namespace')
An AWS custom namespace having custom AWS metrics that you want to sync with SignalFx. See the AWS documentation on publishing metrics for more information.
sdk/python/pulumi_signalfx/aws/outputs.py
namespace
pulumi/pulumi-signalfx
2
python
@property @pulumi.getter def namespace(self) -> str: '\n \n ' return pulumi.get(self, 'namespace')
@property @pulumi.getter def namespace(self) -> str: '\n \n ' return pulumi.get(self, 'namespace')<|docstring|>An AWS custom namespace having custom AWS metrics that you want to sync with SignalFx. See the AWS documentation on publishing metrics for more information.<|endoftext|>
53d8c20776227ce43db617bc59eda02fd579879887c1ff8e67b99778854b64af
@property @pulumi.getter(name='defaultAction') def default_action(self) -> Optional[str]: '\n Controls the SignalFx default behavior for processing data from an AWS namespace. If you do specify a filter, use this property to control how SignalFx treats data that doesn\'t match the filter. The available actions are one of `"Include"` or `"Exclude"`.\n ' return pulumi.get(self, 'default_action')
Controls the SignalFx default behavior for processing data from an AWS namespace. If you do specify a filter, use this property to control how SignalFx treats data that doesn't match the filter. The available actions are one of `"Include"` or `"Exclude"`.
sdk/python/pulumi_signalfx/aws/outputs.py
default_action
pulumi/pulumi-signalfx
2
python
@property @pulumi.getter(name='defaultAction') def default_action(self) -> Optional[str]: '\n Controls the SignalFx default behavior for processing data from an AWS namespace. If you do specify a filter, use this property to control how SignalFx treats data that doesn\'t match the filter. The available actions are one of `"Include"` or `"Exclude"`.\n ' return pulumi.get(self, 'default_action')
@property @pulumi.getter(name='defaultAction') def default_action(self) -> Optional[str]: '\n Controls the SignalFx default behavior for processing data from an AWS namespace. If you do specify a filter, use this property to control how SignalFx treats data that doesn\'t match the filter. The available actions are one of `"Include"` or `"Exclude"`.\n ' return pulumi.get(self, 'default_action')<|docstring|>Controls the SignalFx default behavior for processing data from an AWS namespace. If you do specify a filter, use this property to control how SignalFx treats data that doesn't match the filter. The available actions are one of `"Include"` or `"Exclude"`.<|endoftext|>
74c1c268ff3a2abb288da840122c52b189f69fedbdbe838c3cc028763a76c92c
@property @pulumi.getter(name='filterAction') def filter_action(self) -> Optional[str]: '\n Controls how SignalFx processes data from a custom AWS namespace. The available actions are one of `"Include"` or `"Exclude"`.\n ' return pulumi.get(self, 'filter_action')
Controls how SignalFx processes data from a custom AWS namespace. The available actions are one of `"Include"` or `"Exclude"`.
sdk/python/pulumi_signalfx/aws/outputs.py
filter_action
pulumi/pulumi-signalfx
2
python
@property @pulumi.getter(name='filterAction') def filter_action(self) -> Optional[str]: '\n \n ' return pulumi.get(self, 'filter_action')
@property @pulumi.getter(name='filterAction') def filter_action(self) -> Optional[str]: '\n \n ' return pulumi.get(self, 'filter_action')<|docstring|>Controls how SignalFx processes data from a custom AWS namespace. The available actions are one of `"Include"` or `"Exclude"`.<|endoftext|>
06d30016a12ec6de0b3cbceffd14427bcc06c941cdda0330927d4295df4194c1
@property @pulumi.getter(name='filterSource') def filter_source(self) -> Optional[str]: '\n Expression that selects the data that SignalFx should sync for the custom namespace associated with this sync rule. The expression uses the syntax defined for the SignalFlow `filter()` function; it can be any valid SignalFlow filter expression.\n ' return pulumi.get(self, 'filter_source')
Expression that selects the data that SignalFx should sync for the custom namespace associated with this sync rule. The expression uses the syntax defined for the SignalFlow `filter()` function; it can be any valid SignalFlow filter expression.
sdk/python/pulumi_signalfx/aws/outputs.py
filter_source
pulumi/pulumi-signalfx
2
python
@property @pulumi.getter(name='filterSource') def filter_source(self) -> Optional[str]: '\n \n ' return pulumi.get(self, 'filter_source')
@property @pulumi.getter(name='filterSource') def filter_source(self) -> Optional[str]: '\n \n ' return pulumi.get(self, 'filter_source')<|docstring|>Expression that selects the data that SignalFx should sync for the custom namespace associated with this sync rule. The expression uses the syntax defined for the SignalFlow `filter()` function; it can be any valid SignalFlow filter expression.<|endoftext|>
53a59f8bc17acfab8fa3379cda28dbbdd8a55a551483de58d0e8cd43da3cead0
@abstractmethod def construct_circuit(self, mode, qubits=None, circuit=None): "Construct the qft circuit.\n\n Args:\n mode (str): 'vector' or 'circuit'\n qubits (QuantumRegister or qubits): register or qubits to build the qft circuit on.\n circuit (QuantumCircuit): circuit for construction.\n\n Returns:\n The qft circuit.\n " raise NotImplementedError()
Construct the qft circuit. Args: mode (str): 'vector' or 'circuit' qubits (QuantumRegister or qubits): register or qubits to build the qft circuit on. circuit (QuantumCircuit): circuit for construction. Returns: The qft circuit.
qiskit/aqua/components/qfts/qft.py
construct_circuit
dpad/qiskit-aqua
0
python
@abstractmethod def construct_circuit(self, mode, qubits=None, circuit=None): "Construct the qft circuit.\n\n Args:\n mode (str): 'vector' or 'circuit'\n qubits (QuantumRegister or qubits): register or qubits to build the qft circuit on.\n circuit (QuantumCircuit): circuit for construction.\n\n Returns:\n The qft circuit.\n " raise NotImplementedError()
@abstractmethod def construct_circuit(self, mode, qubits=None, circuit=None): "Construct the qft circuit.\n\n Args:\n mode (str): 'vector' or 'circuit'\n qubits (QuantumRegister or qubits): register or qubits to build the qft circuit on.\n circuit (QuantumCircuit): circuit for construction.\n\n Returns:\n The qft circuit.\n " raise NotImplementedError()<|docstring|>Construct the qft circuit. Args: mode (str): 'vector' or 'circuit' qubits (QuantumRegister or qubits): register or qubits to build the qft circuit on. circuit (QuantumCircuit): circuit for construction. Returns: The qft circuit.<|endoftext|>
0363bffdeac2734b8288787f3dcd435665475132e8fd92b0698bc13fd7162b9f
def reporthook(count, block_size, total_size): '\n Function that displays the status and speed of the download\n\n ' global start_time if (count == 0): start_time = time.time() return duration = (time.time() - start_time) progress_size = int((count * block_size)) speed = int((progress_size / (1024 * duration))) percent = int((((count * block_size) * 100) / total_size)) sys.stdout.write(('\r...%d%%, %d MB, %d KB/s, %d seconds passed' % (percent, (progress_size / (1024 * 1024)), speed, duration))) sys.stdout.flush()
Function that displays the status and speed of the download
codes/util/input_output.py
reporthook
jagar2/Revealing-Ferroelectric-Switching-Character-Using-Deep-Recurrent-Neural-Networks
20
python
def reporthook(count, block_size, total_size): '\n \n\n ' global start_time if (count == 0): start_time = time.time() return duration = (time.time() - start_time) progress_size = int((count * block_size)) speed = int((progress_size / (1024 * duration))) percent = int((((count * block_size) * 100) / total_size)) sys.stdout.write(('\r...%d%%, %d MB, %d KB/s, %d seconds passed' % (percent, (progress_size / (1024 * 1024)), speed, duration))) sys.stdout.flush()
def reporthook(count, block_size, total_size): '\n \n\n ' global start_time if (count == 0): start_time = time.time() return duration = (time.time() - start_time) progress_size = int((count * block_size)) speed = int((progress_size / (1024 * duration))) percent = int((((count * block_size) * 100) / total_size)) sys.stdout.write(('\r...%d%%, %d MB, %d KB/s, %d seconds passed' % (percent, (progress_size / (1024 * 1024)), speed, duration))) sys.stdout.flush()<|docstring|>Function that displays the status and speed of the download<|endoftext|>
ff1b6cd2b315906cd6816f8a584fa21960a81b6673d0b3bb42c42b46bbdc9657
def download_file(url, filename): '\n Function that downloads the data file from a URL\n\n Parameters\n ----------\n\n url : string\n url where the file to download is located\n filename : string\n location where to save the file\n reporthook : function\n callback to display the download progress\n\n ' if (not os.path.isfile(filename)): urllib.request.urlretrieve(url, filename, reporthook)
Function that downloads the data file from a URL Parameters ---------- url : string url where the file to download is located filename : string location where to save the file reporthook : function callback to display the download progress
codes/util/input_output.py
download_file
jagar2/Revealing-Ferroelectric-Switching-Character-Using-Deep-Recurrent-Neural-Networks
20
python
def download_file(url, filename): '\n Function that downloads the data file from a URL\n\n Parameters\n ----------\n\n url : string\n url where the file to download is located\n filename : string\n location where to save the file\n reporthook : function\n callback to display the download progress\n\n ' if (not os.path.isfile(filename)): urllib.request.urlretrieve(url, filename, reporthook)
def download_file(url, filename): '\n Function that downloads the data file from a URL\n\n Parameters\n ----------\n\n url : string\n url where the file to download is located\n filename : string\n location where to save the file\n reporthook : function\n callback to display the download progress\n\n ' if (not os.path.isfile(filename)): urllib.request.urlretrieve(url, filename, reporthook)<|docstring|>Function that downloads the data file from a URL Parameters ---------- url : string url where the file to download is located filename : string location where to save the file reporthook : function callback to display the download progress<|endoftext|>
34bacfa98f2311f2bd0b840f1515eae85f30d6b6e5030871fe5f1b8df48c975f
def compress_folder(base_name, format, root_dir=None): '\n Function that zips a folder can save zip and tar\n\n Parameters\n ----------\n\n base_name : string\n base name of the zip file\n format : string\n sets the format of the zip file. Can either be zip or tar\n root_dir : string (optional)\n sets the root directory to save the file\n\n ' shutil.make_archive(base_name, format, root_dir)
Function that zips a folder can save zip and tar Parameters ---------- base_name : string base name of the zip file format : string sets the format of the zip file. Can either be zip or tar root_dir : string (optional) sets the root directory to save the file
codes/util/input_output.py
compress_folder
jagar2/Revealing-Ferroelectric-Switching-Character-Using-Deep-Recurrent-Neural-Networks
20
python
def compress_folder(base_name, format, root_dir=None): '\n Function that zips a folder can save zip and tar\n\n Parameters\n ----------\n\n base_name : string\n base name of the zip file\n format : string\n sets the format of the zip file. Can either be zip or tar\n root_dir : string (optional)\n sets the root directory to save the file\n\n ' shutil.make_archive(base_name, format, root_dir)
def compress_folder(base_name, format, root_dir=None): '\n Function that zips a folder can save zip and tar\n\n Parameters\n ----------\n\n base_name : string\n base name of the zip file\n format : string\n sets the format of the zip file. Can either be zip or tar\n root_dir : string (optional)\n sets the root directory to save the file\n\n ' shutil.make_archive(base_name, format, root_dir)<|docstring|>Function that zips a folder can save zip and tar Parameters ---------- base_name : string base name of the zip file format : string sets the format of the zip file. Can either be zip or tar root_dir : string (optional) sets the root directory to save the file<|endoftext|>
599f37ce817e6f40f03afefccd2517b53cca050b32d8084f16a9cc9c89a0f751
def unzip(filename, path): '\n Function that unzips the files\n\n Parameters\n ----------\n\n filename : string\n base name of the zip file\n path : string\n path where the zip file will be saved\n\n ' zip_ref = zipfile.ZipFile(('./' + filename), 'r') zip_ref.extractall(path) zip_ref.close()
Function that unzips the files Parameters ---------- filename : string base name of the zip file path : string path where the zip file will be saved
codes/util/input_output.py
unzip
jagar2/Revealing-Ferroelectric-Switching-Character-Using-Deep-Recurrent-Neural-Networks
20
python
def unzip(filename, path): '\n Function that unzips the files\n\n Parameters\n ----------\n\n filename : string\n base name of the zip file\n path : string\n path where the zip file will be saved\n\n ' zip_ref = zipfile.ZipFile(('./' + filename), 'r') zip_ref.extractall(path) zip_ref.close()
def unzip(filename, path): '\n Function that unzips the files\n\n Parameters\n ----------\n\n filename : string\n base name of the zip file\n path : string\n path where the zip file will be saved\n\n ' zip_ref = zipfile.ZipFile(('./' + filename), 'r') zip_ref.extractall(path) zip_ref.close()<|docstring|>Function that unzips the files Parameters ---------- filename : string base name of the zip file path : string path where the zip file will be saved<|endoftext|>
8b8b8347f89a24e63ee8ac44ca3539f091a33f6dba881ba2164cb396ff170d3e
def get_size(start_path='.'): '\n\n Function that computes the size of a folder\n\n Parameters\n ----------\n\n start_path : string\n Path to compute the size of\n\n Return\n ----------\n\n total_size : float\n Size of the folder\n ' total_size = 0 for (dirpath, dirnames, filenames) in os.walk(start_path): for f in filenames: fp = os.path.join(dirpath, f) total_size += os.path.getsize(fp) return total_size
Function that computes the size of a folder Parameters ---------- start_path : string Path to compute the size of Return ---------- total_size : float Size of the folder
codes/util/input_output.py
get_size
jagar2/Revealing-Ferroelectric-Switching-Character-Using-Deep-Recurrent-Neural-Networks
20
python
def get_size(start_path='.'): '\n\n Function that computes the size of a folder\n\n Parameters\n ----------\n\n start_path : string\n Path to compute the size of\n\n Return\n ----------\n\n total_size : float\n Size of the folder\n ' total_size = 0 for (dirpath, dirnames, filenames) in os.walk(start_path): for f in filenames: fp = os.path.join(dirpath, f) total_size += os.path.getsize(fp) return total_size
def get_size(start_path='.'): '\n\n Function that computes the size of a folder\n\n Parameters\n ----------\n\n start_path : string\n Path to compute the size of\n\n Return\n ----------\n\n total_size : float\n Size of the folder\n ' total_size = 0 for (dirpath, dirnames, filenames) in os.walk(start_path): for f in filenames: fp = os.path.join(dirpath, f) total_size += os.path.getsize(fp) return total_size<|docstring|>Function that computes the size of a folder Parameters ---------- start_path : string Path to compute the size of Return ---------- total_size : float Size of the folder<|endoftext|>
6b3e06b0191fb9def6954ee3a31013c0c82f795dd2dcda4c47457e2c6e43bea4
def download_and_unzip(filename, url, save_path, download_data): '\n\n Function that computes the size of a folder\n\n Parameters\n ----------\n\n filename : string\n filename to save the zip file\n url : string\n url where the file is located\n save_path : string\n place where the data is saved\n download_data : bool\n sets if to download the data\n\n ' if (np.int((get_size(save_path) / 1000000000.0)) < 1): if (np.int((get_size(save_path) / 1000000000.0)) > 1): print('Using files already downloaded') elif download_data: print('downloading data') download_file(url, filename) elif os.path.isfile(filename): print('Using zip file already available') else: pass if os.path.isfile(filename): print(f'extracting {filename} to {save_path}') unzip(filename, save_path)
Function that computes the size of a folder Parameters ---------- filename : string filename to save the zip file url : string url where the file is located save_path : string place where the data is saved download_data : bool sets if to download the data
codes/util/input_output.py
download_and_unzip
jagar2/Revealing-Ferroelectric-Switching-Character-Using-Deep-Recurrent-Neural-Networks
20
python
def download_and_unzip(filename, url, save_path, download_data): '\n\n Function that computes the size of a folder\n\n Parameters\n ----------\n\n filename : string\n filename to save the zip file\n url : string\n url where the file is located\n save_path : string\n place where the data is saved\n download_data : bool\n sets if to download the data\n\n ' if (np.int((get_size(save_path) / 1000000000.0)) < 1): if (np.int((get_size(save_path) / 1000000000.0)) > 1): print('Using files already downloaded') elif download_data: print('downloading data') download_file(url, filename) elif os.path.isfile(filename): print('Using zip file already available') else: pass if os.path.isfile(filename): print(f'extracting {filename} to {save_path}') unzip(filename, save_path)
def download_and_unzip(filename, url, save_path, download_data): '\n\n Function that computes the size of a folder\n\n Parameters\n ----------\n\n filename : string\n filename to save the zip file\n url : string\n url where the file is located\n save_path : string\n place where the data is saved\n download_data : bool\n sets if to download the data\n\n ' if (np.int((get_size(save_path) / 1000000000.0)) < 1): if (np.int((get_size(save_path) / 1000000000.0)) > 1): print('Using files already downloaded') elif download_data: print('downloading data') download_file(url, filename) elif os.path.isfile(filename): print('Using zip file already available') else: pass if os.path.isfile(filename): print(f'extracting {filename} to {save_path}') unzip(filename, save_path)<|docstring|>Function that computes the size of a folder Parameters ---------- filename : string filename to save the zip file url : string url where the file is located save_path : string place where the data is saved download_data : bool sets if to download the data<|endoftext|>
ab3394018c574df266e9ed3a584d8d3b360bb3a19a580ecef3fb1a06f81b36a7
def __dump_operator(operator: Operator, index: int): '\n Prints operator in human-readable format.\n :param operator: The operator to dump.\n :param index: The index of the operator.\n ' if (operator.type == OperatorType.INTRINSIC): readable_operator_name = operator.operand.name readable_operator = f'${readable_operator_name}' else: readable_operator_type = operator.type.name readable_operator = f'@{readable_operator_type}, {operator.operand}' print(f'index {index}, {readable_operator}')
Prints operator in human-readable format. :param operator: The operator to dump. :param index: The index of the operator.
src/gofra/systems/dump.py
__dump_operator
GofraLang/core
5
python
def __dump_operator(operator: Operator, index: int): '\n Prints operator in human-readable format.\n :param operator: The operator to dump.\n :param index: The index of the operator.\n ' if (operator.type == OperatorType.INTRINSIC): readable_operator_name = operator.operand.name readable_operator = f'${readable_operator_name}' else: readable_operator_type = operator.type.name readable_operator = f'@{readable_operator_type}, {operator.operand}' print(f'index {index}, {readable_operator}')
def __dump_operator(operator: Operator, index: int): '\n Prints operator in human-readable format.\n :param operator: The operator to dump.\n :param index: The index of the operator.\n ' if (operator.type == OperatorType.INTRINSIC): readable_operator_name = operator.operand.name readable_operator = f'${readable_operator_name}' else: readable_operator_type = operator.type.name readable_operator = f'@{readable_operator_type}, {operator.operand}' print(f'index {index}, {readable_operator}')<|docstring|>Prints operator in human-readable format. :param operator: The operator to dump. :param index: The index of the operator.<|endoftext|>
be0122d4f92b135fc90c10851792f9836fefc50bf0cfc31c4052813f91a5f7f6
def dump(operators: List[Operator]): '\n Prints all operators from given list in human-readable format.\n :param operators: List of operators.\n ' assert (len(operators) > 0), 'List of operators should be not empty!' for (index, operator) in enumerate(operators): __dump_operator(operator, index)
Prints all operators from given list in human-readable format. :param operators: List of operators.
src/gofra/systems/dump.py
dump
GofraLang/core
5
python
def dump(operators: List[Operator]): '\n Prints all operators from given list in human-readable format.\n :param operators: List of operators.\n ' assert (len(operators) > 0), 'List of operators should be not empty!' for (index, operator) in enumerate(operators): __dump_operator(operator, index)
def dump(operators: List[Operator]): '\n Prints all operators from given list in human-readable format.\n :param operators: List of operators.\n ' assert (len(operators) > 0), 'List of operators should be not empty!' for (index, operator) in enumerate(operators): __dump_operator(operator, index)<|docstring|>Prints all operators from given list in human-readable format. :param operators: List of operators.<|endoftext|>
30650166082cb41096727c6981cb7e84d0ed9c077321cfec7eca208825297b50
def connect_to_database(self, module_name: str=None, database: str=None, username: str=None, password: str=None, host: str=None, port: int=None, charset: str=None, config_file: str='db.cfg', autocommit: bool=False): 'Connect to database using DB API 2.0 module.\n\n :param module_name: database module to use\n :param database: name of the database\n :param username: of the user accessing the database\n :param password: of the user accessing the database\n :param host: SQL server address\n :param port: SQL server port\n :param charset: for example, "utf-8", defaults to None\n :param config_file: location of configuration file, defaults to "db.cfg"\n :param autocommit: set autocommit value for connect (only with pymssql atm)\n\n Example:\n\n .. code-block:: robotframework\n\n Connect To Database pymysql database username password host port\n Connect To Database ${CURDIR}${/}resources${/}dbconfig.cfg\n\n ' self.config.parse_arguments(module_name, database, username, password, host, port, charset, config_file) if (self.config.module_name in ('excel', 'excelrw')): self.db_api_module_name = 'pyodbc' dbmodule = importlib.import_module('pyodbc') else: self.db_api_module_name = self.config.module_name dbmodule = importlib.import_module(self.config.module_name) if (module_name in ['MySQLdb', 'pymysql']): self.config.set_default_port(3306) self.logger.info(self.config.get_connection_parameters_as_string()) self._dbconnection = dbmodule.connect(db=self.config.get('database'), user=self.config.get('username'), passwd=self.config.get('password'), host=self.config.get('host'), port=self.config.get('port'), charset=self.config.get('charset')) elif (module_name == 'psycopg2'): self.config.set_default_port(5432) self.logger.info(self.config.get_connection_parameters_as_string()) self._dbconnection = dbmodule.connect(database=self.config.get('database'), user=self.config.get('username'), password=self.config.get('password'), host=self.config.get('host'), port=self.config.get('port')) elif (module_name in ('pyodbc', 'pypyodbc')): self.config.set_default_port(1433) self.config.set_val('connect_string', ('DRIVER={SQL Server};SERVER=%s,%s;DATABASE=%s;UID=%s;PWD=%s' % (self.config.get('host'), self.config.get('port'), self.config.get('database'), self.config.get('username'), self.config.get('password')))) self.logger.info(self.config.get_connection_parameters_as_string()) self._dbconnection = dbmodule.connect(self.config.get('connect_string')) elif (module_name == 'excel'): self.config.set_val('connect_string', ('DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=%s;ReadOnly=1;Extended Properties="Excel 8.0;HDR=YES";)' % self.config.get('database'))) self.logger.info(self.config.get_connection_parameters_as_string()) self._dbconnection = dbmodule.connect(self.config.get('connect_string'), autocommit=True) elif (module_name == 'excelrw'): self.config.set_val('connect_string', ('DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=%s;ReadOnly=0;Extended Properties="Excel 8.0;HDR=YES";)' % self.config.get('database'))) self.logger.info(self.config.get_connection_parameters_as_string()) self._dbconnection = dbmodule.connect(self.config.get('connect_string'), autocommit=True) elif (module_name in ('ibm_db', 'ibm_db_dbi')): self.config.set_default_port(50000) self.config.set_val('connect_string', ('DATABASE=%s;HOSTNAME=%s;PORT=%s;PROTOCOL=TCPIP;UID=%s;PWD=%s;' % (self.config.get('database'), self.config.get('host'), self.config.get('port'), self.config.get('username'), self.config.get('password')))) self.logger.info(self.config.get_connection_parameters_as_string()) self._dbconnection = dbmodule.connect(self.config.get('connect_string'), '', '') elif (module_name == 'cx_Oracle'): self.config.set_default_port(1521) oracle_dsn = dbmodule.makedsn(host=self.config.get('host'), port=self.config.get('port'), service_name=self.config.get('database')) self.config.set_val('oracle_dsn', oracle_dsn) self.logger.info(self.config.get_connection_parameters_as_string()) self._dbconnection = dbmodule.connect(user=self.config.get('username'), password=self.config.get('password'), dsn=self.config.get('oracle_dsn')) elif (module_name == 'teradata'): self.config.set_default_port(1025) teradata_udaExec = dbmodule.UdaExec(appName='RobotFramework', version='1.0', logConsole=False) self.logger.info(self.config.get_connection_parameters_as_string()) self._dbconnection = teradata_udaExec.connect(method='odbc', system=self.config.get('host'), database=self.config.get('database'), username=self.config.get('username'), password=self.config.get('password'), host=self.config.get('host'), port=self.config.get('port')) elif (module_name == 'pymssql'): self.config.set_default_port(1433) self.logger.info(self.config.get_connection_parameters_as_string()) self._dbconnection = dbmodule.connect(server=self.config.get('host'), user=self.config.get('username'), password=self.config.get('password'), database=self.config.get('database'), port=self.config.get('port'), host=self.config.get('host', '.'), autocommit=autocommit) else: conf = self.config.all_but_empty() self.logger.info(self.config.get_connection_parameters_as_string(conf)) self._dbconnection = dbmodule.connect(**conf)
Connect to database using DB API 2.0 module. :param module_name: database module to use :param database: name of the database :param username: of the user accessing the database :param password: of the user accessing the database :param host: SQL server address :param port: SQL server port :param charset: for example, "utf-8", defaults to None :param config_file: location of configuration file, defaults to "db.cfg" :param autocommit: set autocommit value for connect (only with pymssql atm) Example: .. code-block:: robotframework Connect To Database pymysql database username password host port Connect To Database ${CURDIR}${/}resources${/}dbconfig.cfg
packages/main/src/RPA/Database.py
connect_to_database
rooky-c3bo/rpaframework
518
python
def connect_to_database(self, module_name: str=None, database: str=None, username: str=None, password: str=None, host: str=None, port: int=None, charset: str=None, config_file: str='db.cfg', autocommit: bool=False): 'Connect to database using DB API 2.0 module.\n\n :param module_name: database module to use\n :param database: name of the database\n :param username: of the user accessing the database\n :param password: of the user accessing the database\n :param host: SQL server address\n :param port: SQL server port\n :param charset: for example, "utf-8", defaults to None\n :param config_file: location of configuration file, defaults to "db.cfg"\n :param autocommit: set autocommit value for connect (only with pymssql atm)\n\n Example:\n\n .. code-block:: robotframework\n\n Connect To Database pymysql database username password host port\n Connect To Database ${CURDIR}${/}resources${/}dbconfig.cfg\n\n ' self.config.parse_arguments(module_name, database, username, password, host, port, charset, config_file) if (self.config.module_name in ('excel', 'excelrw')): self.db_api_module_name = 'pyodbc' dbmodule = importlib.import_module('pyodbc') else: self.db_api_module_name = self.config.module_name dbmodule = importlib.import_module(self.config.module_name) if (module_name in ['MySQLdb', 'pymysql']): self.config.set_default_port(3306) self.logger.info(self.config.get_connection_parameters_as_string()) self._dbconnection = dbmodule.connect(db=self.config.get('database'), user=self.config.get('username'), passwd=self.config.get('password'), host=self.config.get('host'), port=self.config.get('port'), charset=self.config.get('charset')) elif (module_name == 'psycopg2'): self.config.set_default_port(5432) self.logger.info(self.config.get_connection_parameters_as_string()) self._dbconnection = dbmodule.connect(database=self.config.get('database'), user=self.config.get('username'), password=self.config.get('password'), host=self.config.get('host'), port=self.config.get('port')) elif (module_name in ('pyodbc', 'pypyodbc')): self.config.set_default_port(1433) self.config.set_val('connect_string', ('DRIVER={SQL Server};SERVER=%s,%s;DATABASE=%s;UID=%s;PWD=%s' % (self.config.get('host'), self.config.get('port'), self.config.get('database'), self.config.get('username'), self.config.get('password')))) self.logger.info(self.config.get_connection_parameters_as_string()) self._dbconnection = dbmodule.connect(self.config.get('connect_string')) elif (module_name == 'excel'): self.config.set_val('connect_string', ('DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=%s;ReadOnly=1;Extended Properties="Excel 8.0;HDR=YES";)' % self.config.get('database'))) self.logger.info(self.config.get_connection_parameters_as_string()) self._dbconnection = dbmodule.connect(self.config.get('connect_string'), autocommit=True) elif (module_name == 'excelrw'): self.config.set_val('connect_string', ('DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=%s;ReadOnly=0;Extended Properties="Excel 8.0;HDR=YES";)' % self.config.get('database'))) self.logger.info(self.config.get_connection_parameters_as_string()) self._dbconnection = dbmodule.connect(self.config.get('connect_string'), autocommit=True) elif (module_name in ('ibm_db', 'ibm_db_dbi')): self.config.set_default_port(50000) self.config.set_val('connect_string', ('DATABASE=%s;HOSTNAME=%s;PORT=%s;PROTOCOL=TCPIP;UID=%s;PWD=%s;' % (self.config.get('database'), self.config.get('host'), self.config.get('port'), self.config.get('username'), self.config.get('password')))) self.logger.info(self.config.get_connection_parameters_as_string()) self._dbconnection = dbmodule.connect(self.config.get('connect_string'), , ) elif (module_name == 'cx_Oracle'): self.config.set_default_port(1521) oracle_dsn = dbmodule.makedsn(host=self.config.get('host'), port=self.config.get('port'), service_name=self.config.get('database')) self.config.set_val('oracle_dsn', oracle_dsn) self.logger.info(self.config.get_connection_parameters_as_string()) self._dbconnection = dbmodule.connect(user=self.config.get('username'), password=self.config.get('password'), dsn=self.config.get('oracle_dsn')) elif (module_name == 'teradata'): self.config.set_default_port(1025) teradata_udaExec = dbmodule.UdaExec(appName='RobotFramework', version='1.0', logConsole=False) self.logger.info(self.config.get_connection_parameters_as_string()) self._dbconnection = teradata_udaExec.connect(method='odbc', system=self.config.get('host'), database=self.config.get('database'), username=self.config.get('username'), password=self.config.get('password'), host=self.config.get('host'), port=self.config.get('port')) elif (module_name == 'pymssql'): self.config.set_default_port(1433) self.logger.info(self.config.get_connection_parameters_as_string()) self._dbconnection = dbmodule.connect(server=self.config.get('host'), user=self.config.get('username'), password=self.config.get('password'), database=self.config.get('database'), port=self.config.get('port'), host=self.config.get('host', '.'), autocommit=autocommit) else: conf = self.config.all_but_empty() self.logger.info(self.config.get_connection_parameters_as_string(conf)) self._dbconnection = dbmodule.connect(**conf)
def connect_to_database(self, module_name: str=None, database: str=None, username: str=None, password: str=None, host: str=None, port: int=None, charset: str=None, config_file: str='db.cfg', autocommit: bool=False): 'Connect to database using DB API 2.0 module.\n\n :param module_name: database module to use\n :param database: name of the database\n :param username: of the user accessing the database\n :param password: of the user accessing the database\n :param host: SQL server address\n :param port: SQL server port\n :param charset: for example, "utf-8", defaults to None\n :param config_file: location of configuration file, defaults to "db.cfg"\n :param autocommit: set autocommit value for connect (only with pymssql atm)\n\n Example:\n\n .. code-block:: robotframework\n\n Connect To Database pymysql database username password host port\n Connect To Database ${CURDIR}${/}resources${/}dbconfig.cfg\n\n ' self.config.parse_arguments(module_name, database, username, password, host, port, charset, config_file) if (self.config.module_name in ('excel', 'excelrw')): self.db_api_module_name = 'pyodbc' dbmodule = importlib.import_module('pyodbc') else: self.db_api_module_name = self.config.module_name dbmodule = importlib.import_module(self.config.module_name) if (module_name in ['MySQLdb', 'pymysql']): self.config.set_default_port(3306) self.logger.info(self.config.get_connection_parameters_as_string()) self._dbconnection = dbmodule.connect(db=self.config.get('database'), user=self.config.get('username'), passwd=self.config.get('password'), host=self.config.get('host'), port=self.config.get('port'), charset=self.config.get('charset')) elif (module_name == 'psycopg2'): self.config.set_default_port(5432) self.logger.info(self.config.get_connection_parameters_as_string()) self._dbconnection = dbmodule.connect(database=self.config.get('database'), user=self.config.get('username'), password=self.config.get('password'), host=self.config.get('host'), port=self.config.get('port')) elif (module_name in ('pyodbc', 'pypyodbc')): self.config.set_default_port(1433) self.config.set_val('connect_string', ('DRIVER={SQL Server};SERVER=%s,%s;DATABASE=%s;UID=%s;PWD=%s' % (self.config.get('host'), self.config.get('port'), self.config.get('database'), self.config.get('username'), self.config.get('password')))) self.logger.info(self.config.get_connection_parameters_as_string()) self._dbconnection = dbmodule.connect(self.config.get('connect_string')) elif (module_name == 'excel'): self.config.set_val('connect_string', ('DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=%s;ReadOnly=1;Extended Properties="Excel 8.0;HDR=YES";)' % self.config.get('database'))) self.logger.info(self.config.get_connection_parameters_as_string()) self._dbconnection = dbmodule.connect(self.config.get('connect_string'), autocommit=True) elif (module_name == 'excelrw'): self.config.set_val('connect_string', ('DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=%s;ReadOnly=0;Extended Properties="Excel 8.0;HDR=YES";)' % self.config.get('database'))) self.logger.info(self.config.get_connection_parameters_as_string()) self._dbconnection = dbmodule.connect(self.config.get('connect_string'), autocommit=True) elif (module_name in ('ibm_db', 'ibm_db_dbi')): self.config.set_default_port(50000) self.config.set_val('connect_string', ('DATABASE=%s;HOSTNAME=%s;PORT=%s;PROTOCOL=TCPIP;UID=%s;PWD=%s;' % (self.config.get('database'), self.config.get('host'), self.config.get('port'), self.config.get('username'), self.config.get('password')))) self.logger.info(self.config.get_connection_parameters_as_string()) self._dbconnection = dbmodule.connect(self.config.get('connect_string'), , ) elif (module_name == 'cx_Oracle'): self.config.set_default_port(1521) oracle_dsn = dbmodule.makedsn(host=self.config.get('host'), port=self.config.get('port'), service_name=self.config.get('database')) self.config.set_val('oracle_dsn', oracle_dsn) self.logger.info(self.config.get_connection_parameters_as_string()) self._dbconnection = dbmodule.connect(user=self.config.get('username'), password=self.config.get('password'), dsn=self.config.get('oracle_dsn')) elif (module_name == 'teradata'): self.config.set_default_port(1025) teradata_udaExec = dbmodule.UdaExec(appName='RobotFramework', version='1.0', logConsole=False) self.logger.info(self.config.get_connection_parameters_as_string()) self._dbconnection = teradata_udaExec.connect(method='odbc', system=self.config.get('host'), database=self.config.get('database'), username=self.config.get('username'), password=self.config.get('password'), host=self.config.get('host'), port=self.config.get('port')) elif (module_name == 'pymssql'): self.config.set_default_port(1433) self.logger.info(self.config.get_connection_parameters_as_string()) self._dbconnection = dbmodule.connect(server=self.config.get('host'), user=self.config.get('username'), password=self.config.get('password'), database=self.config.get('database'), port=self.config.get('port'), host=self.config.get('host', '.'), autocommit=autocommit) else: conf = self.config.all_but_empty() self.logger.info(self.config.get_connection_parameters_as_string(conf)) self._dbconnection = dbmodule.connect(**conf)<|docstring|>Connect to database using DB API 2.0 module. :param module_name: database module to use :param database: name of the database :param username: of the user accessing the database :param password: of the user accessing the database :param host: SQL server address :param port: SQL server port :param charset: for example, "utf-8", defaults to None :param config_file: location of configuration file, defaults to "db.cfg" :param autocommit: set autocommit value for connect (only with pymssql atm) Example: .. code-block:: robotframework Connect To Database pymysql database username password host port Connect To Database ${CURDIR}${/}resources${/}dbconfig.cfg<|endoftext|>
8e4dbecec712c9cf443fcbb2755fc8723e96fe79f4285e653947eb02ecfc919e
def call_stored_procedure(self, name, params=None, sanstran=False): 'Call stored procedure with name and params.\n\n :param name: procedure name\n :param params: parameters for the procedure as a list, defaults to None\n :param sanstran: run command without an explicit transaction commit or rollback,\n defaults to False\n\n Example:\n\n .. code-block:: robotframework\n\n @{params} Create List FirstParam SecondParam ThirdParam\n @{results} Call Stored Procedure mystpr ${params}\n\n ' params = (params or []) cur = None try: if (self.db_api_module_name == 'cx_Oracle'): cur = self._dbconnection.cursor() else: cur = self._dbconnection.cursor(as_dict=False) PY3K = (sys.version_info >= (3, 0)) if (not PY3K): name = name.encode('ascii', 'ignore') cur.callproc(name, params) cur.nextset() value = [] for row in cur: value.append(row) if (not sanstran): self._dbconnection.commit() return value finally: if cur: if (not sanstran): self._dbconnection.rollback()
Call stored procedure with name and params. :param name: procedure name :param params: parameters for the procedure as a list, defaults to None :param sanstran: run command without an explicit transaction commit or rollback, defaults to False Example: .. code-block:: robotframework @{params} Create List FirstParam SecondParam ThirdParam @{results} Call Stored Procedure mystpr ${params}
packages/main/src/RPA/Database.py
call_stored_procedure
rooky-c3bo/rpaframework
518
python
def call_stored_procedure(self, name, params=None, sanstran=False): 'Call stored procedure with name and params.\n\n :param name: procedure name\n :param params: parameters for the procedure as a list, defaults to None\n :param sanstran: run command without an explicit transaction commit or rollback,\n defaults to False\n\n Example:\n\n .. code-block:: robotframework\n\n @{params} Create List FirstParam SecondParam ThirdParam\n @{results} Call Stored Procedure mystpr ${params}\n\n ' params = (params or []) cur = None try: if (self.db_api_module_name == 'cx_Oracle'): cur = self._dbconnection.cursor() else: cur = self._dbconnection.cursor(as_dict=False) PY3K = (sys.version_info >= (3, 0)) if (not PY3K): name = name.encode('ascii', 'ignore') cur.callproc(name, params) cur.nextset() value = [] for row in cur: value.append(row) if (not sanstran): self._dbconnection.commit() return value finally: if cur: if (not sanstran): self._dbconnection.rollback()
def call_stored_procedure(self, name, params=None, sanstran=False): 'Call stored procedure with name and params.\n\n :param name: procedure name\n :param params: parameters for the procedure as a list, defaults to None\n :param sanstran: run command without an explicit transaction commit or rollback,\n defaults to False\n\n Example:\n\n .. code-block:: robotframework\n\n @{params} Create List FirstParam SecondParam ThirdParam\n @{results} Call Stored Procedure mystpr ${params}\n\n ' params = (params or []) cur = None try: if (self.db_api_module_name == 'cx_Oracle'): cur = self._dbconnection.cursor() else: cur = self._dbconnection.cursor(as_dict=False) PY3K = (sys.version_info >= (3, 0)) if (not PY3K): name = name.encode('ascii', 'ignore') cur.callproc(name, params) cur.nextset() value = [] for row in cur: value.append(row) if (not sanstran): self._dbconnection.commit() return value finally: if cur: if (not sanstran): self._dbconnection.rollback()<|docstring|>Call stored procedure with name and params. :param name: procedure name :param params: parameters for the procedure as a list, defaults to None :param sanstran: run command without an explicit transaction commit or rollback, defaults to False Example: .. code-block:: robotframework @{params} Create List FirstParam SecondParam ThirdParam @{results} Call Stored Procedure mystpr ${params}<|endoftext|>
53f5083045e7a346d78cbc4ad1ee22a3bf24a344fbcbcb45215ab2fb7c7c1305
def description(self, table): 'Get description of the SQL table\n\n :param table: name of the SQL table\n\n Example:\n\n .. code-block:: robotframework\n\n Connect To Database pymysql mydb user pass 127.0.0.1\n ${db_description} Description mytable\n\n ' try: result = self.query(('DESCRIBE %s' % table), as_table=True) except Exception as e: raise AssertionError(("Operation not supported for '%s' type database" % self.db_api_module_name)) from e return result.to_list()
Get description of the SQL table :param table: name of the SQL table Example: .. code-block:: robotframework Connect To Database pymysql mydb user pass 127.0.0.1 ${db_description} Description mytable
packages/main/src/RPA/Database.py
description
rooky-c3bo/rpaframework
518
python
def description(self, table): 'Get description of the SQL table\n\n :param table: name of the SQL table\n\n Example:\n\n .. code-block:: robotframework\n\n Connect To Database pymysql mydb user pass 127.0.0.1\n ${db_description} Description mytable\n\n ' try: result = self.query(('DESCRIBE %s' % table), as_table=True) except Exception as e: raise AssertionError(("Operation not supported for '%s' type database" % self.db_api_module_name)) from e return result.to_list()
def description(self, table): 'Get description of the SQL table\n\n :param table: name of the SQL table\n\n Example:\n\n .. code-block:: robotframework\n\n Connect To Database pymysql mydb user pass 127.0.0.1\n ${db_description} Description mytable\n\n ' try: result = self.query(('DESCRIBE %s' % table), as_table=True) except Exception as e: raise AssertionError(("Operation not supported for '%s' type database" % self.db_api_module_name)) from e return result.to_list()<|docstring|>Get description of the SQL table :param table: name of the SQL table Example: .. code-block:: robotframework Connect To Database pymysql mydb user pass 127.0.0.1 ${db_description} Description mytable<|endoftext|>
e24fdd5359b8656c1443fdb0c45b09c536f327178c29770246f8e79d78327e07
def disconnect_from_database(self): 'Close connection to SQL database\n\n Example:\n\n .. code-block:: robotframework\n\n Connect To Database pymysql mydb user pass 127.0.0.1\n ${result} Query Select firstname, lastname FROM table\n Disconnect From Database\n\n ' if self._dbconnection: self._dbconnection.close()
Close connection to SQL database Example: .. code-block:: robotframework Connect To Database pymysql mydb user pass 127.0.0.1 ${result} Query Select firstname, lastname FROM table Disconnect From Database
packages/main/src/RPA/Database.py
disconnect_from_database
rooky-c3bo/rpaframework
518
python
def disconnect_from_database(self): 'Close connection to SQL database\n\n Example:\n\n .. code-block:: robotframework\n\n Connect To Database pymysql mydb user pass 127.0.0.1\n ${result} Query Select firstname, lastname FROM table\n Disconnect From Database\n\n ' if self._dbconnection: self._dbconnection.close()
def disconnect_from_database(self): 'Close connection to SQL database\n\n Example:\n\n .. code-block:: robotframework\n\n Connect To Database pymysql mydb user pass 127.0.0.1\n ${result} Query Select firstname, lastname FROM table\n Disconnect From Database\n\n ' if self._dbconnection: self._dbconnection.close()<|docstring|>Close connection to SQL database Example: .. code-block:: robotframework Connect To Database pymysql mydb user pass 127.0.0.1 ${result} Query Select firstname, lastname FROM table Disconnect From Database<|endoftext|>
f618333c73f2752da894d304bddd166ed5862bf2d9e0cd0fd7f0db84cc7dbd2b
def execute_sql_script(self, filename, sanstran=False, encoding='utf-8'): 'Execute content of SQL script as SQL commands.\n\n :param filename: filepath to SQL script to execute\n :param sanstran: run command without an explicit transaction commit or rollback,\n defaults to False\n :param encoding: character encoding of file\n\n Example:\n\n .. code-block:: robotframework\n\n Execute SQL Script script.sql\n\n ' with open(filename, encoding=encoding) as script_file: sql_script = script_file.readlines() cur = None try: cur = self._dbconnection.cursor() sqlStatement = '' for line in sql_script: if (line.startswith('#') or line.startswith('--')): continue sql_fragments = line.split(';') if (len(sql_fragments) == 1): sqlStatement += (line + ' ') else: for sqlFragment in sql_fragments: sqlFragment = sqlFragment.strip() if (len(sqlFragment) == 0): continue sqlStatement += (sqlFragment + ' ') self.__execute_sql(cur, sqlStatement) sqlStatement = '' sqlStatement = sqlStatement.strip() if (len(sqlStatement) != 0): self.__execute_sql(cur, sqlStatement) if (not sanstran): self._dbconnection.commit() finally: if cur: if (not sanstran): self._dbconnection.rollback()
Execute content of SQL script as SQL commands. :param filename: filepath to SQL script to execute :param sanstran: run command without an explicit transaction commit or rollback, defaults to False :param encoding: character encoding of file Example: .. code-block:: robotframework Execute SQL Script script.sql
packages/main/src/RPA/Database.py
execute_sql_script
rooky-c3bo/rpaframework
518
python
def execute_sql_script(self, filename, sanstran=False, encoding='utf-8'): 'Execute content of SQL script as SQL commands.\n\n :param filename: filepath to SQL script to execute\n :param sanstran: run command without an explicit transaction commit or rollback,\n defaults to False\n :param encoding: character encoding of file\n\n Example:\n\n .. code-block:: robotframework\n\n Execute SQL Script script.sql\n\n ' with open(filename, encoding=encoding) as script_file: sql_script = script_file.readlines() cur = None try: cur = self._dbconnection.cursor() sqlStatement = for line in sql_script: if (line.startswith('#') or line.startswith('--')): continue sql_fragments = line.split(';') if (len(sql_fragments) == 1): sqlStatement += (line + ' ') else: for sqlFragment in sql_fragments: sqlFragment = sqlFragment.strip() if (len(sqlFragment) == 0): continue sqlStatement += (sqlFragment + ' ') self.__execute_sql(cur, sqlStatement) sqlStatement = sqlStatement = sqlStatement.strip() if (len(sqlStatement) != 0): self.__execute_sql(cur, sqlStatement) if (not sanstran): self._dbconnection.commit() finally: if cur: if (not sanstran): self._dbconnection.rollback()
def execute_sql_script(self, filename, sanstran=False, encoding='utf-8'): 'Execute content of SQL script as SQL commands.\n\n :param filename: filepath to SQL script to execute\n :param sanstran: run command without an explicit transaction commit or rollback,\n defaults to False\n :param encoding: character encoding of file\n\n Example:\n\n .. code-block:: robotframework\n\n Execute SQL Script script.sql\n\n ' with open(filename, encoding=encoding) as script_file: sql_script = script_file.readlines() cur = None try: cur = self._dbconnection.cursor() sqlStatement = for line in sql_script: if (line.startswith('#') or line.startswith('--')): continue sql_fragments = line.split(';') if (len(sql_fragments) == 1): sqlStatement += (line + ' ') else: for sqlFragment in sql_fragments: sqlFragment = sqlFragment.strip() if (len(sqlFragment) == 0): continue sqlStatement += (sqlFragment + ' ') self.__execute_sql(cur, sqlStatement) sqlStatement = sqlStatement = sqlStatement.strip() if (len(sqlStatement) != 0): self.__execute_sql(cur, sqlStatement) if (not sanstran): self._dbconnection.commit() finally: if cur: if (not sanstran): self._dbconnection.rollback()<|docstring|>Execute content of SQL script as SQL commands. :param filename: filepath to SQL script to execute :param sanstran: run command without an explicit transaction commit or rollback, defaults to False :param encoding: character encoding of file Example: .. code-block:: robotframework Execute SQL Script script.sql<|endoftext|>
edc1f371ea6d9d821e11062fa8b975917ad73ab2dceafccd219e6389052e66e7
def query(self, statement: str, assertion: str=None, sanstran: bool=False, as_table: bool=True): "Make a SQL query.\n\n :param statement: SQL statement to execute\n :param assertion: assert on query result, row_count or columns.\n Works only for SELECT statements Defaults to None.\n :param sanstran: run command without an explicit transaction commit or rollback,\n defaults to False\n :param as_table: if result should be instance of ``Table``, defaults to `True`\n `False` means that return type would be `list`\n\n Example:\n\n .. code-block:: robotframework\n\n @{res} Query Select firstname, lastname FROM table\n FOR ${row} IN @{RES}\n Log ${row}\n END\n @{res} Query Select * FROM table row_count > ${EXPECTED}\n @{res} Query Select * FROM table 'arvo' in columns\n @{res} Query Select * FROM table columns == ['id', 'arvo']\n\n " rows = None columns = None result = None cursor = None try: cursor = self._dbconnection.cursor() self.logger.info('Executing : Query | %s ', statement) result = self.__execute_sql(cursor, statement) if self._is_returnable_statement(statement): rows = cursor.fetchall() columns = [c[0] for c in cursor.description] self._result_assertion(rows, columns, assertion) if as_table: return Table(rows, columns) return rows else: if (result is not None): if (not sanstran): self._dbconnection.commit() if (not sanstran): self._dbconnection.commit() finally: if cursor: if (not sanstran): self._dbconnection.rollback() return result
Make a SQL query. :param statement: SQL statement to execute :param assertion: assert on query result, row_count or columns. Works only for SELECT statements Defaults to None. :param sanstran: run command without an explicit transaction commit or rollback, defaults to False :param as_table: if result should be instance of ``Table``, defaults to `True` `False` means that return type would be `list` Example: .. code-block:: robotframework @{res} Query Select firstname, lastname FROM table FOR ${row} IN @{RES} Log ${row} END @{res} Query Select * FROM table row_count > ${EXPECTED} @{res} Query Select * FROM table 'arvo' in columns @{res} Query Select * FROM table columns == ['id', 'arvo']
packages/main/src/RPA/Database.py
query
rooky-c3bo/rpaframework
518
python
def query(self, statement: str, assertion: str=None, sanstran: bool=False, as_table: bool=True): "Make a SQL query.\n\n :param statement: SQL statement to execute\n :param assertion: assert on query result, row_count or columns.\n Works only for SELECT statements Defaults to None.\n :param sanstran: run command without an explicit transaction commit or rollback,\n defaults to False\n :param as_table: if result should be instance of ``Table``, defaults to `True`\n `False` means that return type would be `list`\n\n Example:\n\n .. code-block:: robotframework\n\n @{res} Query Select firstname, lastname FROM table\n FOR ${row} IN @{RES}\n Log ${row}\n END\n @{res} Query Select * FROM table row_count > ${EXPECTED}\n @{res} Query Select * FROM table 'arvo' in columns\n @{res} Query Select * FROM table columns == ['id', 'arvo']\n\n " rows = None columns = None result = None cursor = None try: cursor = self._dbconnection.cursor() self.logger.info('Executing : Query | %s ', statement) result = self.__execute_sql(cursor, statement) if self._is_returnable_statement(statement): rows = cursor.fetchall() columns = [c[0] for c in cursor.description] self._result_assertion(rows, columns, assertion) if as_table: return Table(rows, columns) return rows else: if (result is not None): if (not sanstran): self._dbconnection.commit() if (not sanstran): self._dbconnection.commit() finally: if cursor: if (not sanstran): self._dbconnection.rollback() return result
def query(self, statement: str, assertion: str=None, sanstran: bool=False, as_table: bool=True): "Make a SQL query.\n\n :param statement: SQL statement to execute\n :param assertion: assert on query result, row_count or columns.\n Works only for SELECT statements Defaults to None.\n :param sanstran: run command without an explicit transaction commit or rollback,\n defaults to False\n :param as_table: if result should be instance of ``Table``, defaults to `True`\n `False` means that return type would be `list`\n\n Example:\n\n .. code-block:: robotframework\n\n @{res} Query Select firstname, lastname FROM table\n FOR ${row} IN @{RES}\n Log ${row}\n END\n @{res} Query Select * FROM table row_count > ${EXPECTED}\n @{res} Query Select * FROM table 'arvo' in columns\n @{res} Query Select * FROM table columns == ['id', 'arvo']\n\n " rows = None columns = None result = None cursor = None try: cursor = self._dbconnection.cursor() self.logger.info('Executing : Query | %s ', statement) result = self.__execute_sql(cursor, statement) if self._is_returnable_statement(statement): rows = cursor.fetchall() columns = [c[0] for c in cursor.description] self._result_assertion(rows, columns, assertion) if as_table: return Table(rows, columns) return rows else: if (result is not None): if (not sanstran): self._dbconnection.commit() if (not sanstran): self._dbconnection.commit() finally: if cursor: if (not sanstran): self._dbconnection.rollback() return result<|docstring|>Make a SQL query. :param statement: SQL statement to execute :param assertion: assert on query result, row_count or columns. Works only for SELECT statements Defaults to None. :param sanstran: run command without an explicit transaction commit or rollback, defaults to False :param as_table: if result should be instance of ``Table``, defaults to `True` `False` means that return type would be `list` Example: .. code-block:: robotframework @{res} Query Select firstname, lastname FROM table FOR ${row} IN @{RES} Log ${row} END @{res} Query Select * FROM table row_count > ${EXPECTED} @{res} Query Select * FROM table 'arvo' in columns @{res} Query Select * FROM table columns == ['id', 'arvo']<|endoftext|>
7163ccf3b81e4d56b0e37f828facf448fffc38287bf261517f93dada5bfa425a
def set_auto_commit(self, autocommit=True): 'Set database auto commit mode.\n\n :param autocommit: boolean value for auto commit, defaults to True\n\n Example:\n\n .. code-block:: robotframework\n\n Set Auto Commit # auto commit is set on\n Set Auto Commit False # auto commit is turned off\n\n ' self._dbconnection.autocommit = autocommit
Set database auto commit mode. :param autocommit: boolean value for auto commit, defaults to True Example: .. code-block:: robotframework Set Auto Commit # auto commit is set on Set Auto Commit False # auto commit is turned off
packages/main/src/RPA/Database.py
set_auto_commit
rooky-c3bo/rpaframework
518
python
def set_auto_commit(self, autocommit=True): 'Set database auto commit mode.\n\n :param autocommit: boolean value for auto commit, defaults to True\n\n Example:\n\n .. code-block:: robotframework\n\n Set Auto Commit # auto commit is set on\n Set Auto Commit False # auto commit is turned off\n\n ' self._dbconnection.autocommit = autocommit
def set_auto_commit(self, autocommit=True): 'Set database auto commit mode.\n\n :param autocommit: boolean value for auto commit, defaults to True\n\n Example:\n\n .. code-block:: robotframework\n\n Set Auto Commit # auto commit is set on\n Set Auto Commit False # auto commit is turned off\n\n ' self._dbconnection.autocommit = autocommit<|docstring|>Set database auto commit mode. :param autocommit: boolean value for auto commit, defaults to True Example: .. code-block:: robotframework Set Auto Commit # auto commit is set on Set Auto Commit False # auto commit is turned off<|endoftext|>
fb4c1cfaa93e1e3d6a10be04edac539ea97ffa9469beb17bc4fad2f3dfd11f0f
def get_rows(self, table, columns=None, conditions=None, as_table=True): "Get rows from table. Columns and conditions can be\n set to filter result.\n\n :param table: name of the SQL table\n :param columns: name of columns to return, defaults to `None`\n means that all columns are returned\n :param conditions: limiting result by WHERE clause, defaults to `None`\n :param as_table: if result should be instance of ``Table``, defaults to `True`\n `False` means that return type would be `list`\n\n Example:\n\n .. code-block:: robotframework\n\n @{res} Get Rows tablename arvo\n @{res} Get Rows tablename arvo columns=id,name\n @{res} Get Rows tablename columns=id conditions=column1='newvalue'\n @{res} Get Rows tablename conditions=column2='updatedvalue'\n\n " columns = (columns or '*') where_cond = (f' WHERE {conditions}' if conditions else '') return self.query(('SELECT %s FROM %s%s' % (columns, table, where_cond)), as_table=as_table)
Get rows from table. Columns and conditions can be set to filter result. :param table: name of the SQL table :param columns: name of columns to return, defaults to `None` means that all columns are returned :param conditions: limiting result by WHERE clause, defaults to `None` :param as_table: if result should be instance of ``Table``, defaults to `True` `False` means that return type would be `list` Example: .. code-block:: robotframework @{res} Get Rows tablename arvo @{res} Get Rows tablename arvo columns=id,name @{res} Get Rows tablename columns=id conditions=column1='newvalue' @{res} Get Rows tablename conditions=column2='updatedvalue'
packages/main/src/RPA/Database.py
get_rows
rooky-c3bo/rpaframework
518
python
def get_rows(self, table, columns=None, conditions=None, as_table=True): "Get rows from table. Columns and conditions can be\n set to filter result.\n\n :param table: name of the SQL table\n :param columns: name of columns to return, defaults to `None`\n means that all columns are returned\n :param conditions: limiting result by WHERE clause, defaults to `None`\n :param as_table: if result should be instance of ``Table``, defaults to `True`\n `False` means that return type would be `list`\n\n Example:\n\n .. code-block:: robotframework\n\n @{res} Get Rows tablename arvo\n @{res} Get Rows tablename arvo columns=id,name\n @{res} Get Rows tablename columns=id conditions=column1='newvalue'\n @{res} Get Rows tablename conditions=column2='updatedvalue'\n\n " columns = (columns or '*') where_cond = (f' WHERE {conditions}' if conditions else ) return self.query(('SELECT %s FROM %s%s' % (columns, table, where_cond)), as_table=as_table)
def get_rows(self, table, columns=None, conditions=None, as_table=True): "Get rows from table. Columns and conditions can be\n set to filter result.\n\n :param table: name of the SQL table\n :param columns: name of columns to return, defaults to `None`\n means that all columns are returned\n :param conditions: limiting result by WHERE clause, defaults to `None`\n :param as_table: if result should be instance of ``Table``, defaults to `True`\n `False` means that return type would be `list`\n\n Example:\n\n .. code-block:: robotframework\n\n @{res} Get Rows tablename arvo\n @{res} Get Rows tablename arvo columns=id,name\n @{res} Get Rows tablename columns=id conditions=column1='newvalue'\n @{res} Get Rows tablename conditions=column2='updatedvalue'\n\n " columns = (columns or '*') where_cond = (f' WHERE {conditions}' if conditions else ) return self.query(('SELECT %s FROM %s%s' % (columns, table, where_cond)), as_table=as_table)<|docstring|>Get rows from table. Columns and conditions can be set to filter result. :param table: name of the SQL table :param columns: name of columns to return, defaults to `None` means that all columns are returned :param conditions: limiting result by WHERE clause, defaults to `None` :param as_table: if result should be instance of ``Table``, defaults to `True` `False` means that return type would be `list` Example: .. code-block:: robotframework @{res} Get Rows tablename arvo @{res} Get Rows tablename arvo columns=id,name @{res} Get Rows tablename columns=id conditions=column1='newvalue' @{res} Get Rows tablename conditions=column2='updatedvalue'<|endoftext|>
2f40fc22651e6025daef967b53799ce2ef04672929f5ef2970c932eb11e73cb1
def get_number_of_rows(self, table, conditions=None): "Get number of rows in a table. Conditions can be given\n as arguments for WHERE clause.\n\n :param table: name of the SQL table\n :param conditions: restrictions for selections, defaults to None\n\n Example:\n\n .. code-block:: robotframework\n\n ${count} Get Number Of Rows tablename\n ${count} Get Number Of Rows tablename column1=5 and column2='x'\n\n " where_cond = (f' WHERE {conditions}' if conditions else '') result = self.query(('SELECT COUNT(*) FROM %s%s' % (table, where_cond)), as_table=False) return result[0][0]
Get number of rows in a table. Conditions can be given as arguments for WHERE clause. :param table: name of the SQL table :param conditions: restrictions for selections, defaults to None Example: .. code-block:: robotframework ${count} Get Number Of Rows tablename ${count} Get Number Of Rows tablename column1=5 and column2='x'
packages/main/src/RPA/Database.py
get_number_of_rows
rooky-c3bo/rpaframework
518
python
def get_number_of_rows(self, table, conditions=None): "Get number of rows in a table. Conditions can be given\n as arguments for WHERE clause.\n\n :param table: name of the SQL table\n :param conditions: restrictions for selections, defaults to None\n\n Example:\n\n .. code-block:: robotframework\n\n ${count} Get Number Of Rows tablename\n ${count} Get Number Of Rows tablename column1=5 and column2='x'\n\n " where_cond = (f' WHERE {conditions}' if conditions else ) result = self.query(('SELECT COUNT(*) FROM %s%s' % (table, where_cond)), as_table=False) return result[0][0]
def get_number_of_rows(self, table, conditions=None): "Get number of rows in a table. Conditions can be given\n as arguments for WHERE clause.\n\n :param table: name of the SQL table\n :param conditions: restrictions for selections, defaults to None\n\n Example:\n\n .. code-block:: robotframework\n\n ${count} Get Number Of Rows tablename\n ${count} Get Number Of Rows tablename column1=5 and column2='x'\n\n " where_cond = (f' WHERE {conditions}' if conditions else ) result = self.query(('SELECT COUNT(*) FROM %s%s' % (table, where_cond)), as_table=False) return result[0][0]<|docstring|>Get number of rows in a table. Conditions can be given as arguments for WHERE clause. :param table: name of the SQL table :param conditions: restrictions for selections, defaults to None Example: .. code-block:: robotframework ${count} Get Number Of Rows tablename ${count} Get Number Of Rows tablename column1=5 and column2='x'<|endoftext|>
5cf0738494cca1d0ded09f6b784e02e65980e7fd8ad81c6ee3541d05f06dd092
@abstractmethod def _create_splits(self) -> Dict[(str, Tuple[str])]: 'Create the key splits using keys as the split name (i.e. ``train``) and the\n values as a list of the keys for the corresponding split.\n\n ' pass
Create the key splits using keys as the split name (i.e. ``train``) and the values as a list of the keys for the corresponding split.
src/python/zensols/dataset/split.py
_create_splits
plandes/deeplearn
2
python
@abstractmethod def _create_splits(self) -> Dict[(str, Tuple[str])]: 'Create the key splits using keys as the split name (i.e. ``train``) and the\n values as a list of the keys for the corresponding split.\n\n ' pass
@abstractmethod def _create_splits(self) -> Dict[(str, Tuple[str])]: 'Create the key splits using keys as the split name (i.e. ``train``) and the\n values as a list of the keys for the corresponding split.\n\n ' pass<|docstring|>Create the key splits using keys as the split name (i.e. ``train``) and the values as a list of the keys for the corresponding split.<|endoftext|>
b5b2a842b0171f85d65becf96cf5140f6e5be13282fa759f9f60c5b636b6a014
def _create_splits_and_write(self): 'Write the keys in order to the file system.\n\n ' self.key_path.mkdir(parents=True, exist_ok=True) for (name, keys) in self._create_splits().items(): fname = self.pattern.format(**{'name': name}) key_path = (self.key_path / fname) with open(key_path, 'w') as f: for k in keys: f.write((k + '\n'))
Write the keys in order to the file system.
src/python/zensols/dataset/split.py
_create_splits_and_write
plandes/deeplearn
2
python
def _create_splits_and_write(self): '\n\n ' self.key_path.mkdir(parents=True, exist_ok=True) for (name, keys) in self._create_splits().items(): fname = self.pattern.format(**{'name': name}) key_path = (self.key_path / fname) with open(key_path, 'w') as f: for k in keys: f.write((k + '\n'))
def _create_splits_and_write(self): '\n\n ' self.key_path.mkdir(parents=True, exist_ok=True) for (name, keys) in self._create_splits().items(): fname = self.pattern.format(**{'name': name}) key_path = (self.key_path / fname) with open(key_path, 'w') as f: for k in keys: f.write((k + '\n'))<|docstring|>Write the keys in order to the file system.<|endoftext|>
5528bb232c32e299f52991a08f865de5a05ccc9837eec409cea359d75b8a260f
def _read_splits(self): 'Read the keys in order from the file system.\n\n ' by_name = {} for path in self.key_path.iterdir(): p = parse.parse(self.pattern, path.name) if (p is not None): p = p.named if ('name' in p): with open(path) as f: by_name[p['name']] = tuple(map((lambda ln: ln.strip()), f.readlines())) return by_name
Read the keys in order from the file system.
src/python/zensols/dataset/split.py
_read_splits
plandes/deeplearn
2
python
def _read_splits(self): '\n\n ' by_name = {} for path in self.key_path.iterdir(): p = parse.parse(self.pattern, path.name) if (p is not None): p = p.named if ('name' in p): with open(path) as f: by_name[p['name']] = tuple(map((lambda ln: ln.strip()), f.readlines())) return by_name
def _read_splits(self): '\n\n ' by_name = {} for path in self.key_path.iterdir(): p = parse.parse(self.pattern, path.name) if (p is not None): p = p.named if ('name' in p): with open(path) as f: by_name[p['name']] = tuple(map((lambda ln: ln.strip()), f.readlines())) return by_name<|docstring|>Read the keys in order from the file system.<|endoftext|>
1cfa2340c1ac29fe49c6191dcbd7a71ffc9dd28d109c9e2407cb74275fc9d23a
def explained_variance(ypred, y): '\n Computes the fraction of variance that ypred explains about y\n '
Computes the fraction of variance that ypred explains about y
baselines/common/math_util.py
explained_variance
baihuaxie/drl-lib
0
python
def explained_variance(ypred, y): '\n \n '
def explained_variance(ypred, y): '\n \n '<|docstring|>Computes the fraction of variance that ypred explains about y<|endoftext|>
db4d965456ee4587800b1e2af84aa6413e8f949295b0476d4e05987adc6f84d2
def project_p3d(p: Vector, camera: bpy.types.Object=bpy.context.scene.camera, render: bpy.types.RenderSettings=bpy.context.scene.render) -> Vector: 'Project a point p onto the image plane of a camera. The returned value is\n in normalized device coordiantes. That is, left upper corner is -1,1, right\n bottom lower corner is 1/-1.\n\n Args:\n p (Vector): 3D vector to project to image plane\n camera (bpy.types.Object): blender camera to use for projection\n render (bpy.types.RenderSettings): render settings used for computation\n\n Returns:\n 2D vector with projected p in normalized device coordiantes\n ' if (camera.type != 'CAMERA'): raise Exception(f'Object {camera.name} is not a camera') if (len(p) != 3): raise Exception(f'Vector {p} needs to be 3 dimensional') depsgraph = bpy.context.evaluated_depsgraph_get() modelview = camera.matrix_world.inverted() projection = camera.calc_matrix_camera(depsgraph, x=render.resolution_x, y=render.resolution_y, scale_x=render.pixel_aspect_x, scale_y=render.pixel_aspect_y) p_hom = ((projection @ modelview) @ Vector((p.x, p.y, p.z, 1))) if (p_hom.w == 0.0): return None else: return Vector(((p_hom.x / p_hom.w), (p_hom.y / p_hom.w)))
Project a point p onto the image plane of a camera. The returned value is in normalized device coordiantes. That is, left upper corner is -1,1, right bottom lower corner is 1/-1. Args: p (Vector): 3D vector to project to image plane camera (bpy.types.Object): blender camera to use for projection render (bpy.types.RenderSettings): render settings used for computation Returns: 2D vector with projected p in normalized device coordiantes
src/amira_blender_rendering/math/geometry.py
project_p3d
patrickkesper/amira_blender_rendering
26
python
def project_p3d(p: Vector, camera: bpy.types.Object=bpy.context.scene.camera, render: bpy.types.RenderSettings=bpy.context.scene.render) -> Vector: 'Project a point p onto the image plane of a camera. The returned value is\n in normalized device coordiantes. That is, left upper corner is -1,1, right\n bottom lower corner is 1/-1.\n\n Args:\n p (Vector): 3D vector to project to image plane\n camera (bpy.types.Object): blender camera to use for projection\n render (bpy.types.RenderSettings): render settings used for computation\n\n Returns:\n 2D vector with projected p in normalized device coordiantes\n ' if (camera.type != 'CAMERA'): raise Exception(f'Object {camera.name} is not a camera') if (len(p) != 3): raise Exception(f'Vector {p} needs to be 3 dimensional') depsgraph = bpy.context.evaluated_depsgraph_get() modelview = camera.matrix_world.inverted() projection = camera.calc_matrix_camera(depsgraph, x=render.resolution_x, y=render.resolution_y, scale_x=render.pixel_aspect_x, scale_y=render.pixel_aspect_y) p_hom = ((projection @ modelview) @ Vector((p.x, p.y, p.z, 1))) if (p_hom.w == 0.0): return None else: return Vector(((p_hom.x / p_hom.w), (p_hom.y / p_hom.w)))
def project_p3d(p: Vector, camera: bpy.types.Object=bpy.context.scene.camera, render: bpy.types.RenderSettings=bpy.context.scene.render) -> Vector: 'Project a point p onto the image plane of a camera. The returned value is\n in normalized device coordiantes. That is, left upper corner is -1,1, right\n bottom lower corner is 1/-1.\n\n Args:\n p (Vector): 3D vector to project to image plane\n camera (bpy.types.Object): blender camera to use for projection\n render (bpy.types.RenderSettings): render settings used for computation\n\n Returns:\n 2D vector with projected p in normalized device coordiantes\n ' if (camera.type != 'CAMERA'): raise Exception(f'Object {camera.name} is not a camera') if (len(p) != 3): raise Exception(f'Vector {p} needs to be 3 dimensional') depsgraph = bpy.context.evaluated_depsgraph_get() modelview = camera.matrix_world.inverted() projection = camera.calc_matrix_camera(depsgraph, x=render.resolution_x, y=render.resolution_y, scale_x=render.pixel_aspect_x, scale_y=render.pixel_aspect_y) p_hom = ((projection @ modelview) @ Vector((p.x, p.y, p.z, 1))) if (p_hom.w == 0.0): return None else: return Vector(((p_hom.x / p_hom.w), (p_hom.y / p_hom.w)))<|docstring|>Project a point p onto the image plane of a camera. The returned value is in normalized device coordiantes. That is, left upper corner is -1,1, right bottom lower corner is 1/-1. Args: p (Vector): 3D vector to project to image plane camera (bpy.types.Object): blender camera to use for projection render (bpy.types.RenderSettings): render settings used for computation Returns: 2D vector with projected p in normalized device coordiantes<|endoftext|>
b19ad39faba010fdb21bebc63ea77d8b02bd10dbdbcc024cf80e3389c56c2a08
def p2d_to_pixel_coords(p: Vector, render: bpy.types.RenderSettings=bpy.context.scene.render) -> Vector: 'Take a 2D point in normalized device coordiantes to pixel coordinates\n using specified render settings.\n\n Args:\n p (Vector): 2D vector in normalized device coordinates\n render (bpy.types.RenderSettings): blender render settings to use for\n pixel calculation\n\n Returns:\n 2D vector containing screen space (pixel) coordinate of p\n ' if (len(p) != 2): raise Exception(f'Vector {p} needs to be 2 dimensinoal') return Vector(((((render.resolution_x - 1) * (p.x + 1.0)) / (+ 2.0)), (((render.resolution_y - 1) * (p.y - 1.0)) / (- 2.0))))
Take a 2D point in normalized device coordiantes to pixel coordinates using specified render settings. Args: p (Vector): 2D vector in normalized device coordinates render (bpy.types.RenderSettings): blender render settings to use for pixel calculation Returns: 2D vector containing screen space (pixel) coordinate of p
src/amira_blender_rendering/math/geometry.py
p2d_to_pixel_coords
patrickkesper/amira_blender_rendering
26
python
def p2d_to_pixel_coords(p: Vector, render: bpy.types.RenderSettings=bpy.context.scene.render) -> Vector: 'Take a 2D point in normalized device coordiantes to pixel coordinates\n using specified render settings.\n\n Args:\n p (Vector): 2D vector in normalized device coordinates\n render (bpy.types.RenderSettings): blender render settings to use for\n pixel calculation\n\n Returns:\n 2D vector containing screen space (pixel) coordinate of p\n ' if (len(p) != 2): raise Exception(f'Vector {p} needs to be 2 dimensinoal') return Vector(((((render.resolution_x - 1) * (p.x + 1.0)) / (+ 2.0)), (((render.resolution_y - 1) * (p.y - 1.0)) / (- 2.0))))
def p2d_to_pixel_coords(p: Vector, render: bpy.types.RenderSettings=bpy.context.scene.render) -> Vector: 'Take a 2D point in normalized device coordiantes to pixel coordinates\n using specified render settings.\n\n Args:\n p (Vector): 2D vector in normalized device coordinates\n render (bpy.types.RenderSettings): blender render settings to use for\n pixel calculation\n\n Returns:\n 2D vector containing screen space (pixel) coordinate of p\n ' if (len(p) != 2): raise Exception(f'Vector {p} needs to be 2 dimensinoal') return Vector(((((render.resolution_x - 1) * (p.x + 1.0)) / (+ 2.0)), (((render.resolution_y - 1) * (p.y - 1.0)) / (- 2.0))))<|docstring|>Take a 2D point in normalized device coordiantes to pixel coordinates using specified render settings. Args: p (Vector): 2D vector in normalized device coordinates render (bpy.types.RenderSettings): blender render settings to use for pixel calculation Returns: 2D vector containing screen space (pixel) coordinate of p<|endoftext|>
ace303e3f89efdcf97e4917d4b4831f04f10063fb58e5830ea88ce68439b06eb
def get_relative_rotation(obj1: bpy.types.Object, obj2: bpy.types.Object=bpy.context.scene.camera) -> Euler: "Get the relative rotation between two objects in terms of the second\n object's coordinate system. Note that the second object will be default\n initialized to the scene's camera.\n\n Returns:\n Euler angles given in radians\n " obj1_m = obj1.matrix_world.to_3x3().normalized() obj2_m = obj2.matrix_world.to_3x3().normalized() rel_rotation = (obj2_m.inverted() @ obj1_m).to_euler() return rel_rotation
Get the relative rotation between two objects in terms of the second object's coordinate system. Note that the second object will be default initialized to the scene's camera. Returns: Euler angles given in radians
src/amira_blender_rendering/math/geometry.py
get_relative_rotation
patrickkesper/amira_blender_rendering
26
python
def get_relative_rotation(obj1: bpy.types.Object, obj2: bpy.types.Object=bpy.context.scene.camera) -> Euler: "Get the relative rotation between two objects in terms of the second\n object's coordinate system. Note that the second object will be default\n initialized to the scene's camera.\n\n Returns:\n Euler angles given in radians\n " obj1_m = obj1.matrix_world.to_3x3().normalized() obj2_m = obj2.matrix_world.to_3x3().normalized() rel_rotation = (obj2_m.inverted() @ obj1_m).to_euler() return rel_rotation
def get_relative_rotation(obj1: bpy.types.Object, obj2: bpy.types.Object=bpy.context.scene.camera) -> Euler: "Get the relative rotation between two objects in terms of the second\n object's coordinate system. Note that the second object will be default\n initialized to the scene's camera.\n\n Returns:\n Euler angles given in radians\n " obj1_m = obj1.matrix_world.to_3x3().normalized() obj2_m = obj2.matrix_world.to_3x3().normalized() rel_rotation = (obj2_m.inverted() @ obj1_m).to_euler() return rel_rotation<|docstring|>Get the relative rotation between two objects in terms of the second object's coordinate system. Note that the second object will be default initialized to the scene's camera. Returns: Euler angles given in radians<|endoftext|>
81ef0b072c1eb391762699be2029067d4f810068bee1da1f4b3b11d7d51f2fd2
def get_relative_rotation_to_cam_deg(obj, cam, zeroing=Vector((90, 0, 0))): "Get the relative rotation between an object and a camera in the camera's\n frame of reference.\n\n For more details, see get_relative_rotation_to_cam_rad.\n\n Args:\n obj: object to compute relative rotation for\n cam: camera to used\n zeroing: camera zeroing angles (in degrees)\n\n Returns:\n Relative rotation between object and camera in the coordinate frame of\n the camera.\n " return get_relative_rotation_to_cam_rad(obj, cam, ((zeroing * pi) / 180))
Get the relative rotation between an object and a camera in the camera's frame of reference. For more details, see get_relative_rotation_to_cam_rad. Args: obj: object to compute relative rotation for cam: camera to used zeroing: camera zeroing angles (in degrees) Returns: Relative rotation between object and camera in the coordinate frame of the camera.
src/amira_blender_rendering/math/geometry.py
get_relative_rotation_to_cam_deg
patrickkesper/amira_blender_rendering
26
python
def get_relative_rotation_to_cam_deg(obj, cam, zeroing=Vector((90, 0, 0))): "Get the relative rotation between an object and a camera in the camera's\n frame of reference.\n\n For more details, see get_relative_rotation_to_cam_rad.\n\n Args:\n obj: object to compute relative rotation for\n cam: camera to used\n zeroing: camera zeroing angles (in degrees)\n\n Returns:\n Relative rotation between object and camera in the coordinate frame of\n the camera.\n " return get_relative_rotation_to_cam_rad(obj, cam, ((zeroing * pi) / 180))
def get_relative_rotation_to_cam_deg(obj, cam, zeroing=Vector((90, 0, 0))): "Get the relative rotation between an object and a camera in the camera's\n frame of reference.\n\n For more details, see get_relative_rotation_to_cam_rad.\n\n Args:\n obj: object to compute relative rotation for\n cam: camera to used\n zeroing: camera zeroing angles (in degrees)\n\n Returns:\n Relative rotation between object and camera in the coordinate frame of\n the camera.\n " return get_relative_rotation_to_cam_rad(obj, cam, ((zeroing * pi) / 180))<|docstring|>Get the relative rotation between an object and a camera in the camera's frame of reference. For more details, see get_relative_rotation_to_cam_rad. Args: obj: object to compute relative rotation for cam: camera to used zeroing: camera zeroing angles (in degrees) Returns: Relative rotation between object and camera in the coordinate frame of the camera.<|endoftext|>
f293ef8c2a71d576f121d7dbdf0be746368ad8a1cf1da4e46cca8803e606f964
def get_relative_rotation_to_cam_rad(obj, cam, zeroing=Vector(((pi / 2), 0, 0))): "Get the relative rotation between an object and a camera in the camera's\n frame of reference.\n\n This function allows to specify a certain 'zeroing' rotation.\n\n A default camera in blender with 0 rotation applied to its transform looks\n along the -Z direction. Blender's modelling viewport, however, assumes that\n the surface plane is spanned by X and Y, where X indicates left/right. This\n can be observed by putting the modelling viewport into the front viewpoint\n (Numpad 1). Then, the viewport looks along the Y direction.\n\n As a consequence, the relative rotation between a camera image and an object\n is only 0 when the camera would look onto the top of the object. Note that\n this is rather unintuitive, as most people would expect that the relative\n rotation is 0 when the camera looks at the front of an object.\n\n Args:\n obj: object to compute relative rotation for\n cam: camera to used\n zeroing: camera zeroing angles (in radians)\n\n Returns:\n Relative rotation between object and camera in the coordinate frame of\n the camera.\n " obj_m = obj.matrix_world.to_3x3().normalized() cam_m = cam.matrix_world.to_3x3().normalized() rel_rotation = (cam_m.inverted() @ obj_m) cam_rot = Euler([zeroing[0], zeroing[1], zeroing[2]]).to_matrix() return (cam_rot @ rel_rotation).to_euler()
Get the relative rotation between an object and a camera in the camera's frame of reference. This function allows to specify a certain 'zeroing' rotation. A default camera in blender with 0 rotation applied to its transform looks along the -Z direction. Blender's modelling viewport, however, assumes that the surface plane is spanned by X and Y, where X indicates left/right. This can be observed by putting the modelling viewport into the front viewpoint (Numpad 1). Then, the viewport looks along the Y direction. As a consequence, the relative rotation between a camera image and an object is only 0 when the camera would look onto the top of the object. Note that this is rather unintuitive, as most people would expect that the relative rotation is 0 when the camera looks at the front of an object. Args: obj: object to compute relative rotation for cam: camera to used zeroing: camera zeroing angles (in radians) Returns: Relative rotation between object and camera in the coordinate frame of the camera.
src/amira_blender_rendering/math/geometry.py
get_relative_rotation_to_cam_rad
patrickkesper/amira_blender_rendering
26
python
def get_relative_rotation_to_cam_rad(obj, cam, zeroing=Vector(((pi / 2), 0, 0))): "Get the relative rotation between an object and a camera in the camera's\n frame of reference.\n\n This function allows to specify a certain 'zeroing' rotation.\n\n A default camera in blender with 0 rotation applied to its transform looks\n along the -Z direction. Blender's modelling viewport, however, assumes that\n the surface plane is spanned by X and Y, where X indicates left/right. This\n can be observed by putting the modelling viewport into the front viewpoint\n (Numpad 1). Then, the viewport looks along the Y direction.\n\n As a consequence, the relative rotation between a camera image and an object\n is only 0 when the camera would look onto the top of the object. Note that\n this is rather unintuitive, as most people would expect that the relative\n rotation is 0 when the camera looks at the front of an object.\n\n Args:\n obj: object to compute relative rotation for\n cam: camera to used\n zeroing: camera zeroing angles (in radians)\n\n Returns:\n Relative rotation between object and camera in the coordinate frame of\n the camera.\n " obj_m = obj.matrix_world.to_3x3().normalized() cam_m = cam.matrix_world.to_3x3().normalized() rel_rotation = (cam_m.inverted() @ obj_m) cam_rot = Euler([zeroing[0], zeroing[1], zeroing[2]]).to_matrix() return (cam_rot @ rel_rotation).to_euler()
def get_relative_rotation_to_cam_rad(obj, cam, zeroing=Vector(((pi / 2), 0, 0))): "Get the relative rotation between an object and a camera in the camera's\n frame of reference.\n\n This function allows to specify a certain 'zeroing' rotation.\n\n A default camera in blender with 0 rotation applied to its transform looks\n along the -Z direction. Blender's modelling viewport, however, assumes that\n the surface plane is spanned by X and Y, where X indicates left/right. This\n can be observed by putting the modelling viewport into the front viewpoint\n (Numpad 1). Then, the viewport looks along the Y direction.\n\n As a consequence, the relative rotation between a camera image and an object\n is only 0 when the camera would look onto the top of the object. Note that\n this is rather unintuitive, as most people would expect that the relative\n rotation is 0 when the camera looks at the front of an object.\n\n Args:\n obj: object to compute relative rotation for\n cam: camera to used\n zeroing: camera zeroing angles (in radians)\n\n Returns:\n Relative rotation between object and camera in the coordinate frame of\n the camera.\n " obj_m = obj.matrix_world.to_3x3().normalized() cam_m = cam.matrix_world.to_3x3().normalized() rel_rotation = (cam_m.inverted() @ obj_m) cam_rot = Euler([zeroing[0], zeroing[1], zeroing[2]]).to_matrix() return (cam_rot @ rel_rotation).to_euler()<|docstring|>Get the relative rotation between an object and a camera in the camera's frame of reference. This function allows to specify a certain 'zeroing' rotation. A default camera in blender with 0 rotation applied to its transform looks along the -Z direction. Blender's modelling viewport, however, assumes that the surface plane is spanned by X and Y, where X indicates left/right. This can be observed by putting the modelling viewport into the front viewpoint (Numpad 1). Then, the viewport looks along the Y direction. As a consequence, the relative rotation between a camera image and an object is only 0 when the camera would look onto the top of the object. Note that this is rather unintuitive, as most people would expect that the relative rotation is 0 when the camera looks at the front of an object. Args: obj: object to compute relative rotation for cam: camera to used zeroing: camera zeroing angles (in radians) Returns: Relative rotation between object and camera in the coordinate frame of the camera.<|endoftext|>
356eefac7204119fd2a094b939927a743ac4cc23af248cb3651e8bbfe5a67798
def get_relative_translation(obj1: bpy.types.Object, obj2: bpy.types.Object=bpy.context.scene.camera) -> Vector: "Get the relative translation between two objects in terms of the second\n object's coordinate system. Note that the second object will be default\n initialized to the scene's camera.\n\n Args:\n obj1 (bpy.types.Object): first object\n obj2 (bpy.types.Object): second object, relative to which the\n translation will be computed.\n\n Returns:\n 3D Vector with relative translation (in OpenGL coordinates)\n " v = (obj1.matrix_world.to_translation() - obj2.matrix_world.to_translation()) rot = obj2.matrix_world.to_3x3().normalized() return (rot.inverted() @ v)
Get the relative translation between two objects in terms of the second object's coordinate system. Note that the second object will be default initialized to the scene's camera. Args: obj1 (bpy.types.Object): first object obj2 (bpy.types.Object): second object, relative to which the translation will be computed. Returns: 3D Vector with relative translation (in OpenGL coordinates)
src/amira_blender_rendering/math/geometry.py
get_relative_translation
patrickkesper/amira_blender_rendering
26
python
def get_relative_translation(obj1: bpy.types.Object, obj2: bpy.types.Object=bpy.context.scene.camera) -> Vector: "Get the relative translation between two objects in terms of the second\n object's coordinate system. Note that the second object will be default\n initialized to the scene's camera.\n\n Args:\n obj1 (bpy.types.Object): first object\n obj2 (bpy.types.Object): second object, relative to which the\n translation will be computed.\n\n Returns:\n 3D Vector with relative translation (in OpenGL coordinates)\n " v = (obj1.matrix_world.to_translation() - obj2.matrix_world.to_translation()) rot = obj2.matrix_world.to_3x3().normalized() return (rot.inverted() @ v)
def get_relative_translation(obj1: bpy.types.Object, obj2: bpy.types.Object=bpy.context.scene.camera) -> Vector: "Get the relative translation between two objects in terms of the second\n object's coordinate system. Note that the second object will be default\n initialized to the scene's camera.\n\n Args:\n obj1 (bpy.types.Object): first object\n obj2 (bpy.types.Object): second object, relative to which the\n translation will be computed.\n\n Returns:\n 3D Vector with relative translation (in OpenGL coordinates)\n " v = (obj1.matrix_world.to_translation() - obj2.matrix_world.to_translation()) rot = obj2.matrix_world.to_3x3().normalized() return (rot.inverted() @ v)<|docstring|>Get the relative translation between two objects in terms of the second object's coordinate system. Note that the second object will be default initialized to the scene's camera. Args: obj1 (bpy.types.Object): first object obj2 (bpy.types.Object): second object, relative to which the translation will be computed. Returns: 3D Vector with relative translation (in OpenGL coordinates)<|endoftext|>
34f00b2bf25d5ccea9b8a13e879a6dfe960edae5fa47a3c6fa6159f685065048
def get_relative_transform(obj1: bpy.types.Object, obj2: bpy.types.Object=bpy.context.scene.camera): "Get the relative transform between obj1 and obj2 in obj2's coordinate\n frame.\n\n Args:\n obj1 (bpy.types.Object): first object\n obj2 (bpy.types.Object): second object, relative to which the\n transform will be computed.\n\n Returns:\n tuple containing the translation and rotation between obj1 and obj2\n (relative to obj2)\n\n " t = get_relative_translation(obj1, obj2) r = get_relative_rotation(obj1, obj2) return (t, r)
Get the relative transform between obj1 and obj2 in obj2's coordinate frame. Args: obj1 (bpy.types.Object): first object obj2 (bpy.types.Object): second object, relative to which the transform will be computed. Returns: tuple containing the translation and rotation between obj1 and obj2 (relative to obj2)
src/amira_blender_rendering/math/geometry.py
get_relative_transform
patrickkesper/amira_blender_rendering
26
python
def get_relative_transform(obj1: bpy.types.Object, obj2: bpy.types.Object=bpy.context.scene.camera): "Get the relative transform between obj1 and obj2 in obj2's coordinate\n frame.\n\n Args:\n obj1 (bpy.types.Object): first object\n obj2 (bpy.types.Object): second object, relative to which the\n transform will be computed.\n\n Returns:\n tuple containing the translation and rotation between obj1 and obj2\n (relative to obj2)\n\n " t = get_relative_translation(obj1, obj2) r = get_relative_rotation(obj1, obj2) return (t, r)
def get_relative_transform(obj1: bpy.types.Object, obj2: bpy.types.Object=bpy.context.scene.camera): "Get the relative transform between obj1 and obj2 in obj2's coordinate\n frame.\n\n Args:\n obj1 (bpy.types.Object): first object\n obj2 (bpy.types.Object): second object, relative to which the\n transform will be computed.\n\n Returns:\n tuple containing the translation and rotation between obj1 and obj2\n (relative to obj2)\n\n " t = get_relative_translation(obj1, obj2) r = get_relative_rotation(obj1, obj2) return (t, r)<|docstring|>Get the relative transform between obj1 and obj2 in obj2's coordinate frame. Args: obj1 (bpy.types.Object): first object obj2 (bpy.types.Object): second object, relative to which the transform will be computed. Returns: tuple containing the translation and rotation between obj1 and obj2 (relative to obj2)<|endoftext|>
cf89d3fc00fe0519bfb8b1b14ec1048341ed878cd967ab192c69c6232897a3f0
def test_visibility(obj, cam, width, height, require_all=True): 'Test if an object is visible from a camera by projecting the bounding box\n of the object and testing if the vertices are visible from the camera or not.\n\n Note that this does not test for occlusions!\n\n Args:\n obj : Object to test visibility for\n cam : Camera object\n width : Viewport width\n height : Viewport height\n require_all: test all (True) or at least one (False) bounding box vertex\n\n Returns:\n True, if object is visible, false if not.\n ' render = bpy.context.scene.render vs = [(obj.matrix_world @ Vector(v)) for v in obj.bound_box] ps = [project_p3d(v, cam, render=render) for v in vs] if (None in ps): return False else: pxs = [p2d_to_pixel_coords(p, render=render) for p in ps] oks = [((px[0] >= 0) and (px[0] < width) and (px[1] >= 0) and (px[1] < height)) for px in pxs] return (all(oks) if require_all else any(oks))
Test if an object is visible from a camera by projecting the bounding box of the object and testing if the vertices are visible from the camera or not. Note that this does not test for occlusions! Args: obj : Object to test visibility for cam : Camera object width : Viewport width height : Viewport height require_all: test all (True) or at least one (False) bounding box vertex Returns: True, if object is visible, false if not.
src/amira_blender_rendering/math/geometry.py
test_visibility
patrickkesper/amira_blender_rendering
26
python
def test_visibility(obj, cam, width, height, require_all=True): 'Test if an object is visible from a camera by projecting the bounding box\n of the object and testing if the vertices are visible from the camera or not.\n\n Note that this does not test for occlusions!\n\n Args:\n obj : Object to test visibility for\n cam : Camera object\n width : Viewport width\n height : Viewport height\n require_all: test all (True) or at least one (False) bounding box vertex\n\n Returns:\n True, if object is visible, false if not.\n ' render = bpy.context.scene.render vs = [(obj.matrix_world @ Vector(v)) for v in obj.bound_box] ps = [project_p3d(v, cam, render=render) for v in vs] if (None in ps): return False else: pxs = [p2d_to_pixel_coords(p, render=render) for p in ps] oks = [((px[0] >= 0) and (px[0] < width) and (px[1] >= 0) and (px[1] < height)) for px in pxs] return (all(oks) if require_all else any(oks))
def test_visibility(obj, cam, width, height, require_all=True): 'Test if an object is visible from a camera by projecting the bounding box\n of the object and testing if the vertices are visible from the camera or not.\n\n Note that this does not test for occlusions!\n\n Args:\n obj : Object to test visibility for\n cam : Camera object\n width : Viewport width\n height : Viewport height\n require_all: test all (True) or at least one (False) bounding box vertex\n\n Returns:\n True, if object is visible, false if not.\n ' render = bpy.context.scene.render vs = [(obj.matrix_world @ Vector(v)) for v in obj.bound_box] ps = [project_p3d(v, cam, render=render) for v in vs] if (None in ps): return False else: pxs = [p2d_to_pixel_coords(p, render=render) for p in ps] oks = [((px[0] >= 0) and (px[0] < width) and (px[1] >= 0) and (px[1] < height)) for px in pxs] return (all(oks) if require_all else any(oks))<|docstring|>Test if an object is visible from a camera by projecting the bounding box of the object and testing if the vertices are visible from the camera or not. Note that this does not test for occlusions! Args: obj : Object to test visibility for cam : Camera object width : Viewport width height : Viewport height require_all: test all (True) or at least one (False) bounding box vertex Returns: True, if object is visible, false if not.<|endoftext|>
8bbc84aea569bd3f20064cd441ad6ca3672c5c285559a900bbf19a9a9da05d09
def test_occlusion(scene, layer, cam, obj, width, height, require_all=True, origin_offset=0.01): "Test if an object is visible or occluded by another object by checking its vertices.\n Note that this also tests if an object is visible.\n\n Args:\n scene: the scene for which to test\n layer: view layer to use for ray casting, e.g. scene.view_layers['View Layer']\n cam: camera to evaluate\n obj: object to evaluate\n width: scene render width, e.g. scene.render.resolution_x\n height: scene render height, e.g. scene.render.resolution_y\n require_all: test all vertices of the object for visibility and\n occlusion or not\n origin_offset: for ray-casting, add this offset along the ray to the\n origin. This helps to prevent numerical issues when a mesh is exactly at\n cam's location.\n\n Returns:\n True if an object is not visible or occluded, False if the object is\n visible and not occluded. Note that the returned value depends on\n argument require_all. Specifically, if require_all is set to False, then\n this function returns False if one of its vertices is visible and not\n occluded, and True if none of the vertex is visible or all are occluded.\n " dg = bpy.context.evaluated_depsgraph_get() dg.update() render = bpy.context.scene.render mesh = obj.evaluated_get(dg).to_mesh() origin = cam.matrix_world.to_translation() vs = [(obj.matrix_world @ v.co) for v in mesh.vertices] obj.to_mesh_clear() ps = [project_p3d(v, cam, render=render) for v in vs] if (None in ps): return True pxs = [p2d_to_pixel_coords(p, render=render) for p in ps] vs_visible = [((px[0] >= 0) and (px[0] < width) and (px[1] >= 0) and (px[1] < height)) for px in pxs] vs_occluded = ([False] * len(vs)) for (i, v) in enumerate(vs): direction = (v - origin) direction.normalize() local_origin = (origin + (origin_offset * direction)) try: hit_record = scene.ray_cast(layer, local_origin, direction) except TypeError: hit_record = scene.ray_cast(layer.depsgraph, local_origin, direction) hit = hit_record[0] hit_obj = hit_record[4] if (hit and (not (hit_obj.type == 'CAMERA')) and (not (hit_obj == obj))): vs_occluded[i] = True if require_all: return (not (all(vs_visible) and all([(not oc) for oc in vs_occluded]))) else: for i in range(len(vs_visible)): if (vs_visible[i] and (not vs_occluded[i])): return False return True
Test if an object is visible or occluded by another object by checking its vertices. Note that this also tests if an object is visible. Args: scene: the scene for which to test layer: view layer to use for ray casting, e.g. scene.view_layers['View Layer'] cam: camera to evaluate obj: object to evaluate width: scene render width, e.g. scene.render.resolution_x height: scene render height, e.g. scene.render.resolution_y require_all: test all vertices of the object for visibility and occlusion or not origin_offset: for ray-casting, add this offset along the ray to the origin. This helps to prevent numerical issues when a mesh is exactly at cam's location. Returns: True if an object is not visible or occluded, False if the object is visible and not occluded. Note that the returned value depends on argument require_all. Specifically, if require_all is set to False, then this function returns False if one of its vertices is visible and not occluded, and True if none of the vertex is visible or all are occluded.
src/amira_blender_rendering/math/geometry.py
test_occlusion
patrickkesper/amira_blender_rendering
26
python
def test_occlusion(scene, layer, cam, obj, width, height, require_all=True, origin_offset=0.01): "Test if an object is visible or occluded by another object by checking its vertices.\n Note that this also tests if an object is visible.\n\n Args:\n scene: the scene for which to test\n layer: view layer to use for ray casting, e.g. scene.view_layers['View Layer']\n cam: camera to evaluate\n obj: object to evaluate\n width: scene render width, e.g. scene.render.resolution_x\n height: scene render height, e.g. scene.render.resolution_y\n require_all: test all vertices of the object for visibility and\n occlusion or not\n origin_offset: for ray-casting, add this offset along the ray to the\n origin. This helps to prevent numerical issues when a mesh is exactly at\n cam's location.\n\n Returns:\n True if an object is not visible or occluded, False if the object is\n visible and not occluded. Note that the returned value depends on\n argument require_all. Specifically, if require_all is set to False, then\n this function returns False if one of its vertices is visible and not\n occluded, and True if none of the vertex is visible or all are occluded.\n " dg = bpy.context.evaluated_depsgraph_get() dg.update() render = bpy.context.scene.render mesh = obj.evaluated_get(dg).to_mesh() origin = cam.matrix_world.to_translation() vs = [(obj.matrix_world @ v.co) for v in mesh.vertices] obj.to_mesh_clear() ps = [project_p3d(v, cam, render=render) for v in vs] if (None in ps): return True pxs = [p2d_to_pixel_coords(p, render=render) for p in ps] vs_visible = [((px[0] >= 0) and (px[0] < width) and (px[1] >= 0) and (px[1] < height)) for px in pxs] vs_occluded = ([False] * len(vs)) for (i, v) in enumerate(vs): direction = (v - origin) direction.normalize() local_origin = (origin + (origin_offset * direction)) try: hit_record = scene.ray_cast(layer, local_origin, direction) except TypeError: hit_record = scene.ray_cast(layer.depsgraph, local_origin, direction) hit = hit_record[0] hit_obj = hit_record[4] if (hit and (not (hit_obj.type == 'CAMERA')) and (not (hit_obj == obj))): vs_occluded[i] = True if require_all: return (not (all(vs_visible) and all([(not oc) for oc in vs_occluded]))) else: for i in range(len(vs_visible)): if (vs_visible[i] and (not vs_occluded[i])): return False return True
def test_occlusion(scene, layer, cam, obj, width, height, require_all=True, origin_offset=0.01): "Test if an object is visible or occluded by another object by checking its vertices.\n Note that this also tests if an object is visible.\n\n Args:\n scene: the scene for which to test\n layer: view layer to use for ray casting, e.g. scene.view_layers['View Layer']\n cam: camera to evaluate\n obj: object to evaluate\n width: scene render width, e.g. scene.render.resolution_x\n height: scene render height, e.g. scene.render.resolution_y\n require_all: test all vertices of the object for visibility and\n occlusion or not\n origin_offset: for ray-casting, add this offset along the ray to the\n origin. This helps to prevent numerical issues when a mesh is exactly at\n cam's location.\n\n Returns:\n True if an object is not visible or occluded, False if the object is\n visible and not occluded. Note that the returned value depends on\n argument require_all. Specifically, if require_all is set to False, then\n this function returns False if one of its vertices is visible and not\n occluded, and True if none of the vertex is visible or all are occluded.\n " dg = bpy.context.evaluated_depsgraph_get() dg.update() render = bpy.context.scene.render mesh = obj.evaluated_get(dg).to_mesh() origin = cam.matrix_world.to_translation() vs = [(obj.matrix_world @ v.co) for v in mesh.vertices] obj.to_mesh_clear() ps = [project_p3d(v, cam, render=render) for v in vs] if (None in ps): return True pxs = [p2d_to_pixel_coords(p, render=render) for p in ps] vs_visible = [((px[0] >= 0) and (px[0] < width) and (px[1] >= 0) and (px[1] < height)) for px in pxs] vs_occluded = ([False] * len(vs)) for (i, v) in enumerate(vs): direction = (v - origin) direction.normalize() local_origin = (origin + (origin_offset * direction)) try: hit_record = scene.ray_cast(layer, local_origin, direction) except TypeError: hit_record = scene.ray_cast(layer.depsgraph, local_origin, direction) hit = hit_record[0] hit_obj = hit_record[4] if (hit and (not (hit_obj.type == 'CAMERA')) and (not (hit_obj == obj))): vs_occluded[i] = True if require_all: return (not (all(vs_visible) and all([(not oc) for oc in vs_occluded]))) else: for i in range(len(vs_visible)): if (vs_visible[i] and (not vs_occluded[i])): return False return True<|docstring|>Test if an object is visible or occluded by another object by checking its vertices. Note that this also tests if an object is visible. Args: scene: the scene for which to test layer: view layer to use for ray casting, e.g. scene.view_layers['View Layer'] cam: camera to evaluate obj: object to evaluate width: scene render width, e.g. scene.render.resolution_x height: scene render height, e.g. scene.render.resolution_y require_all: test all vertices of the object for visibility and occlusion or not origin_offset: for ray-casting, add this offset along the ray to the origin. This helps to prevent numerical issues when a mesh is exactly at cam's location. Returns: True if an object is not visible or occluded, False if the object is visible and not occluded. Note that the returned value depends on argument require_all. Specifically, if require_all is set to False, then this function returns False if one of its vertices is visible and not occluded, and True if none of the vertex is visible or all are occluded.<|endoftext|>
4a964143286e1ffde23b8043eaa3868930b52d9f920d5e1098c4e2c1eeb71805
def _get_bvh(obj): 'Get the BVH for an object\n\n Args:\n obj (variant): object to get the BVH for\n\n Returns:\n BVH for obj\n ' mat = obj.matrix_world vs = [(mat @ v.co) for v in obj.data.vertices] ps = [p.vertices for p in obj.data.polygons] return BVHTree.FromPolygons(vs, ps)
Get the BVH for an object Args: obj (variant): object to get the BVH for Returns: BVH for obj
src/amira_blender_rendering/math/geometry.py
_get_bvh
patrickkesper/amira_blender_rendering
26
python
def _get_bvh(obj): 'Get the BVH for an object\n\n Args:\n obj (variant): object to get the BVH for\n\n Returns:\n BVH for obj\n ' mat = obj.matrix_world vs = [(mat @ v.co) for v in obj.data.vertices] ps = [p.vertices for p in obj.data.polygons] return BVHTree.FromPolygons(vs, ps)
def _get_bvh(obj): 'Get the BVH for an object\n\n Args:\n obj (variant): object to get the BVH for\n\n Returns:\n BVH for obj\n ' mat = obj.matrix_world vs = [(mat @ v.co) for v in obj.data.vertices] ps = [p.vertices for p in obj.data.polygons] return BVHTree.FromPolygons(vs, ps)<|docstring|>Get the BVH for an object Args: obj (variant): object to get the BVH for Returns: BVH for obj<|endoftext|>
11e771cf578f6dd99f0fcbd7aea13e88497153ebd0d4d2e1e98ec96e37f2f5f5
def test_intersection(obj1, obj2): 'Test if two objects intersect each other\n\n Returns true if objects intersect, false if not.\n ' bvh1 = _get_bvh(obj1) bvh2 = _get_bvh(obj2) if bvh1.overlap(bvh2): return True else: return False
Test if two objects intersect each other Returns true if objects intersect, false if not.
src/amira_blender_rendering/math/geometry.py
test_intersection
patrickkesper/amira_blender_rendering
26
python
def test_intersection(obj1, obj2): 'Test if two objects intersect each other\n\n Returns true if objects intersect, false if not.\n ' bvh1 = _get_bvh(obj1) bvh2 = _get_bvh(obj2) if bvh1.overlap(bvh2): return True else: return False
def test_intersection(obj1, obj2): 'Test if two objects intersect each other\n\n Returns true if objects intersect, false if not.\n ' bvh1 = _get_bvh(obj1) bvh2 = _get_bvh(obj2) if bvh1.overlap(bvh2): return True else: return False<|docstring|>Test if two objects intersect each other Returns true if objects intersect, false if not.<|endoftext|>
d43fe7f349fcf893230c99fac816d45955a17e63ef22e4fc201f6fab0dcbf34f
def get_world_to_object_transform(cam2obj_pose: dict, camera: bpy.types.Object=bpy.context.scene.camera): "\n Transform a pose {'R', 't'} expressed in camera coordinates to world coordinates\n\n Args:\n cam2obj_pose(dict): {\n 'R'(np.array(3)) : rotation matrix from camera to obj\n 't'(np.array(3,) : translation vector from camera to obh\n }\n camera(bpq.types.Object): scene camera\n\n Returns:\n {'R','t'} where\n R(np.array(3)): rotation matrix from world frame to object\n t(np.array(3,)): translation vector from world frame to object\n " M_c2o = np.eye(4) M_c2o[(:3, :3)] = cam2obj_pose['R'] M_c2o[(:3, 3)] = cam2obj_pose['t'] M_w2c = np.eye(4) M_w2c[(:3, :3)] = camera.matrix_world.to_3x3().normalized() M_w2c[(:3, 3)] = camera.matrix_world.to_translation() M_w2o = M_w2c.dot(M_c2o) R = M_w2o[(:3, :3)] t = M_w2o[(:3, 3)] return {'R': R, 't': t}
Transform a pose {'R', 't'} expressed in camera coordinates to world coordinates Args: cam2obj_pose(dict): { 'R'(np.array(3)) : rotation matrix from camera to obj 't'(np.array(3,) : translation vector from camera to obh } camera(bpq.types.Object): scene camera Returns: {'R','t'} where R(np.array(3)): rotation matrix from world frame to object t(np.array(3,)): translation vector from world frame to object
src/amira_blender_rendering/math/geometry.py
get_world_to_object_transform
patrickkesper/amira_blender_rendering
26
python
def get_world_to_object_transform(cam2obj_pose: dict, camera: bpy.types.Object=bpy.context.scene.camera): "\n Transform a pose {'R', 't'} expressed in camera coordinates to world coordinates\n\n Args:\n cam2obj_pose(dict): {\n 'R'(np.array(3)) : rotation matrix from camera to obj\n 't'(np.array(3,) : translation vector from camera to obh\n }\n camera(bpq.types.Object): scene camera\n\n Returns:\n {'R','t'} where\n R(np.array(3)): rotation matrix from world frame to object\n t(np.array(3,)): translation vector from world frame to object\n " M_c2o = np.eye(4) M_c2o[(:3, :3)] = cam2obj_pose['R'] M_c2o[(:3, 3)] = cam2obj_pose['t'] M_w2c = np.eye(4) M_w2c[(:3, :3)] = camera.matrix_world.to_3x3().normalized() M_w2c[(:3, 3)] = camera.matrix_world.to_translation() M_w2o = M_w2c.dot(M_c2o) R = M_w2o[(:3, :3)] t = M_w2o[(:3, 3)] return {'R': R, 't': t}
def get_world_to_object_transform(cam2obj_pose: dict, camera: bpy.types.Object=bpy.context.scene.camera): "\n Transform a pose {'R', 't'} expressed in camera coordinates to world coordinates\n\n Args:\n cam2obj_pose(dict): {\n 'R'(np.array(3)) : rotation matrix from camera to obj\n 't'(np.array(3,) : translation vector from camera to obh\n }\n camera(bpq.types.Object): scene camera\n\n Returns:\n {'R','t'} where\n R(np.array(3)): rotation matrix from world frame to object\n t(np.array(3,)): translation vector from world frame to object\n " M_c2o = np.eye(4) M_c2o[(:3, :3)] = cam2obj_pose['R'] M_c2o[(:3, 3)] = cam2obj_pose['t'] M_w2c = np.eye(4) M_w2c[(:3, :3)] = camera.matrix_world.to_3x3().normalized() M_w2c[(:3, 3)] = camera.matrix_world.to_translation() M_w2o = M_w2c.dot(M_c2o) R = M_w2o[(:3, :3)] t = M_w2o[(:3, 3)] return {'R': R, 't': t}<|docstring|>Transform a pose {'R', 't'} expressed in camera coordinates to world coordinates Args: cam2obj_pose(dict): { 'R'(np.array(3)) : rotation matrix from camera to obj 't'(np.array(3,) : translation vector from camera to obh } camera(bpq.types.Object): scene camera Returns: {'R','t'} where R(np.array(3)): rotation matrix from world frame to object t(np.array(3,)): translation vector from world frame to object<|endoftext|>
5f9a8236d2aa27250fb9836244505d55ed15518eb728809c7d226d263cc99258
def gl2cv(R, t): 'Convert transform from OpenGL to OpenCV\n\n Args:\n R(np.array(3,3): rotation matrix\n t(np.array(3,): translation vector\n Returns:\n R_cv\n t_cv\n ' M_gl = np.eye(4) M_gl[(:3, :3)] = R M_gl[(:3, 3)] = t Ccv_Cgl = np.array([[1, 0, 0, 0], [0, (- 1), 0, 0], [0, 0, (- 1), 0], [0, 0, 0, 1]]) Cgl_W = (Ccv_Cgl @ M_gl) return (Cgl_W[(:3, :3)], Cgl_W[(:3, 3)])
Convert transform from OpenGL to OpenCV Args: R(np.array(3,3): rotation matrix t(np.array(3,): translation vector Returns: R_cv t_cv
src/amira_blender_rendering/math/geometry.py
gl2cv
patrickkesper/amira_blender_rendering
26
python
def gl2cv(R, t): 'Convert transform from OpenGL to OpenCV\n\n Args:\n R(np.array(3,3): rotation matrix\n t(np.array(3,): translation vector\n Returns:\n R_cv\n t_cv\n ' M_gl = np.eye(4) M_gl[(:3, :3)] = R M_gl[(:3, 3)] = t Ccv_Cgl = np.array([[1, 0, 0, 0], [0, (- 1), 0, 0], [0, 0, (- 1), 0], [0, 0, 0, 1]]) Cgl_W = (Ccv_Cgl @ M_gl) return (Cgl_W[(:3, :3)], Cgl_W[(:3, 3)])
def gl2cv(R, t): 'Convert transform from OpenGL to OpenCV\n\n Args:\n R(np.array(3,3): rotation matrix\n t(np.array(3,): translation vector\n Returns:\n R_cv\n t_cv\n ' M_gl = np.eye(4) M_gl[(:3, :3)] = R M_gl[(:3, 3)] = t Ccv_Cgl = np.array([[1, 0, 0, 0], [0, (- 1), 0, 0], [0, 0, (- 1), 0], [0, 0, 0, 1]]) Cgl_W = (Ccv_Cgl @ M_gl) return (Cgl_W[(:3, :3)], Cgl_W[(:3, 3)])<|docstring|>Convert transform from OpenGL to OpenCV Args: R(np.array(3,3): rotation matrix t(np.array(3,): translation vector Returns: R_cv t_cv<|endoftext|>
e7ac1f6bb22e772bd0ff10029f438dd3d2c5c855f6ecfc8c9ead6fa00c052cc1
def euler_x_to_matrix(angle): 'Get rotation matrix from euler angle rotation around X.' return np.array([[1, 0, 0], [0, np.cos(angle), (- np.sin(angle))], [0, np.sin(angle), np.cos(angle)]])
Get rotation matrix from euler angle rotation around X.
src/amira_blender_rendering/math/geometry.py
euler_x_to_matrix
patrickkesper/amira_blender_rendering
26
python
def euler_x_to_matrix(angle): return np.array([[1, 0, 0], [0, np.cos(angle), (- np.sin(angle))], [0, np.sin(angle), np.cos(angle)]])
def euler_x_to_matrix(angle): return np.array([[1, 0, 0], [0, np.cos(angle), (- np.sin(angle))], [0, np.sin(angle), np.cos(angle)]])<|docstring|>Get rotation matrix from euler angle rotation around X.<|endoftext|>
370140bf30a73c4c1f035e4db5a09d7c6b2c2cbae28beef21d50aab2b9e34bed
def euler_y_to_matrix(angle): 'Get rotation matrix from euler angle rotation around Y.' return np.array([[np.cos(angle), 0, np.sin(angle)], [0, 1, 0], [(- np.sin(angle)), 0, np.cos(angle)]])
Get rotation matrix from euler angle rotation around Y.
src/amira_blender_rendering/math/geometry.py
euler_y_to_matrix
patrickkesper/amira_blender_rendering
26
python
def euler_y_to_matrix(angle): return np.array([[np.cos(angle), 0, np.sin(angle)], [0, 1, 0], [(- np.sin(angle)), 0, np.cos(angle)]])
def euler_y_to_matrix(angle): return np.array([[np.cos(angle), 0, np.sin(angle)], [0, 1, 0], [(- np.sin(angle)), 0, np.cos(angle)]])<|docstring|>Get rotation matrix from euler angle rotation around Y.<|endoftext|>
827d2d0f4a55c4ee05dacb1be556864652620060579fecb142ee7ef5a1d64a4c
def euler_z_to_matrix(angle): 'Get rotation matrix from euler angle rotation around Z.' return np.array([[np.cos(angle), (- np.sin(angle)), 0], [np.sin(angle), np.cos(angle), 0], [0, 0, 1]])
Get rotation matrix from euler angle rotation around Z.
src/amira_blender_rendering/math/geometry.py
euler_z_to_matrix
patrickkesper/amira_blender_rendering
26
python
def euler_z_to_matrix(angle): return np.array([[np.cos(angle), (- np.sin(angle)), 0], [np.sin(angle), np.cos(angle), 0], [0, 0, 1]])
def euler_z_to_matrix(angle): return np.array([[np.cos(angle), (- np.sin(angle)), 0], [np.sin(angle), np.cos(angle), 0], [0, 0, 1]])<|docstring|>Get rotation matrix from euler angle rotation around Z.<|endoftext|>
77d4f7f0503691f05efb5c412890ae685a24cc4b6f5dd06e870e97a5f5fa5929
def rotation_matrix(alpha, axis, homogeneous=False): 'Euler rotation matrices\n\n Args:\n alpha (float): angle in radians\n axis (str): x/y/z\n homogeneous (bool): output homogeneous coordinates\n\n Returns:\n rotation matrix\n\n ' axis = axis.lower() if (axis == 'x'): rot = euler_x_to_matrix(alpha) elif (axis == 'y'): rot = euler_y_to_matrix(alpha) elif (axis == 'z'): rot = euler_z_to_matrix(alpha) else: get_logger().error('Axis needs to be x/y/z!') raise ValueError if (homogeneous is True): h = np.eye(4) h[(:3, :3)] = rot return h else: return rot
Euler rotation matrices Args: alpha (float): angle in radians axis (str): x/y/z homogeneous (bool): output homogeneous coordinates Returns: rotation matrix
src/amira_blender_rendering/math/geometry.py
rotation_matrix
patrickkesper/amira_blender_rendering
26
python
def rotation_matrix(alpha, axis, homogeneous=False): 'Euler rotation matrices\n\n Args:\n alpha (float): angle in radians\n axis (str): x/y/z\n homogeneous (bool): output homogeneous coordinates\n\n Returns:\n rotation matrix\n\n ' axis = axis.lower() if (axis == 'x'): rot = euler_x_to_matrix(alpha) elif (axis == 'y'): rot = euler_y_to_matrix(alpha) elif (axis == 'z'): rot = euler_z_to_matrix(alpha) else: get_logger().error('Axis needs to be x/y/z!') raise ValueError if (homogeneous is True): h = np.eye(4) h[(:3, :3)] = rot return h else: return rot
def rotation_matrix(alpha, axis, homogeneous=False): 'Euler rotation matrices\n\n Args:\n alpha (float): angle in radians\n axis (str): x/y/z\n homogeneous (bool): output homogeneous coordinates\n\n Returns:\n rotation matrix\n\n ' axis = axis.lower() if (axis == 'x'): rot = euler_x_to_matrix(alpha) elif (axis == 'y'): rot = euler_y_to_matrix(alpha) elif (axis == 'z'): rot = euler_z_to_matrix(alpha) else: get_logger().error('Axis needs to be x/y/z!') raise ValueError if (homogeneous is True): h = np.eye(4) h[(:3, :3)] = rot return h else: return rot<|docstring|>Euler rotation matrices Args: alpha (float): angle in radians axis (str): x/y/z homogeneous (bool): output homogeneous coordinates Returns: rotation matrix<|endoftext|>
e3c16004a969596eb2091db3f83c63374651373a394f0606b3a0d38013c97189
def rotation_matrix_to_quaternion(rot_mat, isprecise=False): '\n Computes the quaternion (with convention WXYZ) out of a given rotation matrix\n Inverse funtion of quaternion_to_rotation_matrix\n\n Parameters\n ----------\n :param rot_mat: np.array of shape (3, 3)\n\n Returns\n -------\n :return q: np.array of shape (4,), quaternion (WXYZ) corresponding to the rotation matrix rot_mat\n \n NOTE: the implementation comes from a mixture of codes. Inspiration is taken from Wikipedia and\n \n Homogeneous Transformation Matrices and Quaternions library\n :Author:\n `Christoph Gohlke <http://www.lfd.uci.edu/~gohlke/>`_\n ' if isprecise: trace = max(np.trace(rot_mat), (- 1.0)) qs = min((np.sqrt((trace + 1)) / 2.0), 1.0) kx = (rot_mat[(2, 1)] - rot_mat[(1, 2)]) ky = (rot_mat[(0, 2)] - rot_mat[(2, 0)]) kz = (rot_mat[(1, 0)] - rot_mat[(0, 1)]) if ((rot_mat[(0, 0)] >= rot_mat[(1, 1)]) and (rot_mat[(0, 0)] >= rot_mat[(2, 2)])): kx1 = (((rot_mat[(0, 0)] - rot_mat[(1, 1)]) - rot_mat[(2, 2)]) + 1) ky1 = (rot_mat[(1, 0)] + rot_mat[(0, 1)]) kz1 = (rot_mat[(2, 0)] + rot_mat[(0, 2)]) add = (kx >= 0) elif (rot_mat[(1, 1)] >= rot_mat[(2, 2)]): kx1 = (rot_mat[(1, 0)] + rot_mat[(0, 1)]) ky1 = (((rot_mat[(1, 1)] - rot_mat[(0, 0)]) - rot_mat[(2, 2)]) + 1) kz1 = (rot_mat[(2, 1)] + rot_mat[(1, 2)]) add = (ky >= 0) else: kx1 = (rot_mat[(2, 0)] + rot_mat[(0, 2)]) ky1 = (rot_mat[(2, 1)] + rot_mat[(1, 2)]) kz1 = (((rot_mat[(2, 2)] - rot_mat[(0, 0)]) - rot_mat[(1, 1)]) + 1) add = (kz >= 0) if add: kx = (kx + kx1) ky = (ky + ky1) kz = (kz + kz1) else: kx = (kx - kx1) ky = (ky - ky1) kz = (kz - kz1) nm = np.linalg.norm(np.array([kx, ky, kz])) if (nm == 0): q = np.array([1.0, 0.0, 0.0, 0.0]) else: s = (np.sqrt((1 - (qs ** 2))) / nm) qv = (s * np.array([kx, ky, kz])) q = np.append(qs, qv) else: m00 = rot_mat[(0, 0)] m01 = rot_mat[(0, 1)] m02 = rot_mat[(0, 2)] m10 = rot_mat[(1, 0)] m11 = rot_mat[(1, 1)] m12 = rot_mat[(1, 2)] m20 = rot_mat[(2, 0)] m21 = rot_mat[(2, 1)] m22 = rot_mat[(2, 2)] K = np.array([[((m00 - m11) - m22), 0.0, 0.0, 0.0], [(m01 + m10), ((m11 - m00) - m22), 0.0, 0.0], [(m02 + m20), (m12 + m21), ((m22 - m00) - m11), 0.0], [(m21 - m12), (m02 - m20), (m10 - m01), ((m00 + m11) + m22)]]) K /= 3.0 (w, V) = np.linalg.eigh(K) q = V[([3, 0, 1, 2], np.argmax(w))] if (q[0] < 0.0): np.negative(q, q) return q
Computes the quaternion (with convention WXYZ) out of a given rotation matrix Inverse funtion of quaternion_to_rotation_matrix Parameters ---------- :param rot_mat: np.array of shape (3, 3) Returns ------- :return q: np.array of shape (4,), quaternion (WXYZ) corresponding to the rotation matrix rot_mat NOTE: the implementation comes from a mixture of codes. Inspiration is taken from Wikipedia and Homogeneous Transformation Matrices and Quaternions library :Author: `Christoph Gohlke <http://www.lfd.uci.edu/~gohlke/>`_
src/amira_blender_rendering/math/geometry.py
rotation_matrix_to_quaternion
patrickkesper/amira_blender_rendering
26
python
def rotation_matrix_to_quaternion(rot_mat, isprecise=False): '\n Computes the quaternion (with convention WXYZ) out of a given rotation matrix\n Inverse funtion of quaternion_to_rotation_matrix\n\n Parameters\n ----------\n :param rot_mat: np.array of shape (3, 3)\n\n Returns\n -------\n :return q: np.array of shape (4,), quaternion (WXYZ) corresponding to the rotation matrix rot_mat\n \n NOTE: the implementation comes from a mixture of codes. Inspiration is taken from Wikipedia and\n \n Homogeneous Transformation Matrices and Quaternions library\n :Author:\n `Christoph Gohlke <http://www.lfd.uci.edu/~gohlke/>`_\n ' if isprecise: trace = max(np.trace(rot_mat), (- 1.0)) qs = min((np.sqrt((trace + 1)) / 2.0), 1.0) kx = (rot_mat[(2, 1)] - rot_mat[(1, 2)]) ky = (rot_mat[(0, 2)] - rot_mat[(2, 0)]) kz = (rot_mat[(1, 0)] - rot_mat[(0, 1)]) if ((rot_mat[(0, 0)] >= rot_mat[(1, 1)]) and (rot_mat[(0, 0)] >= rot_mat[(2, 2)])): kx1 = (((rot_mat[(0, 0)] - rot_mat[(1, 1)]) - rot_mat[(2, 2)]) + 1) ky1 = (rot_mat[(1, 0)] + rot_mat[(0, 1)]) kz1 = (rot_mat[(2, 0)] + rot_mat[(0, 2)]) add = (kx >= 0) elif (rot_mat[(1, 1)] >= rot_mat[(2, 2)]): kx1 = (rot_mat[(1, 0)] + rot_mat[(0, 1)]) ky1 = (((rot_mat[(1, 1)] - rot_mat[(0, 0)]) - rot_mat[(2, 2)]) + 1) kz1 = (rot_mat[(2, 1)] + rot_mat[(1, 2)]) add = (ky >= 0) else: kx1 = (rot_mat[(2, 0)] + rot_mat[(0, 2)]) ky1 = (rot_mat[(2, 1)] + rot_mat[(1, 2)]) kz1 = (((rot_mat[(2, 2)] - rot_mat[(0, 0)]) - rot_mat[(1, 1)]) + 1) add = (kz >= 0) if add: kx = (kx + kx1) ky = (ky + ky1) kz = (kz + kz1) else: kx = (kx - kx1) ky = (ky - ky1) kz = (kz - kz1) nm = np.linalg.norm(np.array([kx, ky, kz])) if (nm == 0): q = np.array([1.0, 0.0, 0.0, 0.0]) else: s = (np.sqrt((1 - (qs ** 2))) / nm) qv = (s * np.array([kx, ky, kz])) q = np.append(qs, qv) else: m00 = rot_mat[(0, 0)] m01 = rot_mat[(0, 1)] m02 = rot_mat[(0, 2)] m10 = rot_mat[(1, 0)] m11 = rot_mat[(1, 1)] m12 = rot_mat[(1, 2)] m20 = rot_mat[(2, 0)] m21 = rot_mat[(2, 1)] m22 = rot_mat[(2, 2)] K = np.array([[((m00 - m11) - m22), 0.0, 0.0, 0.0], [(m01 + m10), ((m11 - m00) - m22), 0.0, 0.0], [(m02 + m20), (m12 + m21), ((m22 - m00) - m11), 0.0], [(m21 - m12), (m02 - m20), (m10 - m01), ((m00 + m11) + m22)]]) K /= 3.0 (w, V) = np.linalg.eigh(K) q = V[([3, 0, 1, 2], np.argmax(w))] if (q[0] < 0.0): np.negative(q, q) return q
def rotation_matrix_to_quaternion(rot_mat, isprecise=False): '\n Computes the quaternion (with convention WXYZ) out of a given rotation matrix\n Inverse funtion of quaternion_to_rotation_matrix\n\n Parameters\n ----------\n :param rot_mat: np.array of shape (3, 3)\n\n Returns\n -------\n :return q: np.array of shape (4,), quaternion (WXYZ) corresponding to the rotation matrix rot_mat\n \n NOTE: the implementation comes from a mixture of codes. Inspiration is taken from Wikipedia and\n \n Homogeneous Transformation Matrices and Quaternions library\n :Author:\n `Christoph Gohlke <http://www.lfd.uci.edu/~gohlke/>`_\n ' if isprecise: trace = max(np.trace(rot_mat), (- 1.0)) qs = min((np.sqrt((trace + 1)) / 2.0), 1.0) kx = (rot_mat[(2, 1)] - rot_mat[(1, 2)]) ky = (rot_mat[(0, 2)] - rot_mat[(2, 0)]) kz = (rot_mat[(1, 0)] - rot_mat[(0, 1)]) if ((rot_mat[(0, 0)] >= rot_mat[(1, 1)]) and (rot_mat[(0, 0)] >= rot_mat[(2, 2)])): kx1 = (((rot_mat[(0, 0)] - rot_mat[(1, 1)]) - rot_mat[(2, 2)]) + 1) ky1 = (rot_mat[(1, 0)] + rot_mat[(0, 1)]) kz1 = (rot_mat[(2, 0)] + rot_mat[(0, 2)]) add = (kx >= 0) elif (rot_mat[(1, 1)] >= rot_mat[(2, 2)]): kx1 = (rot_mat[(1, 0)] + rot_mat[(0, 1)]) ky1 = (((rot_mat[(1, 1)] - rot_mat[(0, 0)]) - rot_mat[(2, 2)]) + 1) kz1 = (rot_mat[(2, 1)] + rot_mat[(1, 2)]) add = (ky >= 0) else: kx1 = (rot_mat[(2, 0)] + rot_mat[(0, 2)]) ky1 = (rot_mat[(2, 1)] + rot_mat[(1, 2)]) kz1 = (((rot_mat[(2, 2)] - rot_mat[(0, 0)]) - rot_mat[(1, 1)]) + 1) add = (kz >= 0) if add: kx = (kx + kx1) ky = (ky + ky1) kz = (kz + kz1) else: kx = (kx - kx1) ky = (ky - ky1) kz = (kz - kz1) nm = np.linalg.norm(np.array([kx, ky, kz])) if (nm == 0): q = np.array([1.0, 0.0, 0.0, 0.0]) else: s = (np.sqrt((1 - (qs ** 2))) / nm) qv = (s * np.array([kx, ky, kz])) q = np.append(qs, qv) else: m00 = rot_mat[(0, 0)] m01 = rot_mat[(0, 1)] m02 = rot_mat[(0, 2)] m10 = rot_mat[(1, 0)] m11 = rot_mat[(1, 1)] m12 = rot_mat[(1, 2)] m20 = rot_mat[(2, 0)] m21 = rot_mat[(2, 1)] m22 = rot_mat[(2, 2)] K = np.array([[((m00 - m11) - m22), 0.0, 0.0, 0.0], [(m01 + m10), ((m11 - m00) - m22), 0.0, 0.0], [(m02 + m20), (m12 + m21), ((m22 - m00) - m11), 0.0], [(m21 - m12), (m02 - m20), (m10 - m01), ((m00 + m11) + m22)]]) K /= 3.0 (w, V) = np.linalg.eigh(K) q = V[([3, 0, 1, 2], np.argmax(w))] if (q[0] < 0.0): np.negative(q, q) return q<|docstring|>Computes the quaternion (with convention WXYZ) out of a given rotation matrix Inverse funtion of quaternion_to_rotation_matrix Parameters ---------- :param rot_mat: np.array of shape (3, 3) Returns ------- :return q: np.array of shape (4,), quaternion (WXYZ) corresponding to the rotation matrix rot_mat NOTE: the implementation comes from a mixture of codes. Inspiration is taken from Wikipedia and Homogeneous Transformation Matrices and Quaternions library :Author: `Christoph Gohlke <http://www.lfd.uci.edu/~gohlke/>`_<|endoftext|>
3f43b2fbc95fa0bb467130c106484fc01f64b64f6b68c4e0e210f54054625577
def file(path_or_f): '\n Verifies that a file exists at a given path and that the file has a\n known extension type.\n\n :Parameters:\n path : `str`\n the path to a dump file\n\n ' if hasattr(path_or_f, 'readline'): return path_or_f else: path = path_or_f path = os.path.expanduser(path) if (not os.path.isfile(path)): raise FileTypeError(("Can't find file %s" % path)) match = EXT_RE.search(path) if (match is None): raise FileTypeError(('No extension found for %s.' % path)) elif (match.groups()[0] not in EXTENSIONS): raise FileTypeError(('File type %r is not supported.' % path)) else: return path
Verifies that a file exists at a given path and that the file has a known extension type. :Parameters: path : `str` the path to a dump file
mw/xml_dump/functions.py
file
makoshark/Mediawiki-Utilities
23
python
def file(path_or_f): '\n Verifies that a file exists at a given path and that the file has a\n known extension type.\n\n :Parameters:\n path : `str`\n the path to a dump file\n\n ' if hasattr(path_or_f, 'readline'): return path_or_f else: path = path_or_f path = os.path.expanduser(path) if (not os.path.isfile(path)): raise FileTypeError(("Can't find file %s" % path)) match = EXT_RE.search(path) if (match is None): raise FileTypeError(('No extension found for %s.' % path)) elif (match.groups()[0] not in EXTENSIONS): raise FileTypeError(('File type %r is not supported.' % path)) else: return path
def file(path_or_f): '\n Verifies that a file exists at a given path and that the file has a\n known extension type.\n\n :Parameters:\n path : `str`\n the path to a dump file\n\n ' if hasattr(path_or_f, 'readline'): return path_or_f else: path = path_or_f path = os.path.expanduser(path) if (not os.path.isfile(path)): raise FileTypeError(("Can't find file %s" % path)) match = EXT_RE.search(path) if (match is None): raise FileTypeError(('No extension found for %s.' % path)) elif (match.groups()[0] not in EXTENSIONS): raise FileTypeError(('File type %r is not supported.' % path)) else: return path<|docstring|>Verifies that a file exists at a given path and that the file has a known extension type. :Parameters: path : `str` the path to a dump file<|endoftext|>
375c3bffc54dffe0a4e7e45ab8246ee19ede06f73d980df9a45a6d4b638fcf94
def open_file(path_or_f): '\n Turns a path to a dump file into a file-like object of (decompressed)\n XML data.\n\n :Parameters:\n path : `str`\n the path to the dump file to read\n ' if hasattr(path_or_f, 'read'): return path_or_f else: path = path_or_f match = EXT_RE.search(path) ext = match.groups()[0] p = subprocess.Popen((EXTENSIONS[ext] + [path]), stdout=subprocess.PIPE, stderr=open(os.devnull, 'w')) return p.stdout
Turns a path to a dump file into a file-like object of (decompressed) XML data. :Parameters: path : `str` the path to the dump file to read
mw/xml_dump/functions.py
open_file
makoshark/Mediawiki-Utilities
23
python
def open_file(path_or_f): '\n Turns a path to a dump file into a file-like object of (decompressed)\n XML data.\n\n :Parameters:\n path : `str`\n the path to the dump file to read\n ' if hasattr(path_or_f, 'read'): return path_or_f else: path = path_or_f match = EXT_RE.search(path) ext = match.groups()[0] p = subprocess.Popen((EXTENSIONS[ext] + [path]), stdout=subprocess.PIPE, stderr=open(os.devnull, 'w')) return p.stdout
def open_file(path_or_f): '\n Turns a path to a dump file into a file-like object of (decompressed)\n XML data.\n\n :Parameters:\n path : `str`\n the path to the dump file to read\n ' if hasattr(path_or_f, 'read'): return path_or_f else: path = path_or_f match = EXT_RE.search(path) ext = match.groups()[0] p = subprocess.Popen((EXTENSIONS[ext] + [path]), stdout=subprocess.PIPE, stderr=open(os.devnull, 'w')) return p.stdout<|docstring|>Turns a path to a dump file into a file-like object of (decompressed) XML data. :Parameters: path : `str` the path to the dump file to read<|endoftext|>
f628b0ad334baf93f540c988d22f34360604b58e1c1bbe3d0bd27877d940f5a6
def append_new_entries(rsc_src: str, restore_new: dict, vocab_new: Dict[(str, int)]): '\n ๊ธฐ๋ถ„์„ ์‚ฌ์ „ ๋นŒ๋“œ ์ค‘์— ์ƒˆ๋กœ ์ถ”๊ฐ€๊ฐ€ ํ•„์š”ํ•œ ์‚ฌ์ „ ์—”ํŠธ๋ฆฌ๋ฅผ ํ•ด๋‹น ์‚ฌ์ „์— ์ถ”๊ฐ€ํ•œ๋‹ค.\n Args:\n rsc_src: ๋ฆฌ์Šค์†Œ ๋””๋ ‰ํ† ๋ฆฌ\n restore_new: ์›ํ˜•๋ณต์› ์‚ฌ์ „์˜ ์ถ”๊ฐ€ํ•  ์—”ํŠธ๋ฆฌ\n vocab_new: ์ถœ๋ ฅ ํƒœ๊ทธ vocabulary์— ์ถ”๊ฐ€ํ•  ์—”ํŠธ๋ฆฌ\n ' if restore_new: with open('{}/restore.dic'.format(rsc_src), 'a', encoding='UTF-8') as fout: for ((char, tag_out), tag_num_mrp_chr_dic) in restore_new.items(): for (tag_num, mrp_chr) in tag_num_mrp_chr_dic.items(): new_entry_str = '{}/{}:{}\t{}'.format(char, tag_out, tag_num, mrp_chr) logging.info('[RESTORE] %s', new_entry_str) print(new_entry_str, file=fout) if vocab_new: with open('{}/vocab.out.more'.format(rsc_src), 'a', encoding='UTF-8') as fout: new_tags = sorted([(num, tag) for (tag, num) in vocab_new.items()]) for (_, tag) in new_tags: logging.info('[TAG] %s', tag) print(tag, file=fout)
๊ธฐ๋ถ„์„ ์‚ฌ์ „ ๋นŒ๋“œ ์ค‘์— ์ƒˆ๋กœ ์ถ”๊ฐ€๊ฐ€ ํ•„์š”ํ•œ ์‚ฌ์ „ ์—”ํŠธ๋ฆฌ๋ฅผ ํ•ด๋‹น ์‚ฌ์ „์— ์ถ”๊ฐ€ํ•œ๋‹ค. Args: rsc_src: ๋ฆฌ์Šค์†Œ ๋””๋ ‰ํ† ๋ฆฌ restore_new: ์›ํ˜•๋ณต์› ์‚ฌ์ „์˜ ์ถ”๊ฐ€ํ•  ์—”ํŠธ๋ฆฌ vocab_new: ์ถœ๋ ฅ ํƒœ๊ทธ vocabulary์— ์ถ”๊ฐ€ํ•  ์—”ํŠธ๋ฆฌ
rsc/bin/compile_restore.py
append_new_entries
juntf/khaiii
1,235
python
def append_new_entries(rsc_src: str, restore_new: dict, vocab_new: Dict[(str, int)]): '\n ๊ธฐ๋ถ„์„ ์‚ฌ์ „ ๋นŒ๋“œ ์ค‘์— ์ƒˆ๋กœ ์ถ”๊ฐ€๊ฐ€ ํ•„์š”ํ•œ ์‚ฌ์ „ ์—”ํŠธ๋ฆฌ๋ฅผ ํ•ด๋‹น ์‚ฌ์ „์— ์ถ”๊ฐ€ํ•œ๋‹ค.\n Args:\n rsc_src: ๋ฆฌ์Šค์†Œ ๋””๋ ‰ํ† ๋ฆฌ\n restore_new: ์›ํ˜•๋ณต์› ์‚ฌ์ „์˜ ์ถ”๊ฐ€ํ•  ์—”ํŠธ๋ฆฌ\n vocab_new: ์ถœ๋ ฅ ํƒœ๊ทธ vocabulary์— ์ถ”๊ฐ€ํ•  ์—”ํŠธ๋ฆฌ\n ' if restore_new: with open('{}/restore.dic'.format(rsc_src), 'a', encoding='UTF-8') as fout: for ((char, tag_out), tag_num_mrp_chr_dic) in restore_new.items(): for (tag_num, mrp_chr) in tag_num_mrp_chr_dic.items(): new_entry_str = '{}/{}:{}\t{}'.format(char, tag_out, tag_num, mrp_chr) logging.info('[RESTORE] %s', new_entry_str) print(new_entry_str, file=fout) if vocab_new: with open('{}/vocab.out.more'.format(rsc_src), 'a', encoding='UTF-8') as fout: new_tags = sorted([(num, tag) for (tag, num) in vocab_new.items()]) for (_, tag) in new_tags: logging.info('[TAG] %s', tag) print(tag, file=fout)
def append_new_entries(rsc_src: str, restore_new: dict, vocab_new: Dict[(str, int)]): '\n ๊ธฐ๋ถ„์„ ์‚ฌ์ „ ๋นŒ๋“œ ์ค‘์— ์ƒˆ๋กœ ์ถ”๊ฐ€๊ฐ€ ํ•„์š”ํ•œ ์‚ฌ์ „ ์—”ํŠธ๋ฆฌ๋ฅผ ํ•ด๋‹น ์‚ฌ์ „์— ์ถ”๊ฐ€ํ•œ๋‹ค.\n Args:\n rsc_src: ๋ฆฌ์Šค์†Œ ๋””๋ ‰ํ† ๋ฆฌ\n restore_new: ์›ํ˜•๋ณต์› ์‚ฌ์ „์˜ ์ถ”๊ฐ€ํ•  ์—”ํŠธ๋ฆฌ\n vocab_new: ์ถœ๋ ฅ ํƒœ๊ทธ vocabulary์— ์ถ”๊ฐ€ํ•  ์—”ํŠธ๋ฆฌ\n ' if restore_new: with open('{}/restore.dic'.format(rsc_src), 'a', encoding='UTF-8') as fout: for ((char, tag_out), tag_num_mrp_chr_dic) in restore_new.items(): for (tag_num, mrp_chr) in tag_num_mrp_chr_dic.items(): new_entry_str = '{}/{}:{}\t{}'.format(char, tag_out, tag_num, mrp_chr) logging.info('[RESTORE] %s', new_entry_str) print(new_entry_str, file=fout) if vocab_new: with open('{}/vocab.out.more'.format(rsc_src), 'a', encoding='UTF-8') as fout: new_tags = sorted([(num, tag) for (tag, num) in vocab_new.items()]) for (_, tag) in new_tags: logging.info('[TAG] %s', tag) print(tag, file=fout)<|docstring|>๊ธฐ๋ถ„์„ ์‚ฌ์ „ ๋นŒ๋“œ ์ค‘์— ์ƒˆ๋กœ ์ถ”๊ฐ€๊ฐ€ ํ•„์š”ํ•œ ์‚ฌ์ „ ์—”ํŠธ๋ฆฌ๋ฅผ ํ•ด๋‹น ์‚ฌ์ „์— ์ถ”๊ฐ€ํ•œ๋‹ค. Args: rsc_src: ๋ฆฌ์Šค์†Œ ๋””๋ ‰ํ† ๋ฆฌ restore_new: ์›ํ˜•๋ณต์› ์‚ฌ์ „์˜ ์ถ”๊ฐ€ํ•  ์—”ํŠธ๋ฆฌ vocab_new: ์ถœ๋ ฅ ํƒœ๊ทธ vocabulary์— ์ถ”๊ฐ€ํ•  ์—”ํŠธ๋ฆฌ<|endoftext|>
e4400c32bb930182f1ac87b20616aa231ac3a21208810fba93e337c32a224ed6
def _make_bin(restore_dic: dict, vocab_out: Dict[(str, int)], vocab_new: Dict[(str, int)]) -> dict: '\n ๋‘ ํ…์ŠคํŠธ ์‚ฌ์ „์„ ์ฝ์–ด๋“ค์—ฌ ๋ฐ”์ด๋„ˆ๋ฆฌ ํ˜•ํƒœ์˜ key-value ์‚ฌ์ „์„ ๋งŒ๋“ ๋‹ค.\n Args:\n restore_dic: ์›ํ˜•๋ณต์› ์‚ฌ์ „\n vocab_out: ์ถœ๋ ฅ ํƒœ๊ทธ ์‚ฌ์ „\n vocab_new: ์ถœ๋ ฅ ํƒœ๊ทธ ์‚ฌ์ „์— ์ถ”๊ฐ€ํ•  ์ƒˆ๋กœ์šด ํƒœ๊ทธ\n Retusns:\n ๋ฐ”์ด๋„ˆ๋ฆฌ ์‚ฌ์ „\n ' bin_dic = {} for ((char, tag), nums_out_dic) in restore_dic.items(): for (num, out) in nums_out_dic.items(): out_tag = '{}:{}'.format(tag, num) logging.debug('%s/%s\t%s', char, out_tag, out) if ((out_tag not in vocab_out) and (out_tag not in vocab_new)): out_num = ((len(vocab_out) + len(vocab_new)) + 1) logging.info('new output tag: [%d] %s', out_num, out_tag) vocab_new[out_tag] = out_num else: out_num = vocab_out[out_tag] key = ((ord(char) << 12) | out_num) if (key in bin_dic): raise KeyError(('duplicated key: 0x08x' % key)) vals = ([0] * MAX_VAL_LEN) for (idx, char_tag) in enumerate(out.split()): if (idx >= MAX_VAL_LEN): raise ValueError('max value length exceeded: {} >= {}'.format(idx, MAX_VAL_LEN)) (char_val, tag_val) = char_tag.rsplit('/', 1) val_mask = (0 if (tag_val[0] == 'B') else 128) tag_val = tag_val[2:] vals[idx] = ((ord(char_val) << 8) | (TAG_SET[tag_val] | val_mask)) bin_dic[key] = vals logging.debug('\t0x%08x => %s', key, ' '.join([('0x%08x' % val) for val in vals])) return bin_dic
๋‘ ํ…์ŠคํŠธ ์‚ฌ์ „์„ ์ฝ์–ด๋“ค์—ฌ ๋ฐ”์ด๋„ˆ๋ฆฌ ํ˜•ํƒœ์˜ key-value ์‚ฌ์ „์„ ๋งŒ๋“ ๋‹ค. Args: restore_dic: ์›ํ˜•๋ณต์› ์‚ฌ์ „ vocab_out: ์ถœ๋ ฅ ํƒœ๊ทธ ์‚ฌ์ „ vocab_new: ์ถœ๋ ฅ ํƒœ๊ทธ ์‚ฌ์ „์— ์ถ”๊ฐ€ํ•  ์ƒˆ๋กœ์šด ํƒœ๊ทธ Retusns: ๋ฐ”์ด๋„ˆ๋ฆฌ ์‚ฌ์ „
rsc/bin/compile_restore.py
_make_bin
juntf/khaiii
1,235
python
def _make_bin(restore_dic: dict, vocab_out: Dict[(str, int)], vocab_new: Dict[(str, int)]) -> dict: '\n ๋‘ ํ…์ŠคํŠธ ์‚ฌ์ „์„ ์ฝ์–ด๋“ค์—ฌ ๋ฐ”์ด๋„ˆ๋ฆฌ ํ˜•ํƒœ์˜ key-value ์‚ฌ์ „์„ ๋งŒ๋“ ๋‹ค.\n Args:\n restore_dic: ์›ํ˜•๋ณต์› ์‚ฌ์ „\n vocab_out: ์ถœ๋ ฅ ํƒœ๊ทธ ์‚ฌ์ „\n vocab_new: ์ถœ๋ ฅ ํƒœ๊ทธ ์‚ฌ์ „์— ์ถ”๊ฐ€ํ•  ์ƒˆ๋กœ์šด ํƒœ๊ทธ\n Retusns:\n ๋ฐ”์ด๋„ˆ๋ฆฌ ์‚ฌ์ „\n ' bin_dic = {} for ((char, tag), nums_out_dic) in restore_dic.items(): for (num, out) in nums_out_dic.items(): out_tag = '{}:{}'.format(tag, num) logging.debug('%s/%s\t%s', char, out_tag, out) if ((out_tag not in vocab_out) and (out_tag not in vocab_new)): out_num = ((len(vocab_out) + len(vocab_new)) + 1) logging.info('new output tag: [%d] %s', out_num, out_tag) vocab_new[out_tag] = out_num else: out_num = vocab_out[out_tag] key = ((ord(char) << 12) | out_num) if (key in bin_dic): raise KeyError(('duplicated key: 0x08x' % key)) vals = ([0] * MAX_VAL_LEN) for (idx, char_tag) in enumerate(out.split()): if (idx >= MAX_VAL_LEN): raise ValueError('max value length exceeded: {} >= {}'.format(idx, MAX_VAL_LEN)) (char_val, tag_val) = char_tag.rsplit('/', 1) val_mask = (0 if (tag_val[0] == 'B') else 128) tag_val = tag_val[2:] vals[idx] = ((ord(char_val) << 8) | (TAG_SET[tag_val] | val_mask)) bin_dic[key] = vals logging.debug('\t0x%08x => %s', key, ' '.join([('0x%08x' % val) for val in vals])) return bin_dic
def _make_bin(restore_dic: dict, vocab_out: Dict[(str, int)], vocab_new: Dict[(str, int)]) -> dict: '\n ๋‘ ํ…์ŠคํŠธ ์‚ฌ์ „์„ ์ฝ์–ด๋“ค์—ฌ ๋ฐ”์ด๋„ˆ๋ฆฌ ํ˜•ํƒœ์˜ key-value ์‚ฌ์ „์„ ๋งŒ๋“ ๋‹ค.\n Args:\n restore_dic: ์›ํ˜•๋ณต์› ์‚ฌ์ „\n vocab_out: ์ถœ๋ ฅ ํƒœ๊ทธ ์‚ฌ์ „\n vocab_new: ์ถœ๋ ฅ ํƒœ๊ทธ ์‚ฌ์ „์— ์ถ”๊ฐ€ํ•  ์ƒˆ๋กœ์šด ํƒœ๊ทธ\n Retusns:\n ๋ฐ”์ด๋„ˆ๋ฆฌ ์‚ฌ์ „\n ' bin_dic = {} for ((char, tag), nums_out_dic) in restore_dic.items(): for (num, out) in nums_out_dic.items(): out_tag = '{}:{}'.format(tag, num) logging.debug('%s/%s\t%s', char, out_tag, out) if ((out_tag not in vocab_out) and (out_tag not in vocab_new)): out_num = ((len(vocab_out) + len(vocab_new)) + 1) logging.info('new output tag: [%d] %s', out_num, out_tag) vocab_new[out_tag] = out_num else: out_num = vocab_out[out_tag] key = ((ord(char) << 12) | out_num) if (key in bin_dic): raise KeyError(('duplicated key: 0x08x' % key)) vals = ([0] * MAX_VAL_LEN) for (idx, char_tag) in enumerate(out.split()): if (idx >= MAX_VAL_LEN): raise ValueError('max value length exceeded: {} >= {}'.format(idx, MAX_VAL_LEN)) (char_val, tag_val) = char_tag.rsplit('/', 1) val_mask = (0 if (tag_val[0] == 'B') else 128) tag_val = tag_val[2:] vals[idx] = ((ord(char_val) << 8) | (TAG_SET[tag_val] | val_mask)) bin_dic[key] = vals logging.debug('\t0x%08x => %s', key, ' '.join([('0x%08x' % val) for val in vals])) return bin_dic<|docstring|>๋‘ ํ…์ŠคํŠธ ์‚ฌ์ „์„ ์ฝ์–ด๋“ค์—ฌ ๋ฐ”์ด๋„ˆ๋ฆฌ ํ˜•ํƒœ์˜ key-value ์‚ฌ์ „์„ ๋งŒ๋“ ๋‹ค. Args: restore_dic: ์›ํ˜•๋ณต์› ์‚ฌ์ „ vocab_out: ์ถœ๋ ฅ ํƒœ๊ทธ ์‚ฌ์ „ vocab_new: ์ถœ๋ ฅ ํƒœ๊ทธ ์‚ฌ์ „์— ์ถ”๊ฐ€ํ•  ์ƒˆ๋กœ์šด ํƒœ๊ทธ Retusns: ๋ฐ”์ด๋„ˆ๋ฆฌ ์‚ฌ์ „<|endoftext|>