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
b96987d71658c2a088aa2c88d7cf60979f0c9934b3cd065eb6832c46010b1215
def close(self): 'Closes the current peer connection.' return self._native_obj.close()
Closes the current peer connection.
python-webrtc/python/webrtc/interfaces/rtc_peer_connection.py
close
MarshalX/python-webrtc
81
python
def close(self): return self._native_obj.close()
def close(self): return self._native_obj.close()<|docstring|>Closes the current peer connection.<|endoftext|>
dc275937eb30a5ae21a1b71529be95045855a73f38271b77d17b74eebc3bfddc
@property def sctp(self) -> Optional['webrtc.RTCSctpTransport']: ":obj:`webrtc.RTCSctpTransport`, optional: An object describing the SCTP transport layer over which SCTP\n data is being sent and received. If SCTP hasn't been negotiated, this value is :obj:`None`" from webrtc import RTCSctpTransport sctp = self._native_obj.sctp if sctp: return RTCSctpTransport._wrap(sctp) return None
:obj:`webrtc.RTCSctpTransport`, optional: An object describing the SCTP transport layer over which SCTP data is being sent and received. If SCTP hasn't been negotiated, this value is :obj:`None`
python-webrtc/python/webrtc/interfaces/rtc_peer_connection.py
sctp
MarshalX/python-webrtc
81
python
@property def sctp(self) -> Optional['webrtc.RTCSctpTransport']: ":obj:`webrtc.RTCSctpTransport`, optional: An object describing the SCTP transport layer over which SCTP\n data is being sent and received. If SCTP hasn't been negotiated, this value is :obj:`None`" from webrtc import RTCSctpTransport sctp = self._native_obj.sctp if sctp: return RTCSctpTransport._wrap(sctp) return None
@property def sctp(self) -> Optional['webrtc.RTCSctpTransport']: ":obj:`webrtc.RTCSctpTransport`, optional: An object describing the SCTP transport layer over which SCTP\n data is being sent and received. If SCTP hasn't been negotiated, this value is :obj:`None`" from webrtc import RTCSctpTransport sctp = self._native_obj.sctp if sctp: return RTCSctpTransport._wrap(sctp) return None<|docstring|>:obj:`webrtc.RTCSctpTransport`, optional: An object describing the SCTP transport layer over which SCTP data is being sent and received. If SCTP hasn't been negotiated, this value is :obj:`None`<|endoftext|>
ac5383c8656fb044e9f957515b1ff2c008679589219a3a65dd703a857ceb51bf
def parse_args(): '\n Parse arguments for this function\n ' parser = argparse.ArgumentParser() parser.add_argument('--output_location', '-o', help='location to store output', default='sample_images') parser.add_argument('--catalog', '-c', help='SEVIR catalog', default='CATALOG.csv') parser.add_argument('--data_path', '-d', help='Path to SEVIR data', default='data/') parser.add_argument('--id', '-i', help='SEVIR id (if not provided, a random case is selected', default=None) parser.add_argument('--resolution', '-r', help='res for statelines', default='c') args = parser.parse_args() return args
Parse arguments for this function
notebooks/eie-sevir/view_sample.py
parse_args
BigDataArchitecture/Assignment1
2
python
def parse_args(): '\n \n ' parser = argparse.ArgumentParser() parser.add_argument('--output_location', '-o', help='location to store output', default='sample_images') parser.add_argument('--catalog', '-c', help='SEVIR catalog', default='CATALOG.csv') parser.add_argument('--data_path', '-d', help='Path to SEVIR data', default='data/') parser.add_argument('--id', '-i', help='SEVIR id (if not provided, a random case is selected', default=None) parser.add_argument('--resolution', '-r', help='res for statelines', default='c') args = parser.parse_args() return args
def parse_args(): '\n \n ' parser = argparse.ArgumentParser() parser.add_argument('--output_location', '-o', help='location to store output', default='sample_images') parser.add_argument('--catalog', '-c', help='SEVIR catalog', default='CATALOG.csv') parser.add_argument('--data_path', '-d', help='Path to SEVIR data', default='data/') parser.add_argument('--id', '-i', help='SEVIR id (if not provided, a random case is selected', default=None) parser.add_argument('--resolution', '-r', help='res for statelines', default='c') args = parser.parse_args() return args<|docstring|>Parse arguments for this function<|endoftext|>
f3b2616faa8e91c2066083f164d0dc1344704070b376c3e9712d6e7253ca8827
def main(): '\n Function to create sample images of a single event in SEVIR\n\n USAGE:\n \n python view_sample.py # only works in SEVIR directory\n\n or, \n\n python view_sample.py --output_location OUTLOC --catalog CATALOG.csv --data_path SEVIR_DATA_PATH \n\n where,\n OUTLOC is where your sample images will be saved (a new dir is made to hold them)\n SEVIR_DATA_PATH is path to the SEVIR data files ()\n\n ' args = parse_args() catalog = pd.read_csv(args.catalog, low_memory=False) cat_groups = catalog.groupby('id') output_location = args.output_location if args.id: sevir_id = args.id cat_groups.get_group(sevir_id) else: allsensors = (cat_groups.size() == 5) ids = np.array(list(cat_groups.groups.keys())) sevir_id = np.random.choice(ids[allsensors], 1)[0] print('Using SEVIR ID', sevir_id) output_location = f'{output_location}/{sevir_id}' try: os.mkdir(output_location) except: pass data = get_data(sevir_id, cat_groups, args.data_path) make_images2(data, output_location, sevir_id, res=args.resolution) update_progress(1.0)
Function to create sample images of a single event in SEVIR USAGE: python view_sample.py # only works in SEVIR directory or, python view_sample.py --output_location OUTLOC --catalog CATALOG.csv --data_path SEVIR_DATA_PATH where, OUTLOC is where your sample images will be saved (a new dir is made to hold them) SEVIR_DATA_PATH is path to the SEVIR data files ()
notebooks/eie-sevir/view_sample.py
main
BigDataArchitecture/Assignment1
2
python
def main(): '\n Function to create sample images of a single event in SEVIR\n\n USAGE:\n \n python view_sample.py # only works in SEVIR directory\n\n or, \n\n python view_sample.py --output_location OUTLOC --catalog CATALOG.csv --data_path SEVIR_DATA_PATH \n\n where,\n OUTLOC is where your sample images will be saved (a new dir is made to hold them)\n SEVIR_DATA_PATH is path to the SEVIR data files ()\n\n ' args = parse_args() catalog = pd.read_csv(args.catalog, low_memory=False) cat_groups = catalog.groupby('id') output_location = args.output_location if args.id: sevir_id = args.id cat_groups.get_group(sevir_id) else: allsensors = (cat_groups.size() == 5) ids = np.array(list(cat_groups.groups.keys())) sevir_id = np.random.choice(ids[allsensors], 1)[0] print('Using SEVIR ID', sevir_id) output_location = f'{output_location}/{sevir_id}' try: os.mkdir(output_location) except: pass data = get_data(sevir_id, cat_groups, args.data_path) make_images2(data, output_location, sevir_id, res=args.resolution) update_progress(1.0)
def main(): '\n Function to create sample images of a single event in SEVIR\n\n USAGE:\n \n python view_sample.py # only works in SEVIR directory\n\n or, \n\n python view_sample.py --output_location OUTLOC --catalog CATALOG.csv --data_path SEVIR_DATA_PATH \n\n where,\n OUTLOC is where your sample images will be saved (a new dir is made to hold them)\n SEVIR_DATA_PATH is path to the SEVIR data files ()\n\n ' args = parse_args() catalog = pd.read_csv(args.catalog, low_memory=False) cat_groups = catalog.groupby('id') output_location = args.output_location if args.id: sevir_id = args.id cat_groups.get_group(sevir_id) else: allsensors = (cat_groups.size() == 5) ids = np.array(list(cat_groups.groups.keys())) sevir_id = np.random.choice(ids[allsensors], 1)[0] print('Using SEVIR ID', sevir_id) output_location = f'{output_location}/{sevir_id}' try: os.mkdir(output_location) except: pass data = get_data(sevir_id, cat_groups, args.data_path) make_images2(data, output_location, sevir_id, res=args.resolution) update_progress(1.0)<|docstring|>Function to create sample images of a single event in SEVIR USAGE: python view_sample.py # only works in SEVIR directory or, python view_sample.py --output_location OUTLOC --catalog CATALOG.csv --data_path SEVIR_DATA_PATH where, OUTLOC is where your sample images will be saved (a new dir is made to hold them) SEVIR_DATA_PATH is path to the SEVIR data files ()<|endoftext|>
659e10986f87a06c2d6d208f47f0b647eb6edc737536a9ed6047f439c8f6b21c
def get_data(sevir_id, grouped_catalog, path): ' \n returns dict { img_type : {"meta" : META, "data": DATA} }\n ' cases = grouped_catalog.get_group(sevir_id) data = {} for typ in TYPES: data[typ] = {} if (typ in cases.img_type.values): meta = cases[(cases.img_type == typ)].squeeze() data[typ]['meta'] = meta file_name = f'{path}/{meta.file_name}' with h5py.File(file_name, 'r') as hf: if (typ == 'lght'): data[typ]['data'] = hf[meta.id][:] else: data[typ]['data'] = hf[meta.img_type][meta.file_index] return data
returns dict { img_type : {"meta" : META, "data": DATA} }
notebooks/eie-sevir/view_sample.py
get_data
BigDataArchitecture/Assignment1
2
python
def get_data(sevir_id, grouped_catalog, path): ' \n \n ' cases = grouped_catalog.get_group(sevir_id) data = {} for typ in TYPES: data[typ] = {} if (typ in cases.img_type.values): meta = cases[(cases.img_type == typ)].squeeze() data[typ]['meta'] = meta file_name = f'{path}/{meta.file_name}' with h5py.File(file_name, 'r') as hf: if (typ == 'lght'): data[typ]['data'] = hf[meta.id][:] else: data[typ]['data'] = hf[meta.img_type][meta.file_index] return data
def get_data(sevir_id, grouped_catalog, path): ' \n \n ' cases = grouped_catalog.get_group(sevir_id) data = {} for typ in TYPES: data[typ] = {} if (typ in cases.img_type.values): meta = cases[(cases.img_type == typ)].squeeze() data[typ]['meta'] = meta file_name = f'{path}/{meta.file_name}' with h5py.File(file_name, 'r') as hf: if (typ == 'lght'): data[typ]['data'] = hf[meta.id][:] else: data[typ]['data'] = hf[meta.img_type][meta.file_index] return data<|docstring|>returns dict { img_type : {"meta" : META, "data": DATA} }<|endoftext|>
86125d2c511a9e830dda9dc65947d68c497cb09145face1f119c48bc10999f50
def mac_from_iface(iface_name): ' Returns the mac address of the specified interface ' ifaddresses = netifaces.ifaddresses(iface_name) return ifaddresses[netifaces.AF_LINK][0]['addr']
Returns the mac address of the specified interface
lte/gateway/python/scripts/fake_user.py
mac_from_iface
electrocucaracha/magma
849
python
def mac_from_iface(iface_name): ' ' ifaddresses = netifaces.ifaddresses(iface_name) return ifaddresses[netifaces.AF_LINK][0]['addr']
def mac_from_iface(iface_name): ' ' ifaddresses = netifaces.ifaddresses(iface_name) return ifaddresses[netifaces.AF_LINK][0]['addr']<|docstring|>Returns the mac address of the specified interface<|endoftext|>
3fe00ef1d297fe4792818719af1d95dab79b22c04111e0dce18b028cd23e3d74
def run(command, ignore_errors=False): ' Runs the shell command ' output(command, 'blue') ret = os.system(command) if ((ret != 0) and (not ignore_errors)): output(('Error!! Command returned: %d' % ret), 'red') sys.exit(1)
Runs the shell command
lte/gateway/python/scripts/fake_user.py
run
electrocucaracha/magma
849
python
def run(command, ignore_errors=False): ' ' output(command, 'blue') ret = os.system(command) if ((ret != 0) and (not ignore_errors)): output(('Error!! Command returned: %d' % ret), 'red') sys.exit(1)
def run(command, ignore_errors=False): ' ' output(command, 'blue') ret = os.system(command) if ((ret != 0) and (not ignore_errors)): output(('Error!! Command returned: %d' % ret), 'red') sys.exit(1)<|docstring|>Runs the shell command<|endoftext|>
2f25275fbfc8f089c091db1fe3a5357101203d927a3273e3a9afcacca3cdd311
def add_flow(table, filter, actions, priority=300): " Adds/modifies an OVS flow.\n We use '0xface0ff' as the cookie for all flows created by this tool " run(('sudo ovs-ofctl add-flow gtp_br0 "cookie=0xface0ff, table=%d, priority=%d,%s actions=%s"' % (table, priority, filter, actions)))
Adds/modifies an OVS flow. We use '0xface0ff' as the cookie for all flows created by this tool
lte/gateway/python/scripts/fake_user.py
add_flow
electrocucaracha/magma
849
python
def add_flow(table, filter, actions, priority=300): " Adds/modifies an OVS flow.\n We use '0xface0ff' as the cookie for all flows created by this tool " run(('sudo ovs-ofctl add-flow gtp_br0 "cookie=0xface0ff, table=%d, priority=%d,%s actions=%s"' % (table, priority, filter, actions)))
def add_flow(table, filter, actions, priority=300): " Adds/modifies an OVS flow.\n We use '0xface0ff' as the cookie for all flows created by this tool " run(('sudo ovs-ofctl add-flow gtp_br0 "cookie=0xface0ff, table=%d, priority=%d,%s actions=%s"' % (table, priority, filter, actions)))<|docstring|>Adds/modifies an OVS flow. We use '0xface0ff' as the cookie for all flows created by this tool<|endoftext|>
16a4edcc77d20ef529fd597537b3709656417ead1686b5ca90abd9a18c1c1f11
def pair_time(pos_k, vel_k, pos_l, vel_l, radius): ' pos_k, pos_l, vel_k, vel_l all have two elements as a list ' t_0 = 0.0 pos_x = (pos_l[0] - pos_k[0]) pos_y = (pos_l[1] - pos_k[1]) Delta_pos = np.array([pos_x, pos_y]) vel_x = (vel_l[0] - vel_k[0]) vel_y = (vel_l[1] - vel_k[1]) Delta_vel = np.array([vel_x, vel_y]) Upsilon = ((Delta_pos.dot(Delta_vel) ** 2) - (Delta_vel.dot(Delta_vel) * (Delta_pos.dot(Delta_pos) - (4.0 * (radius ** 2))))) if ((Upsilon > 0.0) and (Delta_pos.dot(Delta_vel) < 0.0)): return (t_0 - ((Delta_pos.dot(Delta_vel) + m.sqrt(Upsilon)) / Delta_vel.dot(Delta_vel))) else: return float(oo)
pos_k, pos_l, vel_k, vel_l all have two elements as a list
Chapter 2/event_disks_box_simulation.py
pair_time
indrag49/Computational-Stat-Mech
19
python
def pair_time(pos_k, vel_k, pos_l, vel_l, radius): ' ' t_0 = 0.0 pos_x = (pos_l[0] - pos_k[0]) pos_y = (pos_l[1] - pos_k[1]) Delta_pos = np.array([pos_x, pos_y]) vel_x = (vel_l[0] - vel_k[0]) vel_y = (vel_l[1] - vel_k[1]) Delta_vel = np.array([vel_x, vel_y]) Upsilon = ((Delta_pos.dot(Delta_vel) ** 2) - (Delta_vel.dot(Delta_vel) * (Delta_pos.dot(Delta_pos) - (4.0 * (radius ** 2))))) if ((Upsilon > 0.0) and (Delta_pos.dot(Delta_vel) < 0.0)): return (t_0 - ((Delta_pos.dot(Delta_vel) + m.sqrt(Upsilon)) / Delta_vel.dot(Delta_vel))) else: return float(oo)
def pair_time(pos_k, vel_k, pos_l, vel_l, radius): ' ' t_0 = 0.0 pos_x = (pos_l[0] - pos_k[0]) pos_y = (pos_l[1] - pos_k[1]) Delta_pos = np.array([pos_x, pos_y]) vel_x = (vel_l[0] - vel_k[0]) vel_y = (vel_l[1] - vel_k[1]) Delta_vel = np.array([vel_x, vel_y]) Upsilon = ((Delta_pos.dot(Delta_vel) ** 2) - (Delta_vel.dot(Delta_vel) * (Delta_pos.dot(Delta_pos) - (4.0 * (radius ** 2))))) if ((Upsilon > 0.0) and (Delta_pos.dot(Delta_vel) < 0.0)): return (t_0 - ((Delta_pos.dot(Delta_vel) + m.sqrt(Upsilon)) / Delta_vel.dot(Delta_vel))) else: return float(oo)<|docstring|>pos_k, pos_l, vel_k, vel_l all have two elements as a list<|endoftext|>
a57f8dba68776fabbe052347872546ace4324059789587f55494e7cb7dfa8be1
@staticmethod def output_path(test_uid, suite_uid, base=None): '\n Return the path which results for a specific test case should be\n stored.\n ' if (base is None): base = config.result_path return os.path.join(base, suite_uid.replace(os.path.sep, '-'), test_uid.replace(os.path.sep, '-'))
Return the path which results for a specific test case should be stored.
flimsy/result.py
output_path
spwilson2/flimsy
0
python
@staticmethod def output_path(test_uid, suite_uid, base=None): '\n Return the path which results for a specific test case should be\n stored.\n ' if (base is None): base = config.result_path return os.path.join(base, suite_uid.replace(os.path.sep, '-'), test_uid.replace(os.path.sep, '-'))
@staticmethod def output_path(test_uid, suite_uid, base=None): '\n Return the path which results for a specific test case should be\n stored.\n ' if (base is None): base = config.result_path return os.path.join(base, suite_uid.replace(os.path.sep, '-'), test_uid.replace(os.path.sep, '-'))<|docstring|>Return the path which results for a specific test case should be stored.<|endoftext|>
12c34202ca7c86a582f4c0c047c359c02e735f47f3345e39aa3d712df4a5a2b3
@staticmethod def save(results, path): '\n Compile the internal results into JUnit format writting it to the given file.\n ' results = JUnitTestSuites(results) with open(path, 'w') as f: results.write(f)
Compile the internal results into JUnit format writting it to the given file.
flimsy/result.py
save
spwilson2/flimsy
0
python
@staticmethod def save(results, path): '\n \n ' results = JUnitTestSuites(results) with open(path, 'w') as f: results.write(f)
@staticmethod def save(results, path): '\n \n ' results = JUnitTestSuites(results) with open(path, 'w') as f: results.write(f)<|docstring|>Compile the internal results into JUnit format writting it to the given file.<|endoftext|>
5f4aa51b55e15bd082bcd87ec0dde58a5f276acbc231fef0cd1a9216402c9deb
def _start_trace_dialog(self): 'Open Save As dialog to start recording a trace file.' viewer = self._win._qt_viewer dlg = QFileDialog() hist = get_save_history() dlg.setHistory(hist) (filename, _) = dlg.getSaveFileName(parent=viewer, caption=trans._('Record performance trace file'), directory=hist[0], filter=trans._('Trace Files (*.json)')) if filename: if (not filename.endswith('.json')): filename += '.json' QTimer.singleShot(0, (lambda : self._start_trace(filename))) update_save_history(filename)
Open Save As dialog to start recording a trace file.
napari/_qt/menus/debug_menu.py
_start_trace_dialog
perlman/napari
1,345
python
def _start_trace_dialog(self): viewer = self._win._qt_viewer dlg = QFileDialog() hist = get_save_history() dlg.setHistory(hist) (filename, _) = dlg.getSaveFileName(parent=viewer, caption=trans._('Record performance trace file'), directory=hist[0], filter=trans._('Trace Files (*.json)')) if filename: if (not filename.endswith('.json')): filename += '.json' QTimer.singleShot(0, (lambda : self._start_trace(filename))) update_save_history(filename)
def _start_trace_dialog(self): viewer = self._win._qt_viewer dlg = QFileDialog() hist = get_save_history() dlg.setHistory(hist) (filename, _) = dlg.getSaveFileName(parent=viewer, caption=trans._('Record performance trace file'), directory=hist[0], filter=trans._('Trace Files (*.json)')) if filename: if (not filename.endswith('.json')): filename += '.json' QTimer.singleShot(0, (lambda : self._start_trace(filename))) update_save_history(filename)<|docstring|>Open Save As dialog to start recording a trace file.<|endoftext|>
7818118598a96cde7de87b2d122493302bc290970c79f6b35321c0c1b17ba82b
def _stop_trace(self): 'Stop recording a trace file.' perf.timers.stop_trace_file() self._set_recording(False)
Stop recording a trace file.
napari/_qt/menus/debug_menu.py
_stop_trace
perlman/napari
1,345
python
def _stop_trace(self): perf.timers.stop_trace_file() self._set_recording(False)
def _stop_trace(self): perf.timers.stop_trace_file() self._set_recording(False)<|docstring|>Stop recording a trace file.<|endoftext|>
dda9048750a97e60cfa5ff17add3f34cded91c6d2b2ba893f9f5c87b1ecbbfa7
def _set_recording(self, recording: bool): 'Toggle which are enabled/disabled.\n\n Parameters\n ----------\n recording : bool\n Are we currently recording a trace file.\n ' for action in self._perf_menu.actions(): if (trans._('Start Recording') in action.text()): action.setEnabled((not recording)) elif (trans._('Stop Recording') in action.text()): action.setEnabled(recording)
Toggle which are enabled/disabled. Parameters ---------- recording : bool Are we currently recording a trace file.
napari/_qt/menus/debug_menu.py
_set_recording
perlman/napari
1,345
python
def _set_recording(self, recording: bool): 'Toggle which are enabled/disabled.\n\n Parameters\n ----------\n recording : bool\n Are we currently recording a trace file.\n ' for action in self._perf_menu.actions(): if (trans._('Start Recording') in action.text()): action.setEnabled((not recording)) elif (trans._('Stop Recording') in action.text()): action.setEnabled(recording)
def _set_recording(self, recording: bool): 'Toggle which are enabled/disabled.\n\n Parameters\n ----------\n recording : bool\n Are we currently recording a trace file.\n ' for action in self._perf_menu.actions(): if (trans._('Start Recording') in action.text()): action.setEnabled((not recording)) elif (trans._('Stop Recording') in action.text()): action.setEnabled(recording)<|docstring|>Toggle which are enabled/disabled. Parameters ---------- recording : bool Are we currently recording a trace file.<|endoftext|>
2a940da033744feb1daae7f27b718cc956b061d13942729883f96efc845a78fa
def label_smoothing(pred, target, eta=0.1): '\n Refer from https://arxiv.org/pdf/1512.00567.pdf\n :param target: N,\n :param n_classes: int\n :param eta: float\n :return:\n N x C onehot smoothed vector\n ' n_classes = pred.size(1) target = torch.unsqueeze(target, 1) onehot_target = torch.zeros_like(pred) onehot_target.scatter_(1, target, 1) return ((onehot_target * (1 - eta)) + ((eta / n_classes) * 1))
Refer from https://arxiv.org/pdf/1512.00567.pdf :param target: N, :param n_classes: int :param eta: float :return: N x C onehot smoothed vector
training/utils/bags_of_tricks.py
label_smoothing
KyuhwanYeom/proxylessnas
558
python
def label_smoothing(pred, target, eta=0.1): '\n Refer from https://arxiv.org/pdf/1512.00567.pdf\n :param target: N,\n :param n_classes: int\n :param eta: float\n :return:\n N x C onehot smoothed vector\n ' n_classes = pred.size(1) target = torch.unsqueeze(target, 1) onehot_target = torch.zeros_like(pred) onehot_target.scatter_(1, target, 1) return ((onehot_target * (1 - eta)) + ((eta / n_classes) * 1))
def label_smoothing(pred, target, eta=0.1): '\n Refer from https://arxiv.org/pdf/1512.00567.pdf\n :param target: N,\n :param n_classes: int\n :param eta: float\n :return:\n N x C onehot smoothed vector\n ' n_classes = pred.size(1) target = torch.unsqueeze(target, 1) onehot_target = torch.zeros_like(pred) onehot_target.scatter_(1, target, 1) return ((onehot_target * (1 - eta)) + ((eta / n_classes) * 1))<|docstring|>Refer from https://arxiv.org/pdf/1512.00567.pdf :param target: N, :param n_classes: int :param eta: float :return: N x C onehot smoothed vector<|endoftext|>
fa266ed3619eec167c4b94f5d9e3d3b8cdcc43f884d5f99fb2559cb29ff4aaef
@pytest.mark.fast_test def test_dict_list_space_representation(): '\n Tests whether the conversion of the dictionary and list representation\n of a point from a search space works properly.\n ' chef_space = {'Cooking time': (0, 1200), 'Main ingredient': ['cheese', 'cherimoya', 'chicken', 'chard', 'chocolate', 'chicory'], 'Secondary ingredient': ['love', 'passion', 'dedication'], 'Cooking temperature': ((- 273.16), 10000.0)} opt = Optimizer(dimensions=dimensions_aslist(chef_space)) point = opt.ask() assert_equal(point, point_aslist(chef_space, point_asdict(chef_space, point)))
Tests whether the conversion of the dictionary and list representation of a point from a search space works properly.
ProcessOptimizer/tests/test_utils.py
test_dict_list_space_representation
dk-teknologisk-rtfh/ProcessOptimizer
0
python
@pytest.mark.fast_test def test_dict_list_space_representation(): '\n Tests whether the conversion of the dictionary and list representation\n of a point from a search space works properly.\n ' chef_space = {'Cooking time': (0, 1200), 'Main ingredient': ['cheese', 'cherimoya', 'chicken', 'chard', 'chocolate', 'chicory'], 'Secondary ingredient': ['love', 'passion', 'dedication'], 'Cooking temperature': ((- 273.16), 10000.0)} opt = Optimizer(dimensions=dimensions_aslist(chef_space)) point = opt.ask() assert_equal(point, point_aslist(chef_space, point_asdict(chef_space, point)))
@pytest.mark.fast_test def test_dict_list_space_representation(): '\n Tests whether the conversion of the dictionary and list representation\n of a point from a search space works properly.\n ' chef_space = {'Cooking time': (0, 1200), 'Main ingredient': ['cheese', 'cherimoya', 'chicken', 'chard', 'chocolate', 'chicory'], 'Secondary ingredient': ['love', 'passion', 'dedication'], 'Cooking temperature': ((- 273.16), 10000.0)} opt = Optimizer(dimensions=dimensions_aslist(chef_space)) point = opt.ask() assert_equal(point, point_aslist(chef_space, point_asdict(chef_space, point)))<|docstring|>Tests whether the conversion of the dictionary and list representation of a point from a search space works properly.<|endoftext|>
bda1dfe696b81938f0d4de11e9145a962a593961c234598db5b03cb2c8ffb4ca
@pytest.mark.fast_test def test_use_named_args(): '\n Test the function wrapper @use_named_args which is used\n for wrapping an objective function with named args so it\n can be called by the optimizers which only pass a single\n list as the arg.\n\n This test does not actually use the optimizers but merely\n simulates how they would call the function.\n ' dim1 = Real(name='foo', low=0.0, high=1.0) dim2 = Real(name='bar', low=0.0, high=1.0) dim3 = Real(name='baz', low=0.0, high=1.0) dimensions = [dim1, dim2, dim3] default_parameters = [0.5, 0.6, 0.8] @use_named_args(dimensions=dimensions) def func(foo, bar, baz): assert (foo == default_parameters[0]) assert (bar == default_parameters[1]) assert (baz == default_parameters[2]) return (((foo ** 2) + (bar ** 4)) + (baz ** 8)) res = func(x=default_parameters) assert isinstance(res, float) res = func(default_parameters) assert isinstance(res, float) res = func(x=np.array(default_parameters)) assert isinstance(res, float) res = func(np.array(default_parameters)) assert isinstance(res, float)
Test the function wrapper @use_named_args which is used for wrapping an objective function with named args so it can be called by the optimizers which only pass a single list as the arg. This test does not actually use the optimizers but merely simulates how they would call the function.
ProcessOptimizer/tests/test_utils.py
test_use_named_args
dk-teknologisk-rtfh/ProcessOptimizer
0
python
@pytest.mark.fast_test def test_use_named_args(): '\n Test the function wrapper @use_named_args which is used\n for wrapping an objective function with named args so it\n can be called by the optimizers which only pass a single\n list as the arg.\n\n This test does not actually use the optimizers but merely\n simulates how they would call the function.\n ' dim1 = Real(name='foo', low=0.0, high=1.0) dim2 = Real(name='bar', low=0.0, high=1.0) dim3 = Real(name='baz', low=0.0, high=1.0) dimensions = [dim1, dim2, dim3] default_parameters = [0.5, 0.6, 0.8] @use_named_args(dimensions=dimensions) def func(foo, bar, baz): assert (foo == default_parameters[0]) assert (bar == default_parameters[1]) assert (baz == default_parameters[2]) return (((foo ** 2) + (bar ** 4)) + (baz ** 8)) res = func(x=default_parameters) assert isinstance(res, float) res = func(default_parameters) assert isinstance(res, float) res = func(x=np.array(default_parameters)) assert isinstance(res, float) res = func(np.array(default_parameters)) assert isinstance(res, float)
@pytest.mark.fast_test def test_use_named_args(): '\n Test the function wrapper @use_named_args which is used\n for wrapping an objective function with named args so it\n can be called by the optimizers which only pass a single\n list as the arg.\n\n This test does not actually use the optimizers but merely\n simulates how they would call the function.\n ' dim1 = Real(name='foo', low=0.0, high=1.0) dim2 = Real(name='bar', low=0.0, high=1.0) dim3 = Real(name='baz', low=0.0, high=1.0) dimensions = [dim1, dim2, dim3] default_parameters = [0.5, 0.6, 0.8] @use_named_args(dimensions=dimensions) def func(foo, bar, baz): assert (foo == default_parameters[0]) assert (bar == default_parameters[1]) assert (baz == default_parameters[2]) return (((foo ** 2) + (bar ** 4)) + (baz ** 8)) res = func(x=default_parameters) assert isinstance(res, float) res = func(default_parameters) assert isinstance(res, float) res = func(x=np.array(default_parameters)) assert isinstance(res, float) res = func(np.array(default_parameters)) assert isinstance(res, float)<|docstring|>Test the function wrapper @use_named_args which is used for wrapping an objective function with named args so it can be called by the optimizers which only pass a single list as the arg. This test does not actually use the optimizers but merely simulates how they would call the function.<|endoftext|>
0ae3c3328fe106c8afb006db35b064e7b602caed3eac961afc99eb0a88e21285
def ave_last_hidden(self, all_layer_embedding): '\n Average the output from last layer\n ' unmask_num = np.array([sum(mask) for mask in self.masks]) embedding = [] for i in range(len(unmask_num)): sent_len = unmask_num[i] hidden_state_sen = all_layer_embedding[i][((- 1), :, :)] embedding.append(np.mean(hidden_state_sen[(:sent_len, :)], axis=0)) embedding = np.array(embedding) return embedding
Average the output from last layer
malaya/model/sbert_wk.py
ave_last_hidden
AetherPrior/malaya
88
python
def ave_last_hidden(self, all_layer_embedding): '\n \n ' unmask_num = np.array([sum(mask) for mask in self.masks]) embedding = [] for i in range(len(unmask_num)): sent_len = unmask_num[i] hidden_state_sen = all_layer_embedding[i][((- 1), :, :)] embedding.append(np.mean(hidden_state_sen[(:sent_len, :)], axis=0)) embedding = np.array(embedding) return embedding
def ave_last_hidden(self, all_layer_embedding): '\n \n ' unmask_num = np.array([sum(mask) for mask in self.masks]) embedding = [] for i in range(len(unmask_num)): sent_len = unmask_num[i] hidden_state_sen = all_layer_embedding[i][((- 1), :, :)] embedding.append(np.mean(hidden_state_sen[(:sent_len, :)], axis=0)) embedding = np.array(embedding) return embedding<|docstring|>Average the output from last layer<|endoftext|>
821be0979f18ffaea88bac71e17df7af829b7891c1bb15548f09a7368a379ff9
def ave_one_layer(self, all_layer_embedding): '\n Average the output from last layer\n ' unmask_num = np.array([sum(mask) for mask in self.masks]) embedding = [] for i in range(len(unmask_num)): sent_len = unmask_num[i] hidden_state_sen = all_layer_embedding[i][(4, :, :)] embedding.append(np.mean(hidden_state_sen[(:sent_len, :)], axis=0)) embedding = np.array(embedding) return embedding
Average the output from last layer
malaya/model/sbert_wk.py
ave_one_layer
AetherPrior/malaya
88
python
def ave_one_layer(self, all_layer_embedding): '\n \n ' unmask_num = np.array([sum(mask) for mask in self.masks]) embedding = [] for i in range(len(unmask_num)): sent_len = unmask_num[i] hidden_state_sen = all_layer_embedding[i][(4, :, :)] embedding.append(np.mean(hidden_state_sen[(:sent_len, :)], axis=0)) embedding = np.array(embedding) return embedding
def ave_one_layer(self, all_layer_embedding): '\n \n ' unmask_num = np.array([sum(mask) for mask in self.masks]) embedding = [] for i in range(len(unmask_num)): sent_len = unmask_num[i] hidden_state_sen = all_layer_embedding[i][(4, :, :)] embedding.append(np.mean(hidden_state_sen[(:sent_len, :)], axis=0)) embedding = np.array(embedding) return embedding<|docstring|>Average the output from last layer<|endoftext|>
964a90d2a10f157c367f2f2b92afa1f85dfc3e29f73368ebc6a91d83cc610298
def CLS(self, all_layer_embedding): '\n CLS vector as embedding\n ' unmask_num = np.array([sum(mask) for mask in self.masks]) embedding = [] for i in range(len(unmask_num)): sent_len = unmask_num[i] hidden_state_sen = all_layer_embedding[i][((- 1), :, :)] embedding.append(hidden_state_sen[0]) embedding = np.array(embedding) return embedding
CLS vector as embedding
malaya/model/sbert_wk.py
CLS
AetherPrior/malaya
88
python
def CLS(self, all_layer_embedding): '\n \n ' unmask_num = np.array([sum(mask) for mask in self.masks]) embedding = [] for i in range(len(unmask_num)): sent_len = unmask_num[i] hidden_state_sen = all_layer_embedding[i][((- 1), :, :)] embedding.append(hidden_state_sen[0]) embedding = np.array(embedding) return embedding
def CLS(self, all_layer_embedding): '\n \n ' unmask_num = np.array([sum(mask) for mask in self.masks]) embedding = [] for i in range(len(unmask_num)): sent_len = unmask_num[i] hidden_state_sen = all_layer_embedding[i][((- 1), :, :)] embedding.append(hidden_state_sen[0]) embedding = np.array(embedding) return embedding<|docstring|>CLS vector as embedding<|endoftext|>
a791afed1e07f535fab83579cf4ab140da56d2b5f59d27dbf0a9b83eab1f5c8d
def dissecting(self, all_layer_embedding): '\n dissecting deep contextualized model\n ' unmask_num = (np.array([sum(mask) for mask in self.masks]) - 1) all_layer_embedding = np.array(all_layer_embedding)[(:, 4:, :, :)] embedding = [] for sent_index in range(len(unmask_num)): sentence_feature = all_layer_embedding[(sent_index, :, :unmask_num[sent_index], :)] one_sentence_embedding = [] for token_index in range(sentence_feature.shape[1]): token_feature = sentence_feature[(:, token_index, :)] token_embedding = self.unify_token(token_feature) one_sentence_embedding.append(token_embedding) one_sentence_embedding = np.array(one_sentence_embedding) sentence_embedding = self.unify_sentence(sentence_feature, one_sentence_embedding) embedding.append(sentence_embedding) embedding = np.array(embedding) return embedding
dissecting deep contextualized model
malaya/model/sbert_wk.py
dissecting
AetherPrior/malaya
88
python
def dissecting(self, all_layer_embedding): '\n \n ' unmask_num = (np.array([sum(mask) for mask in self.masks]) - 1) all_layer_embedding = np.array(all_layer_embedding)[(:, 4:, :, :)] embedding = [] for sent_index in range(len(unmask_num)): sentence_feature = all_layer_embedding[(sent_index, :, :unmask_num[sent_index], :)] one_sentence_embedding = [] for token_index in range(sentence_feature.shape[1]): token_feature = sentence_feature[(:, token_index, :)] token_embedding = self.unify_token(token_feature) one_sentence_embedding.append(token_embedding) one_sentence_embedding = np.array(one_sentence_embedding) sentence_embedding = self.unify_sentence(sentence_feature, one_sentence_embedding) embedding.append(sentence_embedding) embedding = np.array(embedding) return embedding
def dissecting(self, all_layer_embedding): '\n \n ' unmask_num = (np.array([sum(mask) for mask in self.masks]) - 1) all_layer_embedding = np.array(all_layer_embedding)[(:, 4:, :, :)] embedding = [] for sent_index in range(len(unmask_num)): sentence_feature = all_layer_embedding[(sent_index, :, :unmask_num[sent_index], :)] one_sentence_embedding = [] for token_index in range(sentence_feature.shape[1]): token_feature = sentence_feature[(:, token_index, :)] token_embedding = self.unify_token(token_feature) one_sentence_embedding.append(token_embedding) one_sentence_embedding = np.array(one_sentence_embedding) sentence_embedding = self.unify_sentence(sentence_feature, one_sentence_embedding) embedding.append(sentence_embedding) embedding = np.array(embedding) return embedding<|docstring|>dissecting deep contextualized model<|endoftext|>
a3d19c2132c947c884aefedcd2fbbcc70ccc237c7f6706cda357b383610c30b6
def unify_token(self, token_feature): '\n Unify Token Representation\n ' window_size = 2 alpha_alignment = np.zeros(token_feature.shape[0]) alpha_novelty = np.zeros(token_feature.shape[0]) for k in range(token_feature.shape[0]): left_window = token_feature[((k - window_size):k, :)] right_window = token_feature[((k + 1):((k + window_size) + 1), :)] window_matrix = np.vstack([left_window, right_window, token_feature[(k, :)][(None, :)]]) (Q, R) = np.linalg.qr(window_matrix.T) q = Q[(:, (- 1))] r = R[(:, (- 1))] alpha_alignment[k] = (np.mean(normalize(R[(:(- 1), :(- 1))], axis=0), axis=1).dot(R[(:(- 1), (- 1))]) / np.linalg.norm(r[:(- 1)])) alpha_alignment[k] = (1 / ((alpha_alignment[k] * window_matrix.shape[0]) * 2)) alpha_novelty[k] = (abs(r[(- 1)]) / np.linalg.norm(r)) alpha_alignment = (alpha_alignment / np.sum(alpha_alignment)) alpha_novelty = (alpha_novelty / np.sum(alpha_novelty)) alpha = (alpha_novelty + alpha_alignment) alpha = (alpha / np.sum(alpha)) out_embedding = token_feature.T.dot(alpha) return out_embedding
Unify Token Representation
malaya/model/sbert_wk.py
unify_token
AetherPrior/malaya
88
python
def unify_token(self, token_feature): '\n \n ' window_size = 2 alpha_alignment = np.zeros(token_feature.shape[0]) alpha_novelty = np.zeros(token_feature.shape[0]) for k in range(token_feature.shape[0]): left_window = token_feature[((k - window_size):k, :)] right_window = token_feature[((k + 1):((k + window_size) + 1), :)] window_matrix = np.vstack([left_window, right_window, token_feature[(k, :)][(None, :)]]) (Q, R) = np.linalg.qr(window_matrix.T) q = Q[(:, (- 1))] r = R[(:, (- 1))] alpha_alignment[k] = (np.mean(normalize(R[(:(- 1), :(- 1))], axis=0), axis=1).dot(R[(:(- 1), (- 1))]) / np.linalg.norm(r[:(- 1)])) alpha_alignment[k] = (1 / ((alpha_alignment[k] * window_matrix.shape[0]) * 2)) alpha_novelty[k] = (abs(r[(- 1)]) / np.linalg.norm(r)) alpha_alignment = (alpha_alignment / np.sum(alpha_alignment)) alpha_novelty = (alpha_novelty / np.sum(alpha_novelty)) alpha = (alpha_novelty + alpha_alignment) alpha = (alpha / np.sum(alpha)) out_embedding = token_feature.T.dot(alpha) return out_embedding
def unify_token(self, token_feature): '\n \n ' window_size = 2 alpha_alignment = np.zeros(token_feature.shape[0]) alpha_novelty = np.zeros(token_feature.shape[0]) for k in range(token_feature.shape[0]): left_window = token_feature[((k - window_size):k, :)] right_window = token_feature[((k + 1):((k + window_size) + 1), :)] window_matrix = np.vstack([left_window, right_window, token_feature[(k, :)][(None, :)]]) (Q, R) = np.linalg.qr(window_matrix.T) q = Q[(:, (- 1))] r = R[(:, (- 1))] alpha_alignment[k] = (np.mean(normalize(R[(:(- 1), :(- 1))], axis=0), axis=1).dot(R[(:(- 1), (- 1))]) / np.linalg.norm(r[:(- 1)])) alpha_alignment[k] = (1 / ((alpha_alignment[k] * window_matrix.shape[0]) * 2)) alpha_novelty[k] = (abs(r[(- 1)]) / np.linalg.norm(r)) alpha_alignment = (alpha_alignment / np.sum(alpha_alignment)) alpha_novelty = (alpha_novelty / np.sum(alpha_novelty)) alpha = (alpha_novelty + alpha_alignment) alpha = (alpha / np.sum(alpha)) out_embedding = token_feature.T.dot(alpha) return out_embedding<|docstring|>Unify Token Representation<|endoftext|>
1669dd1d78706010894c6c400839499a767ec00eede62fca3e06e35080bc9cf7
def unify_sentence(self, sentence_feature, one_sentence_embedding): '\n Unify Sentence By Token Importance\n ' sent_len = one_sentence_embedding.shape[0] var_token = np.zeros(sent_len) for token_index in range(sent_len): token_feature = sentence_feature[(:, token_index, :)] sim_map = cosine_similarity(token_feature) var_token[token_index] = np.var(sim_map.diagonal((- 1))) var_token = (var_token / np.sum(var_token)) sentence_embedding = one_sentence_embedding.T.dot(var_token) return sentence_embedding
Unify Sentence By Token Importance
malaya/model/sbert_wk.py
unify_sentence
AetherPrior/malaya
88
python
def unify_sentence(self, sentence_feature, one_sentence_embedding): '\n \n ' sent_len = one_sentence_embedding.shape[0] var_token = np.zeros(sent_len) for token_index in range(sent_len): token_feature = sentence_feature[(:, token_index, :)] sim_map = cosine_similarity(token_feature) var_token[token_index] = np.var(sim_map.diagonal((- 1))) var_token = (var_token / np.sum(var_token)) sentence_embedding = one_sentence_embedding.T.dot(var_token) return sentence_embedding
def unify_sentence(self, sentence_feature, one_sentence_embedding): '\n \n ' sent_len = one_sentence_embedding.shape[0] var_token = np.zeros(sent_len) for token_index in range(sent_len): token_feature = sentence_feature[(:, token_index, :)] sim_map = cosine_similarity(token_feature) var_token[token_index] = np.var(sim_map.diagonal((- 1))) var_token = (var_token / np.sum(var_token)) sentence_embedding = one_sentence_embedding.T.dot(var_token) return sentence_embedding<|docstring|>Unify Sentence By Token Importance<|endoftext|>
2f5be53f72484f8fd6b95c8fe22a6fcf645097dee1a7de08f914dd8bd2ebefbc
def template_jacks(self: 'PtnCombo', minimum_length: int, keys: int) -> np.ndarray: ' A template to quickly create jack lines\n\n E.g. If the ``minimumLength==2``, all jacks that last at least 2 notes are highlighted.\n\n :param minimum_length: The minimum length of the jack\n :param keys: The keys of the map, used to detect pattern limits.\n :return:\n ' assert (minimum_length >= 2), f'Minimum Length must be at least 2, {minimum_length} < 2' return self.combinations(size=minimum_length, flatten=True, make_size2=True, combo_filter=PtnFilterCombo.create([([0] * minimum_length)], keys=keys, method=PtnFilterCombo.Method.REPEAT, invert_filter=False).filter, type_filter=PtnFilterType.create([([HoldTail] + ([object] * (minimum_length - 1)))], keys=keys, method=PtnFilterType.Method.ANY_ORDER, invert_filter=True).filter)
A template to quickly create jack lines E.g. If the ``minimumLength==2``, all jacks that last at least 2 notes are highlighted. :param minimum_length: The minimum length of the jack :param keys: The keys of the map, used to detect pattern limits. :return:
reamber/algorithms/pattern/combos/_PtnCJack.py
template_jacks
Eve-ning/reamber_base_py
10
python
def template_jacks(self: 'PtnCombo', minimum_length: int, keys: int) -> np.ndarray: ' A template to quickly create jack lines\n\n E.g. If the ``minimumLength==2``, all jacks that last at least 2 notes are highlighted.\n\n :param minimum_length: The minimum length of the jack\n :param keys: The keys of the map, used to detect pattern limits.\n :return:\n ' assert (minimum_length >= 2), f'Minimum Length must be at least 2, {minimum_length} < 2' return self.combinations(size=minimum_length, flatten=True, make_size2=True, combo_filter=PtnFilterCombo.create([([0] * minimum_length)], keys=keys, method=PtnFilterCombo.Method.REPEAT, invert_filter=False).filter, type_filter=PtnFilterType.create([([HoldTail] + ([object] * (minimum_length - 1)))], keys=keys, method=PtnFilterType.Method.ANY_ORDER, invert_filter=True).filter)
def template_jacks(self: 'PtnCombo', minimum_length: int, keys: int) -> np.ndarray: ' A template to quickly create jack lines\n\n E.g. If the ``minimumLength==2``, all jacks that last at least 2 notes are highlighted.\n\n :param minimum_length: The minimum length of the jack\n :param keys: The keys of the map, used to detect pattern limits.\n :return:\n ' assert (minimum_length >= 2), f'Minimum Length must be at least 2, {minimum_length} < 2' return self.combinations(size=minimum_length, flatten=True, make_size2=True, combo_filter=PtnFilterCombo.create([([0] * minimum_length)], keys=keys, method=PtnFilterCombo.Method.REPEAT, invert_filter=False).filter, type_filter=PtnFilterType.create([([HoldTail] + ([object] * (minimum_length - 1)))], keys=keys, method=PtnFilterType.Method.ANY_ORDER, invert_filter=True).filter)<|docstring|>A template to quickly create jack lines E.g. If the ``minimumLength==2``, all jacks that last at least 2 notes are highlighted. :param minimum_length: The minimum length of the jack :param keys: The keys of the map, used to detect pattern limits. :return:<|endoftext|>
89f144a049cfdd3b93836b5f39990092c9aec22cad355d1bb606275763ab660b
def authenticate(username, password, session, alreadyHashed=False, retries=0): '\n Authenticates with the router by sending the login information. cookies\n are stored in the given session.\n\n username - The plaintext username to use\n password - The plaintext password to use OR the MD5 hash of the password\n if the alreadyHashed flag is set\n session - requests.Session to use for making connections\n alreadyHashed - Set to True if the password given is the MD5 hash\n ' maxRetries = 2 error = False quit = False m = hashlib.md5() username = username.encode('utf8-') m.update(username) usernameHash = m.hexdigest() if (alreadyHashed == False): m = hashlib.md5() password = password.encode('utf-8') m.update(password) passwordHash = m.hexdigest() else: passwordHash = password url = 'http://192.168.1.1/Forms/login_security_1' session.headers = {'Host': '192.168.1.1', 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:46.0) Gecko/20100101 Firefox/46.0', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate', 'Referer': 'http://192.168.1.1/login_security.html', 'Connection': 'keep-alive'} data = {'tipsFlag': '0', 'timevalue': '0', 'Login_Name': username, 'Login_Pwd': 'Ha2S+eOKqmzA6nrlmTeh7w==', 'uiWebLoginhiddenUsername': usernameHash, 'uiWebLoginhiddenPassword': passwordHash} print('[INFO] Sending login details to router...') try: r = session.post(url, data=data, allow_redirects=False, timeout=5) except requests.ConnectionError as e: print('[ERROR] Connection error while authenticating with router!') error = True except requests.Timeout as e: print('[ERROR] Request timeout while authenticating with router!') error = True except exception as e: print(e.message) if (error == False): if (r.cookies['C1'] == '%00'): print('[ERROR] Incorrect password!') error = True quit = True else: print('[INFO] Login successful!') if ((error == True) and (quit == False)): session.close() if (retries < maxRetries): retries += 1 print('[INFO] Retrying authentication {0}/{1}...'.format(retries, maxRetries)) time.sleep(10) authenticate(username, password, session, alreadyHashed, retries) else: quit = True if (quit == True): print('[ERROR] Unable to autenticate with router!') sys.stdout.flush() exit(1) return
Authenticates with the router by sending the login information. cookies are stored in the given session. username - The plaintext username to use password - The plaintext password to use OR the MD5 hash of the password if the alreadyHashed flag is set session - requests.Session to use for making connections alreadyHashed - Set to True if the password given is the MD5 hash
bandwidth-monitor.py
authenticate
egeldenhuys/bandwidth-monitor
0
python
def authenticate(username, password, session, alreadyHashed=False, retries=0): '\n Authenticates with the router by sending the login information. cookies\n are stored in the given session.\n\n username - The plaintext username to use\n password - The plaintext password to use OR the MD5 hash of the password\n if the alreadyHashed flag is set\n session - requests.Session to use for making connections\n alreadyHashed - Set to True if the password given is the MD5 hash\n ' maxRetries = 2 error = False quit = False m = hashlib.md5() username = username.encode('utf8-') m.update(username) usernameHash = m.hexdigest() if (alreadyHashed == False): m = hashlib.md5() password = password.encode('utf-8') m.update(password) passwordHash = m.hexdigest() else: passwordHash = password url = 'http://192.168.1.1/Forms/login_security_1' session.headers = {'Host': '192.168.1.1', 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:46.0) Gecko/20100101 Firefox/46.0', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate', 'Referer': 'http://192.168.1.1/login_security.html', 'Connection': 'keep-alive'} data = {'tipsFlag': '0', 'timevalue': '0', 'Login_Name': username, 'Login_Pwd': 'Ha2S+eOKqmzA6nrlmTeh7w==', 'uiWebLoginhiddenUsername': usernameHash, 'uiWebLoginhiddenPassword': passwordHash} print('[INFO] Sending login details to router...') try: r = session.post(url, data=data, allow_redirects=False, timeout=5) except requests.ConnectionError as e: print('[ERROR] Connection error while authenticating with router!') error = True except requests.Timeout as e: print('[ERROR] Request timeout while authenticating with router!') error = True except exception as e: print(e.message) if (error == False): if (r.cookies['C1'] == '%00'): print('[ERROR] Incorrect password!') error = True quit = True else: print('[INFO] Login successful!') if ((error == True) and (quit == False)): session.close() if (retries < maxRetries): retries += 1 print('[INFO] Retrying authentication {0}/{1}...'.format(retries, maxRetries)) time.sleep(10) authenticate(username, password, session, alreadyHashed, retries) else: quit = True if (quit == True): print('[ERROR] Unable to autenticate with router!') sys.stdout.flush() exit(1) return
def authenticate(username, password, session, alreadyHashed=False, retries=0): '\n Authenticates with the router by sending the login information. cookies\n are stored in the given session.\n\n username - The plaintext username to use\n password - The plaintext password to use OR the MD5 hash of the password\n if the alreadyHashed flag is set\n session - requests.Session to use for making connections\n alreadyHashed - Set to True if the password given is the MD5 hash\n ' maxRetries = 2 error = False quit = False m = hashlib.md5() username = username.encode('utf8-') m.update(username) usernameHash = m.hexdigest() if (alreadyHashed == False): m = hashlib.md5() password = password.encode('utf-8') m.update(password) passwordHash = m.hexdigest() else: passwordHash = password url = 'http://192.168.1.1/Forms/login_security_1' session.headers = {'Host': '192.168.1.1', 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:46.0) Gecko/20100101 Firefox/46.0', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate', 'Referer': 'http://192.168.1.1/login_security.html', 'Connection': 'keep-alive'} data = {'tipsFlag': '0', 'timevalue': '0', 'Login_Name': username, 'Login_Pwd': 'Ha2S+eOKqmzA6nrlmTeh7w==', 'uiWebLoginhiddenUsername': usernameHash, 'uiWebLoginhiddenPassword': passwordHash} print('[INFO] Sending login details to router...') try: r = session.post(url, data=data, allow_redirects=False, timeout=5) except requests.ConnectionError as e: print('[ERROR] Connection error while authenticating with router!') error = True except requests.Timeout as e: print('[ERROR] Request timeout while authenticating with router!') error = True except exception as e: print(e.message) if (error == False): if (r.cookies['C1'] == '%00'): print('[ERROR] Incorrect password!') error = True quit = True else: print('[INFO] Login successful!') if ((error == True) and (quit == False)): session.close() if (retries < maxRetries): retries += 1 print('[INFO] Retrying authentication {0}/{1}...'.format(retries, maxRetries)) time.sleep(10) authenticate(username, password, session, alreadyHashed, retries) else: quit = True if (quit == True): print('[ERROR] Unable to autenticate with router!') sys.stdout.flush() exit(1) return<|docstring|>Authenticates with the router by sending the login information. cookies are stored in the given session. username - The plaintext username to use password - The plaintext password to use OR the MD5 hash of the password if the alreadyHashed flag is set session - requests.Session to use for making connections alreadyHashed - Set to True if the password given is the MD5 hash<|endoftext|>
1a0d92389f5cd0f69ddca404230a8ace8197466b9835733c107f5f54fd2a4848
def extractValue(indexString, content): "\n Extracts an integer value after the indexString from the given content.\n\n Searched for the given string, then moves over that string + 1 pos (new line),\n then reads the numbers until a '<' is found\n\n indexString - The string to search for.\n content - The content to search in.\n\n Returns:\n Integer if found, else -1\n " index = content.find(indexString) if (index == (- 1)): raise ValueError('String not found!', indexString) index += (len(indexString) + 1) numberStr = '' number = 0 while (content[index] != '<'): if (content[index] != ','): numberStr += content[index] index = (index + 1) number = int(numberStr) return number
Extracts an integer value after the indexString from the given content. Searched for the given string, then moves over that string + 1 pos (new line), then reads the numbers until a '<' is found indexString - The string to search for. content - The content to search in. Returns: Integer if found, else -1
bandwidth-monitor.py
extractValue
egeldenhuys/bandwidth-monitor
0
python
def extractValue(indexString, content): "\n Extracts an integer value after the indexString from the given content.\n\n Searched for the given string, then moves over that string + 1 pos (new line),\n then reads the numbers until a '<' is found\n\n indexString - The string to search for.\n content - The content to search in.\n\n Returns:\n Integer if found, else -1\n " index = content.find(indexString) if (index == (- 1)): raise ValueError('String not found!', indexString) index += (len(indexString) + 1) numberStr = number = 0 while (content[index] != '<'): if (content[index] != ','): numberStr += content[index] index = (index + 1) number = int(numberStr) return number
def extractValue(indexString, content): "\n Extracts an integer value after the indexString from the given content.\n\n Searched for the given string, then moves over that string + 1 pos (new line),\n then reads the numbers until a '<' is found\n\n indexString - The string to search for.\n content - The content to search in.\n\n Returns:\n Integer if found, else -1\n " index = content.find(indexString) if (index == (- 1)): raise ValueError('String not found!', indexString) index += (len(indexString) + 1) numberStr = number = 0 while (content[index] != '<'): if (content[index] != ','): numberStr += content[index] index = (index + 1) number = int(numberStr) return number<|docstring|>Extracts an integer value after the indexString from the given content. Searched for the given string, then moves over that string + 1 pos (new line), then reads the numbers until a '<' is found indexString - The string to search for. content - The content to search in. Returns: Integer if found, else -1<|endoftext|>
7d7c96ec2e7a8d26b6301caddc8acf16dabec58cca6fb8d3ae7d7699bc96a786
def getStatistics(session): '\n Scrape statistics from the web interface. Session needs to be authenticated\n beforehand.\n\n Returns an array containing the total bytes transfered\n [0] - Total Bytes Downloaded\n [1] - Total Bytes Sent\n\n Returns [-1, -1] if there is an error\n ' downUp = [(- 1), (- 1)] url = 'http://192.168.1.1/Forms/status_statistics_1' session.headers['Referer'] = 'http://192.168.1.1/status/status_statistics.htm' data = {'Stat_Radio': 'Zero', 'StatRefresh': 'REFRESH'} try: r = session.post(url, data=data, allow_redirects=True, timeout=5) if (r.url == 'http://192.168.1.1/login_security.html'): downUp = [(- 2), (- 2)] return downUp searchString = '<font color="#000000">Transmit total Bytes</font></td><td class="tabdata"><div align=center>' downUp[0] = extractValue(searchString, r.text) searchString = '<font color="#000000">Receive total Bytes</font></td><td class="tabdata"><div align=center>' downUp[1] = extractValue(searchString, r.text) except requests.Timeout as e: print('[ERROR] Request timed out while fetching statistics!') time.sleep(5) except requests.ConnectionError as e: print('[ERROR] Connection error while fetching statistics!') time.sleep(5) except socket.error as e: print('[ERROR] Socket error while fetching statistics!') time.sleep(5) except exception as e: print(e.message) finally: return downUp
Scrape statistics from the web interface. Session needs to be authenticated beforehand. Returns an array containing the total bytes transfered [0] - Total Bytes Downloaded [1] - Total Bytes Sent Returns [-1, -1] if there is an error
bandwidth-monitor.py
getStatistics
egeldenhuys/bandwidth-monitor
0
python
def getStatistics(session): '\n Scrape statistics from the web interface. Session needs to be authenticated\n beforehand.\n\n Returns an array containing the total bytes transfered\n [0] - Total Bytes Downloaded\n [1] - Total Bytes Sent\n\n Returns [-1, -1] if there is an error\n ' downUp = [(- 1), (- 1)] url = 'http://192.168.1.1/Forms/status_statistics_1' session.headers['Referer'] = 'http://192.168.1.1/status/status_statistics.htm' data = {'Stat_Radio': 'Zero', 'StatRefresh': 'REFRESH'} try: r = session.post(url, data=data, allow_redirects=True, timeout=5) if (r.url == 'http://192.168.1.1/login_security.html'): downUp = [(- 2), (- 2)] return downUp searchString = '<font color="#000000">Transmit total Bytes</font></td><td class="tabdata"><div align=center>' downUp[0] = extractValue(searchString, r.text) searchString = '<font color="#000000">Receive total Bytes</font></td><td class="tabdata"><div align=center>' downUp[1] = extractValue(searchString, r.text) except requests.Timeout as e: print('[ERROR] Request timed out while fetching statistics!') time.sleep(5) except requests.ConnectionError as e: print('[ERROR] Connection error while fetching statistics!') time.sleep(5) except socket.error as e: print('[ERROR] Socket error while fetching statistics!') time.sleep(5) except exception as e: print(e.message) finally: return downUp
def getStatistics(session): '\n Scrape statistics from the web interface. Session needs to be authenticated\n beforehand.\n\n Returns an array containing the total bytes transfered\n [0] - Total Bytes Downloaded\n [1] - Total Bytes Sent\n\n Returns [-1, -1] if there is an error\n ' downUp = [(- 1), (- 1)] url = 'http://192.168.1.1/Forms/status_statistics_1' session.headers['Referer'] = 'http://192.168.1.1/status/status_statistics.htm' data = {'Stat_Radio': 'Zero', 'StatRefresh': 'REFRESH'} try: r = session.post(url, data=data, allow_redirects=True, timeout=5) if (r.url == 'http://192.168.1.1/login_security.html'): downUp = [(- 2), (- 2)] return downUp searchString = '<font color="#000000">Transmit total Bytes</font></td><td class="tabdata"><div align=center>' downUp[0] = extractValue(searchString, r.text) searchString = '<font color="#000000">Receive total Bytes</font></td><td class="tabdata"><div align=center>' downUp[1] = extractValue(searchString, r.text) except requests.Timeout as e: print('[ERROR] Request timed out while fetching statistics!') time.sleep(5) except requests.ConnectionError as e: print('[ERROR] Connection error while fetching statistics!') time.sleep(5) except socket.error as e: print('[ERROR] Socket error while fetching statistics!') time.sleep(5) except exception as e: print(e.message) finally: return downUp<|docstring|>Scrape statistics from the web interface. Session needs to be authenticated beforehand. Returns an array containing the total bytes transfered [0] - Total Bytes Downloaded [1] - Total Bytes Sent Returns [-1, -1] if there is an error<|endoftext|>
75b95f6072ab753793fdb72bcccbab82bcd9fbfb81177eb89011125246be0254
def get_target_times(ti, tf, fmax=0.1): '\n Calculate desired target times given initial time, final time and\n maximum frequency.\n \n Time step is calculated using fmax, then the number of points is rounded up\n to get a power of two.\n \n Parameters\n ----------\n ti, tf: float\n initial and final time (days)\n fmax: float\n maximum frequency used to determine time step\n default = 0.1 (days^-1)\n ' T = (tf - ti) Dt_try = (2 * (1 / fmax)) n = round_to_p2(((T / Dt_try) + 1)) target_times = np.linspace(ti, tf, num=n, endpoint=True) return target_times
Calculate desired target times given initial time, final time and maximum frequency. Time step is calculated using fmax, then the number of points is rounded up to get a power of two. Parameters ---------- ti, tf: float initial and final time (days) fmax: float maximum frequency used to determine time step default = 0.1 (days^-1)
inspace/interpolation.py
get_target_times
Janna112358/nullstreams-enterprise
0
python
def get_target_times(ti, tf, fmax=0.1): '\n Calculate desired target times given initial time, final time and\n maximum frequency.\n \n Time step is calculated using fmax, then the number of points is rounded up\n to get a power of two.\n \n Parameters\n ----------\n ti, tf: float\n initial and final time (days)\n fmax: float\n maximum frequency used to determine time step\n default = 0.1 (days^-1)\n ' T = (tf - ti) Dt_try = (2 * (1 / fmax)) n = round_to_p2(((T / Dt_try) + 1)) target_times = np.linspace(ti, tf, num=n, endpoint=True) return target_times
def get_target_times(ti, tf, fmax=0.1): '\n Calculate desired target times given initial time, final time and\n maximum frequency.\n \n Time step is calculated using fmax, then the number of points is rounded up\n to get a power of two.\n \n Parameters\n ----------\n ti, tf: float\n initial and final time (days)\n fmax: float\n maximum frequency used to determine time step\n default = 0.1 (days^-1)\n ' T = (tf - ti) Dt_try = (2 * (1 / fmax)) n = round_to_p2(((T / Dt_try) + 1)) target_times = np.linspace(ti, tf, num=n, endpoint=True) return target_times<|docstring|>Calculate desired target times given initial time, final time and maximum frequency. Time step is calculated using fmax, then the number of points is rounded up to get a power of two. Parameters ---------- ti, tf: float initial and final time (days) fmax: float maximum frequency used to determine time step default = 0.1 (days^-1)<|endoftext|>
fd11cc4e314a922656e55e2db04e23c5303254aec44547d2d304440c1204da4a
def sinc_interpolation(x, x_data, y_data, TNy=1.0): '\n http://webee.technion.ac.il/Sites/People/YoninaEldar/Info/70.pdf\n \n Parameters\n ----------\n x: NumPy Array\n target x values\n x_data: NumPy Array\n input x values\n y_data: NumPy Array\n input y values\n TNy: float\n default = 1.0\n time scale used in the interpolation,\n frequencies above f=1/2TNy are filtered out\n \n Returns\n -------\n NumPy Array:\n interpolated y values at target x values\n ' n = len(x_data) T = ((max(x_data) - min(x_data)) / (n - 1)) shifts = (np.expand_dims(x, axis=1) - x_data) sincs = np.sinc((shifts / TNy)) weighted_points = (y_data * sincs) y_interp = ((T / TNy) * np.sum(weighted_points, axis=1)) return y_interp
http://webee.technion.ac.il/Sites/People/YoninaEldar/Info/70.pdf Parameters ---------- x: NumPy Array target x values x_data: NumPy Array input x values y_data: NumPy Array input y values TNy: float default = 1.0 time scale used in the interpolation, frequencies above f=1/2TNy are filtered out Returns ------- NumPy Array: interpolated y values at target x values
inspace/interpolation.py
sinc_interpolation
Janna112358/nullstreams-enterprise
0
python
def sinc_interpolation(x, x_data, y_data, TNy=1.0): '\n http://webee.technion.ac.il/Sites/People/YoninaEldar/Info/70.pdf\n \n Parameters\n ----------\n x: NumPy Array\n target x values\n x_data: NumPy Array\n input x values\n y_data: NumPy Array\n input y values\n TNy: float\n default = 1.0\n time scale used in the interpolation,\n frequencies above f=1/2TNy are filtered out\n \n Returns\n -------\n NumPy Array:\n interpolated y values at target x values\n ' n = len(x_data) T = ((max(x_data) - min(x_data)) / (n - 1)) shifts = (np.expand_dims(x, axis=1) - x_data) sincs = np.sinc((shifts / TNy)) weighted_points = (y_data * sincs) y_interp = ((T / TNy) * np.sum(weighted_points, axis=1)) return y_interp
def sinc_interpolation(x, x_data, y_data, TNy=1.0): '\n http://webee.technion.ac.il/Sites/People/YoninaEldar/Info/70.pdf\n \n Parameters\n ----------\n x: NumPy Array\n target x values\n x_data: NumPy Array\n input x values\n y_data: NumPy Array\n input y values\n TNy: float\n default = 1.0\n time scale used in the interpolation,\n frequencies above f=1/2TNy are filtered out\n \n Returns\n -------\n NumPy Array:\n interpolated y values at target x values\n ' n = len(x_data) T = ((max(x_data) - min(x_data)) / (n - 1)) shifts = (np.expand_dims(x, axis=1) - x_data) sincs = np.sinc((shifts / TNy)) weighted_points = (y_data * sincs) y_interp = ((T / TNy) * np.sum(weighted_points, axis=1)) return y_interp<|docstring|>http://webee.technion.ac.il/Sites/People/YoninaEldar/Info/70.pdf Parameters ---------- x: NumPy Array target x values x_data: NumPy Array input x values y_data: NumPy Array input y values TNy: float default = 1.0 time scale used in the interpolation, frequencies above f=1/2TNy are filtered out Returns ------- NumPy Array: interpolated y values at target x values<|endoftext|>
056467314e22c6a56277f1d9130a5905e4a9fa8ee2f4b036a189164cebd68131
def non_uniform_ToninaEldar(x, x_data, y_data): '\n eq 14 + 15(a) in Tonina & Eldar\n http://webee.technion.ac.il/Sites/People/YoninaEldar/Info/70.pdf\n ' T = (max(x_data) - min(x_data)) sample_shifts = (np.expand_dims(x_data, axis=(- 1)) - np.expand_dims(x_data, axis=0)) product_bottom = np.sin(((np.pi * sample_shifts) / T)) target_shifts = (np.expand_dims(x, axis=(- 1)) - np.expand_dims(x_data, axis=0)) product_top = np.sin(((np.pi * target_shifts) / T)) product = np.zeros(shape=(len(x), len(x_data))) for (i, j) in np.ndindex(product.shape): fraction = (product_top[i] / product_bottom[j]) fraction[j] = 1 product[(i, j)] = np.product(fraction) cosine_term = np.cos(((np.pi * target_shifts) / T)) weights = (cosine_term * product) weighted_points = (y_data * weights) interpolated = np.sum(weighted_points, axis=(- 1)) return interpolated
eq 14 + 15(a) in Tonina & Eldar http://webee.technion.ac.il/Sites/People/YoninaEldar/Info/70.pdf
inspace/interpolation.py
non_uniform_ToninaEldar
Janna112358/nullstreams-enterprise
0
python
def non_uniform_ToninaEldar(x, x_data, y_data): '\n eq 14 + 15(a) in Tonina & Eldar\n http://webee.technion.ac.il/Sites/People/YoninaEldar/Info/70.pdf\n ' T = (max(x_data) - min(x_data)) sample_shifts = (np.expand_dims(x_data, axis=(- 1)) - np.expand_dims(x_data, axis=0)) product_bottom = np.sin(((np.pi * sample_shifts) / T)) target_shifts = (np.expand_dims(x, axis=(- 1)) - np.expand_dims(x_data, axis=0)) product_top = np.sin(((np.pi * target_shifts) / T)) product = np.zeros(shape=(len(x), len(x_data))) for (i, j) in np.ndindex(product.shape): fraction = (product_top[i] / product_bottom[j]) fraction[j] = 1 product[(i, j)] = np.product(fraction) cosine_term = np.cos(((np.pi * target_shifts) / T)) weights = (cosine_term * product) weighted_points = (y_data * weights) interpolated = np.sum(weighted_points, axis=(- 1)) return interpolated
def non_uniform_ToninaEldar(x, x_data, y_data): '\n eq 14 + 15(a) in Tonina & Eldar\n http://webee.technion.ac.il/Sites/People/YoninaEldar/Info/70.pdf\n ' T = (max(x_data) - min(x_data)) sample_shifts = (np.expand_dims(x_data, axis=(- 1)) - np.expand_dims(x_data, axis=0)) product_bottom = np.sin(((np.pi * sample_shifts) / T)) target_shifts = (np.expand_dims(x, axis=(- 1)) - np.expand_dims(x_data, axis=0)) product_top = np.sin(((np.pi * target_shifts) / T)) product = np.zeros(shape=(len(x), len(x_data))) for (i, j) in np.ndindex(product.shape): fraction = (product_top[i] / product_bottom[j]) fraction[j] = 1 product[(i, j)] = np.product(fraction) cosine_term = np.cos(((np.pi * target_shifts) / T)) weights = (cosine_term * product) weighted_points = (y_data * weights) interpolated = np.sum(weighted_points, axis=(- 1)) return interpolated<|docstring|>eq 14 + 15(a) in Tonina & Eldar http://webee.technion.ac.il/Sites/People/YoninaEldar/Info/70.pdf<|endoftext|>
57bdac190a271071bcf9ba8106437e3a278da96900bf718426e19c8eef54e24b
def hang(n): '\n Hang body parts\n ' if (n == 6): scaffold() print('| ( * * ) |') print('| ( V ) |') for i in range(6): print('| |') elif (n == 5): scaffold() print('| ( * * ) |') print('| ( V ) |') print('| # |') print('| # |') print('| # |') print('| |') print('| |') print('| |') elif (n == 4): scaffold() print('| ( * * ) |') print('| ( o ) |') print('| # |') print('| ~ ~ # |') print('| # |') print('| |') print('| |') print('| |') elif (n == 3): scaffold() print('| ( * * ) |') print('| ( o ) |') print('| # |') print('| ~ ~ # ~ ~ |') print('| # |') print('| |') print('| |') print('| |') elif (n == 2): scaffold() print('| ( Q Q ) |') print('| ( W ) |') print('| # |') print('| ~ ~ # ~ ~ |') print('| # |') print('| / |') print('| \\ |') print('| |') elif (n == 1): scaffold() print('| ( Q Q ) |') print('| ( W ) |') print('| # |') print('| ~ ~ # ~ ~ |') print('| # |') print('| / \\ |') print('| \\ / |') print('| |') else: scaffold() print('| ( X X ) |') print('| ( ^ ) |') print('| # |') print('| ~ ~ # ~ ~ |') print('| # |') print('| / \\ |') print('| \\ / |') print('| |')
Hang body parts
Github/Hangman/hangman.py
hang
ZachhHsu/Stancode_SC101_project
0
python
def hang(n): '\n \n ' if (n == 6): scaffold() print('| ( * * ) |') print('| ( V ) |') for i in range(6): print('| |') elif (n == 5): scaffold() print('| ( * * ) |') print('| ( V ) |') print('| # |') print('| # |') print('| # |') print('| |') print('| |') print('| |') elif (n == 4): scaffold() print('| ( * * ) |') print('| ( o ) |') print('| # |') print('| ~ ~ # |') print('| # |') print('| |') print('| |') print('| |') elif (n == 3): scaffold() print('| ( * * ) |') print('| ( o ) |') print('| # |') print('| ~ ~ # ~ ~ |') print('| # |') print('| |') print('| |') print('| |') elif (n == 2): scaffold() print('| ( Q Q ) |') print('| ( W ) |') print('| # |') print('| ~ ~ # ~ ~ |') print('| # |') print('| / |') print('| \\ |') print('| |') elif (n == 1): scaffold() print('| ( Q Q ) |') print('| ( W ) |') print('| # |') print('| ~ ~ # ~ ~ |') print('| # |') print('| / \\ |') print('| \\ / |') print('| |') else: scaffold() print('| ( X X ) |') print('| ( ^ ) |') print('| # |') print('| ~ ~ # ~ ~ |') print('| # |') print('| / \\ |') print('| \\ / |') print('| |')
def hang(n): '\n \n ' if (n == 6): scaffold() print('| ( * * ) |') print('| ( V ) |') for i in range(6): print('| |') elif (n == 5): scaffold() print('| ( * * ) |') print('| ( V ) |') print('| # |') print('| # |') print('| # |') print('| |') print('| |') print('| |') elif (n == 4): scaffold() print('| ( * * ) |') print('| ( o ) |') print('| # |') print('| ~ ~ # |') print('| # |') print('| |') print('| |') print('| |') elif (n == 3): scaffold() print('| ( * * ) |') print('| ( o ) |') print('| # |') print('| ~ ~ # ~ ~ |') print('| # |') print('| |') print('| |') print('| |') elif (n == 2): scaffold() print('| ( Q Q ) |') print('| ( W ) |') print('| # |') print('| ~ ~ # ~ ~ |') print('| # |') print('| / |') print('| \\ |') print('| |') elif (n == 1): scaffold() print('| ( Q Q ) |') print('| ( W ) |') print('| # |') print('| ~ ~ # ~ ~ |') print('| # |') print('| / \\ |') print('| \\ / |') print('| |') else: scaffold() print('| ( X X ) |') print('| ( ^ ) |') print('| # |') print('| ~ ~ # ~ ~ |') print('| # |') print('| / \\ |') print('| \\ / |') print('| |')<|docstring|>Hang body parts<|endoftext|>
47efa4c4e200b77da70b2bec7ab9ac6aba695543b893b7d0145be448b736135c
def scaffold(): '\n Create a scaffold\n ' print('<Your Status>') print('-----------------') print('| | |') print('| | |')
Create a scaffold
Github/Hangman/hangman.py
scaffold
ZachhHsu/Stancode_SC101_project
0
python
def scaffold(): '\n \n ' print('<Your Status>') print('-----------------') print('| | |') print('| | |')
def scaffold(): '\n \n ' print('<Your Status>') print('-----------------') print('| | |') print('| | |')<|docstring|>Create a scaffold<|endoftext|>
a1abeacfbb68fc5c0773506a5cf8ba2e46bdd8112823a0333d99ec08b9bd61a1
def random_word(): '\n Here are some random vocabularies to be guessed\n ' num = random.choice(range(9)) if (num == 0): return 'NOTORIOUS' elif (num == 1): return 'GLAMOROUS' elif (num == 2): return 'CAUTIOUS' elif (num == 3): return 'DEMOCRACY' elif (num == 4): return 'BOYCOTT' elif (num == 5): return 'ENTHUSIASTIC' elif (num == 6): return 'HOSPITALITY' elif (num == 7): return 'BUNDLE' elif (num == 8): return 'REFUND'
Here are some random vocabularies to be guessed
Github/Hangman/hangman.py
random_word
ZachhHsu/Stancode_SC101_project
0
python
def random_word(): '\n \n ' num = random.choice(range(9)) if (num == 0): return 'NOTORIOUS' elif (num == 1): return 'GLAMOROUS' elif (num == 2): return 'CAUTIOUS' elif (num == 3): return 'DEMOCRACY' elif (num == 4): return 'BOYCOTT' elif (num == 5): return 'ENTHUSIASTIC' elif (num == 6): return 'HOSPITALITY' elif (num == 7): return 'BUNDLE' elif (num == 8): return 'REFUND'
def random_word(): '\n \n ' num = random.choice(range(9)) if (num == 0): return 'NOTORIOUS' elif (num == 1): return 'GLAMOROUS' elif (num == 2): return 'CAUTIOUS' elif (num == 3): return 'DEMOCRACY' elif (num == 4): return 'BOYCOTT' elif (num == 5): return 'ENTHUSIASTIC' elif (num == 6): return 'HOSPITALITY' elif (num == 7): return 'BUNDLE' elif (num == 8): return 'REFUND'<|docstring|>Here are some random vocabularies to be guessed<|endoftext|>
4b3b1fabef201dbc67e35ca2086876f9cbee499deee749fa1d5d1e596639e1c8
def attach_spm_pet_grouptemplate(main_wf, wf_name='spm_pet_template'): " Attach a PET pre-processing workflow that uses SPM12 to `main_wf`.\n This workflow picks all spm_pet_preproc outputs 'pet_output.warped_files' in `main_wf`\n to create a group template.\n\n Parameters\n ----------\n main_wf: nipype Workflow\n\n wf_name: str\n Name of the preprocessing workflow\n\n Nipype Inputs for `main_wf`\n ---------------------------\n Note: The `main_wf` workflow is expected to have an `input_files` and a `datasink` nodes.\n\n pet_output.warped_files: input node\n\n datasink: nipype Node\n\n spm_pet_preproc: nipype Workflow\n\n Nipype Outputs\n --------------\n group_template.pet_template: file\n The path to the PET group template.\n\n Nipype Workflow Dependencies\n ----------------------------\n This workflow depends on:\n - spm_pet_preproc\n - spm_anat_preproc if `spm_pet_template.do_petpvc` is True.\n\n Returns\n -------\n main_wf: nipype Workflow\n " pet_wf = get_subworkflow(main_wf, 'spm_pet_preproc') in_files = get_input_node(main_wf) datasink = get_datasink(main_wf, name='datasink') pet_fbasename = remove_ext(os.path.basename(get_input_file_name(in_files, 'pet'))) base_outdir = datasink.inputs.base_directory grp_datasink = pe.Node(DataSink(parameterization=False, base_directory=base_outdir), name='{}_grouptemplate_datasink'.format(pet_fbasename)) grp_datasink.inputs.container = '{}_grouptemplate'.format(pet_fbasename) warped_pets = pe.JoinNode(interface=IdentityInterface(fields=['warped_pets']), joinsource='infosrc', joinfield='warped_pets', name='warped_pets') template_wf = spm_create_group_template_wf(wf_name) output = setup_node(IdentityInterface(fields=['pet_template']), name='group_template') regexp_subst = [('/wgrptemplate{pet}_merged_mean_smooth.nii$', '/{pet}_grouptemplate_mni.nii'), ('/w{pet}_merged_mean_smooth.nii$', '/{pet}_grouptemplate_mni.nii')] regexp_subst = format_pair_list(regexp_subst, pet=pet_fbasename) regexp_subst += extension_duplicates(regexp_subst) grp_datasink.inputs.regexp_substitutions = extend_trait_list(grp_datasink.inputs.regexp_substitutions, regexp_subst) main_wf.connect([(pet_wf, warped_pets, [('warp_output.warped_files', 'warped_pets')]), (warped_pets, template_wf, [(('warped_pets', flatten_list), 'grptemplate_input.in_files')]), (template_wf, output, [('grptemplate_output.template', 'pet_template')]), (output, grp_datasink, [('pet_template', '@pet_grouptemplate')])]) do_petpvc = get_config_setting('spm_pet_template.do_petpvc') if do_petpvc: get_subworkflow(main_wf, 'spm_anat_preproc') preproc_wf_name = 'spm_mrpet_grouptemplate_preproc' main_wf = attach_spm_mrpet_preprocessing(main_wf, wf_name=preproc_wf_name, do_group_template=True) preproc_wf = get_subworkflow(main_wf, preproc_wf_name) main_wf.connect([(output, preproc_wf, [('pet_template', 'pet_input.pet_template')])]) else: reg_wf = spm_register_to_template_wf(wf_name='spm_pet_register_to_grouptemplate') main_wf.connect([(output, reg_wf, [('pet_template', 'reg_input.template')]), (in_files, reg_wf, [('pet', 'reg_input.in_file')]), (reg_wf, datasink, [('reg_output.warped', 'pet.group_template.@warped'), ('reg_output.warp_field', 'pet.group_template.@warp_field')])]) regexp_subst = [('group_template/{pet}_sn.mat$', 'group_template/{pet}_grptemplate_params.mat'), ('group_template/wgrptemplate_{pet}.nii$', 'group_template/{pet}_grptemplate.nii'), ('group_template/w{pet}.nii', 'group_template/{pet}_grptemplate.nii')] regexp_subst = format_pair_list(regexp_subst, pet=pet_fbasename) regexp_subst += extension_duplicates(regexp_subst) datasink.inputs.regexp_substitutions = extend_trait_list(datasink.inputs.regexp_substitutions, regexp_subst) return main_wf
Attach a PET pre-processing workflow that uses SPM12 to `main_wf`. This workflow picks all spm_pet_preproc outputs 'pet_output.warped_files' in `main_wf` to create a group template. Parameters ---------- main_wf: nipype Workflow wf_name: str Name of the preprocessing workflow Nipype Inputs for `main_wf` --------------------------- Note: The `main_wf` workflow is expected to have an `input_files` and a `datasink` nodes. pet_output.warped_files: input node datasink: nipype Node spm_pet_preproc: nipype Workflow Nipype Outputs -------------- group_template.pet_template: file The path to the PET group template. Nipype Workflow Dependencies ---------------------------- This workflow depends on: - spm_pet_preproc - spm_anat_preproc if `spm_pet_template.do_petpvc` is True. Returns ------- main_wf: nipype Workflow
neuro_pypes/pet/grouptemplate.py
attach_spm_pet_grouptemplate
Neurita/pypes
14
python
def attach_spm_pet_grouptemplate(main_wf, wf_name='spm_pet_template'): " Attach a PET pre-processing workflow that uses SPM12 to `main_wf`.\n This workflow picks all spm_pet_preproc outputs 'pet_output.warped_files' in `main_wf`\n to create a group template.\n\n Parameters\n ----------\n main_wf: nipype Workflow\n\n wf_name: str\n Name of the preprocessing workflow\n\n Nipype Inputs for `main_wf`\n ---------------------------\n Note: The `main_wf` workflow is expected to have an `input_files` and a `datasink` nodes.\n\n pet_output.warped_files: input node\n\n datasink: nipype Node\n\n spm_pet_preproc: nipype Workflow\n\n Nipype Outputs\n --------------\n group_template.pet_template: file\n The path to the PET group template.\n\n Nipype Workflow Dependencies\n ----------------------------\n This workflow depends on:\n - spm_pet_preproc\n - spm_anat_preproc if `spm_pet_template.do_petpvc` is True.\n\n Returns\n -------\n main_wf: nipype Workflow\n " pet_wf = get_subworkflow(main_wf, 'spm_pet_preproc') in_files = get_input_node(main_wf) datasink = get_datasink(main_wf, name='datasink') pet_fbasename = remove_ext(os.path.basename(get_input_file_name(in_files, 'pet'))) base_outdir = datasink.inputs.base_directory grp_datasink = pe.Node(DataSink(parameterization=False, base_directory=base_outdir), name='{}_grouptemplate_datasink'.format(pet_fbasename)) grp_datasink.inputs.container = '{}_grouptemplate'.format(pet_fbasename) warped_pets = pe.JoinNode(interface=IdentityInterface(fields=['warped_pets']), joinsource='infosrc', joinfield='warped_pets', name='warped_pets') template_wf = spm_create_group_template_wf(wf_name) output = setup_node(IdentityInterface(fields=['pet_template']), name='group_template') regexp_subst = [('/wgrptemplate{pet}_merged_mean_smooth.nii$', '/{pet}_grouptemplate_mni.nii'), ('/w{pet}_merged_mean_smooth.nii$', '/{pet}_grouptemplate_mni.nii')] regexp_subst = format_pair_list(regexp_subst, pet=pet_fbasename) regexp_subst += extension_duplicates(regexp_subst) grp_datasink.inputs.regexp_substitutions = extend_trait_list(grp_datasink.inputs.regexp_substitutions, regexp_subst) main_wf.connect([(pet_wf, warped_pets, [('warp_output.warped_files', 'warped_pets')]), (warped_pets, template_wf, [(('warped_pets', flatten_list), 'grptemplate_input.in_files')]), (template_wf, output, [('grptemplate_output.template', 'pet_template')]), (output, grp_datasink, [('pet_template', '@pet_grouptemplate')])]) do_petpvc = get_config_setting('spm_pet_template.do_petpvc') if do_petpvc: get_subworkflow(main_wf, 'spm_anat_preproc') preproc_wf_name = 'spm_mrpet_grouptemplate_preproc' main_wf = attach_spm_mrpet_preprocessing(main_wf, wf_name=preproc_wf_name, do_group_template=True) preproc_wf = get_subworkflow(main_wf, preproc_wf_name) main_wf.connect([(output, preproc_wf, [('pet_template', 'pet_input.pet_template')])]) else: reg_wf = spm_register_to_template_wf(wf_name='spm_pet_register_to_grouptemplate') main_wf.connect([(output, reg_wf, [('pet_template', 'reg_input.template')]), (in_files, reg_wf, [('pet', 'reg_input.in_file')]), (reg_wf, datasink, [('reg_output.warped', 'pet.group_template.@warped'), ('reg_output.warp_field', 'pet.group_template.@warp_field')])]) regexp_subst = [('group_template/{pet}_sn.mat$', 'group_template/{pet}_grptemplate_params.mat'), ('group_template/wgrptemplate_{pet}.nii$', 'group_template/{pet}_grptemplate.nii'), ('group_template/w{pet}.nii', 'group_template/{pet}_grptemplate.nii')] regexp_subst = format_pair_list(regexp_subst, pet=pet_fbasename) regexp_subst += extension_duplicates(regexp_subst) datasink.inputs.regexp_substitutions = extend_trait_list(datasink.inputs.regexp_substitutions, regexp_subst) return main_wf
def attach_spm_pet_grouptemplate(main_wf, wf_name='spm_pet_template'): " Attach a PET pre-processing workflow that uses SPM12 to `main_wf`.\n This workflow picks all spm_pet_preproc outputs 'pet_output.warped_files' in `main_wf`\n to create a group template.\n\n Parameters\n ----------\n main_wf: nipype Workflow\n\n wf_name: str\n Name of the preprocessing workflow\n\n Nipype Inputs for `main_wf`\n ---------------------------\n Note: The `main_wf` workflow is expected to have an `input_files` and a `datasink` nodes.\n\n pet_output.warped_files: input node\n\n datasink: nipype Node\n\n spm_pet_preproc: nipype Workflow\n\n Nipype Outputs\n --------------\n group_template.pet_template: file\n The path to the PET group template.\n\n Nipype Workflow Dependencies\n ----------------------------\n This workflow depends on:\n - spm_pet_preproc\n - spm_anat_preproc if `spm_pet_template.do_petpvc` is True.\n\n Returns\n -------\n main_wf: nipype Workflow\n " pet_wf = get_subworkflow(main_wf, 'spm_pet_preproc') in_files = get_input_node(main_wf) datasink = get_datasink(main_wf, name='datasink') pet_fbasename = remove_ext(os.path.basename(get_input_file_name(in_files, 'pet'))) base_outdir = datasink.inputs.base_directory grp_datasink = pe.Node(DataSink(parameterization=False, base_directory=base_outdir), name='{}_grouptemplate_datasink'.format(pet_fbasename)) grp_datasink.inputs.container = '{}_grouptemplate'.format(pet_fbasename) warped_pets = pe.JoinNode(interface=IdentityInterface(fields=['warped_pets']), joinsource='infosrc', joinfield='warped_pets', name='warped_pets') template_wf = spm_create_group_template_wf(wf_name) output = setup_node(IdentityInterface(fields=['pet_template']), name='group_template') regexp_subst = [('/wgrptemplate{pet}_merged_mean_smooth.nii$', '/{pet}_grouptemplate_mni.nii'), ('/w{pet}_merged_mean_smooth.nii$', '/{pet}_grouptemplate_mni.nii')] regexp_subst = format_pair_list(regexp_subst, pet=pet_fbasename) regexp_subst += extension_duplicates(regexp_subst) grp_datasink.inputs.regexp_substitutions = extend_trait_list(grp_datasink.inputs.regexp_substitutions, regexp_subst) main_wf.connect([(pet_wf, warped_pets, [('warp_output.warped_files', 'warped_pets')]), (warped_pets, template_wf, [(('warped_pets', flatten_list), 'grptemplate_input.in_files')]), (template_wf, output, [('grptemplate_output.template', 'pet_template')]), (output, grp_datasink, [('pet_template', '@pet_grouptemplate')])]) do_petpvc = get_config_setting('spm_pet_template.do_petpvc') if do_petpvc: get_subworkflow(main_wf, 'spm_anat_preproc') preproc_wf_name = 'spm_mrpet_grouptemplate_preproc' main_wf = attach_spm_mrpet_preprocessing(main_wf, wf_name=preproc_wf_name, do_group_template=True) preproc_wf = get_subworkflow(main_wf, preproc_wf_name) main_wf.connect([(output, preproc_wf, [('pet_template', 'pet_input.pet_template')])]) else: reg_wf = spm_register_to_template_wf(wf_name='spm_pet_register_to_grouptemplate') main_wf.connect([(output, reg_wf, [('pet_template', 'reg_input.template')]), (in_files, reg_wf, [('pet', 'reg_input.in_file')]), (reg_wf, datasink, [('reg_output.warped', 'pet.group_template.@warped'), ('reg_output.warp_field', 'pet.group_template.@warp_field')])]) regexp_subst = [('group_template/{pet}_sn.mat$', 'group_template/{pet}_grptemplate_params.mat'), ('group_template/wgrptemplate_{pet}.nii$', 'group_template/{pet}_grptemplate.nii'), ('group_template/w{pet}.nii', 'group_template/{pet}_grptemplate.nii')] regexp_subst = format_pair_list(regexp_subst, pet=pet_fbasename) regexp_subst += extension_duplicates(regexp_subst) datasink.inputs.regexp_substitutions = extend_trait_list(datasink.inputs.regexp_substitutions, regexp_subst) return main_wf<|docstring|>Attach a PET pre-processing workflow that uses SPM12 to `main_wf`. This workflow picks all spm_pet_preproc outputs 'pet_output.warped_files' in `main_wf` to create a group template. Parameters ---------- main_wf: nipype Workflow wf_name: str Name of the preprocessing workflow Nipype Inputs for `main_wf` --------------------------- Note: The `main_wf` workflow is expected to have an `input_files` and a `datasink` nodes. pet_output.warped_files: input node datasink: nipype Node spm_pet_preproc: nipype Workflow Nipype Outputs -------------- group_template.pet_template: file The path to the PET group template. Nipype Workflow Dependencies ---------------------------- This workflow depends on: - spm_pet_preproc - spm_anat_preproc if `spm_pet_template.do_petpvc` is True. Returns ------- main_wf: nipype Workflow<|endoftext|>
7991f914942a2c1d12d9c25459aa1fa11b16cab4248aa68128c3f36273830995
def read_with_nulls(filepath: str, skiprows: Union[(None, int)]=None) -> pd.DataFrame: 'Read in CSV as a pandas DataFrame and fill in NaNs as empty strings' df = pd.read_csv(filepath, sep=',', skiprows=skiprows).fillna('') return df
Read in CSV as a pandas DataFrame and fill in NaNs as empty strings
clean_data.py
read_with_nulls
prrao87/application-graph
0
python
def read_with_nulls(filepath: str, skiprows: Union[(None, int)]=None) -> pd.DataFrame: df = pd.read_csv(filepath, sep=',', skiprows=skiprows).fillna() return df
def read_with_nulls(filepath: str, skiprows: Union[(None, int)]=None) -> pd.DataFrame: df = pd.read_csv(filepath, sep=',', skiprows=skiprows).fillna() return df<|docstring|>Read in CSV as a pandas DataFrame and fill in NaNs as empty strings<|endoftext|>
82ca194a853f248290d8b15c013417d563e53cfe7bdcf3e0ff22234b31df2d1c
def lookup_id(id_map: Dict[(str, int)], key: str) -> int: 'Return integer ID for a given string PERSID key' return id_map[key]
Return integer ID for a given string PERSID key
clean_data.py
lookup_id
prrao87/application-graph
0
python
def lookup_id(id_map: Dict[(str, int)], key: str) -> int: return id_map[key]
def lookup_id(id_map: Dict[(str, int)], key: str) -> int: return id_map[key]<|docstring|>Return integer ID for a given string PERSID key<|endoftext|>
649368bc8564353b9a32c228861519de255e993b93674c8df7fb7706d8dd5eac
def clean_app_file(filename: str, rawfile_path: str, outpath: str) -> Dict[(str, int)]: 'Convert string IDs to int for apps/services persistent IDs and output to CSV' apps_df = read_with_nulls(os.path.join(rawfile_path, filename)) persids = [item.strip() for item in list(apps_df['PERSID'])] apps_df = apps_df.drop('PERSID', axis=1) apps_df.insert(0, 'persid_int', (apps_df.index + 1)) apps_df.rename({'persid_int': 'PERSID'}, axis=1, inplace=True) apps_df.to_csv(os.path.join(outpath, filename), index=False, header=True) app_id_map = dict(zip(persids, list(apps_df['PERSID']))) return app_id_map
Convert string IDs to int for apps/services persistent IDs and output to CSV
clean_data.py
clean_app_file
prrao87/application-graph
0
python
def clean_app_file(filename: str, rawfile_path: str, outpath: str) -> Dict[(str, int)]: apps_df = read_with_nulls(os.path.join(rawfile_path, filename)) persids = [item.strip() for item in list(apps_df['PERSID'])] apps_df = apps_df.drop('PERSID', axis=1) apps_df.insert(0, 'persid_int', (apps_df.index + 1)) apps_df.rename({'persid_int': 'PERSID'}, axis=1, inplace=True) apps_df.to_csv(os.path.join(outpath, filename), index=False, header=True) app_id_map = dict(zip(persids, list(apps_df['PERSID']))) return app_id_map
def clean_app_file(filename: str, rawfile_path: str, outpath: str) -> Dict[(str, int)]: apps_df = read_with_nulls(os.path.join(rawfile_path, filename)) persids = [item.strip() for item in list(apps_df['PERSID'])] apps_df = apps_df.drop('PERSID', axis=1) apps_df.insert(0, 'persid_int', (apps_df.index + 1)) apps_df.rename({'persid_int': 'PERSID'}, axis=1, inplace=True) apps_df.to_csv(os.path.join(outpath, filename), index=False, header=True) app_id_map = dict(zip(persids, list(apps_df['PERSID']))) return app_id_map<|docstring|>Convert string IDs to int for apps/services persistent IDs and output to CSV<|endoftext|>
05a34362c08a95000b16ab7a48285ed8aa641e99ccd598204da12a325e48e765
def clean_org_file(filename: str, rawfile_path: str, outpath: str, app_id_map: Dict[(str, int)]) -> None: "Convert string IDs to int for organization's app persistent IDs and output to CSV" orgs_df = read_with_nulls(os.path.join(rawfile_path, filename)) orgs_df['PERSID'] = orgs_df['PERSID'].str.replace('nr:', '') orgs_df.insert(0, 'persid_int', orgs_df['PERSID'].apply((lambda x: lookup_id(app_id_map, x)))) orgs_df = orgs_df.drop('PERSID', axis=1) orgs_df.rename({'persid_int': 'APP_PERSID'}, axis=1, inplace=True) orgs_df.to_csv(os.path.join(outpath, filename), index=False, header=True)
Convert string IDs to int for organization's app persistent IDs and output to CSV
clean_data.py
clean_org_file
prrao87/application-graph
0
python
def clean_org_file(filename: str, rawfile_path: str, outpath: str, app_id_map: Dict[(str, int)]) -> None: orgs_df = read_with_nulls(os.path.join(rawfile_path, filename)) orgs_df['PERSID'] = orgs_df['PERSID'].str.replace('nr:', ) orgs_df.insert(0, 'persid_int', orgs_df['PERSID'].apply((lambda x: lookup_id(app_id_map, x)))) orgs_df = orgs_df.drop('PERSID', axis=1) orgs_df.rename({'persid_int': 'APP_PERSID'}, axis=1, inplace=True) orgs_df.to_csv(os.path.join(outpath, filename), index=False, header=True)
def clean_org_file(filename: str, rawfile_path: str, outpath: str, app_id_map: Dict[(str, int)]) -> None: orgs_df = read_with_nulls(os.path.join(rawfile_path, filename)) orgs_df['PERSID'] = orgs_df['PERSID'].str.replace('nr:', ) orgs_df.insert(0, 'persid_int', orgs_df['PERSID'].apply((lambda x: lookup_id(app_id_map, x)))) orgs_df = orgs_df.drop('PERSID', axis=1) orgs_df.rename({'persid_int': 'APP_PERSID'}, axis=1, inplace=True) orgs_df.to_csv(os.path.join(outpath, filename), index=False, header=True)<|docstring|>Convert string IDs to int for organization's app persistent IDs and output to CSV<|endoftext|>
a5f1688e488676b12c207bbbc95b0b201e954688ae4e05dc4694816ec19e6f52
def clean_ahd_file(filename: str, rawfile_path: str, outpath: str, app_id_map: Dict[(str, int)]) -> None: 'Convert string IDs to int for AHD hitrate file and output to CSV' ahd_df = read_with_nulls(os.path.join(rawfile_path, filename)) ahd_df['PERSID'] = ahd_df['PERSID'].str.replace('nr:', '') ahd_df.insert(0, 'persid_int', ahd_df['PERSID'].apply((lambda x: lookup_id(app_id_map, x)))) ahd_df = ahd_df.drop('PERSID', axis=1) ahd_df.rename({'persid_int': 'APP_PERSID'}, axis=1, inplace=True) ahd_df.to_csv(os.path.join(outpath, filename), index=False, header=True)
Convert string IDs to int for AHD hitrate file and output to CSV
clean_data.py
clean_ahd_file
prrao87/application-graph
0
python
def clean_ahd_file(filename: str, rawfile_path: str, outpath: str, app_id_map: Dict[(str, int)]) -> None: ahd_df = read_with_nulls(os.path.join(rawfile_path, filename)) ahd_df['PERSID'] = ahd_df['PERSID'].str.replace('nr:', ) ahd_df.insert(0, 'persid_int', ahd_df['PERSID'].apply((lambda x: lookup_id(app_id_map, x)))) ahd_df = ahd_df.drop('PERSID', axis=1) ahd_df.rename({'persid_int': 'APP_PERSID'}, axis=1, inplace=True) ahd_df.to_csv(os.path.join(outpath, filename), index=False, header=True)
def clean_ahd_file(filename: str, rawfile_path: str, outpath: str, app_id_map: Dict[(str, int)]) -> None: ahd_df = read_with_nulls(os.path.join(rawfile_path, filename)) ahd_df['PERSID'] = ahd_df['PERSID'].str.replace('nr:', ) ahd_df.insert(0, 'persid_int', ahd_df['PERSID'].apply((lambda x: lookup_id(app_id_map, x)))) ahd_df = ahd_df.drop('PERSID', axis=1) ahd_df.rename({'persid_int': 'APP_PERSID'}, axis=1, inplace=True) ahd_df.to_csv(os.path.join(outpath, filename), index=False, header=True)<|docstring|>Convert string IDs to int for AHD hitrate file and output to CSV<|endoftext|>
60e7172e47b6150975a969bba34bf433b6daca367ca8661afc7e5b879e5a9fc9
def clean_os_instances_file(filename: str, rawfile_path: str, outpath: str) -> None: '\n Convert string IDs to int for OS instances monthly usage file and output to CSV.\n Note that the PERSIDs in this file are NOT the same as the PERSIDs for the app file,\n hence we restart the numbering from 1.\n ' os_instances_df = read_with_nulls(os.path.join(rawfile_path, filename)) os_instances_df.rename({u'os_\ufeffPersID': 'PERSID'}, axis=1, inplace=True) os_instances_df.insert(0, 'persid_int', (os_instances_df.index + 1)) persids = [item.strip() for item in list(os_instances_df['PERSID'])] os_instances_df = os_instances_df.drop('PERSID', axis=1) os_instances_df.rename({'persid_int': 'OS_PERSID'}, axis=1, inplace=True) os_instances_df.to_csv(os.path.join(outpath, filename), index=False, header=True) os_id_map = dict(zip(persids, list(os_instances_df['OS_PERSID']))) return os_id_map
Convert string IDs to int for OS instances monthly usage file and output to CSV. Note that the PERSIDs in this file are NOT the same as the PERSIDs for the app file, hence we restart the numbering from 1.
clean_data.py
clean_os_instances_file
prrao87/application-graph
0
python
def clean_os_instances_file(filename: str, rawfile_path: str, outpath: str) -> None: '\n Convert string IDs to int for OS instances monthly usage file and output to CSV.\n Note that the PERSIDs in this file are NOT the same as the PERSIDs for the app file,\n hence we restart the numbering from 1.\n ' os_instances_df = read_with_nulls(os.path.join(rawfile_path, filename)) os_instances_df.rename({u'os_\ufeffPersID': 'PERSID'}, axis=1, inplace=True) os_instances_df.insert(0, 'persid_int', (os_instances_df.index + 1)) persids = [item.strip() for item in list(os_instances_df['PERSID'])] os_instances_df = os_instances_df.drop('PERSID', axis=1) os_instances_df.rename({'persid_int': 'OS_PERSID'}, axis=1, inplace=True) os_instances_df.to_csv(os.path.join(outpath, filename), index=False, header=True) os_id_map = dict(zip(persids, list(os_instances_df['OS_PERSID']))) return os_id_map
def clean_os_instances_file(filename: str, rawfile_path: str, outpath: str) -> None: '\n Convert string IDs to int for OS instances monthly usage file and output to CSV.\n Note that the PERSIDs in this file are NOT the same as the PERSIDs for the app file,\n hence we restart the numbering from 1.\n ' os_instances_df = read_with_nulls(os.path.join(rawfile_path, filename)) os_instances_df.rename({u'os_\ufeffPersID': 'PERSID'}, axis=1, inplace=True) os_instances_df.insert(0, 'persid_int', (os_instances_df.index + 1)) persids = [item.strip() for item in list(os_instances_df['PERSID'])] os_instances_df = os_instances_df.drop('PERSID', axis=1) os_instances_df.rename({'persid_int': 'OS_PERSID'}, axis=1, inplace=True) os_instances_df.to_csv(os.path.join(outpath, filename), index=False, header=True) os_id_map = dict(zip(persids, list(os_instances_df['OS_PERSID']))) return os_id_map<|docstring|>Convert string IDs to int for OS instances monthly usage file and output to CSV. Note that the PERSIDs in this file are NOT the same as the PERSIDs for the app file, hence we restart the numbering from 1.<|endoftext|>
e9c2c9a36e3ae411a83ee99717298aa16e7ea01ba447fa6dc9161c7d694719d8
def clean_similarity_connectedcomps_file(filename: str, rawfile_path: str, outpath: str, app_id_map: Dict[(str, int)]) -> None: '\n Clean up and format string IDs in the connected components similarity table and\n output to CSV.\n ' similarities_df = read_with_nulls(os.path.join(rawfile_path, filename)) similarities_df['PersID-1'] = similarities_df['PersID-1'].str.replace('nr:', '') similarities_df['PersID-2'] = similarities_df['PersID-2'].str.replace('nr:', '') similarities_df.insert(0, 'PERSID_1', similarities_df['PersID-1'].apply((lambda x: lookup_id(app_id_map, x)))) similarities_df.insert(1, 'PERSID_2', similarities_df['PersID-2'].apply((lambda x: lookup_id(app_id_map, x)))) similarities_df = similarities_df.drop(['PersID-1', 'PersID-2'], axis=1) similarities_df.to_csv(os.path.join(outpath, filename), index=False, header=True)
Clean up and format string IDs in the connected components similarity table and output to CSV.
clean_data.py
clean_similarity_connectedcomps_file
prrao87/application-graph
0
python
def clean_similarity_connectedcomps_file(filename: str, rawfile_path: str, outpath: str, app_id_map: Dict[(str, int)]) -> None: '\n Clean up and format string IDs in the connected components similarity table and\n output to CSV.\n ' similarities_df = read_with_nulls(os.path.join(rawfile_path, filename)) similarities_df['PersID-1'] = similarities_df['PersID-1'].str.replace('nr:', ) similarities_df['PersID-2'] = similarities_df['PersID-2'].str.replace('nr:', ) similarities_df.insert(0, 'PERSID_1', similarities_df['PersID-1'].apply((lambda x: lookup_id(app_id_map, x)))) similarities_df.insert(1, 'PERSID_2', similarities_df['PersID-2'].apply((lambda x: lookup_id(app_id_map, x)))) similarities_df = similarities_df.drop(['PersID-1', 'PersID-2'], axis=1) similarities_df.to_csv(os.path.join(outpath, filename), index=False, header=True)
def clean_similarity_connectedcomps_file(filename: str, rawfile_path: str, outpath: str, app_id_map: Dict[(str, int)]) -> None: '\n Clean up and format string IDs in the connected components similarity table and\n output to CSV.\n ' similarities_df = read_with_nulls(os.path.join(rawfile_path, filename)) similarities_df['PersID-1'] = similarities_df['PersID-1'].str.replace('nr:', ) similarities_df['PersID-2'] = similarities_df['PersID-2'].str.replace('nr:', ) similarities_df.insert(0, 'PERSID_1', similarities_df['PersID-1'].apply((lambda x: lookup_id(app_id_map, x)))) similarities_df.insert(1, 'PERSID_2', similarities_df['PersID-2'].apply((lambda x: lookup_id(app_id_map, x)))) similarities_df = similarities_df.drop(['PersID-1', 'PersID-2'], axis=1) similarities_df.to_csv(os.path.join(outpath, filename), index=False, header=True)<|docstring|>Clean up and format string IDs in the connected components similarity table and output to CSV.<|endoftext|>
3c95e9d4fe5b3892ee620ed3c5683b6129364d62e781e9c6c32e7526a4c08aef
def _log_record_context_injector(*args: Any, **kwargs: Any) -> logging.LogRecord: '\n A custom logger LogRecord Factory that injects selected context parameters into newly\n created logs.\n\n Args:\n - *args: arguments to pass to the original LogRecord Factory\n - **kwargs: keyword arguments to pass to the original LogRecord Factory\n\n Returns:\n - logging.LogRecord: the newly created LogRecord\n ' record = _original_log_record_factory(*args, **kwargs) additional_attrs = context.config.logging.get('log_attributes', []) for attr in (PREFECT_LOG_RECORD_ATTRIBUTES + tuple(additional_attrs)): value = context.get(attr, None) if (value or (attr in additional_attrs)): setattr(record, attr, value) return record
A custom logger LogRecord Factory that injects selected context parameters into newly created logs. Args: - *args: arguments to pass to the original LogRecord Factory - **kwargs: keyword arguments to pass to the original LogRecord Factory Returns: - logging.LogRecord: the newly created LogRecord
src/prefect/utilities/logging.py
_log_record_context_injector
zschumacher/prefect
1
python
def _log_record_context_injector(*args: Any, **kwargs: Any) -> logging.LogRecord: '\n A custom logger LogRecord Factory that injects selected context parameters into newly\n created logs.\n\n Args:\n - *args: arguments to pass to the original LogRecord Factory\n - **kwargs: keyword arguments to pass to the original LogRecord Factory\n\n Returns:\n - logging.LogRecord: the newly created LogRecord\n ' record = _original_log_record_factory(*args, **kwargs) additional_attrs = context.config.logging.get('log_attributes', []) for attr in (PREFECT_LOG_RECORD_ATTRIBUTES + tuple(additional_attrs)): value = context.get(attr, None) if (value or (attr in additional_attrs)): setattr(record, attr, value) return record
def _log_record_context_injector(*args: Any, **kwargs: Any) -> logging.LogRecord: '\n A custom logger LogRecord Factory that injects selected context parameters into newly\n created logs.\n\n Args:\n - *args: arguments to pass to the original LogRecord Factory\n - **kwargs: keyword arguments to pass to the original LogRecord Factory\n\n Returns:\n - logging.LogRecord: the newly created LogRecord\n ' record = _original_log_record_factory(*args, **kwargs) additional_attrs = context.config.logging.get('log_attributes', []) for attr in (PREFECT_LOG_RECORD_ATTRIBUTES + tuple(additional_attrs)): value = context.get(attr, None) if (value or (attr in additional_attrs)): setattr(record, attr, value) return record<|docstring|>A custom logger LogRecord Factory that injects selected context parameters into newly created logs. Args: - *args: arguments to pass to the original LogRecord Factory - **kwargs: keyword arguments to pass to the original LogRecord Factory Returns: - logging.LogRecord: the newly created LogRecord<|endoftext|>
7fb587d81cbbc0caaac2f414460eacc38dac95e96521528c0261ebc30ee7f4b8
def _create_logger(name: str) -> logging.Logger: '\n Creates a logger with a `StreamHandler` that has level and formatting\n set from `prefect.config`.\n\n Args:\n - name (str): Name to use for logger.\n\n Returns:\n - logging.Logger: a configured logging object\n ' logging.setLogRecordFactory(_log_record_context_injector) logger = logging.getLogger(name) handler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter(context.config.logging.format, context.config.logging.datefmt) handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(context.config.logging.level) logger.addHandler(CloudHandler()) return logger
Creates a logger with a `StreamHandler` that has level and formatting set from `prefect.config`. Args: - name (str): Name to use for logger. Returns: - logging.Logger: a configured logging object
src/prefect/utilities/logging.py
_create_logger
zschumacher/prefect
1
python
def _create_logger(name: str) -> logging.Logger: '\n Creates a logger with a `StreamHandler` that has level and formatting\n set from `prefect.config`.\n\n Args:\n - name (str): Name to use for logger.\n\n Returns:\n - logging.Logger: a configured logging object\n ' logging.setLogRecordFactory(_log_record_context_injector) logger = logging.getLogger(name) handler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter(context.config.logging.format, context.config.logging.datefmt) handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(context.config.logging.level) logger.addHandler(CloudHandler()) return logger
def _create_logger(name: str) -> logging.Logger: '\n Creates a logger with a `StreamHandler` that has level and formatting\n set from `prefect.config`.\n\n Args:\n - name (str): Name to use for logger.\n\n Returns:\n - logging.Logger: a configured logging object\n ' logging.setLogRecordFactory(_log_record_context_injector) logger = logging.getLogger(name) handler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter(context.config.logging.format, context.config.logging.datefmt) handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(context.config.logging.level) logger.addHandler(CloudHandler()) return logger<|docstring|>Creates a logger with a `StreamHandler` that has level and formatting set from `prefect.config`. Args: - name (str): Name to use for logger. Returns: - logging.Logger: a configured logging object<|endoftext|>
3487908d17355f7a8b991c421fcb83d9b3f4f763e7615aff9e2bccb9e79e2c84
def configure_logging(testing: bool=False) -> logging.Logger: '\n Creates a "prefect" root logger with a `StreamHandler` that has level and formatting\n set from `prefect.config`.\n\n Args:\n - testing (bool, optional): a boolean specifying whether this configuration\n is for testing purposes only; this helps us isolate any global state during testing\n by configuring a "prefect-test-logger" instead of the standard "prefect" logger\n\n Returns:\n - logging.Logger: a configured logging object\n ' name = ('prefect-test-logger' if testing else 'prefect') return _create_logger(name)
Creates a "prefect" root logger with a `StreamHandler` that has level and formatting set from `prefect.config`. Args: - testing (bool, optional): a boolean specifying whether this configuration is for testing purposes only; this helps us isolate any global state during testing by configuring a "prefect-test-logger" instead of the standard "prefect" logger Returns: - logging.Logger: a configured logging object
src/prefect/utilities/logging.py
configure_logging
zschumacher/prefect
1
python
def configure_logging(testing: bool=False) -> logging.Logger: '\n Creates a "prefect" root logger with a `StreamHandler` that has level and formatting\n set from `prefect.config`.\n\n Args:\n - testing (bool, optional): a boolean specifying whether this configuration\n is for testing purposes only; this helps us isolate any global state during testing\n by configuring a "prefect-test-logger" instead of the standard "prefect" logger\n\n Returns:\n - logging.Logger: a configured logging object\n ' name = ('prefect-test-logger' if testing else 'prefect') return _create_logger(name)
def configure_logging(testing: bool=False) -> logging.Logger: '\n Creates a "prefect" root logger with a `StreamHandler` that has level and formatting\n set from `prefect.config`.\n\n Args:\n - testing (bool, optional): a boolean specifying whether this configuration\n is for testing purposes only; this helps us isolate any global state during testing\n by configuring a "prefect-test-logger" instead of the standard "prefect" logger\n\n Returns:\n - logging.Logger: a configured logging object\n ' name = ('prefect-test-logger' if testing else 'prefect') return _create_logger(name)<|docstring|>Creates a "prefect" root logger with a `StreamHandler` that has level and formatting set from `prefect.config`. Args: - testing (bool, optional): a boolean specifying whether this configuration is for testing purposes only; this helps us isolate any global state during testing by configuring a "prefect-test-logger" instead of the standard "prefect" logger Returns: - logging.Logger: a configured logging object<|endoftext|>
ac2abaee8ac1a60264e2e3b300f7047b9f3f198b80ef502b2c483ba2da2d6b06
def configure_extra_loggers() -> None: '\n Creates a "Prefect" configured logger for all strings in extra_loggers config list.\n The logging.extra_loggers config defaults to an empty list.\n ' loggers = context.config.logging.get('extra_loggers', []) for l in loggers: _create_logger(l)
Creates a "Prefect" configured logger for all strings in extra_loggers config list. The logging.extra_loggers config defaults to an empty list.
src/prefect/utilities/logging.py
configure_extra_loggers
zschumacher/prefect
1
python
def configure_extra_loggers() -> None: '\n Creates a "Prefect" configured logger for all strings in extra_loggers config list.\n The logging.extra_loggers config defaults to an empty list.\n ' loggers = context.config.logging.get('extra_loggers', []) for l in loggers: _create_logger(l)
def configure_extra_loggers() -> None: '\n Creates a "Prefect" configured logger for all strings in extra_loggers config list.\n The logging.extra_loggers config defaults to an empty list.\n ' loggers = context.config.logging.get('extra_loggers', []) for l in loggers: _create_logger(l)<|docstring|>Creates a "Prefect" configured logger for all strings in extra_loggers config list. The logging.extra_loggers config defaults to an empty list.<|endoftext|>
61503c269da0b95c6ee3d03c0e4167b8a49a14e6a5f4f8a53cfa333aadcb3168
def create_diagnostic_logger(name: str) -> logging.Logger: '\n Create a logger that does not use the `CloudHandler` but preserves all other\n Prefect logging configuration. For diagnostic / debugging / internal use only.\n ' logger = _create_logger(name) logger.handlers = [h for h in logger.handlers if (not isinstance(h, CloudHandler))] return logger
Create a logger that does not use the `CloudHandler` but preserves all other Prefect logging configuration. For diagnostic / debugging / internal use only.
src/prefect/utilities/logging.py
create_diagnostic_logger
zschumacher/prefect
1
python
def create_diagnostic_logger(name: str) -> logging.Logger: '\n Create a logger that does not use the `CloudHandler` but preserves all other\n Prefect logging configuration. For diagnostic / debugging / internal use only.\n ' logger = _create_logger(name) logger.handlers = [h for h in logger.handlers if (not isinstance(h, CloudHandler))] return logger
def create_diagnostic_logger(name: str) -> logging.Logger: '\n Create a logger that does not use the `CloudHandler` but preserves all other\n Prefect logging configuration. For diagnostic / debugging / internal use only.\n ' logger = _create_logger(name) logger.handlers = [h for h in logger.handlers if (not isinstance(h, CloudHandler))] return logger<|docstring|>Create a logger that does not use the `CloudHandler` but preserves all other Prefect logging configuration. For diagnostic / debugging / internal use only.<|endoftext|>
795138f5b2488ee3c555852b620a509c1905eb928bedc7d3669360adcc95f03d
def get_logger(name: str=None) -> logging.Logger: '\n Returns a "prefect" logger.\n\n Args:\n - name (str): if `None`, the root Prefect logger is returned. If provided, a child\n logger of the name `"prefect.{name}"` is returned. The child logger inherits\n the root logger\'s settings.\n\n Returns:\n - logging.Logger: a configured logging object with the appropriate name\n ' if (name is None): return prefect_logger else: return prefect_logger.getChild(name)
Returns a "prefect" logger. Args: - name (str): if `None`, the root Prefect logger is returned. If provided, a child logger of the name `"prefect.{name}"` is returned. The child logger inherits the root logger's settings. Returns: - logging.Logger: a configured logging object with the appropriate name
src/prefect/utilities/logging.py
get_logger
zschumacher/prefect
1
python
def get_logger(name: str=None) -> logging.Logger: '\n Returns a "prefect" logger.\n\n Args:\n - name (str): if `None`, the root Prefect logger is returned. If provided, a child\n logger of the name `"prefect.{name}"` is returned. The child logger inherits\n the root logger\'s settings.\n\n Returns:\n - logging.Logger: a configured logging object with the appropriate name\n ' if (name is None): return prefect_logger else: return prefect_logger.getChild(name)
def get_logger(name: str=None) -> logging.Logger: '\n Returns a "prefect" logger.\n\n Args:\n - name (str): if `None`, the root Prefect logger is returned. If provided, a child\n logger of the name `"prefect.{name}"` is returned. The child logger inherits\n the root logger\'s settings.\n\n Returns:\n - logging.Logger: a configured logging object with the appropriate name\n ' if (name is None): return prefect_logger else: return prefect_logger.getChild(name)<|docstring|>Returns a "prefect" logger. Args: - name (str): if `None`, the root Prefect logger is returned. If provided, a child logger of the name `"prefect.{name}"` is returned. The child logger inherits the root logger's settings. Returns: - logging.Logger: a configured logging object with the appropriate name<|endoftext|>
601a68b385fccb46c39b7906ea216a33f63f94273f549598d5d4543de1e6eae5
def ensure_started(self) -> None: 'Ensure the log manager is started' if (self.thread is None): self.client = prefect.Client() self.logging_period = context.config.cloud.logging_heartbeat self.thread = threading.Thread(target=self._write_logs_loop, name='prefect-log-manager', daemon=True) self.thread.start() atexit.register(self._on_shutdown)
Ensure the log manager is started
src/prefect/utilities/logging.py
ensure_started
zschumacher/prefect
1
python
def ensure_started(self) -> None: if (self.thread is None): self.client = prefect.Client() self.logging_period = context.config.cloud.logging_heartbeat self.thread = threading.Thread(target=self._write_logs_loop, name='prefect-log-manager', daemon=True) self.thread.start() atexit.register(self._on_shutdown)
def ensure_started(self) -> None: if (self.thread is None): self.client = prefect.Client() self.logging_period = context.config.cloud.logging_heartbeat self.thread = threading.Thread(target=self._write_logs_loop, name='prefect-log-manager', daemon=True) self.thread.start() atexit.register(self._on_shutdown)<|docstring|>Ensure the log manager is started<|endoftext|>
71dd10a3115f34887fdf4cdbd617d0123778506eb31a4c1bd7bd45fd9c1ffefe
def _on_shutdown(self) -> None: 'Called via atexit, flushes all logs and stops the background thread' for _ in range(3): try: self.stop() return except SystemExit: pass
Called via atexit, flushes all logs and stops the background thread
src/prefect/utilities/logging.py
_on_shutdown
zschumacher/prefect
1
python
def _on_shutdown(self) -> None: for _ in range(3): try: self.stop() return except SystemExit: pass
def _on_shutdown(self) -> None: for _ in range(3): try: self.stop() return except SystemExit: pass<|docstring|>Called via atexit, flushes all logs and stops the background thread<|endoftext|>
b810ca2b3b3ea682f9767b0ab7a9dd8aa8e9099bc0d18819b3fceb0d0b2917e9
def stop(self) -> None: 'Flush all logs and stop the background thread' if (self.thread is not None): self._stopped.set() self.thread.join() self._write_logs() self.thread = None self.client = None
Flush all logs and stop the background thread
src/prefect/utilities/logging.py
stop
zschumacher/prefect
1
python
def stop(self) -> None: if (self.thread is not None): self._stopped.set() self.thread.join() self._write_logs() self.thread = None self.client = None
def stop(self) -> None: if (self.thread is not None): self._stopped.set() self.thread.join() self._write_logs() self.thread = None self.client = None<|docstring|>Flush all logs and stop the background thread<|endoftext|>
05d89cc162b1ea84cf772db55638ac2521a39f956557dd4dcb498c593e01ce2f
def _write_logs_loop(self) -> None: 'Runs in a background thread, uploads logs periodically in a loop' while (not self._stopped.wait(self.logging_period)): self._write_logs()
Runs in a background thread, uploads logs periodically in a loop
src/prefect/utilities/logging.py
_write_logs_loop
zschumacher/prefect
1
python
def _write_logs_loop(self) -> None: while (not self._stopped.wait(self.logging_period)): self._write_logs()
def _write_logs_loop(self) -> None: while (not self._stopped.wait(self.logging_period)): self._write_logs()<|docstring|>Runs in a background thread, uploads logs periodically in a loop<|endoftext|>
2cdbd1888ea1bcf79b6f6d847368f443c9633ad525d48e7118766775c804447c
def _write_logs(self) -> None: 'Upload logs in batches until the queue is empty' assert (self.client is not None) cont = True while cont: try: while (self.pending_length < MAX_BATCH_LOG_LENGTH): log = self.queue.get_nowait() self.pending_length += len(log.get('message', '')) self.pending_logs.append(log) except Empty: cont = False if self.pending_logs: try: self.client.write_run_logs(self.pending_logs) self.pending_logs = [] self.pending_length = 0 except Exception as exc: warnings.warn(f'Failed to write logs with error: {exc!r}') cont = False
Upload logs in batches until the queue is empty
src/prefect/utilities/logging.py
_write_logs
zschumacher/prefect
1
python
def _write_logs(self) -> None: assert (self.client is not None) cont = True while cont: try: while (self.pending_length < MAX_BATCH_LOG_LENGTH): log = self.queue.get_nowait() self.pending_length += len(log.get('message', )) self.pending_logs.append(log) except Empty: cont = False if self.pending_logs: try: self.client.write_run_logs(self.pending_logs) self.pending_logs = [] self.pending_length = 0 except Exception as exc: warnings.warn(f'Failed to write logs with error: {exc!r}') cont = False
def _write_logs(self) -> None: assert (self.client is not None) cont = True while cont: try: while (self.pending_length < MAX_BATCH_LOG_LENGTH): log = self.queue.get_nowait() self.pending_length += len(log.get('message', )) self.pending_logs.append(log) except Empty: cont = False if self.pending_logs: try: self.client.write_run_logs(self.pending_logs) self.pending_logs = [] self.pending_length = 0 except Exception as exc: warnings.warn(f'Failed to write logs with error: {exc!r}') cont = False<|docstring|>Upload logs in batches until the queue is empty<|endoftext|>
512b5bd8081b8f8ca1ad2b381f2c5071bd743bbf5270b9a3c159900ce9fd8006
def enqueue(self, message: dict) -> None: 'Enqueue a new log message to be uploaded.\n\n Args:\n - message (dict): a log message to upload.\n ' self.ensure_started() self.queue.put(message)
Enqueue a new log message to be uploaded. Args: - message (dict): a log message to upload.
src/prefect/utilities/logging.py
enqueue
zschumacher/prefect
1
python
def enqueue(self, message: dict) -> None: 'Enqueue a new log message to be uploaded.\n\n Args:\n - message (dict): a log message to upload.\n ' self.ensure_started() self.queue.put(message)
def enqueue(self, message: dict) -> None: 'Enqueue a new log message to be uploaded.\n\n Args:\n - message (dict): a log message to upload.\n ' self.ensure_started() self.queue.put(message)<|docstring|>Enqueue a new log message to be uploaded. Args: - message (dict): a log message to upload.<|endoftext|>
98c49106477c11ba48e2601ce980ba290f707bd4ec221ba3038411d9b94ff5ef
def emit(self, record: logging.LogRecord) -> None: 'Emit a new log' if (not context.config.logging.log_to_cloud): return config_level = getattr(logging, context.config.logging.level, logging.INFO) if (record.levelno < config_level): return msg = self.format(record) if (len(msg) > MAX_LOG_LENGTH): get_logger('prefect.logging').warning('Received a log message of %d bytes, exceeding the limit of %d. The output will be truncated', len(msg), MAX_LOG_LENGTH) msg = msg[:MAX_LOG_LENGTH] log = {'flow_run_id': context.get('flow_run_id'), 'task_run_id': context.get('task_run_id'), 'timestamp': pendulum.from_timestamp((getattr(record, 'created', None) or time.time())).isoformat(), 'name': getattr(record, 'name', None), 'level': getattr(record, 'levelname', None), 'message': msg} LOG_MANAGER.enqueue(log)
Emit a new log
src/prefect/utilities/logging.py
emit
zschumacher/prefect
1
python
def emit(self, record: logging.LogRecord) -> None: if (not context.config.logging.log_to_cloud): return config_level = getattr(logging, context.config.logging.level, logging.INFO) if (record.levelno < config_level): return msg = self.format(record) if (len(msg) > MAX_LOG_LENGTH): get_logger('prefect.logging').warning('Received a log message of %d bytes, exceeding the limit of %d. The output will be truncated', len(msg), MAX_LOG_LENGTH) msg = msg[:MAX_LOG_LENGTH] log = {'flow_run_id': context.get('flow_run_id'), 'task_run_id': context.get('task_run_id'), 'timestamp': pendulum.from_timestamp((getattr(record, 'created', None) or time.time())).isoformat(), 'name': getattr(record, 'name', None), 'level': getattr(record, 'levelname', None), 'message': msg} LOG_MANAGER.enqueue(log)
def emit(self, record: logging.LogRecord) -> None: if (not context.config.logging.log_to_cloud): return config_level = getattr(logging, context.config.logging.level, logging.INFO) if (record.levelno < config_level): return msg = self.format(record) if (len(msg) > MAX_LOG_LENGTH): get_logger('prefect.logging').warning('Received a log message of %d bytes, exceeding the limit of %d. The output will be truncated', len(msg), MAX_LOG_LENGTH) msg = msg[:MAX_LOG_LENGTH] log = {'flow_run_id': context.get('flow_run_id'), 'task_run_id': context.get('task_run_id'), 'timestamp': pendulum.from_timestamp((getattr(record, 'created', None) or time.time())).isoformat(), 'name': getattr(record, 'name', None), 'level': getattr(record, 'levelname', None), 'message': msg} LOG_MANAGER.enqueue(log)<|docstring|>Emit a new log<|endoftext|>
7c4b87ed02124f92e55e569a5c1566667682764ff76adc5c337e8198c3e53246
def write(self, s: str) -> None: '\n Write message from stdout to a prefect logger.\n Note: blank newlines will not be logged.\n\n Args:\n s (str): the message from stdout to be logged\n ' if (not isinstance(s, str)): raise TypeError(f'string argument expected, got {type(s)}') if s.strip(): self.stdout_logger.info(s)
Write message from stdout to a prefect logger. Note: blank newlines will not be logged. Args: s (str): the message from stdout to be logged
src/prefect/utilities/logging.py
write
zschumacher/prefect
1
python
def write(self, s: str) -> None: '\n Write message from stdout to a prefect logger.\n Note: blank newlines will not be logged.\n\n Args:\n s (str): the message from stdout to be logged\n ' if (not isinstance(s, str)): raise TypeError(f'string argument expected, got {type(s)}') if s.strip(): self.stdout_logger.info(s)
def write(self, s: str) -> None: '\n Write message from stdout to a prefect logger.\n Note: blank newlines will not be logged.\n\n Args:\n s (str): the message from stdout to be logged\n ' if (not isinstance(s, str)): raise TypeError(f'string argument expected, got {type(s)}') if s.strip(): self.stdout_logger.info(s)<|docstring|>Write message from stdout to a prefect logger. Note: blank newlines will not be logged. Args: s (str): the message from stdout to be logged<|endoftext|>
392e3744bfac735c55bc254448c0237609642af25c5047ed76d9a2744b37993b
def flush(self) -> None: '\n Implemented flush operation for logger handler\n ' for handler in self.stdout_logger.handlers: handler.flush()
Implemented flush operation for logger handler
src/prefect/utilities/logging.py
flush
zschumacher/prefect
1
python
def flush(self) -> None: '\n \n ' for handler in self.stdout_logger.handlers: handler.flush()
def flush(self) -> None: '\n \n ' for handler in self.stdout_logger.handlers: handler.flush()<|docstring|>Implemented flush operation for logger handler<|endoftext|>
3e404d71f0c0fcca67dc3e5e5b062d39caaab52d65cc4733927f5af0bf5df01c
def __init__(self, feature_name=None, feature_version=None, local_vars_configuration=None): 'VendorSpecificFeature - a model defined in OpenAPI' if (local_vars_configuration is None): local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._feature_name = None self._feature_version = None self.discriminator = None self.feature_name = feature_name self.feature_version = feature_version
VendorSpecificFeature - a model defined in OpenAPI
Examples/python_client/openapi_client/com/h21lab/TS29510_Nnrf_NFDiscovery/handler/vendor_specific_feature.py
__init__
H21lab/5GC_build
12
python
def __init__(self, feature_name=None, feature_version=None, local_vars_configuration=None): if (local_vars_configuration is None): local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._feature_name = None self._feature_version = None self.discriminator = None self.feature_name = feature_name self.feature_version = feature_version
def __init__(self, feature_name=None, feature_version=None, local_vars_configuration=None): if (local_vars_configuration is None): local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._feature_name = None self._feature_version = None self.discriminator = None self.feature_name = feature_name self.feature_version = feature_version<|docstring|>VendorSpecificFeature - a model defined in OpenAPI<|endoftext|>
51d6668dd977e011001daa9b689c179eefec93390547cdc75140f76c982ca66f
@property def feature_name(self): 'Gets the feature_name of this VendorSpecificFeature. # noqa: E501\n\n\n :return: The feature_name of this VendorSpecificFeature. # noqa: E501\n :rtype: str\n ' return self._feature_name
Gets the feature_name of this VendorSpecificFeature. # noqa: E501 :return: The feature_name of this VendorSpecificFeature. # noqa: E501 :rtype: str
Examples/python_client/openapi_client/com/h21lab/TS29510_Nnrf_NFDiscovery/handler/vendor_specific_feature.py
feature_name
H21lab/5GC_build
12
python
@property def feature_name(self): 'Gets the feature_name of this VendorSpecificFeature. # noqa: E501\n\n\n :return: The feature_name of this VendorSpecificFeature. # noqa: E501\n :rtype: str\n ' return self._feature_name
@property def feature_name(self): 'Gets the feature_name of this VendorSpecificFeature. # noqa: E501\n\n\n :return: The feature_name of this VendorSpecificFeature. # noqa: E501\n :rtype: str\n ' return self._feature_name<|docstring|>Gets the feature_name of this VendorSpecificFeature. # noqa: E501 :return: The feature_name of this VendorSpecificFeature. # noqa: E501 :rtype: str<|endoftext|>
c146620143c81b6f50b576f130957e60d016d33c87915eff2c9511c8771c82ff
@feature_name.setter def feature_name(self, feature_name): 'Sets the feature_name of this VendorSpecificFeature.\n\n\n :param feature_name: The feature_name of this VendorSpecificFeature. # noqa: E501\n :type: str\n ' if (self.local_vars_configuration.client_side_validation and (feature_name is None)): raise ValueError('Invalid value for `feature_name`, must not be `None`') self._feature_name = feature_name
Sets the feature_name of this VendorSpecificFeature. :param feature_name: The feature_name of this VendorSpecificFeature. # noqa: E501 :type: str
Examples/python_client/openapi_client/com/h21lab/TS29510_Nnrf_NFDiscovery/handler/vendor_specific_feature.py
feature_name
H21lab/5GC_build
12
python
@feature_name.setter def feature_name(self, feature_name): 'Sets the feature_name of this VendorSpecificFeature.\n\n\n :param feature_name: The feature_name of this VendorSpecificFeature. # noqa: E501\n :type: str\n ' if (self.local_vars_configuration.client_side_validation and (feature_name is None)): raise ValueError('Invalid value for `feature_name`, must not be `None`') self._feature_name = feature_name
@feature_name.setter def feature_name(self, feature_name): 'Sets the feature_name of this VendorSpecificFeature.\n\n\n :param feature_name: The feature_name of this VendorSpecificFeature. # noqa: E501\n :type: str\n ' if (self.local_vars_configuration.client_side_validation and (feature_name is None)): raise ValueError('Invalid value for `feature_name`, must not be `None`') self._feature_name = feature_name<|docstring|>Sets the feature_name of this VendorSpecificFeature. :param feature_name: The feature_name of this VendorSpecificFeature. # noqa: E501 :type: str<|endoftext|>
44b3ce5b8a4d78b4e3bd5f331b5dbe62f3d7b71d8486b406073a3ad7b0b552a1
@property def feature_version(self): 'Gets the feature_version of this VendorSpecificFeature. # noqa: E501\n\n\n :return: The feature_version of this VendorSpecificFeature. # noqa: E501\n :rtype: str\n ' return self._feature_version
Gets the feature_version of this VendorSpecificFeature. # noqa: E501 :return: The feature_version of this VendorSpecificFeature. # noqa: E501 :rtype: str
Examples/python_client/openapi_client/com/h21lab/TS29510_Nnrf_NFDiscovery/handler/vendor_specific_feature.py
feature_version
H21lab/5GC_build
12
python
@property def feature_version(self): 'Gets the feature_version of this VendorSpecificFeature. # noqa: E501\n\n\n :return: The feature_version of this VendorSpecificFeature. # noqa: E501\n :rtype: str\n ' return self._feature_version
@property def feature_version(self): 'Gets the feature_version of this VendorSpecificFeature. # noqa: E501\n\n\n :return: The feature_version of this VendorSpecificFeature. # noqa: E501\n :rtype: str\n ' return self._feature_version<|docstring|>Gets the feature_version of this VendorSpecificFeature. # noqa: E501 :return: The feature_version of this VendorSpecificFeature. # noqa: E501 :rtype: str<|endoftext|>
6cd0f4836f1c74dfb2fd48b2ce0df925e4bd6d73ee6d6ef6bfad970dadd07b4e
@feature_version.setter def feature_version(self, feature_version): 'Sets the feature_version of this VendorSpecificFeature.\n\n\n :param feature_version: The feature_version of this VendorSpecificFeature. # noqa: E501\n :type: str\n ' if (self.local_vars_configuration.client_side_validation and (feature_version is None)): raise ValueError('Invalid value for `feature_version`, must not be `None`') self._feature_version = feature_version
Sets the feature_version of this VendorSpecificFeature. :param feature_version: The feature_version of this VendorSpecificFeature. # noqa: E501 :type: str
Examples/python_client/openapi_client/com/h21lab/TS29510_Nnrf_NFDiscovery/handler/vendor_specific_feature.py
feature_version
H21lab/5GC_build
12
python
@feature_version.setter def feature_version(self, feature_version): 'Sets the feature_version of this VendorSpecificFeature.\n\n\n :param feature_version: The feature_version of this VendorSpecificFeature. # noqa: E501\n :type: str\n ' if (self.local_vars_configuration.client_side_validation and (feature_version is None)): raise ValueError('Invalid value for `feature_version`, must not be `None`') self._feature_version = feature_version
@feature_version.setter def feature_version(self, feature_version): 'Sets the feature_version of this VendorSpecificFeature.\n\n\n :param feature_version: The feature_version of this VendorSpecificFeature. # noqa: E501\n :type: str\n ' if (self.local_vars_configuration.client_side_validation and (feature_version is None)): raise ValueError('Invalid value for `feature_version`, must not be `None`') self._feature_version = feature_version<|docstring|>Sets the feature_version of this VendorSpecificFeature. :param feature_version: The feature_version of this VendorSpecificFeature. # noqa: E501 :type: str<|endoftext|>
5a4e41bb6a0def746593298cb605df98f1366e957c4ca89b12010ea7db707963
def to_dict(self): 'Returns the model properties as a dict' result = {} for (attr, _) in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value)) elif hasattr(value, 'to_dict'): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map((lambda item: ((item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item)), value.items())) else: result[attr] = value return result
Returns the model properties as a dict
Examples/python_client/openapi_client/com/h21lab/TS29510_Nnrf_NFDiscovery/handler/vendor_specific_feature.py
to_dict
H21lab/5GC_build
12
python
def to_dict(self): result = {} for (attr, _) in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value)) elif hasattr(value, 'to_dict'): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map((lambda item: ((item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item)), value.items())) else: result[attr] = value return result
def to_dict(self): result = {} for (attr, _) in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value)) elif hasattr(value, 'to_dict'): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map((lambda item: ((item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item)), value.items())) else: result[attr] = value return result<|docstring|>Returns the model properties as a dict<|endoftext|>
cbb19eaa2fc8a113d9e32f924ef280a7e97563f8915f94f65dab438997af2e99
def to_str(self): 'Returns the string representation of the model' return pprint.pformat(self.to_dict())
Returns the string representation of the model
Examples/python_client/openapi_client/com/h21lab/TS29510_Nnrf_NFDiscovery/handler/vendor_specific_feature.py
to_str
H21lab/5GC_build
12
python
def to_str(self): return pprint.pformat(self.to_dict())
def to_str(self): return pprint.pformat(self.to_dict())<|docstring|>Returns the string representation of the model<|endoftext|>
772243a2c2b3261a9b954d07aaf295e3c1242a579a495e2d6a5679c677861703
def __repr__(self): 'For `print` and `pprint`' return self.to_str()
For `print` and `pprint`
Examples/python_client/openapi_client/com/h21lab/TS29510_Nnrf_NFDiscovery/handler/vendor_specific_feature.py
__repr__
H21lab/5GC_build
12
python
def __repr__(self): return self.to_str()
def __repr__(self): return self.to_str()<|docstring|>For `print` and `pprint`<|endoftext|>
7ac6cad7de44177c6d8bc0e8cb82d921c044a10badb9ece5bf3b359e0d09f7dd
def __eq__(self, other): 'Returns true if both objects are equal' if (not isinstance(other, VendorSpecificFeature)): return False return (self.to_dict() == other.to_dict())
Returns true if both objects are equal
Examples/python_client/openapi_client/com/h21lab/TS29510_Nnrf_NFDiscovery/handler/vendor_specific_feature.py
__eq__
H21lab/5GC_build
12
python
def __eq__(self, other): if (not isinstance(other, VendorSpecificFeature)): return False return (self.to_dict() == other.to_dict())
def __eq__(self, other): if (not isinstance(other, VendorSpecificFeature)): return False return (self.to_dict() == other.to_dict())<|docstring|>Returns true if both objects are equal<|endoftext|>
f01f2f88141bac8926a59d63c0261034d4f0948db922ce4847cf23ef7cdb774b
def __ne__(self, other): 'Returns true if both objects are not equal' if (not isinstance(other, VendorSpecificFeature)): return True return (self.to_dict() != other.to_dict())
Returns true if both objects are not equal
Examples/python_client/openapi_client/com/h21lab/TS29510_Nnrf_NFDiscovery/handler/vendor_specific_feature.py
__ne__
H21lab/5GC_build
12
python
def __ne__(self, other): if (not isinstance(other, VendorSpecificFeature)): return True return (self.to_dict() != other.to_dict())
def __ne__(self, other): if (not isinstance(other, VendorSpecificFeature)): return True return (self.to_dict() != other.to_dict())<|docstring|>Returns true if both objects are not equal<|endoftext|>
36f5e09b5fc8f915ca3cd2e151cb6b57bc5360b799add9e70ea4ad721217bc76
def predict(self, X, Z, clusters): '\n Predict using trained MERF. For known clusters the trained random effect correction is applied. For unknown\n clusters the pure fixed effect (RF) estimate is used.\n :param X: fixed effect covariates\n :param Z: random effect covariates\n :param clusters: cluster assignments for samples\n :return: y_hat, i.e. predictions\n ' if (self.trained_rf is None): raise NotFittedError("This MERF instance is not fitted yet. Call 'fit' with appropriate arguments before using this method") Z = np.array(Z) y_hat = self.trained_rf.predict(X) for cluster_id in self.cluster_counts.index: indices_i = (clusters == cluster_id) if (len(indices_i) == 0): continue b_i = self.trained_b.loc[cluster_id] Z_i = Z[indices_i] y_hat[indices_i] += Z_i.dot(b_i) return y_hat
Predict using trained MERF. For known clusters the trained random effect correction is applied. For unknown clusters the pure fixed effect (RF) estimate is used. :param X: fixed effect covariates :param Z: random effect covariates :param clusters: cluster assignments for samples :return: y_hat, i.e. predictions
merf/merf.py
predict
ittegrat/merf
0
python
def predict(self, X, Z, clusters): '\n Predict using trained MERF. For known clusters the trained random effect correction is applied. For unknown\n clusters the pure fixed effect (RF) estimate is used.\n :param X: fixed effect covariates\n :param Z: random effect covariates\n :param clusters: cluster assignments for samples\n :return: y_hat, i.e. predictions\n ' if (self.trained_rf is None): raise NotFittedError("This MERF instance is not fitted yet. Call 'fit' with appropriate arguments before using this method") Z = np.array(Z) y_hat = self.trained_rf.predict(X) for cluster_id in self.cluster_counts.index: indices_i = (clusters == cluster_id) if (len(indices_i) == 0): continue b_i = self.trained_b.loc[cluster_id] Z_i = Z[indices_i] y_hat[indices_i] += Z_i.dot(b_i) return y_hat
def predict(self, X, Z, clusters): '\n Predict using trained MERF. For known clusters the trained random effect correction is applied. For unknown\n clusters the pure fixed effect (RF) estimate is used.\n :param X: fixed effect covariates\n :param Z: random effect covariates\n :param clusters: cluster assignments for samples\n :return: y_hat, i.e. predictions\n ' if (self.trained_rf is None): raise NotFittedError("This MERF instance is not fitted yet. Call 'fit' with appropriate arguments before using this method") Z = np.array(Z) y_hat = self.trained_rf.predict(X) for cluster_id in self.cluster_counts.index: indices_i = (clusters == cluster_id) if (len(indices_i) == 0): continue b_i = self.trained_b.loc[cluster_id] Z_i = Z[indices_i] y_hat[indices_i] += Z_i.dot(b_i) return y_hat<|docstring|>Predict using trained MERF. For known clusters the trained random effect correction is applied. For unknown clusters the pure fixed effect (RF) estimate is used. :param X: fixed effect covariates :param Z: random effect covariates :param clusters: cluster assignments for samples :return: y_hat, i.e. predictions<|endoftext|>
eca3d416f4a26deda153098bd79f0da71a17b179e527ade27593ccf9aa388b9c
def fit(self, X, Z, clusters, y): '\n Fit MERF using EM algorithm.\n :param X: fixed effect covariates\n :param Z: random effect covariates\n :param clusters: cluster assignments for samples\n :param y: response/target variable\n :return: fitted model\n ' assert (len(Z) == len(X)) assert (len(y) == len(X)) assert (len(clusters) == len(X)) n_clusters = clusters.nunique() n_obs = len(y) q = Z.shape[1] Z = np.array(Z) cluster_counts = clusters.value_counts() Z_by_cluster = {} y_by_cluster = {} n_by_cluster = {} I_by_cluster = {} indices_by_cluster = {} for cluster_id in cluster_counts.index: indices_i = (clusters == cluster_id) indices_by_cluster[cluster_id] = indices_i Z_by_cluster[cluster_id] = Z[indices_i] y_by_cluster[cluster_id] = y[indices_i] n_by_cluster[cluster_id] = cluster_counts[cluster_id] I_by_cluster[cluster_id] = np.eye(cluster_counts[cluster_id]) iteration = 0 b_hat_df = pd.DataFrame(np.zeros((n_clusters, q)), index=cluster_counts.index) sigma2_hat = 1 D_hat = np.eye(q) self.b_hat_history.append(b_hat_df) self.sigma2_hat_history.append(sigma2_hat) self.D_hat_history.append(D_hat) early_stop_flag = False while ((iteration < self.max_iterations) and (not early_stop_flag)): iteration += 1 logger.debug('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') logger.debug('Iteration: {}'.format(iteration)) logger.debug('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') y_star = np.zeros(len(y)) for cluster_id in cluster_counts.index: y_i = y_by_cluster[cluster_id] Z_i = Z_by_cluster[cluster_id] b_hat_i = b_hat_df.loc[cluster_id] logger.debug('E-step, cluster {}, b_hat = {}'.format(cluster_id, b_hat_i)) indices_i = indices_by_cluster[cluster_id] y_star_i = (y_i - Z_i.dot(b_hat_i)) y_star[indices_i] = y_star_i assert (len(y_star.shape) == 1) rf = RandomForestRegressor(**self.rf_params) rf.fit(X, y_star) f_hat = rf.oob_prediction_ sigma2_hat_sum = 0 D_hat_sum = 0 for cluster_id in cluster_counts.index: indices_i = indices_by_cluster[cluster_id] y_i = y_by_cluster[cluster_id] Z_i = Z_by_cluster[cluster_id] n_i = n_by_cluster[cluster_id] I_i = I_by_cluster[cluster_id] f_hat_i = f_hat[indices_i] V_hat_i = (Z_i.dot(D_hat).dot(Z_i.T) + (sigma2_hat * I_i)) V_hat_inv_i = np.linalg.pinv(V_hat_i) logger.debug('M-step, pre-update, cluster {}, b_hat = {}'.format(cluster_id, b_hat_df.loc[cluster_id])) b_hat_i = D_hat.dot(Z_i.T).dot(V_hat_inv_i).dot((y_i - f_hat_i)) logger.debug('M-step, post-update, cluster {}, b_hat = {}'.format(cluster_id, b_hat_i)) eps_hat_i = ((y_i - f_hat_i) - Z_i.dot(b_hat_i)) logger.debug('------------------------------------------') logger.debug('M-step, cluster {}'.format(cluster_id)) logger.debug('error squared for cluster = {}'.format(eps_hat_i.T.dot(eps_hat_i))) b_hat_df.loc[(cluster_id, :)] = b_hat_i logger.debug('M-step, post-update, recalled from db, cluster {}, b_hat = {}'.format(cluster_id, b_hat_df.loc[cluster_id])) sigma2_hat_sum += (eps_hat_i.T.dot(eps_hat_i) + (sigma2_hat * (n_i - (sigma2_hat * np.trace(V_hat_inv_i))))) D_hat_sum += (np.outer(b_hat_i, b_hat_i) + (D_hat - D_hat.dot(Z_i.T).dot(V_hat_inv_i).dot(Z_i).dot(D_hat))) sigma2_hat = ((1.0 / n_obs) * sigma2_hat_sum) D_hat = ((1.0 / n_clusters) * D_hat_sum) logger.debug('b_hat = {}'.format(b_hat_df)) logger.debug('sigma2_hat = {}'.format(sigma2_hat)) logger.debug('D_hat = {}'.format(D_hat)) self.b_hat_history.append(b_hat_df.copy()) self.sigma2_hat_history.append(sigma2_hat) self.D_hat_history.append(D_hat) gll = 0 for cluster_id in cluster_counts.index: indices_i = indices_by_cluster[cluster_id] y_i = y_by_cluster[cluster_id] Z_i = Z_by_cluster[cluster_id] I_i = I_by_cluster[cluster_id] f_hat_i = f_hat[indices_i] R_hat_i = (sigma2_hat * I_i) b_hat_i = b_hat_df.loc[cluster_id] (_, logdet_D_hat) = np.linalg.slogdet(D_hat) (_, logdet_R_hat_i) = np.linalg.slogdet(R_hat_i) gll += (((((y_i - f_hat_i) - Z_i.dot(b_hat_i)).T.dot(np.linalg.pinv(R_hat_i)).dot(((y_i - f_hat_i) - Z_i.dot(b_hat_i))) + b_hat_i.T.dot(np.linalg.pinv(D_hat)).dot(b_hat_i)) + logdet_D_hat) + logdet_R_hat_i) logger.info('GLL is {} at iteration {}.'.format(gll, iteration)) self.gll_history.append(gll) if ((self.gll_early_stop_threshold is not None) and (len(self.gll_history) > 1)): curr_threshold = np.abs(((gll - self.gll_history[(- 2)]) / self.gll_history[(- 2)])) logger.debug('stop threshold = {}'.format(curr_threshold)) if (curr_threshold < self.gll_early_stop_threshold): logger.info('Gll {} less than threshold {}, stopping early ...'.format(gll, curr_threshold)) early_stop_flag = True self.cluster_counts = cluster_counts self.trained_rf = rf self.trained_b = b_hat_df return self
Fit MERF using EM algorithm. :param X: fixed effect covariates :param Z: random effect covariates :param clusters: cluster assignments for samples :param y: response/target variable :return: fitted model
merf/merf.py
fit
ittegrat/merf
0
python
def fit(self, X, Z, clusters, y): '\n Fit MERF using EM algorithm.\n :param X: fixed effect covariates\n :param Z: random effect covariates\n :param clusters: cluster assignments for samples\n :param y: response/target variable\n :return: fitted model\n ' assert (len(Z) == len(X)) assert (len(y) == len(X)) assert (len(clusters) == len(X)) n_clusters = clusters.nunique() n_obs = len(y) q = Z.shape[1] Z = np.array(Z) cluster_counts = clusters.value_counts() Z_by_cluster = {} y_by_cluster = {} n_by_cluster = {} I_by_cluster = {} indices_by_cluster = {} for cluster_id in cluster_counts.index: indices_i = (clusters == cluster_id) indices_by_cluster[cluster_id] = indices_i Z_by_cluster[cluster_id] = Z[indices_i] y_by_cluster[cluster_id] = y[indices_i] n_by_cluster[cluster_id] = cluster_counts[cluster_id] I_by_cluster[cluster_id] = np.eye(cluster_counts[cluster_id]) iteration = 0 b_hat_df = pd.DataFrame(np.zeros((n_clusters, q)), index=cluster_counts.index) sigma2_hat = 1 D_hat = np.eye(q) self.b_hat_history.append(b_hat_df) self.sigma2_hat_history.append(sigma2_hat) self.D_hat_history.append(D_hat) early_stop_flag = False while ((iteration < self.max_iterations) and (not early_stop_flag)): iteration += 1 logger.debug('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') logger.debug('Iteration: {}'.format(iteration)) logger.debug('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') y_star = np.zeros(len(y)) for cluster_id in cluster_counts.index: y_i = y_by_cluster[cluster_id] Z_i = Z_by_cluster[cluster_id] b_hat_i = b_hat_df.loc[cluster_id] logger.debug('E-step, cluster {}, b_hat = {}'.format(cluster_id, b_hat_i)) indices_i = indices_by_cluster[cluster_id] y_star_i = (y_i - Z_i.dot(b_hat_i)) y_star[indices_i] = y_star_i assert (len(y_star.shape) == 1) rf = RandomForestRegressor(**self.rf_params) rf.fit(X, y_star) f_hat = rf.oob_prediction_ sigma2_hat_sum = 0 D_hat_sum = 0 for cluster_id in cluster_counts.index: indices_i = indices_by_cluster[cluster_id] y_i = y_by_cluster[cluster_id] Z_i = Z_by_cluster[cluster_id] n_i = n_by_cluster[cluster_id] I_i = I_by_cluster[cluster_id] f_hat_i = f_hat[indices_i] V_hat_i = (Z_i.dot(D_hat).dot(Z_i.T) + (sigma2_hat * I_i)) V_hat_inv_i = np.linalg.pinv(V_hat_i) logger.debug('M-step, pre-update, cluster {}, b_hat = {}'.format(cluster_id, b_hat_df.loc[cluster_id])) b_hat_i = D_hat.dot(Z_i.T).dot(V_hat_inv_i).dot((y_i - f_hat_i)) logger.debug('M-step, post-update, cluster {}, b_hat = {}'.format(cluster_id, b_hat_i)) eps_hat_i = ((y_i - f_hat_i) - Z_i.dot(b_hat_i)) logger.debug('------------------------------------------') logger.debug('M-step, cluster {}'.format(cluster_id)) logger.debug('error squared for cluster = {}'.format(eps_hat_i.T.dot(eps_hat_i))) b_hat_df.loc[(cluster_id, :)] = b_hat_i logger.debug('M-step, post-update, recalled from db, cluster {}, b_hat = {}'.format(cluster_id, b_hat_df.loc[cluster_id])) sigma2_hat_sum += (eps_hat_i.T.dot(eps_hat_i) + (sigma2_hat * (n_i - (sigma2_hat * np.trace(V_hat_inv_i))))) D_hat_sum += (np.outer(b_hat_i, b_hat_i) + (D_hat - D_hat.dot(Z_i.T).dot(V_hat_inv_i).dot(Z_i).dot(D_hat))) sigma2_hat = ((1.0 / n_obs) * sigma2_hat_sum) D_hat = ((1.0 / n_clusters) * D_hat_sum) logger.debug('b_hat = {}'.format(b_hat_df)) logger.debug('sigma2_hat = {}'.format(sigma2_hat)) logger.debug('D_hat = {}'.format(D_hat)) self.b_hat_history.append(b_hat_df.copy()) self.sigma2_hat_history.append(sigma2_hat) self.D_hat_history.append(D_hat) gll = 0 for cluster_id in cluster_counts.index: indices_i = indices_by_cluster[cluster_id] y_i = y_by_cluster[cluster_id] Z_i = Z_by_cluster[cluster_id] I_i = I_by_cluster[cluster_id] f_hat_i = f_hat[indices_i] R_hat_i = (sigma2_hat * I_i) b_hat_i = b_hat_df.loc[cluster_id] (_, logdet_D_hat) = np.linalg.slogdet(D_hat) (_, logdet_R_hat_i) = np.linalg.slogdet(R_hat_i) gll += (((((y_i - f_hat_i) - Z_i.dot(b_hat_i)).T.dot(np.linalg.pinv(R_hat_i)).dot(((y_i - f_hat_i) - Z_i.dot(b_hat_i))) + b_hat_i.T.dot(np.linalg.pinv(D_hat)).dot(b_hat_i)) + logdet_D_hat) + logdet_R_hat_i) logger.info('GLL is {} at iteration {}.'.format(gll, iteration)) self.gll_history.append(gll) if ((self.gll_early_stop_threshold is not None) and (len(self.gll_history) > 1)): curr_threshold = np.abs(((gll - self.gll_history[(- 2)]) / self.gll_history[(- 2)])) logger.debug('stop threshold = {}'.format(curr_threshold)) if (curr_threshold < self.gll_early_stop_threshold): logger.info('Gll {} less than threshold {}, stopping early ...'.format(gll, curr_threshold)) early_stop_flag = True self.cluster_counts = cluster_counts self.trained_rf = rf self.trained_b = b_hat_df return self
def fit(self, X, Z, clusters, y): '\n Fit MERF using EM algorithm.\n :param X: fixed effect covariates\n :param Z: random effect covariates\n :param clusters: cluster assignments for samples\n :param y: response/target variable\n :return: fitted model\n ' assert (len(Z) == len(X)) assert (len(y) == len(X)) assert (len(clusters) == len(X)) n_clusters = clusters.nunique() n_obs = len(y) q = Z.shape[1] Z = np.array(Z) cluster_counts = clusters.value_counts() Z_by_cluster = {} y_by_cluster = {} n_by_cluster = {} I_by_cluster = {} indices_by_cluster = {} for cluster_id in cluster_counts.index: indices_i = (clusters == cluster_id) indices_by_cluster[cluster_id] = indices_i Z_by_cluster[cluster_id] = Z[indices_i] y_by_cluster[cluster_id] = y[indices_i] n_by_cluster[cluster_id] = cluster_counts[cluster_id] I_by_cluster[cluster_id] = np.eye(cluster_counts[cluster_id]) iteration = 0 b_hat_df = pd.DataFrame(np.zeros((n_clusters, q)), index=cluster_counts.index) sigma2_hat = 1 D_hat = np.eye(q) self.b_hat_history.append(b_hat_df) self.sigma2_hat_history.append(sigma2_hat) self.D_hat_history.append(D_hat) early_stop_flag = False while ((iteration < self.max_iterations) and (not early_stop_flag)): iteration += 1 logger.debug('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') logger.debug('Iteration: {}'.format(iteration)) logger.debug('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') y_star = np.zeros(len(y)) for cluster_id in cluster_counts.index: y_i = y_by_cluster[cluster_id] Z_i = Z_by_cluster[cluster_id] b_hat_i = b_hat_df.loc[cluster_id] logger.debug('E-step, cluster {}, b_hat = {}'.format(cluster_id, b_hat_i)) indices_i = indices_by_cluster[cluster_id] y_star_i = (y_i - Z_i.dot(b_hat_i)) y_star[indices_i] = y_star_i assert (len(y_star.shape) == 1) rf = RandomForestRegressor(**self.rf_params) rf.fit(X, y_star) f_hat = rf.oob_prediction_ sigma2_hat_sum = 0 D_hat_sum = 0 for cluster_id in cluster_counts.index: indices_i = indices_by_cluster[cluster_id] y_i = y_by_cluster[cluster_id] Z_i = Z_by_cluster[cluster_id] n_i = n_by_cluster[cluster_id] I_i = I_by_cluster[cluster_id] f_hat_i = f_hat[indices_i] V_hat_i = (Z_i.dot(D_hat).dot(Z_i.T) + (sigma2_hat * I_i)) V_hat_inv_i = np.linalg.pinv(V_hat_i) logger.debug('M-step, pre-update, cluster {}, b_hat = {}'.format(cluster_id, b_hat_df.loc[cluster_id])) b_hat_i = D_hat.dot(Z_i.T).dot(V_hat_inv_i).dot((y_i - f_hat_i)) logger.debug('M-step, post-update, cluster {}, b_hat = {}'.format(cluster_id, b_hat_i)) eps_hat_i = ((y_i - f_hat_i) - Z_i.dot(b_hat_i)) logger.debug('------------------------------------------') logger.debug('M-step, cluster {}'.format(cluster_id)) logger.debug('error squared for cluster = {}'.format(eps_hat_i.T.dot(eps_hat_i))) b_hat_df.loc[(cluster_id, :)] = b_hat_i logger.debug('M-step, post-update, recalled from db, cluster {}, b_hat = {}'.format(cluster_id, b_hat_df.loc[cluster_id])) sigma2_hat_sum += (eps_hat_i.T.dot(eps_hat_i) + (sigma2_hat * (n_i - (sigma2_hat * np.trace(V_hat_inv_i))))) D_hat_sum += (np.outer(b_hat_i, b_hat_i) + (D_hat - D_hat.dot(Z_i.T).dot(V_hat_inv_i).dot(Z_i).dot(D_hat))) sigma2_hat = ((1.0 / n_obs) * sigma2_hat_sum) D_hat = ((1.0 / n_clusters) * D_hat_sum) logger.debug('b_hat = {}'.format(b_hat_df)) logger.debug('sigma2_hat = {}'.format(sigma2_hat)) logger.debug('D_hat = {}'.format(D_hat)) self.b_hat_history.append(b_hat_df.copy()) self.sigma2_hat_history.append(sigma2_hat) self.D_hat_history.append(D_hat) gll = 0 for cluster_id in cluster_counts.index: indices_i = indices_by_cluster[cluster_id] y_i = y_by_cluster[cluster_id] Z_i = Z_by_cluster[cluster_id] I_i = I_by_cluster[cluster_id] f_hat_i = f_hat[indices_i] R_hat_i = (sigma2_hat * I_i) b_hat_i = b_hat_df.loc[cluster_id] (_, logdet_D_hat) = np.linalg.slogdet(D_hat) (_, logdet_R_hat_i) = np.linalg.slogdet(R_hat_i) gll += (((((y_i - f_hat_i) - Z_i.dot(b_hat_i)).T.dot(np.linalg.pinv(R_hat_i)).dot(((y_i - f_hat_i) - Z_i.dot(b_hat_i))) + b_hat_i.T.dot(np.linalg.pinv(D_hat)).dot(b_hat_i)) + logdet_D_hat) + logdet_R_hat_i) logger.info('GLL is {} at iteration {}.'.format(gll, iteration)) self.gll_history.append(gll) if ((self.gll_early_stop_threshold is not None) and (len(self.gll_history) > 1)): curr_threshold = np.abs(((gll - self.gll_history[(- 2)]) / self.gll_history[(- 2)])) logger.debug('stop threshold = {}'.format(curr_threshold)) if (curr_threshold < self.gll_early_stop_threshold): logger.info('Gll {} less than threshold {}, stopping early ...'.format(gll, curr_threshold)) early_stop_flag = True self.cluster_counts = cluster_counts self.trained_rf = rf self.trained_b = b_hat_df return self<|docstring|>Fit MERF using EM algorithm. :param X: fixed effect covariates :param Z: random effect covariates :param clusters: cluster assignments for samples :param y: response/target variable :return: fitted model<|endoftext|>
d3a7515af18abb1a765fa21305538694dc12dc79a0fd4c98724d5b04a27a794f
def __init__(__self__, resource_name, opts=None, description=None, rest_api=None, stage_description=None, stage_name=None, triggers=None, variables=None, __props__=None, __name__=None, __opts__=None): '\n Provides an API Gateway REST Deployment.\n\n > **Note:** This resource depends on having at least one `apigateway.Integration` created in the REST API, which\n itself has other dependencies. To avoid race conditions when all resources are being created together, you need to add\n implicit resource references via the `triggers` argument or explicit resource references using the\n [resource `dependsOn` meta-argument](https://www.pulumi.com/docs/intro/concepts/programming-model/#dependson).\n\n ## Example Usage\n\n ```python\n import pulumi\n import pulumi_aws as aws\n\n my_demo_api = aws.apigateway.RestApi("myDemoAPI", description="This is my API for demonstration purposes")\n my_demo_resource = aws.apigateway.Resource("myDemoResource",\n rest_api=my_demo_api.id,\n parent_id=my_demo_api.root_resource_id,\n path_part="test")\n my_demo_method = aws.apigateway.Method("myDemoMethod",\n rest_api=my_demo_api.id,\n resource_id=my_demo_resource.id,\n http_method="GET",\n authorization="NONE")\n my_demo_integration = aws.apigateway.Integration("myDemoIntegration",\n rest_api=my_demo_api.id,\n resource_id=my_demo_resource.id,\n http_method=my_demo_method.http_method,\n type="MOCK")\n my_demo_deployment = aws.apigateway.Deployment("myDemoDeployment",\n rest_api=my_demo_api.id,\n stage_name="test",\n variables={\n "answer": "42",\n },\n opts=ResourceOptions(depends_on=[my_demo_integration]))\n ```\n\n :param str resource_name: The name of the resource.\n :param pulumi.ResourceOptions opts: Options for the resource.\n :param pulumi.Input[str] description: The description of the deployment\n :param pulumi.Input[dict] rest_api: The ID of the associated REST API\n :param pulumi.Input[str] stage_description: The description of the stage\n :param pulumi.Input[str] stage_name: The name of the stage. If the specified stage already exists, it will be updated to point to the new deployment. If the stage does not exist, a new one will be created and point to this deployment.\n :param pulumi.Input[dict] triggers: A map of arbitrary keys and values that, when changed, will trigger a redeployment.\n :param pulumi.Input[dict] variables: A map that defines variables for the stage\n ' if (__name__ is not None): warnings.warn('explicit use of __name__ is deprecated', DeprecationWarning) resource_name = __name__ if (__opts__ is not None): warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning) opts = __opts__ if (opts is None): opts = pulumi.ResourceOptions() if (not isinstance(opts, pulumi.ResourceOptions)): raise TypeError('Expected resource options to be a ResourceOptions instance') if (opts.version is None): opts.version = utilities.get_version() if (opts.id is None): if (__props__ is not None): raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = dict() __props__['description'] = description if (rest_api is None): raise TypeError("Missing required property 'rest_api'") __props__['rest_api'] = rest_api __props__['stage_description'] = stage_description __props__['stage_name'] = stage_name __props__['triggers'] = triggers __props__['variables'] = variables __props__['created_date'] = None __props__['execution_arn'] = None __props__['invoke_url'] = None super(Deployment, __self__).__init__('aws:apigateway/deployment:Deployment', resource_name, __props__, opts)
Provides an API Gateway REST Deployment. > **Note:** This resource depends on having at least one `apigateway.Integration` created in the REST API, which itself has other dependencies. To avoid race conditions when all resources are being created together, you need to add implicit resource references via the `triggers` argument or explicit resource references using the [resource `dependsOn` meta-argument](https://www.pulumi.com/docs/intro/concepts/programming-model/#dependson). ## Example Usage ```python import pulumi import pulumi_aws as aws my_demo_api = aws.apigateway.RestApi("myDemoAPI", description="This is my API for demonstration purposes") my_demo_resource = aws.apigateway.Resource("myDemoResource", rest_api=my_demo_api.id, parent_id=my_demo_api.root_resource_id, path_part="test") my_demo_method = aws.apigateway.Method("myDemoMethod", rest_api=my_demo_api.id, resource_id=my_demo_resource.id, http_method="GET", authorization="NONE") my_demo_integration = aws.apigateway.Integration("myDemoIntegration", rest_api=my_demo_api.id, resource_id=my_demo_resource.id, http_method=my_demo_method.http_method, type="MOCK") my_demo_deployment = aws.apigateway.Deployment("myDemoDeployment", rest_api=my_demo_api.id, stage_name="test", variables={ "answer": "42", }, opts=ResourceOptions(depends_on=[my_demo_integration])) ``` :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] description: The description of the deployment :param pulumi.Input[dict] rest_api: The ID of the associated REST API :param pulumi.Input[str] stage_description: The description of the stage :param pulumi.Input[str] stage_name: The name of the stage. If the specified stage already exists, it will be updated to point to the new deployment. If the stage does not exist, a new one will be created and point to this deployment. :param pulumi.Input[dict] triggers: A map of arbitrary keys and values that, when changed, will trigger a redeployment. :param pulumi.Input[dict] variables: A map that defines variables for the stage
sdk/python/pulumi_aws/apigateway/deployment.py
__init__
michael-golden/pulumi-aws
0
python
def __init__(__self__, resource_name, opts=None, description=None, rest_api=None, stage_description=None, stage_name=None, triggers=None, variables=None, __props__=None, __name__=None, __opts__=None): '\n Provides an API Gateway REST Deployment.\n\n > **Note:** This resource depends on having at least one `apigateway.Integration` created in the REST API, which\n itself has other dependencies. To avoid race conditions when all resources are being created together, you need to add\n implicit resource references via the `triggers` argument or explicit resource references using the\n [resource `dependsOn` meta-argument](https://www.pulumi.com/docs/intro/concepts/programming-model/#dependson).\n\n ## Example Usage\n\n ```python\n import pulumi\n import pulumi_aws as aws\n\n my_demo_api = aws.apigateway.RestApi("myDemoAPI", description="This is my API for demonstration purposes")\n my_demo_resource = aws.apigateway.Resource("myDemoResource",\n rest_api=my_demo_api.id,\n parent_id=my_demo_api.root_resource_id,\n path_part="test")\n my_demo_method = aws.apigateway.Method("myDemoMethod",\n rest_api=my_demo_api.id,\n resource_id=my_demo_resource.id,\n http_method="GET",\n authorization="NONE")\n my_demo_integration = aws.apigateway.Integration("myDemoIntegration",\n rest_api=my_demo_api.id,\n resource_id=my_demo_resource.id,\n http_method=my_demo_method.http_method,\n type="MOCK")\n my_demo_deployment = aws.apigateway.Deployment("myDemoDeployment",\n rest_api=my_demo_api.id,\n stage_name="test",\n variables={\n "answer": "42",\n },\n opts=ResourceOptions(depends_on=[my_demo_integration]))\n ```\n\n :param str resource_name: The name of the resource.\n :param pulumi.ResourceOptions opts: Options for the resource.\n :param pulumi.Input[str] description: The description of the deployment\n :param pulumi.Input[dict] rest_api: The ID of the associated REST API\n :param pulumi.Input[str] stage_description: The description of the stage\n :param pulumi.Input[str] stage_name: The name of the stage. If the specified stage already exists, it will be updated to point to the new deployment. If the stage does not exist, a new one will be created and point to this deployment.\n :param pulumi.Input[dict] triggers: A map of arbitrary keys and values that, when changed, will trigger a redeployment.\n :param pulumi.Input[dict] variables: A map that defines variables for the stage\n ' if (__name__ is not None): warnings.warn('explicit use of __name__ is deprecated', DeprecationWarning) resource_name = __name__ if (__opts__ is not None): warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning) opts = __opts__ if (opts is None): opts = pulumi.ResourceOptions() if (not isinstance(opts, pulumi.ResourceOptions)): raise TypeError('Expected resource options to be a ResourceOptions instance') if (opts.version is None): opts.version = utilities.get_version() if (opts.id is None): if (__props__ is not None): raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = dict() __props__['description'] = description if (rest_api is None): raise TypeError("Missing required property 'rest_api'") __props__['rest_api'] = rest_api __props__['stage_description'] = stage_description __props__['stage_name'] = stage_name __props__['triggers'] = triggers __props__['variables'] = variables __props__['created_date'] = None __props__['execution_arn'] = None __props__['invoke_url'] = None super(Deployment, __self__).__init__('aws:apigateway/deployment:Deployment', resource_name, __props__, opts)
def __init__(__self__, resource_name, opts=None, description=None, rest_api=None, stage_description=None, stage_name=None, triggers=None, variables=None, __props__=None, __name__=None, __opts__=None): '\n Provides an API Gateway REST Deployment.\n\n > **Note:** This resource depends on having at least one `apigateway.Integration` created in the REST API, which\n itself has other dependencies. To avoid race conditions when all resources are being created together, you need to add\n implicit resource references via the `triggers` argument or explicit resource references using the\n [resource `dependsOn` meta-argument](https://www.pulumi.com/docs/intro/concepts/programming-model/#dependson).\n\n ## Example Usage\n\n ```python\n import pulumi\n import pulumi_aws as aws\n\n my_demo_api = aws.apigateway.RestApi("myDemoAPI", description="This is my API for demonstration purposes")\n my_demo_resource = aws.apigateway.Resource("myDemoResource",\n rest_api=my_demo_api.id,\n parent_id=my_demo_api.root_resource_id,\n path_part="test")\n my_demo_method = aws.apigateway.Method("myDemoMethod",\n rest_api=my_demo_api.id,\n resource_id=my_demo_resource.id,\n http_method="GET",\n authorization="NONE")\n my_demo_integration = aws.apigateway.Integration("myDemoIntegration",\n rest_api=my_demo_api.id,\n resource_id=my_demo_resource.id,\n http_method=my_demo_method.http_method,\n type="MOCK")\n my_demo_deployment = aws.apigateway.Deployment("myDemoDeployment",\n rest_api=my_demo_api.id,\n stage_name="test",\n variables={\n "answer": "42",\n },\n opts=ResourceOptions(depends_on=[my_demo_integration]))\n ```\n\n :param str resource_name: The name of the resource.\n :param pulumi.ResourceOptions opts: Options for the resource.\n :param pulumi.Input[str] description: The description of the deployment\n :param pulumi.Input[dict] rest_api: The ID of the associated REST API\n :param pulumi.Input[str] stage_description: The description of the stage\n :param pulumi.Input[str] stage_name: The name of the stage. If the specified stage already exists, it will be updated to point to the new deployment. If the stage does not exist, a new one will be created and point to this deployment.\n :param pulumi.Input[dict] triggers: A map of arbitrary keys and values that, when changed, will trigger a redeployment.\n :param pulumi.Input[dict] variables: A map that defines variables for the stage\n ' if (__name__ is not None): warnings.warn('explicit use of __name__ is deprecated', DeprecationWarning) resource_name = __name__ if (__opts__ is not None): warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning) opts = __opts__ if (opts is None): opts = pulumi.ResourceOptions() if (not isinstance(opts, pulumi.ResourceOptions)): raise TypeError('Expected resource options to be a ResourceOptions instance') if (opts.version is None): opts.version = utilities.get_version() if (opts.id is None): if (__props__ is not None): raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = dict() __props__['description'] = description if (rest_api is None): raise TypeError("Missing required property 'rest_api'") __props__['rest_api'] = rest_api __props__['stage_description'] = stage_description __props__['stage_name'] = stage_name __props__['triggers'] = triggers __props__['variables'] = variables __props__['created_date'] = None __props__['execution_arn'] = None __props__['invoke_url'] = None super(Deployment, __self__).__init__('aws:apigateway/deployment:Deployment', resource_name, __props__, opts)<|docstring|>Provides an API Gateway REST Deployment. > **Note:** This resource depends on having at least one `apigateway.Integration` created in the REST API, which itself has other dependencies. To avoid race conditions when all resources are being created together, you need to add implicit resource references via the `triggers` argument or explicit resource references using the [resource `dependsOn` meta-argument](https://www.pulumi.com/docs/intro/concepts/programming-model/#dependson). ## Example Usage ```python import pulumi import pulumi_aws as aws my_demo_api = aws.apigateway.RestApi("myDemoAPI", description="This is my API for demonstration purposes") my_demo_resource = aws.apigateway.Resource("myDemoResource", rest_api=my_demo_api.id, parent_id=my_demo_api.root_resource_id, path_part="test") my_demo_method = aws.apigateway.Method("myDemoMethod", rest_api=my_demo_api.id, resource_id=my_demo_resource.id, http_method="GET", authorization="NONE") my_demo_integration = aws.apigateway.Integration("myDemoIntegration", rest_api=my_demo_api.id, resource_id=my_demo_resource.id, http_method=my_demo_method.http_method, type="MOCK") my_demo_deployment = aws.apigateway.Deployment("myDemoDeployment", rest_api=my_demo_api.id, stage_name="test", variables={ "answer": "42", }, opts=ResourceOptions(depends_on=[my_demo_integration])) ``` :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] description: The description of the deployment :param pulumi.Input[dict] rest_api: The ID of the associated REST API :param pulumi.Input[str] stage_description: The description of the stage :param pulumi.Input[str] stage_name: The name of the stage. If the specified stage already exists, it will be updated to point to the new deployment. If the stage does not exist, a new one will be created and point to this deployment. :param pulumi.Input[dict] triggers: A map of arbitrary keys and values that, when changed, will trigger a redeployment. :param pulumi.Input[dict] variables: A map that defines variables for the stage<|endoftext|>
104808536667a00e8471005f5407d723e883d283b4d88cb2a6b6cd9b3089e9bd
@staticmethod def get(resource_name, id, opts=None, created_date=None, description=None, execution_arn=None, invoke_url=None, rest_api=None, stage_description=None, stage_name=None, triggers=None, variables=None): "\n Get an existing Deployment resource's state with the given name, id, and optional extra\n properties used to qualify the lookup.\n\n :param str resource_name: The unique name of the resulting resource.\n :param str id: The unique provider ID of the resource to lookup.\n :param pulumi.ResourceOptions opts: Options for the resource.\n :param pulumi.Input[str] created_date: The creation date of the deployment\n :param pulumi.Input[str] description: The description of the deployment\n :param pulumi.Input[str] execution_arn: The execution ARN to be used in `lambda_permission` resource's `source_arn`\n when allowing API Gateway to invoke a Lambda function,\n e.g. `arn:aws:execute-api:eu-west-2:123456789012:z4675bid1j/prod`\n :param pulumi.Input[str] invoke_url: The URL to invoke the API pointing to the stage,\n e.g. `https://z4675bid1j.execute-api.eu-west-2.amazonaws.com/prod`\n :param pulumi.Input[dict] rest_api: The ID of the associated REST API\n :param pulumi.Input[str] stage_description: The description of the stage\n :param pulumi.Input[str] stage_name: The name of the stage. If the specified stage already exists, it will be updated to point to the new deployment. If the stage does not exist, a new one will be created and point to this deployment.\n :param pulumi.Input[dict] triggers: A map of arbitrary keys and values that, when changed, will trigger a redeployment.\n :param pulumi.Input[dict] variables: A map that defines variables for the stage\n " opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = dict() __props__['created_date'] = created_date __props__['description'] = description __props__['execution_arn'] = execution_arn __props__['invoke_url'] = invoke_url __props__['rest_api'] = rest_api __props__['stage_description'] = stage_description __props__['stage_name'] = stage_name __props__['triggers'] = triggers __props__['variables'] = variables return Deployment(resource_name, opts=opts, __props__=__props__)
Get an existing Deployment resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param str id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] created_date: The creation date of the deployment :param pulumi.Input[str] description: The description of the deployment :param pulumi.Input[str] execution_arn: The execution ARN to be used in `lambda_permission` resource's `source_arn` when allowing API Gateway to invoke a Lambda function, e.g. `arn:aws:execute-api:eu-west-2:123456789012:z4675bid1j/prod` :param pulumi.Input[str] invoke_url: The URL to invoke the API pointing to the stage, e.g. `https://z4675bid1j.execute-api.eu-west-2.amazonaws.com/prod` :param pulumi.Input[dict] rest_api: The ID of the associated REST API :param pulumi.Input[str] stage_description: The description of the stage :param pulumi.Input[str] stage_name: The name of the stage. If the specified stage already exists, it will be updated to point to the new deployment. If the stage does not exist, a new one will be created and point to this deployment. :param pulumi.Input[dict] triggers: A map of arbitrary keys and values that, when changed, will trigger a redeployment. :param pulumi.Input[dict] variables: A map that defines variables for the stage
sdk/python/pulumi_aws/apigateway/deployment.py
get
michael-golden/pulumi-aws
0
python
@staticmethod def get(resource_name, id, opts=None, created_date=None, description=None, execution_arn=None, invoke_url=None, rest_api=None, stage_description=None, stage_name=None, triggers=None, variables=None): "\n Get an existing Deployment resource's state with the given name, id, and optional extra\n properties used to qualify the lookup.\n\n :param str resource_name: The unique name of the resulting resource.\n :param str id: The unique provider ID of the resource to lookup.\n :param pulumi.ResourceOptions opts: Options for the resource.\n :param pulumi.Input[str] created_date: The creation date of the deployment\n :param pulumi.Input[str] description: The description of the deployment\n :param pulumi.Input[str] execution_arn: The execution ARN to be used in `lambda_permission` resource's `source_arn`\n when allowing API Gateway to invoke a Lambda function,\n e.g. `arn:aws:execute-api:eu-west-2:123456789012:z4675bid1j/prod`\n :param pulumi.Input[str] invoke_url: The URL to invoke the API pointing to the stage,\n e.g. `https://z4675bid1j.execute-api.eu-west-2.amazonaws.com/prod`\n :param pulumi.Input[dict] rest_api: The ID of the associated REST API\n :param pulumi.Input[str] stage_description: The description of the stage\n :param pulumi.Input[str] stage_name: The name of the stage. If the specified stage already exists, it will be updated to point to the new deployment. If the stage does not exist, a new one will be created and point to this deployment.\n :param pulumi.Input[dict] triggers: A map of arbitrary keys and values that, when changed, will trigger a redeployment.\n :param pulumi.Input[dict] variables: A map that defines variables for the stage\n " opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = dict() __props__['created_date'] = created_date __props__['description'] = description __props__['execution_arn'] = execution_arn __props__['invoke_url'] = invoke_url __props__['rest_api'] = rest_api __props__['stage_description'] = stage_description __props__['stage_name'] = stage_name __props__['triggers'] = triggers __props__['variables'] = variables return Deployment(resource_name, opts=opts, __props__=__props__)
@staticmethod def get(resource_name, id, opts=None, created_date=None, description=None, execution_arn=None, invoke_url=None, rest_api=None, stage_description=None, stage_name=None, triggers=None, variables=None): "\n Get an existing Deployment resource's state with the given name, id, and optional extra\n properties used to qualify the lookup.\n\n :param str resource_name: The unique name of the resulting resource.\n :param str id: The unique provider ID of the resource to lookup.\n :param pulumi.ResourceOptions opts: Options for the resource.\n :param pulumi.Input[str] created_date: The creation date of the deployment\n :param pulumi.Input[str] description: The description of the deployment\n :param pulumi.Input[str] execution_arn: The execution ARN to be used in `lambda_permission` resource's `source_arn`\n when allowing API Gateway to invoke a Lambda function,\n e.g. `arn:aws:execute-api:eu-west-2:123456789012:z4675bid1j/prod`\n :param pulumi.Input[str] invoke_url: The URL to invoke the API pointing to the stage,\n e.g. `https://z4675bid1j.execute-api.eu-west-2.amazonaws.com/prod`\n :param pulumi.Input[dict] rest_api: The ID of the associated REST API\n :param pulumi.Input[str] stage_description: The description of the stage\n :param pulumi.Input[str] stage_name: The name of the stage. If the specified stage already exists, it will be updated to point to the new deployment. If the stage does not exist, a new one will be created and point to this deployment.\n :param pulumi.Input[dict] triggers: A map of arbitrary keys and values that, when changed, will trigger a redeployment.\n :param pulumi.Input[dict] variables: A map that defines variables for the stage\n " opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = dict() __props__['created_date'] = created_date __props__['description'] = description __props__['execution_arn'] = execution_arn __props__['invoke_url'] = invoke_url __props__['rest_api'] = rest_api __props__['stage_description'] = stage_description __props__['stage_name'] = stage_name __props__['triggers'] = triggers __props__['variables'] = variables return Deployment(resource_name, opts=opts, __props__=__props__)<|docstring|>Get an existing Deployment resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param str id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] created_date: The creation date of the deployment :param pulumi.Input[str] description: The description of the deployment :param pulumi.Input[str] execution_arn: The execution ARN to be used in `lambda_permission` resource's `source_arn` when allowing API Gateway to invoke a Lambda function, e.g. `arn:aws:execute-api:eu-west-2:123456789012:z4675bid1j/prod` :param pulumi.Input[str] invoke_url: The URL to invoke the API pointing to the stage, e.g. `https://z4675bid1j.execute-api.eu-west-2.amazonaws.com/prod` :param pulumi.Input[dict] rest_api: The ID of the associated REST API :param pulumi.Input[str] stage_description: The description of the stage :param pulumi.Input[str] stage_name: The name of the stage. If the specified stage already exists, it will be updated to point to the new deployment. If the stage does not exist, a new one will be created and point to this deployment. :param pulumi.Input[dict] triggers: A map of arbitrary keys and values that, when changed, will trigger a redeployment. :param pulumi.Input[dict] variables: A map that defines variables for the stage<|endoftext|>
5b106c1142390c6de90f111ac28498aaf497136c7ef9c23fbfc8d86634a40d05
def main(config): 'Read shapes, plot map\n ' data_path = config['paths']['data'] output_file = os.path.join(config['paths']['figures'], 'network-road-map.png') road_edge_file_national = os.path.join(data_path, 'network', 'road_edges_national.shp') road_edge_file_provincial = os.path.join(data_path, 'network', 'road_edges_provincial.shp') proj_lat_lon = ccrs.PlateCarree() ax = get_axes() plot_basemap(ax, data_path) scale_bar(ax, location=(0.8, 0.05)) plot_basemap_labels(ax, data_path, include_regions=False) colors = {'National': '#ba0f03', 'Provincial': '#e0881f'} edges_provincial = geopandas.read_file(road_edge_file_provincial) ax.add_geometries(list(edges_provincial.geometry), crs=proj_lat_lon, linewidth=1.25, edgecolor=colors['Provincial'], facecolor='none', zorder=4) edges_national = geopandas.read_file(road_edge_file_national) ax.add_geometries(list(edges_national.geometry), crs=proj_lat_lon, linewidth=1.25, edgecolor=colors['National'], facecolor='none', zorder=5) legend_handles = [mpatches.Patch(color=color, label=label) for (label, color) in colors.items()] plt.legend(handles=legend_handles, loc='lower left') save_fig(output_file)
Read shapes, plot map
src/atra/plot/network_road.py
main
oi-analytics/argentina-transport
1
python
def main(config): '\n ' data_path = config['paths']['data'] output_file = os.path.join(config['paths']['figures'], 'network-road-map.png') road_edge_file_national = os.path.join(data_path, 'network', 'road_edges_national.shp') road_edge_file_provincial = os.path.join(data_path, 'network', 'road_edges_provincial.shp') proj_lat_lon = ccrs.PlateCarree() ax = get_axes() plot_basemap(ax, data_path) scale_bar(ax, location=(0.8, 0.05)) plot_basemap_labels(ax, data_path, include_regions=False) colors = {'National': '#ba0f03', 'Provincial': '#e0881f'} edges_provincial = geopandas.read_file(road_edge_file_provincial) ax.add_geometries(list(edges_provincial.geometry), crs=proj_lat_lon, linewidth=1.25, edgecolor=colors['Provincial'], facecolor='none', zorder=4) edges_national = geopandas.read_file(road_edge_file_national) ax.add_geometries(list(edges_national.geometry), crs=proj_lat_lon, linewidth=1.25, edgecolor=colors['National'], facecolor='none', zorder=5) legend_handles = [mpatches.Patch(color=color, label=label) for (label, color) in colors.items()] plt.legend(handles=legend_handles, loc='lower left') save_fig(output_file)
def main(config): '\n ' data_path = config['paths']['data'] output_file = os.path.join(config['paths']['figures'], 'network-road-map.png') road_edge_file_national = os.path.join(data_path, 'network', 'road_edges_national.shp') road_edge_file_provincial = os.path.join(data_path, 'network', 'road_edges_provincial.shp') proj_lat_lon = ccrs.PlateCarree() ax = get_axes() plot_basemap(ax, data_path) scale_bar(ax, location=(0.8, 0.05)) plot_basemap_labels(ax, data_path, include_regions=False) colors = {'National': '#ba0f03', 'Provincial': '#e0881f'} edges_provincial = geopandas.read_file(road_edge_file_provincial) ax.add_geometries(list(edges_provincial.geometry), crs=proj_lat_lon, linewidth=1.25, edgecolor=colors['Provincial'], facecolor='none', zorder=4) edges_national = geopandas.read_file(road_edge_file_national) ax.add_geometries(list(edges_national.geometry), crs=proj_lat_lon, linewidth=1.25, edgecolor=colors['National'], facecolor='none', zorder=5) legend_handles = [mpatches.Patch(color=color, label=label) for (label, color) in colors.items()] plt.legend(handles=legend_handles, loc='lower left') save_fig(output_file)<|docstring|>Read shapes, plot map<|endoftext|>
441f043dd5fd2217b56864f855a04f442a14c78d3abe34e4124ce2404e6efc6d
@property def should_save(self): 'True if the session should be saved. By default this is only\n true for :attr:`modified` cookies, not :attr:`new`.\n ' return self.modified
True if the session should be saved. By default this is only true for :attr:`modified` cookies, not :attr:`new`.
jam/third_party/werkzeug/secure_cookie/securecookie.py
should_save
platipusica/AssetInventoryMSAccess
384
python
@property def should_save(self): 'True if the session should be saved. By default this is only\n true for :attr:`modified` cookies, not :attr:`new`.\n ' return self.modified
@property def should_save(self): 'True if the session should be saved. By default this is only\n true for :attr:`modified` cookies, not :attr:`new`.\n ' return self.modified<|docstring|>True if the session should be saved. By default this is only true for :attr:`modified` cookies, not :attr:`new`.<|endoftext|>
a8791fa674c7f8ae62ea8dd45628f70dbb130509ce13d0b523075f7966cdfcc7
@classmethod def quote(cls, value): 'Quote the value for the cookie. This can be any object\n supported by :attr:`serialization_method`.\n\n :param value: The value to quote.\n ' if (cls.serialization_method is not None): value = cls.serialization_method.dumps(value) if cls.quote_base64: value = b''.join(base64.b64encode(to_bytes(value, 'utf8')).splitlines()).strip() return value
Quote the value for the cookie. This can be any object supported by :attr:`serialization_method`. :param value: The value to quote.
jam/third_party/werkzeug/secure_cookie/securecookie.py
quote
platipusica/AssetInventoryMSAccess
384
python
@classmethod def quote(cls, value): 'Quote the value for the cookie. This can be any object\n supported by :attr:`serialization_method`.\n\n :param value: The value to quote.\n ' if (cls.serialization_method is not None): value = cls.serialization_method.dumps(value) if cls.quote_base64: value = b.join(base64.b64encode(to_bytes(value, 'utf8')).splitlines()).strip() return value
@classmethod def quote(cls, value): 'Quote the value for the cookie. This can be any object\n supported by :attr:`serialization_method`.\n\n :param value: The value to quote.\n ' if (cls.serialization_method is not None): value = cls.serialization_method.dumps(value) if cls.quote_base64: value = b.join(base64.b64encode(to_bytes(value, 'utf8')).splitlines()).strip() return value<|docstring|>Quote the value for the cookie. This can be any object supported by :attr:`serialization_method`. :param value: The value to quote.<|endoftext|>
96ba152f8942ced5b912220251f0f41e06d4c5fcfac5cc574c7bb7cce7a3f7dd
@classmethod def unquote(cls, value): 'Unquote the value for the cookie. If unquoting does not work\n a :exc:`UnquoteError` is raised.\n\n :param value: The value to unquote.\n ' try: if cls.quote_base64: value = base64.b64decode(value) if (cls.serialization_method is not None): value = cls.serialization_method.loads(value) return value except Exception: raise UnquoteError()
Unquote the value for the cookie. If unquoting does not work a :exc:`UnquoteError` is raised. :param value: The value to unquote.
jam/third_party/werkzeug/secure_cookie/securecookie.py
unquote
platipusica/AssetInventoryMSAccess
384
python
@classmethod def unquote(cls, value): 'Unquote the value for the cookie. If unquoting does not work\n a :exc:`UnquoteError` is raised.\n\n :param value: The value to unquote.\n ' try: if cls.quote_base64: value = base64.b64decode(value) if (cls.serialization_method is not None): value = cls.serialization_method.loads(value) return value except Exception: raise UnquoteError()
@classmethod def unquote(cls, value): 'Unquote the value for the cookie. If unquoting does not work\n a :exc:`UnquoteError` is raised.\n\n :param value: The value to unquote.\n ' try: if cls.quote_base64: value = base64.b64decode(value) if (cls.serialization_method is not None): value = cls.serialization_method.loads(value) return value except Exception: raise UnquoteError()<|docstring|>Unquote the value for the cookie. If unquoting does not work a :exc:`UnquoteError` is raised. :param value: The value to unquote.<|endoftext|>
d520b0ee173add3d8b9f2d77412dce55a95803781545d9e07a07530e16d72f6f
def serialize(self, expires=None): 'Serialize the secure cookie into a string.\n\n If expires is provided, the session will be automatically\n invalidated after expiration when you unseralize it. This\n provides better protection against session cookie theft.\n\n :param expires: An optional expiration date for the cookie (a\n :class:`datetime.datetime` object).\n ' if (self.secret_key is None): raise RuntimeError('no secret key defined') if expires: self['_expires'] = _date_to_unix(expires) result = [] mac = hmac(self.secret_key, None, self.hash_method) for (key, value) in sorted(self.items()): result.append(('%s=%s' % (url_quote_plus(key), self.quote(value).decode('ascii'))).encode('ascii')) mac.update((b'|' + result[(- 1)])) return b'?'.join([base64.b64encode(mac.digest()).strip(), b'&'.join(result)])
Serialize the secure cookie into a string. If expires is provided, the session will be automatically invalidated after expiration when you unseralize it. This provides better protection against session cookie theft. :param expires: An optional expiration date for the cookie (a :class:`datetime.datetime` object).
jam/third_party/werkzeug/secure_cookie/securecookie.py
serialize
platipusica/AssetInventoryMSAccess
384
python
def serialize(self, expires=None): 'Serialize the secure cookie into a string.\n\n If expires is provided, the session will be automatically\n invalidated after expiration when you unseralize it. This\n provides better protection against session cookie theft.\n\n :param expires: An optional expiration date for the cookie (a\n :class:`datetime.datetime` object).\n ' if (self.secret_key is None): raise RuntimeError('no secret key defined') if expires: self['_expires'] = _date_to_unix(expires) result = [] mac = hmac(self.secret_key, None, self.hash_method) for (key, value) in sorted(self.items()): result.append(('%s=%s' % (url_quote_plus(key), self.quote(value).decode('ascii'))).encode('ascii')) mac.update((b'|' + result[(- 1)])) return b'?'.join([base64.b64encode(mac.digest()).strip(), b'&'.join(result)])
def serialize(self, expires=None): 'Serialize the secure cookie into a string.\n\n If expires is provided, the session will be automatically\n invalidated after expiration when you unseralize it. This\n provides better protection against session cookie theft.\n\n :param expires: An optional expiration date for the cookie (a\n :class:`datetime.datetime` object).\n ' if (self.secret_key is None): raise RuntimeError('no secret key defined') if expires: self['_expires'] = _date_to_unix(expires) result = [] mac = hmac(self.secret_key, None, self.hash_method) for (key, value) in sorted(self.items()): result.append(('%s=%s' % (url_quote_plus(key), self.quote(value).decode('ascii'))).encode('ascii')) mac.update((b'|' + result[(- 1)])) return b'?'.join([base64.b64encode(mac.digest()).strip(), b'&'.join(result)])<|docstring|>Serialize the secure cookie into a string. If expires is provided, the session will be automatically invalidated after expiration when you unseralize it. This provides better protection against session cookie theft. :param expires: An optional expiration date for the cookie (a :class:`datetime.datetime` object).<|endoftext|>
8b0ba986c27d0204519cd92aa232aaaa520e2acb15d752459367bb219abc704c
@classmethod def unserialize(cls, string, secret_key): 'Load the secure cookie from a serialized string.\n\n :param string: The cookie value to unserialize.\n :param secret_key: The secret key used to serialize the cookie.\n :return: A new :class:`SecureCookie`.\n ' if isinstance(string, text_type): string = string.encode('utf-8', 'replace') if isinstance(secret_key, text_type): secret_key = secret_key.encode('utf-8', 'replace') try: (base64_hash, data) = string.split(b'?', 1) except (ValueError, IndexError): items = () else: items = {} mac = hmac(secret_key, None, cls.hash_method) for item in data.split(b'&'): mac.update((b'|' + item)) if (b'=' not in item): items = None break (key, value) = item.split(b'=', 1) key = url_unquote_plus(key.decode('ascii')) try: key = to_native(key) except UnicodeError: pass items[key] = value try: client_hash = base64.b64decode(base64_hash) except TypeError: items = client_hash = None if ((items is not None) and safe_str_cmp(client_hash, mac.digest())): try: for (key, value) in iteritems(items): items[key] = cls.unquote(value) except UnquoteError: items = () else: if ('_expires' in items): if (time() > items['_expires']): items = () else: del items['_expires'] else: items = () return cls(items, secret_key, False)
Load the secure cookie from a serialized string. :param string: The cookie value to unserialize. :param secret_key: The secret key used to serialize the cookie. :return: A new :class:`SecureCookie`.
jam/third_party/werkzeug/secure_cookie/securecookie.py
unserialize
platipusica/AssetInventoryMSAccess
384
python
@classmethod def unserialize(cls, string, secret_key): 'Load the secure cookie from a serialized string.\n\n :param string: The cookie value to unserialize.\n :param secret_key: The secret key used to serialize the cookie.\n :return: A new :class:`SecureCookie`.\n ' if isinstance(string, text_type): string = string.encode('utf-8', 'replace') if isinstance(secret_key, text_type): secret_key = secret_key.encode('utf-8', 'replace') try: (base64_hash, data) = string.split(b'?', 1) except (ValueError, IndexError): items = () else: items = {} mac = hmac(secret_key, None, cls.hash_method) for item in data.split(b'&'): mac.update((b'|' + item)) if (b'=' not in item): items = None break (key, value) = item.split(b'=', 1) key = url_unquote_plus(key.decode('ascii')) try: key = to_native(key) except UnicodeError: pass items[key] = value try: client_hash = base64.b64decode(base64_hash) except TypeError: items = client_hash = None if ((items is not None) and safe_str_cmp(client_hash, mac.digest())): try: for (key, value) in iteritems(items): items[key] = cls.unquote(value) except UnquoteError: items = () else: if ('_expires' in items): if (time() > items['_expires']): items = () else: del items['_expires'] else: items = () return cls(items, secret_key, False)
@classmethod def unserialize(cls, string, secret_key): 'Load the secure cookie from a serialized string.\n\n :param string: The cookie value to unserialize.\n :param secret_key: The secret key used to serialize the cookie.\n :return: A new :class:`SecureCookie`.\n ' if isinstance(string, text_type): string = string.encode('utf-8', 'replace') if isinstance(secret_key, text_type): secret_key = secret_key.encode('utf-8', 'replace') try: (base64_hash, data) = string.split(b'?', 1) except (ValueError, IndexError): items = () else: items = {} mac = hmac(secret_key, None, cls.hash_method) for item in data.split(b'&'): mac.update((b'|' + item)) if (b'=' not in item): items = None break (key, value) = item.split(b'=', 1) key = url_unquote_plus(key.decode('ascii')) try: key = to_native(key) except UnicodeError: pass items[key] = value try: client_hash = base64.b64decode(base64_hash) except TypeError: items = client_hash = None if ((items is not None) and safe_str_cmp(client_hash, mac.digest())): try: for (key, value) in iteritems(items): items[key] = cls.unquote(value) except UnquoteError: items = () else: if ('_expires' in items): if (time() > items['_expires']): items = () else: del items['_expires'] else: items = () return cls(items, secret_key, False)<|docstring|>Load the secure cookie from a serialized string. :param string: The cookie value to unserialize. :param secret_key: The secret key used to serialize the cookie. :return: A new :class:`SecureCookie`.<|endoftext|>
769110d184fadf6472e73c08e035039a9396ed17241e93e27455728b2cf34557
@classmethod def load_cookie(cls, request, key='session', secret_key=None): 'Load a :class:`SecureCookie` from a cookie in the request. If\n the cookie is not set, a new :class:`SecureCookie` instance is\n returned.\n\n :param request: A request object that has a `cookies` attribute\n which is a dict of all cookie values.\n :param key: The name of the cookie.\n :param secret_key: The secret key used to unquote the cookie.\n Always provide the value even though it has no default!\n ' data = request.cookies.get(key) if (not data): return cls(secret_key=secret_key) return cls.unserialize(data, secret_key)
Load a :class:`SecureCookie` from a cookie in the request. If the cookie is not set, a new :class:`SecureCookie` instance is returned. :param request: A request object that has a `cookies` attribute which is a dict of all cookie values. :param key: The name of the cookie. :param secret_key: The secret key used to unquote the cookie. Always provide the value even though it has no default!
jam/third_party/werkzeug/secure_cookie/securecookie.py
load_cookie
platipusica/AssetInventoryMSAccess
384
python
@classmethod def load_cookie(cls, request, key='session', secret_key=None): 'Load a :class:`SecureCookie` from a cookie in the request. If\n the cookie is not set, a new :class:`SecureCookie` instance is\n returned.\n\n :param request: A request object that has a `cookies` attribute\n which is a dict of all cookie values.\n :param key: The name of the cookie.\n :param secret_key: The secret key used to unquote the cookie.\n Always provide the value even though it has no default!\n ' data = request.cookies.get(key) if (not data): return cls(secret_key=secret_key) return cls.unserialize(data, secret_key)
@classmethod def load_cookie(cls, request, key='session', secret_key=None): 'Load a :class:`SecureCookie` from a cookie in the request. If\n the cookie is not set, a new :class:`SecureCookie` instance is\n returned.\n\n :param request: A request object that has a `cookies` attribute\n which is a dict of all cookie values.\n :param key: The name of the cookie.\n :param secret_key: The secret key used to unquote the cookie.\n Always provide the value even though it has no default!\n ' data = request.cookies.get(key) if (not data): return cls(secret_key=secret_key) return cls.unserialize(data, secret_key)<|docstring|>Load a :class:`SecureCookie` from a cookie in the request. If the cookie is not set, a new :class:`SecureCookie` instance is returned. :param request: A request object that has a `cookies` attribute which is a dict of all cookie values. :param key: The name of the cookie. :param secret_key: The secret key used to unquote the cookie. Always provide the value even though it has no default!<|endoftext|>
c223d1eafb62c5b4f0fb9a7524b3547f7ddba583d073f30bcc311ee3d73cec07
def save_cookie(self, response, key='session', expires=None, session_expires=None, max_age=None, path='/', domain=None, secure=None, httponly=False, force=False): 'Save the data securely in a cookie on response object. All\n parameters that are not described here are forwarded directly\n to :meth:`~BaseResponse.set_cookie`.\n\n :param response: A response object that has a\n :meth:`~BaseResponse.set_cookie` method.\n :param key: The name of the cookie.\n :param session_expires: The expiration date of the secure cookie\n stored information. If this is not provided the cookie\n ``expires`` date is used instead.\n ' if (force or self.should_save): data = self.serialize((session_expires or expires)) response.set_cookie(key, data, expires=expires, max_age=max_age, path=path, domain=domain, secure=secure, httponly=httponly)
Save the data securely in a cookie on response object. All parameters that are not described here are forwarded directly to :meth:`~BaseResponse.set_cookie`. :param response: A response object that has a :meth:`~BaseResponse.set_cookie` method. :param key: The name of the cookie. :param session_expires: The expiration date of the secure cookie stored information. If this is not provided the cookie ``expires`` date is used instead.
jam/third_party/werkzeug/secure_cookie/securecookie.py
save_cookie
platipusica/AssetInventoryMSAccess
384
python
def save_cookie(self, response, key='session', expires=None, session_expires=None, max_age=None, path='/', domain=None, secure=None, httponly=False, force=False): 'Save the data securely in a cookie on response object. All\n parameters that are not described here are forwarded directly\n to :meth:`~BaseResponse.set_cookie`.\n\n :param response: A response object that has a\n :meth:`~BaseResponse.set_cookie` method.\n :param key: The name of the cookie.\n :param session_expires: The expiration date of the secure cookie\n stored information. If this is not provided the cookie\n ``expires`` date is used instead.\n ' if (force or self.should_save): data = self.serialize((session_expires or expires)) response.set_cookie(key, data, expires=expires, max_age=max_age, path=path, domain=domain, secure=secure, httponly=httponly)
def save_cookie(self, response, key='session', expires=None, session_expires=None, max_age=None, path='/', domain=None, secure=None, httponly=False, force=False): 'Save the data securely in a cookie on response object. All\n parameters that are not described here are forwarded directly\n to :meth:`~BaseResponse.set_cookie`.\n\n :param response: A response object that has a\n :meth:`~BaseResponse.set_cookie` method.\n :param key: The name of the cookie.\n :param session_expires: The expiration date of the secure cookie\n stored information. If this is not provided the cookie\n ``expires`` date is used instead.\n ' if (force or self.should_save): data = self.serialize((session_expires or expires)) response.set_cookie(key, data, expires=expires, max_age=max_age, path=path, domain=domain, secure=secure, httponly=httponly)<|docstring|>Save the data securely in a cookie on response object. All parameters that are not described here are forwarded directly to :meth:`~BaseResponse.set_cookie`. :param response: A response object that has a :meth:`~BaseResponse.set_cookie` method. :param key: The name of the cookie. :param session_expires: The expiration date of the secure cookie stored information. If this is not provided the cookie ``expires`` date is used instead.<|endoftext|>
4ccbf1b1b0ab6298b07e28b7546dc7273b9d7c5cf794912cd14a414f51b70ad6
def merge_dicts(dict1: dict, dict2: dict) -> dict: 'Merge 2 dictionaries\n\n Arguments:\n dict1 {dict} -- 1st Dictionary\n dict2 {dict} -- 2nd Dictionary\n\n Returns:\n dict -- Concatenated Dictionary\n ' return {**dict1, **dict2}
Merge 2 dictionaries Arguments: dict1 {dict} -- 1st Dictionary dict2 {dict} -- 2nd Dictionary Returns: dict -- Concatenated Dictionary
stavroslib/dict.py
merge_dicts
spitoglou/stavros-lib
0
python
def merge_dicts(dict1: dict, dict2: dict) -> dict: 'Merge 2 dictionaries\n\n Arguments:\n dict1 {dict} -- 1st Dictionary\n dict2 {dict} -- 2nd Dictionary\n\n Returns:\n dict -- Concatenated Dictionary\n ' return {**dict1, **dict2}
def merge_dicts(dict1: dict, dict2: dict) -> dict: 'Merge 2 dictionaries\n\n Arguments:\n dict1 {dict} -- 1st Dictionary\n dict2 {dict} -- 2nd Dictionary\n\n Returns:\n dict -- Concatenated Dictionary\n ' return {**dict1, **dict2}<|docstring|>Merge 2 dictionaries Arguments: dict1 {dict} -- 1st Dictionary dict2 {dict} -- 2nd Dictionary Returns: dict -- Concatenated Dictionary<|endoftext|>
2475af231c3b67ed51dcafe99aec1be8aa5e7f8c5f370625012e89ab9c14b317
async def send_message(endpoint: EndpointConfig, sender_id: Text, message: Text, parse_data: Optional[Dict[(Text, Any)]]=None) -> Dict[(Text, Any)]: 'Send a user message to a conversation.' payload = {'sender': UserUttered.type_name, 'message': message, 'parse_data': parse_data} return (await endpoint.request(json=payload, method='post', subpath='/conversations/{}/messages'.format(sender_id)))
Send a user message to a conversation.
rasa/core/training/interactive.py
send_message
LaudateCorpus1/rasa_core
2,433
python
async def send_message(endpoint: EndpointConfig, sender_id: Text, message: Text, parse_data: Optional[Dict[(Text, Any)]]=None) -> Dict[(Text, Any)]: payload = {'sender': UserUttered.type_name, 'message': message, 'parse_data': parse_data} return (await endpoint.request(json=payload, method='post', subpath='/conversations/{}/messages'.format(sender_id)))
async def send_message(endpoint: EndpointConfig, sender_id: Text, message: Text, parse_data: Optional[Dict[(Text, Any)]]=None) -> Dict[(Text, Any)]: payload = {'sender': UserUttered.type_name, 'message': message, 'parse_data': parse_data} return (await endpoint.request(json=payload, method='post', subpath='/conversations/{}/messages'.format(sender_id)))<|docstring|>Send a user message to a conversation.<|endoftext|>
4c3fc3040640bda7c2d7c27ed3f1959adcc0d2c6e36f27329361b3116bf289b4
async def request_prediction(endpoint: EndpointConfig, sender_id: Text) -> Dict[(Text, Any)]: 'Request the next action prediction from core.' return (await endpoint.request(method='post', subpath='/conversations/{}/predict'.format(sender_id)))
Request the next action prediction from core.
rasa/core/training/interactive.py
request_prediction
LaudateCorpus1/rasa_core
2,433
python
async def request_prediction(endpoint: EndpointConfig, sender_id: Text) -> Dict[(Text, Any)]: return (await endpoint.request(method='post', subpath='/conversations/{}/predict'.format(sender_id)))
async def request_prediction(endpoint: EndpointConfig, sender_id: Text) -> Dict[(Text, Any)]: return (await endpoint.request(method='post', subpath='/conversations/{}/predict'.format(sender_id)))<|docstring|>Request the next action prediction from core.<|endoftext|>
91363d6822fdc2a5d774f2bac67a59ce1307e7d15d2dec40e38297581dc5a5d2
async def retrieve_domain(endpoint: EndpointConfig) -> Dict[(Text, Any)]: 'Retrieve the domain from core.' return (await endpoint.request(method='get', subpath='/domain', headers={'Accept': 'application/json'}))
Retrieve the domain from core.
rasa/core/training/interactive.py
retrieve_domain
LaudateCorpus1/rasa_core
2,433
python
async def retrieve_domain(endpoint: EndpointConfig) -> Dict[(Text, Any)]: return (await endpoint.request(method='get', subpath='/domain', headers={'Accept': 'application/json'}))
async def retrieve_domain(endpoint: EndpointConfig) -> Dict[(Text, Any)]: return (await endpoint.request(method='get', subpath='/domain', headers={'Accept': 'application/json'}))<|docstring|>Retrieve the domain from core.<|endoftext|>
59efc24abdb5ebe0ec48fe9b06ffb4345eb2d9abe723a6a7f2e90f4690af428c
async def retrieve_status(endpoint: EndpointConfig) -> Dict[(Text, Any)]: 'Retrieve the status from core.' return (await endpoint.request(method='get', subpath='/status'))
Retrieve the status from core.
rasa/core/training/interactive.py
retrieve_status
LaudateCorpus1/rasa_core
2,433
python
async def retrieve_status(endpoint: EndpointConfig) -> Dict[(Text, Any)]: return (await endpoint.request(method='get', subpath='/status'))
async def retrieve_status(endpoint: EndpointConfig) -> Dict[(Text, Any)]: return (await endpoint.request(method='get', subpath='/status'))<|docstring|>Retrieve the status from core.<|endoftext|>
9d6955093cbf4c76278010989eb2f9ab0db030edbd6eb641ddfbe26186799fe5
async def retrieve_tracker(endpoint: EndpointConfig, sender_id: Text, verbosity: EventVerbosity=EventVerbosity.ALL) -> Dict[(Text, Any)]: 'Retrieve a tracker from core.' path = '/conversations/{}/tracker?include_events={}'.format(sender_id, verbosity.name) return (await endpoint.request(method='get', subpath=path, headers={'Accept': 'application/json'}))
Retrieve a tracker from core.
rasa/core/training/interactive.py
retrieve_tracker
LaudateCorpus1/rasa_core
2,433
python
async def retrieve_tracker(endpoint: EndpointConfig, sender_id: Text, verbosity: EventVerbosity=EventVerbosity.ALL) -> Dict[(Text, Any)]: path = '/conversations/{}/tracker?include_events={}'.format(sender_id, verbosity.name) return (await endpoint.request(method='get', subpath=path, headers={'Accept': 'application/json'}))
async def retrieve_tracker(endpoint: EndpointConfig, sender_id: Text, verbosity: EventVerbosity=EventVerbosity.ALL) -> Dict[(Text, Any)]: path = '/conversations/{}/tracker?include_events={}'.format(sender_id, verbosity.name) return (await endpoint.request(method='get', subpath=path, headers={'Accept': 'application/json'}))<|docstring|>Retrieve a tracker from core.<|endoftext|>
3b9765c659f2ec4670469addda6d85b8ccd164207273d8d7b9b3debd3b11b44e
async def send_action(endpoint: EndpointConfig, sender_id: Text, action_name: Text, policy: Optional[Text]=None, confidence: Optional[float]=None, is_new_action: bool=False) -> Dict[(Text, Any)]: 'Log an action to a conversation.' payload = ActionExecuted(action_name, policy, confidence).as_dict() subpath = '/conversations/{}/execute'.format(sender_id) try: return (await endpoint.request(json=payload, method='post', subpath=subpath)) except ClientError: if is_new_action: warning_questions = questionary.confirm("WARNING: You have created a new action: '{}', which was not successfully executed. If this action does not return any events, you do not need to do anything. If this is a custom action which returns events, you are recommended to implement this action in your action server and try again.".format(action_name)) (await _ask_questions(warning_questions, sender_id, endpoint)) payload = ActionExecuted(action_name).as_dict() return (await send_event(endpoint, sender_id, payload)) else: logger.error('failed to execute action!') raise
Log an action to a conversation.
rasa/core/training/interactive.py
send_action
LaudateCorpus1/rasa_core
2,433
python
async def send_action(endpoint: EndpointConfig, sender_id: Text, action_name: Text, policy: Optional[Text]=None, confidence: Optional[float]=None, is_new_action: bool=False) -> Dict[(Text, Any)]: payload = ActionExecuted(action_name, policy, confidence).as_dict() subpath = '/conversations/{}/execute'.format(sender_id) try: return (await endpoint.request(json=payload, method='post', subpath=subpath)) except ClientError: if is_new_action: warning_questions = questionary.confirm("WARNING: You have created a new action: '{}', which was not successfully executed. If this action does not return any events, you do not need to do anything. If this is a custom action which returns events, you are recommended to implement this action in your action server and try again.".format(action_name)) (await _ask_questions(warning_questions, sender_id, endpoint)) payload = ActionExecuted(action_name).as_dict() return (await send_event(endpoint, sender_id, payload)) else: logger.error('failed to execute action!') raise
async def send_action(endpoint: EndpointConfig, sender_id: Text, action_name: Text, policy: Optional[Text]=None, confidence: Optional[float]=None, is_new_action: bool=False) -> Dict[(Text, Any)]: payload = ActionExecuted(action_name, policy, confidence).as_dict() subpath = '/conversations/{}/execute'.format(sender_id) try: return (await endpoint.request(json=payload, method='post', subpath=subpath)) except ClientError: if is_new_action: warning_questions = questionary.confirm("WARNING: You have created a new action: '{}', which was not successfully executed. If this action does not return any events, you do not need to do anything. If this is a custom action which returns events, you are recommended to implement this action in your action server and try again.".format(action_name)) (await _ask_questions(warning_questions, sender_id, endpoint)) payload = ActionExecuted(action_name).as_dict() return (await send_event(endpoint, sender_id, payload)) else: logger.error('failed to execute action!') raise<|docstring|>Log an action to a conversation.<|endoftext|>
86ce40fd0d87b71396f7459fa3fb16501660a99df36f6187ec4a203be68037d2
async def send_event(endpoint: EndpointConfig, sender_id: Text, evt: Dict[(Text, Any)]) -> Dict[(Text, Any)]: 'Log an event to a conversation.' subpath = '/conversations/{}/tracker/events'.format(sender_id) return (await endpoint.request(json=evt, method='post', subpath=subpath))
Log an event to a conversation.
rasa/core/training/interactive.py
send_event
LaudateCorpus1/rasa_core
2,433
python
async def send_event(endpoint: EndpointConfig, sender_id: Text, evt: Dict[(Text, Any)]) -> Dict[(Text, Any)]: subpath = '/conversations/{}/tracker/events'.format(sender_id) return (await endpoint.request(json=evt, method='post', subpath=subpath))
async def send_event(endpoint: EndpointConfig, sender_id: Text, evt: Dict[(Text, Any)]) -> Dict[(Text, Any)]: subpath = '/conversations/{}/tracker/events'.format(sender_id) return (await endpoint.request(json=evt, method='post', subpath=subpath))<|docstring|>Log an event to a conversation.<|endoftext|>
6dc6944985a741e5f59b7b0786b8b806154ca49be43592ad00bd004893c05eea
async def replace_events(endpoint: EndpointConfig, sender_id: Text, evts: List[Dict[(Text, Any)]]) -> Dict[(Text, Any)]: 'Replace all the events of a conversation with the provided ones.' subpath = '/conversations/{}/tracker/events'.format(sender_id) return (await endpoint.request(json=evts, method='put', subpath=subpath))
Replace all the events of a conversation with the provided ones.
rasa/core/training/interactive.py
replace_events
LaudateCorpus1/rasa_core
2,433
python
async def replace_events(endpoint: EndpointConfig, sender_id: Text, evts: List[Dict[(Text, Any)]]) -> Dict[(Text, Any)]: subpath = '/conversations/{}/tracker/events'.format(sender_id) return (await endpoint.request(json=evts, method='put', subpath=subpath))
async def replace_events(endpoint: EndpointConfig, sender_id: Text, evts: List[Dict[(Text, Any)]]) -> Dict[(Text, Any)]: subpath = '/conversations/{}/tracker/events'.format(sender_id) return (await endpoint.request(json=evts, method='put', subpath=subpath))<|docstring|>Replace all the events of a conversation with the provided ones.<|endoftext|>
c77ff0ee0ff8fdb7494b4ff1c89ad3d308d3bbf13577615b5f8dfb9a572fad63
async def send_finetune(endpoint: EndpointConfig, evts: List[Dict[(Text, Any)]]) -> Dict[(Text, Any)]: 'Finetune a core model on the provided additional training samples.' return (await endpoint.request(json=evts, method='post', subpath='/finetune'))
Finetune a core model on the provided additional training samples.
rasa/core/training/interactive.py
send_finetune
LaudateCorpus1/rasa_core
2,433
python
async def send_finetune(endpoint: EndpointConfig, evts: List[Dict[(Text, Any)]]) -> Dict[(Text, Any)]: return (await endpoint.request(json=evts, method='post', subpath='/finetune'))
async def send_finetune(endpoint: EndpointConfig, evts: List[Dict[(Text, Any)]]) -> Dict[(Text, Any)]: return (await endpoint.request(json=evts, method='post', subpath='/finetune'))<|docstring|>Finetune a core model on the provided additional training samples.<|endoftext|>
3e90a7e4e9fe39d40a8d9ecdef8414d0af8da1db8aba70d86fb814239570ade4
def format_bot_output(message: Dict[(Text, Any)]) -> Text: 'Format a bot response to be displayed in the history table.' output = (message.get('text') or '') data = message.get('data', {}) if (not data): return output if data.get('image'): output += ('\nImage: ' + data.get('image')) if data.get('attachment'): output += ('\nAttachment: ' + data.get('attachment')) if data.get('buttons'): output += '\nButtons:' for (idx, button) in enumerate(data.get('buttons')): button_str = button_to_string(button, idx) output += ('\n' + button_str) if data.get('elements'): output += '\nElements:' for (idx, element) in enumerate(data.get('elements')): element_str = element_to_string(element, idx) output += ('\n' + element_str) if data.get('quick_replies'): output += '\nQuick replies:' for (idx, element) in enumerate(data.get('quick_replies')): element_str = element_to_string(element, idx) output += ('\n' + element_str) return output
Format a bot response to be displayed in the history table.
rasa/core/training/interactive.py
format_bot_output
LaudateCorpus1/rasa_core
2,433
python
def format_bot_output(message: Dict[(Text, Any)]) -> Text: output = (message.get('text') or ) data = message.get('data', {}) if (not data): return output if data.get('image'): output += ('\nImage: ' + data.get('image')) if data.get('attachment'): output += ('\nAttachment: ' + data.get('attachment')) if data.get('buttons'): output += '\nButtons:' for (idx, button) in enumerate(data.get('buttons')): button_str = button_to_string(button, idx) output += ('\n' + button_str) if data.get('elements'): output += '\nElements:' for (idx, element) in enumerate(data.get('elements')): element_str = element_to_string(element, idx) output += ('\n' + element_str) if data.get('quick_replies'): output += '\nQuick replies:' for (idx, element) in enumerate(data.get('quick_replies')): element_str = element_to_string(element, idx) output += ('\n' + element_str) return output
def format_bot_output(message: Dict[(Text, Any)]) -> Text: output = (message.get('text') or ) data = message.get('data', {}) if (not data): return output if data.get('image'): output += ('\nImage: ' + data.get('image')) if data.get('attachment'): output += ('\nAttachment: ' + data.get('attachment')) if data.get('buttons'): output += '\nButtons:' for (idx, button) in enumerate(data.get('buttons')): button_str = button_to_string(button, idx) output += ('\n' + button_str) if data.get('elements'): output += '\nElements:' for (idx, element) in enumerate(data.get('elements')): element_str = element_to_string(element, idx) output += ('\n' + element_str) if data.get('quick_replies'): output += '\nQuick replies:' for (idx, element) in enumerate(data.get('quick_replies')): element_str = element_to_string(element, idx) output += ('\n' + element_str) return output<|docstring|>Format a bot response to be displayed in the history table.<|endoftext|>
e2fd96c6dee1d5be9ac420e58922bb3fa6ded467c753b4cac730f074982f85bd
def latest_user_message(evts: List[Dict[(Text, Any)]]) -> Optional[Dict[(Text, Any)]]: 'Return most recent user message.' for (i, e) in enumerate(reversed(evts)): if (e.get('event') == UserUttered.type_name): return e return None
Return most recent user message.
rasa/core/training/interactive.py
latest_user_message
LaudateCorpus1/rasa_core
2,433
python
def latest_user_message(evts: List[Dict[(Text, Any)]]) -> Optional[Dict[(Text, Any)]]: for (i, e) in enumerate(reversed(evts)): if (e.get('event') == UserUttered.type_name): return e return None
def latest_user_message(evts: List[Dict[(Text, Any)]]) -> Optional[Dict[(Text, Any)]]: for (i, e) in enumerate(reversed(evts)): if (e.get('event') == UserUttered.type_name): return e return None<|docstring|>Return most recent user message.<|endoftext|>
5c2a79fb4042ef852c00c0c9634ee574122fecfed7081913fe210478a39ddbbc
def all_events_before_latest_user_msg(evts: List[Dict[(Text, Any)]]) -> List[Dict[(Text, Any)]]: 'Return all events that happened before the most recent user message.' for (i, e) in enumerate(reversed(evts)): if (e.get('event') == UserUttered.type_name): return evts[:(- (i + 1))] return evts
Return all events that happened before the most recent user message.
rasa/core/training/interactive.py
all_events_before_latest_user_msg
LaudateCorpus1/rasa_core
2,433
python
def all_events_before_latest_user_msg(evts: List[Dict[(Text, Any)]]) -> List[Dict[(Text, Any)]]: for (i, e) in enumerate(reversed(evts)): if (e.get('event') == UserUttered.type_name): return evts[:(- (i + 1))] return evts
def all_events_before_latest_user_msg(evts: List[Dict[(Text, Any)]]) -> List[Dict[(Text, Any)]]: for (i, e) in enumerate(reversed(evts)): if (e.get('event') == UserUttered.type_name): return evts[:(- (i + 1))] return evts<|docstring|>Return all events that happened before the most recent user message.<|endoftext|>
d9ab6becbbc945d51751ab94421716be9acb7c992cfab6b14a1e94136dbed080
async def _ask_questions(questions: Union[(Form, Question)], sender_id: Text, endpoint: EndpointConfig, is_abort: Callable[([Dict[(Text, Any)]], bool)]=(lambda x: False)) -> Any: 'Ask the user a question, if Ctrl-C is pressed provide user with menu.' should_retry = True answers = {} while should_retry: answers = questions.ask() if ((answers is None) or is_abort(answers)): should_retry = (await _ask_if_quit(sender_id, endpoint)) else: should_retry = False return answers
Ask the user a question, if Ctrl-C is pressed provide user with menu.
rasa/core/training/interactive.py
_ask_questions
LaudateCorpus1/rasa_core
2,433
python
async def _ask_questions(questions: Union[(Form, Question)], sender_id: Text, endpoint: EndpointConfig, is_abort: Callable[([Dict[(Text, Any)]], bool)]=(lambda x: False)) -> Any: should_retry = True answers = {} while should_retry: answers = questions.ask() if ((answers is None) or is_abort(answers)): should_retry = (await _ask_if_quit(sender_id, endpoint)) else: should_retry = False return answers
async def _ask_questions(questions: Union[(Form, Question)], sender_id: Text, endpoint: EndpointConfig, is_abort: Callable[([Dict[(Text, Any)]], bool)]=(lambda x: False)) -> Any: should_retry = True answers = {} while should_retry: answers = questions.ask() if ((answers is None) or is_abort(answers)): should_retry = (await _ask_if_quit(sender_id, endpoint)) else: should_retry = False return answers<|docstring|>Ask the user a question, if Ctrl-C is pressed provide user with menu.<|endoftext|>
e916f1fe00d9ac84fa7c12ee37e946bc2bc4727946dc1bee25374d1d3ae2a808
def _selection_choices_from_intent_prediction(predictions: List[Dict[(Text, Any)]]) -> List[Dict[(Text, Text)]]: '"Given a list of ML predictions create a UI choice list.' sorted_intents = sorted(predictions, key=(lambda k: ((- k['confidence']), k['name']))) choices = [] for p in sorted_intents: name_with_confidence = '{:03.2f} {:40}'.format(p.get('confidence'), p.get('name')) choice = {'name': name_with_confidence, 'value': p.get('name')} choices.append(choice) return choices
"Given a list of ML predictions create a UI choice list.
rasa/core/training/interactive.py
_selection_choices_from_intent_prediction
LaudateCorpus1/rasa_core
2,433
python
def _selection_choices_from_intent_prediction(predictions: List[Dict[(Text, Any)]]) -> List[Dict[(Text, Text)]]: sorted_intents = sorted(predictions, key=(lambda k: ((- k['confidence']), k['name']))) choices = [] for p in sorted_intents: name_with_confidence = '{:03.2f} {:40}'.format(p.get('confidence'), p.get('name')) choice = {'name': name_with_confidence, 'value': p.get('name')} choices.append(choice) return choices
def _selection_choices_from_intent_prediction(predictions: List[Dict[(Text, Any)]]) -> List[Dict[(Text, Text)]]: sorted_intents = sorted(predictions, key=(lambda k: ((- k['confidence']), k['name']))) choices = [] for p in sorted_intents: name_with_confidence = '{:03.2f} {:40}'.format(p.get('confidence'), p.get('name')) choice = {'name': name_with_confidence, 'value': p.get('name')} choices.append(choice) return choices<|docstring|>"Given a list of ML predictions create a UI choice list.<|endoftext|>
b18359b2aa2fcd7a8e316644b4df99ce214936bd6f43df2cd3640a6f29f34a9b
async def _request_fork_from_user(sender_id, endpoint) -> Optional[List[Dict[(Text, Any)]]]: 'Take in a conversation and ask at which point to fork the conversation.\n\n Returns the list of events that should be kept. Forking means, the\n conversation will be reset and continued from this previous point.' tracker = (await retrieve_tracker(endpoint, sender_id, EventVerbosity.AFTER_RESTART)) choices = [] for (i, e) in enumerate(tracker.get('events', [])): if (e.get('event') == UserUttered.type_name): choices.append({'name': e.get('text'), 'value': i}) fork_idx = (await _request_fork_point_from_list(list(reversed(choices)), sender_id, endpoint)) if (fork_idx is not None): return tracker.get('events', [])[:int(fork_idx)] else: return None
Take in a conversation and ask at which point to fork the conversation. Returns the list of events that should be kept. Forking means, the conversation will be reset and continued from this previous point.
rasa/core/training/interactive.py
_request_fork_from_user
LaudateCorpus1/rasa_core
2,433
python
async def _request_fork_from_user(sender_id, endpoint) -> Optional[List[Dict[(Text, Any)]]]: 'Take in a conversation and ask at which point to fork the conversation.\n\n Returns the list of events that should be kept. Forking means, the\n conversation will be reset and continued from this previous point.' tracker = (await retrieve_tracker(endpoint, sender_id, EventVerbosity.AFTER_RESTART)) choices = [] for (i, e) in enumerate(tracker.get('events', [])): if (e.get('event') == UserUttered.type_name): choices.append({'name': e.get('text'), 'value': i}) fork_idx = (await _request_fork_point_from_list(list(reversed(choices)), sender_id, endpoint)) if (fork_idx is not None): return tracker.get('events', [])[:int(fork_idx)] else: return None
async def _request_fork_from_user(sender_id, endpoint) -> Optional[List[Dict[(Text, Any)]]]: 'Take in a conversation and ask at which point to fork the conversation.\n\n Returns the list of events that should be kept. Forking means, the\n conversation will be reset and continued from this previous point.' tracker = (await retrieve_tracker(endpoint, sender_id, EventVerbosity.AFTER_RESTART)) choices = [] for (i, e) in enumerate(tracker.get('events', [])): if (e.get('event') == UserUttered.type_name): choices.append({'name': e.get('text'), 'value': i}) fork_idx = (await _request_fork_point_from_list(list(reversed(choices)), sender_id, endpoint)) if (fork_idx is not None): return tracker.get('events', [])[:int(fork_idx)] else: return None<|docstring|>Take in a conversation and ask at which point to fork the conversation. Returns the list of events that should be kept. Forking means, the conversation will be reset and continued from this previous point.<|endoftext|>
515dc4dd877a067df4e2cac90e6f76e7576d561b5ab916ca2da179fa91d1661e
async def _request_intent_from_user(latest_message, intents, sender_id, endpoint) -> Dict[(Text, Any)]: 'Take in latest message and ask which intent it should have been.\n\n Returns the intent dict that has been selected by the user.' predictions = latest_message.get('parse_data', {}).get('intent_ranking', []) predicted_intents = {p['name'] for p in predictions} for i in intents: if (i not in predicted_intents): predictions.append({'name': i, 'confidence': 0.0}) choices = ([{'name': '<create_new_intent>', 'value': OTHER_INTENT}] + _selection_choices_from_intent_prediction(predictions)) intent_name = (await _request_selection_from_intent_list(choices, sender_id, endpoint)) if (intent_name == OTHER_INTENT): intent_name = (await _request_free_text_intent(sender_id, endpoint)) return {'name': intent_name, 'confidence': 1.0} return next((x for x in predictions if (x['name'] == intent_name)), None)
Take in latest message and ask which intent it should have been. Returns the intent dict that has been selected by the user.
rasa/core/training/interactive.py
_request_intent_from_user
LaudateCorpus1/rasa_core
2,433
python
async def _request_intent_from_user(latest_message, intents, sender_id, endpoint) -> Dict[(Text, Any)]: 'Take in latest message and ask which intent it should have been.\n\n Returns the intent dict that has been selected by the user.' predictions = latest_message.get('parse_data', {}).get('intent_ranking', []) predicted_intents = {p['name'] for p in predictions} for i in intents: if (i not in predicted_intents): predictions.append({'name': i, 'confidence': 0.0}) choices = ([{'name': '<create_new_intent>', 'value': OTHER_INTENT}] + _selection_choices_from_intent_prediction(predictions)) intent_name = (await _request_selection_from_intent_list(choices, sender_id, endpoint)) if (intent_name == OTHER_INTENT): intent_name = (await _request_free_text_intent(sender_id, endpoint)) return {'name': intent_name, 'confidence': 1.0} return next((x for x in predictions if (x['name'] == intent_name)), None)
async def _request_intent_from_user(latest_message, intents, sender_id, endpoint) -> Dict[(Text, Any)]: 'Take in latest message and ask which intent it should have been.\n\n Returns the intent dict that has been selected by the user.' predictions = latest_message.get('parse_data', {}).get('intent_ranking', []) predicted_intents = {p['name'] for p in predictions} for i in intents: if (i not in predicted_intents): predictions.append({'name': i, 'confidence': 0.0}) choices = ([{'name': '<create_new_intent>', 'value': OTHER_INTENT}] + _selection_choices_from_intent_prediction(predictions)) intent_name = (await _request_selection_from_intent_list(choices, sender_id, endpoint)) if (intent_name == OTHER_INTENT): intent_name = (await _request_free_text_intent(sender_id, endpoint)) return {'name': intent_name, 'confidence': 1.0} return next((x for x in predictions if (x['name'] == intent_name)), None)<|docstring|>Take in latest message and ask which intent it should have been. Returns the intent dict that has been selected by the user.<|endoftext|>
b1813e510ecfd23eb9d84f965998f8edac4a5d732ac87a318a3091f95957d90d
async def _print_history(sender_id: Text, endpoint: EndpointConfig) -> None: 'Print information about the conversation for the user.' tracker_dump = (await retrieve_tracker(endpoint, sender_id, EventVerbosity.AFTER_RESTART)) evts = tracker_dump.get('events', []) table = _chat_history_table(evts) slot_strs = _slot_history(tracker_dump) print('------') print('Chat History\n') print(table) if slot_strs: print('\n') print('Current slots: \n\t{}\n'.format(', '.join(slot_strs))) print('------')
Print information about the conversation for the user.
rasa/core/training/interactive.py
_print_history
LaudateCorpus1/rasa_core
2,433
python
async def _print_history(sender_id: Text, endpoint: EndpointConfig) -> None: tracker_dump = (await retrieve_tracker(endpoint, sender_id, EventVerbosity.AFTER_RESTART)) evts = tracker_dump.get('events', []) table = _chat_history_table(evts) slot_strs = _slot_history(tracker_dump) print('------') print('Chat History\n') print(table) if slot_strs: print('\n') print('Current slots: \n\t{}\n'.format(', '.join(slot_strs))) print('------')
async def _print_history(sender_id: Text, endpoint: EndpointConfig) -> None: tracker_dump = (await retrieve_tracker(endpoint, sender_id, EventVerbosity.AFTER_RESTART)) evts = tracker_dump.get('events', []) table = _chat_history_table(evts) slot_strs = _slot_history(tracker_dump) print('------') print('Chat History\n') print(table) if slot_strs: print('\n') print('Current slots: \n\t{}\n'.format(', '.join(slot_strs))) print('------')<|docstring|>Print information about the conversation for the user.<|endoftext|>
8edb6a1e8f738ec277c03c55e8abfd488ce5c0d16beda463894933de94e587d9
def _chat_history_table(evts: List[Dict[(Text, Any)]]) -> Text: 'Create a table containing bot and user messages.\n\n Also includes additional information, like any events and\n prediction probabilities.' def wrap(txt, max_width): return '\n'.join(textwrap.wrap(txt, max_width, replace_whitespace=False)) def colored(txt, color): return (((((('{' + color) + '}') + txt) + '{/') + color) + '}') def format_user_msg(user_evt, max_width): _parsed = user_evt.get('parse_data', {}) _intent = _parsed.get('intent', {}).get('name') _confidence = _parsed.get('intent', {}).get('confidence', 1.0) _md = _as_md_message(_parsed) _lines = [colored(wrap(_md, max_width), 'hired'), 'intent: {} {:03.2f}'.format(_intent, _confidence)] return '\n'.join(_lines) def bot_width(_table: AsciiTable) -> int: return _table.column_max_width(1) def user_width(_table: AsciiTable) -> int: return _table.column_max_width(3) def add_bot_cell(data, cell): data.append([len(data), Color(cell), '', '']) def add_user_cell(data, cell): data.append([len(data), '', '', Color(cell)]) table_data = [['# ', Color(colored('Bot ', 'autoblue')), ' ', Color(colored('You ', 'hired'))]] table = SingleTable(table_data, 'Chat History') bot_column = [] for (idx, evt) in enumerate(evts): if (evt.get('event') == ActionExecuted.type_name): bot_column.append(colored(evt['name'], 'autocyan')) if (evt['confidence'] is not None): bot_column[(- 1)] += colored(' {:03.2f}'.format(evt['confidence']), 'autowhite') elif (evt.get('event') == UserUttered.type_name): if bot_column: text = '\n'.join(bot_column) add_bot_cell(table_data, text) bot_column = [] msg = format_user_msg(evt, user_width(table)) add_user_cell(table_data, msg) elif (evt.get('event') == BotUttered.type_name): wrapped = wrap(format_bot_output(evt), bot_width(table)) bot_column.append(colored(wrapped, 'autoblue')) else: e = Event.from_parameters(evt) if e.as_story_string(): bot_column.append(wrap(e.as_story_string(), bot_width(table))) if bot_column: text = '\n'.join(bot_column) add_bot_cell(table_data, text) table.inner_heading_row_border = False table.inner_row_border = True table.inner_column_border = False table.outer_border = False table.justify_columns = {0: 'left', 1: 'left', 2: 'center', 3: 'right'} return table.table
Create a table containing bot and user messages. Also includes additional information, like any events and prediction probabilities.
rasa/core/training/interactive.py
_chat_history_table
LaudateCorpus1/rasa_core
2,433
python
def _chat_history_table(evts: List[Dict[(Text, Any)]]) -> Text: 'Create a table containing bot and user messages.\n\n Also includes additional information, like any events and\n prediction probabilities.' def wrap(txt, max_width): return '\n'.join(textwrap.wrap(txt, max_width, replace_whitespace=False)) def colored(txt, color): return (((((('{' + color) + '}') + txt) + '{/') + color) + '}') def format_user_msg(user_evt, max_width): _parsed = user_evt.get('parse_data', {}) _intent = _parsed.get('intent', {}).get('name') _confidence = _parsed.get('intent', {}).get('confidence', 1.0) _md = _as_md_message(_parsed) _lines = [colored(wrap(_md, max_width), 'hired'), 'intent: {} {:03.2f}'.format(_intent, _confidence)] return '\n'.join(_lines) def bot_width(_table: AsciiTable) -> int: return _table.column_max_width(1) def user_width(_table: AsciiTable) -> int: return _table.column_max_width(3) def add_bot_cell(data, cell): data.append([len(data), Color(cell), , ]) def add_user_cell(data, cell): data.append([len(data), , , Color(cell)]) table_data = [['# ', Color(colored('Bot ', 'autoblue')), ' ', Color(colored('You ', 'hired'))]] table = SingleTable(table_data, 'Chat History') bot_column = [] for (idx, evt) in enumerate(evts): if (evt.get('event') == ActionExecuted.type_name): bot_column.append(colored(evt['name'], 'autocyan')) if (evt['confidence'] is not None): bot_column[(- 1)] += colored(' {:03.2f}'.format(evt['confidence']), 'autowhite') elif (evt.get('event') == UserUttered.type_name): if bot_column: text = '\n'.join(bot_column) add_bot_cell(table_data, text) bot_column = [] msg = format_user_msg(evt, user_width(table)) add_user_cell(table_data, msg) elif (evt.get('event') == BotUttered.type_name): wrapped = wrap(format_bot_output(evt), bot_width(table)) bot_column.append(colored(wrapped, 'autoblue')) else: e = Event.from_parameters(evt) if e.as_story_string(): bot_column.append(wrap(e.as_story_string(), bot_width(table))) if bot_column: text = '\n'.join(bot_column) add_bot_cell(table_data, text) table.inner_heading_row_border = False table.inner_row_border = True table.inner_column_border = False table.outer_border = False table.justify_columns = {0: 'left', 1: 'left', 2: 'center', 3: 'right'} return table.table
def _chat_history_table(evts: List[Dict[(Text, Any)]]) -> Text: 'Create a table containing bot and user messages.\n\n Also includes additional information, like any events and\n prediction probabilities.' def wrap(txt, max_width): return '\n'.join(textwrap.wrap(txt, max_width, replace_whitespace=False)) def colored(txt, color): return (((((('{' + color) + '}') + txt) + '{/') + color) + '}') def format_user_msg(user_evt, max_width): _parsed = user_evt.get('parse_data', {}) _intent = _parsed.get('intent', {}).get('name') _confidence = _parsed.get('intent', {}).get('confidence', 1.0) _md = _as_md_message(_parsed) _lines = [colored(wrap(_md, max_width), 'hired'), 'intent: {} {:03.2f}'.format(_intent, _confidence)] return '\n'.join(_lines) def bot_width(_table: AsciiTable) -> int: return _table.column_max_width(1) def user_width(_table: AsciiTable) -> int: return _table.column_max_width(3) def add_bot_cell(data, cell): data.append([len(data), Color(cell), , ]) def add_user_cell(data, cell): data.append([len(data), , , Color(cell)]) table_data = [['# ', Color(colored('Bot ', 'autoblue')), ' ', Color(colored('You ', 'hired'))]] table = SingleTable(table_data, 'Chat History') bot_column = [] for (idx, evt) in enumerate(evts): if (evt.get('event') == ActionExecuted.type_name): bot_column.append(colored(evt['name'], 'autocyan')) if (evt['confidence'] is not None): bot_column[(- 1)] += colored(' {:03.2f}'.format(evt['confidence']), 'autowhite') elif (evt.get('event') == UserUttered.type_name): if bot_column: text = '\n'.join(bot_column) add_bot_cell(table_data, text) bot_column = [] msg = format_user_msg(evt, user_width(table)) add_user_cell(table_data, msg) elif (evt.get('event') == BotUttered.type_name): wrapped = wrap(format_bot_output(evt), bot_width(table)) bot_column.append(colored(wrapped, 'autoblue')) else: e = Event.from_parameters(evt) if e.as_story_string(): bot_column.append(wrap(e.as_story_string(), bot_width(table))) if bot_column: text = '\n'.join(bot_column) add_bot_cell(table_data, text) table.inner_heading_row_border = False table.inner_row_border = True table.inner_column_border = False table.outer_border = False table.justify_columns = {0: 'left', 1: 'left', 2: 'center', 3: 'right'} return table.table<|docstring|>Create a table containing bot and user messages. Also includes additional information, like any events and prediction probabilities.<|endoftext|>
1271e0ba57b51835e508c24eb2f356533bf56ad497324fbf24e20c35cd64a8c6
def _slot_history(tracker_dump: Dict[(Text, Any)]) -> List[Text]: 'Create an array of slot representations to be displayed.' slot_strs = [] for (k, s) in tracker_dump.get('slots').items(): colored_value = cliutils.wrap_with_color(str(s), rasa.cli.utils.bcolors.WARNING) slot_strs.append('{}: {}'.format(k, colored_value)) return slot_strs
Create an array of slot representations to be displayed.
rasa/core/training/interactive.py
_slot_history
LaudateCorpus1/rasa_core
2,433
python
def _slot_history(tracker_dump: Dict[(Text, Any)]) -> List[Text]: slot_strs = [] for (k, s) in tracker_dump.get('slots').items(): colored_value = cliutils.wrap_with_color(str(s), rasa.cli.utils.bcolors.WARNING) slot_strs.append('{}: {}'.format(k, colored_value)) return slot_strs
def _slot_history(tracker_dump: Dict[(Text, Any)]) -> List[Text]: slot_strs = [] for (k, s) in tracker_dump.get('slots').items(): colored_value = cliutils.wrap_with_color(str(s), rasa.cli.utils.bcolors.WARNING) slot_strs.append('{}: {}'.format(k, colored_value)) return slot_strs<|docstring|>Create an array of slot representations to be displayed.<|endoftext|>
dfc1d21aeff736093686e3c20a415d1eebbfec498a44d0cc240743ab2ee28933
async def _write_data_to_file(sender_id: Text, endpoint: EndpointConfig): 'Write stories and nlu data to file.' (story_path, nlu_path, domain_path) = _request_export_info() tracker = (await retrieve_tracker(endpoint, sender_id)) evts = tracker.get('events', []) (await _write_stories_to_file(story_path, evts)) (await _write_nlu_to_file(nlu_path, evts)) (await _write_domain_to_file(domain_path, evts, endpoint)) logger.info('Successfully wrote stories and NLU data')
Write stories and nlu data to file.
rasa/core/training/interactive.py
_write_data_to_file
LaudateCorpus1/rasa_core
2,433
python
async def _write_data_to_file(sender_id: Text, endpoint: EndpointConfig): (story_path, nlu_path, domain_path) = _request_export_info() tracker = (await retrieve_tracker(endpoint, sender_id)) evts = tracker.get('events', []) (await _write_stories_to_file(story_path, evts)) (await _write_nlu_to_file(nlu_path, evts)) (await _write_domain_to_file(domain_path, evts, endpoint)) logger.info('Successfully wrote stories and NLU data')
async def _write_data_to_file(sender_id: Text, endpoint: EndpointConfig): (story_path, nlu_path, domain_path) = _request_export_info() tracker = (await retrieve_tracker(endpoint, sender_id)) evts = tracker.get('events', []) (await _write_stories_to_file(story_path, evts)) (await _write_nlu_to_file(nlu_path, evts)) (await _write_domain_to_file(domain_path, evts, endpoint)) logger.info('Successfully wrote stories and NLU data')<|docstring|>Write stories and nlu data to file.<|endoftext|>
d98aa1081f3099be20f9480c2981951dae1e8d8e2226c1bfccf7513bf990d6f4
async def _ask_if_quit(sender_id: Text, endpoint: EndpointConfig) -> bool: 'Display the exit menu.\n\n Return `True` if the previous question should be retried.' answer = questionary.select(message='Do you want to stop?', choices=[Choice('Continue', 'continue'), Choice('Undo Last', 'undo'), Choice('Fork', 'fork'), Choice('Start Fresh', 'restart'), Choice('Export & Quit', 'quit')]).ask() if ((not answer) or (answer == 'quit')): (await _write_data_to_file(sender_id, endpoint)) raise Abort() elif (answer == 'continue'): return True elif (answer == 'undo'): raise UndoLastStep() elif (answer == 'fork'): raise ForkTracker() elif (answer == 'restart'): raise RestartConversation()
Display the exit menu. Return `True` if the previous question should be retried.
rasa/core/training/interactive.py
_ask_if_quit
LaudateCorpus1/rasa_core
2,433
python
async def _ask_if_quit(sender_id: Text, endpoint: EndpointConfig) -> bool: 'Display the exit menu.\n\n Return `True` if the previous question should be retried.' answer = questionary.select(message='Do you want to stop?', choices=[Choice('Continue', 'continue'), Choice('Undo Last', 'undo'), Choice('Fork', 'fork'), Choice('Start Fresh', 'restart'), Choice('Export & Quit', 'quit')]).ask() if ((not answer) or (answer == 'quit')): (await _write_data_to_file(sender_id, endpoint)) raise Abort() elif (answer == 'continue'): return True elif (answer == 'undo'): raise UndoLastStep() elif (answer == 'fork'): raise ForkTracker() elif (answer == 'restart'): raise RestartConversation()
async def _ask_if_quit(sender_id: Text, endpoint: EndpointConfig) -> bool: 'Display the exit menu.\n\n Return `True` if the previous question should be retried.' answer = questionary.select(message='Do you want to stop?', choices=[Choice('Continue', 'continue'), Choice('Undo Last', 'undo'), Choice('Fork', 'fork'), Choice('Start Fresh', 'restart'), Choice('Export & Quit', 'quit')]).ask() if ((not answer) or (answer == 'quit')): (await _write_data_to_file(sender_id, endpoint)) raise Abort() elif (answer == 'continue'): return True elif (answer == 'undo'): raise UndoLastStep() elif (answer == 'fork'): raise ForkTracker() elif (answer == 'restart'): raise RestartConversation()<|docstring|>Display the exit menu. Return `True` if the previous question should be retried.<|endoftext|>