id
stringlengths
2
8
text
stringlengths
16
264k
dataset_id
stringclasses
1 value
9655119
<reponame>Heron-Repositories/Transfer-Learning-In-Animals import numpy as np import copy class MTT: def __init__(self, _min_distance_to_target, _max_distance_to_target, _target_offsets, _trap_offsets, _dt, _man_speed, _must_lift_at_target, up_or_down): self.min_distance_to_target = _min_distance_to_target self.max_distance_to_target = _max_distance_to_target self.target_offsets = _target_offsets self.trap_offsets = _trap_offsets self.dt = _dt self.man_speed = _man_speed self.must_lift_at_target = _must_lift_at_target self.positions_of_visuals = np.empty(3) self.up_or_down = up_or_down manipulandum, target, trap = self.initialise_trial() self.positions_of_visuals = np.array([manipulandum, target, trap]) self.initial_positions_of_visuals = copy.copy(self.positions_of_visuals) self.angle_dif_between_man_and_target_trap = 5 ''' def initialise_trial_with_variable_target_trap(self): manipulandum = np.random.randint(360 - 80, 360 - 9) if self.up_or_down: target = np.random.randint(manipulandum + self.min_distance_to_target + 11, np.min([manipulandum + self.max_distance_to_target + 12, 0])) trap = np.random.randint(360 - 90, manipulandum - 9) else: trap = np.random.randint(manipulandum + 11, 360) target = np.random.randint(np.max([manipulandum - self.max_distance_to_target - 10, 360 - 90]), manipulandum - self.min_distance_to_target - 9) return manipulandum, target, trap ''' def initialise_trial(self): def offset(target, trap): def adjust(pos): if pos < 0: return pos + 360 if pos > 360: return pos - 360 return pos target_minus = target + self.target_offsets[0] target_plus = target + self.target_offsets[1] trap_minus = trap + self.trap_offsets[0] trap_plus = trap + self.trap_offsets[1] if target_minus != target_plus: target = adjust(np.random.randint(target_minus, target_plus)) if trap_minus != trap_plus: trap = adjust(np.random.randint(trap_minus, trap_plus)) return target, trap if self.up_or_down: target, trap = offset(360, 360-90) manipulandum = np.random.randint(np.max([target - self.max_distance_to_target, trap - 3]), target - np.max([self.min_distance_to_target, 3])) else: target, trap = offset(360 - 90, 360) manipulandum = np.random.randint(target + np.max([self.min_distance_to_target, 3]), np.min([target + self.max_distance_to_target, trap - 3])) return manipulandum, target, trap def calculate_positions_for_auto_movement(self, current_time, total_time): time_steps_required = (total_time - current_time) / self.dt position_change_required = self.initial_positions_of_visuals[1] - self.positions_of_visuals[0] if time_steps_required > 0: position_step = position_change_required / time_steps_required self.positions_of_visuals[0] = self.positions_of_visuals[0] + position_step return self.positions_of_visuals def calculate_positions_for_levers_movement(self, levers_pressed_time): if np.abs(levers_pressed_time) > 0: self.positions_of_visuals[0] = self.initial_positions_of_visuals[0] + \ self.man_speed * levers_pressed_time/1000 if levers_pressed_time == 0: self.positions_of_visuals[0] = self.initial_positions_of_visuals[0] if self.positions_of_visuals[0] > 360 or self.positions_of_visuals[0] < 0: self.positions_of_visuals[0] = self.positions_of_visuals[0] % 360 if not self.must_lift_at_target: if self.has_man_reached_target(): self.positions_of_visuals[0] = self.positions_of_visuals[1] elif self.has_man_reached_trap(): self.positions_of_visuals[0] = self.positions_of_visuals[2] #print(levers_pressed_time, self.positions_of_visuals[0]) return self.positions_of_visuals def has_man_reached_target(self): man_pos = self.positions_of_visuals[0] target_pos = self.positions_of_visuals[1] if np.abs(target_pos - man_pos) < self.angle_dif_between_man_and_target_trap \ or np.abs(target_pos - man_pos) > 360 - self.angle_dif_between_man_and_target_trap: return True else: return False def has_man_reached_trap(self): man_pos = self.positions_of_visuals[0] trap_pos = self.positions_of_visuals[2] if np.abs(trap_pos - man_pos) < self.angle_dif_between_man_and_target_trap \ or np.abs(trap_pos - man_pos) > 360 - self.angle_dif_between_man_and_target_trap: return True else: return False def back_to_initial_positions(self): self.positions_of_visuals = copy.copy(self.initial_positions_of_visuals)
StarcoderdataPython
312747
<gh_stars>100-1000 # -*- coding: utf-8 -*- import pytest import mock from addons.onedrive import settings from addons.onedrive.client import OneDriveClient from addons.onedrive.tests.utils import (raw_root_folder_response, raw_me_response, raw_user_personal_drive_response, dummy_user_info) def test_headers(): client = OneDriveClient(access_token='<PASSWORD>') assert(client._default_headers == {'Authorization': 'Bearer meowmix'}) def test_folders(): def _quack(method, url, headers, params, expects, throws): if method != 'GET': raise 'failure to match method' if '{}/drives'.format(settings.MSGRAPH_API_URL) not in url: raise 'failure to match url' mock_res = mock.Mock() mock_res.json = mock.Mock(return_value={'value': raw_root_folder_response}) return mock_res client = OneDriveClient(access_token='<PASSWORD>') with mock.patch.object(client, '_make_request', side_effect=_quack): retval = client.folders(drive_id='abcd') assert(retval == raw_root_folder_response) def test_user_info_token(): def _woof(method, url, headers, expects, throws): if method != 'GET': raise 'failure to match method' if url.endswith('/me'): mock_me_res = mock.Mock() mock_me_res.json = mock.Mock(return_value=raw_me_response) return mock_me_res elif url.endswith('/drive'): mock_drive_res = mock.Mock() mock_drive_res.json = mock.Mock(return_value=raw_user_personal_drive_response) return mock_drive_res raise 'failure to match url' client = OneDriveClient(access_token='<PASSWORD>') with mock.patch.object(client, '_make_request', side_effect=_woof): retval = client.user_info() assert(retval == dummy_user_info)
StarcoderdataPython
3215451
<gh_stars>1-10 # This file is part of Indico. # Copyright (C) 2002 - 2020 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from __future__ import unicode_literals from indico.core.settings import AttributeProxyProperty from indico.modules.events.models.reviews import ProposalMixin from indico.modules.events.papers.models.revisions import PaperRevisionState from indico.util.locators import locator_property from indico.util.string import return_ascii class Paper(ProposalMixin): """Proxy class to facilitate access to all paper-related properties.""" proxied_attr = 'contribution' # Proposal mixin properties proposal_type = 'paper' call_for_proposals_attr = 'cfp' revisions_enabled = True def __init__(self, contribution): self.contribution = contribution @return_ascii def __repr__(self): state = self.state.name if self.last_revision else None return '<Paper(contribution_id={}, state={})>'.format(self.contribution.id, state) @locator_property def locator(self): return self.contribution.locator # Contribution-related event = AttributeProxyProperty('event') title = AttributeProxyProperty('title') verbose_title = AttributeProxyProperty('verbose_title') # Paper-related revisions = AttributeProxyProperty('_paper_revisions') last_revision = AttributeProxyProperty('_paper_last_revision') accepted_revision = AttributeProxyProperty('_accepted_paper_revision') revision_count = AttributeProxyProperty('_paper_revision_count') files = AttributeProxyProperty('_paper_files') @property def state(self): return self.last_revision.state @state.setter def state(self, state): self.last_revision.state = state @property def judgment_comment(self): return self.last_revision._judgment_comment @property def is_in_final_state(self): return self.state in {PaperRevisionState.accepted, PaperRevisionState.rejected} def can_comment(self, user, check_state=False): if not user: return False if check_state and self.is_in_final_state: return False return self.can_submit(user) or self.can_judge(user) or self.can_review(user) def can_submit(self, user): return self.contribution.can_submit_proceedings(user) def can_manage(self, user): if not user: return False return self.event.can_manage(user) def can_judge(self, user, check_state=False): if not user: return False elif check_state and self.is_in_final_state: return False elif self.can_manage(user): return True return user in self.contribution.paper_judges def can_review(self, user, check_state=False): if not user: return False elif check_state and self.is_in_final_state: return False elif self.can_manage(user): return True return self.contribution.is_paper_reviewer(user) def get_revisions(self): return self.revisions def get_last_revision(self): return self.last_revision def reset_state(self): self.last_revision.state = PaperRevisionState.submitted self.last_revision.judgment_comment = '' self.last_revision.judge = None self.last_revision.judgment_dt = None
StarcoderdataPython
9739325
""" testing case_class.utils Copyright (c) 2016 <NAME> -- licensed under MIT, see LICENSE """ from unittest import TestCase from case_class import utils class TestUtils(TestCase): """ Tests the Utilities. """ def test_exec_(self): """ Tests that the exec_ function can run code. """ local_vars = { 'x': 1 } local_vars_after = { 'x': 1, 'y': 2 } utils.exec_('y = x + 1', local_vars, local_vars) self.assertEqual(local_vars['x'], local_vars_after['x'], "kept x") self.assertEqual(local_vars['y'], local_vars_after['y'], "set y") def test_is_string(self): """ Tests that the is_string method works properly. """ self.assertTrue(utils.is_string("hello world"), "normal string is a " "string") self.assertTrue(utils.is_string('hello world'), "single char string " "is a string") self.assertTrue(utils.is_string("""A docstring"""), "docstring is a " "string") self.assertFalse(utils.is_string(1), "Number is not a string") self.assertFalse(utils.is_string(dict()), "Dictionary is not a string") def test_is_lambda(self): """ Tests that the is_lambda method works properly. """ class C(object): def __call__(self): return False def f(): return 1 self.assertTrue(utils.is_lambda(lambda q:q), "Lambda function is a " "lambda function") self.assertFalse(utils.is_lambda(f), "Normal function is not a lambda") self.assertFalse(utils.is_lambda(C), "Callable function is not a " "lambda")
StarcoderdataPython
205165
import numpy as np from glob import glob from os.path import join, basename, splitext import open3d as o3d load_dir = '/home/alex/github/waymo_to_kitti_converter/tools/dataloader/one_example' pc_range = [-51.2, -51.2, -3, 51.2, 51.2, 9] test_range = [0, -40, -3.0, 70.4, 40, 3.0] # load_dir = '/home/alex/github/waymo_to_kitti_converter/tools/dataloader/kitti_one_example' # pc_range = [0, -39.68, -3, 69.12, 39.68, 1] # test_range = [0, -40, -3.0, 70.4, 40, 3.0] def corners_to_lines(qs, color=[0,0,0]): """ Draw 3d bounding box in image qs: (8,3) array of vertices for the 3d box in following order: 7 -------- 4 /| /| 6 -------- 5 . | | | | . 3 -------- 0 |/ |/ 2 -------- 1 """ idx = [(1,0), (5,4), (2,3), (6,7), (1,2), (5,6), (0,3), (4,7), (1,5), (0,4), (2,6), (3,7)] cl = [color for i in range(12)] # print('draw bbox') # print('qs', qs) line_set = o3d.geometry.LineSet( points=o3d.utility.Vector3dVector(qs), lines=o3d.utility.Vector2iVector(idx), ) line_set.colors = o3d.utility.Vector3dVector(cl) return line_set def boxes3d_to_corners3d_lidar(x, y, z, w, l, h, ry): """ :param boxes3d: (N, 7) [x, y, z, w, l, h, rz] in LiDAR coords :return: corners3d: (N, 8, 3) 7 -------- 4 /| /| 6 -------- 5 . | | | | . 3 -------- 0 |/ |/ 2 -------- 1 z x |/ y--O """ # due to convention difference, h is for y and w is for x and l is for z # also, box origin at bottom x_corners = np.array([w / 2., -w / 2., -w / 2., w / 2., w / 2., -w / 2., -w / 2., w / 2.]) y_corners = np.array([-l / 2., -l / 2., l / 2., l / 2., -l / 2., -l / 2., l / 2., l / 2.]) z_corners = np.array([0, 0, 0, 0, h, h, h, h]) # x_corners = np.array([l / 2., -l / 2., -l / 2., l / 2., l / 2., -l / 2., -l / 2., l / 2.]) # y_corners = np.array([-w / 2., -w / 2., w / 2., w / 2., -w / 2., -w / 2., w / 2., w / 2.]) # z_corners = np.array([0,0,0,0,h,h,h,h]) corners = np.concatenate((x_corners.reshape(1, 8), y_corners.reshape(1, 8), z_corners.reshape(1, 8)), axis=0) # (3, 8) print('ry\n', ry) # actually Rz, as ry is in ref frame Ry = np.array([[ np.cos(ry), -np.sin(ry), 0], [ np.sin(ry), np.cos(ry), 0], [ 0, 0, 1]]) print('Rot\n', Ry) print('corners', corners.T) rotated_corners = np.matmul(Ry, corners) # (3, 8) print('rotated_corners', rotated_corners.T) rotated_corners += np.array([x, y, z]).reshape(3, 1) print('shifted_corners', rotated_corners.T) return rotated_corners.astype(np.float32) def get_range_box(xmin, ymin, zmin, xmax, ymax, zmax): """ :param boxes3d: (N, 7) [x, y, z, w, l, h, rz] in LiDAR/Vehicle coords :return: corners3d: (N, 8, 3) 7 -------- 4 /| /| 6 -------- 5 . | | | | . 3 -------- 0 |/ |/ 2 -------- 1 z x |/ y--O """ x_corners = np.array([xmax, xmin, xmin, xmax, xmax, xmin, xmin, xmax]) y_corners = np.array([ymin, ymin, ymax, ymax, ymin, ymin, ymax, ymax]) z_corners = np.array([zmin, zmin, zmin, zmin, zmax, zmax, zmax, zmax]) corners = np.concatenate((x_corners.reshape(1, 8), y_corners.reshape(1, 8), z_corners.reshape(1, 8)), axis=0) # (3, 8) return corners.astype(np.float32) def main(): all_content = {} all_bin_pathnames = glob(join(load_dir, '*.bin')) for bin_pathname in all_bin_pathnames: stem, _ = splitext(basename(bin_pathname)) splits = stem.split('-') k, d = splits[0], splits[1] if d == 'object': continue shape = splits[2:] shape = tuple([int(s) for s in shape]) all_content[k] = np.fromfile(bin_pathname, dtype=d).reshape(shape) print(k, all_content[k].shape) print(all_content['points']) point_cloud = all_content['points'][:, 1:4] # (N, 3) TODO: what??? idx 1:4 bboxes = all_content['gt_boxes'][0] # (N, 8), 7 param + type print(all_content['gt_boxes']) print('==============') print(all_content['sample_idx']) # test point cloud full_pc_pathname = glob(join(load_dir, 'full_pc/*.bin'))[0] full_pc = np.fromfile(full_pc_pathname, dtype=np.float32).reshape(-1, 4) full_pcd = o3d.geometry.PointCloud() full_pcd.points = o3d.utility.Vector3dVector(full_pc[:, :3]) full_pcd.paint_uniform_color([0, 0, 0]) bboxes_corners = [] for i in range(bboxes.shape[0]): x, y, z, w, l, h, ry, t = bboxes[i].tolist() # lidar coord: wlh print(x,y,z,w,l,h,ry,t) bbox_corners = boxes3d_to_corners3d_lidar(x, y, z, w, l, h, ry) # lidar coord bboxes_corners.append(bbox_corners) pcd = o3d.geometry.PointCloud() pcd.points = o3d.utility.Vector3dVector(point_cloud) voxels = o3d.geometry.PointCloud() voxels.points = o3d.utility.Vector3dVector(all_content['voxel_centers']) voxels.paint_uniform_color([1, 0, 0]) pc_range_box = get_range_box(*pc_range) pc_range_box_lines = corners_to_lines(pc_range_box.T.tolist(), color=[1,0,0]) test_range_box = get_range_box(*test_range) test_range_box_lines = corners_to_lines(test_range_box.T.tolist()) voxel_box = get_range_box(0,0,-3,0.16,0.16,1) voxel_box_lines = corners_to_lines(voxel_box.T.tolist()) axis = o3d.geometry.TriangleMesh.create_coordinate_frame( size=1, origin=[0, 0, 0]) # visual = [full_pcd, pcd, voxels, axis, pc_range_box_lines, test_range_box_lines, voxel_box_lines] visual = [pcd, voxels, axis, pc_range_box_lines, test_range_box_lines, voxel_box_lines] # visual = [pcd, axis, pc_range_box_lines, test_range_box_lines, voxel_box_lines] for bbox3d in bboxes_corners: bbox3d = bbox3d.T.tolist() # (8, 3) # print(bbox3d) visual.append(corners_to_lines(bbox3d, color=[0, 0, 1])) o3d.visualization.draw_geometries(visual) # print(all_content) if __name__ == '__main__': main()
StarcoderdataPython
379387
# Tabela verdade do operador not x = True y = False print(not x) print(not y) # Tabela verdade do operador and (e)(apenas true e true da true) x = True y = False print(x and y) # Tabela verdade do operador or (ou) (apenas false ou false da false)(o resto da true) x = True y = False print(x or y) # exemplo 1 not x = 10 y = 1 res = not x > y print(res) # exemplo 2 and x = 10 y = 1 z = 5.5 res = x > y and z == y print(res) # exemplo 3 or x = 10 y = 1 z = 5.5 res = x > y or z == y print (res) # exemplo 4 todos juntos x = 10 y = 1 z = 5.5 res = x > y or not z == y and y != y + z / x print(res) # exemplo 5
StarcoderdataPython
1898569
def plaindrome(phrase): return phrase==phrase[::-1] print(plaindrome("anna"))
StarcoderdataPython
5112574
<gh_stars>0 import mechanize, urllib2 from bs4 import BeautifulSoup url = "http://foodscores.state.al.us/(S(bcxxpt55pb2zrt45ki3yef55))/Default.aspx" def prep(): br = mechanize.Browser() br.set_handle_robots(False) br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')] br.open(url) br.select_form(nr=0) return br def find_counties_types(): br = prep() type_control = br.form.find_control(name="ctl00$ContentPlaceHolder1$DrpEstdType") county_control = br.form.find_control(name="ctl00$ContentPlaceHolder1$DrpCnty") counties = {} for county in county_control.items: if not county.attrs.has_key('selected'): counties[ county.attrs['contents'] ] = county.attrs['value'] types = {} for typ in type_control.items: if not typ.attrs.has_key('selected'): types[ typ.attrs['contents'] ] = typ.attrs['value'] return (types, counties) def parse_entry(tr): spans = tr.find_all("span") data = [] for s in spans: data.append(s.text) links = tr.find_all("a", target="_blank") for a in links: data.append(a.text) return (data, tr.find_next_sibling()) def parse_entries(tr): data = [] while tr != None: (dd, tr) = parse_entry(tr) data.append(dd) return data def get_establishments( county, estab_type ): br = prep() type_control = br.form.find_control(name="ctl00$ContentPlaceHolder1$DrpEstdType") county_control = br.form.find_control(name="ctl00$ContentPlaceHolder1$DrpCnty") br.form.set(True, county, county_control.name) br.form.set(True, estab_type, type_control.name) resp = br.submit() soup = BeautifulSoup(resp) tt = soup.find(id="ctl00_ContentPlaceHolder1_DtList") if tt is None: return None else: return parse_entries(tt.find("tr")) if __name__=="__main__": (tt, cc) = find_counties_types() for (k,v) in tt.iteritems(): print v data = get_establishments(cc['MADISON'], v) if data is None: continue f = open('MADISON/' + v + '.tsv', 'w') f.write('\t'.join([ "Name", "City", "Zip", "Score", "Non-Smoking", "Date", "Street"])) f.write('\n') for d in data: zip_code = d[2].strip('-') if len(zip_code) == 0: zip_code = 'NULL' f.write('\t'.join([ d[0].encode("utf8"), d[1].encode("utf8"), str(zip_code), str(int(d[3])), d[4].encode("utf8"), d[5].encode("utf8"), d[6].encode("utf8")])) f.write('\n')
StarcoderdataPython
1715458
<reponame>gyger/PICwriter #!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Default MPB launch-file for computing electromagnetic modes of arbitrary PICwriter waveguides. MCM = "MPB Compute Mode" Launches a MPB simulation to compute the electromagnetic mode profile for a given waveguide template and material stack. @author: dkita """ from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np import meep as mp from meep import mpb import h5py import argparse import matplotlib.pyplot as plt import os def str2bool(v): """ Allow proper argparse handling of boolean inputs """ if v.lower() in ("yes", "true", "True", "t", "y", "1"): return True elif v.lower() in ("no", "false", "False", "f", "n", "0"): return False else: raise argparse.ArgumentTypeError("Boolean value expected.") def main(args): """ Args: * **res** (int): Resolution of the simulation [pixels/um] (default=10) * **wavelength** (float): Wavelength in microns (default=1.55) * **sx** (float): Size of the simulation region in the x-direction (default=4.0) * **sy** (float): Size of the simulation region in the y-direction (default=4.0) * **plot_mode_number** (int): Which mode to plot (only plots one mode at a time). Must be a number equal to or less than num_mode (default=1) * **polarization** (string): If true, outputs the fields at the relevant waveguide cross-sections (top-down and side-view) * **epsilon_file** (string): Filename with the dielectric "block" objects (default=None) * **output_directory** (string): If true, outputs the fields at the relevant waveguide cross-sections (top-down and side-view) * **save_mode_data** (boolean): Save the mode image and data to a separate file (default=None) * **suppress_window** (boolean): Suppress the matplotlib window (default=False) """ # Boolean inputs save_mode_data = args.save_mode_data suppress_window = args.suppress_window # String inputs polarization = args.polarization epsilon_file = args.epsilon_file output_directory = args.output_directory if not os.path.exists(output_directory): os.makedirs(output_directory) # Int inputs res = args.res # num_modes = args.num_modes plot_mode_number = args.plot_mode_number # Float inputs wavelength = args.wavelength sx = args.sx sy = args.sy geometry_lattice = mp.Lattice(size=mp.Vector3(0, sy, sx)) with h5py.File(epsilon_file, "r") as hf: data = np.array( [ np.array(hf.get("CX")), np.array(hf.get("CY")), np.array(hf.get("width_list")), np.array(hf.get("height_list")), np.array(hf.get("eps_list")), ] ) geometry = [] for i in range(len(data[0])): geometry.append( mp.Block( size=mp.Vector3(mp.inf, data[3][i], data[2][i]), center=mp.Vector3(0, data[1][i], data[0][i]), material=mp.Medium(epsilon=data[4][i]), ) ) ms = mpb.ModeSolver( geometry_lattice=geometry_lattice, geometry=geometry, resolution=res, default_material=mp.Medium(epsilon=1.0), num_bands=plot_mode_number, ) freq = 1 / wavelength kdir = mp.Vector3(1, 0, 0) tol = 1e-6 kmag_guess = freq * 2.02 kmag_min = freq * 0.01 kmag_max = freq * 10.0 if polarization == "TE": parity = mp.ODD_Z elif polarization == "TM": parity = mp.EVEN_Z elif polarization == "None": parity = mp.NO_PARITY k = ms.find_k( parity, freq, plot_mode_number, plot_mode_number, kdir, tol, kmag_guess, kmag_min, kmag_max, ) vg = ms.compute_group_velocities() print("k=" + str(k)) print("v_g=" + str(vg)) k = k[0] vg = vg[0][0] """ Plot modes """ eps = ms.get_epsilon() ms.get_dfield(plot_mode_number) E = ms.get_efield(plot_mode_number) Eabs = np.sqrt( np.multiply(E[:, :, 0, 2], E[:, :, 0, 2]) + np.multiply(E[:, :, 0, 1], E[:, :, 0, 1]) + np.multiply(E[:, :, 0, 0], E[:, :, 0, 0]) ) H = ms.get_hfield(plot_mode_number) Habs = np.sqrt( np.multiply(H[:, :, 0, 2], H[:, :, 0, 2]) + np.multiply(H[:, :, 0, 1], H[:, :, 0, 1]) + np.multiply(H[:, :, 0, 0], H[:, :, 0, 0]) ) plt_extent = [-sy / 2.0, +sy / 2.0, -sx / 2.0, +sx / 2.0] cmap_fields = "hot_r" cmap_geom = "viridis" if not suppress_window: """ First plot electric field """ plt.figure(figsize=(14, 8)) plt.subplot(2, 3, 1) plt.imshow( abs(E[:, :, 0, 2]), cmap=cmap_fields, origin="lower", aspect="auto", extent=plt_extent, ) plt.title("Waveguide mode $|E_x|$") plt.ylabel("y-axis") plt.xlabel("x-axis") plt.colorbar() plt.subplot(2, 3, 2) plt.imshow( abs(E[:, :, 0, 1]), cmap=cmap_fields, origin="lower", aspect="auto", extent=plt_extent, ) plt.title("Waveguide mode $|E_y|$") plt.ylabel("y-axis") plt.xlabel("x-axis") plt.colorbar() plt.subplot(2, 3, 3) plt.imshow( abs(E[:, :, 0, 0]), cmap=cmap_fields, origin="lower", aspect="auto", extent=plt_extent, ) plt.title("Waveguide mode $|E_z|$") plt.ylabel("y-axis") plt.xlabel("x-axis") plt.colorbar() plt.subplot(2, 3, 4) plt.imshow( abs(Eabs), cmap=cmap_fields, origin="lower", aspect="auto", extent=plt_extent, ) plt.title("Waveguide mode $|E|$") plt.ylabel("y-axis") plt.xlabel("x-axis") plt.colorbar() plt.subplot(2, 3, 5) plt.imshow( eps, cmap=cmap_geom, origin="lower", aspect="auto", extent=plt_extent ) plt.title("Waveguide dielectric") plt.ylabel("y-axis") plt.xlabel("x-axis") plt.colorbar() plt.tight_layout() plt.show() """ Then plot magnetic field """ plt.figure(figsize=(14, 8)) plt.subplot(2, 3, 1) plt.imshow( abs(H[:, :, 0, 2]), cmap=cmap_fields, origin="lower", aspect="auto", extent=plt_extent, ) plt.title("Waveguide mode $|H_x|$") plt.ylabel("y-axis") plt.xlabel("x-axis") plt.colorbar() plt.subplot(2, 3, 2) plt.imshow( abs(H[:, :, 0, 1]), cmap=cmap_fields, origin="lower", aspect="auto", extent=plt_extent, ) plt.title("Waveguide mode $|H_y|$") plt.ylabel("y-axis") plt.xlabel("x-axis") plt.colorbar() plt.subplot(2, 3, 3) plt.imshow( abs(H[:, :, 0, 0]), cmap=cmap_fields, origin="lower", aspect="auto", extent=plt_extent, ) plt.title("Waveguide mode $|H_z|$") plt.ylabel("y-axis") plt.xlabel("x-axis") plt.colorbar() plt.subplot(2, 3, 4) plt.imshow( abs(Habs), cmap=cmap_fields, origin="lower", aspect="auto", extent=plt_extent, ) plt.title("Waveguide mode $|H|$") plt.ylabel("y-axis") plt.xlabel("x-axis") plt.colorbar() plt.subplot(2, 3, 5) plt.imshow( eps, cmap=cmap_geom, origin="lower", aspect="auto", extent=plt_extent ) plt.title("Waveguide dielectric") plt.ylabel("y-axis") plt.xlabel("x-axis") plt.colorbar() plt.tight_layout() plt.show() if save_mode_data: """ First plot electric field """ plt.figure(figsize=(14, 8)) plt.subplot(2, 3, 1) plt.imshow( abs(E[:, :, 0, 2]), cmap=cmap_fields, origin="lower", aspect="auto", extent=plt_extent, ) plt.title("Waveguide mode $|E_x|$") plt.ylabel("y-axis") plt.xlabel("x-axis") plt.colorbar() plt.subplot(2, 3, 2) plt.imshow( abs(E[:, :, 0, 1]), cmap=cmap_fields, origin="lower", aspect="auto", extent=plt_extent, ) plt.title("Waveguide mode $|E_y|$") plt.ylabel("y-axis") plt.xlabel("x-axis") plt.colorbar() plt.subplot(2, 3, 3) plt.imshow( abs(E[:, :, 0, 0]), cmap=cmap_fields, origin="lower", aspect="auto", extent=plt_extent, ) plt.title("Waveguide mode $|E_z|$") plt.ylabel("y-axis") plt.xlabel("x-axis") plt.colorbar() plt.subplot(2, 3, 4) plt.imshow( abs(Eabs), cmap=cmap_fields, origin="lower", aspect="auto", extent=plt_extent, ) plt.title("Waveguide mode $|E|$") plt.ylabel("y-axis") plt.xlabel("x-axis") plt.colorbar() plt.subplot(2, 3, 5) plt.imshow( eps, cmap=cmap_geom, origin="lower", aspect="auto", extent=plt_extent ) plt.title("Waveguide dielectric") plt.ylabel("y-axis") plt.xlabel("x-axis") plt.colorbar() plt.tight_layout() if polarization == "TE": savetxt = "%s/TE_mode%d_Efield.png" % (output_directory, plot_mode_number) elif polarization == "TM": savetxt = "%s/TM_mode%d_Efield.png" % (output_directory, plot_mode_number) elif polarization == "None": savetxt = "%s/mode%d_Efield.png" % (output_directory, plot_mode_number) plt.savefig(savetxt) """ Then plot magnetic field """ plt.figure(figsize=(14, 8)) plt.subplot(2, 3, 1) plt.imshow( abs(H[:, :, 0, 2]), cmap=cmap_fields, origin="lower", aspect="auto", extent=plt_extent, ) plt.title("Waveguide mode $|H_x|$") plt.ylabel("y-axis") plt.xlabel("x-axis") plt.colorbar() plt.subplot(2, 3, 2) plt.imshow( abs(H[:, :, 0, 1]), cmap=cmap_fields, origin="lower", aspect="auto", extent=plt_extent, ) plt.title("Waveguide mode $|H_y|$") plt.ylabel("y-axis") plt.xlabel("x-axis") plt.colorbar() plt.subplot(2, 3, 3) plt.imshow( abs(H[:, :, 0, 0]), cmap=cmap_fields, origin="lower", aspect="auto", extent=plt_extent, ) plt.title("Waveguide mode $|H_z|$") plt.ylabel("y-axis") plt.xlabel("x-axis") plt.colorbar() plt.subplot(2, 3, 4) plt.imshow( abs(Habs), cmap=cmap_fields, origin="lower", aspect="auto", extent=plt_extent, ) plt.title("Waveguide mode $|H|$") plt.ylabel("y-axis") plt.xlabel("x-axis") plt.colorbar() plt.subplot(2, 3, 5) plt.imshow( eps, cmap=cmap_geom, origin="lower", aspect="auto", extent=plt_extent ) plt.title("Waveguide dielectric") plt.ylabel("y-axis") plt.xlabel("x-axis") plt.colorbar() plt.tight_layout() if polarization == "TE": savetxt = "%s/TE_mode%d_Hfield.png" % (output_directory, plot_mode_number) elif polarization == "TM": savetxt = "%s/TM_mode%d_Hfield.png" % (output_directory, plot_mode_number) elif polarization == "None": savetxt = "%s/mode%d_Hfield.png" % (output_directory, plot_mode_number) plt.savefig(savetxt) """ Save the mode data to a .txt file """ if polarization == "TE": datafilename = "%s/TE_mode%d_data.txt" % ( output_directory, plot_mode_number, ) elif polarization == "TM": datafilename = "%s/TM_mode%d_data.txt" % ( output_directory, plot_mode_number, ) elif polarization == "None": datafilename = "%s/mode%d_data.txt" % (output_directory, plot_mode_number) f = open(datafilename, "w") f.write("#################################################################\n") f.write("Mode %d with %s polarization \n" % (plot_mode_number, polarization)) f.write("#################################################################\n") f.write("\n") f.write("k \t\t %0.6f \n" % (k)) f.write("n_eff \t\t %0.6f \n" % (wavelength * k)) f.write("vg \t\t %0.6f \n" % (vg)) f.write("ng \t\t %0.6f \n" % (1 / vg)) if __name__ == "__main__": """ Args: * **res** (int): Resolution of the simulation [pixels/um] (default=10) * **wavelength** (float): Wavelength in microns (default=1.55) * **sx** (float): Size of the simulation region in the x-direction (default=4.0) * **sy** (float): Size of the simulation region in the y-direction (default=4.0) * **plot_mode_number** (int): Which mode to plot (only plots one mode at a time). Must be a number equal to or less than num_mode (default=1) * **polarization** (string): If true, outputs the fields at the relevant waveguide cross-sections (top-down and side-view) * **epsilon_file** (string): Filename with the dielectric "block" objects (default=None) * **output_directory** (string): If true, outputs the fields at the relevant waveguide cross-sections (top-down and side-view) * **save_mode_data** (boolean): Save the mode image and data to a separate file (default=None) * **suppress_window** (boolean): Suppress the matplotlib window (default=False) """ parser = argparse.ArgumentParser() parser.add_argument( "-res", type=int, default=10, help="Resolution of the simulation [pixels/um] (default=10)", ) parser.add_argument( "-wavelength", type=float, default=1.55, help="Wavelength in microns (default=1.55)", ) parser.add_argument( "-sx", type=float, default=4.0, help="Size of the simulation region in the x-direction (default=4.0)", ) parser.add_argument( "-sy", type=float, default=4.0, help="Size of the simulation region in the y-direction (default=4.0)", ) # parser.add_argument('-num_modes', type=int, default=1, help='Number of modes to compute (defaults=1)') parser.add_argument( "-plot_mode_number", type=int, default=1, help="Which mode to plot (only plots one mode at a time). Must be a number equal to or less than num_mode (default=1)", ) parser.add_argument( "-polarization", type=str, default=None, help="Name of the output directory (for storing the fields) (default=None)", ) parser.add_argument( "-epsilon_file", type=str, default=None, help='Filename with the dielectric "block" objects (default=None)', ) parser.add_argument( "-output_directory", type=str, default=None, help="Name of the output directory (for storing the fields) (default=None)", ) parser.add_argument( "-save_mode_data", type=str2bool, nargs="?", const=True, default=True, help="Save the mode image and data to a separate file (default=True)", ) parser.add_argument( "-suppress_window", type=str2bool, nargs="?", const=True, default=False, help="Suppress the matplotlib window (default=False)", ) args = parser.parse_args() main(args)
StarcoderdataPython
6481907
<filename>mil/metrics/manager.py from mil.metrics import * from mil.errors.custom_exceptions import ExpectedListError from mil.errors.custom_warnings import invalid_metric_string class MetricsManager: def __init__(self, metrics=[]): self.check_exceptions(metrics) self.import_metrics(metrics) def check_exceptions(self, metrics): if type(metrics) != list: raise ExpectedListError def import_metrics(self, metrics_): metrics = metrics_.copy() self.metrics = {} # Complete all list of possible imports if 'acc' in metrics: metrics.remove('acc') self.metrics['accuracy'] = Accuracy() if 'spec' in metrics: metrics.remove('spec') self.metrics['specificity'] = Specificity() if 'sens' in metrics: metrics.remove('sens') self.metrics['sensibility'] = Sensibility() if 'ppv' in metrics: metrics.remove('ppv') self.metrics['ppv'] = PPV() if 'npv' in metrics: metrics.remove('npv') self.metrics['npv'] = NPV() # Adding non string metrics for m in metrics: if type(m) == str: invalid_metric_string() elif str(type(m)).split('.')[0].split("'")[-1] == 'mil': self.metrics[type(m).__name__.lower()] = m() else: self.metrics[m.__name__.lower()] = m() def update_state(self, y_true, y_pred, sample_weight=None): for key in self.metrics: self.metrics[key].update_state(y_true, y_pred, sample_weight) def result(self): result = {} for key in self.metrics: result[key] = self.metrics[key].result().numpy() return result def reset_states(self): for key in self.metrics: self.metrics[key].reset_states()
StarcoderdataPython
4802688
""" SALTS XBMC Addon Copyright (C) 2014 tknorris This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import scraper import urllib import urlparse import re import xbmcaddon from salts_lib.constants import VIDEO_TYPES from salts_lib.constants import QUALITIES BASE_URL = 'https://movieshd.eu' class MoviesHD_Scraper(scraper.Scraper): base_url = BASE_URL def __init__(self, timeout=scraper.DEFAULT_TIMEOUT): self.timeout = timeout self.base_url = xbmcaddon.Addon().getSetting('%s-base_url' % (self.get_name())) @classmethod def provides(cls): return frozenset([VIDEO_TYPES.MOVIE]) @classmethod def get_name(cls): return 'MoviesHD' def resolve_link(self, link): if 'videomega' in link: html = self._http_get(link, cache_limit=.5) match = re.search('ref="([^"]+)', html) if match: return 'http://videomega.tv/iframe.php?ref=%s' % (match.group(1)) else: return link def format_source_label(self, item): return '[%s] %s' % (item['quality'], item['host']) def get_sources(self, video): source_url = self.get_url(video) hosters = [] if source_url: url = urlparse.urljoin(self.base_url, source_url) html = self._http_get(url, cache_limit=.5) match = re.search("(?:'|\")([^'\"]+hashkey=[^'\"]+)", html) stream_url = '' if match: stream_url = match.group(1) if stream_url.startswith('//'): stream_url = 'http:' + stream_url host = 'videomega.tv' else: match = re.search('iframe[^>]*src="([^"]+)', html) if match: stream_url = match.group(1) host = urlparse.urlparse(stream_url).hostname if stream_url: hoster = {'multi-part': False, 'url': stream_url, 'host': host, 'class': self, 'quality': QUALITIES.HD720, 'views': None, 'rating': None, 'up': None, 'down': None, 'direct': False} hosters.append(hoster) return hosters def get_url(self, video): return super(MoviesHD_Scraper, self)._default_get_url(video) def search(self, video_type, title, year): search_url = urlparse.urljoin(self.base_url, '/?s=') search_url += urllib.quote_plus(title) html = self._http_get(search_url, cache_limit=.25) results = [] if not re.search('nothing matched your search criteria', html, re.I): pattern = 'href="([^"]+)"\s+title="([^"]+)\s+\((\d{4})\)' for match in re.finditer(pattern, html): url, title, match_year = match.groups('') if not year or not match_year or year == match_year: result = {'url': url.replace(self.base_url, ''), 'title': title, 'year': match_year} results.append(result) return results def _http_get(self, url, cache_limit=8): return super(MoviesHD_Scraper, self)._cached_http_get(url, self.base_url, self.timeout, cache_limit=cache_limit)
StarcoderdataPython
5131714
<gh_stars>0 # -*- coding: utf-8 -*- print "test" #中文注释 print u"为了巩固记忆,手打代码,不要偷懒(也不怎么费时间吧\n" #ex1~ex4 省略了 #ex5 格式化字符 # my_name = 'Zed' # my_age = 35;my_height = 74;my_weight = 180 # my_eyes = 'blue' # my_teeth = 'white' # my_hair = 'brown' # print "let's talk about %s \nHe's %d inches tall" %(my_name,my_height) # print "if i add %d, %d and %d, I get %d" %(my_age, my_height, my_weight, my_age + my_height + my_weight) #ex6 # x = "there are %d types of people" %(10+1) # binary = "binary" # do_not = "don't" # y = "Those who know %s and those who %s." %(binary, do_not) #%s后面可以直接接字符 # print x # print y # print "I said : %r." %x # print "I also said : %s." %y # hilarious = False # joke_evaluation = "Isn't that joke so funny?! %s" # print joke_evaluation %hilarious # w = "Left" ; e = "Right" # print w + " " + e #ex7 # print "\n" # print "." *10 # end1 = "C"; end2 = "h"; end3 = "e" # end4 = "e"; end5 = "s"; end6 = "e" # print end1 + end2 + end3, # print end4 + end5 + end6 #ex8 # formatter = "%s %r %r %r" # print formatter %(1,2,3,4) # print formatter %(u"一", "two\n", "three", "four") # print formatter %(True, False, False, True) # print formatter %( # "I had this thing", # "That you could type up right", # "But it didn't sing", # "So i said goodnight.") #ex10 # print " " # print "\' \" \r dfe" # print "abc" #ex11 print "This is an example:", a= raw_input("input a:") print type(a) print "a is %s" %a
StarcoderdataPython
4982864
<filename>bin/macro_gen.py #!/bin/python from os import path, walk import sys import argparse import yaml import re import json def macro_gen(STRONTIC_PATH, REPO_PATH, VERBOSE): macros = [] macro = dict() with open(STRONTIC_PATH, 'r', encoding='utf-8-sig') as file: strontic_objects = json.load(file,strict=False) for process_object, values in strontic_objects.items(): if 'meta_original_filename' in values: # make macro object macro['definition'] = 'Processes.process_name=' + process_object.split("-")[0] + ' OR Processes.original_file_name=' + values['meta_original_filename'] macro['description'] = "matches the process with its original file name, data for this macro came from: https://strontic.github.io/" macro['name'] = process_object.split("-")[0].lower().replace(".", "_") macros.append(macro) if VERBOSE: print("generating macro: {0} with definition: {1}".format(macro['name'], macro['definition'])) #final_macros = [] # check for duplicate first #for macro in macros: # if macro not in final_macros: # final_macros.append(macro) #else: # extended_definition = ' OR Processes.process_name=' + process_object.split("-")[0] + ' OR Processes.original_file_name=' + values['meta_original_filename'] # macro['definition'] = macro['definition'] + extended_definition #print(macro['definition']) #print(macros) return len(macros) def main(args): parser = argparse.ArgumentParser(description="keeps yamls in security_content sorted and pretty printed with custom sort keys, \ meant to run quitely for CI, use -v flag to make it bark") parser.add_argument("-s", "--strontic_json", required=True, help="path to strontic json") parser.add_argument("-p", "--path", required=True, help="path to security_content repo") parser.add_argument("-v", "--verbose", required=False, default=False, action='store_true', help="prints verbose output") # parse them args = parser.parse_args() STRONTIC_PATH = args.strontic_json REPO_PATH = args.path VERBOSE = args.verbose generated_count = macro_gen(STRONTIC_PATH, REPO_PATH, VERBOSE) #if VERBOSE: print("generated {0} macros from strontics list".format(generated_count)) print("finished successfully!") if __name__ == "__main__": main(sys.argv[1:])
StarcoderdataPython
3127
from __future__ import absolute_import import unittest from testutils import ADMIN_CLIENT from testutils import TEARDOWN from library.user import User from library.project import Project from library.repository import Repository from library.repository import pull_harbor_image from library.repository import push_image_to_project from testutils import harbor_server from library.base import _assert_status_code class TestProjects(unittest.TestCase): @classmethod def setUp(self): self.project = Project() self.user = User() self.repo = Repository() @classmethod def tearDown(self): print "Case completed" @unittest.skipIf(TEARDOWN == False, "Test data won't be erased.") def test_ClearData(self): #1. Delete repository(RA) by user(UA); self.repo.delete_repoitory(TestProjects.project_ra_name_a, TestProjects.repo_name_in_project_a.split('/')[1], **TestProjects.USER_RA_CLIENT) self.repo.delete_repoitory(TestProjects.project_ra_name_b, TestProjects.repo_name_in_project_b.split('/')[1], **TestProjects.USER_RA_CLIENT) self.repo.delete_repoitory(TestProjects.project_ra_name_c, TestProjects.repo_name_in_project_c.split('/')[1], **TestProjects.USER_RA_CLIENT) self.repo.delete_repoitory(TestProjects.project_ra_name_a, TestProjects.repo_name_pa.split('/')[1], **TestProjects.USER_RA_CLIENT) #2. Delete project(PA); self.project.delete_project(TestProjects.project_ra_id_a, **TestProjects.USER_RA_CLIENT) self.project.delete_project(TestProjects.project_ra_id_b, **TestProjects.USER_RA_CLIENT) self.project.delete_project(TestProjects.project_ra_id_c, **TestProjects.USER_RA_CLIENT) #3. Delete user(UA). self.user.delete_user(TestProjects.user_ra_id, **ADMIN_CLIENT) def testRobotAccount(self): """ Test case: Robot Account Test step and expected result: 1. Create user(UA); 2. Create private project(PA), private project(PB) and public project(PC) by user(UA); 3. Push image(ImagePA) to project(PA), image(ImagePB) to project(PB) and image(ImagePC) to project(PC) by user(UA); 4. Create a new robot account(RA) with pull and push privilige in project(PA) by user(UA); 5. Check robot account info, it should has both pull and push priviliges; 6. Pull image(ImagePA) from project(PA) by robot account(RA), it must be successful; 7. Push image(ImageRA) to project(PA) by robot account(RA), it must be successful; 8. Push image(ImageRA) to project(PB) by robot account(RA), it must be not successful; 9. Pull image(ImagePB) from project(PB) by robot account(RA), it must be not successful; 10. Pull image from project(PC), it must be successful; 11. Push image(ImageRA) to project(PC) by robot account(RA), it must be not successful; 12. Update action property of robot account(RA); 13. Pull image(ImagePA) from project(PA) by robot account(RA), it must be not successful; 14. Push image(ImageRA) to project(PA) by robot account(RA), it must be not successful; 15. Delete robot account(RA), it must be not successful. Tear down: 1. Delete repository(RA) by user(UA); 2. Delete project(PA); 3. Delete user(UA). """ url = ADMIN_CLIENT["endpoint"] admin_name = ADMIN_CLIENT["username"] admin_password = ADMIN_CLIENT["password"] user_ra_password = "<PASSWORD>" image_project_a = "haproxy" image_project_b = "hello-world" image_project_c = "httpd" image_robot_account = "alpine" tag = "latest" print "#1. Create user(UA);" TestProjects.user_ra_id, user_ra_name = self.user.create_user(user_password = <PASSWORD>, **ADMIN_CLIENT) TestProjects.USER_RA_CLIENT=dict(endpoint = url, username = user_ra_name, password = <PASSWORD>) print "#2. Create private project(PA), private project(PB) and public project(PC) by user(UA);" TestProjects.project_ra_id_a, TestProjects.project_ra_name_a = self.project.create_project(metadata = {"public": "false"}, **TestProjects.USER_RA_CLIENT) TestProjects.project_ra_id_b, TestProjects.project_ra_name_b = self.project.create_project(metadata = {"public": "false"}, **TestProjects.USER_RA_CLIENT) TestProjects.project_ra_id_c, TestProjects.project_ra_name_c = self.project.create_project(metadata = {"public": "true"}, **TestProjects.USER_RA_CLIENT) print "#3. Push image(ImagePA) to project(PA), image(ImagePB) to project(PB) and image(ImagePC) to project(PC) by user(UA);" TestProjects.repo_name_in_project_a, tag_a = push_image_to_project(TestProjects.project_ra_name_a, harbor_server, user_ra_name, user_ra_password, image_project_a, tag) TestProjects.repo_name_in_project_b, tag_b = push_image_to_project(TestProjects.project_ra_name_b, harbor_server, user_ra_name, user_ra_password, image_project_b, tag) TestProjects.repo_name_in_project_c, tag_c = push_image_to_project(TestProjects.project_ra_name_c, harbor_server, user_ra_name, user_ra_password, image_project_c, tag) print "#4. Create a new robot account(RA) with pull and push privilige in project(PA) by user(UA);" robot_id, robot_account = self.project.add_project_robot_account(TestProjects.project_ra_id_a, TestProjects.project_ra_name_a, 2441000531 ,**TestProjects.USER_RA_CLIENT) print robot_account.name print robot_account.token print "#5. Check robot account info, it should has both pull and push priviliges;" data = self.project.get_project_robot_account_by_id(TestProjects.project_ra_id_a, robot_id, **TestProjects.USER_RA_CLIENT) _assert_status_code(robot_account.name, data.name) print "#6. Pull image(ImagePA) from project(PA) by robot account(RA), it must be successful;" pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_a, tag_a) print "#7. Push image(ImageRA) to project(PA) by robot account(RA), it must be successful;" TestProjects.repo_name_pa, _ = push_image_to_project(TestProjects.project_ra_name_a, harbor_server, robot_account.name, robot_account.token, image_robot_account, tag) print "#8. Push image(ImageRA) to project(PB) by robot account(RA), it must be not successful;" push_image_to_project(TestProjects.project_ra_name_b, harbor_server, robot_account.name, robot_account.token, image_robot_account, tag, expected_error_message = "unauthorized to access repository") print "#9. Pull image(ImagePB) from project(PB) by robot account(RA), it must be not successful;" pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_b, tag_b, expected_error_message = "unauthorized to access repository") print "#10. Pull image from project(PC), it must be successful;" pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_c, tag_c) print "#11. Push image(ImageRA) to project(PC) by robot account(RA), it must be not successful;" push_image_to_project(TestProjects.project_ra_name_c, harbor_server, robot_account.name, robot_account.token, image_robot_account, tag, expected_error_message = "unauthorized to access repository") print "#12. Update action property of robot account(RA);" self.project.disable_project_robot_account(TestProjects.project_ra_id_a, robot_id, True, **TestProjects.USER_RA_CLIENT) print "#13. Pull image(ImagePA) from project(PA) by robot account(RA), it must be not successful;" pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_a, tag_a, expected_login_error_message = "unauthorized: authentication required") print "#14. Push image(ImageRA) to project(PA) by robot account(RA), it must be not successful;" push_image_to_project(TestProjects.project_ra_name_a, harbor_server, robot_account.name, robot_account.token, image_robot_account, tag, expected_login_error_message = "unauthorized: authentication required") print "#15. Delete robot account(RA), it must be not successful." self.project.delete_project_robot_account(TestProjects.project_ra_id_a, robot_id, **TestProjects.USER_RA_CLIENT) if __name__ == '__main__': unittest.main()
StarcoderdataPython
4909291
<reponame>jhconning/DevII<gh_stars>10-100 import numpy as np import matplotlib.pyplot as plt from scipy.optimize import fsolve Pc = 4 Pw = 8 c = 1/2 d = 1/2 def F(x,P=Pc,c=c): '''Cattle Profit Function''' return P*x - c*x**2 def AG(x, P=Pw): '''Wheat farm profit before crop damage''' return P*(x**0) # to return an array of len(x) def AGD(x,P=Pw,d=d): '''Wheat farm profit after damage''' return AG(x,P) - d*x**2 def copt(P=Pc,c=c): '''rancher private optimum''' return P/(2*c) def topt(P=Pc,c=c, d=d): '''Social effient optimum''' return P/(2*(c+d)) CE, TE = copt(),topt() def coaseplot1(): xx = np.linspace(0,6,100) fig = plt.subplots(figsize=(12,8)) plt.plot(xx, F(xx), label = 'Rancher Profit' ) plt.plot(xx, AG(xx), '--', label = 'Farm w/ no cattle damage' ) plt.plot(xx, AGD(xx), label = 'Farm w/ cattle damage') plt.plot(xx, F(xx) + AGD(xx),label='Sum of both activities') plt.scatter(copt(),F(copt())) plt.scatter(copt(), 0) plt.scatter(topt(),F(topt()) + AGD(topt())) plt.grid() plt.xlim(0,6) plt.ylim(0,14) plt.xlabel('x -- head of cattle', fontsize=18) plt.ylabel('Benefits/Profit', fontsize=18) plt.legend(fontsize=14); def MC(x,c=1/2): '''Cattle MC''' return 2*c*x def excost(x,d=1/2): return 2*d*x def coaseplot2(Pw=Pw, Pc=Pc): xx = np.linspace(0,6,100) fig = plt.subplots(figsize=(12,9)) plt.axhline(Pc); plt.plot(xx, MC(xx), label = 'Rancher PMC' ) plt.plot(xx, MC(xx)+excost(xx), label = 'SMC') plt.fill_between(xx, MC(xx)+excost(xx),Pc*xx**0, where=((MC(xx)<=Pc*xx**0) & (xx>2)), facecolor='green', alpha=0.2, label='DWL') plt.text(3,5,'DWL' , fontsize=15) plt.text(5,3.5,r'$SMB = P_C$', fontsize=15) plt.text(5,5.5, r'$PMC$', fontsize=15) plt.text(4.5,8.5, r'$SMC$', fontsize=15) #plt.scatter(topt(),G(topt()) + AGD(topt())) plt.grid() plt.xlim(0,6) plt.ylim(0,10) plt.yticks(np.arange(0, 10, 1)) plt.xlabel('x -- head of cattle') plt.ylabel('Benefits/Profit') plt.legend(); # #### Code for land example A=1 def FT(T, A=A): return A*np.sqrt(T) def MVPT(P,T,A=A): return A*P/T**(1/2) def LD(P,r,A=A): return (P*A/r)**2 A=1 Tbar = 10 # Total land endowment P = 5.5 # Price of output cl = 3 # cost of clearing land def req(P, cl, Tb=Tbar, N=2, A=A): '''equilibrium rental rate''' def landemand(r): return N*(A*P/r)**2 - Tb return fsolve(landemand, 1)[0] def mopt(P,cl,A=A): '''Optimum land use for each i at the P*MPT = max(cl,r)''' r = req(P,cl) ru = max(cl, r) return (A*P/ru)**2 mopt(P,cl), MVPT(P, mopt(P,cl) ) def landmarket(P, cl, title, A=A): t = np.linspace(0.1,Tbar-0.1, 2*Tbar) fig = plt.subplots(figsize=(12,8)) x0 = mopt(P,cl,A=A) plt.ylim(0,5) #plt.axhline(cl,linestyle=':') plt.axhline(max(cl,req(P,cl,A=A)),linestyle='--') plt.axhline(cl,linestyle=':') plt.plot(t,MVPT(P,t)) plt.text(8, MVPT(P,8),r'$P \cdot F_T(T)$', fontsize=18) plt.text(1, MVPT(P,Tbar-1),r'$P \cdot F_T(\bar T - T)$', fontsize=18) plt.xlabel('T -- land use', fontsize=18) plt.ylabel('MVPT', fontsize=18) plt.scatter(x0, MVPT(P,x0)) plt.scatter(Tbar-mopt(P,cl),MVPT(P,x0)) plt.plot([x0,x0],[0,MVPT(P,x0)],':') plt.plot([Tbar-x0,Tbar-x0],[0,MVPT(P,x0)],':') plt.plot(t,MVPT(P,Tbar - t)) plt.plot(t,MVPT(P,Tbar-t)) plt.title(title, fontsize=18) plt.xlim(0,Tbar);
StarcoderdataPython
1753012
import os, sys, argparse, codecs, getpass from xml.dom.minidom import parse from urllib.parse import unquote from platform import system from re import search, sub from tkinter import Tk from tkinter.filedialog import askopenfilename, askdirectory ################################################################## ## CONSTANTS ################################################################## DEBUG = False SETTINGS_NAME = "settings" # name for the settings file DEFAULT_FORMAT = "M3U8" # default format to export playlists in TAB_SIZE = 4 # number of spaces in a tab TABLE_WIDTH = 50 # width of table used to print playlists ################################################################## ## CLASSES ################################################################## class iTunes_Library_Parser(): def __init__(self, xml_file, document = None): if DEBUG: print("Called iTunes Library Parser constructor") self.xml_file = xml_file self.document = document if document is None: self.document = parse(self.xml_file) self.FIRST_TRACK_DICT = 3 self.TRACK_DICT_SKIP = 4 self.TRACK_DICT_ID = 2 def __str__(self): return "iTunes Library located at " + str(self.xml_file) def get_key(self, node, key_name): """return a node of tag name "key" with given name if it exists, else returns None""" keys = node.getElementsByTagName("key") for key in keys: if key.nodeType == key.ELEMENT_NODE: # return the first key with the specified name found if key.childNodes[0].nodeValue == key_name: return key return None def get_tracks_node(self): """Returns the <dict> node containing all of the track information""" tracks_key = self.get_key(self.document, "Tracks") return tracks_key.nextSibling.nextSibling def get_track_dicts(self): """Returns a list of <dict>s for each track in the library""" # set initial variables root_dict = self.get_tracks_node() track_dicts = [] tracks_left = True index = 1 # while there are tracks left while tracks_left: # try to get the corresponding child node to the index try: track_dict = root_dict.childNodes[self.FIRST_TRACK_DICT + self.TRACK_DICT_SKIP * index] # if the index doesn't exist, there are no more tracks, quit the loop except IndexError: tracks_left = False break # add the track to the list, increment the index else: track_dicts.append(track_dict) index += 1 return track_dicts def get_key_value(self, node, to_find): """Finds the value of the key given if the key exists, otherwise returns None""" key = None key_node = self.get_key(node, to_find) if key_node is not None: key = key_node.nextSibling.childNodes[0].nodeValue return key def get_key_bool_value(self, node, to_find): """Finds the boolean value of the key given if the key exists, otherwise returns None""" key = None key_node = self.get_key(node, to_find) if key_node is not None: key = key_node.nextSibling.nodeName return key def get_track_info(self, track_dict): """Returns a string with the location on disk of a track with the given ID""" info = {} # get and process the length by getting windows path and removing percent encoding raw = self.get_key_value(track_dict, "Location") trimmed = search(r"[A-Z]:.*", raw) info['location'] = normalize_path(unquote(trimmed.group(0))) # get and process the total time in seconds milliseconds = self.get_key_value(track_dict, "Total Time") info['length'] = int(milliseconds)/1000 # get and process song and artist name info['name'] = self.get_key_value(track_dict, "Name") info['artist'] = self.get_key_value(track_dict, "Artist") return info class Playlist_Parser(iTunes_Library_Parser): """Contains relevant information and method for a playlist""" def __init__(self, node, xml_file, document = None): self.node = node super().__init__(xml_file, document) def get_track_ids(self): """Returns an array of all the items in the playlist node""" # variable initialization array = None items = [] # find the tag in the playlist named array arrays = self.node.getElementsByTagName("array") # if the tag doesn't exist, return an empty list of items try: array = arrays[0] except IndexError: return [] # loop the <dict>s containing Track IDs, add the Track IDs to items list current_dict = array.childNodes[0].nextSibling while current_dict is not None: track_id = int(current_dict.childNodes[0].nextSibling.nextSibling.childNodes[0].nodeValue) items.append(track_id) current_dict = current_dict.nextSibling.nextSibling return items def get_tracks_info(self, track_ids = None): """Gets the locations on disk of the songs with the given track IDs""" # initialize tracks as an empty list tracks = [] # get track ids if not given if track_ids is None: track_ids = self.get_track_ids() track_dicts = self.get_track_dicts() for track_dict in track_dicts: # get the track_id from the dict track_id = int(track_dict.childNodes[self.TRACK_DICT_ID].childNodes[0].nodeValue) # if track_id is in the list of track_ids # get the info of the track and remove the id from the list if track_id in track_ids: if DEBUG: print("Found id " + str(track_id)) info = self.get_track_info(track_dict) tracks.append(info) track_ids.remove(track_id) # all remaining ids in the list of track ids could not be found for remaining in track_ids: sys.stderr.write("Could not find track with ID " + str(remaining) + "!\n") return tracks class Playlist(): """Information about a playlist""" def __init__(self, playlists_node, xml_file, document = None): self.parser = Playlist_Parser(playlists_node, xml_file, document) def __str__(self): return self.name def set_name(self): """Sets the value of self.name by finding the value of "Name" in the XML""" self.name = self.parser.get_key_value(self.parser.node, "Name") def set_persistent_ID(self): """Sets the value of self.persistent_ID by finding the value of "Playlist Persistent ID" in the XML""" self.persistent_ID = self.parser.get_key_value(self.parser.node, "Playlist Persistent ID") def set_parent_ID(self): """Sets the value of self.parent_ID by finding the value of "Parent Persistent ID" in the XML""" self.parent_ID = self.parser.get_key_value(self.parser.node, "Parent Persistent ID") def set_is_folder(self): """Sets the value of self.is_folder by finding the boolean value of "Folder" in the XML""" self.is_folder = False is_folder = self.parser.get_key_bool_value(self.parser.node, "Folder") if is_folder == "true": self.is_folder = True def set_is_smart(self): """Sets the value of self.is_smart by finding whether the "Smart Info" key exists in the XML""" self.is_smart = self.parser.get_key(self.parser.node, "Smart Info") is not None def set_items(self): """Sets the list of items in the Playlist""" if DEBUG: print("Setting items for playlist \"" + self.name + "\"") self.items = self.parser.get_tracks_info() if DEBUG: print("Finished setting info for \"" + self.name + "\"") def get_total_length(self): """Returns the total length in seconds of this Playlist""" total = 0 for item in self.items: total += item['length'] return total def set_quick(self): """Calls the quick set functions above""" self.set_name() self.set_persistent_ID() self.set_parent_ID() self.set_is_folder() self.set_is_smart() class iTunes_Library(): """Information about an iTunes XML Library""" def __init__(self, xml_file): if DEBUG: print("Called iTunes Library constructor") if not DEBUG: print("Parsing iTunes Library XML file ...", end = " ") self.xml_file = xml_file self.parser = iTunes_Library_Parser(self.xml_file) if not DEBUG: print("Done!") def get_playlists(self): """Sets the non time consuming information for each playlist (everything except items)""" # create array to contain Playlist_Parser objects self.playlists = [] playlists_key = self.parser.get_key(self.parser.document, "Playlists") playlists_node = playlists_key.nextSibling.nextSibling # create a Playlist object for each playlist for node in playlists_node.childNodes: if not node.nodeType == node.TEXT_NODE: playlist = Playlist(node, self.xml_file, self.parser.document) playlist.set_quick() self.playlists.append(playlist) def get_items(self, playlists, export_all): """Creates Playlist object for each playlist found and adds them to a list""" # get the playlists if necessary if not hasattr(self, "playlists"): self.get_playlists() force_select = False # ask the user to select the playlists to export if none are specified if len(playlists) == 0 and export_all == False: playlists = self.select_playlists() force_select = True self.export = [] # set the items for the playlists specified to export for playlist in self.playlists: if export_all or playlist.name in playlists: if DEBUG: print("Adding playlist " + playlist.name + " to self.export") playlist.set_items() self.export.append(playlist) # check to see if any playlists were excluded from self.export if len(playlists) > 0 and not force_select: # make list of names of playlists to be exported names_list = [] for playlist in self.export: names_list.append(playlist.name) check_for_excluded(playlists, names_list) def get_num_playlist_ancestors(self, Playlist): """Determines the Playlist's place in the directory structure""" num_ancestors = 0 current_ancestor = Playlist # while the current ancestor has a parent while current_ancestor.parent_ID is not None: # find the current ancestor's parent by looping through the array check_num = 0 check = self.playlists[check_num] while not check.persistent_ID == current_ancestor.parent_ID: check_num += 1 check = self.playlists[check_num] # set the current ancestor's parent as the new current ancestor current_ancestor = check num_ancestors += 1 return num_ancestors def select_playlists(self): """Prints the playlists in the library indented by their folder levels""" # get the playlists if not hasattr(self, "playlists"): self.get_playlists() print("You have not specified any playlists to export! " + "The playlists available will now be printed, " + "please enter y to export the playlist or n to skip it.") chosen = [] satisfied = False tab = " " * TAB_SIZE # loop through the playlists and print them appropriately while not satisfied: for playlist in self.playlists: # determine its indentation level indents = self.get_num_playlist_ancestors(playlist) tab_string = tab * indents # determine the type of Playlist type_string = "" if playlist.is_smart: type_string += "Smart " if playlist.is_folder: type_string += "Folder" else: type_string += "Playlist" input_start = tab_string + playlist.name input_end = " <" + type_string + "> [y/n]? " filler_string = " " * (TABLE_WIDTH - len(input_start) - len(input_end)) # print the Playlist export = input(input_start + filler_string + input_end) # determine whether to export the playlist if export == "y": chosen.append(playlist) # run the playlist chooser until the user is satisfied with their selection chosen_string = (''.join(str(choice.name) + ", " for choice in chosen)).rstrip(", ") report = input('Playlists to be exported are: ' + chosen_string + '\n' + 'To continue, type "y", to choose a new ' + 'set of playlists, type "n" ') if not report == "n": satisfied = True return chosen class Playlist_Writer(): """Writes playlists to disk""" def __init__(self, playlist, root, extension): self.playlist = playlist self.root = root self.extension = extension self.location = normalize_path(os.path.join(root, self.playlist.name + extension)) def playlist_exists(self): """Tests whether the file to write to already exists""" # try to open file to read it try: file = open(self.location, 'r') # if it fails, then the file doesn't exist except IOError: return False file.close() return True def write_file(self): raise NotImplementedError("Subclass must implement abstract method") def change_location(self): """Determines location based on whether the user wishes to overwrite existing playlist""" # variables for the loop first = True counter = 2 name = self.playlist.name + self.extension # change the name of the playlist while the location is occupied while self.playlist_exists(): if first == True: overwrite = input("File " + name + " exists. Overwrite? [y/n] ") first = False # if the user chooses not to overwrite, exit the loop if overwrite == "y": print("Will overwrite " + name) break else: print("Creating new name for \"" + name + "\"") # give the playlist a new name new_name = self.playlist.name + " (" + str(counter) + ")" + self.extension self.location = normalize_path(os.path.join(self.root, new_name)) counter += 1 print("new name for " + self.playlist.name + " is " + new_name) class WPL_Writer(Playlist_Writer): """Writes WPL playlists to disk""" def __init__(self, playlist, root): super().__init__(playlist, root, ".wpl") def write_file(self): """Writes the playlist file""" if DEBUG: print("Writing file for " + self.playlist.name) # open the file as utf8 file = codecs.open(self.location, 'w', "utf-8") # HEADER # write initial data file.write(r'<?wpl version = "1.0"?>') file.write("\n" + r"<smil>") file.write("\n" + "\t" + r"<head>") # write meta data file.write("\n" + "\t" + "\t" + r"""<meta name = "Generator" content = "Kar's iTunes Export Python Script"/>""") file.write("\n" + "\t" + "\t" + r'<meta name = "TotalDuration" content = ' + "\"" + str(self.playlist.get_total_length()) + r'"/>') file.write("\n" + "\t" + "\t" + r'<meta name = "ItemCount" content = ' + "\"" + str(len(self.playlist.items)) + r'"/>') file.write("\n" + "\t" + "\t" + r"<author>" + getpass.getuser() + r"</author>") file.write("\n" + "\t" + "\t" + r"<title>" + self.playlist.name + r"</title>") file.write("\n" + "\t" + r"</head>") # begin writing body file.write("\n" + "\t" + r"<body>") file.write("\n" + "\t" + "\t" + r"<seq>") # BODY for item in self.playlist.items: file.write("\n" + "\t" + "\t" + "\t") clean_loc = self.clean_string(item['location']) file.write(r'<media src = "' + clean_loc + "\"" + r'/>') # FOOTER # finish writing the file file.write("\n" + "\t" + "\t" + r"</seq>") file.write("\n" + "\t" + r"</body>") file.write("\n" + r"</smil>") # close the file file.close() def clean_string(self, location): """Cleans the location of characters that will break the file""" return location.replace("&", "&amp;") class M3U8_Writer(Playlist_Writer): """Writes m3u8 playlist files to disk""" def __init__(self, playlist, root): super().__init__(playlist, root, ".m3u8") def write_file(self): """Writes the playlist file""" if DEBUG: print("Writing file for " + self.playlist.name) sep = os.linesep # open the file as utf8 file = codecs.open(self.location, 'w', "utf-8") # HEADER file.write(r'#EXTM3U') # BODY for item in self.playlist.items: file.write(sep + r"#EXTINF:" + str(int(round(item['length'], 0))) + "," + item['name'] + " - " + item['artist']) file.write(sep + item['location']) # close the file file.close() ################################################################## ## FUNCTIONS ################################################################## def get_settings_location(): """Get the playlist info text file from the current directory""" # set up the path path_name = os.path.dirname(sys.argv[0]) settings_location = os.path.abspath(path_name) # normalize and return the entire path return normalize_path(os.path.join(settings_location, SETTINGS_NAME + ".txt")) def get_settings_lines(): """Returns a list of the lines in the settings file""" settings_location = get_settings_location(); # open the file if it exists, create the file if it doesn't try: settings_file = open(settings_location, 'r') except IOError: settings_file = open(settings_location, 'w') settings_file.close() settings_file = open(settings_location, 'r') settings_lines = settings_file.readlines() # close the file and return the lines settings_file.close() return settings_lines def confirm_name(info_lines, line_num, filetypes, title): """GUI asks user to choose a file/directory if the existing cannot be found""" # set initial variables, if filetypes is blank, then a directory is wanted path = info_lines[line_num - 1].rstrip('\r\n') directory = filetypes is None # if the path does not exist, prompt for a new one if not os.path.exists(path): if DEBUG: print("path " + str(path) + " does not exist") Tk().withdraw() if directory: path = askdirectory(title = title) else: path = askopenfilename(filetypes = filetypes, title = title) # throw SystemExit exception if the user does not choose a valid path if not os.path.exists(path): sys.exit() # save the new path to the array if the user chooses a valid path else: if DEBUG: print(str(info_lines[line_num - 1]).rstrip('\r\n') + " will be changed to " + str(path)) info_lines[line_num - 1] = path + "\n" elif DEBUG: print(str(path) + " exists") return path def normalize_path(path): """Normalize the path by replacing all the slashes with the default system slash""" # replace forward slashes in Windows and backslashes otherwise if system() == "Windows": return path.replace("/", "\\") else: return path.replace("\\", "/") def save(lines): """Save the changes made to the settings file by rewriting its contents""" file = open(get_settings_location(), 'w') file.writelines(lines) file.close() def create_writers(playlists, extension, export_location): """Creates and returns a list of writers corresponding to the extension and playlists""" writers = [] # if the extension is WPL, make a WPL_Writer for all the playlists given if extension.lower() == "wpl": for playlist in playlists: writers.append(WPL_Writer(playlist, export_location)) # if the extension is M3U8, make an M3U8_Writer for all the playlists given if extension.lower() == "m3u8": for playlist in playlists: writers.append(M3U8_Writer(playlist, export_location)) return writers def determine_writers(playlists, args, export_location): """Returns a list of writers corresponding to command line arguments or constants""" writers = [] # for every extension given, create a corresponding Playlist_Writer for extension in args.extension: if extension.lower() == "wpl": print("Length of playlists is " + str(len(playlists))) for playlist in playlists: writers.append(WPL_Writer(playlist, export_location)) if extension.lower() == "m3u8": for playlist in playlists: writers.append(M3U8_Writer(playlist, export_location)) return writers def check_for_excluded(list1, list2): """Check to see if every item in list1 is in list2""" for item in list1: if not item in list2: sys.stderr.write("Item " + item + " not found!\n") def command_line_args(): """Set up command line arguments""" if DEBUG: print("Parsing command line arguments") # create the argument parser parser = argparse.ArgumentParser(description = "Export iTunes playlists") # set up the available arguments parser.add_argument('-a', '--all', action = 'store_true', help = "export all playlists") parser.add_argument('-e', '--extension', nargs = '*', default = [DEFAULT_FORMAT], help = "specify the extension of the playlist in the form 'wpl' or 'm3u8'") parser.add_argument('-p', '--playlists', nargs = '*', help = "specify the playlists to export") parser.add_argument('-f', '--file', action = 'store_true', help = "export playlists specified in a text file (use the settings" + "file to specify the location of the text file)") # parse and return the arguments args = parser.parse_args() return args def settings_file(args): """Deal with settings file""" if DEBUG: print("Reading the settings file") lines = get_settings_lines() # test to see if the paths in the file exist, prompt for new ones if they don't try: library_location = confirm_name(lines, 1, [('xml files', '.xml')], "Choose iTunes library xml file") export_location = confirm_name(lines, 2, None, "Choose the directory for the files to be exported") playlists_location = None if args.file: playlists_location = confirm_name(lines, 3, [('Text files', '.txt')], "Choose the location of the text file " + "containing the playlists") # if a user does not choose a directory, catch the SystemExit exception, save and exit except SystemExit: print("Correct file/folder was not chosen, script will now save and exit") save(lines) else: save(lines) return library_location, export_location, playlists_location def write_playlists(args, library_location, export_location, playlists_location): """Create the iTunes Library object and write the playlists""" playlist_names = args.playlists if playlist_names is None: playlist_names = [] # create a list of playlists if they were given if playlists_location is not None: # set up file to be read playlist_names = [] playlists_file = open(playlists_location, 'r') playlist_line = playlists_file.readline() # read all the lines in the file while not playlist_line == '': playlist_names.append(playlist_line.rstrip('\r\n')) playlist_line = playlists_file.readline() # close the file playlists_file.close() # create the library and get the items to export if DEBUG: print("Reading library") library = iTunes_Library(library_location) library.get_items(playlist_names, args.all) playlist_names = ', '.join([playlist.name for playlist in library.export]) print("Items to export are " + str(playlist_names) + ".") # create writers for the items and write them to disk writers = determine_writers(library.export, args, export_location) if DEBUG: print("Writing " + str(len(writers)) + " playlists") for writer in writers: writer.change_location() writer.write_file() ################################################################## ## BODY ################################################################## if __name__ == "__main__": args = command_line_args() library_location, export_location, playlists_location = settings_file(args) write_playlists(args, library_location, export_location, playlists_location) print("Finished writing playlists, will now exit!")
StarcoderdataPython
5102034
<reponame>ArkDu/nanomanufacturing import numpy as np import cv2, statistics, pprint from pathlib import Path from argparse import ArgumentParser, RawTextHelpFormatter import os import sys class Config: '''Configuration and Argument Parser for particle detection.''' def __init__(self, args): self.parser = ArgumentParser(description='parser for nanomanufacturing', formatter_class=RawTextHelpFormatter) self.parser.add_argument('--video_path', type=str, default=r"./10k20v.avi", help="Input path for video to image convertion") self.parser.add_argument('--image_path', type=str, default='./output', help="Output path for video to image convertion") self.parser.add_argument('--sampling_interval', type=int, default=30, help="Take one frame for every sampling interval.") self.parser.add_argument('--min_radius', type=int, default=1, help='Minimum radius for particles being detected.') self.parser.add_argument('--max_radius', type=int, default=50, help='Maximum radius for particles being detected.') args_parsed = self.parser.parse_args(args) for arg_name in vars(args_parsed): self.__dict__[arg_name] = getattr(args_parsed, arg_name) class ParticleDetector: def __init__(self, cfg): self.config = cfg self.video_path = cfg.video_path self.image_path = cfg.image_path self.sampling_interval = cfg.sampling_interval self.min_radius = cfg.min_radius self.max_radius = cfg.max_radius self.bar1 = [(265, 95), (265, 900)] self.bar2 = [(490, 95), (490, 900)] self.bar3 = [(710, 95), (710, 900)] self.bar4 = [(936, 95), (936, 900)] self.bar5 = [(1160, 95), (1160, 900)] def convert_video_to_images(self): # sampling_interval = 30 cap = cv2.VideoCapture(self.video_path) max_frame_no = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) # create a empty folder root_folder_path = Path(self.image_path) root_folder_path.mkdir(exist_ok=True) # capture images in avi file according to the framerate. for frame_no in range(0, max_frame_no, self.sampling_interval): if frame_no > 0 and frame_no < max_frame_no: cap.set(cv2.CAP_PROP_POS_FRAMES, frame_no) ret, frame = cap.read() outname = root_folder_path / (str(frame_no)+'.jpg') cv2.imwrite(str(outname), frame) def read_analyze_images(self): # should be a 4-tuple item list with each 4-tuple (x1, y1, x2, y2) # only capture particles in the following zones: between bar2 and bar3, between bar4 and bar5. feature_group_0 = [] feature_group_1 = [] for image_path in Path(self.image_path).glob("**/*.jpg"): bags_0 = [] bags_1 = [] img = cv2.imread(str(image_path)) kernel = np.ones((5,5),np.uint8) img = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) detected_circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1,20, param1=50,param2=30,minRadius=self.min_radius, maxRadius=self.max_radius) detected_circles = np.uint16(np.around(detected_circles)) cv2.line(img, self.bar1[0], self.bar1[1], (0, 255, 0)) cv2.line(img, self.bar2[0], self.bar2[1], (0, 255, 0)) cv2.line(img, self.bar3[0], self.bar3[1], (0, 255, 0)) cv2.line(img, self.bar4[0], self.bar4[1], (0, 255, 0)) cv2.line(img, self.bar5[0], self.bar5[1], (0, 255, 0)) for pt in detected_circles[0, :]: a, b, r = pt[0], pt[1], pt[2] if b < self.bar1[0][1] or b > self.bar1[1][1]: #filtering particles that are too high or too low. continue if (a >= self.bar2[0][0] and a <= self.bar3[0][0]): bags_0.append((a,b,r)) if (a >= self.bar4[0][0] and a <= self.bar5[0][0]): bags_1.append((a,b,r)) for a,b,r in bags_0+bags_1: cv2.circle(img, (a, b), r, (0, 255, 0), 2) # Draw the circumference of the circle. cv2.circle(img, (a, b), 1, (0, 0, 255), 3) # Draw a small circle (of radius 1) to show the center. try: x_avr_0 = sum([p[0] for p in bags_0]) / len(bags_0) x_std_0 = statistics.stdev([float(p[0]) for p in bags_0]) y_avr_0 = sum([p[1] for p in bags_0]) / len(bags_0) y_std_0 = statistics.stdev([float(p[1]) for p in bags_0]) x_avr_1 = sum([p[0] for p in bags_1]) / len(bags_1) x_std_1 = statistics.stdev([float(p[0]) for p in bags_1]) y_avr_1 = sum([p[1] for p in bags_1]) / len(bags_1) y_std_1 = statistics.stdev([float(p[1]) for p in bags_1]) feature_group_0.append((int(image_path.name.split('.')[0]), (x_avr_0, x_std_0, y_avr_0, y_std_0))) feature_group_1.append((int(image_path.name.split('.')[0]), (x_avr_1, x_std_1, y_avr_1, y_std_1))) except: print(image_path) cv2.imshow("Detected Circle", img) cv2.waitKey(0) feature_group_0 = sorted(feature_group_0, key=lambda x: x[0]) feature_group_1 = sorted(feature_group_1, key=lambda x: x[0]) with open('output1.txt', 'w') as file1, open('output2.txt', 'w') as file2: pprint.pprint(feature_group_0, file1) pprint.pprint(feature_group_1, file2) import pdb; pdb.set_trace() if __name__ == "__main__": ''' sample command python nano.py --video_path ./10k20v.avi --image_path ./output''' cfg = Config(sys.argv[1:]) detector = ParticleDetector(cfg) # detector.convert_video_to_images() detector.read_analyze_images() # convert_video_to_images(r"./10k20v.avi" , "./output") # read_analyze_images("./output")
StarcoderdataPython
7823
<reponame>obilaniu/orion<filename>tests/unittests/plotting/test_plotly_backend.py """Collection of tests for :mod:`orion.plotting.backend_plotly`.""" import copy import numpy import pandas import plotly import pytest import orion.client from orion.analysis.partial_dependency_utils import partial_dependency_grid from orion.core.worker.experiment import Experiment from orion.plotting.base import ( lpi, parallel_coordinates, partial_dependencies, rankings, regret, regrets, ) from orion.testing import create_experiment from orion.testing.plotting import ( assert_lpi_plot, assert_parallel_coordinates_plot, assert_partial_dependencies_plot, assert_rankings_plot, assert_regret_plot, assert_regrets_plot, ) config = dict( name="experiment-name", space={"x": "uniform(0, 200)"}, metadata={ "user": "test-user", "orion_version": "XYZ", "VCS": { "type": "git", "is_dirty": False, "HEAD_sha": "test", "active_branch": None, "diff_sha": "diff", }, }, version=1, pool_size=1, max_trials=10, working_dir="", algorithms={"random": {"seed": 1}}, producer={"strategy": "NoParallelStrategy"}, ) trial_config = { "experiment": 0, "status": "completed", "worker": None, "start_time": None, "end_time": None, "heartbeat": None, "results": [], "params": [], } def mock_space(x="uniform(0, 6)", y="uniform(0, 3)", **kwargs): """Build a mocked space""" mocked_config = copy.deepcopy(config) mocked_config["space"] = {"x": x} if y is not None: mocked_config["space"]["y"] = y mocked_config["space"].update(kwargs) return mocked_config def mock_experiment( monkeypatch, ids=None, x=None, y=None, z=None, objectives=None, status=None ): """Mock experiment to_pandas to return given data (or default one)""" if ids is None: ids = ["a", "b", "c", "d"] if x is None: x = [0, 1, 2, 4] if y is None: y = [3, 2, 0, 1] if objectives is None: objectives = [0.1, 0.2, 0.3, 0.5] if status is None: status = ["completed", "completed", "completed", "completed"] data = { "id": ids, "x": x, "objective": objectives, "status": status, "suggested": ids, } if not isinstance(y, str): data["y"] = y if z is not None: data["z"] = z def to_pandas(self, with_evc_tree=False): return pandas.DataFrame(data=data) monkeypatch.setattr(Experiment, "to_pandas", to_pandas) def mock_experiment_with_random_to_pandas(monkeypatch, status=None, unbalanced=False): def to_pandas(self, with_evc_tree=False): if unbalanced: N = numpy.random.randint(5, 15) elif status is not None: N = len(status) else: N = 10 ids = numpy.arange(N) x = numpy.random.normal(0, 0.1, size=N) y = numpy.random.normal(0, 0.1, size=N) objectives = numpy.random.normal(0, 0.1, size=N) if status is None: exp_status = ["completed"] * N else: exp_status = status data = pandas.DataFrame( data={ "id": ids, "x": x, "y": y, "objective": objectives, "status": exp_status, "suggested": ids, } ) return data monkeypatch.setattr(Experiment, "to_pandas", to_pandas) def mock_model(): """Return a mocked regressor which just predict iterated integers""" class Model: """Mocked Regressor""" def __init__(self): self.i = 0 def predict(self, data): """Returns counting of predictions requested.""" data = numpy.arange(data.shape[0]) + self.i self.i += data.shape[0] return data # + numpy.random.normal(0, self.i, size=data.shape[0]) return Model() def mock_train_regressor(monkeypatch, assert_model=None, assert_model_kwargs=None): """Mock the train_regressor to return the mocked regressor instead""" def train_regressor(model, data, **kwargs): """Return the mocked model, and then model argument if requested""" if assert_model: assert model == assert_model if assert_model_kwargs: assert kwargs == assert_model_kwargs return mock_model() monkeypatch.setattr( "orion.analysis.partial_dependency_utils.train_regressor", train_regressor ) @pytest.mark.usefixtures("version_XYZ") class TestLPI: """Tests the ``lpi()`` method provided by the plotly backend""" def test_requires_argument(self): """Tests that the experiment data are required.""" with pytest.raises(ValueError): lpi(None) def test_returns_plotly_object(self): """Tests that the plotly backend returns a plotly object""" with create_experiment(config, trial_config, ["completed"]) as ( _, _, experiment, ): plot = lpi(experiment, model_kwargs=dict(random_state=1)) assert type(plot) is plotly.graph_objects.Figure def test_graph_layout(self, monkeypatch): """Tests the layout of the plot""" config = mock_space() mock_experiment(monkeypatch) with create_experiment(config, trial_config, ["completed"]) as ( _, _, experiment, ): plot = lpi(experiment, model_kwargs=dict(random_state=1)) df = experiment.to_pandas() assert df["x"].tolist() == [0, 1, 2, 4] assert df["y"].tolist() == [3, 2, 0, 1] assert df["objective"].tolist() == [0.1, 0.2, 0.3, 0.5] assert_lpi_plot(plot, dims=["x", "y"]) def test_experiment_worker_as_parameter(self, monkeypatch): """Tests that ``Experiment`` is a valid parameter""" config = mock_space() mock_experiment(monkeypatch) with create_experiment(config, trial_config, ["completed"]) as ( _, experiment, _, ): plot = lpi(experiment, model_kwargs=dict(random_state=1)) assert_lpi_plot(plot, dims=["x", "y"]) def test_ignore_uncompleted_statuses(self, monkeypatch): """Tests that uncompleted statuses are ignored""" config = mock_space() mock_experiment( monkeypatch, ids="abcdefgh", x=[0, 0, 0, 1, 0, 2, 0, 3], y=[1, 0, 0, 2, 0, 0, 0, 3], objectives=[0.1, None, None, 0.2, None, 0.3, None, 0.5], status=[ "completed", "new", "reserved", "completed", "broken", "completed", "interrupted", "completed", ], ) with create_experiment(config, trial_config) as (_, _, experiment): plot = lpi(experiment) assert_lpi_plot(plot, dims=["x", "y"]) def test_multidim(self, monkeypatch): """Tests that dimensions with shape > 1 are flattened properly""" config = mock_space(y="uniform(0, 3, shape=2)") mock_experiment(monkeypatch, y=[[3, 3], [2, 3], [1, 2], [0, 3]]) with create_experiment(config, trial_config) as (_, _, experiment): plot = lpi(experiment, model_kwargs=dict(random_state=1)) assert_lpi_plot(plot, dims=["x", "y[0]", "y[1]"]) def test_fidelity(self, monkeypatch): """Tests that fidelity is supported""" config = mock_space(y="fidelity(1, 200, base=3)") mock_experiment(monkeypatch, y=[1, 3 ** 2, 1, 3 ** 4]) with create_experiment(config, trial_config) as (_, _, experiment): plot = lpi(experiment, model_kwargs=dict(random_state=1)) assert_lpi_plot(plot, dims=["x", "y"]) def test_categorical(self, monkeypatch): """Tests that categorical is supported""" config = mock_space(y='choices(["a", "b", "c"])') mock_experiment(monkeypatch, y=["c", "c", "a", "b"]) with create_experiment(config, trial_config) as (_, _, experiment): plot = lpi(experiment, model_kwargs=dict(random_state=1)) assert_lpi_plot(plot, dims=["x", "y"]) def test_categorical_multidim(self, monkeypatch): """Tests that multidim categorical is supported""" config = mock_space(y='choices(["a", "b", "c"], shape=3)') mock_experiment( monkeypatch, y=[["c", "b", "a"], ["c", "a", "c"], ["a", "b", "a"], ["c", "b", "b"]], ) with create_experiment(config, trial_config) as (_, _, experiment): plot = lpi(experiment, model_kwargs=dict(random_state=1)) assert_lpi_plot(plot, dims=["x", "y[0]", "y[1]", "y[2]"]) @pytest.mark.usefixtures("version_XYZ") class TestParallelCoordinates: """Tests the ``parallel_coordinates()`` method provided by the plotly backend""" def test_requires_argument(self): """Tests that the experiment data are required.""" with pytest.raises(ValueError): parallel_coordinates(None) def test_returns_plotly_object(self): """Tests that the plotly backend returns a plotly object""" with create_experiment(config, trial_config, ["completed"]) as ( _, _, experiment, ): plot = parallel_coordinates(experiment) assert type(plot) is plotly.graph_objects.Figure def test_graph_layout(self): """Tests the layout of the plot""" with create_experiment(config, trial_config, ["completed"]) as ( _, _, experiment, ): plot = parallel_coordinates(experiment) assert_parallel_coordinates_plot(plot, order=["x", "loss"]) def test_experiment_worker_as_parameter(self): """Tests that ``Experiment`` is a valid parameter""" with create_experiment(config, trial_config, ["completed"]) as ( _, experiment, _, ): plot = parallel_coordinates(experiment) assert_parallel_coordinates_plot(plot, order=["x", "loss"]) def test_ignore_uncompleted_statuses(self): """Tests that uncompleted statuses are ignored""" with create_experiment(config, trial_config) as (_, _, experiment): plot = parallel_coordinates(experiment) assert_parallel_coordinates_plot(plot, order=["x", "loss"]) def test_unsupported_order_key(self): """Tests that unsupported order keys are rejected""" with create_experiment(config, trial_config) as (_, _, experiment): with pytest.raises(ValueError): parallel_coordinates(experiment, order=["unsupported"]) def test_order_columns(self): """Tests that columns are sorted according to ``order``""" multidim_config = copy.deepcopy(config) for k in "yzutv": multidim_config["space"][k] = "uniform(0, 200)" with create_experiment(multidim_config, trial_config) as (_, _, experiment): plot = parallel_coordinates(experiment, order="vzyx") assert_parallel_coordinates_plot(plot, order=["v", "z", "y", "x", "loss"]) def test_multidim(self): """Tests that dimensions with shape > 1 are flattened properly""" multidim_config = copy.deepcopy(config) multidim_config["space"]["y"] = "uniform(0, 200, shape=4)" with create_experiment(multidim_config, trial_config) as (_, _, experiment): plot = parallel_coordinates(experiment) assert_parallel_coordinates_plot( plot, order=["x", "y[0]", "y[1]", "y[2]", "y[3]", "loss"] ) def test_fidelity(self): """Tests that fidelity is set to first column by default""" fidelity_config = copy.deepcopy(config) fidelity_config["space"]["z"] = "fidelity(1, 200, base=3)" with create_experiment(fidelity_config, trial_config) as (_, _, experiment): plot = parallel_coordinates(experiment) assert_parallel_coordinates_plot(plot, order=["z", "x", "loss"]) def test_categorical(self): """Tests that categorical is supported""" categorical_config = copy.deepcopy(config) categorical_config["space"]["z"] = 'choices(["a", "b", "c"])' with create_experiment(categorical_config, trial_config) as (_, _, experiment): plot = parallel_coordinates(experiment) assert_parallel_coordinates_plot(plot, order=["x", "z", "loss"]) def test_categorical_multidim(self): """Tests that multidim categorical is supported""" categorical_config = copy.deepcopy(config) categorical_config["space"]["z"] = 'choices(["a", "b", "c"], shape=3)' with create_experiment(categorical_config, trial_config) as (_, _, experiment): plot = parallel_coordinates(experiment) assert_parallel_coordinates_plot( plot, order=["x", "z[0]", "z[1]", "z[2]", "loss"] ) @pytest.mark.usefixtures("version_XYZ") class TestPartialDependencies: """Tests the ``partial_dependencies()`` method provided by the plotly backend""" def test_returns_plotly_object(self, monkeypatch): """Tests that the plotly backend returns a plotly object""" mock_train_regressor(monkeypatch) with create_experiment(config, trial_config, ["completed"]) as ( _, _, experiment, ): plot = partial_dependencies( experiment, n_grid_points=5, model_kwargs=dict(random_state=1) ) assert type(plot) is plotly.graph_objects.Figure def test_graph_layout(self, monkeypatch): """Tests the layout of the plot""" mock_train_regressor(monkeypatch) config = mock_space() mock_experiment(monkeypatch) with create_experiment(config, trial_config, ["completed"]) as ( _, _, experiment, ): plot = partial_dependencies( experiment, n_grid_points=5, model_kwargs=dict(random_state=1) ) df = experiment.to_pandas() assert df["x"].tolist() == [0, 1, 2, 4] assert df["y"].tolist() == [3, 2, 0, 1] assert df["objective"].tolist() == [0.1, 0.2, 0.3, 0.5] assert_partial_dependencies_plot(plot, dims=["x", "y"]) def test_ignore_uncompleted_statuses(self, monkeypatch): """Tests that uncompleted statuses are ignored""" mock_train_regressor(monkeypatch) config = mock_space() mock_experiment( monkeypatch, ids="abcdefgh", x=[0, 0, 0, 1, 0, 2, 0, 3], y=[1, 0, 0, 2, 0, 0, 0, 3], objectives=[0.1, None, None, 0.2, None, 0.3, None, 0.5], status=[ "completed", "new", "reserved", "completed", "broken", "completed", "interrupted", "completed", ], ) with create_experiment(config, trial_config) as (_, _, experiment): plot = partial_dependencies(experiment, n_grid_points=5) assert_partial_dependencies_plot(plot, dims=["x", "y"]) def test_multidim(self, monkeypatch): """Tests that dimensions with shape > 1 are flattened properly""" mock_train_regressor(monkeypatch) config = mock_space(y="uniform(0, 3, shape=2)") mock_experiment(monkeypatch, y=[[3, 3], [2, 3], [1, 2], [0, 3]]) with create_experiment(config, trial_config) as (_, _, experiment): plot = partial_dependencies( experiment, n_grid_points=5, model_kwargs=dict(random_state=1) ) assert_partial_dependencies_plot(plot, dims=["x", "y[0]", "y[1]"]) def test_fidelity(self, monkeypatch): """Tests that fidelity is supported""" mock_train_regressor(monkeypatch) config = mock_space(y="fidelity(1, 200, base=3)") mock_experiment(monkeypatch, y=[1, 3 ** 2, 1, 3 ** 4]) with create_experiment(config, trial_config) as (_, _, experiment): plot = partial_dependencies( experiment, n_grid_points=5, model_kwargs=dict(random_state=1) ) assert_partial_dependencies_plot(plot, dims=["x", "y"], log_dims=["y"]) def test_categorical(self, monkeypatch): """Tests that categorical is supported""" mock_train_regressor(monkeypatch) config = mock_space(y='choices(["a", "b", "c"])') mock_experiment(monkeypatch, y=["c", "c", "a", "b"]) with create_experiment(config, trial_config) as (_, _, experiment): plot = partial_dependencies( experiment, n_grid_points=5, model_kwargs=dict(random_state=1) ) # There is only 3 categories, so test must be adjusted accordingly. assert_partial_dependencies_plot( plot, dims=["x", "y"], n_grid_points={"x": 5, "y": 3} ) def test_categorical_multidim(self, monkeypatch): """Tests that multidim categorical is supported""" mock_train_regressor(monkeypatch) config = mock_space(y='choices(["a", "b", "c"], shape=3)') mock_experiment( monkeypatch, y=[["c", "b", "a"], ["c", "a", "c"], ["a", "b", "a"], ["c", "b", "b"]], ) with create_experiment(config, trial_config) as (_, _, experiment): plot = partial_dependencies( experiment, n_grid_points=5, model_kwargs=dict(random_state=1) ) assert_partial_dependencies_plot( plot, dims=["x", "y[0]", "y[1]", "y[2]"], n_grid_points={"x": 5, "y[0]": 3, "y[1]": 3, "y[2]": 3}, ) def test_logarithmic_scales_first(self, monkeypatch): """Test that log dims are turn to log scale Test first dim specifically because special xaxis name for first dim. """ mock_train_regressor(monkeypatch) config = mock_space(x="loguniform(0.001, 1)", z="uniform(0, 1)") mock_experiment(monkeypatch, x=[0.001, 0.1, 0.01, 1], z=[0, 0.1, 0.2, 0.5]) with create_experiment(config, trial_config) as (_, _, experiment): plot = partial_dependencies( experiment, n_grid_points=5, model_kwargs=dict(random_state=1) ) assert_partial_dependencies_plot( plot, dims=["x", "y", "z"], n_grid_points=5, log_dims=["x"] ) def test_logarithmic_scales_any_dim(self, monkeypatch): """Test that log dims are turn to log scale""" mock_train_regressor(monkeypatch) config = mock_space(y="loguniform(0.001, 1)", z="uniform(0, 1)") mock_experiment(monkeypatch, y=[0.001, 0.1, 0.01, 1], z=[0, 0.1, 0.2, 0.5]) with create_experiment(config, trial_config) as (_, _, experiment): plot = partial_dependencies( experiment, n_grid_points=5, model_kwargs=dict(random_state=1) ) assert_partial_dependencies_plot( plot, dims=["x", "y", "z"], n_grid_points=5, log_dims=["y"] ) def test_int_logarithmic_scales(self, monkeypatch): """Test that int log dims are turn to log scale""" mock_train_regressor(monkeypatch) config = mock_space(y="loguniform(1, 1000, discrete=True)", z="uniform(0, 1)") mock_experiment(monkeypatch, y=[1, 10, 100, 1000], z=[0, 0.1, 0.2, 0.5]) with create_experiment(config, trial_config) as (_, _, experiment): plot = partial_dependencies( experiment, n_grid_points=5, model_kwargs=dict(random_state=1) ) assert_partial_dependencies_plot( plot, dims=["x", "y", "z"], n_grid_points=5, log_dims=["y"] ) def test_one_param(self, monkeypatch): """Test ploting a space with only 1 dim""" mock_train_regressor(monkeypatch) config = mock_space(y=None) mock_experiment(monkeypatch, y="drop") with create_experiment(config, trial_config) as (_, _, experiment): plot = partial_dependencies( experiment, n_grid_points=5, model_kwargs=dict(random_state=1) ) assert_partial_dependencies_plot(plot, dims=["x"], n_grid_points=5) def test_select_params(self, monkeypatch): """Test selecting subset""" mock_train_regressor(monkeypatch) config = mock_space(z="uniform(0, 1)") mock_experiment(monkeypatch, z=[0, 0.1, 0.2, 0.5]) for params in [["x"], ["x", "y"], ["y", "z"]]: with create_experiment(config, trial_config) as (_, _, experiment): plot = partial_dependencies( experiment, params=params, n_grid_points=5, model_kwargs=dict(random_state=1), ) assert_partial_dependencies_plot(plot, dims=params, n_grid_points=5) def test_custom_smoothing(self, monkeypatch): """Test changing smoothing value""" mock_train_regressor(monkeypatch) config = mock_space() mock_experiment(monkeypatch) with create_experiment(config, trial_config) as (_, _, experiment): plot = partial_dependencies( experiment, n_grid_points=5, model_kwargs=dict(random_state=1), smoothing=1.2, ) with pytest.raises(AssertionError): assert_partial_dependencies_plot(plot, dims=["x", "y"], n_grid_points=5) assert_partial_dependencies_plot( plot, dims=["x", "y"], n_grid_points=5, smoothing=1.2 ) def test_custom_n_grid_points(self, monkeypatch): """Test changing n_grid_points value""" mock_train_regressor(monkeypatch) config = mock_space() mock_experiment(monkeypatch) with create_experiment(config, trial_config) as (_, _, experiment): plot = partial_dependencies( experiment, n_grid_points=10, model_kwargs=dict(random_state=1), ) with pytest.raises(AssertionError): assert_partial_dependencies_plot(plot, dims=["x", "y"], n_grid_points=5) assert_partial_dependencies_plot(plot, dims=["x", "y"], n_grid_points=10) def test_custom_n_samples(self, monkeypatch): """Test changing n_samples value""" mock_train_regressor(monkeypatch) config = mock_space() mock_experiment(monkeypatch) PARAMS = ["x", "y"] N_SAMPLES = numpy.random.randint(20, 50) def mock_partial_dependency_grid(space, model, params, samples, n_points): print(samples) assert samples.shape == (N_SAMPLES, len(PARAMS)) return partial_dependency_grid(space, model, params, samples, n_points) monkeypatch.setattr( "orion.analysis.partial_dependency_utils.partial_dependency_grid", mock_partial_dependency_grid, ) with create_experiment(config, trial_config) as (_, _, experiment): plot = partial_dependencies( experiment, n_grid_points=10, model_kwargs=dict(random_state=1), n_samples=N_SAMPLES, ) def test_custom_colorscale(self, monkeypatch): """Test changing colorscale""" mock_train_regressor(monkeypatch) config = mock_space() mock_experiment(monkeypatch) with create_experiment(config, trial_config) as (_, _, experiment): plot = partial_dependencies( experiment, n_grid_points=5, colorscale="Viridis", model_kwargs=dict(random_state=1), ) with pytest.raises(AssertionError): assert_partial_dependencies_plot( plot, dims=["x", "y"], n_grid_points=5, custom_colorscale=False ) assert_partial_dependencies_plot( plot, dims=["x", "y"], n_grid_points=5, custom_colorscale=True ) def test_custom_model(self, monkeypatch): """Test changing type of regression model""" mock_train_regressor(monkeypatch, assert_model="BaggingRegressor") config = mock_space() mock_experiment(monkeypatch) with create_experiment(config, trial_config) as (_, _, experiment): plot = partial_dependencies( experiment, n_grid_points=5, model="BaggingRegressor", model_kwargs=dict(random_state=1), ) def test_custom_model_kwargs(self, monkeypatch): """Test changing arguments of regression model""" mock_train_regressor(monkeypatch, assert_model_kwargs=dict(random_state=1)) config = mock_space() mock_experiment(monkeypatch) with create_experiment(config, trial_config) as (_, _, experiment): plot = partial_dependencies( experiment, n_grid_points=5, model_kwargs=dict(random_state=1), ) @pytest.mark.usefixtures("version_XYZ") class TestRankings: """Tests the ``rankings()`` method provided by the plotly backend""" def test_requires_argument(self): """Tests that the experiment data are required.""" with pytest.raises(ValueError): rankings(None) def test_returns_plotly_object(self, monkeypatch): """Tests that the plotly backend returns a plotly object""" mock_experiment_with_random_to_pandas(monkeypatch) with create_experiment(config, trial_config, ["completed"]) as ( _, _, experiment, ): plot = rankings([experiment, experiment]) assert type(plot) is plotly.graph_objects.Figure def test_graph_layout(self, monkeypatch): """Tests the layout of the plot""" mock_experiment_with_random_to_pandas(monkeypatch) with create_experiment(config, trial_config, ["completed"]) as ( _, _, experiment, ): plot = rankings([experiment]) assert_rankings_plot(plot, [f"{experiment.name}-v{experiment.version}"]) def test_list_of_experiments(self, monkeypatch): """Tests the rankings with list of experiments""" mock_experiment_with_random_to_pandas(monkeypatch) with create_experiment(config, trial_config, ["completed"]) as ( _, _, experiment, ): child = orion.client.create_experiment( experiment.name, branching={"branch_to": "child"} ) plot = rankings([experiment, child]) # Exps are sorted alphabetically by names. assert_rankings_plot( plot, [f"{exp.name}-v{exp.version}" for exp in [child, experiment]] ) def test_list_of_experiments_name_conflict(self, monkeypatch): """Tests the rankings with list of experiments with the same name""" mock_experiment_with_random_to_pandas(monkeypatch) with create_experiment(config, trial_config, ["completed"]) as ( _, _, experiment, ): child = orion.client.create_experiment( experiment.name, branching={"branch_to": experiment.name} ) assert child.name == experiment.name assert child.version == experiment.version + 1 plot = rankings([experiment, child]) # Exps are sorted alphabetically by names. assert_rankings_plot( plot, [f"{exp.name}-v{exp.version}" for exp in [experiment, child]] ) def test_dict_of_experiments(self, monkeypatch): """Tests the rankings with renamed experiments""" mock_experiment_with_random_to_pandas(monkeypatch) with create_experiment(config, trial_config, ["completed"]) as ( _, _, experiment, ): plot = rankings({"exp-1": experiment, "exp-2": experiment}) assert_rankings_plot(plot, ["exp-1", "exp-2"]) def test_list_of_dict_of_experiments(self, monkeypatch): """Tests the rankings with avg of competitions""" mock_experiment_with_random_to_pandas(monkeypatch) with create_experiment(config, trial_config, ["completed"]) as ( _, _, experiment, ): plot = rankings( [{"exp-1": experiment, "exp-2": experiment} for _ in range(10)] ) assert_rankings_plot(plot, ["exp-1", "exp-2"], with_avg=True) def test_dict_of_list_of_experiments(self, monkeypatch): """Tests the rankings with avg of experiments separated in lists""" mock_experiment_with_random_to_pandas(monkeypatch) with create_experiment(config, trial_config, ["completed"]) as ( _, _, experiment, ): plot = rankings({"exp-1": [experiment] * 10, "exp-2": [experiment] * 10}) assert_rankings_plot(plot, ["exp-1", "exp-2"], with_avg=True) def test_unbalanced_experiments(self, monkeypatch): """Tests the regrets with avg of unbalanced experiments""" mock_experiment_with_random_to_pandas(monkeypatch, unbalanced=True) with create_experiment(config, trial_config, ["completed"]) as ( _, _, experiment, ): plot = rankings({"exp-1": [experiment] * 10, "exp-2": [experiment] * 10}) assert_rankings_plot(plot, ["exp-1", "exp-2"], with_avg=True, balanced=0) def test_ignore_uncompleted_statuses(self, monkeypatch): """Tests that uncompleted statuses are ignored""" mock_experiment_with_random_to_pandas( monkeypatch, status=[ "completed", "new", "reserved", "completed", "broken", "completed", "interrupted", "completed", ], ) with create_experiment(config, trial_config) as (_, _, experiment): plot = rankings([experiment]) assert_rankings_plot( plot, [f"{experiment.name}-v{experiment.version}"], balanced=4 ) def test_unsupported_order_key(self): """Tests that unsupported order keys are rejected""" with create_experiment(config, trial_config) as (_, _, experiment): with pytest.raises(ValueError): rankings([experiment], order_by="unsupported") @pytest.mark.usefixtures("version_XYZ") class TestRegret: """Tests the ``regret()`` method provided by the plotly backend""" def test_requires_argument(self): """Tests that the experiment data are required.""" with pytest.raises(ValueError): regret(None) def test_returns_plotly_object(self): """Tests that the plotly backend returns a plotly object""" with create_experiment(config, trial_config, ["completed"]) as ( _, _, experiment, ): plot = regret(experiment) assert type(plot) is plotly.graph_objects.Figure def test_graph_layout(self): """Tests the layout of the plot""" with create_experiment(config, trial_config, ["completed"]) as ( _, _, experiment, ): plot = regret(experiment) assert_regret_plot(plot) def test_experiment_worker_as_parameter(self): """Tests that ``Experiment`` is a valid parameter""" with create_experiment(config, trial_config, ["completed"]) as ( _, experiment, _, ): plot = regret(experiment) assert_regret_plot(plot) def test_ignore_uncompleted_statuses(self): """Tests that uncompleted statuses are ignored""" with create_experiment(config, trial_config) as (_, _, experiment): plot = regret(experiment) assert_regret_plot(plot) def test_unsupported_order_key(self): """Tests that unsupported order keys are rejected""" with create_experiment(config, trial_config) as (_, _, experiment): with pytest.raises(ValueError): regret(experiment, order_by="unsupported") @pytest.mark.usefixtures("version_XYZ") class TestRegrets: """Tests the ``regrets()`` method provided by the plotly backend""" def test_requires_argument(self): """Tests that the experiment data are required.""" with pytest.raises(ValueError): regrets(None) def test_returns_plotly_object(self, monkeypatch): """Tests that the plotly backend returns a plotly object""" mock_experiment_with_random_to_pandas(monkeypatch) with create_experiment(config, trial_config, ["completed"]) as ( _, _, experiment, ): plot = regrets([experiment]) assert type(plot) is plotly.graph_objects.Figure def test_graph_layout(self, monkeypatch): """Tests the layout of the plot""" mock_experiment_with_random_to_pandas(monkeypatch) with create_experiment(config, trial_config, ["completed"]) as ( _, _, experiment, ): plot = regrets([experiment]) assert_regrets_plot(plot, [f"{experiment.name}-v{experiment.version}"]) def test_list_of_experiments(self, monkeypatch): """Tests the regrets with list of experiments""" mock_experiment_with_random_to_pandas(monkeypatch) with create_experiment(config, trial_config, ["completed"]) as ( _, _, experiment, ): child = orion.client.create_experiment( experiment.name, branching={"branch_to": "child"} ) plot = regrets([experiment, child]) # Exps are sorted alphabetically by names. assert_regrets_plot( plot, [f"{exp.name}-v{exp.version}" for exp in [child, experiment]] ) def test_list_of_experiments_name_conflict(self, monkeypatch): """Tests the regrets with list of experiments with the same name""" mock_experiment_with_random_to_pandas(monkeypatch) with create_experiment(config, trial_config, ["completed"]) as ( _, _, experiment, ): child = orion.client.create_experiment( experiment.name, branching={"branch_to": experiment.name} ) assert child.name == experiment.name assert child.version == experiment.version + 1 plot = regrets([experiment, child]) # Exps are sorted alphabetically by names. assert_regrets_plot( plot, [f"{exp.name}-v{exp.version}" for exp in [experiment, child]] ) def test_dict_of_experiments(self, monkeypatch): """Tests the regrets with renamed experiments""" mock_experiment_with_random_to_pandas(monkeypatch) with create_experiment(config, trial_config, ["completed"]) as ( _, _, experiment, ): plot = regrets({"exp-1": experiment, "exp-2": experiment}) assert_regrets_plot(plot, ["exp-1", "exp-2"]) def test_dict_of_list_of_experiments(self, monkeypatch): """Tests the regrets with avg of experiments""" mock_experiment_with_random_to_pandas(monkeypatch) with create_experiment(config, trial_config, ["completed"]) as ( _, _, experiment, ): plot = regrets({"exp-1": [experiment] * 10, "exp-2": [experiment] * 10}) assert_regrets_plot(plot, ["exp-1", "exp-2"], with_avg=True) def test_unbalanced_experiments(self, monkeypatch): """Tests the regrets with avg of unbalanced experiments""" mock_experiment_with_random_to_pandas(monkeypatch, unbalanced=True) with create_experiment(config, trial_config, ["completed"]) as ( _, _, experiment, ): plot = regrets({"exp-1": [experiment] * 10, "exp-2": [experiment] * 10}) assert_regrets_plot(plot, ["exp-1", "exp-2"], with_avg=True, balanced=0) def test_ignore_uncompleted_statuses(self, monkeypatch): """Tests that uncompleted statuses are ignored""" mock_experiment_with_random_to_pandas( monkeypatch, status=[ "completed", "new", "reserved", "completed", "broken", "completed", "interrupted", "completed", ], ) with create_experiment(config, trial_config) as (_, _, experiment): plot = regrets([experiment]) assert_regrets_plot( plot, [f"{experiment.name}-v{experiment.version}"], balanced=4 ) def test_unsupported_order_key(self): """Tests that unsupported order keys are rejected""" with create_experiment(config, trial_config) as (_, _, experiment): with pytest.raises(ValueError): regrets([experiment], order_by="unsupported")
StarcoderdataPython
3419619
<reponame>pento-group/terran from terran.tracking.face import face_tracking # noqa
StarcoderdataPython
78996
<filename>board/viewmixins.py import logging from .models import Board class BoardContextMixin(object): logger = logging.getLogger(__name__) def dispatch(self, *args, **kwargs): self.board = Board.objects.get(slug=self.kwargs.get('slug')) self.block_size = self.board.block_size self.chunk_size = self.board.chunk_size return super(BoardContextMixin, self).dispatch(*args, **kwargs)
StarcoderdataPython
209927
import re class Lexer(object): def __init__(self, code): self.code = code def tokenize(self): tokens = [] code = self.code.split() code_len = 0 while code_len < len(code): word = code[code_len] if word == "var": tokens.append(["VARIABLE", word]) elif re.match('[a-z]', word) or re.match('[A-Z]', word) and word != 'var' and word !='showme': if word[-1] == '.': tokens.append(["IDENTIFIRE", word[0:len(word)-1]]) else: tokens.append(["IDENTIFIRE", word]) elif re.match('[0-9]',word): if word[-1]=='.': tokens.append(["INTEGER", word[0:len(word)-1]]) else: tokens.append(["INTEGER", word]) elif word in "+-*/%=@": tokens.append(["OPARETOR", word]) elif word == ",": tokens.append(["COMMA", word]) elif '"' in word: if word[-1] == '.': tokens.append(["STRING", word[1:len(word)-2]]) else: tokens.append(["STRING", word[1:len(word)-1]]) if word == '.': tokens.append(["STATEMENT_END", word]) elif word[-1] == '.': tokens.append(["STATEMENT_END", word[-1]]) elif word in "()[]": tokens.append(["BRACKET",word]) elif word == "~": tokens.append(["INOUT",word]) code_len = code_len+1 tokens.append(["EMPTY",0]) return tokens
StarcoderdataPython
9798590
<gh_stars>0 import logging from ssl import CertificateError import discord from aiohttp import ClientConnectorError from discord.ext.commands import BadArgument, Context, Converter log = logging.getLogger(__name__) class ValidPythonIdentifier(Converter): """ A converter that checks whether the given string is a valid Python identifier. This is used to have package names that correspond to how you would use the package in your code, e.g. `import package`. Raises `BadArgument` if the argument is not a valid Python identifier, and simply passes through the given argument otherwise. """ @staticmethod async def convert(ctx, argument: str): if not argument.isidentifier(): raise BadArgument(f"`{argument}` is not a valid Python identifier") return argument class ValidURL(Converter): """ Represents a valid webpage URL. This converter checks whether the given URL can be reached and requesting it returns a status code of 200. If not, `BadArgument` is raised. Otherwise, it simply passes through the given URL. """ @staticmethod async def convert(ctx, url: str): try: async with ctx.bot.http_session.get(url) as resp: if resp.status != 200: raise BadArgument( f"HTTP GET on `{url}` returned status `{resp.status_code}`, expected 200" ) except CertificateError: if url.startswith('https'): raise BadArgument( f"Got a `CertificateError` for URL `{url}`. Does it support HTTPS?" ) raise BadArgument(f"Got a `CertificateError` for URL `{url}`.") except ValueError: raise BadArgument(f"`{url}` doesn't look like a valid hostname to me.") except ClientConnectorError: raise BadArgument(f"Cannot connect to host with URL `{url}`.") return url class InfractionSearchQuery(Converter): """ A converter that checks if the argument is a Discord user, and if not, falls back to a string. """ @staticmethod async def convert(ctx, arg): try: maybe_snowflake = arg.strip("<@!>") return await ctx.bot.get_user_info(maybe_snowflake) except (discord.NotFound, discord.HTTPException): return arg class Subreddit(Converter): """ Forces a string to begin with "r/" and checks if it's a valid subreddit. """ @staticmethod async def convert(ctx, sub: str): sub = sub.lower() if not sub.startswith("r/"): sub = f"r/{sub}" resp = await ctx.bot.http_session.get( "https://www.reddit.com/subreddits/search.json", params={"q": sub} ) json = await resp.json() if not json["data"]["children"]: raise BadArgument( f"The subreddit `{sub}` either doesn't exist, or it has no posts." ) return sub class TagNameConverter(Converter): @staticmethod async def convert(ctx: Context, tag_name: str): def is_number(value): try: float(value) except ValueError: return False return True tag_name = tag_name.lower().strip() # The tag name has at least one invalid character. if ascii(tag_name)[1:-1] != tag_name: log.warning(f"{ctx.author} tried to put an invalid character in a tag name. " "Rejecting the request.") raise BadArgument("Don't be ridiculous, you can't use that character!") # The tag name is either empty, or consists of nothing but whitespace. elif not tag_name: log.warning(f"{ctx.author} tried to create a tag with a name consisting only of whitespace. " "Rejecting the request.") raise BadArgument("Tag names should not be empty, or filled with whitespace.") # The tag name is a number of some kind, we don't allow that. elif is_number(tag_name): log.warning(f"{ctx.author} tried to create a tag with a digit as its name. " "Rejecting the request.") raise BadArgument("Tag names can't be numbers.") # The tag name is longer than 127 characters. elif len(tag_name) > 127: log.warning(f"{ctx.author} tried to request a tag name with over 127 characters. " "Rejecting the request.") raise BadArgument("Are you insane? That's way too long!") return tag_name class TagContentConverter(Converter): @staticmethod async def convert(ctx: Context, tag_content: str): tag_content = tag_content.strip() # The tag contents should not be empty, or filled with whitespace. if not tag_content: log.warning(f"{ctx.author} tried to create a tag containing only whitespace. " "Rejecting the request.") raise BadArgument("Tag contents should not be empty, or filled with whitespace.") return tag_content
StarcoderdataPython
9707469
<gh_stars>100-1000 from uuid import uuid4 from datetime import datetime from typing import List, Optional, Union from pydbantic import DataBaseModel, PrimaryKey class Department(DataBaseModel): department_id: str name: str company: str is_sensitive: bool = False positions: List[Optional['Positions']] = [] class Positions(DataBaseModel): position_id: str name: str department: Department = None employees: List[Optional['Employee']] = [] class EmployeeInfo(DataBaseModel): #__renamed__= [{'old_name': 'first_name', 'new_name': 'first_names'}] ssn: str first_name: str last_name: str address: str address2: Optional[str] city: Optional[str] zip: Optional[int] new: Optional[str] employee: Optional[Union['Employee', dict]] = None class Employee(DataBaseModel): employee_id: str = PrimaryKey() employee_info: Optional[EmployeeInfo] = None position: List[Optional[Positions]] = [] salary: float is_employed: bool date_employed: Optional[str] def time_now(): return datetime.now().isoformat() def get_uuid4(): return str(uuid4()) class Coordinate(DataBaseModel): id: str = PrimaryKey(default=get_uuid4) lat_long: tuple journeys: List[Optional["Journey"]] = [] class Journey(DataBaseModel): trip_id: str = PrimaryKey(default=get_uuid4) waypoints: List[Optional[Coordinate]] = []
StarcoderdataPython
1752211
<reponame>forestGzh/VTK #!/usr/bin/env python import vtk from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() vtk.vtkMultiThreader.SetGlobalMaximumNumberOfThreads(1) reader = vtk.vtkImageReader() reader.SetDataByteOrderToLittleEndian() reader.SetDataExtent(0,63,0,63,1,93) reader.SetDataSpacing(3.2,3.2,1.5) reader.SetFilePrefix("" + str(VTK_DATA_ROOT) + "/Data/headsq/quarter") reader.SetDataMask(0x7fff) rangeStart = 0.0 rangeEnd = 0.2 LUT = vtk.vtkLookupTable() LUT.SetTableRange(0,1800) LUT.SetSaturationRange(1,1) LUT.SetHueRange(rangeStart,rangeEnd) LUT.SetValueRange(1,1) LUT.SetAlphaRange(1,1) LUT.Build() # The prototype of this function has # arguments so that the code can be # translated to python for testing. def changeLUT (a=0,b=0,__vtk__temp0=0,__vtk__temp1=0): global rangeStart, rangeEnd rangeStart = expr.expr(globals(), locals(),["rangeStart","+","0.1"]) rangeEnd = expr.expr(globals(), locals(),["rangeEnd","+","0.1"]) if (rangeEnd > 1.0): rangeStart = 0.0 rangeEnd = 0.2 pass LUT.SetHueRange(rangeStart,rangeEnd) LUT.Build() mapToRGBA = vtk.vtkImageMapToColors() mapToRGBA.SetInputConnection(reader.GetOutputPort()) mapToRGBA.SetOutputFormatToRGBA() mapToRGBA.SetLookupTable(LUT) #mapToRGBA.AddObserver("EndEvent",changeLUT) imageStreamer = vtk.vtkImageDataStreamer() imageStreamer.SetInputConnection(mapToRGBA.GetOutputPort()) imageStreamer.SetNumberOfStreamDivisions(8) # make sure we get the correct translator. imageStreamer.UpdateInformation() imageStreamer.GetExtentTranslator().SetSplitModeToBlock() # set the window/level to 255.0/127.5 to view full range viewer = vtk.vtkImageViewer() viewer.SetInputConnection(imageStreamer.GetOutputPort()) viewer.SetColorWindow(255.0) viewer.SetColorLevel(127.5) viewer.SetZSlice(50) viewer.Render() #make interface viewer.Render() # --- end of script --
StarcoderdataPython
1986549
<reponame>dlitz/vimfiles<filename>pack/vendor/start/taghelper.vim/pythonx/taghelper_c.py def parse(buffer, tags): curtag = None last_unindented_line = '' last_unindented_line_number = 1 for n, line in enumerate(buffer, 1): line = line.rstrip() # For now we assume a particular C style: # type # function_name(... # ...) # { # ... # } # this should also work: # type function_name(... # ...) # { # ... # } # and now I'm trying to add support for # type function_name(...) { # ... # } if line[:1] == '{': if '(' in last_unindented_line: name = last_unindented_line.partition('(')[0].split()[-1] name = name.strip('*') if curtag and curtag.lastline is None: curtag.lastline = last_unindented_line_number - 1 curtag = tags.add(name, last_unindented_line_number) last_unindented_line = '' if line[:1] == '}': if curtag and curtag.lastline is None: curtag.lastline = n if line and (line[0].isalpha() or line[0] == '_'): last_unindented_line = line last_unindented_line_number = n if line.endswith(') {'): if '(' in last_unindented_line: name = last_unindented_line.partition('(')[0].split()[-1] name = name.strip('*') if curtag and curtag.lastline is None: curtag.lastline = last_unindented_line_number - 1 curtag = tags.add(name, last_unindented_line_number) last_unindented_line = '' if curtag and curtag.lastline is None: curtag.lastline = n
StarcoderdataPython
6474069
class RsDnsError(RuntimeError): def __init__(self, error): self.error_msg = "" try: for message in error['validationErrors']['messages']: self.error_msg += message except KeyError: self.error_msg += "... (did not understand the RsDNS response)." super(RsDnsError, self).__init__(self.error_msg) def __str__(self): return self.message class FutureResource(object): """Polls a callback url to return a resource.""" def __init__(self, manager, jobId, callbackUrl, status, **kwargs): self.manager = manager self.jobId = jobId self.callbackUrl = unicode(callbackUrl) self.result = None management_url = unicode(self.manager.api.client.management_url) if self.callbackUrl.startswith(management_url): self.callbackUrl = self.callbackUrl[len(management_url):] def call_callback(self): return self.manager.api.client.get(self.callbackUrl + "?showDetails=true") def poll(self): if not self.result: resp, body = self.call_callback() if resp.status == 202: return None if resp.status == 200: if body['status'] == 'ERROR': raise RsDnsError(body['error']) elif body['status'] != 'COMPLETED': return None resp_list = body['response'][self.response_list_name()] self.result = self.manager.create_from_list(resp_list) return self.result @property def ready(self): return (self.result or self.poll()) is not None @property def resource(self): return self.result or self.poll()
StarcoderdataPython
6502546
#! /usr/bin/env python3 # # Copyright 2018 California Institute of Technology # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # ISOFIT: Imaging Spectrometer Optimal FITting # Author: <NAME>, <EMAIL> # import scipy as s from common import recursive_replace, eps from copy import deepcopy from scipy.linalg import det, norm, pinv, sqrtm, inv, block_diag from importlib import import_module from scipy.interpolate import interp1d from instrument import Instrument # Supported RT modules, filenames, and class names RT_models = [('modtran_radiative_transfer', 'rt_modtran', 'ModtranRT'), ('libradtran_radiative_transfer', 'rt_libradtran', 'LibRadTranRT'), ('planetary_radiative_transfer', 'rt_planetary', 'PlanetaryRT'), ('uplooking_radiative_transfer', 'rt_uplook', 'UplookRT'), ('sixs_radiative_transfer', 'rt_6s', 'SixSRT')] # Supported surface modules, filenames, and class names surface_models = [('surface', 'surf', 'Surface'), ('multicomponent_surface', 'surf_multicomp', 'MultiComponentSurface'), ('emissive_surface', 'surf_emissive', 'MixBBSurface'), ('cat_surface', 'surf_cat', 'CATSurface'), ('glint_surface', 'surf_glint', 'GlintSurface'), ('iop_surface', 'surf_iop', 'IOPSurface')] class ForwardModel: def __init__(self, config): '''ForwardModel contains all the information about how to calculate radiance measurements at a specific spectral calibration, given a state vector. It also manages the distributions of unretrieved, unknown parameters of the state vector (i.e. the S_b and K_b matrices of Rodgers et al.''' self.instrument = Instrument(config['instrument']) self.n_meas = self.instrument.n_chan # Build the radiative transfer model self.RT = None for key, module, cname in RT_models: if key in config: self.RT = getattr(import_module(module), cname)(config[key]) if self.RT is None: raise ValueError('Must specify a valid radiative transfer model') # Build the surface model self.surface = None for key, module, cname in surface_models: if key in config: self.surface = getattr( import_module(module), cname)(config[key]) if self.surface is None: raise ValueError('Must specify a valid surface model') # Set up passthrough option bounds, scale, init, statevec = [], [], [], [] # Build state vector for each part of our forward model for name in ['surface', 'RT', 'instrument']: obj = getattr(self, name) inds = len(statevec) + s.arange(len(obj.statevec), dtype=int) setattr(self, 'idx_%s' % name, inds) for b in obj.bounds: bounds.append(deepcopy(b)) for c in obj.scale: scale.append(deepcopy(c)) for v in obj.init: init.append(deepcopy(v)) for v in obj.statevec: statevec.append(deepcopy(v)) self.bounds = tuple(s.array(bounds).T) self.scale = s.array(scale) self.init = s.array(init) self.statevec = statevec self.nstate = len(self.statevec) # Capture unmodeled variables bvec, bval = [], [] for name in ['RT', 'instrument', 'surface']: obj = getattr(self, name) inds = len(bvec) + s.arange(len(obj.bvec), dtype=int) setattr(self, '%s_b_inds' % name, inds) for b in obj.bval: bval.append(deepcopy(b)) for v in obj.bvec: bvec.append(deepcopy(v)) self.bvec = s.array(bvec) self.nbvec = len(self.bvec) self.bval = s.array(bval) self.Sb = s.diagflat(pow(self.bval, 2)) return def out_of_bounds(self, x): """Is state vector inside the bounds?""" x_RT = x[self.idx_RT] x_surface = x[self.idx_surface] bound_lwr = self.bounds[0] bound_upr = self.bounds[1] return any(x_RT >= (bound_upr[self.idx_RT] - eps*2.0)) or \ any(x_RT <= (bound_lwr[self.idx_RT] + eps*2.0)) def xa(self, x, geom): """Calculate the prior mean of the state vector (the concatenation of state vectors for the surface, Radiative Transfer model, and instrument). Note that the surface prior mean depends on the current state - this is so we can calculate the local prior.""" x_surface = x[self.idx_surface] xa_surface = self.surface.xa(x_surface, geom) xa_RT = self.RT.xa() xa_instrument = self.instrument.xa() return s.concatenate((xa_surface, xa_RT, xa_instrument), axis=0) def Sa(self, x, geom): """Calculate the prior covariance of the state vector (the concatenation of state vectors for the surface and Radiative Transfer model). Note that the surface prior depends on the current state - this is so we can calculate the local linearized answer.""" x_surface = x[self.idx_surface] Sa_surface = self.surface.Sa(x_surface, geom)[:, :] Sa_RT = self.RT.Sa()[:, :] Sa_instrument = self.instrument.Sa()[:, :] return block_diag(Sa_surface, Sa_RT, Sa_instrument) def calc_rdn(self, x, geom, rfl=None, Ls=None): """Calculate the high-resolution radiance, permitting overrides Project to top of atmosphere and translate to radiance""" x_surface, x_RT, x_instrument = self.unpack(x) if rfl is None: rfl = self.surface.calc_rfl(x_surface, geom) if Ls is None: Ls = self.surface.calc_Ls(x_surface, geom) rfl_hi = self.upsample(self.surface.wl, rfl) Ls_hi = self.upsample(self.surface.wl, Ls) return self.RT.calc_rdn(x_RT, rfl_hi, Ls_hi, geom) def calc_meas(self, x, geom, rfl=None, Ls=None): """Calculate the model observation at instrument wavelengths""" x_surface, x_RT, x_instrument = self.unpack(x) rdn_hi = self.calc_rdn(x, geom, rfl, Ls) return self.instrument.sample(x_instrument, self.RT.wl, rdn_hi) def calc_Ls(self, x, geom): """calculate the surface emission.""" return self.surface.calc_Ls(x[self.idx_surface], geom) def calc_rfl(self, x, geom): """calculate the surface reflectance""" return self.surface.calc_rfl(x[self.idx_surface], geom) def calc_lamb(self, x, geom): """calculate the Lambertian surface reflectance""" return self.surface.calc_lamb(x[self.idx_surface], geom) def Seps(self, x, meas, geom): """Calculate the total uncertainty of the observation, including both the instrument noise and the uncertainty due to unmodeled variables. This is the S_epsilon matrix of Rodgers et al.""" Kb = self.Kb(x, geom) Sy = self.instrument.Sy(meas, geom) return Sy + Kb.dot(self.Sb).dot(Kb.T) def K(self, x, geom): """Derivative of observation with respect to state vector. This is the concatenation of jacobians with respect to parameters of the surface and radiative transfer model.""" # Unpack state vector x_surface, x_RT, x_instrument = self.unpack(x) # Get partials of reflectance WRT state, and upsample rfl = self.surface.calc_rfl(x_surface, geom) drfl_dsurface = self.surface.drfl_dsurface(x_surface, geom) rfl_hi = self.upsample(self.surface.wl, rfl) drfl_dsurface_hi = self.upsample(self.surface.wl, drfl_dsurface.T).T # Get partials of emission WRT state, and upsample Ls = self.surface.calc_Ls(x_surface, geom) dLs_dsurface = self.surface.dLs_dsurface(x_surface, geom) Ls_hi = self.upsample(self.surface.wl, Ls) dLs_dsurface_hi = self.upsample(self.surface.wl, dLs_dsurface.T).T # Derivatives of RTM radiance drdn_dRT, drdn_dsurface = self.RT.drdn_dRT(x_RT, x_surface, rfl_hi, drfl_dsurface_hi, Ls_hi, dLs_dsurface_hi, geom) # Derivatives of measurement, avoiding recalculation of rfl, Ls dmeas_dsurface = self.instrument.sample(x_instrument, self.RT.wl, drdn_dsurface.T).T dmeas_dRT = self.instrument.sample(x_instrument, self.RT.wl, drdn_dRT.T).T rdn_hi = self.calc_rdn(x, geom, rfl=rfl, Ls=Ls) dmeas_dinstrument = self.instrument.dmeas_dinstrument(x_instrument, self.RT.wl, rdn_hi) # Put it all together K = s.zeros((self.n_meas, self.nstate), dtype=float) K[:, self.idx_surface] = dmeas_dsurface K[:, self.idx_RT] = dmeas_dRT K[:, self.idx_instrument] = dmeas_dinstrument return K def Kb(self, x, geom): """Derivative of measurement with respect to unmodeled & unretrieved unknown variables, e.g. S_b. This is the concatenation of Jacobians with respect to parameters of the surface, radiative transfer model, and instrument. Currently we only treat uncertainties in the instrument and RT model.""" # Unpack state vector x_surface, x_RT, x_instrument = self.unpack(x) # Get partials of reflectance and upsample rfl = self.surface.calc_rfl(x_surface, geom) rfl_hi = self.upsample(self.surface.wl, rfl) Ls = self.surface.calc_Ls(x_surface, geom) Ls_hi = self.upsample(self.surface.wl, Ls) rdn_hi = self.calc_rdn(x, geom, rfl=rfl, Ls=Ls) drdn_dRTb = self.RT.drdn_dRTb(x_RT, rfl_hi, Ls_hi, geom) dmeas_dRTb = self.instrument.sample(x_instrument, self.RT.wl, drdn_dRTb.T).T dmeas_dinstrumentb = self.instrument.dmeas_dinstrumentb( x_instrument, self.RT.wl, rdn_hi) Kb = s.zeros((self.n_meas, self.nbvec), dtype=float) Kb[:, self.RT_b_inds] = dmeas_dRTb Kb[:, self.instrument_b_inds] = dmeas_dinstrumentb return Kb def summarize(self, x, geom): """State vector summary""" x_surface, x_RT, x_instrument = self.unpack(x) return self.surface.summarize(x_surface, geom) + \ ' ' + self.RT.summarize(x_RT, geom) + \ ' ' + self.instrument.summarize(x_instrument, geom) def calibration(self, x): """Calculate measured wavelengths and fwhm""" x_inst = x[self.idx_instrument] return self.instrument.calibration(x_inst) def upsample(self, wl, q): """Linear interpolation to RT wavelengths""" if q.ndim > 1: q2 = [] for qi in q: p = interp1d(wl, qi, fill_value='extrapolate') q2.append(p(self.RT.wl)) return s.array(q2) else: p = interp1d(wl, q, fill_value='extrapolate') return p(self.RT.wl) def unpack(self, x): """Unpack the state vector in appropriate index ordering""" x_surface = x[self.idx_surface] x_RT = x[self.idx_RT] x_instrument = x[self.idx_instrument] return x_surface, x_RT, x_instrument def reconfigure(self, config_surface, config_rt, config_instrument): """Reconfigure the components of the forward model. This could update components' initialization values and/or priors, or (for the case of a defined surface reflectance) the surface reflectance file itself.""" self.surface.reconfigure(config_surface) self.RT.reconfigure(config_rt) self.instrument.reconfigure(config_instrument) self.init = s.concatenate((self.surface.init, self.RT.init, self.instrument.init))
StarcoderdataPython
1668226
<filename>sgm/plot.py import argparse import datetime import os import matplotlib.pyplot as plt import pandas as pd import seaborn as sns def returns_v_cleanup_steps(df): # Hack for current planner names df.loc[df["Planner"] == "SGM", "Planner"] = "Sparse Graphical Memory (ours)" df.loc[df["Planner"] == "SoRB", "Planner"] = "SoRB + Our Proposed Cleanup" ax = sns.lineplot(x="Cleanup Steps", y="Success Rate", hue="Planner", style="Planner", data=df, palette="viridis") ax.legend(loc="upper right", bbox_to_anchor=(0.98, 0.8)) ax.set_title("How Performance Improves with Cleaning") timestamp = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') output_directory = os.path.join(os.getcwd(), "plots", f"returns_v_cleanup_steps_{timestamp}") if not os.path.isdir(output_directory): os.makedirs(output_directory) output_file = os.path.join(output_directory, "returns_v_cleanup_steps.png") fig = ax.get_figure() fig.savefig(output_file, dpi=200) plt.close() def cleanup_timing(df, max_cleanup_steps=100000): df["Time per Action Choice"] = df["Time to Choose Action"] / df["Action Attempts"] df = df.loc[ (0 < df["Cleanup Steps"]) & (df["Cleanup Steps"] <= max_cleanup_steps), ["Planner", "Time to Clean Graph", "Time per Action Choice"]] print(df.groupby(["Planner"]).describe()) def get_combined_dataframe(directories): df = pd.DataFrame() for directory in directories: filename = os.path.join(os.getcwd(), directory, "evaluation.csv") to_append = pd.read_csv(filename) df = df.append(to_append, ignore_index=True) return df if __name__ == "__main__": parser = argparse.ArgumentParser(description="Plot experimental results") parser.add_argument("logdirs", type=str, nargs="+", help="The directories of the experiment logs") parser.add_argument("--returns_v_cleanup_steps", dest="returns_v_cleanup_steps", action="store_true", help="Plot the evaluation return versus the number of environment cleanup steps") parser.add_argument("--cleanup_timing", dest="cleanup_timing", action="store_true", help="Report the amount of time to clean the graph") args = parser.parse_args() df = get_combined_dataframe(args.logdirs) if args.returns_v_cleanup_steps: returns_v_cleanup_steps(df) if args.cleanup_timing: cleanup_timing(df)
StarcoderdataPython
129917
<reponame>jachallbound/kmeans_python<filename>src/GaussianDistributionGenerator.py import numpy as np import numpy.random as npr def generate_gaussian_data(D, ndim, samples, priors = None, means = None, covs = None ): """Generate D N-dimension Gaussian Distributions of size samples. Parameters: --- D: *int* Amount of IID Gaussian clusters to create. When used in K-Means, should probably be equal to K. ndim: *int* Dimensionality of data. Returned data with be ndim arrays of sample data (in a matrix) samples: *int* Amount of data samples per Gaussian cluster. priors: *array_like* D element array of priors of corresponding Gaussian distributions. Default: random values from a Dirichlet distribution. means: *array_like* D by ndim matrix of means. Default: rand(ndim) values times randint(1,high=10) (D times) covs = *array_like* D by ndim by ndim matrix of covariances. Default: rand(ndim,ndim) values times randint(1,high=3) (D times) This can lead to 'not positive-semidefinite' covs for high ndim. Returns: --- gaussian_dict: *dict* Dictionary of data, labels, and Gaussian distribution parameters. """ "Generate distribution parameters if they weren't passed" if priors == None: priors = npr.dirichlet(np.ones(D), size=1) if means == None: means = np.array([npr.rand(ndim)*npr.randint(10,high=200) for i in range(D)]) if covs == None: covs = np.array([npr.rand(ndim,ndim)*npr.randint(10, high=30) for i in range(D)]) "Fix not positive-semidefinite covariance matrices" "https://stackoverflow.com/questions/41515522/numpy-positive-semi-definite-warning" for d in range(D): min_eigen_value = np.min(np.real(np.linalg.eigvals(covs[d, ]))) if min_eigen_value < 0: covs[d, ] -= 10*min_eigen_value * np.eye(*covs[d, ].shape) "Distribution Parameters" # Number of means to search for, also number of distributions to create priors_csum = np.r_[0, np.cumsum(priors)] pd = npr.rand(samples) # Decision vector for choosing observed data based on priors "Data matrix" data_D = np.zeros((D,ndim,samples)) # All distribution data data = np.zeros((ndim,samples)) # Observation data labels = np.zeros((samples), dtype=int) "Generate K Gaussian Distributions" for d in range(D): data_D[d, ] = npr.multivariate_normal(means[d, ], covs[d, ], size=samples).T observation = np.logical_and(pd>priors_csum[d], pd<=priors_csum[d+1]) data = np.where(observation, data_D[d, ], data) labels = np.where(observation, d, labels) gaussian_dict = {'data': data, 'labels': labels, 'data_D': data_D, 'priors': priors, 'means': means, 'covs': covs} return gaussian_dict
StarcoderdataPython
8095169
"""Trivial redis store for domains. Will be used to store a 7-day "sliding window" count of domains appearing in delta reports. Reads from Heroku Dataclip of domains in delta reports, writes to Redis. Dataclip is: select distinct delta_value->>0 as domain from ( select json_array_elements(data.value::json->'new') as delta_value from data union all select json_array_elements(data.value::json->'updated') as delta_value from data union all select json_array_elements(data.value::json->'deleted') as delta_value from data ) as delta_values where delta_value->>0 != 'null' Note: The window is a bit fuzzy on the definition of "sliding". If the domain does not change in 7 days, then it will be removed, so would be considered not noisy. In the first 7 days it must change "threshold" times to be noisy then after that it only needs to change once every 7 days to remain noisy. This is a form of hysteresis caused by the simplicity I want to use for redis storage. """ import datetime import os import redis from dnstwister import dnstwist EXPIRY = int(datetime.timedelta(days=7).total_seconds()) class RedisStatsStore(object): """The store for the statistics.""" def __init__(self): self._conn = None @property def r_conn(self): """I am a redis connection!!!""" if self._conn is None: url = os.getenv('REDIS_URL') if url is None: raise Exception('REDIS connection configuration not set!') self._conn = redis.from_url(url) return self._conn def note(self, domain): """Record that the domains have appeared in a delta report. We increment each time we note, and move the expiry forward to the chosen number of seconds. That gives us a sliding window of changes over the period. """ if dnstwist.is_valid_domain(domain): pipe = self.r_conn.pipeline() pipe.incr(domain) pipe.expire(domain, EXPIRY) pipe.execute() def is_noisy(self, domain, threshold=4): """A domain is noisy if it changes more than threshold times over the expiry window. Domains not in the redis store return None, which becomes threshold, so that they are always false. """ score = self.r_conn.get(domain) return int(score or threshold) > threshold
StarcoderdataPython
11273670
#!/bin/python3 import math import os import random import re import sys # # Complete the 'miniMaxSum' function below. # # The function accepts INTEGER_ARRAY arr as parameter. # def miniMaxSum(arr): # Write your code here sum = 0 for i in arr: sum+= i print(sum-max(arr), sum-min(arr)) if __name__ == '__main__': arr = list(map(int, input().rstrip().split())) miniMaxSum(arr)
StarcoderdataPython
3476769
<reponame>ldtri0209/robotframework<filename>atest/testdata/test_libraries/dynamic_libraries/DynamicLibraryWithoutArgspec.py class DynamicLibraryWithoutArgspec(object): def get_keyword_names(self): return [name for name in dir(self) if name.startswith('do_')] def run_keyword(self, name, args): return getattr(self, name)(*args) def do_something(self, x): print x def do_something_else(self, x, y=0): print 'x: %s, y: %s' % (x, y) def do_something_third(self, a, b=2, c=3): print a, b, c
StarcoderdataPython
12827874
# -*- coding: utf-8 -*- # snapshottest: v1 - https://goo.gl/zC4yUc from __future__ import unicode_literals from snapshottest import Snapshot snapshots = Snapshot() snapshots["test_weather_route_payload_errors Missing payload"] = { "detail": [ { "loc": ["body", "lat"], "msg": "field required", "type": "value_error.missing", }, { "loc": ["body", "lon"], "msg": "field required", "type": "value_error.missing", }, ] } snapshots["test_weather_route_payload_errors Incorrect payload type"] = { "detail": [ { "loc": ["body", "lat"], "msg": "value is not a valid float", "type": "type_error.float", }, { "ctx": {"limit_value": 180.0}, "loc": ["body", "lon"], "msg": "ensure this value is less than or equal to 180.0", "type": "value_error.number.not_le", }, ] } snapshots["test_custom_route_definitions Custom route definition"] = { "detail": [ { "loc": ["query", "vendor"], "msg": "field required", "type": "value_error.missing", }, { "loc": ["header", "auth-header"], "msg": "field required", "type": "value_error.missing", }, ] }
StarcoderdataPython
340555
<filename>rtamt/node/ltl/since.py from rtamt.node.binary_node import BinaryNode class Since(BinaryNode): """A class for storing STL Since nodes Inherits TemporalNode """ def __init__(self, child1, child2): """Constructor for Since node Parameters: child1 : stl.Node child2 : stl.Node """ super(Since, self).__init__(child1, child2) self.in_vars = child1.in_vars + child2.in_vars self.out_vars = child1.out_vars + child2.out_vars self.name = '(' + child1.name + ')since(' + child2.name + ')'
StarcoderdataPython
1983203
import os import raven from .base import * # noqa ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', '').split(' ') DEBUG = False # Persistent database connections if os.environ.get('DATABASE_CONN_MAX_AGE'): DATABASES['default']['CONN_MAX_AGE'] = int(os.environ.get('DATABASE_CONN_MAX_AGE')) # Avoid server side cursors with pgbouncer if os.environ.get('DATABASE_PGBOUNCER'): DATABASES['default']['DISABLE_SERVER_SIDE_CURSORS'] = True # Use cached templates in production TEMPLATES[0]['APP_DIRS'] = False TEMPLATES[0]['OPTIONS']['loaders'] = [ ( 'django.template.loaders.cached.Loader', [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ] ), ] # SSL required for session/CSRF cookies CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True # Improve password security to a reasonable bare minimum AUTH_PASSWORD_VALIDATORS = [ {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'}, {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'}, {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'}, {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'}, ] # Add more raven data to help diagnose bugs RAVEN_CONFIG = { 'release': raven.fetch_git_sha(BASE_DIR), } # Elastic APM if os.environ.get('ELASTIC_APM_SERVER_URL'): INSTALLED_APPS += [ 'elasticapm.contrib.django.apps.ElasticAPMConfig', ] MIDDLEWARE = [ 'elasticapm.contrib.django.middleware.TracingMiddleware', ] + MIDDLEWARE # Cache backed sessions for optimum performance SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'
StarcoderdataPython
5157827
''' Created on 12.12.2020 MIT License Copyright (c) 2020 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. @autor: <NAME>, Mindscan ''' import os import json import time import uuid as uid from de.mindscan.cheaplithium.datamodel.consts import * # @UnusedWildImport class KnowledgeBaseArticles(object): ''' classdocs ''' def __init__(self, knowledge_dir: str): ''' Constructor ''' self.__datamodel_directory = knowledge_dir self.__inMemoryDatabase = {} def _create_article_internal(self, pagetitle:str, pagecontent:str, pagesummary:str): kba_uuid = str(uid.uuid4()) article = { KBA_UUID: 'KBA_'+kba_uuid, KBA_PAGETITLE: pagetitle, KBA_PAGESUMMARY: pagesummary, KBA_PAGECONTENT: pagecontent, KBA_CREATED: str(time.time()), KBA_MODIFIED: "", KBA_REVISION: 1 } return article, kba_uuid # TODO: should be a separate backend def _save_article_by_uuid(self, kba_uuid): if kba_uuid not in self.__inMemoryDatabase: return jsonfilepath = self.__datamodel_directory + kba_uuid + '.json' with open(jsonfilepath,"w") as json_target_file: json.dump(self.__inMemoryDatabase[kba_uuid], json_target_file,indent=2) # TODO: should be a separate backend def _load_article_by_uuid(self, kba_uuid): jsonfilepath = self.__datamodel_directory + kba_uuid + '.json' if os.path.isfile(jsonfilepath): with open(jsonfilepath) as json_source_file: tmp_article = json.load(json_source_file) self.__inMemoryDatabase[kba_uuid] = tmp_article return tmp_article else: return None # TODO: should be a separate backend def load_all_acrticles(self): for file in os.listdir(self.__datamodel_directory): if str(file).endswith(".json"): uuid, _ = os.path.splitext(file) self._load_article_by_uuid(uuid) def insert_article(self, pagetitle:str, pagecontent:str, pagesummary:str): article, kba_uuid = self._create_article_internal(pagetitle, pagecontent, pagesummary) self.__inMemoryDatabase[kba_uuid] = article self._save_article_by_uuid(kba_uuid) return article, kba_uuid def select_article_by_uuid(self, kba_uuid:str): if kba_uuid not in self.__inMemoryDatabase: article = self._load_article_by_uuid(kba_uuid) if article is not None: return article else: article, _ = self._create_article_internal("Unknown title / Unknown article", "This knowledgebase article doesn't exist. No such UUID in knowledge_base.", "Error retrieving article content") return article return self.__inMemoryDatabase[kba_uuid] def update_article_where_uuid(self, kba_uuid:str, pagetitle:str, pagecontent:str, pagesummary:str ): # this mus exist either on disk or in memeory because otherwise an attack with random uuids numbers will fill # the disk space and the memory (Denial of Service) article = self.select_article_by_uuid(kba_uuid) article[KBA_PAGETITLE] = pagetitle article[KBA_PAGECONTENT] = pagecontent article[KBA_PAGESUMMARY] = pagesummary article[KBA_REVISION] = 1 + article[KBA_REVISION] article[KBA_MODIFIED] = str(time.time()) self.__inMemoryDatabase[kba_uuid] = article self._save_article_by_uuid(kba_uuid) return article, kba_uuid def select_all_from_article(self): result_list = [] for key, value in self.__inMemoryDatabase.items(): result_list.append({ KBA_UUID : key, KBA_PAGETITLE : value[KBA_PAGETITLE], KBA_REVISION : value[KBA_REVISION], KBA_PAGESUMMARY : value[KBA_PAGESUMMARY], KBA_CREATED : value[KBA_CREATED], KBA_MODIFIED : value[KBA_MODIFIED] }); # TODO: order by pagetitle return {'result':result_list}
StarcoderdataPython
92963
from typing import Optional, List from seedwork.domain.entities import Aggregate from seedwork.domain.value_objects import UUID from modules.iam.domain.value_objects import Session ANONYMOUS_ID = UUID("00000000-0000-0000-0000-000000000000") class User(Aggregate): id: UUID username: str email: str = "" hashed_password: str = "" first_name: Optional[str] = "" last_name: Optional[str] = "" def change_main_attributes( self, username: str = None, first_name: str = None, last_name: str = None, email: str = None, ): if username: self.username = username if first_name: self.first_name = first_name if last_name: self.last_name = last_name if email: self.email = email def activate(self): # TODO: maybe later ... def deactivate(self): # TODO: maybe later ... def is_disabled(self): return False def is_anonymous(self): return self.id == ANONYMOUS_ID def is_active(self): return not self.is_anonymous() and not self.is_disabled() @classmethod def Anonymous(cls): return User( id=ANONYMOUS_ID, username="anonymous", )
StarcoderdataPython
6645387
import os import sys sys.path.append("/data/luowei/MMIN") # print(sys.path) import json from typing import List import torch import numpy as np import h5py from torch.nn.utils.rnn import pad_sequence from torch.nn.utils.rnn import pack_padded_sequence from data.base_dataset import BaseDataset class MultimodalDataset(BaseDataset): @staticmethod def modify_commandline_options(parser, isTrain=None): parser.add_argument('--cvNo', type=int, help='which cross validation set') parser.add_argument('--A_type', type=str, help='which audio feat to use') parser.add_argument('--V_type', type=str, help='which visual feat to use') parser.add_argument('--L_type', type=str, help='which lexical feat to use') parser.add_argument('--output_dim', type=int, help='how many label types in this dataset') parser.add_argument('--norm_method', type=str, choices=['utt', 'trn'], help='how to normalize input comparE feature') return parser def __init__(self, opt, set_name): ''' IEMOCAP dataset reader set_name in ['trn', 'val', 'tst'] ''' super().__init__(opt) # record & load basic settings cvNo = opt.cvNo self.set_name = set_name pwd = os.path.abspath(__file__) pwd = os.path.dirname(pwd) config = json.load(open(os.path.join(pwd, 'config', 'IEMOCAP_config.json'))) self.norm_method = opt.norm_method # load feature self.A_type = opt.A_type self.all_A = h5py.File(os.path.join(config['feature_root'], 'A', f'{self.A_type}.h5'), 'r') if self.A_type == 'comparE': self.mean_std = h5py.File(os.path.join(config['feature_root'], 'A', 'comparE_mean_std.h5'), 'r') self.mean = torch.from_numpy(self.mean_std[str(cvNo)]['mean'][()]).unsqueeze(0).float() self.std = torch.from_numpy(self.mean_std[str(cvNo)]['std'][()]).unsqueeze(0).float() self.V_type = opt.V_type self.all_V = h5py.File(os.path.join(config['feature_root'], 'V', f'{self.V_type}.h5'), 'r') self.L_type = opt.L_type self.all_L = h5py.File(os.path.join(config['feature_root'], 'L', f'{self.L_type}.h5'), 'r') # load target label_path = os.path.join(config['target_root'], f'{cvNo}', f"{set_name}_label.npy") int2name_path = os.path.join(config['target_root'], f'{cvNo}', f"{set_name}_int2name.npy") self.label = np.load(label_path) self.label = np.argmax(self.label, axis=1) self.int2name = np.load(int2name_path) # in aligned dataset, you should move out Ses03M_impro03_M001 # if 'Ses03M_impro03_M001' in self.int2name: # idx = self.int2name.index('Ses03M_impro03_M001') # self.int2name.pop(idx) # self.label = np.delete(self.label, idx, axis=0) self.manual_collate_fn = True def __getitem__(self, index): int2name = self.int2name[index][0].decode() label = torch.tensor(self.label[index]) # process A_feat A_feat = torch.from_numpy(self.all_A[int2name][()]).float() if self.A_type == 'comparE': A_feat = self.normalize_on_utt(A_feat) if self.norm_method == 'utt' else self.normalize_on_trn(A_feat) # process V_feat V_feat = torch.from_numpy(self.all_V[int2name][()]).float() # process L_feat L_feat = torch.from_numpy(self.all_L[int2name][()]).float() return { 'A_feat': A_feat, 'V_feat': V_feat, 'L_feat': L_feat, 'label': label, 'int2name': int2name } def __len__(self): return len(self.label) def normalize_on_utt(self, features): mean_f = torch.mean(features, dim=0).unsqueeze(0).float() std_f = torch.std(features, dim=0).unsqueeze(0).float() std_f[std_f == 0.0] = 1.0 features = (features - mean_f) / std_f return features def normalize_on_trn(self, features): features = (features - self.mean) / self.std return features def collate_fn(self, batch): A = [sample['A_feat'] for sample in batch] V = [sample['V_feat'] for sample in batch] L = [sample['L_feat'] for sample in batch] lengths = torch.tensor([len(sample) for sample in A]).long() # 填充句子到相同长度,例如 A = pad_sequence(A, batch_first=True, padding_value=0) V = pad_sequence(V, batch_first=True, padding_value=0) L = pad_sequence(L, batch_first=True, padding_value=0) label = torch.tensor([sample['label'] for sample in batch]) int2name = [sample['int2name'] for sample in batch] return { 'A_feat': A, 'V_feat': V, 'L_feat': L, 'label': label, 'lengths': lengths, 'int2name': int2name } if __name__ == '__main__': class test: cvNo = 1 A_type = "comparE" V_type = "denseface" L_type = "bert_large" norm_method = 'trn' opt = test() print('Reading from dataset:') a = MultimodalDataset(opt, set_name='trn') data = next(iter(a)) for k, v in data.items(): if k not in ['int2name', 'label']: print(k, v.shape) else: print(k, v) print('Reading from dataloader:') x = [a[100], a[34], a[890]] # 从dataloader取3个样本 print('each one:') for i, _x in enumerate(x): print(i, ':') for k, v in _x.items(): if k not in ['int2name', 'label']: print(k, v.shape) else: print(k, v) ''' 从dataloader取3个样本,发现长度的维度不一致 0 : A_feat torch.Size([43, 130]) V_feat torch.Size([50, 342]) L_feat torch.Size([22, 1024]) label tensor(1) int2name Ses02M_impro07_M020 1 : A_feat torch.Size([62, 130]) V_feat torch.Size([50, 342]) L_feat torch.Size([22, 1024]) label tensor(2) int2name Ses02M_script02_2_M017 2 : A_feat torch.Size([26, 130]) V_feat torch.Size([50, 342]) L_feat torch.Size([22, 1024]) ''' # 3个样本的维度都不一致,使用collate_fn来进行padding print('packed output') x = a.collate_fn(x) for k, v in x.items(): if k not in ['int2name', 'label']: print(k, v.shape) else: print(k, v) ''' 经过collate_fn,一个batch(size=3)中A、V、L都padding到了它们当中最长的那个序列的长度 A_feat torch.Size([3, 62, 130]) V_feat torch.Size([3, 50, 342]) L_feat torch.Size([3, 22, 1024]) '''
StarcoderdataPython
1657125
<reponame>kirillzx/Math-projects def helix(n): t = [[0]*n for i in range (n)] i, j = 0, 0 for k in range(1, n*n+1): t[i][j]=k if k == n*n: break if i<=j+1 and i+j<n-1: j+=1 elif i<j and i+j>=n-1: i+=1 elif i>=j and i+j>n-1: j-=1 elif i>j+1 and i+j<=n-1: i-=1 return t #test res = helix(6) for i in res: print(*i)
StarcoderdataPython
9704767
"""URL route definitions for secure authorization tool.""" import json from flask import render_template, flash, redirect, url_for from app.routes import routes_bp from app.util.crypto import get_public_key_hex @routes_bp.route("/secure_auth", methods=["GET", "POST"]) def secure_auth(): result = get_public_key_hex() if result.failure: flash(result.error) return redirect(url_for("routes.secure_auth")) public_key = result.value return render_template( "auth.html", title="Secure Authorization Tool", public_key=public_key, )
StarcoderdataPython
4866679
<filename>egs/babel/tts1/babel_prepare.py<gh_stars>0 import os import numpy as np import librosa UNK = ['(())'] NONWORD = '~' EPS = 1e-3 LOGEPS = -60 DEBUG = True def VAD(y, fs, thres=EPS, coeff=1.0): L = y.shape[0] window_len = min(int(fs * 0.1), L) dur = float(y.shape[0]/fs) exp_filter = coeff ** (np.arange(window_len)[::-1]) exp_filter /= window_len y_smooth = np.convolve(np.abs(y), exp_filter, 'same') mask = (y_smooth > thres).astype(float) mask_diff = np.diff(mask) start_nonsils = np.where(mask_diff > 0)[0] end_nonsils = np.where(mask_diff < 0)[0] start_sec_nonsils = [float(start/fs) for start in start_nonsils] end_sec_nonsils = [float(end/fs) for end in end_nonsils] if len(end_sec_nonsils) < len(start_sec_nonsils): end_sec_nonsils.append(dur) # print(start_sec_nonsils[:10], end_sec_nonsils[:10]) # print(start_nonsils[:10], end_nonsils[:10]) return start_sec_nonsils, end_sec_nonsils def VAD2(y, fs, thres=EPS): L = y.shape[0] dur = float(y.shape[0] / fs) n_fft = int(25 * fs / 1000) hop_length = int(10 * fs / 1000) # win_len = 2 sgram = librosa.feature.melspectrogram(y=y, sr=fs, n_mels=40, n_fft=n_fft, hop_length=hop_length) # print(sgram.shape) energies = np.sum(sgram, axis=0) mask = (energies > thres).astype(float) mask_diff = np.diff(mask) start_nonsils = np.where(mask_diff > 0)[0] end_nonsils = np.where(mask_diff < 0)[0] start_sec_nonsils = [float(start * hop_length) / fs for start in start_nonsils] end_sec_nonsils = [float(end * hop_length) / fs for end in end_nonsils] if len(end_sec_nonsils) < len(start_sec_nonsils): end_sec_nonsils.append(dur) # print(start_sec_nonsils[:10], end_sec_nonsils[:10]) # print(start_nonsils[:10], end_nonsils[:10]) return start_sec_nonsils, end_sec_nonsils class BabelKaldiPreparer: def __init__(self, data_root, exp_root, sph2pipe, configs): self.audio_type = configs.get('audio_type', 'scripted') self.is_segment = configs.get('is_segment', False) self.vad = configs.get('vad', True) self.verbose = configs.get('verbose', 0) self.fs = 8000 self.data_root = data_root self.exp_root = exp_root self.sph2pipe = sph2pipe if self.audio_type == 'conversational': # XXX Use sub-train self.transcripts = {'train': os.listdir(data_root+'conversational/sub-train/transcript_roman/'), 'test': os.listdir(data_root+'conversational/eval/transcript_roman/'), 'dev': os.listdir(data_root+'conversational/dev/transcript_roman/')} self.audios = {'train': os.listdir(data_root+'conversational/training/audio/'), 'test': os.listdir(data_root+'conversational/eval/audio/'), 'dev': os.listdir(data_root+'conversational/dev/audio/')} elif self.audio_type == 'scripted': self.transcripts = {'train': os.listdir(data_root+'scripted/training/transcript_roman/'), 'test': os.listdir(data_root+'scripted/training/transcript_roman/'), 'dev': os.listdir(data_root+'scripted/training/transcript_roman/')} self.audios = {'train': os.listdir(data_root+'scripted/training/audio/'), 'test': os.listdir(data_root+'scripted/eval/audio/'), 'dev': os.listdir(data_root+'scripted/dev/audio/')} else: raise NotImplementedError def prepare_tts(self): if not os.path.isdir('data'): os.mkdir('data') os.mkdir('data/train') os.mkdir('data/test') os.mkdir('data/dev') if not os.path.isdir(self.exp_root): os.mkdir(exp_root) os.mkdir(exp_root + 'train') os.mkdir(exp_root + 'test') os.mkdir(exp_root + 'dev') if self.audio_type == 'conversational': sph_dir = { 'train': self.data_root + 'conversational/training/', 'test': self.data_root + 'conversational/eval/', 'dev': self.data_root + 'conversational/dev/' } elif self.audio_type == 'scripted': sph_dir = { 'train': self.data_root + 'scripted/training/', 'test': self.data_root + 'scripted/training/', 'dev': self.data_root + 'scripted/training/' } else: raise NotImplementedError for x in ['train', 'dev', 'test']: with open(os.path.join('data', x, 'text'), 'w') as text_f, \ open(os.path.join('data', x, 'wav.scp'), 'w') as wav_scp_f, \ open(os.path.join('data', x, 'utt2spk'), 'w') as utt2spk_f, \ open(os.path.join('data', x, 'segments'), 'w') as segment_f: text_f.truncate() wav_scp_f.truncate() utt2spk_f.truncate() segment_f.truncate() i = 0 for transcript_fn, audio_fn in zip(sorted(self.transcripts[x], key=lambda x:x.split('.')[0]), sorted(self.audios[x], key=lambda x:x.split('.')[0])): # XXX # if i > 1: # continue # i += 1 # Load audio os.system('/home/lwang114/kaldi/tools/sph2pipe_v2.5/sph2pipe -f wav -p -c 1 %s temp.wav' % (sph_dir[x] + 'audio/' + audio_fn)) y, _ = librosa.load('temp.wav', sr=self.fs) utt_id = transcript_fn.split('.')[0] sent = [] if self.is_segment: print(x, utt_id) with open(sph_dir[x] + 'transcript_roman/' + transcript_fn, 'r') as transcript_f: lines = transcript_f.readlines() i_seg = 0 for i_seg, (start, segment, end) in enumerate(zip(lines[::2], lines[1::2], lines[2::2])): # XXX # if i_seg > 1: # continue # i_seg += 1 start_sec = float(start[1:-2]) end_sec = float(end[1:-2]) start = int(self.fs * start_sec) end = int(self.fs * end_sec) if start_sec >= end_sec: if self.verbose > 0: print('Corrupted segment info') continue if end_sec - start_sec >= 30: print('Audio sequence too long: ', utt_id, start_sec, end_sec) continue words = segment.strip().split(' ') words = [w for w in words if w not in UNK and (w[0] != '<' or w[-1] != '>') and w not in NONWORD] subsegments = [] sent += words # Remove utterances that are too long if len(words) == 0: if self.verbose > 0: print('Empty segment') continue elif len(words) > 400: print('Phone sequence too long: ', utt_id, len(words)) continue # Skip silence interval if self.vad: start_sec_nonsils, end_sec_nonsils = VAD2(np.append(np.zeros((start,)), y[start:end]), self.fs) if len(start_sec_nonsils) == 0: print('Audio too quiet') continue # for i_subseg, (start_sec_nonsil, end_sec_nonsil) in enumerate(zip(start_sec_nonsils, end_sec_nonsils)): segment_f.write('%s_%04d %s %.2f %.2f\n' % (utt_id, i_seg, utt_id, start_sec_nonsils[0], end_sec_nonsils[-1])) else: segment_f.write('%s_%04d %s %.2f %.2f\n' % (utt_id, i_seg, utt_id, start_sec, end_sec)) text_f.write('%s_%04d %s\n' % (utt_id, i_seg, ' '.join(words))) utt2spk_f.write('%s_%04d %s\n' % (utt_id, i_seg, utt_id)) # XXX dummy speaker id if len(sent) == 0: continue wav_scp_f.write(utt_id + ' ' + self.sph2pipe + ' -f wav -p -c 1 ' + \ os.path.join(sph_dir[x], 'audio/', utt_id + '.sph') + ' |\n') else: # TODO: Remove silence interval print(x, utt_id) sent = [] with open(sph_dir[x] + 'transcript_roman/' + transcript_fn, 'r') as transcript_f: lines = transcript_f.readlines() for line in lines[1::2]: words = line.strip().split(' ') words = [w for w in words if w not in UNK and (w[0] != '<' or w[-1] != '>')] sent += words if len(words) == 0: if self.verbose > 0: print('Empty transcript file') continue text_f.write(utt_id + ' ' + ' '.join(sent) + '\n') wav_scp_f.write(utt_id + ' ' + self.sph2pipe + ' -f wav -p -c 1 ' + \ os.path.join(sph_dir[x], 'audio/', utt_id + '.sph') + ' |\n') utt2spk_f.write(utt_id + ' ' + '001\n') # XXX dummy speaker id if not self.is_segment: os.remove(os.path.join('data', x, 'segments')) # TODO def remove_silence(self): feat_dir = 'fbank/' if not os.path.isdir('fbank_no_silence/'): os.mkdir('fbank_no_silence') ark_files = { 'train': os.listdir(feat_dir+'*_train.ark'), 'dev': os.listdir(feat_dir+'*_dev.ark'), 'test': os.listdir(feat_dir+'*_test.ark') } if __name__ == '__main__': data_root = '/home/lwang114/data/babel/IARPA_BABEL_BP_101/' exp_root = 'exp/apr1_BP1_101_conversational/' sph2pipe = '/home/lwang114/kaldi/tools/sph2pipe_v2.5/sph2pipe' configs = {'audio_type': 'conversational', 'is_segment': True, 'vad': False} kaldi_prep = BabelKaldiPreparer(data_root, exp_root, sph2pipe, configs) kaldi_prep.prepare_tts()
StarcoderdataPython
11325016
import io import json import logging import struct import sys import traceback import typing from fastavro import schemaless_reader, schemaless_writer from schema_registry.client import SchemaRegistryClient, schema from schema_registry.client.errors import ClientError from .errors import SerializerError log = logging.getLogger(__name__) MAGIC_BYTE = 0 class ContextStringIO(io.BytesIO): """ Wrapper to allow use of StringIO via 'with' constructs. """ def __enter__(self) -> "ContextStringIO": return self def __exit__(self, *args: typing.Any) -> None: self.close() class MessageSerializer: """ A helper class that can serialize and deserialize messages Args: schemaregistry_client (schema_registry.client.SchemaRegistryClient): Http Client """ def __init__( self, schemaregistry_client: SchemaRegistryClient, reader_schema: typing.Optional[schema.AvroSchema] = None, return_record_name: bool = False, ): self.schemaregistry_client = schemaregistry_client self.id_to_decoder_func = {} # type: typing.Dict self.id_to_writers = {} # type: typing.Dict self.reader_schema = reader_schema self.return_record_name = return_record_name def _get_encoder_func(self, avro_schema: typing.Union[schema.AvroSchema, str]) -> typing.Callable: if isinstance(avro_schema, str): avro_schema = schema.AvroSchema(json.loads(avro_schema)) return lambda record, fp: schemaless_writer(fp, avro_schema.schema, record) # type: ignore def encode_record_with_schema( self, subject: str, avro_schema: typing.Union[schema.AvroSchema, str], record: dict ) -> bytes: """ Given a parsed avro schema, encode a record for the given subject. The record is expected to be a dictionary. The schema is registered with the subject of 'topic-value' Args: subject (str): Subject name schema (avro.schema.RecordSchema): Avro Schema record (dict): An object to serialize Returns: bytes: Encoded record with schema ID as bytes """ # Try to register the schema schema_id = self.schemaregistry_client.register(subject, avro_schema) if not schema_id: message = f"Unable to retrieve schema id for subject {subject}" raise SerializerError(message) # cache writer if not self.id_to_writers.get(schema_id): self.id_to_writers[schema_id] = self._get_encoder_func(avro_schema) return self.encode_record_with_schema_id(schema_id, record) def encode_record_with_schema_id(self, schema_id: int, record: dict) -> bytes: """ Encode a record with a given schema id. The record must be a python dictionary. Args: schema_id (int): integer ID record (dict): An object to serialize Returns: func: decoder function """ # use slow avro if schema_id not in self.id_to_writers: try: avro_schema = self.schemaregistry_client.get_by_id(schema_id) if not avro_schema: raise SerializerError("Schema does not exist") self.id_to_writers[schema_id] = self._get_encoder_func(avro_schema) except ClientError: exc_type, exc_value, exc_traceback = sys.exc_info() raise SerializerError(repr(traceback.format_exception(exc_type, exc_value, exc_traceback))) writer = self.id_to_writers[schema_id] with ContextStringIO() as outf: # Write the magic byte and schema ID in network byte order (big endian) outf.write(struct.pack(">bI", MAGIC_BYTE, schema_id)) # write the record to the rest of the buffer writer(record, outf) return outf.getvalue() def _get_decoder_func(self, schema_id: int, payload: ContextStringIO) -> typing.Callable: if schema_id in self.id_to_decoder_func: return self.id_to_decoder_func[schema_id] try: writer_schema = self.schemaregistry_client.get_by_id(schema_id) except ClientError as e: raise SerializerError(f"unable to fetch schema with id {schema_id}: {e}") if writer_schema is None: raise SerializerError(f"unable to fetch schema with id {schema_id}") self.id_to_decoder_func[schema_id] = lambda payload: schemaless_reader( payload, writer_schema.schema, self.reader_schema, self.return_record_name ) return self.id_to_decoder_func[schema_id] def decode_message(self, message: typing.Optional[bytes]) -> typing.Optional[dict]: """ Decode a message from kafka that has been encoded for use with the schema registry. Args: message (bytes or None): message key or value to be decoded Returns: dict: Decoded message contents. """ if message is None: return None if len(message) <= 5: raise SerializerError("message is too small to decode") with ContextStringIO(message) as payload: magic, schema_id = struct.unpack(">bI", payload.read(5)) if magic != MAGIC_BYTE: raise SerializerError("message does not start with magic byte") decoder_func = self._get_decoder_func(schema_id, payload) return decoder_func(payload)
StarcoderdataPython
4963258
# -*- coding: utf-8 -*- # # This class was auto-generated from the API references found at # https://support.direct.ingenico.com/documentation/api/reference/ # from ingenico.direct.sdk.data_object import DataObject class OrderTypeInformation(DataObject): """ | Object that holds the purchase and usage type indicators """ __purchase_type = None __transaction_type = None @property def purchase_type(self): """ | Possible values are: | * physical (tangible goods shipped to the customers) | * digital (digital services like ebooks, streaming...) Type: str """ return self.__purchase_type @purchase_type.setter def purchase_type(self, value): self.__purchase_type = value @property def transaction_type(self): """ | Identifies the type of transaction being authenticated. Possible values are: | * purchase = The purpose of the transaction is to purchase goods or services (Default) | * check-acceptance = The purpose of the transaction is to accept a 'check'/'cheque' | * account-funding = The purpose of the transaction is to fund an account | * quasi-cash = The purpose of the transaction is to buy a quasi cash type product that is representative of actual cash such as money orders, traveler's checks, foreign currency, lottery tickets or casino gaming chips | * prepaid-activation-or-load = The purpose of the transaction is to activate or load a prepaid card Type: str """ return self.__transaction_type @transaction_type.setter def transaction_type(self, value): self.__transaction_type = value def to_dictionary(self): dictionary = super(OrderTypeInformation, self).to_dictionary() if self.purchase_type is not None: dictionary['purchaseType'] = self.purchase_type if self.transaction_type is not None: dictionary['transactionType'] = self.transaction_type return dictionary def from_dictionary(self, dictionary): super(OrderTypeInformation, self).from_dictionary(dictionary) if 'purchaseType' in dictionary: self.purchase_type = dictionary['purchaseType'] if 'transactionType' in dictionary: self.transaction_type = dictionary['transactionType'] return self
StarcoderdataPython
184292
import gmplot import matplotlib.pyplot as plt import pvlib as pv import mplcursors from datetime import datetime, timedelta from analytics.location.path import Path, LinearPath from loguru import logger def main(): path = LinearPath.create( start_loc=pv.location.Location(latitude=42, longitude=-71), end_loc=pv.location.Location(latitude=31, longitude=-170), start_time=datetime.now(), end_time=datetime.now() + timedelta(days=1) ) plot_path(path) def plot_path(path: Path): fig, ax = plt.subplots(nrows=1, ncols=1) lats, lons = path.lats_lons ax.plot(lons, lats) ax.set_xlabel("Longitude") ax.set_ylabel("Latitude") ax.set_xlim(-180, 180) ax.set_ylim(-90, 90) ax.grid() mplcursors.cursor() plt.show() def plot_path_gmap(path: Path): gmap = gmplot.GoogleMapPlotter(0, 0, 0) lats, lons = path.lats_lons gmap.plot(lats, lons) gmap.draw("output/map.html") if __name__ == "__main__": main()
StarcoderdataPython
1913027
<gh_stars>1-10 from typing import Any from rx.core import ObservableBase, Observable def of(*args: Any) -> ObservableBase: """This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. Example: res = rx.Observable.of(1,2,3) Returns the observable sequence whose elements are pulled from the given arguments """ return Observable.from_iterable(args)
StarcoderdataPython
8131445
from django.shortcuts import render from django.http import Http404 def home(request): return render(request, 'ashgear/home.html', {'projects': ['project1', 'project2']}) def handler404(request, exception): return render(request, "errors/404.html", {}) def products(request): raise Http404("Poll does not exist")
StarcoderdataPython
6520984
aluno = dict() aluno['nome'] = str(input('Nome: ')).strip() aluno['media'] = float(input(f'Média de {aluno["nome"]}: ')) print(f'Média é igual a {aluno["media"]}') if aluno['media'] < 7: print('Situação é igual a Reprovado!') else: print('Situação é igual a Aprovado!')
StarcoderdataPython
1973341
<reponame>doobdev/doob import logging from random import choice, randint, random from typing import Optional from aiohttp import request from datetime import datetime from asyncio import sleep from discord import Member, Embed, Colour from discord.ext.commands import Cog, command, cooldown, BucketType, group from discord.utils import get from discord_slash import cog_ext from owoify import Owoifator owoifactor = Owoifator() from ..db import db # pylint: disable=relative-beyond-top-level import json with open("config.json") as config_file: config = json.load(config_file) log = logging.getLogger() class Fun(Cog): def __init__(self, bot): self.bot = bot @command(name="hello", aliases=["hi"], brief="Say Hi to Doob!") async def say_hello(self, ctx): """Say Hi to Doob!""" # Chooses Hello, Hi, or Hey at random, to say Hi to the user. await ctx.reply(f"{choice(('Hello', 'Hi', 'Hey'))} {ctx.author.mention}!") @command(name="dice", aliases=["roll", "rolldice"], brief="Roll some dice!") @cooldown(1, 10, BucketType.user) async def roll_dice(self, ctx, die_string: str): """Role some dice, (number)d(number) syntax.""" dice, value = (int(term) for term in die_string.split("d")) # If the dice is less or equal to 40, then run the command if dice <= 40: rolls = [randint(1, value) for i in range(dice)] await ctx.reply(" + ".join(str(r) for r in rolls) + f" = {sum(rolls)}") else: await ctx.reply("Please roll a lower number of dice.", delete_after=10) @command(name="echo", aliases=["say"], brief="Make Doob say something!") async def echo_message(self, ctx, *, message): """Make Doob say a message! | `Patreon Only`""" homeGuild = self.bot.get_guild(config["homeGuild_id"]) # Support Server ID. patreonRole = get( homeGuild.roles, id=config["patreonRole_id"] ) # Patreon role ID. member = [] # Checks if a user is a Patreon member. for pledger in homeGuild.members: if pledger == ctx.author: member = pledger if ctx.author in homeGuild.members and patreonRole in member.roles: # If they are, run the command. await ctx.message.delete() await ctx.send(message) log.info(f"{ctx.author.name} used the Echo command and said {message}") else: await ctx.reply( "You are not a Patron to Doob, subscribe to any of the tiers at <https://patreon.com/doobdev> to gain access to this command." ) @command( name="fact", aliases=["dogfact", "facts"], brief="Learn a random fact about dogs!", ) @cooldown(3, 10, BucketType.user) async def dog_fact(self, ctx): """Get a wacky dog fact""" # URL of the API URL = "https://some-random-api.ml/facts/dog" # GETs a json response from URL, puts the fact into an embed, then sends it to the user. async with request("GET", URL, headers={}) as response: if response.status == 200: data = ( await response.json() ) # Right here is where it gets the data from the json response. embed = Embed( title="Dog Fact!", description=data["fact"], colour=ctx.author.colour, ) embed.set_footer( text=f"{ctx.author} requested this fact!", icon_url=ctx.author.avatar_url, ) await ctx.reply(embed=embed) else: # if the API responds with a status not being "200" (200=Working just fine), sends out an error message to the user with the status number. await ctx.reply(f"Dog fact API sent a {response.status} status.") @command(name="luckydog", aliases=["ldog"], brief="Get an instant Lucky Dog!") @cooldown(2, 5, BucketType.user) async def lucky_dog_image(self, ctx, *, dog: Optional[str]): """Shows the lucky dogs possible!\nIsn't eligable for the Nitro Giveaways\n`Patreon` permission required""" homeGuild = self.bot.get_guild(config["homeGuild_id"]) # Support Server ID. patreonRole = get( homeGuild.roles, id=config["patreonRole_id"] ) # Patreon role ID. member = [] # Checks if someone is a Patron for pledger in homeGuild.members: if pledger == ctx.author: member = pledger # If they are, let them run the command if ctx.author in homeGuild.members and patreonRole in member.roles: if dog == "1": embed = Embed( title="Lucky Dog Picture!", description="This is [Liquid Mendo](https://twitter.com/Mendo)'s dog Koda!", colour=Colour.gold(), ) embed.set_footer( text=f"{ctx.author} got this lucky dog picture!", icon_url=ctx.author.avatar_url, ) embed.set_image( url="https://pbs.twimg.com/media/EgXfe_XUcAABT41?format=jpg&name=360x360" ) elif dog == "2": embed = Embed( title="Lucky Dog Picture!", description="You selected the old `GAMING` server PFP!", colour=Colour.gold(), ) embed.set_footer( text=f"Thanks for supporting Doob, {ctx.author.name}!", icon_url=ctx.author.avatar_url, ) embed.set_image(url="https://i.imgur.com/pzqRLdi.jpg") elif dog == "3": embed = Embed( title="Lucky Dog Picture!", description="This is [Weest](https://twitter.com/weesterner)'s dog Kevin!", colour=Colour.gold(), ) embed.set_footer( text=f"Thanks for supporting Doob, {ctx.author.name}!", icon_url=ctx.author.avatar_url, ) embed.set_image(url="https://i.imgur.com/guF2Y3z.png") elif dog == "4": embed = Embed( title="Lucky Dog Picture!", description="This is [@KittyKay000](https://twitter.com/kittykay000)'s concept drawing of Doob!", colour=Colour.gold(), ) embed.set_footer( text=f"Thanks for supporting Doob, {ctx.author.name}!", icon_url=ctx.author.avatar_url, ) embed.set_image(url="https://i.imgur.com/KFOR8YJ.jpeg") else: embed = Embed( title="Lucky Dogs Possible:", description="1 = [Liquid Mendo](https://twitter.com/mendo)'s dog Koda\n2 = Old `GAMING` server PFP\n3 = [Weest](https://twitter.com/weesterner)'s dog Kevin\n4 = [@KittyKay000](https://twitter.com/kittykay000)'s concept drawing for Doob!", colour=ctx.author.colour, ) embed.set_footer( text=f"Thanks for supporting Doob, {ctx.author.name}!", icon_url=ctx.author.avatar_url, ) await ctx.reply(embed=embed) else: await ctx.reply( "This is a Patreon (<https://patreon.com/doobdev>) only command." ) @command( name="luckydogs", aliases=["dogscaught", "ldc", "ld", "checkdogs", "lds"], brief="Check how many Lucky Dogs you have gotten!", ) @cooldown(2, 5, BucketType.user) async def check_lucky_dogs(self, ctx, *, target: Optional[Member]): """Check how many Lucky dogs you have gotten in the last month!""" target = target or ctx.author # Pulls from the database how many luckydogs a user has. LuckyDogs = db.records( "SELECT LuckyDogs FROM luckydogs WHERE UserID = ?", target.id ) # Gives how many lucky dogs a user has. embed = Embed( title=f"{target.name} has gotten:", description=f"{str(LuckyDogs[0][0])} Lucky Dog(s) this month.", colour=target.colour, ) embed.set_footer( text=f"{ctx.author.name} requested this. | Doob", icon_url=ctx.author.avatar_url, ) embed.set_thumbnail(url=target.avatar_url) await ctx.reply(embed=embed) @command(name="dog", aliases=["dogimage"], brief="See a random picture of a dog!") @cooldown(2, 5, BucketType.user) async def dog_image(self, ctx): """So this is what you came for...\nGives you a random picture of a dog!""" LuckyDogs = db.records( "SELECT LuckyDogs FROM luckydogs WHERE UserID = ?", ctx.author.id ) homeGuild = self.bot.get_guild(config["homeGuild_id"]) # Support Server ID. patreonRole = get( homeGuild.roles, id=config["patreonRole_id"] ) # Patreon role ID. member = [] # Checks if user is a Patron for pledger in homeGuild.members: if pledger == ctx.author: member = pledger # If the user is, give them a higher chance in the Lucky Dog Rolls if ctx.author in homeGuild.members and patreonRole in member.roles: # Rolls a random number between 1 and 53 for Patrons, to give them a higher chance of getting a "Lucky Dog" random = randint(1, 53) # If the user doesn't get a lucky dog roll, then contact the API and get a picture! if random not in [50, 51, 52, 53]: # URL for the API URL = "https://dog.ceo/api/breeds/image/random" async with request("GET", URL, headers={}) as response: if response.status == 200: data = await response.json() embed = Embed(title="Dog Picture!", colour=ctx.author.colour) # embed.set_footer(text=f"DEBUG: L_DOG: {random}") embed.set_image(url=data["message"]) await ctx.reply(embed=embed) elif random == 50: embed = Embed( title="Lucky Dog Picture!", description="This is [Liquid Mendo](https://twitter.com/Mendo)'s dog Koda!", colour=Colour.gold(), ) embed.set_footer( text=f"{ctx.author} got this lucky dog picture! | There is a 1 in 50 chance of getting this picture!", icon_url=ctx.author.avatar_url, ) embed.set_image( url="https://pbs.twimg.com/media/EgXfe_XUcAABT41?format=jpg&name=360x360" ) db.execute( "UPDATE luckydogs SET (LuckyDogs, LastUpdated) = (?, ?) WHERE UserID = ?", LuckyDogs[0][0] + 1, datetime.utcnow(), ctx.author.id, ) await ctx.reply(embed=embed) elif random == 51: embed = Embed( title="Lucky Dog Picture!", description="There is a 1 in 50 chance of getting this picture!", colour=Colour.gold(), ) embed.set_footer( text=f"{ctx.author} got this lucky dog picture!", icon_url=ctx.author.avatar_url, ) embed.set_image(url="https://i.imgur.com/pzqRLdi.jpg") db.execute( "UPDATE luckydogs SET (LuckyDogs, LastUpdated) = (?, ?) WHERE UserID = ?", LuckyDogs[0][0] + 1, datetime.utcnow(), ctx.author.id, ) await ctx.reply(embed=embed) elif random == 52: embed = Embed( title="Lucky Dog Picture!", description="This is [Weest](https://twitter.com/weesterner)'s dog Kevin!", colour=Colour.gold(), ) embed.set_footer( text=f"{ctx.author} got this lucky dog picture! | There is a 1 in 50 chance of getting this picture!", icon_url=ctx.author.avatar_url, ) embed.set_image(url="https://i.imgur.com/guF2Y3z.png") db.execute( "UPDATE luckydogs SET (LuckyDogs, LastUpdated) = (?, ?) WHERE UserID = ?", LuckyDogs[0][0] + 1, datetime.utcnow(), ctx.author.id, ) await ctx.reply(embed=embed) else: embed = Embed( title="Lucky Dog Picture!", description="This is [@KittyKay000](https://twitter.com/kittykay000)'s concept drawing of Doob!", colour=Colour.gold(), ) embed.set_footer( text=f"{ctx.author} got this lucky dog picture! | There is a 1 in 50 chance of getting this picture!", icon_url=ctx.author.avatar_url, ) embed.set_image(url="https://i.imgur.com/KFOR8YJ.jpeg") db.execute( "UPDATE luckydogs SET (LuckyDogs, LastUpdated) = (?, ?) WHERE UserID = ?", LuckyDogs[0][0] + 1, datetime.utcnow(), ctx.author.id, ) await ctx.reply(embed=embed) else: # If they aren't a Patron, it calls the function below. await self.lucky_dogs(ctx) @cog_ext.cog_slash(name="dog", description="See a random picture of a dog!") async def dog_slash_command(self, SlashContext): ctx = SlashContext LuckyDogs = db.records( "SELECT LuckyDogs FROM luckydogs WHERE UserID = ?", ctx.author.id ) homeGuild = self.bot.get_guild(config["homeGuild_id"]) # Support Server ID. patreonRole = get( homeGuild.roles, id=config["patreonRole_id"] ) # Patreon role ID. member = [] # Checks if user is a Patron for pledger in homeGuild.members: if pledger == ctx.author: member = pledger # If the user is, give them a higher chance in the Lucky Dog Rolls if ctx.author in homeGuild.members and patreonRole in member.roles: # Rolls a random number between 1 and 53 for Patrons, to give them a higher chance of getting a "Lucky Dog" random = randint(1, 53) # If the user doesn't get a lucky dog roll, then contact the API and get a picture! if random not in [50, 51, 52, 53]: # URL for the API URL = "https://dog.ceo/api/breeds/image/random" async with request("GET", URL, headers={}) as response: if response.status == 200: data = await response.json() embed = Embed(title="Dog Picture!", colour=ctx.author.colour) # embed.set_footer(text=f"DEBUG: L_DOG: {random}") embed.set_image(url=data["message"]) await ctx.send(embed=embed) elif random == 50: embed = Embed( title="Lucky Dog Picture!", description="This is [Liquid Mendo](https://twitter.com/Mendo)'s dog Koda!", colour=Colour.gold(), ) embed.set_footer( text=f"{ctx.author} got this lucky dog picture! | There is a 1 in 50 chance of getting this picture!", icon_url=ctx.author.avatar_url, ) embed.set_image( url="https://pbs.twimg.com/media/EgXfe_XUcAABT41?format=jpg&name=360x360" ) db.execute( "UPDATE luckydogs SET (LuckyDogs, LastUpdated) = (?, ?) WHERE UserID = ?", LuckyDogs[0][0] + 1, datetime.utcnow(), ctx.author.id, ) await ctx.send(embed=embed) elif random == 51: embed = Embed( title="Lucky Dog Picture!", description="There is a 1 in 50 chance of getting this picture!", colour=Colour.gold(), ) embed.set_footer( text=f"{ctx.author} got this lucky dog picture!", icon_url=ctx.author.avatar_url, ) embed.set_image(url="https://i.imgur.com/pzqRLdi.jpg") db.execute( "UPDATE luckydogs SET (LuckyDogs, LastUpdated) = (?, ?) WHERE UserID = ?", LuckyDogs[0][0] + 1, datetime.utcnow(), ctx.author.id, ) await ctx.send(embed=embed) elif random == 52: embed = Embed( title="Lucky Dog Picture!", description="This is [Weest](https://twitter.com/weesterner)'s dog Kevin!", colour=Colour.gold(), ) embed.set_footer( text=f"{ctx.author} got this lucky dog picture! | There is a 1 in 50 chance of getting this picture!", icon_url=ctx.author.avatar_url, ) embed.set_image(url="https://i.imgur.com/guF2Y3z.png") db.execute( "UPDATE luckydogs SET (LuckyDogs, LastUpdated) = (?, ?) WHERE UserID = ?", LuckyDogs[0][0] + 1, datetime.utcnow(), ctx.author.id, ) await ctx.send(embed=embed) else: embed = Embed( title="Lucky Dog Picture!", description="This is [@KittyKay000](https://twitter.com/kittykay000)'s concept drawing of Doob!", colour=Colour.gold(), ) embed.set_footer( text=f"{ctx.author} got this lucky dog picture! | There is a 1 in 50 chance of getting this picture!", icon_url=ctx.author.avatar_url, ) embed.set_image(url="https://i.imgur.com/KFOR8YJ.jpeg") db.execute( "UPDATE luckydogs SET (LuckyDogs, LastUpdated) = (?, ?) WHERE UserID = ?", LuckyDogs[0][0] + 1, datetime.utcnow(), ctx.author.id, ) await ctx.send(embed=embed) else: # If they aren't a Patron, it calls the function below. await self.lucky_dogs(ctx) async def lucky_dogs(self, ctx): # Rolls a number for the Lucky Dogs random = randint(1, 503) # Rolls a number for the "Patreon Ad", which is just a small ad at the top of the embed telling them that they can get # a higher chance of getting a Lucky Dog by subscribing to the Patreon. patreon_ad = randint(1, 4) LuckyDogs = db.records( "SELECT LuckyDogs FROM luckydogs WHERE UserID = ?", ctx.author.id ) if random not in [100, 101, 102]: # URL for the API URL = "https://dog.ceo/api/breeds/image/random" # This is for the "Patreon Ad" at the top of d!dog you get times. if patreon_ad != 1: async with request("GET", URL, headers={}) as response: if response.status == 200: data = await response.json() embed = Embed(title="Dog Picture!", colour=ctx.author.colour) embed.set_image(url=data["message"]) await ctx.send(embed=embed) else: async with request("GET", URL, headers={}) as response: if response.status == 200: data = await response.json() embed = Embed(title="Dog Picture!", colour=ctx.author.colour) embed.set_author( name="Get a higher chance of getting a Lucky Dog by subscribing to our Patreon", icon_url="https://i.imgur.com/OosmBb4.png", url="https://patreon.com/doobdev", ) embed.set_image(url=data["message"]) await ctx.send(embed=embed) elif random == 100: embed = Embed( title="Lucky Dog Picture!", description="This is [Liquid Mendo](https://twitter.com/mendo)'s dog Koda!", colour=Colour.gold(), ) embed.set_footer( text=f"{ctx.author} got this lucky dog picture! | There is a 1 in 1000 chance of getting this picture!", icon_url=ctx.author.avatar_url, ) embed.set_image( url="https://pbs.twimg.com/media/EgXfe_XUcAABT41?format=jpg&name=360x360" ) db.execute( "UPDATE luckydogs SET (LuckyDogs, LastUpdated) = (?, ?) WHERE UserID = ?", LuckyDogs[0][0] + 1, datetime.utcnow(), ctx.author.id, ) await ctx.send(embed=embed) elif random == 101: embed = Embed( title="Lucky Dog Picture!", description="There is a 1 in 1000 chance of getting this picture!", colour=Colour.gold(), ) embed.set_footer( text=f"{ctx.author} got this lucky dog picture!", icon_url=ctx.author.avatar_url, ) embed.set_image(url="https://i.imgur.com/pzqRLdi.jpg") db.execute( "UPDATE luckydogs SET (LuckyDogs, LastUpdated) = (?, ?) WHERE UserID = ?", LuckyDogs[0][0] + 1, datetime.utcnow(), ctx.author.id, ) await ctx.send(embed=embed) else: embed = Embed( title="Lucky Dog Picture!", description="This is [Weest](https://twitter.com/weesterner)'s dog Kevin!", colour=Colour.gold(), ) embed.set_footer( text=f"{ctx.author} got this lucky dog picture! | There is a 1 in 1000 chance of getting this picture!", icon_url=ctx.author.avatar_url, ) embed.set_image(url="https://i.imgur.com/guF2Y3z.png") db.execute( "UPDATE luckydogs SET (LuckyDogs, LastUpdated) = (?, ?) WHERE UserID = ?", LuckyDogs[0][0] + 1, datetime.utcnow(), ctx.author.id, ) await ctx.send(embed=embed) @command(name="nukeserver", brief="We do a little trolling", hidden=True) @cooldown(1, 5, BucketType.guild) async def nuke_server_trollage_command(self, ctx): msg = await ctx.send("Nuking Server [------------------]") await sleep(1) await msg.edit(content="Nuking Server [=-----------------]") await sleep(1) await msg.edit(content="Nuking Server [==----------------]") await sleep(1) await msg.edit(content="Nuking Server [===---------------]") await sleep(1) await msg.edit(content="Nuking Server [====--------------]") await sleep(1) await msg.edit(content="Nuking Server [=====-------------]") await sleep(1) await msg.edit(content="Nuking Server [======------------]") await sleep(1) await msg.edit(content="Nuking Server [=======-----------]") await sleep(1) await msg.edit(content="Nuking Server [========----------]") await sleep(1) await msg.edit(content="Nuking Server [=========---------]") await sleep(1) await msg.edit(content="Nuking Server [==========--------]") await sleep(1) await msg.edit(content="Nuking Server [===========-------]") await sleep(1) await msg.edit(content="Nuking Server [============------]") await sleep(1) await msg.edit(content="Nuking Server [=============-----]") await sleep(1) await msg.edit(content="Nuking Server [==============----]") await sleep(1) await msg.edit(content="Nuking Server [===============---]") await sleep(1) await msg.edit(content="Nuking Server [================--]") await sleep(1) await msg.edit(content="Nuking Server [=================-]") await sleep(1) await msg.edit(content="Nuking Server [==================]") await sleep(1) await msg.edit(content="trolololol") @command( name="notanimposter", aliases=["nai", "amonguscrew", "crewmate"], brief="Shows a user as not the imposter!", ) @cooldown(1, 4, BucketType.user) async def not_an_imposter(self, ctx, *, target: Optional[str]): """Among Us Command - Shows a user as `not the imposter`\nI SWEAR I SAW HIM VENT! He wasn't an imposter...""" target = target or ctx.author # Checks if the target is an "@everyone" or "@here" ping, so Doob doesn't ping the entire server. if target in ["@everyone", "@here"]: await ctx.reply("nope, no ping pong here.") else: await ctx.reply( f".    。    •   ゚  。   .\n   .      .     。   。 .  \n\n.   。      ඞ 。 .    •     •\n\n  ゚   {target} was not An Impostor.  。 .\n\n  '    1 Impostor remain     。\n\n  ゚   .   . ,    .  ." ) @command( name="animposter", aliases=["ai", "amongusimposter", "imposter"], brief="Shows a user as the imposter!", ) @cooldown(1, 4, BucketType.user) async def an_imposter(self, ctx, *, target: Optional[str]): """Among Us Command - Shows a user as `the imposter`\nI SWEAR I SAW HIM VENT! He was an imposter. I knew it!!!""" target = target or ctx.author if target in ["@everyone", "@here"]: await ctx.reply("nope, no ping pong here.") else: await ctx.reply( f".    。    •   ゚  。   .\n   .      .     。   。 .  \n\n.   。      ඞ 。 .    •     •\n\n  ゚   {target} was An Impostor.  。 .\n\n  '    0 Impostors remain     。\n\n  ゚   .   . ,    .  ." ) async def valroll_func(self, ctx): characters = ( "Viper", "Sova", "Sage", "Reyna", "Raze", "Phoenix", "Omen", "Jett", "Cypher", "Brimstone", "Breach", "Killjoy", "Skye", "Yoru", "Astra", ) char = choice((characters)) log.info(char) embed = Embed( title=f"Play: {char}", description="Enjoy!", colour=ctx.author.colour ) if char == "Brimstone": embed.set_image( url="https://static.wikia.nocookie.net/valorant/images/3/37/Brimstone_artwork.png/revision/latest/scale-to-width-down/587?cb=20200602020239" ) elif char == "Viper": embed.set_image( url="https://static.wikia.nocookie.net/valorant/images/9/91/Viper_artwork.png/revision/latest/scale-to-width-down/587?cb=20200602020322" ) elif char == "Omen": embed.set_image( url="https://static.wikia.nocookie.net/valorant/images/0/06/Omen_artwork.png/revision/latest/scale-to-width-down/587?cb=20200602020233" ) elif char == "Killjoy": embed.set_image( url="https://static.wikia.nocookie.net/valorant/images/8/8c/Killjoy.png/revision/latest/scale-to-width-down/587?cb=20200729134445" ) elif char == "Cypher": embed.set_image( url="https://static.wikia.nocookie.net/valorant/images/b/bb/Cypher_artwork.png/revision/latest/scale-to-width-down/587?cb=20200602020329" ) elif char == "Sova": embed.set_image( url="https://static.wikia.nocookie.net/valorant/images/6/61/Sova_artwork.png/revision/latest/scale-to-width-down/587?cb=20200602020314" ) elif char == "Sage": embed.set_image( url="https://static.wikia.nocookie.net/valorant/images/1/1e/Sage_artwork.png/revision/latest/scale-to-width-down/587?cb=20200602020306" ) elif char == "Phoenix": embed.set_image( url="https://static.wikia.nocookie.net/valorant/images/f/fa/Phoenix_artwork.png/revision/latest/scale-to-width-down/652?cb=20200602020246" ) elif char == "Jett": embed.set_image( url="https://static.wikia.nocookie.net/valorant/images/7/79/Jett_artwork.png/revision/latest/scale-to-width-down/587?cb=20200602020209" ) elif char == "Reyna": embed.set_image( url="https://static.wikia.nocookie.net/valorant/images/4/41/Reyna_artwork.png/revision/latest/scale-to-width-down/587?cb=20200602020340" ) elif char == "Raze": embed.set_image( url="https://static.wikia.nocookie.net/valorant/images/c/c4/Raze_artwork.png/revision/latest/scale-to-width-down/587?cb=20200602020217" ) elif char == "Breach": embed.set_image( url="https://static.wikia.nocookie.net/valorant/images/5/5c/Breach_artwork.png/revision/latest/scale-to-width-down/587?cb=20200602020225" ) elif char == "Skye": embed.set_image( url="https://static.wikia.nocookie.net/valorant/images/b/b9/Skye_Keyart_final.png/revision/latest/scale-to-width-down/587?cb=20201013182515" ) elif char == "Yoru": embed.set_image( url="https://static.wikia.nocookie.net/valorant/images/a/a1/Yoru2.png/revision/latest/scale-to-width-down/587?cb=20210112180407" ) elif char == "Astra": embed.set_image( url="https://static.wikia.nocookie.net/valorant/images/8/8a/Astra_artwork.png/revision/latest/scale-to-width-down/326?cb=20210302170140" ) await ctx.reply(embed=embed) @group(name="valroll", brief="Roll a random VALORANT character.") @cooldown(1, 2, BucketType.user) async def valroll(self, ctx): """Get a random VALORANT character to play!""" if ctx.invoked_subcommand is None: await self.valroll_func(ctx) @valroll.command(name="-duelists", aliases=["-duel"]) async def valroll_duelists_command(self, ctx): characters = ( "Reyna", "Raze", "Phoenix", "Jett", "Yoru", ) char = choice((characters)) log.info(char) embed = Embed( title=f"Play: {char}", description="Enjoy!", colour=ctx.author.colour ) if char == "Phoenix": embed.set_image( url="https://static.wikia.nocookie.net/valorant/images/f/fa/Phoenix_artwork.png/revision/latest/scale-to-width-down/652?cb=20200602020246" ) elif char == "Jett": embed.set_image( url="https://static.wikia.nocookie.net/valorant/images/7/79/Jett_artwork.png/revision/latest/scale-to-width-down/587?cb=20200602020209" ) elif char == "Reyna": embed.set_image( url="https://static.wikia.nocookie.net/valorant/images/4/41/Reyna_artwork.png/revision/latest/scale-to-width-down/587?cb=20200602020340" ) elif char == "Raze": embed.set_image( url="https://static.wikia.nocookie.net/valorant/images/c/c4/Raze_artwork.png/revision/latest/scale-to-width-down/587?cb=20200602020217" ) elif char == "Yoru": embed.set_image( url="https://static.wikia.nocookie.net/valorant/images/a/a1/Yoru2.png/revision/latest/scale-to-width-down/587?cb=20210112180407" ) await ctx.reply(embed=embed) @valroll.command(name="-sentinels", aliases=["-sen", "-sentinel"]) async def valroll_sentinels_command(self, ctx): characters = ( "Sage", "Cypher", "Killjoy", ) char = choice((characters)) log.info(char) embed = Embed( title=f"Play: {char}", description="Enjoy!", colour=ctx.author.colour ) if char == "Sage": embed.set_image( url="https://static.wikia.nocookie.net/valorant/images/1/1e/Sage_artwork.png/revision/latest/scale-to-width-down/587?cb=20200602020306" ) elif char == "Cypher": embed.set_image( url="https://static.wikia.nocookie.net/valorant/images/b/bb/Cypher_artwork.png/revision/latest/scale-to-width-down/587?cb=20200602020329" ) elif char == "Killjoy": embed.set_image( url="https://static.wikia.nocookie.net/valorant/images/8/8c/Killjoy.png/revision/latest/scale-to-width-down/587?cb=20200729134445" ) await ctx.reply(embed=embed) @valroll.command(name="-initiators", aliases=["-init", "-initiator"]) async def valroll_initiators_command(self, ctx): characters = ( "Breach", "Sova", "Skye", ) char = choice((characters)) log.info(char) embed = Embed( title=f"Play: {char}", description="Enjoy!", colour=ctx.author.colour ) if char == "Breach": embed.set_image( url="https://static.wikia.nocookie.net/valorant/images/5/5c/Breach_artwork.png/revision/latest/scale-to-width-down/587?cb=20200602020225" ) elif char == "Sova": embed.set_image( url="https://static.wikia.nocookie.net/valorant/images/6/61/Sova_artwork.png/revision/latest/scale-to-width-down/587?cb=20200602020314" ) elif char == "Skye": embed.set_image( url="https://static.wikia.nocookie.net/valorant/images/b/b9/Skye_Keyart_final.png/revision/latest/scale-to-width-down/587?cb=20201013182515" ) await ctx.reply(embed=embed) @valroll.command(name="-controllers", aliases=["-ctrl", "-controller"]) async def valroll_controllers_command(self, ctx): characters = ( "Omen", "Brimstone", "Viper", "Astra", ) char = choice((characters)) log.info(char) embed = Embed( title=f"Play: {char}", description="Enjoy!", colour=ctx.author.colour ) if char == "Omen": embed.set_image( url="https://static.wikia.nocookie.net/valorant/images/0/06/Omen_artwork.png/revision/latest/scale-to-width-down/587?cb=20200602020233" ) elif char == "Brimstone": embed.set_image( url="https://static.wikia.nocookie.net/valorant/images/3/37/Brimstone_artwork.png/revision/latest/scale-to-width-down/587?cb=20200602020239" ) elif char == "Viper": embed.set_image( url="https://static.wikia.nocookie.net/valorant/images/9/91/Viper_artwork.png/revision/latest/scale-to-width-down/587?cb=20200602020322" ) elif char == "Astra": embed.set_image( url="https://static.wikia.nocookie.net/valorant/images/8/8a/Astra_artwork.png/revision/latest/scale-to-width-down/326?cb=20210302170140" ) await ctx.reply(embed=embed) @command(name="owoify", aliases=["owo"], brief="'Owoify' your text.") async def owoify_command(self, ctx, *, text: str): """<:4Weird:799869851190558751> 🤚🛑 STOP IT WEEBS""" owo_text = owoifactor.owoify(text) await ctx.reply(f"{owo_text}") @command( name="owroll", aliases=["overwatchroll"], brief="Roll a random Overwatch character.", ) @cooldown(1, 3, BucketType.user) async def overwatch_roll_command(self, ctx): """Get a random Overwatch character to play!""" characters = ( "D.va", "Orisa", "Reinhardt", "Roadhog", "Sigma", "Winston", "<NAME>", "Zarya", "Ashe", "Bastion", "Doobfist", "Echo", "Genji", "Hanzo", "Junkrat", "McCree", "Mei", "Pharah", "Reaper", "Soldier: 76", "Sombra", "Symmetra", "Torbjörn", "Tracer", "Widowmaker", "Ana", "Baptiste", "Brigitte", "Lúcio", "Mercy", "Moira", "Zenyatta", ) char = choice((characters)) log.info(char) embed = Embed( title=f"Play: {char}", description="Enjoy!", colour=ctx.author.colour ) if char == "D.va": embed.set_image( url="https://static.wikia.nocookie.net/overwatch/images/d/dc/Dva_portrait.png/revision/latest/scale-to-width-down/786?cb=20160429040128" ) elif char == "Orisa": embed.set_image( url="https://static.wikia.nocookie.net/overwatch/images/f/f9/Orisa_portrait.png/revision/latest/scale-to-width-down/795?cb=20170323183330" ) elif char == "Reinhardt": embed.set_image( url="https://static.wikia.nocookie.net/overwatch/images/a/a2/Reinhardt-ow2.png/revision/latest/scale-to-width-down/1000?cb=20201021030948" ) elif char == "Roadhog": embed.set_image( url="https://static.wikia.nocookie.net/overwatch/images/1/15/Roadhog_portrait_m.png/revision/latest/scale-to-width-down/1000?cb=20160429040723" ) elif char == "Sigma": embed.set_image( url="https://static.wikia.nocookie.net/overwatch/images/6/6a/Sigma_Portrait.png/revision/latest/scale-to-width-down/621?cb=20200326150607" ) elif char == "Winston": embed.set_image( url="https://static.wikia.nocookie.net/overwatch/images/1/1f/Winston-ow2.png/revision/latest/scale-to-width-down/852?cb=20201122033102" ) elif char == "Wrecking Ball": embed.set_image( url="https://static.wikia.nocookie.net/overwatch/images/8/83/WreckingBall_portrait.png/revision/latest?cb=20190114232714" ) elif char == "Zarya": embed.set_image( url="https://static.wikia.nocookie.net/overwatch/images/d/d1/Zarya_portrait.png/revision/latest/scale-to-width-down/725?cb=20160429041121" ) elif char == "Ashe": embed.set_image( url="https://static.wikia.nocookie.net/overwatch/images/c/c1/Ashe_portrait2.png/revision/latest/scale-to-width-down/878?cb=20181106125518" ) elif char == "Bastion": embed.set_image( url="https://static.wikia.nocookie.net/overwatch/images/6/6a/Bastion_portrait.png/revision/latest/scale-to-width-down/932?cb=20160429042023" ) elif char == "Doomfist": embed.set_image( url="https://static.wikia.nocookie.net/overwatch/images/0/0e/Doomfist_portrait.png/revision/latest/scale-to-width-down/699?cb=20170807035611" ) elif char == "Echo": embed.set_image( url="https://static.wikia.nocookie.net/overwatch/images/5/53/Echo_portrait.png/revision/latest/scale-to-width-down/321?cb=20200319191425" ) elif char == "Genji": embed.set_image( url="https://static.wikia.nocookie.net/overwatch/images/2/23/Genji-ow2.png/revision/latest/scale-to-width-down/521?cb=20201122032955" ) elif char == "Hanzo": embed.set_image( url="https://static.wikia.nocookie.net/overwatch/images/c/c2/Hanzo_portrait.png/revision/latest/scale-to-width-down/579?cb=20160429042113" ) elif char == "Junkrat": embed.set_image( url="https://static.wikia.nocookie.net/overwatch/images/5/53/Junkrat_portrait.png/revision/latest/scale-to-width-down/545?cb=20160429040823" ) elif char == "McCree": embed.set_image( url="https://static.wikia.nocookie.net/overwatch/images/f/f3/Mccree_portrait.png/revision/latest/scale-to-width-down/748?cb=20160429041214" ) elif char == "Mei": embed.set_image( url="https://static.wikia.nocookie.net/overwatch/images/3/33/Mei-ow2.png/revision/latest/scale-to-width-down/595?cb=20201122033029" ) elif char == "Pharah": embed.set_image( url="https://static.wikia.nocookie.net/overwatch/images/f/fe/Pharah_portrait.png/revision/latest/scale-to-width-down/725?cb=20160429041650" ) elif char == "Reaper": embed.set_image( url="https://static.wikia.nocookie.net/overwatch/images/e/ee/Reaper_portrait.png/revision/latest/scale-to-width-down/721?cb=20160429041404" ) elif char == "Soldier: 76": embed.set_image( url="https://static.wikia.nocookie.net/overwatch/images/c/c3/Soldier76_portrait.png/revision/latest/scale-to-width-down/653?cb=20160429041023" ) elif char == "Sombra": embed.set_image( url="https://static.wikia.nocookie.net/overwatch/images/f/fc/Sombra_portrait.png/revision/latest/scale-to-width-down/518?cb=20170105140023" ) elif char == "Symmetra": embed.set_image( url="https://static.wikia.nocookie.net/overwatch/images/e/eb/Symmetra_portrait.png/revision/latest/scale-to-width-down/546?cb=20160429041836" ) elif char == "Torbjörn": embed.set_image( url="https://static.wikia.nocookie.net/overwatch/images/e/e5/Torbjorn_portrait.png/revision/latest/scale-to-width-down/819?cb=20160429041926" ) elif char == "Tracer": embed.set_image( url="https://static.wikia.nocookie.net/overwatch/images/0/07/Tracer-ow2.png/revision/latest/scale-to-width-down/424?cb=20201122033046" ) elif char == "Widowmaker": embed.set_image( url="https://static.wikia.nocookie.net/overwatch/images/1/1e/Widow.png/revision/latest/scale-to-width-down/1000?cb=20201211185156" ) elif char == "Ana": embed.set_image( url="https://static.wikia.nocookie.net/overwatch/images/0/0b/Ana_portrait2.png/revision/latest/scale-to-width-down/1000?cb=20181108050042" ) elif char == "Baptiste": embed.set_image( url="https://static.wikia.nocookie.net/overwatch/images/1/1c/Baptiste_Portrait.png/revision/latest/scale-to-width-down/502?cb=20200326145408" ) elif char == "Brigitte": embed.set_image( url="https://static.wikia.nocookie.net/overwatch/images/7/7b/Brigitte_portrait.png/revision/latest/scale-to-width-down/750?cb=20190114232133" ) elif char == "Lúcio": embed.set_image( url="https://static.wikia.nocookie.net/overwatch/images/4/44/Lucio-ow2.png/revision/latest/scale-to-width-down/455?cb=20201122033010" ) elif char == "Mercy": embed.set_image( url="https://static.wikia.nocookie.net/overwatch/images/7/75/Mercy-ow2.png/revision/latest/scale-to-width-down/505?cb=20201122032817" ) elif char == "Moira": embed.set_image( url="https://static.wikia.nocookie.net/overwatch/images/a/a2/Moira_portrait0.png/revision/latest/scale-to-width-down/747?cb=20181108054744" ) elif char == "Zenyatta": embed.set_image( url="https://static.wikia.nocookie.net/overwatch/images/f/f5/Zenyatta_portrait.png/revision/latest/scale-to-width-down/846?cb=20160429042336" ) await ctx.reply(embed=embed) @command(name="coinflip", aliases=["cf"], brief="Flip a coin") async def coin_flip_command(self, ctx): if random() > 0.001: await ctx.reply(choice(("Heads!", "Tails!"))) else: await ctx.reply("The coin landed on its side...") @command(name="coinfliptimes", aliases=["cft"], brief="Flip a coin multiple times") async def coin_flip_times_command(self, ctx, num: int): heads = 0 tails = 0 if num <= 1000: num = num num_limit = False else: num = 1000 num_limit = True for x in range(0, num): coinflip = choice(("Heads", "Tails")) if coinflip == "Heads": heads += 1 elif coinflip == "Tails": tails += 1 embed = Embed( title="Coinflip Results:", description=f"Tails: {str(tails)}\nHeads: {str(heads)}", colour=ctx.author.color, ) if tails > heads: embed.set_footer( text=f"Tails won by {tails-heads}!", icon_url=ctx.author.avatar_url ) elif tails < heads: embed.set_footer( text=f"Heads won by {heads-tails}!", icon_url=ctx.author.avatar_url ) else: embed.set_footer(text="TIE!", icon_url=ctx.author.avatar_url) if num_limit: embed.set_footer( text="The maximum number is 1000, your number was too big.", icon_url=ctx.author.avatar_url, ) await ctx.reply(embed=embed) @Cog.listener() async def on_ready(self): if not self.bot.ready: self.bot.cogs_ready.ready_up("fun") def setup(bot): bot.add_cog(Fun(bot))
StarcoderdataPython
3448697
import os, time, flask, string, MySQLdb, openpyxl, wtforms, jinja2 from flask import Flask, Blueprint, render_template, request, redirect, url_for, flash, sessions, session, send_from_directory, send_file from flaskr import app, allowed_file, flask_bcrypt, db, bcrypt, models from os.path import join, dirname, realpath from flask_sqlalchemy import SQLAlchemy from openpyxl import load_workbook from werkzeug.utils import * from werkzeug.wrappers import BaseRequest from werkzeug.wsgi import responder from werkzeug.exceptions import HTTPException, NotFound from forms import RegistrationForm, LoginForm, PostForm from flaskr.models import User, Post from flask_bcrypt import Bcrypt from flask_login import login_user, current_user, logout_user, login_required from flask_sqlalchemy import * from sqlalchemy import * from github import Github from string import ascii_lowercase import itertools #Github configuration, for automatic update checking. f = open("githublogin.txt", "r") for x in f: username = f.readline() password = f.readline() g = Github(username, password) #For the exception catchers, for some reason they need a value first. a, b, c, d = '', '', '', '' @app.route('/', methods=['GET', 'POST']) @app.route('/page/<int:page>', methods=['GET', 'POST']) def index(page=1): try: registerform = RegistrationForm() if registerform.validate_on_submit(): checkUsername = registerform.username.data checkEmail = registerform.email.data hashed_password = bcrypt.generate_password_hash(registerform.password.data).decode('utf-8') user = User(username=registerform.username.data, email=registerform.email.data, password=<PASSWORD>) usernameExists = db.session.query(db.session.query(User).filter_by(username=checkUsername).exists()).scalar() emailExists = db.session.query(db.session.query(User).filter_by(email=checkEmail).exists()).scalar() if usernameExists or emailExists: message = 'That username or email is already taken' flash(str(message), 'loginError') return redirect("/") return render_template('index.html', loginError=loginError) else: db.session.add(user) db.session.commit() message = 'Registration succesfull!' flash(str(message), 'loginError') return redirect("/") return render_template('index.html', loginError=loginError) return redirect("/") return render_template('index.html', loginError=loginError) loginform = LoginForm() if loginform.validate_on_submit(): user = User.query.filter_by(email=loginform.email.data).first() if user and bcrypt.check_password_hash(user.password, loginform.password.data): login_user(user, remember=loginform.remember.data) #next_page = request.args.get('next') #return redirect(next_page) if next_page else redirect(url_for('index')) return redirect(url_for('/')) else: message = 'Invalid login, please check your login values and try again' flash(str(message), 'loginError') return redirect("/") return render_template('index.html', loginError=loginError) if current_user.is_authenticated: userfolder = current_user.username converteduserfiles = [] userfiles = [] path = f'files/{userfolder}/' if (os.path.exists(f'files/{userfolder}/converted')): pathtoconverted = f'files/{userfolder}/converted' else: if not (os.path.exists(f'files/{userfolder}')): os.mkdir(f'files/{userfolder}') os.mkdir(f'files/{userfolder}/converted') pathtoconverted = f'files/{userfolder}/converted' for filename in os.listdir(path): if os.path.isfile and filename != 'converted': userfiles.append(filename) for filename in os.listdir(pathtoconverted): if os.path.isfile: converteduserfiles.append(filename) else: filename = '' path = '' userfiles = '', '' converteduserfiles = '' pathtoconverted = '' session['filename'] = filename session['path'] = path session['userfiles[]'] = userfiles session['converteduserfiles[]'] = converteduserfiles session['pathtoconverted'] = pathtoconverted session['filename'] = filename session['path'] = path session['userfiles[]'] = userfiles session['converteduserfiles[]'] = converteduserfiles session['pathtoconverted'] = pathtoconverted postform = PostForm() if postform.validate_on_submit(): post = Post(title=postform.title.data, content=postform.content.data, author=current_user) db.session.add(post) db.session.commit() flash('Your post has been created!', 'success') return redirect(url_for('index')) RESULTS_PER_PAGE = 5 #posts = Post.query.all() #models.Post.query.paginate(page, per_page, error_out=False) #posts = Post.query.order_by(Post.id.title()).paginate(page,per_page,error_out=False) posts = models.Post.query.paginate(page, RESULTS_PER_PAGE, False) num = int(ceil(float(posts.total) / RESULTS_PER_PAGE)) + 1 environment = jinja2.Environment(os) environment.filters['os'] = os #{% for post in posts|sort(attribute='date_posted', reverse=true) %} #VERGEET DIT NIET TE VERANDEREN IN BETWEEN RELEASES TIM currentVersion = "Excelsplitter version 1.0.2" repo = g.get_repo("timdeplatvis111/ExcelSplitter") print(repo.name) #repo.compare latestRelease = repo.get_latest_release() if latestRelease.title == currentVersion: uptodate = 'true' else: uptodate = 'false' return render_template('index.html', title='Account', loginform=loginform, registerform=registerform, postform=postform, posts=posts, number_of_pages=num, userfiles=session['userfiles[]'], path=session['path'], filename=session['filename'], pathtoconverted=session['pathtoconverted'], converteduserfiles=session['converteduserfiles[]'], os=os, uptodate=uptodate) #All exception catchers, most of these will never happen but they're there just to be sure. except KeyError as a: flash(str(a), 'error') return redirect("/") return render_template('index.html', error=error) session.pop('_flashes', None) except NameError as b: flash(str(b), 'error') return redirect("/") return render_template('index.html', error=error) session.pop('_flashes', None) except ValueError as c: flash(str(c), 'error') return redirect("/") return render_template('index.html', error=error) session.pop('_flashes', None) except TypeError as f: flash(str(f), 'error') return redirect("/") return render_template('index.html', error=error) session.pop('_flashes', None) except: #message = 'You broke my webapp somehow, if this is a recurring error then please contact the developer' #flash(str(message), 'error') return redirect("/") #return render_template('index.html', error=error) return render_template('index.html') session.pop('_flashes', None) """ @app.route(, methods=['GET', 'POST']) def userfiles(): filename = session.get('filename') path = session.get('path') userfiles = session.get('userfiles[]') for index, filename in enumerate(userfiles): print('nice') return send_from_directory(f'../{path}', userfiles[index], as_attachment=True) """ @app.route('/files/<filename>', methods=['GET', 'POST']) def files(filename): try: path = session.get('path') userfiles = session.get('userfiles[]') return send_from_directory(f'../{path}', filename, as_attachment=True) except KeyError as d: flash(str(d), 'error') return redirect("/") return render_template('index.html', error=error) except NameError as b: flash(str(b), 'error') return redirect("/") return render_template('index.html', error=error) session.pop('_flashes', None) except ValueError as c: flash(str(c), 'error') return redirect("/") return render_template('index.html', error=error) session.pop('_flashes', None) except TypeError as f: flash(str(f), 'error') return redirect("/") return render_template('index.html', error=error) session.pop('_flashes', None) except: message = 'An error was detected, please try again' flash(str(message), 'error') return redirect("/") return render_template('index.html', error=error) @app.route('/files/converted/<filename>', methods=['GET', 'POST']) def files2(filename): try: pathtoconverted = session.get('pathtoconverted') converteduserfiles = session.get('converteduserfiles[]') return send_from_directory(f'../{pathtoconverted}', filename, as_attachment=True) except KeyError as d: flash(str(d), 'error') return redirect("/") return render_template('index.html', error=error) except NameError as b: flash(str(b), 'error') return redirect("/") return render_template('index.html', error=error) session.pop('_flashes', None) except ValueError as c: flash(str(c), 'error') return redirect("/") return render_template('index.html', error=error) session.pop('_flashes', None) except TypeError as f: flash(str(f), 'error') return redirect("/") return render_template('index.html', error=error) session.pop('_flashes', None) except: message = 'An error was detected, please try again' flash(str(message), 'error') return redirect("/") return render_template('index.html', error=error) @app.route('/logout') def logout(): logout_user() return redirect(url_for('index')) @app.route('/upload', methods=['POST', 'GET']) def upload(): try: #Takes the files from the forms request.files['uploadedfile1'] request.files['uploadedfile2'] userfolder = current_user.username #Creates a list from the files so we can loop through them later yeet1 = request.files.getlist('uploadedfile1') yeet2 = request.files.getlist('uploadedfile2') yeet3 = yeet1 + yeet2 filenamen = [] #Loops through the filelist for file in yeet3: files = request.files.to_dict() filename = secure_filename(file.filename) filenamen.append(filename) #Checks if the uploaded file is an .xlxs file if file and allowed_file(filename): if (os.path.exists(f'files/{userfolder}')): file.save(f'files/{userfolder}/{filename}') else: os.makedirs(f'files/{userfolder}') file.save(f'files/{userfolder}/{filename}') else: fileerror= 'fuck' flash('yeet', 'fileerror') return render_template('index.html', fileerror=fileerror) if len(filenamen) is not 2: flash('Please upload 2 Excel files', 'error') return render_template('convert.html', error=error) else: #Puts the filenames into a session for use in the next route session['filenamen[]'] = filenamen return render_template('convert.html', filenamen=session['filenamen[]']) except KeyError as d: flash(str(d), 'error') return redirect("/") return render_template('index.html', error=error) except NameError as b: flash(str(b), 'error') return redirect("/") return render_template('index.html', error=error) session.pop('_flashes', None) except ValueError as c: flash(str(c), 'error') return redirect("/") return render_template('index.html', error=error) session.pop('_flashes', None) except TypeError as f: flash(str(f), 'error') return redirect("/") return render_template('index.html', error=error) session.pop('_flashes', None) except: message = 'An error was detected, please try again' flash(str(message), 'error') return redirect("/") return render_template('index.html', error=error) @app.route('/brupload', methods=['POST', 'GET']) def brupload(): try: request.files['bruploadedfile'] userfolder = current_user.username yeet4 = request.files.getlist('bruploadedfile') brfilenamen = [] for file in yeet4: files = request.files.to_dict() filename = secure_filename(file.filename) brfilenamen.append(filename) print(brfilenamen[0]) #Checks if the uploaded file is an .xlxs file if file and allowed_file(filename): if (os.path.exists(f'files/{userfolder}/br')): file.save(f'files/{userfolder}/br/{filename}') else: os.makedirs(f'files/{userfolder}/br') file.save(f'files/{userfolder}/br/{filename}') else: fileerror= 'fuck' flash('yeet', 'fileerror') return render_template('index.html', fileerror=fileerror) session['brfilenamen[]'] = brfilenamen return render_template('brconvert.html', brfilenamen=session['brfilenamen[]']) except KeyError as d: flash(str(d), 'error') return redirect("/") return render_template('index.html', error=error) except NameError as b: flash(str(b), 'error') return redirect("/") return render_template('index.html', error=error) session.pop('_flashes', None) except ValueError as c: flash(str(c), 'error') return redirect("/") return render_template('index.html', error=error) session.pop('_flashes', None) except TypeError as f: flash(str(f), 'error') return redirect("/") return render_template('index.html', error=error) session.pop('_flashes', None) except: message = 'An error was detected, please try again' flash(str(message), 'error') return redirect("/") return render_template('index.html', error=error) @app.route('/brconvert', methods=['GET', 'POST']) def brconvert(): try: def iter_all_strings(): for size in itertools.count(1): for letter in itertools.product(ascii_lowercase, repeat=size): yield "".join(letter) values = dict() randomindex = 0 for letter in itertools.islice(iter_all_strings(), 30): randomindex +=1 values[randomindex] = letter userfolder = current_user.username brfilenamen = session.get('brfilenamen[]') filenaam1 = brfilenamen[0] print(brfilenamen[0]) workbook1 = load_workbook(filename=(f"files/{userfolder}/br/{filenaam1}")) sheet1 = workbook1.active column1 = request.form['column1'] column1 = int(column1) sheet1column = values[column1] br = '<br> ' closebr = ' <br />' for cell in sheet1[sheet1column]: I = cell.row brplacedata = sheet1.cell(row=I, column=column1).value brplacedata = br + brplacedata + closebr sheet1.cell(row=I, column=column1, value=brplacedata) workbook1.save(f'files/{userfolder}/{filenaam1}') return send_from_directory(f'../files/{userfolder}', filenaam1, as_attachment=True) except KeyError as d: flash(str(d), 'error') return redirect("/") return render_template('index.html', error=error) except NameError as b: flash(str(b), 'error') return redirect("/") return render_template('index.html', error=error) session.pop('_flashes', None) except ValueError as c: flash(str(c), 'error') return redirect("/") return render_template('index.html', error=error) session.pop('_flashes', None) except TypeError as f: flash(str(f), 'error') return redirect("/") return render_template('index.html', error=error) session.pop('_flashes', None) except: message = 'An error was detected, please try again' flash(str(message), 'error') return redirect("/") return render_template('index.html', error=error) @app.route('/convert', methods=['GET', 'POST']) def convert(): try: def iter_all_strings(): for size in itertools.count(1): for letter in itertools.product(ascii_lowercase, repeat=size): yield "".join(letter) values = dict() randomindex = 0 for letter in itertools.islice(iter_all_strings(), 30): randomindex +=1 values[randomindex] = letter #Sets the userfolder equal to the logged in user's username. userfolder = current_user.username #Gets the filenamen list from the session filenamen = session.get('filenamen[]') #Splits the array into 2 seperate variables filenaam1 = filenamen[0] filenaam2 = filenamen[1] #column1 = The first column you want to compare, generated from the form (filenaam1) #column2 = The second column you want to compare, generated from the form (filenaam2) column1 = request.form['column1'] column2 = request.form['column2'] #option = Variable for deciding which file you want to copy values from option = request.form['option'] #column1copy = The column where it copies the values from #column2copy = The column where it copies the values to column1copy = request.form['column1copy'] column2copy = request.form['column2copy'] #part1column = The first position for the string matching system #part2column = The second position for the string matching system #Example: part1column = 5, part2column = 7 #With these values it matches the 6th character (counting from 1) to the 8th character (counting from 1) partcolumn1 = request.form['partcolumn1'] partcolumn2 = request.form['partcolumn2'] #Sets both workbooks as active, so we can manipulate them using openpyxl workbook1 = load_workbook(filename=(f"files/{userfolder}/{filenaam1}")) sheet1 = workbook1.active workbook2 = load_workbook(filename=(f"files/{userfolder}/{filenaam2}")) sheet2 = workbook2.active #Converts these values to integers for later use column1copy = int(column1copy) column2copy = int(column2copy) column1 = int(column1) column2 = int(column2) #Checks if these values are empty, then sets them to a high value to prevent errors if partcolumn1 == '' or partcolumn2 == '': partcolumn1 = 0 partcolumn2 = 100000 partcolumn1 = int(partcolumn1) partcolumn2 = int(partcolumn2) else: partcolumn1 = int(partcolumn1) partcolumn2 = int(partcolumn2) sheet1column = values[column1] sheet2column = values[column2] keepdataoption = request.form['keepdataoption'] colourcells = request.form['colourcells'] color1 = request.form['color1'] #Sets the colour of the cell coloring feature. myColour = openpyxl.styles.colors.Color(rgb=color1) colourFill = openpyxl.styles.fills.PatternFill(patternType='solid', fgColor=myColour) #Defines some variables for measuring the time, amount of loops, and the amount of skipped loops t = time.process_time() loops = 0 errorloops = 0 #This if statement can definitely be removed somehow, writing this code twice is really inefficient. if option == 'file0': filename = filenaam1 for cell in sheet1[sheet1column]: try: filename = filenaam2 I = cell.row sheet1value = sheet1.cell(row=I, column=column1).value print(sheet1value) #time.sleep(5) if sheet1value != None: try: sheet1value = sheet1value[partcolumn1:partcolumn2] except: print("Out of range") pass for cell in sheet2[sheet2column]: E = cell.row sheet2value = sheet2.cell(row=E, column=column2).value print(sheet2value) #time.sleep(5) if sheet2value != None: try: sheet2value = sheet2value[partcolumn1:partcolumn2] except: print("Out of range") pass if sheet1value == sheet2value: sheet1copyvalue = sheet1.cell(row=I, column=column1copy).value if colourcells == 'colourcells2': sheet2.cell(row=E, column=column2copy).fill = colourFill if keepdataoption == 'keepdata1': keepdatacell = sheet2.cell(row=E, column=column2copy).value try: keepdatacell = keepdatacell + sheet1copyvalue sheet2.cell(row=E, column=column2copy, value=keepdatacell) loops +=1 except: sheet2.cell(row=E, column=column2copy, value=sheet1copyvalue) loops +=1 else: sheet2.cell(row=E, column=column2copy, value=sheet1copyvalue) loops +=1 else: loops +=1 except: print('F') print('sheet1value') print(sheet1value) print('sheet2value') print(sheet2value) errorloops +=1 elif option == 'file1': filename = filenaam2 for cell in sheet2[sheet2column]: try: I = cell.row sheet2value = sheet2.cell(row=I, column=column2).value print(sheet2value) #time.sleep(5) if sheet2value != None: try: sheet2value = sheet2value[partcolumn1:partcolumn2] except: print("Out of range") pass for cell in sheet1[sheet1column]: E = cell.row sheet1value = sheet1.cell(row=E, column=column1).value print(sheet1value) #time.sleep(5) if sheet1value != None: try: sheet1value = sheet1value[partcolumn1:partcolumn2] except: print("Out of range") pass if sheet2value == sheet1value: sheet1copyvalue = sheet2.cell(row=I, column=column1copy).value if colourcells == 'colourcells2': sheet1.cell(row=E, column=column2copy).fill = colourFill if keepdataoption == 'keepdata1': keepdatacell = sheet1.cell(row=E, column=column2copy).value try: keepdatacell = keepdatacell + sheet1copyvalue sheet1.cell(row=E, column=column2copy, value=keepdatacell) loops +=1 except: sheet1.cell(row=E, column=column2copy, value=sheet1copyvalue) loops +=1 else: sheet1.cell(row=E, column=column2copy, value=sheet1copyvalue) loops +=1 else: loops +=1 except: print('F') print('sheet1value') print(sheet1value) print('sheet2value') print(sheet2value) errorloops +=1 #Saves the files to our userfolder if option == 'file0': if (os.path.exists(f'files/{userfolder}')): workbook1.save(f'files/{userfolder}/{filenaam1}') workbook2.save(f'files/{userfolder}/{filenaam2}') else: os.makedirs(f'files/{userfolder}') workbook1.save(f'files/{userfolder}/{filenaam1}') workbook2.save(f'files/{userfolder}/{filenaam2}') elif option == 'file1': if (os.path.exists(f'files/{userfolder}')): workbook1.save(f'files/{userfolder}/{filenaam1}') workbook2.save(f'files/{userfolder}/{filenaam2}') else: os.makedirs(f'files/{userfolder}') workbook1.save(f'files/{userfolder}/{filenaam1}') workbook2.save(f'files/{userfolder}/{filenaam2}') #Measured the time it takes for the program to go through all the code above elapsed_time = time.process_time() - t #Renders the amount of loops, errorloops and the amount of time it took to go through all the code above flash(elapsed_time, 'time') flash(loops, 'loops') flash(errorloops, 'errorloops') if (os.path.exists(f'files/{userfolder}/converted')): print('Converted yeet') else: os.mkdir(f'files/{userfolder}/converted') if option == 'file0': workbook2.save(f'files/{userfolder}/converted/{filenaam2}') return send_from_directory(f'../files/{userfolder}', filenaam2, as_attachment=True) elif option == 'file1': workbook1.save(f'files/{userfolder}/converted/{filenaam1}') return send_from_directory(f'../files/{userfolder}', filenaam1, as_attachment=True) #Exception catchers, just to be sure except KeyError as a: flash(str(a), 'error') return redirect("/") return render_template('index.html', error=error) except NameError as b: flash(str(b), 'error') return redirect("/") return render_template('index.html', error=error) except ValueError as c: flash(str(c), 'valueError') return redirect("/") return render_template('index.html', valueError=valueError) except TypeError as f: flash(str(f), 'error') return redirect("/") return render_template('index.html', error=error) except: message = 'An error was detected, please try again' flash(str(message), 'error') return redirect("/") return render_template('index.html', error=error) session.pop('_flashes', None)
StarcoderdataPython
3272787
# Calculate level completion rates via mixpanel export API # TODO: unique users # TODO: align output # TODO: order output import sys from mixpanel import Mixpanel try: import json except ImportError: import simplejson as json # NOTE: mixpanel dates are by day and inclusive # E.g. '2014-12-08' is any date that day, up to 2014-12-09 12am if __name__ == '__main__': if not len(sys.argv) is 3: print "Script format: <script> <api_key> <api_secret>" else: api_key = sys.argv[1] api_secret = sys.argv[2] api = Mixpanel( api_key = api_key, api_secret = api_secret ) startDate = '2014-12-31' endDate = '2015-01-05' print("Requesting data for {0} to {1}".format(startDate, endDate)) data = api.request(['export'], { 'event' : ['Started Level', 'Saw Victory'], 'from_date' : startDate, 'to_date' : endDate }) levelRates = {} lines = data.split('\n') print "Received %d entries" % len(lines) for line in lines: try: if len(line) is 0: continue eventData = json.loads(line) eventName = eventData['event'] if not eventName in ['Started Level', 'Saw Victory']: print 'Unexpected event ' + eventName break properties = eventData['properties'] if 'levelID' in properties: levelID = properties['levelID'] elif 'level' in properties: levelID = properties['level'].lower().replace(' ', '-') else: print("Unkonwn levelID for", eventName) print(properties) break if not levelID in levelRates: levelRates[levelID] = {'started': 0, 'finished': 0} if eventName == 'Started Level': levelRates[levelID]['started'] += 1 elif eventName == 'Saw Victory': levelRates[levelID]['finished'] += 1 else: print("Unknown event name", eventName) print(eventData) break except: print "Unexpected error:", sys.exc_info()[0] print line break # print(levelRates) for levelID in levelRates: started = levelRates[levelID]['started'] finished = levelRates[levelID]['finished'] # if not levelID == 'endangered-burl': # continue if started > 0: print("{0}\t{1}\t{2}\t{3}%".format(levelID, started, finished, float(finished) / started * 100)) else: print("{0}\t{1}\t{2}".format(levelID, started, finished))
StarcoderdataPython
8115101
<filename>Service/__init__.py __author__ = 'sgrubor'
StarcoderdataPython
9633667
<filename>api/handlers/orders.py from datetime import datetime from fastapi import APIRouter, status from sqlalchemy import and_ from starlette.exceptions import HTTPException from starlette.responses import JSONResponse from sqlalchemy.exc import IntegrityError from db.base import Session from api.schema import Order, Orders, Courier, CourierID, check_courier_time_for_order, OrderDone from db.schema import Order as OrderSchema, Courier as CourierSchema router = APIRouter(prefix="/orders") @router.post('/') async def post_orders(order_list: Orders): db = Session() order_ids = [] order_fail_ids = [] for order in order_list.data: db_order = OrderSchema( order_id=order.order_id, weight=order.weight, region=order.region, delivery_hours=order.delivery_hours ) db.add(db_order) try: db.commit() except IntegrityError: order_fail_ids.append(order.order_id) else: db.refresh(db_order) order_ids.append(order.order_id) if len(order_fail_ids) == 0: return JSONResponse(content={'couriers': [{'id': c_id} for c_id in order_ids]}, status_code=status.HTTP_201_CREATED) else: return JSONResponse(content={"validation_error": { 'couriers': [{'id': c_id} for c_id in order_fail_ids]}}, status_code=status.HTTP_400_BAD_REQUEST) @router.post('/assign') async def assign_post(courier_id: CourierID): response_ids = [] default_response = JSONResponse(status_code=status.HTTP_400_BAD_REQUEST) db = Session() courier_from_db = db.query(CourierSchema).get(courier_id.courier_id) if not courier_from_db: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Courier not found") query = db.query(OrderSchema).filter( and_(OrderSchema.region.in_(courier_from_db.regions)), (OrderSchema.weight <= courier_from_db.courier_type.weight()) ).all() if not query: return default_response for order in query: if check_courier_time_for_order(courier_from_db.working_hours, order.delivery_hours): order.courier_id_assigned = courier_from_db.courier_id response_ids.append(order.order_id) if response_ids: db.commit() return JSONResponse(status_code=status.HTTP_200_OK, content={ 'orders': [{'id': id_} for id_ in response_ids], 'assign_time': datetime.now().isoformat()[:-4] + 'Z' }) else: return default_response @router.post('/complete') async def complete_post(order: OrderDone): db = Session() courier_from_db = db.query(CourierSchema).get(order.courier_id) order_from_db = db.query(OrderSchema).get(order.order_id) if not courier_from_db or not order_from_db or courier_from_db.courier_id != order.courier_id: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Wrong courier or order id") # TODO count rating db.delete(order_from_db) db.commit() return JSONResponse(status_code=status.HTTP_200_OK, content={ 'order_id': order.order_id })
StarcoderdataPython
6654461
# # Created on Tue Dec 21 2021 # # Copyright (c) 2021 Lenders Cooperative, a division of Summit Technology Group, Inc. # from django.conf import settings from django.contrib import admin from django.contrib.contenttypes.models import ContentType from django.core.cache import cache from django.shortcuts import redirect from .models import ( DocusignChoiceConfig, DocusignEnvelopeStageData, DocusignOrgTemplate, DocusignTemplate, DocusignTemplateOrgExclusion, DocuSignUserAuth, ) # from loans.models import EtranLoan from .utils.docusign_helper import check_docusign_access_token @admin.register(DocusignEnvelopeStageData) class DocusignEnvelopeStageDataAdmin(admin.ModelAdmin): model = DocusignEnvelopeStageData list_display = ( "id", "envelope_id", "record_status", "recipient_status", "created", "modified", ) search_fields = ("envelope_id",) def get_actions(self, request): # Disable delete actions = super(DocusignEnvelopeStageDataAdmin, self).get_actions(request) return actions actions = ["clear_docusign_throttling_locks", "clear_docusign_app_locks"] def clear_docusign_throttling_locks(self, request, queryset): rate_reset_lock = cache.delete("docusign_rate_reset") self.message_user( request, f"DocuSign Throttling Lock Released: {rate_reset_lock}" ) clear_docusign_throttling_locks.short_description = "Clear Docusign Throttling Lock" def clear_docusign_app_locks(self, request, queryset): delete_count = 0 for loan in queryset.all(): if cache.delete(f"send_for_docusign:{loan.id}"): delete_count += 1 self.message_user( request, f"{delete_count} successfully released redis locks on applications for docusign.", ) clear_docusign_app_locks.short_description = "Clear Docusign Application Lock" @admin.register(DocusignOrgTemplate) class DocusignOrgTemplateAdmin(admin.ModelAdmin): model = DocusignOrgTemplate list_display = ( "organization_model", "docusign_template", ) # autocomplete_fields = ["organization_model"] list_filter = ( "organization_model", "docusign_template", ) @admin.register(DocusignChoiceConfig) class DocusignChoiceConfigAdmin(admin.ModelAdmin): model = DocusignChoiceConfig list_display = ( "docusign_model", "config_key", ) # autocomplete_fields = ["organization_model"] list_filter = ( "docusign_model", "config_key", ) @admin.register(DocusignTemplate) class DocusignTemplateAdmin(admin.ModelAdmin): model = DocusignTemplate list_display = ( "template_type", "is_active", "created", "modified", ) list_filter = ("template_type",) @admin.register(DocusignTemplateOrgExclusion) class DocusignTemplateOrgExclusionAdmin(admin.ModelAdmin): model = DocusignTemplateOrgExclusion list_display = ( "organization_model", "document_name", "template", ) list_filter = ("organization_model", "template") @admin.register(ContentType) class ContentTypeAdmin(admin.ModelAdmin): model = ContentType @admin.register(DocuSignUserAuth) class DocuSignUserAuthAdmin(admin.ModelAdmin): model = DocuSignUserAuth list_display = ( "organization_model", "default_user", ) # autocomplete_fields = ["organization_model"] # list_filter = ('organization_model',) def check_docusign_consent(self, request, queryset): for org in queryset: # loan = EtranLoan.objects.filter(organization_id=org.id).last() consent_url = check_docusign_access_token(org) if consent_url: print("Consent URL: " + consent_url) print("Current Path: " + request.get_full_path()) request.session["docusign_redirect_path"] = request.get_full_path() BASE_URL = settings.BASE_URL DOCUSIGN_REDIRECT_APP_URL = settings.DOCUSIGN_REDIRECT_APP_URL redirect_uri = BASE_URL + request.get_full_path() final_consent_url = consent_url.replace( DOCUSIGN_REDIRECT_APP_URL, redirect_uri ) print(f"Final Consent URL: {final_consent_url}") return redirect(final_consent_url) check_docusign_consent.short_description = ( "Check if consent is required from Docusign" ) def get_actions(self, request): # Disable delete actions = super(DocuSignUserAuthAdmin, self).get_actions(request) return actions actions = [check_docusign_consent]
StarcoderdataPython
1964321
<reponame>WING-NUS/RL-for-Question-Generation<filename>src/onqg/models/decoders/TransfDecoder.py import torch import torch.nn as nn import onqg.dataset.Constants as Constants from onqg.models.modules.MaxOut import MaxOut from onqg.models.modules.Layers import DecoderLayer from onqg.utils.mask import get_non_pad_mask, get_subsequent_mask, get_attn_key_pad_mask from onqg.utils.sinusoid import get_sinusoid_encoding_table class TransfDecoder(nn.Module): def __init__(self, n_vocab, len_max_seq, d_word_vec, d_model, n_layer, d_inner, n_head, d_k, d_v, layer_attn, n_enc_layer, feat_vocab, d_feat_vec, maxout_pool_size, dropout, mode='normal'): self.name = 'transf' super(TransfDecoder, self).__init__() n_position = len_max_seq + 5 self.layer_attn = layer_attn self.word_emb = nn.Embedding(n_vocab, d_word_vec, padding_idx=Constants.PAD) self.pos_emb = nn.Embedding.from_pretrained( get_sinusoid_encoding_table(n_position, d_word_vec, padding_idx=Constants.PAD), freeze=True ) self.feature = False if not feat_vocab else True self.d_feat = len(feat_vocab) * d_feat_vec if self.feature else 0 if self.feature: self.feat_embs = nn.ModuleList([ nn.Embedding(n_f_vocab, d_feat_vec, padding_idx=Constants.PAD) for n_f_vocab in feat_vocab ]) self.layer_stack = nn.ModuleList([ DecoderLayer(d_model, d_inner, n_head, d_k, d_v, addition_input=self.d_feat, dropout=dropout, layer_attn=layer_attn, n_enc_layer=n_enc_layer) for _ in range(n_layer) ]) self.maxout = MaxOut(maxout_pool_size) self.maxout_pool_size = maxout_pool_size @classmethod def from_opt(cls, opt): if 'mode' not in opt: opt['mode'] = 'normal' return cls(opt['n_vocab'], opt['len_max_seq'], opt['d_word_vec'], opt['d_model'], opt['n_layer'], opt['d_inner'], opt['n_head'], opt['d_k'], opt['d_v'], opt['layer_attn'], opt['n_enc_layer'], opt['feat_vocab'], opt['d_feat_vec'], opt['maxout_pool_size'], opt['dropout'], opt['mode'],) def forward(self, inputs, max_length=300, return_attns=False): tgt_seq, tgt_pos, feat_seqs = inputs['tgt_seq'], inputs['tgt_pos'], inputs['feat_seqs'] src_seq, enc_output, _ = inputs['src_seq'], inputs['enc_output'], inputs['hidden'] non_pad_mask = get_non_pad_mask(tgt_seq) slf_attn_mask_subseq = get_subsequent_mask(tgt_seq) slf_attn_mask_keypad = get_attn_key_pad_mask(seq_k=tgt_seq, seq_q=tgt_seq) slf_attn_mask = (slf_attn_mask_keypad + slf_attn_mask_subseq).gt(0) dec_enc_attn_mask = get_attn_key_pad_mask(seq_k=src_seq, seq_q=tgt_seq) if self.layer_attn: enc_output = torch.stack(enc_output) # layer_num x batch_size x src_len x dim batch_size, layer_num, dim = enc_output.size(1), enc_output.size(0), enc_output.size(-1) layer_src_seq = src_seq.unsqueeze(1).repeat(1, layer_num, 1) # batch_size x layer_num x src_len layer_src_seq = layer_src_seq.contiguous().view(batch_size, -1) # batch_size x (layer_num x src_len) dec_enc_attn_mask = get_attn_key_pad_mask(seq_k=layer_src_seq, seq_q=tgt_seq) enc_output = enc_output.permute(1, 0, 2, 3).contiguous().view(batch_size, -1, dim) # batch_size x (layer_num x src_len) x dim if self.feature: feat_inputs = [feat_emb(feat_seq) for feat_seq, feat_emb in zip(feat_seqs, self.feat_embs)] feat_inputs = torch.cat(feat_inputs, dim=2) if self.layer_attn: feat_inputs = feat_inputs.repeat(1, layer_num, 1) enc_output = torch.cat((enc_output, feat_inputs), dim=2) dec_output = self.word_emb(tgt_seq) + self.pos_emb(tgt_pos) for dec_layer in self.layer_stack: dec_output, *_ = dec_layer(dec_output, enc_output, non_pad_mask=non_pad_mask, slf_attn_mask=slf_attn_mask, dec_enc_attn_mask=dec_enc_attn_mask) dec_output = self.maxout(dec_output) rst = {'pred':dec_output} return rst
StarcoderdataPython
359653
# coding: utf-8 """ Idfy.Signature Sign contracts, declarations, forms and other documents using digital signatures. ## Last update Last build date for this endpoint: 18.03.2019 """ import pprint import re from typing import List, Dict from datetime import datetime as datetime from idfy_sdk.services.signature.models.document_summary import DocumentSummary from idfy_sdk.services.signature.models.links import Links class CollectionWithPagingDocumentSummary(object): """NOTE: This class is generated by Eivind. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'offset': int, 'limit': int, 'size': int, 'links': Links, 'data': List[DocumentSummary] } attribute_map = { 'offset': 'offset', 'limit': 'limit', 'size': 'size', 'links': 'links', 'data': 'data' } def __init__(self, offset=None, limit=None, size=None, links=None, data=None): self._offset = None self._limit = None self._size = None self._links = None self._data = None self.discriminator = None if offset is not None: self.offset = offset if limit is not None: self.limit = limit if size is not None: self.size = size if links is not None: self.links = links if data is not None: self.data = data @property def offset(self): """Gets the offset of this CollectionWithPagingDocumentSummary. The offset of the current page. :return: The offset of this CollectionWithPagingDocumentSummary. :rtype: int """ return self._offset @offset.setter def offset(self, offset): """Sets the offset of this CollectionWithPagingDocumentSummary. The offset of the current page. :param offset: The offset of this CollectionWithPagingDocumentSummary. :type: int """ self._offset = offset @property def limit(self): """Gets the limit of this CollectionWithPagingDocumentSummary. The limit of the current paging options. :return: The limit of this CollectionWithPagingDocumentSummary. :rtype: int """ return self._limit @limit.setter def limit(self, limit): """Sets the limit of this CollectionWithPagingDocumentSummary. The limit of the current paging options. :param limit: The limit of this CollectionWithPagingDocumentSummary. :type: int """ self._limit = limit @property def size(self): """Gets the size of this CollectionWithPagingDocumentSummary. The total size of the collection (irrespective of any paging options). :return: The size of this CollectionWithPagingDocumentSummary. :rtype: int """ return self._size @size.setter def size(self, size): """Sets the size of this CollectionWithPagingDocumentSummary. The total size of the collection (irrespective of any paging options). :param size: The size of this CollectionWithPagingDocumentSummary. :type: int """ self._size = size @property def links(self): """Gets the links of this CollectionWithPagingDocumentSummary. :return: The links of this CollectionWithPagingDocumentSummary. :rtype: Links """ return self._links @links.setter def links(self, links): """Sets the links of this CollectionWithPagingDocumentSummary. :param links: The links of this CollectionWithPagingDocumentSummary. :type: Links """ self._links = links @property def data(self): """Gets the data of this CollectionWithPagingDocumentSummary. :return: The data of this CollectionWithPagingDocumentSummary. :rtype: List[DocumentSummary] """ return self._data @data.setter def data(self, data): """Sets the data of this CollectionWithPagingDocumentSummary. :param data: The data of this CollectionWithPagingDocumentSummary. :type: List[DocumentSummary] """ self._data = data def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in self.swagger_types.items(): 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_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, CollectionWithPagingDocumentSummary): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
StarcoderdataPython
8082784
import sys import subprocess import logging from pathlib import Path import numpy as np from types import SimpleNamespace import io from contextlib import redirect_stdout from PyQt5 import QtGui, QtWidgets, QtCore from PyQt5.QtCore import Qt, QObject, pyqtSlot, QThread, pyqtSignal, QLocale from PyQt5.QtGui import QIcon, QPixmap from PyQt5.QtGui import QTextCursor from pyqtgraph.dockarea import Dock from pyqtgraph.parametertree import Parameter, ParameterTree from pymodaq.daq_utils import daq_utils as utils from pymodaq.daq_utils import gui_utils as gutils from pymodaq.daq_utils.parameter import utils as putils, ioxml from pymodaq.daq_utils.h5modules import browse_data from pymodaq.daq_utils.plotting.viewer2D.viewer2D_main import Viewer2D from pymodaq.daq_utils.plotting.viewer1D.viewer1D_main import Viewer1D from pymodaq.daq_utils.plotting.viewer0D.viewer0D_main import Viewer0D from pymodaq.daq_utils.managers.roi_manager import LinearROI from pymodaq_femto.graphics import RetrievalResultPlot, MplCanvas, NavigationToolbar, MeshDataPlot, PulsePlot, PulsePropagationPlot from pymodaq_femto.simulation import Simulator, methods, nlprocesses, materials from collections import OrderedDict from pypret import FourierTransform, Pulse, PNPS, lib, MeshData, random_gaussian from pypret.frequencies import om2wl, wl2om, convert import scipy import importlib from scipy.fftpack import next_fast_len from pymodaq.daq_utils.h5modules import H5BrowserUtil, H5Saver from pyqtgraph.graphicsItems.GradientEditorItem import Gradients from pymodaq_femto import _PNPS_CLASSES from pypret.retrieval.retriever import _RETRIEVER_CLASSES import warnings import math import inspect import pymodaq_femto.materials retriever_algos = list(_RETRIEVER_CLASSES.keys()) config = utils.load_config() logger = utils.set_logger(utils.get_module_name(__file__)) materials_propagation = [] for item in inspect.getmembers(pymodaq_femto.materials): if isinstance(item[1], pymodaq_femto.materials.BaseMaterial): materials_propagation.append(item[1]) class DataIn(OrderedDict): def __init__(self, name='', source='', trace_in=None, pulse_in=None, raw_spectrum=None, raw_trace=None, **kwargs): """class subclassing from OrderedDict defining data to be processed by the retriever, either experimental or simulated Parameters ---------- name: (str) data identifier source: (str) either "simulated" or "experimental" trace_in: (MeshData) MeshData object as defined in pypret and containing the trace data pulse_in: (Pulse) Pulse object as defined in pypret and containing fundamental spectrum (at least) raw_spectrum: (dict) with data and axis as keys containing the spectrum and an Axis object raw_trace: (dict) with data axis and parameter_axis keys """ if not isinstance(name, str): raise TypeError('name for the DataIn class should be a string') self['name'] = name if not isinstance(source, str): raise TypeError('source for the DataIn class should be a string') elif not ('simulated' in source or 'experimental' in source): raise ValueError('Invalid "source" for the DataIn class') self['source'] = source self['trace_in'] = trace_in self['pulse_in'] = pulse_in for k in kwargs: self[k] = kwargs[k] def pulse_from_spectrum(wavelength, spectrum, pulse=None): """ Generates a pulse instance from a measured spectrum. """ # scale to intensity over frequency, convert to amplitude and normalize spectrum = spectrum * wavelength * wavelength spectrum[spectrum < 0.0] = 0.0 spectrum = np.sqrt(spectrum + 0.0j) spectrum /= spectrum.max() # calculate angular frequencies w = convert(wavelength, "wl", "om") if pulse is None: # create pulse parameters from the measured spectrum # choose center wavelength as the mean of the intensity w0 = lib.mean(w, lib.abs2(spectrum)) # choose simulation grid that encompasses the measured spectrum dw = abs(np.mean(np.diff(w))) N = 4 * next_fast_len(int(abs(w[-1] - w[0]) / dw)) ft = FourierTransform(N, dw=dw) pulse = Pulse(ft, w0, unit="om") # interpolate pulse.spectrum = scipy.interpolate.interp1d(w - pulse.w0, spectrum, bounds_error=False, fill_value=0.0)(pulse.w) return pulse def preprocess(trace, signal_range=None, dark_signal_range=None): if dark_signal_range is not None: dark_signal = trace.copy() dark_signal.limit(dark_signal_range, axes=1) dark_signal = np.median(dark_signal.data, axis=1) if signal_range is not None: trace.limit(*signal_range) if dark_signal_range is not None: # subtract dark counts for every spectrum separately trace.data -= dark_signal[:, None] # normalize trace.normalize() return trace # interpolate the measurement def preprocess2(trace, pnps): if trace.units[1] == "m": # scaled in wavelength -> has to be corrected wavelength = trace.axes[1] frequency = convert(wavelength, "wl", "om") trace.scale(wavelength * wavelength) trace.normalize() trace.axes[1] = frequency trace.units[1] = "Hz" trace.interpolate(axis2=pnps.process_w) def substract_linear_phase(pulse): phase = np.unwrap(np.angle(pulse.spectrum)) intensity = np.abs(pulse.spectrum) z = np.polyfit(pulse.w, phase, 1) pulse.spectrum *= np.exp(- 1j * np.poly1d(z)(pulse.w)) return pulse def fit_pulse_phase(pulse, phase_blanking_threshold, order): phase = np.unwrap(np.angle(pulse.spectrum)) amp = np.abs(pulse.spectrum) # delta = 100e-9 x, phase = lib.mask_phase(pulse.w, amp, phase, phase_blanking_threshold) # fitarea = (pulse.wl > pulse.wl0-delta/2)&(pulse.wl < pulse.wl0+delta/2) # z = np.polyfit(pulse.w[fitarea], phase[fitarea], order) z = np.polyfit(x.compressed(),phase.compressed(),order) return z def mask(x, y, where, **kwargs): y = scipy.interpolate.interp1d(x[~where], y[~where], **kwargs)(x) return y params_simul = Simulator.params params_algo = utils.find_dict_in_list_from_key_val(params_simul, 'name', 'algo') def truncate(number, digits) -> float: stepper = 10.0 ** digits return math.trunc(stepper * number) / stepper #method of pypret.Retriever which overwrites the _error_vector method for a modified one which uses # an energy dependent weighting to account for unknown spectral response def nonuniform_error_vector(self, Tmn, store=True): " Modified to allow for energy dependent weights" # rename rs = self._retrieval_state Tmn_meas = self.Tmn_meas # scaling factor w2 = self._weights * self._weights #mu is vector if spectral response is unknown mean_mu = np.sum(Tmn_meas * Tmn * w2) / np.sum(Tmn * Tmn * w2) mu = np.full(self.N, mean_mu) mask = (w2.sum(axis=0) > 0.0) & (# weights equal to zero Tmn_meas.sum(axis=0) > 0.0) # measurement is zero mu[mask] = ( np.sum(Tmn_meas * Tmn * w2, axis=0)[mask] / np.sum(Tmn * Tmn * w2, axis=0)[mask] ) # extend the edges of the response function idx1 = lib.find(mask, lambda x: x) mu[:idx1] = mu[idx1] idx2 = lib.find(mask, lambda x: x, n=-1) mu[idx2:] = mu[idx2] # store intermediate results in current retrieval state if store: rs.mu = mu rs.Tmn = Tmn rs.Smk = self.pnps.Smk return np.ravel((Tmn_meas - mu * Tmn) * self._weights) def popup_message(title,text): msg = QtWidgets.QMessageBox() msg.setWindowTitle(title) msg.setText(text) msg.setIcon(QtWidgets.QMessageBox.Warning) msg.exec_() class Retriever(QObject): """ Main class initializing a DAQ_Scan module with its dashboard and scanning control panel """ status_signal = pyqtSignal(str) retriever_signal = pyqtSignal(str) params_in = [params_algo, {'title': 'Data Info', 'name': 'data_in_info', 'type': 'group', 'children': [ {'title': 'Loaded file:', 'name': 'loaded_file', 'type': 'text', 'value': "", 'readonly': True, 'tip': 'Loaded trace file'}, {'title': 'Loaded node:', 'name': 'loaded_node', 'type': 'str', 'value': "", 'readonly': True, 'tip': 'Loaded node within trace file'}, {'title': 'Trace Info', 'name': 'trace_in_info', 'type': 'group', 'children': [ {'title': 'Wl0 (nm)', 'name': 'wl0', 'type': 'float', 'value': 0, 'readonly': True, 'tip': 'Central spectrum wavelength in nanometers'}, {'title': 'FWHM (nm)', 'name': 'wl_fwhm', 'type': 'float', 'value': 0, 'readonly': True, 'tip': 'FWHM of the spectrum in nanometers'}, {'title': 'Param Size', 'name': 'trace_param_size', 'type': 'int', 'value': 0, 'readonly': True}, {'title': 'Wavelentgh Size', 'name': 'trace_wl_size', 'type': 'int', 'value': 0, 'readonly': True}, {'title': 'Scaling (m)', 'name': 'wl_scaling', 'type': 'float', 'value': 1, 'readonly': False, 'tip': 'Scaling to go from the Trace wavelength values to wavelength in meters'}, {'title': 'Scaling Parameter', 'name': 'param_scaling', 'type': 'float', 'value': 1, 'readonly': False, 'tip': 'Scaling to go from the trace parameter values to delay in seconds, insertion in m (dscan) ' 'or phase in rad (miips)'}, ]}, {'title': 'Spectrum Info', 'name': 'spectrum_in_info', 'type': 'group', 'children': [ {'title': 'Wl0 (nm)', 'name': 'wl0', 'type': 'float', 'value': 0, 'readonly': True, 'tip': 'Central spectrum wavelength in nanometers'}, {'title': 'FWHM (nm)', 'name': 'wl_fwhm', 'type': 'float', 'value': 0, 'readonly': True, 'tip': 'FWHM of the spectrum in nanometers'}, {'title': 'Wavelength Size', 'name': 'spectrum_size', 'type': 'int', 'value': 0, 'readonly': True}, {'title': 'Scaling (m)', 'name': 'wl_scaling', 'type': 'float', 'value': 1e-9, 'readonly': False, 'tip': 'Scaling to go from the spectrum wavelength values to wavelength in meters'}, ]}, ]}, {'title': 'Processing', 'name': 'processing', 'type': 'group', 'children': [ {'title': 'Grid settings:', 'name': 'grid_settings', 'type': 'group', 'children': [ {'title': 'lambda0 (nm):', 'name': 'wl0', 'type': 'float', 'value': 750, 'tip': 'Central Wavelength of the Pulse spectrum and frequency grid'}, {'title': 'Npoints:', 'name': 'npoints', 'type': 'list', 'values': [2 ** n for n in range(8, 16)], 'value': 1024, 'tip': 'Number of points for the temporal and Fourier Transform Grid'}, {'title': 'Time resolution (fs):', 'name': 'time_resolution', 'type': 'float', 'value': 1.0, 'tip': 'Time spacing between 2 points in the time grid'}, ]}, {'title': 'Trace limits:', 'name': 'ROIselect', 'type': 'group', 'visible': True, 'children': [ {'title': 'Crop Trace?:', 'name': 'crop_trace', 'type': 'bool', 'value': False}, {'title': 'x0:', 'name': 'x0', 'type': 'int', 'value': 0, 'min': 0}, {'title': 'y0:', 'name': 'y0', 'type': 'int', 'value': 0, 'min': 0}, {'title': 'width:', 'name': 'width', 'type': 'int', 'value': 10, 'min': 1}, {'title': 'height:', 'name': 'height', 'type': 'int', 'value': 10, 'min': 1}, ]}, {'title': 'Substract background:', 'name': 'linearselect', 'type': 'group', 'visible': True, 'children': [ {'title': 'Substract?:', 'name': 'dosubstract', 'type': 'bool', 'value': False}, {'title': 'wl0:', 'name': 'wl0', 'type': 'float', 'value': 0.}, {'title': 'wl1:', 'name': 'wl1', 'type': 'float', 'value': 10.}, ]}, {'title': 'Process Spectrum', 'name': 'process_spectrum', 'type': 'action', 'tip': 'Use ROIs to select frequency areas from the spectrum that should be removed'}, {'title': 'Process trace', 'name': 'process_trace', 'type': 'action', 'tip': 'Use one ROI to select a frequency area from the trace in order to remove the background' ' and use ROISelect to reduce the area around the trace'}, {'title': 'Process Both', 'name': 'process_both', 'type': 'action', 'tip': 'Process both the trace and the spectrum'}, ]}, {'title': 'Retrieving', 'name': 'retrieving', 'type': 'group', 'children': [ {'title': 'Algo type:', 'name': 'algo_type', 'type': 'list', 'values': retriever_algos, 'tip': 'Retriever Algorithm'}, {'title': 'Initial guess:', 'name': 'guess_type', 'type': 'list', 'values': ['Random gaussian', 'Fundamental spectrum'], 'tip': 'Retriever Algorithm'}, {'title': 'Verbose Info:', 'name': 'verbose', 'type': 'bool', 'value': True, 'tip': 'Display infos during retrieval'}, {'title': 'Uniform spectral response:', 'name': 'uniform_response', 'type': 'bool', 'value': True, 'tip': 'Assume uniform response of non-linear process. Turn off for real data.'}, {'title': 'Max iteration:', 'name': 'max_iter', 'type': 'int', 'value': 30, 'tip': 'Max iteration for the algorithm'}, {'title': 'Initial Pulse Guess', 'name': 'pulse_guess', 'type': 'group', 'visible':True , 'children': [ {'title': 'FWHM (fs):', 'name': 'fwhm', 'type': 'float', 'value': 5.0, 'tip': 'Guess of the pulse duration (used as a starting point)'}, {'title': 'Phase amp. (rad):', 'name': 'phase_amp', 'type': 'float', 'value': 0.1, 'tip': 'Amplitude of the random phase applied to the initial guess'}, ]}, {'title': 'Start Retrieval', 'name': 'start', 'type': 'action', 'tip': 'Start the retrieval process'}, {'title': 'Stop Retrieval', 'name': 'stop', 'type': 'action', 'tip': 'Stop the retrieval process'}, {'title': 'Propagate result', 'name': 'propagate', 'type': 'action', 'tip': 'Propagate the retrieved pulse'} ]}, ] material_names = [material.name for material in materials_propagation] index = material_names.index("Air") material_names.insert(0, material_names.pop(index)) air_first_material_names = material_names.copy() index = material_names.index("FS") material_names.insert(0, material_names.pop(index)) prop_param = [ {'title': 'Materials', 'name': 'materials', 'type': 'group', 'children': [ {'title': 'Material 1:', 'name': 'material1', 'type': 'list', 'values': air_first_material_names, 'readonly': False, 'tip': 'First material'}, {'title': 'Thickness (mm)', 'name': 'thickness1', 'type': 'float', 'value': 0, 'readonly': False, }, {'title': 'Material 2:', 'name': 'material2', 'type': 'list', 'values': material_names, 'readonly': False, 'tip': 'Second material'}, {'title': 'Thickness (mm)', 'name': 'thickness2', 'type': 'float', 'value': 0, 'readonly': False, }, {'title': 'Plot oversampling', 'name': 'prop_oversampling', 'type': 'int', 'value': 4, 'readonly': False, }, {'title': 'Resolution for FWHM calc (fs)', 'name': 'dt_fwhm', 'type': 'float', 'value': 0.5, 'readonly': False, }, {'title': 'Phase masking threshold', 'name': 'fit_threshold', 'type': 'float', 'value': 0.1, 'readonly': False, } ] }] pulse_prop = [ {'title': 'Pulse properties', 'name': 'pulse_prop', 'type': 'group', 'children': [ {'title': 'FWHM (fs)', 'name': 'fwhm_meas', 'type': 'float', 'values': 0, 'readonly': True, 'tip': 'Full width at half maximum of propagated pulse'}, #{'title': 'Fourier Limit (fs)', 'name': 'fwhm_ftl', 'type': 'float', 'values': 0, #'readonly': True, #'tip': 'Full width at half maximum of fourier transformed pulse'}, #{'title': 'Peak intensity compared to FTL (%)', 'name': 'ratio_main_pulse', 'type': 'float', 'values': 0.0, #'readonly': True, #'tip': 'Peak intensity compared to the Fourier transform limited pulse'}, {'title': 'GDD (fs^2)', 'name': 'gdd', 'type': 'float', 'values': 0, 'readonly': True, 'tip': 'GDD'}, {'title': 'TOD (fs3)', 'name': 'tod', 'type': 'float', 'values': 0, 'readonly': True, 'tip': 'TOD'}, {'title': 'FOD (fs4)', 'name': 'fod', 'type': 'float', 'values': 0, 'readonly': True, 'tip': 'FOD'}, ]}] def __init__(self, dockarea=None, dashboard=None): """ Parameters ---------- dockarea: (dockarea) instance of the modified pyqtgraph Dockarea (see daq_utils) dashboard: (DashBoard) instance of the pymodaq dashboard """ QLocale.setDefault(QLocale(QLocale.English, QLocale.UnitedStates)) logger.info('Initializing Retriever Extension') super().__init__() self.h5browse = H5BrowserUtil() self.dockarea = dockarea self.dashboard = dashboard self.mainwindow = self.dockarea.parent() self.settings = Parameter.create(name='dataIN_settings', type='group', children=self.params_in) self.settings.sigTreeStateChanged.connect(self.settings_changed) self.prop_settings = Parameter.create(name='propagation_settings', type='group', children=self.prop_param) self.pulse_settings = Parameter.create(name='pulse_settings', type='group', children=self.pulse_prop) self.prop_settings.sigTreeStateChanged.connect(self.prop_settings_changed) self.setupUI() self.create_menu(self.mainwindow.menuBar()) self.simulator = None self.data_in = None self.ft = None self.retriever = None self.pnps = None self.retriever_thread = None self.save_file_pathname = None self.settings.child('processing', 'process_trace').sigActivated.connect(self.process_trace) self.settings.child('processing', 'process_spectrum').sigActivated.connect(self.process_spectrum) self.settings.child('processing', 'process_both').sigActivated.connect(self.process_both) self.settings.child('retrieving', 'start').sigActivated.connect(self.start_retriever) self.settings.child('retrieving', 'stop').sigActivated.connect(self.stop_retriever) self.settings.child('retrieving', 'propagate').sigActivated.connect(self.propagate) self.viewer_trace_in.ROI_select_signal.connect(self.update_ROI) self.viewer_trace_in.ROIselect_action.triggered.connect(self.show_ROI) self.settings.child('algo', 'miips_parameter').hide() self.settings.child('algo', 'dscan_parameter').hide() self.settings.child('algo', 'alpha').hide() self.settings.child('algo', 'gamma').hide() self.state = [] def save_data(self, save_file_pathname=None): try: if save_file_pathname is None: save_file_pathname = gutils.select_file(start_path=self.save_file_pathname, save=True, ext='h5') # see daq_utils h5saver = H5Saver(save_type='custom') h5saver.init_file(update_h5=True, custom_naming=False, addhoc_file_path=save_file_pathname, raw_group_name='PyMoDAQFemtoAnalysis') settings_str = b'<All_settings>' + ioxml.parameter_to_xml_string(self.settings) settings_str += b'</All_settings>' # TODO h5saver.set_attr(h5saver.raw_group, 'settings', settings_str) data_in_group = h5saver.get_set_group(h5saver.raw_group, "DataIn") trace_group = h5saver.get_set_group(data_in_group, 'NLTrace') spectrum_group = h5saver.get_set_group(data_in_group, 'FunSpectrum') h5saver.add_data(trace_group, self.data_in['raw_trace'], scan_type='') h5saver.add_data(spectrum_group, self.data_in['raw_spectrum'], scan_type='') except Exception as e: pass h5saver.close_file() def create_menu(self, menubar): """ Create the menubar object looking like : """ menubar.clear() # %% create Settings menu self.main_menu = menubar.addMenu('Main') self.quit_action = self.main_menu.addAction('Quit') self.restart_action = self.main_menu.addAction('Restart') self.quit_action.triggered.connect(self.quit_fun) self.restart_action.triggered.connect(self.restart_fun) self.data_in_menu = menubar.addMenu('Data In') self.data_in_menu.addAction(self.load_trace_in_action) self.data_in_menu.addAction(self.load_spectrum_in_action) self.data_in_menu.addSeparator() self.data_in_menu.addAction(self.gen_trace_in_action) self.data_in_menu.addAction(self.load_from_simulation_action) def settings_changed(self, param, changes): for param, change, data in changes: path = self.settings.childPath(param) if change == 'childAdded': pass elif change == 'parent': pass elif change == 'value': if param.name() == 'method': self.settings.child('algo', 'nlprocess').setLimits(list(_PNPS_CLASSES[param.value()].keys())) if param.value() == 'miips': self.settings.child('algo', 'alpha').show() self.settings.child('algo', 'gamma').show() else: self.settings.child('algo', 'alpha').hide() self.settings.child('algo', 'gamma').hide() if param.value() == 'dscan': self.settings.child('algo', 'material').show() else: self.settings.child('algo', 'material').hide() elif param.name() in putils.iter_children(self.settings.child('processing', 'ROIselect'), []) and 'ROIselect' in param.parent().name(): # to be sure # a param named 'y0' for instance will not collide with the y0 from the ROI try: self.viewer_trace_in.ROI_select_signal.disconnect(self.update_ROI) except Exception as e: pass if self.settings.child('processing', 'ROIselect', 'crop_trace').value(): if not self.viewer_trace_in.ROIselect_action.isChecked(): self.viewer_trace_in.ROIselect_action.trigger() QtWidgets.QApplication.processEvents() self.viewer_trace_in.ui.ROIselect.setPos( self.settings.child('processing', 'ROIselect', 'x0').value(), self.settings.child('processing', 'ROIselect', 'y0').value()) self.viewer_trace_in.ui.ROIselect.setSize( [self.settings.child('processing', 'ROIselect', 'width').value(), self.settings.child('processing', 'ROIselect', 'height').value()]) self.viewer_trace_in.ROI_select_signal.connect(self.update_ROI) else: if self.viewer_trace_in.ROIselect_action.isChecked(): self.viewer_trace_in.ROIselect_action.trigger() elif param.name() in putils.iter_children(self.settings.child('processing', 'linearselect'), []) and 'linearselect' in param.parent().name(): # to be sure # a param named 'y0' for instance will not collide with the y0 from the ROI try: self.linear_region.sigRegionChangeFinished.disconnect(self.update_linear) except Exception as e: pass self.linear_region.setVisible(self.settings.child('processing', 'linearselect', 'dosubstract').value()) pos_real = np.array([self.settings.child('processing', 'linearselect', 'wl0').value(), self.settings.child('processing', 'linearselect', 'wl1').value()]) * 1e-9 pos_pxl, y = self.viewer_trace_in.unscale_axis(np.array(pos_real), np.array([0, 1])) self.linear_region.setPos(pos_pxl) self.linear_region.sigRegionChangeFinished.connect(self.update_linear) elif param.name() == 'method': self.settings.child('algo', 'nlprocess').setLimits(list(_PNPS_CLASSES[param.value()].keys())) if param.value() == 'miips': self.settings.child('algo', 'alpha').show() self.settings.child('algo', 'gamma').show() self.settings.child('algo', 'miips_parameter').show() else: self.settings.child('algo', 'alpha').hide() self.settings.child('algo', 'gamma').hide() self.settings.child('algo', 'miips_parameter').hide() if param.value() == 'dscan': self.settings.child('algo', 'material').show() self.settings.child('algo', 'dscan_parameter').show() else: self.settings.child('algo', 'material').hide() self.settings.child('algo', 'dscan_parameter').hide() elif param.name() == 'guess_type': if param.value() == 'Fundamental spectrum': self.settings.child('retrieving', 'pulse_guess').hide() elif param.value() == 'Random gaussian': self.settings.child('retrieving', 'pulse_guess').show() def prop_settings_changed(self, param, changes): for param, change, data in changes: path = self.settings.childPath(param) if change == 'childAdded': pass elif change == 'parent': pass elif change == 'value': if param.name() in ['material1', 'material2', 'thickness1', 'thickness2', 'prop_oversampling','fit_threshold']: self.propagate() elif param.name() == 'dt_fwhm': self.update_fwhm() def quit_fun(self): """ """ try: if hasattr(self, 'mainwindow'): self.mainwindow.close() except Exception as e: logger.exception(str(e)) def restart_fun(self, ask=False): ret = False mssg = QtWidgets.QMessageBox() if ask: mssg.setText('You have to restart the application to take the modifications into account!') mssg.setInformativeText("Do you want to restart?") mssg.setStandardButtons(mssg.Ok | mssg.Cancel) ret = mssg.exec() if ret == mssg.Ok or not ask: self.quit_fun() subprocess.call([sys.executable, __file__]) def setupUI(self): self.ui = QObject() # create main docks self.ui.dock_settings = Dock('Settings') self.dockarea.addDock(self.ui.dock_settings, 'top') self.ui.dock_data_in = Dock('Data In') self.dockarea.addDock(self.ui.dock_data_in, 'left', self.ui.dock_settings) self.ui.dock_processed = Dock('Processed Data') self.dockarea.addDock(self.ui.dock_processed, 'below', self.ui.dock_data_in) self.ui.dock_retriever = Dock('Retriever') self.dockarea.addDock(self.ui.dock_retriever, 'below', self.ui.dock_processed) self.ui.dock_retrieved_data = Dock('Retrieved Data') self.dockarea.addDock(self.ui.dock_retrieved_data, 'below', self.ui.dock_retriever) self.ui.dock_propagation = Dock('Propagation') self.dockarea.addDock(self.ui.dock_propagation, 'below', self.ui.dock_retriever) self.ui.dock_processed.raiseDock() # ###################################################### # setup settings in dock self.settings_tree = ParameterTree() self.settings_tree.setMinimumWidth(300) self.ui.dock_settings.addWidget(self.settings_tree) self.ui.dock_settings.setStretch(0.5) # setup toolbar self.toolbar = QtWidgets.QToolBar() self.mainwindow.addToolBar(self.toolbar) if self.dashboard is not None: if self.dashboard.scan_module is not None: self.load_last_scan_action = gutils.QAction(QIcon(QPixmap(":/icons/Icon_Library/Open_2D.png")), 'Load last 2D scan') self.toolbar.addAction(self.load_last_scan_action) self.toolbar.addSeparator() self.load_last_scan_action.triggered.connect(self.load_last_scan) self.load_trace_in_action = gutils.QAction(QIcon(QPixmap(":/icons/Icon_Library/Open_2D.png")), 'Load Experimental Trace') self.load_spectrum_in_action = gutils.QAction(QIcon(QPixmap(":/icons/Icon_Library/Open_1D.png")), 'Load Experimental Spectrum') self.gen_trace_in_action = gutils.QAction(QIcon(QPixmap(":/icons/Icon_Library/ini.png")), 'Simulate Experimental Trace') self.load_from_simulation_action = gutils.QAction(QIcon(QPixmap(":/icons/Icon_Library/Open_sim.png")), 'Load Data from Simulation') self.save_data_action = gutils.QAction(QIcon(QPixmap(":/icons/Icon_Library/Save.png")), 'Save Data') self.load_trace_in_action.triggered.connect(self.load_trace_in) self.load_spectrum_in_action.triggered.connect(self.load_spectrum_in) self.gen_trace_in_action.triggered.connect(self.open_simulator) self.load_from_simulation_action.triggered.connect(self.load_from_simulator) self.save_data_action.triggered.connect(self.save_data) self.toolbar.addAction(self.load_trace_in_action) self.toolbar.addAction(self.load_spectrum_in_action) self.toolbar.addSeparator() self.toolbar.addAction(self.gen_trace_in_action) self.toolbar.addAction(self.load_from_simulation_action) self.toolbar.addSeparator() self.toolbar.addAction(self.save_data_action) # ###################################################### # setup data in dock data_in_splitter = QtWidgets.QSplitter() self.viewer_trace_in = Viewer2D() self.viewer_trace_in.ui.histogram_red.gradient.restoreState(Gradients['femto']) self.viewer_trace_in.aspect_ratio_action.click() pos = self.viewer_trace_in.roi_manager.viewer_widget.plotItem.vb.viewRange()[0] self.linear_region = LinearROI(index=0, pos=pos) self.linear_region.setZValue(-10) self.linear_region.setOpacity(0.5) self.linear_region.setBrush([255, 0, 0, 0]) self.viewer_trace_in.roi_manager.viewer_widget.plotItem.addItem(self.linear_region) self.linear_region.sigRegionChangeFinished.connect(self.update_linear) self.linear_region.setVisible(False) self.viewer_spectrum_in = Viewer1D() data_in_splitter.addWidget(self.viewer_trace_in.parent) data_in_splitter.addWidget(self.viewer_spectrum_in.parent) self.ui.dock_data_in.addWidget(data_in_splitter) self.settings_tree.setParameters(self.settings, showTop=False) # ################################################# # setup retriever dock retriever_widget = QtWidgets.QSplitter() self.viewer_live_trace = Viewer2D() self.viewer_live_trace.ui.histogram_red.gradient.restoreState(Gradients['femto_error']) self.viewer_live_trace.aspect_ratio_action.trigger() #self.viewer_live_trace.auto_levels_action.trigger() self.viewer_live_time = Viewer1D() self.viewer_live_lambda = Viewer1D() self.info_widget = QtWidgets.QTextEdit() self.info_widget.setReadOnly(True) vsplitter = QtWidgets.QSplitter(QtCore.Qt.Vertical) self.ui.dock_retriever.addWidget(retriever_widget) retriever_widget.addWidget(self.viewer_live_trace.parent) vsplitter.addWidget(self.viewer_live_time.parent) vsplitter.addWidget(self.viewer_live_lambda.parent) retriever_widget.addWidget(vsplitter) retriever_widget.addWidget(self.info_widget) ##################################### # setup processed dock main_widget = QtWidgets.QWidget() main_widget.setLayout(QtWidgets.QHBoxLayout()) trace_widget = QtWidgets.QWidget() pulse_widget = QtWidgets.QWidget() main_widget.layout().addWidget(trace_widget) main_widget.layout().addWidget(pulse_widget) self.ui.dock_processed.addWidget(main_widget) self.pulse_canvas = MplCanvas(pulse_widget, width=5, height=4, dpi=100) # Create toolbar, passing canvas as first parament, parent (self, the MainWindow) as second. toolbar_pulse = NavigationToolbar(self.pulse_canvas, trace_widget) self.trace_canvas = MplCanvas(trace_widget, width=5, height=4, dpi=100) # Create toolbar, passing canvas as first parament, parent (self, the MainWindow) as second. toolbar_trace = NavigationToolbar(self.trace_canvas, trace_widget) pulse_widget.setLayout(QtWidgets.QVBoxLayout()) pulse_widget.layout().addWidget(toolbar_pulse) pulse_widget.layout().addWidget(self.pulse_canvas) trace_widget.setLayout(QtWidgets.QVBoxLayout()) trace_widget.layout().addWidget(toolbar_trace) trace_widget.layout().addWidget(self.trace_canvas) ################################################## # setup retrievd data dock data_widget = QtWidgets.QWidget() data_widget.setLayout(QtWidgets.QVBoxLayout()) self.data_canvas = MplCanvas(data_widget, width=5, height=4, dpi=100) # Create toolbar, passing canvas as first parament, parent (self, the MainWindow) as second. toolbar_data = NavigationToolbar(self.data_canvas, data_widget) data_widget.layout().addWidget(toolbar_data) data_widget.layout().addWidget(self.data_canvas) self.ui.dock_retrieved_data.addWidget(data_widget) ################################################## # setup propagation dock prop_widget = QtWidgets.QWidget() prop_widget.setLayout(QtWidgets.QVBoxLayout()) param_widget = QtWidgets.QWidget() param_widget.setLayout(QtWidgets.QHBoxLayout()) param_widget.setMinimumHeight(300) self.prop_tree = ParameterTree() self.pulse_tree = ParameterTree() param_widget.layout().addWidget(self.prop_tree,1) param_widget.layout().addWidget(self.pulse_tree, 1) prop_widget.layout().addWidget(param_widget,1) propagated_widget = QtWidgets.QWidget() prop_widget.layout().addWidget(propagated_widget,5) self.ui.dock_propagation.addWidget(prop_widget) self.prop_canvas = MplCanvas(propagated_widget, width=5, height=4, dpi=100) # Create toolbar, passing canvas as first parament, parent (self, the MainWindow) as second. toolbar_prop = NavigationToolbar(self.prop_canvas, propagated_widget) propagated_widget.setLayout(QtWidgets.QVBoxLayout()) propagated_widget.layout().addWidget(toolbar_prop) propagated_widget.layout().addWidget(self.prop_canvas) self.prop_tree.setParameters(self.prop_settings, showTop=False) self.pulse_tree.setParameters(self.pulse_settings, showTop=False) self.ui.dock_data_in.raiseDock() def open_simulator(self): simulator_widget = QtWidgets.QWidget() self.simulator = Simulator(simulator_widget) simulator_widget.setWindowTitle('PyMoDAQ Femto Simulator') simulator_widget.show() def load_from_simulator(self): if self.simulator is not None: data, axis, parameter_axis = self.simulator.trace_exp(Npts=512) spectrum_axis, spectrum = self.simulator.spectrum_exp(Npts=512) if self.data_in is None: self.data_in = DataIn(source='simulated') self.data_in.update(dict(source='simulated', raw_spectrum=dict(data=spectrum, x_axis=spectrum_axis), raw_trace=dict(data=data, x_axis=axis, y_axis=parameter_axis))) self.display_data_in() self.update_spectrum_info(self.data_in['raw_spectrum']) self.update_trace_info(self.data_in['raw_trace']) for child in putils.iter_children_params(self.settings.child('algo'), childlist=[]): path = ['algo'] path.extend(self.settings.child('algo').childPath(child)) self.settings.child(*path).setValue(self.simulator.settings.child(*path).value()) self.settings.child('data_in_info', 'loaded_file').setValue('Simulation') def update_spectrum_info(self, raw_spectrum): wl0, fwhm = utils.my_moment(raw_spectrum['x_axis']['data'], raw_spectrum['data']) self.settings.child('data_in_info', 'spectrum_in_info', 'wl0').setValue(wl0 * 1e9) self.settings.child('data_in_info', 'spectrum_in_info', 'wl_fwhm').setValue(fwhm * 1e9) self.settings.child('data_in_info', 'spectrum_in_info', 'spectrum_size').setValue(len(raw_spectrum['data'])) self.settings.child('processing', 'grid_settings', 'wl0').setValue(wl0 * 1e9) self.state.append("spectrum_loaded") def update_trace_info(self, raw_trace): wl0, fwhm = utils.my_moment(raw_trace['x_axis']['data'], np.sum(raw_trace['data'], 0)) self.settings.child('data_in_info', 'trace_in_info', 'wl0').setValue(wl0 * 1e9) self.settings.child('data_in_info', 'trace_in_info', 'wl_fwhm').setValue(fwhm * 1e9) self.settings.child('data_in_info', 'trace_in_info', 'trace_param_size').setValue( len(raw_trace['y_axis']['data'])) self.settings.child('data_in_info', 'trace_in_info', 'trace_wl_size').setValue(len(raw_trace['x_axis']['data'])) self.settings.child('processing', 'grid_settings', 'npoints').setValue(next_fast_len(len(raw_trace['x_axis']['data']))) method = self.settings.child('algo', 'method').value() if not (method == 'dscan' or method == 'miips'): self.settings.child('processing', 'grid_settings', 'time_resolution').setValue(np.mean( np.diff(raw_trace['y_axis']['data'])) * 1e15) self.state.append("trace_loaded") def generate_ft_grid(self): wl0 = self.settings.child('processing', 'grid_settings', 'wl0').value() * 1e-9 Npts = self.settings.child('processing', 'grid_settings', 'npoints').value() dt = self.settings.child('processing', 'grid_settings', 'time_resolution').value() * 1e-15 self.ft = FourierTransform(Npts, dt, w0=wl2om(-wl0 - 300e-9)) def process_trace(self): if "trace_loaded" not in self.state: popup_message("Error", "Please load a trace first!") return if "spectrum_processed" not in self.state: popup_message("Error", "Please process the spectrum first") return self.ui.dock_processed.raiseDock() if self.pnps is None: logger.info('PNPS is not yet defined, process the spectrum first') return trace_in = self.get_trace_in() # TODO # ## substract bright spots range (if any) # if len(self.viewer_trace_in.roi_manager.ROIs) > 0: # roi = [self.viewer_trace_in.roi_manager.ROIs.keys()][0] # pos = self.viewer_trace_in.roi_manager.ROIs[roi].pos() # width, height = self.viewer_trace_in.roi_manager.ROIs[roi].size() # xlim_pxls = np.array([pos.x(), pos.y()+width]) # ylim_pxls = np.array([pos.x(), pos.y() + height]) # xlim, ylim = self.viewer_trace_in.scale_axis(xlim_pxls, ylim_pxls) # trace_in = preprocess(trace_in, signal_range=None, bright_signal_range=tuple(xlim)) # bright_signal_range doesn't exists yet' if self.settings.child('processing', 'linearselect', 'dosubstract').value(): xlim = np.array((self.settings.child('processing', 'linearselect', 'wl0').value(), self.settings.child('processing', 'linearselect', 'wl1').value())) * 1e-9 trace_in = preprocess(trace_in, signal_range=None, dark_signal_range=tuple(xlim)) if self.settings.child('processing', 'ROIselect', 'crop_trace').value(): x0 = self.settings.child('processing', 'ROIselect', 'x0').value() y0 = self.settings.child('processing', 'ROIselect', 'y0').value() width = self.settings.child('processing', 'ROIselect', 'width').value() height = self.settings.child('processing', 'ROIselect', 'height').value() xlim_pxls = np.array([x0, x0+width]) ylim_pxls = np.array([y0, y0+height]) xlim, ylim = self.viewer_trace_in.scale_axis(xlim_pxls, ylim_pxls) trace_in = preprocess(trace_in, signal_range=(tuple(ylim), tuple(xlim))) self.data_in['trace_in'] = trace_in preprocess2(self.data_in['trace_in'], self.pnps) self.state.append("trace_processed") self.trace_canvas.figure.clf() MeshDataPlot(trace_in, self.trace_canvas.figure, limit=True) self.trace_canvas.draw() def process_both(self): self.process_spectrum() self.process_trace() def propagate(self): if "result_ok" not in self.state: popup_message("Error", "Complete the retrieval first") return self.ui.dock_propagation.raiseDock() self.propagated_pulse = Pulse(self.result.pnps.ft, self.result.pnps.w0, unit="om") self.propagated_pulse.spectrum = self.result.pulse_retrieved material_list = [] material_list.append(self.prop_settings.child('materials', 'material1').value()) material_list.append(self.prop_settings.child('materials', 'material2').value()) thickness_list = [] thickness_list.append(self.prop_settings.child('materials', 'thickness1').value()) thickness_list.append(self.prop_settings.child('materials', 'thickness2').value()) for material, length in zip(material_list, thickness_list): item = getattr(pymodaq_femto.materials, material) w1, w2 = sorted(wl2om(np.array(item._range))) w = self.propagated_pulse.w+ self.propagated_pulse.w0 valid = (w >= w1) & (w <= w2) w = w[valid] k = item.k(w, unit='om') k0 = item.k(self.propagated_pulse.w0, unit='om') k1 = item.k(self.propagated_pulse.w0 + self.propagated_pulse.ft.dw, unit="om") dk = (k1 - k0) / self.propagated_pulse.ft.dw #Add material dispersion without 0th and 1st Taylor orders (they don't change the pulse) kfull = np.zeros_like(self.propagated_pulse.w) kfull[valid] = (k - k0 - dk * self.propagated_pulse.w[valid]) self.propagated_pulse.spectrum *= np.exp(1j * kfull * 1e-3 * length) phasepoly = fit_pulse_phase(self.propagated_pulse, self.prop_settings.child('materials', 'fit_threshold').value(), 4) self.propagated_pulse.spectrum *= np.exp(- 1j * np.poly1d(phasepoly[-1])(self.propagated_pulse.w)) self.propagated_pulse.spectrum *= np.exp(- 1j * np.poly1d(phasepoly[-2])(self.propagated_pulse.w)) self.pulse_settings.child('pulse_prop', 'gdd').setValue(truncate(phasepoly[-3]*1e30*2,4)) self.pulse_settings.child('pulse_prop', 'tod').setValue(truncate(phasepoly[-4]*1e45*6,4)) self.pulse_settings.child('pulse_prop', 'fod').setValue(truncate(phasepoly[-5]*1e60*24,4)) self.update_fwhm() plot_oversampling = self.prop_settings.child('materials', 'prop_oversampling').value() self.prop_canvas.figure.clf() PulsePropagationPlot(self.propagated_pulse, phasepoly, fwhm = self.pulse_settings.child('pulse_prop', 'fwhm_meas').value(), fig=self.prop_canvas.figure, oversampling = plot_oversampling, phase_blanking=True, phase_blanking_threshold=self.prop_settings.child('materials', 'fit_threshold').value()) self.prop_canvas.draw() def update_fwhm(self): precision = 1e-15 * self.prop_settings.child('materials', 'dt_fwhm').value() try: fwhm = 1e15 * self.propagated_pulse.fwhm(precision) self.pulse_settings.child('pulse_prop', 'fwhm_meas').setValue(truncate(fwhm,4)) # self.pulse_settings.child('pulse_prop', 'fwhm_ftl').setValue(truncate(1e15 * self.data_in['pulse_in'].fwhm(precision),4)) # ratio_ideal = lib.abs2(self.propagated_pulse.field).max() / lib.abs2(ftl.field).max() # self.pulse_settings.child('pulse_prop', 'ratio_main_pulse').setValue(truncate(ratio_ideal*100,4)) except ValueError: warnings.warn("FWHM is undefined.") self.pulse_settings.child('pulse_prop', 'fwhm_meas').setValue(0) def process_spectrum(self): if "spectrum_loaded" not in self.state: popup_message("Error", "Please load a spectrum first!") return self.ui.dock_processed.raiseDock() self.generate_ft_grid() method = self.settings.child('algo', 'method').value() nlprocess = self.settings.child('algo', 'nlprocess').value() wl0 = self.settings.child('data_in_info', 'trace_in_info', 'wl0').value() * 1e-9 spectrum = self.data_in['raw_spectrum']['data'] wavelength = self.data_in['raw_spectrum']['x_axis']['data'] if 'shg' in nlprocess: wl0real = 2 * wl0 elif 'thg' in nlprocess: wl0real = 3 * wl0 else: wl0real = wl0 self.data_in['pulse_in'] = Pulse(self.ft, wl0real) for roi in self.viewer_spectrum_in.roi_manager.ROIs: range = self.viewer_spectrum_in.roi_manager.ROIs[roi].pos() spectrum = mask(wavelength, spectrum, (range[0] <= wavelength) & (wavelength <= range[1])) self.data_in['pulse_in'] = pulse_from_spectrum(wavelength, spectrum, pulse=self.data_in['pulse_in']) #self.pnps = PNPS(self.data_in['pulse_in'], method, nlprocess) if method == 'dscan': material = materials[self.settings.child('algo', 'material').value()] self.pnps = PNPS(self.data_in['pulse_in'], method, nlprocess, material=material) parameter = utils.linspace_step(self.settings.child('algo', 'dscan_parameter', 'min').value(), self.settings.child('algo', 'dscan_parameter', 'max').value(), self.settings.child('algo', 'dscan_parameter', 'step').value()) parameter *= 1e-3 elif method == 'miips': alpha = self.settings.child('algo', 'alpha').value() gamma = self.settings.child('algo', 'gamma').value() self.pnps = PNPS(self.data_in['pulse_in'], method, nlprocess, alpha=alpha, gamma=gamma) parameter = utils.linspace_step(self.settings.child('algo', 'miips_parameter', 'min').value(), self.settings.child('algo', 'miips_parameter', 'max').value(), self.settings.child('algo', 'miips_parameter', 'step').value()) else: self.pnps = PNPS(self.data_in['pulse_in'], method, nlprocess) self.state.append("spectrum_processed") self.pulse_canvas.figure.clf() PulsePlot(self.data_in['pulse_in'], self.pulse_canvas.figure) self.pulse_canvas.draw() def start_retriever(self): if "trace_processed" not in self.state: popup_message("Error", "Please process the trace first!") return self.ui.dock_retriever.raiseDock() self.info_widget.clear() # mandatory to deal with multithreads if self.retriever_thread is not None: if self.retriever_thread.isRunning(): self.retriever_thread.terminate() while not self.retriever_thread.isFinished(): QThread.msleep(100) self.retriever_thread = None self.retriever_thread = QThread() retriever = RetrieverWorker(self.data_in, self.pnps, self.settings) retriever.moveToThread(self.retriever_thread) retriever.status_sig[str].connect(self.update_retriever_info) retriever.result_signal[SimpleNamespace].connect(self.display_results) retriever.callback_sig[list].connect(self.update_retriever) self.retriever_signal[str].connect(retriever.command_retriever) self.retriever_thread.retriever = retriever self.retriever_thread.start() self.retriever_signal.emit('start') self.state.append("retrieving") def stop_retriever(self): if "retrieving" not in self.state: popup_message("Error", "No retrieval running") return self.retriever_signal.emit('stop') def update_retriever_info(self, info): self.info_widget.moveCursor(QTextCursor.End) self.info_widget.insertPlainText(info+'\n') self.info_widget.moveCursor(QTextCursor.End) @pyqtSlot(list) def update_retriever(self, args): max = 0.8*np.max([np.abs(np.max(args[0])), np.abs(np.min(args[0]))]) self.viewer_live_trace.ui.histogram_red.setHistogramRange(-max, max) self.viewer_live_trace.ui.histogram_red.setLevels(-max, max) self.viewer_live_trace.setImage(args[0]) self.viewer_live_trace.x_axis = utils.Axis(data=args[2], label='Time', units='s') self.viewer_live_trace.y_axis = utils.Axis(data=args[1], label='Frequency', units='m') self.data_in['pulse_in'].spectrum = args[3] #self.data_in['pulse_in'] = substract_linear_phase(self.data_in['pulse_in']) self.viewer_live_time.show_data([np.abs(self.data_in['pulse_in'].field)**2], x_axis=utils.Axis(data=self.data_in['pulse_in'].t, label='Time', units='s'), labels=['Temporal Intensity']) self.viewer_live_lambda.show_data([np.abs(self.data_in['pulse_in'].spectrum)**2], x_axis=utils.Axis(data=self.data_in['pulse_in'].wl, label='Wavelength', units='m'), labels=['Spectral Intensity']) @pyqtSlot(SimpleNamespace) def display_results(self, result): self.result = result self.state.append("result_ok") self.ui.dock_retrieved_data.raiseDock() self.data_in['pulse_in'].spectrum = result.pulse_retrieved fundamental = self.data_in['raw_spectrum']['data'] wavelength = self.data_in['raw_spectrum']['x_axis']['data'] #fundamental *= (wavelength * wavelength) spec = self.data_in['pulse_in'].spectral_intensity spec = scipy.interpolate.interp1d(self.data_in['pulse_in'].wl, spec, bounds_error=False, fill_value=0.0)(wavelength) fundamental *= lib.best_scale(fundamental, spec) print("spectrum error", "%e" % lib.nrms(fundamental, spec)) # do the retrieval plot self.data_canvas.figure.clf() RetrievalResultPlot(result, fig=self.data_canvas.figure, fundamental=fundamental, fundamental_wavelength=wavelength, oversampling=8, phase_blanking=True, phase_blanking_threshold=0.01, limit=True) self.data_canvas.draw() @pyqtSlot(QtCore.QRectF) def update_ROI(self, rect=QtCore.QRectF(0, 0, 1, 1)): self.settings.child('processing', 'ROIselect', 'x0').setValue(int(rect.x())) self.settings.child('processing', 'ROIselect', 'y0').setValue(int(rect.y())) self.settings.child('processing', 'ROIselect', 'width').setValue(max([1, int(rect.width())])) self.settings.child('processing', 'ROIselect', 'height').setValue(max([1, int(rect.height())])) def update_linear(self, linear_roi): pos = linear_roi.pos() pos_real, y = self.viewer_trace_in.scale_axis(np.array(pos), np.array([0, 1])) pos_real *= 1e9 self.settings.child('processing', 'linearselect', 'wl0').setValue(pos_real[0]) self.settings.child('processing', 'linearselect', 'wl1').setValue(pos_real[1]) def show_ROI(self): # self.settings.child('processing', 'ROIselect').setOpts( # visible=self.viewer_trace_in.ROIselect_action.isChecked()) data = self.data_in['raw_trace']['data'] axes = [np.arange(0, data.shape[0]), np.arange(0, data.shape[1])] axes_index = list(range(data.ndim)) marginals = lib.marginals(data) limits = [] for index in axes_index: limit = lib.limit(axes[index], marginals[index], threshold=1e-2, padding=0.25) limits.append(limit) self.viewer_trace_in.ui.ROIselect.setPos((limits[1][0], limits[0][0])) self.viewer_trace_in.ui.ROIselect.setSize((limits[1][1]-limits[1][0], limits[0][1] - limits[0][0])) self.linear_region.setPos(limits[1]) pos = self.viewer_trace_in.ui.ROIselect.pos() size = self.viewer_trace_in.ui.ROIselect.size() self.update_ROI(QtCore.QRectF(pos[0], pos[1], size[0], size[1])) def get_trace_in(self): method = self.settings.child('algo', 'method').value() if method == 'dscan': label = 'Insertion' unit = 'm' elif method == 'miips': label = 'Phase' unit = 'rad' else: label = 'Delay' unit = 's' self.data_in['trace_in'] = MeshData(self.data_in['raw_trace']['data'], self.data_in['raw_trace']['y_axis']['data'], self.data_in['raw_trace']['x_axis']['data'], labels=[label, "wavelength"], units=[unit, "m"]) return self.data_in['trace_in'] def get_pulse_in(self): self.data_in['pulse_in'] = pulse_from_spectrum(self.data_in['raw_spectrum']['x_axis']['data'], self.data_in['raw_spectrum']['data']) def get_axes_from_trace_node(self, fname, node_path): h5file = self.h5browse.open_file(fname) data, axes, nav_axes, is_spread = self.h5browse.get_h5_data(node_path) self.h5browse.close_file() return axes['x_axis'], axes['nav_00'] def load_last_scan(self): try: viewer = self.dashboard.scan_module.ui.scan2D_graph parameter_axis = utils.Axis(data=viewer.x_axis_scaled.copy(), label=viewer.scaling_options['scaled_xaxis']['label'], units=viewer.scaling_options['scaled_xaxis']['units']) wl = utils.Axis(data=viewer.y_axis_scaled.copy(), label=viewer.scaling_options['scaled_yaxis']['label'], units=viewer.scaling_options['scaled_yaxis']['units']) data = self.dashboard.scan_module.scan_data_2D[0].T.copy() self.set_data_in_exp(data, wl, parameter_axis) except Exception as e: pass def load_trace_in(self, fname=None, node_path=None): try: if fname is not None and node_path is not None: h5file = self.h5browse.open_file(fname) data, axes, nav_axes, is_spread = self.h5browse.get_h5_data(node_path) self.h5browse.close_file() else: data, fname, node_path = browse_data(ret_all=True, message='Select the node corresponding to the' 'Characterization Trace') if fname != '': self.save_file_pathname = fname self.settings.child('data_in_info', 'loaded_file').setValue(fname) self.settings.child('data_in_info', 'loaded_node').setValue(node_path) wl, parameter_axis = self.get_axes_from_trace_node(fname, node_path) self.set_data_in_exp(data, wl, parameter_axis, fname, node_path) except Exception as e: logger.exception(str(e)) def set_data_in_exp(self, data, wl, parameter_axis, fname='', node_path=''): if self.data_in is None: self.data_in = DataIn(source='experimental') scaling_parameter = self.settings.child('data_in_info', 'trace_in_info', 'param_scaling').value() scaling_wl = self.settings.child('data_in_info', 'trace_in_info', 'wl_scaling').value() wl['units'] = 'm' wl['data'] *= scaling_wl parameter_axis['data'] *= scaling_parameter parameter_axis['units'] = 'p.u.' self.data_in.update(dict(raw_trace={'data': data, 'x_axis': wl, 'y_axis': parameter_axis}, file_path=fname, node_path=node_path)) self.update_trace_info(self.data_in['raw_trace']) self.display_trace_in() self.viewer_trace_in.ROIselect_action.trigger() def load_spectrum_in(self, fname=None, node_path=None): if fname is not None and node_path is not None: h5file = self.h5browse.open_file(fname) data, axes, nav_axes, is_spread = self.h5browse.get_h5_data(node_path) self.h5browse.close_file() else: data, fname, node_path = browse_data(ret_all=True, message='Select the node corresponding to the' 'Fundamental Spectrum') if fname != '': h5file = self.h5browse.open_file(fname) data, axes, nav_axes, is_spread = self.h5browse.get_h5_data(node_path) self.h5browse.close_file() else: return if self.data_in is None: self.data_in = DataIn(source='experimental') self.data_in.update(dict(raw_spectrum={'data': data, 'x_axis': axes['x_axis']})) self.update_spectrum_info(self.data_in['raw_spectrum']) self.display_spectrum_in() def display_trace_in(self): self.viewer_trace_in.setImage(self.data_in['raw_trace']['data']) self.viewer_trace_in.x_axis = self.data_in['raw_trace']['x_axis'] self.viewer_trace_in.y_axis = self.data_in['raw_trace']['y_axis'] def display_spectrum_in(self): self.viewer_spectrum_in.show_data([self.data_in['raw_spectrum']['data']], x_axis=self.data_in['raw_spectrum']['x_axis'], labels=['Spectrum']) def display_data_in(self): self.display_trace_in() self.display_spectrum_in() class RetrieverWorker(QObject): result_signal = pyqtSignal(SimpleNamespace) status_sig = pyqtSignal(str) callback_sig = pyqtSignal(list) def __init__(self, data_in, pnps, settings): super().__init__() self.settings = settings self.data_in = data_in self.pnps = pnps self.retriever = None # def send_callback(self, pnps): # self.callback_sig.emit([pnps.Tmn, [pnps.parameter, pnps.process_w], pnps.pulse.field, pnps.field.t]) @pyqtSlot(str) def command_retriever(self, command): if command == 'start': self.start_retriever() elif command == 'stop': self.stop_retriever() def start_retriever(self): retriever_cls = _RETRIEVER_CLASSES[self.settings.child('retrieving', 'algo_type').value()] verbose = self.settings.child('retrieving', 'verbose').value() max_iter = self.settings.child('retrieving', 'max_iter').value() fwhm = self.settings.child('retrieving', 'pulse_guess', 'fwhm').value() amplitude = self.settings.child('retrieving', 'pulse_guess', 'phase_amp').value() uniform_response = self.settings.child('retrieving', 'uniform_response').value() preprocess2(self.data_in['trace_in'], self.pnps) self.retriever = retriever_cls(self.pnps, logging=True, verbose=verbose, maxiter=max_iter, status_sig=self.status_sig, callback=self.callback_sig.emit, step_command=QtWidgets.QApplication.processEvents) if not uniform_response: self.retriever._error_vector = nonuniform_error_vector.__get__(self.retriever) if self.settings.child('retrieving', 'guess_type').value() == 'Fundamental spectrum': pulse_guess = self.data_in['pulse_in'].copy() pulse_guess.spectrum = (1 + 0 * 1j) * np.abs(self.data_in['pulse_in'].spectrum) pulse_guess.spectrum /= (self.data_in['pulse_in'].wl * self.data_in['pulse_in'].wl) pulse_guess.field /= np.abs(pulse_guess.field).max() guess = pulse_guess.spectrum elif self.settings.child('retrieving', 'guess_type').value() == 'Random gaussian': random_gaussian(self.data_in['pulse_in'] , fwhm*1e-15, phase_max=amplitude) guess = self.data_in['pulse_in'].spectrum self.retriever.retrieve(self.data_in['trace_in'], guess, weights=None) self.result_signal.emit(self.retriever.result()) def stop_retriever(self): self.retriever._retrieval_state.running = False def main(): from pymodaq.daq_utils.daq_utils import get_set_preset_path app = QtWidgets.QApplication(sys.argv) win = QtWidgets.QMainWindow() area = gutils.DockArea() win.setCentralWidget(area) win.resize(1000, 500) win.setWindowTitle('PyMoDAQ Retriever') prog = Retriever(dashboard=None, dockarea=area) win.show() # try: # prog.load_trace_in(fname='C:\\Data\\2021\\20210315\\Dataset_20210315_001\\Dataset_20210315_001.h5', # node_path='/Raw_datas/Scan001/Detector000/Data1D/Ch000/Data') # prog.load_spectrum_in(fname='C:\\Users\\weber\\Desktop\\pulse.h5', # node_path='/Raw_datas/Detector000/Data1D/Ch000/Data') # prog.save_data('C:\\Users\\weber\\Desktop\\pulse_analysis.h5') # except: # pass sys.exit(app.exec_()) if __name__ == '__main__': main()
StarcoderdataPython
5070196
from rpy2.robjects.packages import importr, isinstalled from rpy2.rinterface import FloatSexpVector, ComplexSexpVector from rpy2.robjects.conversion import Converter import rpy2.robjects as robjects import pandas as pd # method to return Python representation of R vectors @robjects.conversion.py2ri.register(FloatSexpVector) def tuple_str(tpl): return FloatSexpVector(tpl) @robjects.conversion.py2ri.register(ComplexSexpVector) def complex_sexp_str(dictionary): return ComplexSexpVector(dictionary) my_converter = Converter('my converter') my_converter.py2ri.register(tuple, tuple_str) my_converter.py2ri.register(dict, complex_sexp_str) ''' installs required packages and libraries for executing R functions ''' def install_packages(): packnames = ('base', 'ggplot2', 'smoof', 'mlr', 'mlrMBO', 'DiceKriging', 'randomForest', 'ParamHelpers', 'stats', 'rgenoud', 'lhs', 'methods', 'emoa') if all(isinstalled(x) for x in packnames): have_tutorial_packages = True else: have_tutorial_packages = False if not have_tutorial_packages: # import R's utility package utils = importr('utils') # select a mirror for R packages utils.chooseCRANmirror(ind = 1) # select the first mirror in the list # R vector of strings from rpy2.robjects.vectors import StrVector # file packnames_to_install = [x for x in packnames if not isinstalled(x)] if len(packnames_to_install) > 0: utils.install_packages(StrVector(packnames_to_install)) ''' converts python dict to panda DataFrame to be passed as arg to MLR MBO ''' # https://stackoverflow.com/questions/18837262/convert-python-dict-into-a-dataframe def convert_dict_to_df(dictionary): your_df_from_dict = pd.DataFrame([dictionary]) print(your_df_from_dict) return your_df_from_dict def convert_df_to_dict(df): converted_dict = pd.DataFrame.to_dict(df, orient='index') return converted_dict[0]
StarcoderdataPython
72613
###################################################################################################################### # Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # # # Licensed under the Apache License Version 2.0 (the "License"). You may not use this file except in compliance # # with the License. A copy of the License is located at # # # # http://www.apache.org/licenses/ # # # # or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES # # OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions # # and limitations under the License. # ###################################################################################################################### import os import types from datetime import datetime import actions import boto_retry import handlers import handlers.task_tracking_table import services from handlers.task_tracking_table import TaskTrackingTable from helpers import safe_dict, safe_json, full_stack from helpers.dynamodb import unpack_record from main import lambda_handler from outputs.queued_logger import QueuedLogger from outputs.result_notifications import ResultNotifications ACTIVE_INSTANCES = "InstanceCount" CONCURRENCY_ID = handlers.TASK_TR_CONCURRENCY_ID ENV_DEBUG_TASK_TACKING_HANDLER = "DEBUG_TASK_TRACKING_HANDLER" NEW_TASK = 0 FINISHED_TASK = 1 FINISHED_CONCURRENCY_TASK = 2 CHECK_COMPLETION = 3 DELETE_ITEM = 4 START_WAITING_ACTION = 5 TASK_ACTION_STRINGS = [ "New task", "Finished task", "Finished task with concurrency handling", "Check task completion", "Delete task item", "Start waiting task" ] WARN_DELETING_RESOURCES = "Error deleting resources from bucket {} with key {}" DEBUG_ACTION = "Action is \"{}\" for task \"{}\", task-id is {}" DEBUG_DRYRUN = "Action will be executed in in dry-run mode" DEBUG_LAMBDA = "Lambda function invoked {}" DEBUG_ACTION_PARAMETERS = "Action parameters are {}" DEBUG_RUNNING_ECS_TASK = "Running {} step of task {} as ECS job" DEBUG_RESULT = "Handling actions tracking update took {:>.3f} seconds" DEBUG_MEMORY_SIZE = "Task memory allocation for executing lambda is {}" DEBUG_LAMBDA_FUNCTION_ = "Executing action with Lambda function {}, payload is {}" DEBUG_START_WAITING = "Waiting list count for ConcurrencyId \"{}\" is {}, action is \"{}\", starting waiting " \ "task \"{}\" with id {}" DEBUG_WAITING = "The waiting list for action \"{}\" with concurrency key \"{}\" is {}, the maximum number of concurrent " \ "running actions for this key is {}, action with id \"{}\" has been put in waiting state" DEBUG_DELETING_RESOURCES_FROM_S3 = "Deleting resource object {} from bucket {}, {}" ERR_RUNNING_TASK = "Error running task {}, {}, {}" LOG_STREAM = "{}-{:0>4d}{:0>2d}{:0>2d}" SCHEDULER_LAMBDA_FUNCTION_DEFAULT = "SchedulerDefault" SIZED_SCHEDULER_NAME_TEMPLATE = "Scheduler{:0>04d}" class TaskTrackingHandler(object): """ Class to handle events triggered by inserting new items in the actions tracking table. """ def __init__(self, event, context): """ Initializes the instance. :param event: Handled event :param context: Context if running in Lambda """ self._context = context self._event = event self._tracking_table = None self._concurrency_table = None self.started_tasks = 0 self.started_waiting_tasks = 0 self.waiting_for_execution_tasks = 0 self.started_completion_checks = 0 self.finished_concurrency_tasks = 0 self.done_work = False self.invoked_lambda_functions = [] self.events_client = None self._s3_client = None self._db_client = None # setup logging classname = self.__class__.__name__ dt = datetime.utcnow() logstream = LOG_STREAM.format(classname, dt.year, dt.month, dt.day) self._logger = QueuedLogger(logstream=logstream, context=self._context, buffersize=20, debug=os.getenv(ENV_DEBUG_TASK_TACKING_HANDLER, "false").lower() == "true") @classmethod def is_handling_request(cls, event, context): # In simulation the handler is called directly when inserting or updating items in the table if handlers.running_local(context): return False if event.get("Records", [{}])[0].get("eventSource", "") != "aws:dynamodb": return False source_arn = event["Records"][0]["eventSourceARN"] table_name = source_arn.split("/")[1] return table_name in [os.getenv(handlers.ENV_ACTION_TRACKING_TABLE), os.getenv(handlers.ENV_CONCURRENCY_TABLE)] @classmethod def task_string(cls, action): return TASK_ACTION_STRINGS[action] if 0 <= action < len(TASK_ACTION_STRINGS) else "Unknown" @property def tracking_table(self): """ Gets an instance of the tracking table and use it in subsequent calls :return: Instance tracking table """ if self._tracking_table is None: self._tracking_table = TaskTrackingTable(self._context, self._logger) return self._tracking_table @property def s3_client(self): if self._s3_client is None: self._s3_client = boto_retry.get_client_with_retries("s3", ["delete_item"], logger=self._logger) return self._s3_client @property def db_client(self): if self._db_client is None: self._db_client = boto_retry.get_client_with_retries("dynamodb", ["delete_item"], logger=self._logger) return self._db_client def _get_action_concurrency_key(self, item): """ Gets the concurrency key for a tasks action :param item: The task item :return: The concurrency key for the tasks action """ action = item[handlers.TASK_TR_ACTION] # get the name of the optional method to return the concurrency key action_class = actions.get_action_class(action) concurrency_key_method = getattr(action_class, handlers.ACTION_CONCURRENCY_KEY_METHOD, None) # prepare parameters for calling static function that returns the concurrency key if concurrency_key_method is not None: get_key_params = { actions.ACTION_PARAM_RESOURCES: handlers.get_item_resource_data(item, self._context), actions.ACTION_PARAM_ACCOUNT: item[handlers.TASK_TR_ACCOUNT], actions.ACTION_PARAM_STACK: os.getenv(handlers.ENV_STACK_NAME), actions.ACTION_PARAM_STACK_ID: os.getenv(handlers.ENV_STACK_ID), actions.ACTION_PARAM_TASK_ID: item[handlers.TASK_TR_ID], actions.ACTION_PARAM_TASK: item[handlers.TASK_TR_NAME] } get_key_params.update(item.get(handlers.TASK_TR_PARAMETERS)) return concurrency_key_method(get_key_params) else: # if this method is not available for action then use the name of the action as the key return action def _enter_waiting_list(self, concurrency_key): """ Adds 1 to waiting list counter for the specified concurrency key and returns new value :param concurrency_key: Concurrency key for counter :return: Updated counter """ # update/read counter for the concurrency key if not handlers.running_local(self._context): resp = self.concurrency_table.update_item_with_retries(Key={CONCURRENCY_ID: concurrency_key}, UpdateExpression="ADD InstanceCount :one SET RunNext=:run", ExpressionAttributeValues={":one": 1, ":run": False}, ReturnValues="UPDATED_NEW") return int(resp["Attributes"].get("InstanceCount", 0)) else: resp = self.concurrency_table.get_item_with_retries(Key={CONCURRENCY_ID: concurrency_key}) return resp.get("Item", {}).get(ACTIVE_INSTANCES, 0) def _leave_waiting_list(self, task_id, concurrency_key): """ Subtracts 1 from waiting list counter for the specified concurrency key and returns new value. If the counter reaches 0 then the entry for the concurrency key is removed :param concurrency_key: Concurrency key for counter :return: Updated counter """ # make a consistent read of the task self.tracking_table.get_task_item(task_id) if not handlers.running_local(self._context): resp = self.concurrency_table.update_item_with_retries(Key={CONCURRENCY_ID: concurrency_key}, UpdateExpression="ADD InstanceCount :min_one SET RunNext=:run", ExpressionAttributeValues={":min_one": -1, ":run": True}, ReturnValues="UPDATED_NEW") count = max(0, int(resp["Attributes"].get(ACTIVE_INSTANCES, 0))) # remove entry if no more waiting items for this key if count == 0: self.concurrency_table.delete_item_with_retries(Key={CONCURRENCY_ID: concurrency_key}) else: resp = self.concurrency_table.get_item_with_retries(Key={CONCURRENCY_ID: concurrency_key}) count = resp.get("Item", {}).get(ACTIVE_INSTANCES, 0) TaskTrackingTable._run_local_stream_event(os.getenv(handlers.ENV_CONCURRENCY_TABLE), "UPDATE", {"ConcurrencyId": concurrency_key, "InstanceCount": count}, {"ConcurrencyId": concurrency_key, "InstanceCount": count + 1}, self._context) return count @property def concurrency_table(self): """ Returns table to store last execution time for this handler. :return: table to store last execution time for this handler """ if self._concurrency_table is None: tablename = os.getenv(handlers.ENV_CONCURRENCY_TABLE) self._logger.debug("Using concurrency table {}", tablename) self._concurrency_table = services.get_session().resource("dynamodb").Table(tablename) boto_retry.add_retry_methods_to_resource(self._concurrency_table, ["update_item", "get_item", "delete_item"], context=self._context) return self._concurrency_table def _is_wait_listed(self, item): """ Test if there is a max concurrency level for the tasks action. If this is the case then a concurrency key is retrieved from the action and it is used to update the counter in the concurrency table for that key. The updated counter is tested against the max concurrency level for the tasks action :param item: task item :return: True if counter for tasks action concurrency key > mac concurrency level, False if it is less or equal or the action has no max concurrency level """ action = item.get(handlers.TASK_TR_ACTION, None) if action is None: return False action_properties = actions.get_action_properties(action) # test if there are concurrency restrictions max_action_concurrency = action_properties.get(actions.ACTION_MAX_CONCURRENCY) # no maximum if max_action_concurrency in [None, 0]: return False # property may be a lambda function, call the function with parameters of task as lambda parameters if types.FunctionType == type(max_action_concurrency): parameters = item[handlers.TASK_TR_PARAMETERS] max_action_concurrency = max_action_concurrency(parameters) if max_action_concurrency in [None, 0]: return False # get the key for the tasks action concurrency_key = self._get_action_concurrency_key(item) # enter the waiting list for that key count = int(self._enter_waiting_list(concurrency_key)) # set status to waiting if count > max concurrency level status = handlers.STATUS_WAITING if count >= int(max_action_concurrency) else None # store the concurrency key twice, the concurrency id is used for the index in the GSI and is removed after the # action is handled so it does not longer show in the GSI, but we keep another copy in the task tracking table that # we need to decrement the counter in the waiting list and possible start waiting instances with the same key self.tracking_table.update_task(item[handlers.TASK_TR_ID], task=item[handlers.TASK_TR_NAME], task_metrics=item.get(handlers.TASK_TR_METRICS, False), status=status, status_data={ handlers.TASK_TR_CONCURRENCY_KEY: concurrency_key, handlers.TASK_TR_CONCURRENCY_ID: concurrency_key }) if count > max_action_concurrency: self._logger.debug(DEBUG_WAITING, item[handlers.TASK_TR_ACTION], concurrency_key, count, max_action_concurrency, item[handlers.TASK_TR_ID]) return True return False def _start_task_execution(self, task_item, action=handlers.HANDLER_ACTION_EXECUTE): """ Creates an instance of the lambda function that executes the tasks action. It first checks is the action has specific memory requirements and based on this it creates a copy of this instance or one configured for the required memory. All information for executing the action is passed in the event. :param task_item: Task item for which action is executed :return: """ try: self._logger.debug("Entering start_task_execution ({}) with task {}", action, safe_json(task_item, indent=3)) # Create event for execution of the action and set its action so that is picked up by the execution handler event = {i: task_item.get(i) for i in task_item} event[handlers.HANDLER_EVENT_ACTION] = action self._logger.debug(DEBUG_ACTION, task_item[handlers.TASK_TR_ACTION], task_item[handlers.TASK_TR_NAME], task_item[handlers.TASK_TR_ID]) self._logger.debug(DEBUG_ACTION_PARAMETERS, safe_json(task_item.get(handlers.TASK_TR_PARAMETERS, {}), indent=3)) # get memory allocation for executing the task lambda_size = handlers.TASK_TR_COMPLETION_SIZE \ if action == handlers.HANDLER_ACTION_TEST_COMPLETION \ else handlers.TASK_TR_EXECUTE_SIZE execute_lambda_size = task_item.get(lambda_size, actions.ACTION_SIZE_STANDARD) if execute_lambda_size == actions.ACTION_USE_ECS: ecs_memory = task_item.get(handlers.TASK_EXECUTE_ECS_MEMORY if action == handlers.HANDLER_ACTION_EXECUTE else handlers.TASK_COMPLETION_ECS_MEMORY, None) else: ecs_memory = None if not handlers.running_local(self._context): self._logger.debug(DEBUG_MEMORY_SIZE, execute_lambda_size) if execute_lambda_size != actions.ACTION_USE_ECS: # create event payload payload = str.encode(safe_json(event)) # determine which lambda to execute on function_name = "{}-{}-{}".format(os.getenv(handlers.ENV_STACK_NAME), os.getenv(handlers.ENV_LAMBDA_NAME), execute_lambda_size) self._logger.debug("Running execution of task on lambda function {}", function_name) self._logger.debug(DEBUG_LAMBDA_FUNCTION_, function_name, payload) # start lambda function lambda_client = boto_retry.get_client_with_retries("lambda", ["invoke"], context=self._context, logger=self._logger) resp = lambda_client.invoke_with_retries(FunctionName=function_name, InvocationType="Event", LogType="None", Payload=payload) task_info = { "id": task_item[handlers.TASK_TR_ID], "task": task_item[handlers.TASK_TR_NAME], "action": task_item[handlers.TASK_TR_ACTION], "payload": payload, "status-code": resp["StatusCode"] } self._logger.debug(DEBUG_LAMBDA, safe_json(task_info, indent=2)) self.invoked_lambda_functions.append(task_info) else: # run as ECS job ecs_args = { handlers.HANDLER_EVENT_ACTION: action, handlers.TASK_NAME: task_item[handlers.TASK_TR_NAME], handlers.TASK_TR_ID: task_item[handlers.TASK_TR_ID]} self._logger.debug(DEBUG_RUNNING_ECS_TASK, action, task_item[handlers.TASK_TR_NAME]) handlers.run_as_ecs_job(ecs_args, ecs_memory_size=ecs_memory, context=self._context, logger=self._logger) else: lambda_handler(event, self._context) ResultNotifications(context=self._context, logger=self._logger).publish_started(task_item) except Exception as ex: self._logger.error(ERR_RUNNING_TASK, task_item, str(ex), full_stack()) def _handle_new_task_item(self, task_item): """ Handles stream updates for new tasks added to the task tracking table :param task_item: :return: """ self._logger.debug("Handling new task logic") # tasks can be wait listed if there is a max concurrency level for its action if self._is_wait_listed(task_item): self.waiting_for_execution_tasks += 1 return # if not wait listed start the action for the task self.started_tasks += 1 self._start_task_execution(task_item) def _handle_completed_concurrency_item(self, task_item): self._logger.debug("Handling completed concurrency logic") # gets the concurrency key for the task concurrency_key = task_item[handlers.TASK_TR_CONCURRENCY_KEY] self._logger.debug("Handling completed task with ConcurrencyKey {}", concurrency_key) # use the concurrency key to decrement the counter for that key in the waiting list count = self._leave_waiting_list(task_item[handlers.TASK_TR_ID], concurrency_key) self._logger.debug("Concurrency count for ConcurrencyKey {} is {}", concurrency_key, count) self.finished_concurrency_tasks += 1 ResultNotifications(context=self._context, logger=self._logger).publish_ended(task_item) def _handle_finished_task_without_completion(self, task_item): ResultNotifications(context=self._context, logger=self._logger).publish_ended(task_item) def _handle_start_waiting_action(self, concurrency_item): self._logger.debug("Handling start waiting task logic") # gets the concurrency key for the task concurrency_id = concurrency_item[handlers.TASK_TR_CONCURRENCY_ID] self._logger.debug("Handling completed task with ConcurrencyId {}", concurrency_id) waiting_list = self.tracking_table.get_waiting_tasks(concurrency_id) self._logger.debug(" List of waiting tasks for ConcurrencyKey {} is {}", concurrency_id, safe_json(waiting_list, indent=3)) if len(waiting_list) > 0: count = concurrency_item.get(ACTIVE_INSTANCES, 0) oldest_waiting_task = sorted(waiting_list, key=lambda w: w[handlers.TASK_TR_CREATED_TS])[0] self._logger.debug(DEBUG_START_WAITING, concurrency_id, count, oldest_waiting_task[handlers.TASK_TR_ACTION], oldest_waiting_task[handlers.TASK_TR_NAME], oldest_waiting_task[handlers.TASK_TR_ID]) self.started_waiting_tasks += 1 self._start_task_execution(oldest_waiting_task) def _handle_check_completion(self, task_item): self._logger.debug("Handling test for completion logic") if task_item.get(handlers.TASK_TR_RUN_LOCAL, False) and not handlers.running_local(self._context): self._logger.debug("Item running in local mode skipped") return self.started_completion_checks += 1 self._start_task_execution(task_item=task_item, action=handlers.HANDLER_ACTION_TEST_COMPLETION) def _handle_deleted_item(self, task_item): if task_item.get(handlers.TASK_TR_S3_RESOURCES, False): bucket = os.getenv(handlers.ENV_RESOURCE_BUCKET) key = task_item[handlers.TASK_TR_ID] + ".json" try: self._logger.debug(DEBUG_DELETING_RESOURCES_FROM_S3, bucket, key) self.s3_client.delete_object_with_retries(Bucket=bucket, Key=key) except Exception as ex: self._logger.warning(WARN_DELETING_RESOURCES, bucket, key, ex) def handle_request(self): """ Handles the event triggered by updates to the actions tracking table. :return: results of handling selected updates """ def tasks_items_to_execute(): """ Generator function that selects all record items from the event that need processing. :return: """ def table_name(rec): source_arn = rec["eventSourceARN"] return source_arn.split("/")[1] def from_tracking_table(rec): return table_name(rec) == os.getenv(handlers.ENV_ACTION_TRACKING_TABLE) def from_concurrency_table(rec): return table_name(rec) == os.getenv(handlers.ENV_CONCURRENCY_TABLE) def get_old_image(task_record): return task_record["dynamodb"].get("OldImage", {}) def get_new_image(task_record): return task_record["dynamodb"].get("NewImage", {}) def get_new_status(task_record): return get_new_image(task_record).get(handlers.TASK_TR_STATUS, {}).get("S") def get_old_status(task_record): return get_new_image(task_record).get(handlers.TASK_TR_STATUS, {}).get("S") def is_task_tracking_table_update(task_record): if not from_tracking_table(task_record): return False return task_record["eventName"] in ["UPDATE", "MODIFY"] def is_task_done(task_record): if not is_task_tracking_table_update(task_record): return False new_status = get_new_status(task_record) old_status = get_old_status(task_record) if old_status != new_status: return False return new_status in handlers.task_tracking_table.NOT_LONGER_ACTIVE_STATUSES def is_task_with_concurrency(task_record): return get_new_image(task_record).get(handlers.TASK_TR_CONCURRENCY_KEY, {}).get("S") is not None def get_old_last_update(task_record): return get_old_image(task_record).get(handlers.TASK_TR_LAST_WAIT_COMPLETION, {}).get("S") def get_new_last_update(task_record): return get_new_image(task_record).get(handlers.TASK_TR_LAST_WAIT_COMPLETION, {}).get("S") def is_delete_task(task_record): return from_tracking_table(r) and task_record["eventName"] == "REMOVE" def is_new_task(task_record): if from_tracking_table(r) and task_record["eventName"] == "INSERT": return get_new_status(task_record) == handlers.STATUS_PENDING return False def is_completed_with_concurrency(task_record): return is_task_done(task_record) and is_task_with_concurrency(task_record) def is_completed_without_concurrency(task_record): return is_task_done(task_record) and not is_task_with_concurrency(task_record) def is_wait_for_completion(task_record): if not is_task_tracking_table_update(task_record): return False if get_old_status(task_record) != handlers.STATUS_WAIT_FOR_COMPLETION or \ get_new_status(task_record) != handlers.STATUS_WAIT_FOR_COMPLETION: return False return get_old_last_update(task_record) != get_new_last_update(task_record) def is_concurrency_task_completed(concurrency_record): if not from_concurrency_table(concurrency_record): return False if concurrency_record["eventName"] == "REMOVE": return False return concurrency_record["dynamodb"].get("NewImage", {}).get("RunNext", {}).get("BOOL", False) def get_action_type(rec): if is_new_task(rec): return NEW_TASK if is_completed_without_concurrency(rec): return FINISHED_TASK if is_completed_with_concurrency(rec): return FINISHED_CONCURRENCY_TASK if is_wait_for_completion(rec): return CHECK_COMPLETION if is_delete_task(rec): return DELETE_ITEM if is_concurrency_task_completed(rec): return START_WAITING_ACTION return None for r in self._event.get("Records"): self._logger.debug("Record to process is {}", safe_json(r, indent=2)) if r.get("eventSource") == "aws:dynamodb": image_used = "NewImage" if "NewImage" in r["dynamodb"] else "OldImage" if r["dynamodb"].get("NewImage", {}).get(handlers.TASK_TR_ACTION) is None and \ r["dynamodb"].get("OldImage", {}).get(handlers.TASK_TR_ACTION) is not None: continue self._logger.debug_enabled = r["dynamodb"][image_used].get(handlers.TASK_TR_DEBUG, {}).get("BOOL", False) update_to_handle = get_action_type(r) if update_to_handle is not None: yield update_to_handle, r else: self._logger.debug("No action for record") try: start = datetime.now() task_handlers = [ self._handle_new_task_item, self._handle_finished_task_without_completion, self._handle_completed_concurrency_item, self._handle_check_completion, self._handle_deleted_item, self._handle_start_waiting_action ] for task_tracking_update_type, record in tasks_items_to_execute(): self.done_work = True used_image = "OldImage" if record["eventName"] == "REMOVE" else "NewImage" image = record["dynamodb"][used_image] handled_item = unpack_record(image) self._logger.debug_enabled = handled_item.get(handlers.TASK_TR_DEBUG, False) self._logger.debug("Executing handler function {} for type {} ({})", task_handlers[task_tracking_update_type].__name__, self.task_string(task_tracking_update_type), task_tracking_update_type) task_handlers[task_tracking_update_type](handled_item) if not self.done_work: self._logger.clear() running_time = float((datetime.now() - start).total_seconds()) if self.done_work: self._logger.debug(DEBUG_RESULT, running_time) return safe_dict({ "datetime": datetime.now().isoformat(), "waiting-for-execution": self.waiting_for_execution_tasks, "started-check-for-completion": self.started_completion_checks, "started-execution": self.started_tasks, "started-waiting": self.started_waiting_tasks, "completed-concurrency-tasks": self.finished_concurrency_tasks, "running-time": running_time }) finally: self._logger.flush()
StarcoderdataPython
3362345
<filename>leasing/tests/test_utils.py from datetime import date from leasing.utils import calculate_increase_with_360_day_calendar, days360 def test_days360_year(): date1 = date(year=2020, month=1, day=1) date2 = date(year=2021, month=1, day=1) days = days360(date1, date2, True) assert days == 360 def test_days360_leap_year(): date1 = date(year=2020, month=1, day=15) date2 = date(year=2020, month=3, day=15) days = days360(date1, date2, True) assert days == 60 def test_calculate_increase_with_360_day_calendar(): date1 = date(year=2020, month=8, day=3) date2 = date(year=2020, month=10, day=15) increase_percentage = 3 current_amount = 150000.0 expected_amount = 151000.0 calculated_amount = calculate_increase_with_360_day_calendar( date1, date2, increase_percentage, current_amount ) assert expected_amount == calculated_amount
StarcoderdataPython
9688759
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-12-26 10:21 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('cats', '0011_auto_20171226_1745'), ] operations = [ migrations.CreateModel( name='CatImgs', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('adate', models.DateTimeField(auto_now_add=True)), ('img_hash', models.CharField(default='', max_length=64, unique=True)), ('img_src', models.CharField(default='', max_length=255)), ('img_desc', models.CharField(default='', max_length=255)), ('img_from', models.CharField(default='', max_length=255)), ('img_status', models.BooleanField(db_index=True, default=0)), ('img_like', models.IntegerField(default=0)), ], options={ 'verbose_name': 'cat imgs', 'verbose_name_plural': 'cat imgs', 'db_table': 'cat_imgs', }, ), migrations.CreateModel( name='PicComments', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('adate', models.DateTimeField(auto_now_add=True, db_index=True)), ('content', models.TextField(default='')), ('stars', models.DecimalField(decimal_places=1, default=0, max_digits=4)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='+', to=settings.AUTH_USER_MODEL, to_field='username')), ('img_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='cats.CatImgs')), ], options={ 'verbose_name': 'pic comments', 'verbose_name_plural': 'cat imgs comments', 'db_table': 'cats_pic_comments', }, ), migrations.CreateModel( name='PicLikes', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('adate', models.DateTimeField(auto_now_add=True, db_index=True)), ('is_like', models.IntegerField(choices=[(-1, '不喜欢'), (0, '取消'), (1, '喜欢')])), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='+', to=settings.AUTH_USER_MODEL, to_field='username')), ('img_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='cats.CatImgs')), ], options={ 'verbose_name': 'cat imgs likes', 'verbose_name_plural': 'cat imgs likes', 'db_table': 'cats_pic_likes', }, ), migrations.CreateModel( name='PicStars', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('stars', models.BigIntegerField(default=0)), ('comments', models.BigIntegerField(default=0)), ('img_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='cats.CatImgs')), ], options={ 'verbose_name': 'cat imgs stars', 'verbose_name_plural': 'cat imgs stars', 'db_table': 'cats_pic_stars', }, ), migrations.AlterField( model_name='viewlog', name='author', field=models.ForeignKey(db_column='author', on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, to_field='username'), ), ]
StarcoderdataPython
203316
<reponame>abhikpal/p5-examples from p5 import * def draw(): no_loop() arc((180, 180), 251, 251, 0, PI + QUARTER_PI, 'OPEN') run()
StarcoderdataPython
9607256
<reponame>calhewitt/snewpdag<gh_stars>0 """ Node in the directed acyclic graph. Implemented on observer-observable pattern. Plugins should subclass Node and override alert, revoke, reset, report. """ import logging from snewpdag.values import History class Node: def __init__(self, name, **kwargs): """ Initialize the node. OVERRIDE this method to initialize more instance data. At the end call super().__init__(**kwargs) to continue initialization. """ self.name = name # name of the Node self.observers = [] # observers of this Node self.watch_list = [] # nodes this Node is observing self.last_data = {} # data after last update self.last_source = None # source of last update def dispose(self): """ Clear the last data, and detach from all observers and observables. """ self.last_data.clear() for n in self.observers: self.detach(n) for n in self.watch_list: n.detach(self) def attach(self, observer): """ Register observer (of type Node). The observer's notify() is called when this Node is done processing. The watch list is only to keep track of inputs. """ if observer not in self.observers: self.observers.append(observer) observer.watch_list.append(self) def detach(self, observer): """ Stop notifications to the specified observer. Also removes this node from observer's watch list. """ if observer in self.observers: self.observers.remove(observer) observer.watch_list.remove(self) def notify(self, action, data): """ Notify all observers that they need to update. Update history by appending name of current node. """ self.last_data = data.copy() # shallow copy (copies refs of objects) # record action self.last_data['action'] = action # append to history (tuple, so remember that tuples are immutable) #if history == None: # if 'history' in data: # h1 = self.last_data['history'] # else: # #h1 = () # h1 = History() #else: # h1 = history if 'history' not in data: self.last_data['history'] = History() self.last_data['history'].append(self.name) #h2 = (self.name,) #self.last_data['history'] = h1 + h2 # notify all observers for obs in self.observers: logging.debug('DEBUG:{0}: notify {1}'.format(self.name, obs.name)) obs.update(self.last_data) # # entry points # alert, revoke, report, reset are preferred. # this update() will invoke one of the four. # overriding update() gives full control to the subclass. # # alert/revoke/report/reset will be called first. # return True if forward action downstream. # return False/None if don't forward. # return payload to notify downstream. # notify() will add this node name to the history, # so if you need to update the payload history, # just record the past history, i.e., before this node. # # These methods are called by update() with their own local shallow # copy of the payload. They can therefore modify the contents of the # payload itself, though underlying mutable objects shouldn't be modified # (as the modifications will be seen by any plugins executing # after this one). # # Remember that mutable objects in python are list, dict, byte array. # Immutable objects: int, float, complex, string, tuple, frozen set, bytes. # def alert(self, data): """ Alert action. Override this method to perform calculations. """ return True def revoke(self, data): """ Revoke action. Override this method to update calculation. """ return True def report(self, data): """ Report action. Override to provide a final answer. """ return True def reset(self, data): """ Reset action. Override to clear alert data (revoke all inputs). Not used in single-instance calculation, but rather for MC trials. """ return True def other(self, data): """ An action not defined by default. Override to implement handling a custom alert. By default, it gives an error message and consumes (doesn't forward) the alert. (Note that action is defined in the payload, because that's how we got here in the first place) """ logging.error('{0}: unrecognized action {1}'.format( self.name, data['action'])) return False def update(self, data): """ Update this object with provided data. If you know what you're doing, override this method to perform calculations. When done, call notify. Default method notifies using original data. A nontrivial calculation is likely to notify with different data. It is preferred to override alert/revoke/report/reset methods. This method makes a local shallow copy of the payload before calling the action methods. So it should be all right for an action to add to the payload and return it for notification (which will make another shallow copy as self.last_data). """ logging.debug('{0}: update({1})'.format(self.name, data['action'] if 'action' in data else 'None')) cdata = data.copy() # local shallow copy if 'history' in cdata: cdata['history'] = data['history'].copy() # local copy of history self.last_source = cdata['history'].last() if 'action' in cdata: action = cdata['action'] v = False if action == 'alert': v = self.alert(cdata) elif action == 'revoke': v = self.revoke(cdata) elif action == 'report': v = self.report(cdata) elif action == 'reset': v = self.reset(cdata) else: v = self.other(cdata) if v == True: self.notify(action, cdata) # notify() will update history elif v == False: return elif type(v) is dict: self.notify(v['action'] if 'action' in v else action, v) else: logging.error('{0}: empty action response'.format(self.name)) return else: logging.error('[{}] Action not specified'.format(self.name)) # # utility functions # def watch_index(self, source): """ Utility function to find index in watch_list for given source. Returns -1 if not found. """ for i in range(len(self.watch_list)): if source == self.watch_list[i].name: return i logging.error('{}: unrecognized source {}'.format(self.name, source)) return -1 def last_watch_index(self): if self.last_source: return self.watch_index(self.last_source) logging.error('{}: no payload source'.format(self.name)) return -1
StarcoderdataPython
12840129
<gh_stars>0 """ A simple example for Reinforcement Learning using table lookup Q-learning method. An agent "o" is on the left of a 1 dimensional world, the treasure is on the rightmost location. Run this program and to see how the agent will improve its strategy of finding the treasure. View more on my tutorial page: https://morvanzhou.github.io/tutorials/ A better explanation is available at https://medium.com/emergent-future/simple-reinforcement-learning-with-tensorflow-part-0-q-learning-with-tables-and-neural-networks-d195264329d0 """ """ Notes: Unlike policy gradient methods, which attempt to learn functions which directly map an observation to an action, Q-Learning attempts to learn the value of being in a given state, and taking a specific action there. Q learning helps learn long term expected rewards In it’s simplest implementation, Q-Learning is a table of values for every state (row) and action (column) possible in the environment. Within each cell of the table, we learn a value for how good it is to take a given action within a given state. In the case of the FrozenLake environment (OpenAI), we have 16 possible states (one for each block), and 4 possible actions (the four directions of movement), giving us a 16x4 table of Q-values. We start by initializing the table to be uniform (all zeros), and then as we observe the rewards we obtain for various actions, we update the table accordingly. For making updates to Q-table values, we use Bellman equation: Q(s,a) = r + γ(max(Q(s’,a’)) This says that the Q-value for a given state (s) and action (a) should represent the current reward (r) plus the maximum discounted (γ) future reward expected according to our own table for the next state (s’) we would end up in. The discount variable allows us to decide how important the possible future rewards are compared to the present reward. By updating in this way, the table slowly begins to obtain accurate measures of the expected future reward for a given action in a given state. """ import numpy as np import pandas as pd import time np.random.seed(2) # reproducible N_STATES = 6 # the length of the 1 dimensional world ACTIONS = ['left', 'right'] # available actions EPSILON = 0.9 # greedy police. There is 0.1 probability of randomness so that agent may be able to explore the world and find robust solutions ALPHA = 0.1 # learning rate GAMMA = 0.9 # discount factor. discount variable allows us to decide how important the possible future rewards are compared to the present reward. MAX_EPISODES = 13 # maximum episodes FRESH_TIME = 0.2 # fresh time for one move def build_q_table(n_states, actions): """ Initialize a zero-valued q-table of states and actions """ table = pd.DataFrame( np.zeros((n_states, len(actions))), # q_table initial values columns=actions, # actions's name ) # print(table) # show table return table def choose_action(state, q_table): """ Decide on the next move. Act non-greedily every now and then, or explore arena if unexplored, else choose the state with maximum reward """ # This is how to choose an action state_actions = q_table.iloc[state, :] if (np.random.uniform() > EPSILON) or ((state_actions == 0).all()): # act non-greedy or state-action have no value (unexplored arena) action_name = np.random.choice(ACTIONS) else: # act greedy action_name = state_actions.idxmax() # replace argmax to idxmax as argmax means a different function in newer version of pandas return action_name def get_env_feedback(S, A): # This is how agent will interact with the environment if A == 'right': # move right if S == N_STATES - 2: # terminate S_ = 'terminal' R = 1 else: S_ = S + 1 R = 0 else: # move left R = 0 if S == 0: S_ = S # reach the wall else: S_ = S - 1 # New state and reward obtained return S_, R def update_env(S, episode, step_counter): # This is how environment is updated env_list = ['-']*(N_STATES-1) + ['T'] # '---------T' our environment if S == 'terminal': interaction = 'Episode %s: total_steps = %s' % (episode+1, step_counter) print('\r{}'.format(interaction), end='') time.sleep(2) print('\r ', end='') else: env_list[S] = 'o' interaction = ''.join(env_list) print('\r{}'.format(interaction), end='') time.sleep(FRESH_TIME) def update_q_table(q_table, S, A, S_, R): """ Bellman equation """ is_terminated = False q_predict = q_table.loc[S, A] if S_ != 'terminal': q_target = R + GAMMA * q_table.iloc[S_, :].max() # next state is not terminal else: q_target = R # next state is terminal is_terminated = True # terminate this episode q_table.loc[S, A] += ALPHA * (q_target - q_predict) # update return q_table, S_, is_terminated def rl(): # main part of RL loop q_table = build_q_table(N_STATES, ACTIONS) for episode in range(MAX_EPISODES): step_counter = 0 S = 0 is_terminated = False update_env(S, episode, step_counter) while not is_terminated: A = choose_action(S, q_table) S_, R = get_env_feedback(S, A) # take action & get next state and reward q_table, S, is_terminated = update_q_table(q_table, S, A, S_, R) # move to next state update_env(S, episode, step_counter+1) step_counter += 1 return q_table if __name__ == "__main__": q_table = rl() print('\r\nQ-table:\n') print(q_table)
StarcoderdataPython
9603949
<filename>debugwire.py import time import avrasm as asm from collections import namedtuple class DummyProfiler: def step(self, title): pass class SimpleProfiler: def __init__(self): self.prev = time.monotonic() def step(self, msg): now = time.monotonic() print("{:10.6f}s {}".format(now - self.prev, msg)) self.prev = now class DWException(Exception): pass # used as pointer for r/w operations REG_Z = 30 # debugWIRE commands CMD_DISABLE = 0x06 CMD_RESET = 0x07 CMD_GO = 0x20 CMD_STEP = 0x23 CMD_RUN = 0x30 CMD_RW = 0x66 CMD_RW_MODE = 0xc2 CMD_SET_PC = 0xd0 CMD_SET_BP = 0xd1 CMD_SET_IR= 0xd2 CMD_READ_SIG = 0xf3 # CMD_RW_MODE modes RW_MODE_READ_SRAM = 0x00 RW_MODE_READ_REGS = 0x01 RW_MODE_READ_FLASH = 0x02 RW_MODE_WRITE_SRAM = 0x04 RW_MODE_WRITE_REGS = 0x05 # SPMCSR register bits SPMEN = 0x01 PGERS = 0x02 PGWRT = 0x04 RFLB = 0x08 CTPB = 0x10 # Mostly everything courtesy of http://www.ruemohr.org/docs/debugwire.html class DebugWire: def __init__(self, iface, enable_log=False): self.iface = iface self.enable_log = enable_log def open(self): """Open the interface. Returns interface baud rate.""" baudrate = self.iface.open() self.reset() return baudrate def close(self): self.iface.close() def __enter__(self): return self def __exit__(self, type, value, traceback): self.close() def reset(self): """Reset the target device.""" self.iface.send_break() self.iface.write([CMD_RESET]) while self.iface.read(1)[0] != 0x55: pass def run(self): """Run the code on the target device.""" self.iface.write([CMD_RUN]) def disable(self): """Disable DebugWire and enable ISP until the next power cycle.""" self.iface.write([CMD_DISABLE]) def read_signature(self): """Returns the device debugWIRE signature as an integer.""" self.iface.write([CMD_READ_SIG]) sig = self.iface.read(2) return (sig[0] << 8) | sig[1] def read_regs(self, start, count): """Read registers from the target and return a list.""" self.iface.write([ CMD_RW, CMD_RW_MODE, RW_MODE_READ_REGS, CMD_SET_PC, 0x00, start, CMD_SET_BP, 0x00, start + count, CMD_GO]) return self.iface.read(count) def write_regs(self, start, values): """Write a list of register values to the target.""" self.iface.write([ CMD_RW, CMD_RW_MODE, RW_MODE_WRITE_REGS, CMD_SET_PC, 0x00, start, CMD_SET_BP, 0x00, start + len(values), CMD_GO] + list(values)) def read_sram(self, start, count): """Read a segment of SRAM memory from the target.""" end = count * 2 self.write_regs(REG_Z, [start & 0xff, (start >> 8) & 0xff]) self.iface.write([ CMD_RW, CMD_RW_MODE, RW_MODE_READ_SRAM, CMD_SET_PC, 0x00, 0x00, CMD_SET_BP, (end >> 8) & 0xff, end & 0xff, CMD_GO]) return self.iface.read(count) def write_sram(self, start, values): """Write a segment of SRAM memory to the target.""" end = len(values) * 2 + 1 self.write_regs(REG_Z, [start & 0xff, (start >> 8) & 0xff]) self.iface.write([ CMD_RW, CMD_RW_MODE, RW_MODE_WRITE_SRAM, CMD_SET_PC, 0x00, 0x01, CMD_SET_BP, (end >> 8) & 0xff, end & 0xff, CMD_GO] + list(values)) def read_flash(self, start, count): """Read a segment of flash memory from the target.""" end = count * 2 self.write_regs(REG_Z, [start & 0xff, (start >> 8) & 0xff]) self.iface.write([ CMD_RW, CMD_RW_MODE, RW_MODE_READ_FLASH, CMD_SET_PC, 0x00, 0x00, CMD_SET_BP, (end >> 8) & 0xff, end & 0xff, CMD_GO]) return self.iface.read(count) def _exec(self, code): buf = bytes() for inst in code: if type(inst) == bytes: buf += inst else: buf += bytes([ CMD_SET_IR, (inst >> 8) & 0xff, inst & 0xff, CMD_STEP]) self.iface.write(buf) def write_flash_page(self, dev, start, data): if start % dev.flash_pagesize != 0: raise DWException("Bad page offset") if len(data) != dev.flash_pagesize: raise DWException("Bad page size") prof = (SimpleProfiler if self.enable_log else DummyProfiler)() prof.step("Starting page write") # set up constants in registers self.write_regs(26, [ SPMEN, # r26 PGERS | SPMEN, # r27 PGWRT | SPMEN, # r28 CTPB | SPMEN, # r29 start & 0xff, (start >> 8) & 0xff # r30:r31(Z) ]) # clear self-programming buffer prof.step("Write constants") self._exec([ asm.movw(24, 30), # movw r24, r30 asm.out(dev.reg_spmcsr, 29), # out SPMCSR, r29 ; CTPB | SPMEN asm.spm()]) # spm self.iface.send_break() prof.step("Clear buffer") # erase flash page self._exec([ asm.out(dev.reg_spmcsr, 27), # out SPMCSR, r27 ; PGERS | SPMEN asm.spm(), # spm ]) # wait for erase to complete self.iface.send_break() prof.step("Erase page") # write data to buffer # How many instruction bytes to write at once # The maximum suitable value for this is probably related to USB buffer sizes etc. CHUNK_LEN = 16 for ci in range(0, len(data), CHUNK_LEN): buf = [] for ii in range(ci, ci + CHUNK_LEN, 2): if dev.reg_dwdr: buf += [ asm.in_(dev.reg_dwdr, 0), bytes([data[ii]]), # in r0, DWDR ; (low byte) asm.in_(dev.reg_dwdr, 1), bytes([data[ii + 1]])] # in r1, DWDR ; (high byte) else: buf += [ asm.ldi(22, data[ii]), # ldi r22, (low byte) asm.ldi(23, data[ii + 1]), # ldi r23, (high byte) asm.movw(0, 22)] # movw r0, r22 buf += [ asm.out(dev.reg_spmcsr, 26), # out SPMCSR, r26 ; SPMEN asm.spm(), # spm asm.adiw(30, 2)] # adiw Z, 2 self._exec(buf) prof.step("Write data") # write buffer to flash self._exec([ asm.movw(30, 24), # movw r30, r24 asm.out(dev.reg_spmcsr, 28), # out SPMCSR, r28 ; PGWRT | SPMEN asm.spm()]) # spm # wait for write to complete self.iface.send_break() prof.step("Write flash") def read_fuses(self, dev): """Reads the fuse and lock bits from the target and returns them as a named tuple.""" # set up constants buf = [ asm.ldi(29, RFLB | SPMEN), # ldi r29, RFLB | SPMEN asm.ldi(31, 0), # ldi r31, 0 ; (high byte of Z) ] # there are four bytes to read for index in reversed(range(4)): # read fuse/lock bit into r0 buf += [ asm.ldi(30, index), # ldi r31, index ; (low byte of Z) asm.out(dev.reg_spmcsr, 29), # out SPMCSR, r29 ; RFLB | SPMEN asm.lpm(), # lpm ] # move into another register if not reading index 0 if index != 0: buf += [ asm.mov(index, 0), # mov r[index], r0 ] # execute generated code self._exec(buf) # read r0-r3 which now contain the bytes that were read return Fuses(*self.read_regs(0, 4)) Fuses = namedtuple("Fuses", ["low_fuse", "lock_bits", "extended_fuse", "high_fuse"])
StarcoderdataPython
12825916
#!/usr/bin/env python3 #_*_ coding: utf-8 _*_ __author__ = "monkey" from dal import autocomplete from apps.blog.models import Category, Tag class CategoryAutoComplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated: return Category.objects.none() qs = Category.objects.filter(owner=self.request.user) if self.q: qs = qs.filter(name__istartswith=self.q) return qs class TagAutoComplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated: return Tag.objects.none() qs = Tag.objects.filter(owner=self.request.user) if self.q: qs = qs.filter(name__istartswith=self.q) return qs
StarcoderdataPython
11254263
<filename>sprp_dialog.py # -*- coding: utf-8 -*- """ /*************************************************************************** SimplePhotogrammetryRoutePlannerDialog A QGIS plugin A imple photogrammetry route planner. Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/ ------------------- begin : 2021-04-24 git sha : $Format:%H$ copyright : (C) 2021 by <NAME> email : <EMAIL> ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ """ import os,string from qgis.PyQt import uic from qgis.PyQt import QtWidgets from PyQt5.QtWidgets import * from PyQt5.QtCore import (Qt, pyqtSignal) from qgis.core import * from qgis.utils import iface import sys sys.path.insert(0, os.path.join(os.path.dirname(__file__),'sprp')) from sprp.core.alg import * from sprp.export.shapefile import * from sprp.export.memory import * MAIN_DLG = None def setProgressVaue(currentValue,totalValue,msg): #print(MAIN_DLG) MAIN_DLG.progressChanged.emit(currentValue,totalValue,msg) QApplication.processEvents() # This loads your .ui file so that PyQt can populate your plugin with the elements from Qt Designer FORM_CLASS, _ = uic.loadUiType(os.path.join( os.path.dirname(__file__), 'sprp_dialog_base.ui')) class SimplePhotogrammetryRoutePlannerDialog(QtWidgets.QDialog, FORM_CLASS): progressChanged = pyqtSignal(int,int,str) def __init__(self, parent=None): """Constructor.""" super(SimplePhotogrammetryRoutePlannerDialog, self).__init__(parent) # Set up the user interface from Designer through FORM_CLASS. # After self.setupUi() you can access any designer object by doing # self.<objectname>, and you can use autoconnect slots - see # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html # #widgets-and-dialogs-with-auto-connect self.setupUi(self) self.stackedWidget.setCurrentIndex(0) self.setupConnection() self.wkt_polygon = None global MAIN_DLG MAIN_DLG = self def setupConnection(self): self.selectPathBtn.clicked.connect(self.selectPath) self.calculateBtn.clicked.connect(self.doCalcuate) self.polygonModeRadioButton.clicked.connect(self.polygonModeRadioButton_clicked) self.lineModeRadioButton.clicked.connect(self.lineModeRadioButton_clicked) self.selectLinePushButton.clicked.connect(self.selectLinePushButton_clicked) self.selectPolygonBtn.clicked.connect(self.selectPolygonBtn_clicked) self.progressChanged.connect(self.setProgressValue) self.saveCheckBox.clicked.connect(self.saveCheckBox_triggered) def checkToSaveFile(self,sc,path,basename): if self.saveCheckBox.isChecked(): if os.path.exists(path) == True: sfe = ShapefileExportor(path,basename) sfe.save(sc) else: QMessageBox.warning(self, "Error"," Please select a correct path!") return def saveCheckBox_triggered(self): if self.saveCheckBox.isChecked(): self.fileNameEdit.setEnabled(True) self.savePathEdit.setEnabled(True) self.selectPathBtn.setEnabled(True) else: self.fileNameEdit.setEnabled(False) self.savePathEdit.setEnabled(False) self.selectPathBtn.setEnabled(False) def setProgressValue(self,currentValue,totalValue,msg): self.progressBar.setFormat("%p% --\t" + msg) self.progressBar.setRange(0,totalValue) self.progressBar.setValue(currentValue) #self.progressBar.setText(msg) ################################################################################ # polygon def selectPolygonBtn_clicked(self): vectorDraftLyr = QgsVectorLayer('Polygon?crs=epsg:4326', 'Please Draw A Polygon for Planning' , "memory") QgsProject().instance().addMapLayer(vectorDraftLyr) #vectorDraftLyr.startEditing() # remove the original myvl #QgsProject.instance().layerTreeRoot().removeChildNode(myvl) # set layer active self.hide() iface.setActiveLayer(vectorDraftLyr) # start edit iface.actionToggleEditing().trigger() # enable tool iface.actionAddFeature().trigger() #self.show() iface.actionToggleEditing().triggered.connect(self.endDrawPolygon) #print("get here") def endDrawPolygon(self): iface.actionToggleEditing().triggered.disconnect(self.endDrawPolygon) self.show() vlayer = iface.activeLayer() selection = vlayer.getFeatures() count = vlayer.featureCount() #print("当前选择层有特征数:%d" % count) for feature in selection: geom = feature.geometry() geomSingleType = QgsWkbTypes.isSingleType(geom.wkbType()) if geom.type() == QgsWkbTypes.PolygonGeometry: if geomSingleType: x = geom.asPolygon() #print("Polygon: ", x, "length: ", geom.length(),"area: ", geom.area()) #print(geom.asWkt()) self.wkt_polygon = geom.asWkt() ################################################################################ # line def selectLinePushButton_clicked(self): #self.hide() vectorDraftLyr = QgsVectorLayer('LineString?crs=epsg:4326', 'Please Draw A Line for Planning' , "memory") QgsProject().instance().addMapLayer(vectorDraftLyr) # set layer active self.hide() iface.setActiveLayer(vectorDraftLyr) # start edit iface.actionToggleEditing().trigger() # enable tool iface.actionAddFeature().trigger() #self.show() iface.actionToggleEditing().triggered.connect(self.endDrawLine) def endDrawLine(self): iface.actionToggleEditing().triggered.disconnect(self.endDrawLine) self.show() vlayer = iface.activeLayer() selection = vlayer.getFeatures() count = vlayer.featureCount() #print("当前选择层有特征数:%d" % count) for feature in selection: geom = feature.geometry() geomSingleType = QgsWkbTypes.isSingleType(geom.wkbType()) if geom.type() == QgsWkbTypes.LineGeometry: if geomSingleType: x = geom.asPolyline() print("Line: ", x, "length: ", geom.length()) pstr_list = [] for index in range(len(x) - 1): resStr = "{},{},{},{}".format(x[index].x(),x[index].y() ,x[index+1].x(), x[index+1].y()) pstr_list.append(resStr) print(pstr_list) self.startEndPointEdt.setText(';'.join(pstr_list)) def polygonModeRadioButton_clicked(self): if self.polygonModeRadioButton.isChecked(): self.stackedWidget.setCurrentIndex(1) def lineModeRadioButton_clicked(self): if self.lineModeRadioButton.isChecked(): self.stackedWidget.setCurrentIndex(0) def selectPath(self): # dlg = QtWidgets.QFileDialog(self) # dlg.setFileMode(QFileDialog::Directory) self.save_dir_name = QFileDialog.getExistingDirectory(self,"Select Save Directory","/") print(self.save_dir_name) self.savePathEdit.setText(self.save_dir_name) def doCalcuate(self): focusLength = float(self.focusLengthEdit.text()) pixelSize = float(self.pixelSizeEdit.text()) gsd = float(self.gsdEdit.text()) flightSpeed = float(self.flightSpeedEdit.text()) courseOverlap = float(self.courseOverlapSpin.value()) / 100 sidewiseOverlap = float(self.sidewiseOverlapSpin.value()) / 100 cameraWidth = int(self.cameraWidthEdit.text()) cameraHeight = int(self.cameraHeightEdit.text()) if self.saveCheckBox.isChecked(): if self.savePathEdit.text() =='' or self.fileNameEdit.text() =='': QMessageBox.warning(self, "Warning"," Please enter the filename and filepath!") return if os.path.exists(self.savePathEdit.text()) is not True: QMessageBox.warning(self, "Error"," Please select a correct path!") return ################################## # 多边形处理 if self.polygonModeRadioButton.isChecked(): if self.wkt_polygon: # try: sc = SimplePolygonCalculator(self.wkt_polygon, **{ "cameraWidth": cameraWidth, "cameraHeight":cameraHeight, "focusLength":focusLength, "pixelSize":pixelSize, "gsd":gsd, "flightSpeed":flightSpeed, "courseOverlap":courseOverlap, "sidewiseOverlap":sidewiseOverlap, }) sc.calculate() me = MemoryExportor() me.save(sc) self.checkToSaveFile(sc,self.savePathEdit.text(),self.fileNameEdit.text()) # except Exception as e: # QMessageBox.warning(self, "Error",str(e)) # return else: QMessageBox.warning(self, "Warning"," Please draw a polygon!") return ################################## leftExpand = int(self.leftExpandEdit.text()) rightExpand = int(self.rightExpandEdit.text()) startEndPoint = () startEndPointStr = "{}".format(self.startEndPointEdt.text()) if not self.multiLineCheckBox.isChecked(): startEndPoint = startEndPointStr.split(",") if len(startEndPoint) != 4: QMessageBox.warning(self, "Warning"," Start End Point Format Error!") return if self.multiLineCheckBox.isChecked(): lines = [] startEndLines = startEndPointStr.split(";") for linestr in startEndLines: lines.append(linestr.split(",")) print(lines) lineIndex = 0 for line in lines: lineIndex = lineIndex + 1 sc = SimpleStripCalculator(float(line[0]),float(line[1]), float(line[2]),float(line[3]), leftExpand,rightExpand, **{ "cameraWidth": cameraWidth, "cameraHeight":cameraHeight, "focusLength":focusLength, "pixelSize":pixelSize, "gsd":gsd, "flightSpeed":flightSpeed, "courseOverlap":courseOverlap, "sidewiseOverlap":sidewiseOverlap, }) sc.calculate() me = MemoryExportor() me.save(sc) self.checkToSaveFile(sc,self.savePathEdit.text(),"{}-{}".format(self.fileNameEdit.text(),lineIndex)) else: sc = SimpleStripCalculator(float(startEndPoint[0]),float(startEndPoint[1]), float(startEndPoint[2]),float(startEndPoint[3]), leftExpand,rightExpand, **{ "cameraWidth": cameraWidth, "cameraHeight":cameraHeight, "focusLength":focusLength, "pixelSize":pixelSize, "gsd":gsd, "flightSpeed":flightSpeed, "courseOverlap":courseOverlap, "sidewiseOverlap":sidewiseOverlap, }) sc.set_pogress_callback(setProgressVaue) sc.calculate() me = MemoryExportor() me.save(sc) self.checkToSaveFile(sc,self.savePathEdit.text(),self.fileNameEdit.text()) stastics_str = """ <font size="3"> <table cellspacing="0" width=100% > <thead> <tr bgcolor="#69c401" style="color:aliceblue"> <td align="center" width=30% >specification</td> <td align="center" width=50%>value</td> <td align="center">comment</td> </tr> </thead> <tr > <td style="border-bottom:1px solid #69c401">Flight Height(m)</td> <td style="border-bottom:1px solid #69c401" align="center">{:.2f}</td> <td style="border-bottom:1px solid #69c401"></td> </tr> <tr> <td style="border-bottom:1px solid #69c401">Couseline Count</td> <td style="border-bottom:1px solid #69c401" align="center">{}</td> <td style="border-bottom:1px solid #69c401"></td> </tr> <tr> <td style="border-bottom:1px solid #69c401">Point Count</td> <td style="border-bottom:1px solid #69c401" align="center">{}</td> <td style="border-bottom:1px solid #69c401"></td> </tr> <tr> <td style="border-bottom:1px solid #69c401">Distance(km)</td> <td style="border-bottom:1px solid #69c401" align="center">{:.2f}</td> <td style="border-bottom:1px solid #69c401"></td> </tr> <tr> <td style="border-bottom:1px solid #69c401">Working Time(minute)</td> <td style="border-bottom:1px solid #69c401" align="center">{:.2f}</td> <td style="border-bottom:1px solid #69c401">no turning time</td> </tr> </table> </font> """ stastics = sc.stastics() self.stasticTextEdit.setHtml(stastics_str.format( stastics["flightHeight"], stastics["couselineCount"], stastics["pointCount"], stastics["distance"], stastics["workingTime"] )) iface.messageBar().pushMessage("Info", "Compelte a automatic photogrammetry route planning.", level=Qgis.Info, duration=3) def calculateExpandPoint(self,start_long, start_lat,end_long,end_lat, courseline, sidewayline,leftExpand=0,rightExpand=0): geod = pyproj.Geod(ellps="WGS84") angle,backAngle,distanceTmp = geod.inv(start_long, start_lat,end_long,end_lat) print("courseline={}\nsidewayline={}\nleftExpand=={}\nrightExpand=={}\n".format( courseline, sidewayline,leftExpand,rightExpand)) lineStardEndPoints = [] result = [] forwardAngle = 0 totalLine = leftExpand + rightExpand + 1 currentLineIndex = 0 self.progressBar.setValue(0) long = start_long lat = start_lat for index in range(leftExpand): long,lat,tmpAngle = geod.fwd(long,lat, angle-90,sidewayline) e_long,e_lat,tempAngle = geod.fwd(long,lat, angle,distanceTmp) lineStardEndPoints.append((long,lat,e_long,e_lat)) lineStardEndPoints.append((start_long, start_lat,end_long,end_lat)) long = start_long lat = start_lat for index in range(rightExpand): long,lat,tmpAngle = geod.fwd(long,lat, angle+90,sidewayline) e_long,e_lat,tempAngle = geod.fwd(long,lat, angle,distanceTmp) lineStardEndPoints.append((long,lat,e_long,e_lat)) for line in lineStardEndPoints: lineResults,forwardAngle = caculateLine(float(line[0]),float(line[1]), float(line[2]),float(line[3]), courseline) result.append(lineResults) currentLineIndex = currentLineIndex + 1 self.progressBar.setValue(int(currentLineIndex/totalLine * 100)) return result,forwardAngle
StarcoderdataPython
4998956
# -*- coding: utf-8 -*- from collections import Counter class Solution: def hasGroupsSizeX(self, deck): counts = Counter(deck).values() min_count = min(counts) if min_count == 1: return False partition_size = min_count for count in counts: remainder = count % min_count if remainder > 1: partition_size = min(partition_size, remainder) return all(count % partition_size == 0 for count in counts) if __name__ == '__main__': solution = Solution() assert solution.hasGroupsSizeX([1, 2, 3, 4, 4, 3, 2, 1]) assert not solution.hasGroupsSizeX([1, 1, 1, 2, 2, 2, 3, 3]) assert not solution.hasGroupsSizeX([1]) assert solution.hasGroupsSizeX([1, 1]) assert solution.hasGroupsSizeX([1, 1, 2, 2, 2, 2]) assert solution.hasGroupsSizeX([1, 1, 1, 1, 2, 2, 2, 2, 2, 2])
StarcoderdataPython
19870
# Imports import socket import subprocess import os import requests # from prettytable import PrettyTable import getpass import CONFIG def send_message(text): try: requests.post('https://slack.com/api/chat.postMessage', { 'token': CONFIG.SLACK_TOKEN, 'channel': CONFIG.SLACK_CHANNEL_INFO, 'text': text, 'username': CONFIG.SLACK_BOT_NAME, }) except ConnectionError: exit("Connection Error.") def get_username(): return getpass.getuser() def get_hostname(): return socket.gethostname() def get_local_ip(): local_ip_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) local_ip_socket.connect(('10.255.255.255', 1)) local_ip_address = local_ip_socket.getsockname()[0] local_ip_socket.close() return local_ip_address def get_connected_network(): output = str(subprocess.check_output(['iwgetid'])) network= output.split('"')[1] return network def get_using_interface(): output = str(subprocess.check_output(['iwgetid'])) network = output.split(' ')[0] return network def get_device_uptime(): uptime_data = os.popen('uptime -p').read()[:-1] uptime_data = [f'{x.capitalize()} ' for x in uptime_data.split(' ')] uptime_data = ''.join(uptime_data).rstrip() return uptime_data def get_ram_usage(): total_m = os.popen('free -h').readlines()[1].split()[1] used_m= os.popen('free -h').readlines()[1].split()[2] return f'{used_m} of {total_m}' username = get_username() hostname = get_hostname() local_ip = get_local_ip() wifi = get_connected_network() interface = get_using_interface() device_uptime = get_device_uptime() ram = get_ram_usage() ssh_port = '*under_construction*' INFORMATION = '''USERNAME: "{}" HOSTNAME: "{}" LOCAL IP: "{}" CONNECTED NETWORK: "{}" USING NETWORK INTERFACE: "{}" DEVICE UPTIME: "{}" RAM USAGE: "{}" SSH PORT: "{}"'''.format(username, hostname, local_ip, wifi, interface, device_uptime, ram, ssh_port) def make_table(): # table = PrettyTable(['Hostname', 'Local IP', 'Wi-Fi', 'Interface', 'Uptime', 'RAM']) # data = ([hostname, local_ip, wifi, interface, device_uptime, ram]) # table.add_row(data) # print(table) pass send_message(INFORMATION)
StarcoderdataPython
3384887
<gh_stars>10-100 """Logging.""" import logging import platform # Logging logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) console_handler = logging.StreamHandler() file_handler = logging.FileHandler('.plonk.log') console_handler.setLevel(logging.INFO) file_handler.setLevel(logging.DEBUG) console_format = logging.Formatter('%(levelname)s - %(funcName)s - %(message)s') file_format = logging.Formatter( '%(asctime)s - %(levelname)s - %(funcName)s - %(message)s' ) console_handler.setFormatter(console_format) file_handler.setFormatter(file_format) logger.addHandler(console_handler) logger.addHandler(file_handler) def get_os_info(): """Get the operating system version for logging.""" system = platform.system() if system == 'Darwin': system = 'macOS' release = platform.release() return f'{system} version: {release}' def logger_init(__version__): """Log versions and platform.""" logger.debug(f'Plonk v{__version__} on Python {platform.python_version()}') logger.debug(f'{get_os_info()}, {platform.machine()}')
StarcoderdataPython
11386020
<filename>src/PolygonGrouper.py from __future__ import division import numpy as np from matplotlib.patches import Polygon import collections import matplotlib.pyplot as plt import matplotlib.path as path #from SpectrumImagePlotter import PatchWatcher class PolygonGroupManager(object): def __init__(self, axis): ''' Dictionary containing integer key for each polygon group used Pass polygons from Creator to the correct Group''' self.currentID = 0 self.axis = axis self.polyDict = collections.OrderedDict() self.polyDict[self.currentID] = PolygonGroup(self.axis, 'k') self.RecolourGroups() def AddPolygon(self, polygon): self.polyDict[self.currentID].AddPolygon(polygon) def NewGroup(self): self.polyDict[self.currentID].Deselect() self.currentID = max(self.polyDict.keys()) + 1 self.polyDict[self.currentID] = PolygonGroup(self.axis, 'k') self.RecolourGroups() def NextGroup(self, step=1): self.polyDict[self.currentID].Deselect() self.currentID = (self.currentID + step) % (max(self.polyDict.keys()) + 1) self.polyDict[self.currentID].SelectNext() def RecolourGroups(self): colours = plt.get_cmap('Dark2') for i, (j,g) in zip(np.linspace(0,1,len(self.polyDict.keys())), self.polyDict.items()): g.SetColour(colours(i)) def NextPolygon(self, step=1): self.polyDict[self.currentID].SelectNext(step) def GetActivePolygon(self): return self.polyDict[self.currentID].GetActivePolygon() def DeleteActivePolygon(self): self.polyDict[self.currentID].DeleteSelectedPolygon() def GetActiveMask(self, masksize): mask = self.polyDict[self.currentID].GetMask(masksize) return mask def ToggleActiveMask(self): self.polyDict[self.currentID].MaskOn = not self.polyDict[self.currentID].MaskOn return self.polyDict[self.currentID].MaskOn def ToggleGroupActive(self): if not self.polyDict[self.currentID].IsActive: self.polyDict[self.currentID].Activate() else: self.polyDict[self.currentID].Deactivate() class PolygonGroup(object): def __init__(self, axis, colour): '''A single group of polygons, containing one or more polygons to mask an area of the image''' self.colour = colour self.axis = axis self.polygonList = [] self.selected = None self.IsActive = True self.MaskOn = False def AddPolygon(self, polygon): self.polygonList.append(polygon) polygon.set_facecolor(self.colour) self.Select(len(self.polygonList)-1) def DeleteSelectedPolygon(self): self.polygonList[self.selected].remove() del self.polygonList[self.selected] if self.selected == len(self.polygonList): self.selected = 0 def SetColour(self, colour): self.colour = colour for p in self.polygonList: p.set_facecolor(colour) def Deactivate(self): self.IsActive = False for p in self.polygonList: p.set_alpha(0.05) def Activate(self): self.IsActive = True for p in self.polygonList: p.set_alpha(0.2) def Select(self, i): self.Deselect() self.selected = i self.polygonList[self.selected].set_edgecolor((1, 1, 0)) self.polygonList[self.selected].set_linewidth(3) def SelectNext(self, step=1): if not self.polygonList: return if self.selected is None: self.Select(0) else: self.Select((self.selected + step) % len(self.polygonList)) def Deselect(self): if self.selected is not None: self.polygonList[self.selected].set_linewidth(1) self.polygonList[self.selected].set_edgecolor([0, 0, 0, 0.2]) self.selected = None def GetActivePolygon(self): if self.selected is not None: return self.polygonList[self.selected] def GetMask(self, masksize): mesh = np.transpose(np.reshape(np.meshgrid(np.arange(masksize[1]), np.arange(masksize[0])), (2, masksize[0] * masksize[1]))) testp = [] for ii in self.polygonList: testp.append(np.reshape(path.Path(ii.get_xy()).contains_points(mesh), (masksize[0], masksize[1]))) mask = np.sum(testp, axis = 0).astype(bool) return mask
StarcoderdataPython
1939573
<filename>counter/migrations/0003_auto_20201205_2353.py<gh_stars>0 # Generated by Django 3.1.4 on 2020-12-05 21:53 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('counter', '0002_auto_20201205_2349'), ] operations = [ migrations.RemoveField( model_name='breakfast', name='calories', ), migrations.RemoveField( model_name='dinner', name='calories', ), migrations.RemoveField( model_name='lunch', name='calories', ), ]
StarcoderdataPython
8176775
<reponame>Nitin-Mane/Python-Deep-Learning-Projects<filename>Chapter05/3. rnn_lstm_seq2seq.py #!/usr/bin/env python2 # -*- coding: utf-8 -*- import numpy as np , os import tensorflow as tf import collections # Data Preparation def build_dataset(words, n_words): count = [['GO', 0], ['PAD', 1], ['EOS', 2], ['UNK', 3]] count.extend(collections.Counter(words).most_common(n_words - 1)) dictionary = dict() for word, _ in count: dictionary[word] = len(dictionary) data = list() unk_count = 0 for word in words: index = dictionary.get(word, 0) if index == 0: unk_count += 1 data.append(index) count[0][1] = unk_count reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys())) return data, count, dictionary, reversed_dictionary file_path = './conversation_data/' with open(file_path+'from.txt', 'r') as fopen: text_from = fopen.read().lower().split('\n') with open(file_path+'to.txt', 'r') as fopen: text_to = fopen.read().lower().split('\n') print('len from: %d, len to: %d'%(len(text_from), len(text_to))) concat_from = ' '.join(text_from).split() vocabulary_size_from = len(list(set(concat_from))) data_from, count_from, dictionary_from, rev_dictionary_from = build_dataset(concat_from, vocabulary_size_from) print('vocab from size: %d'%(vocabulary_size_from)) print('Most common words', count_from[4:10]) print('Sample data', data_from[:10], [rev_dictionary_from[i] for i in data_from[:10]]) concat_to = ' '.join(text_to).split() vocabulary_size_to = len(list(set(concat_to))) data_to, count_to, dictionary_to, rev_dictionary_to = build_dataset(concat_to, vocabulary_size_to) print('vocab to size: %d'%(vocabulary_size_to)) print('Most common words', count_to[4:10]) print('Sample data', data_to[:10], [rev_dictionary_to[i] for i in data_to[:10]]) GO = dictionary_from['GO'] PAD = dictionary_from['PAD'] EOS = dictionary_from['EOS'] UNK = dictionary_from['UNK'] #Defining seq2seq model class Chatbot: def __init__(self, size_layer, num_layers, embedded_size, from_dict_size, to_dict_size, learning_rate, batch_size): def cells(reuse=False): return tf.nn.rnn_cell.LSTMCell(size_layer,initializer=tf.orthogonal_initializer(),reuse=reuse) self.X = tf.placeholder(tf.int32, [None, None]) self.Y = tf.placeholder(tf.int32, [None, None]) self.X_seq_len = tf.placeholder(tf.int32, [None]) self.Y_seq_len = tf.placeholder(tf.int32, [None]) with tf.variable_scope("encoder_embeddings"): encoder_embeddings = tf.Variable(tf.random_uniform([from_dict_size, embedded_size], -1, 1)) encoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, self.X) main = tf.strided_slice(self.X, [0, 0], [batch_size, -1], [1, 1]) with tf.variable_scope("decoder_embeddings"): decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1) decoder_embeddings = tf.Variable(tf.random_uniform([to_dict_size, embedded_size], -1, 1)) decoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, decoder_input) with tf.variable_scope("encoder"): rnn_cells = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)]) _, last_state = tf.nn.dynamic_rnn(rnn_cells, encoder_embedded, dtype = tf.float32) with tf.variable_scope("decoder"): rnn_cells_dec = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)]) outputs, _ = tf.nn.dynamic_rnn(rnn_cells_dec, decoder_embedded, initial_state = last_state, dtype = tf.float32) with tf.variable_scope("logits"): self.logits = tf.layers.dense(outputs,to_dict_size) print(self.logits) masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32) with tf.variable_scope("cost"): self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.logits, targets = self.Y, weights = masks) with tf.variable_scope("optimizer"): self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost) #Hyperparameters size_layer = 128 num_layers = 2 embedded_size = 128 learning_rate = 0.001 batch_size = 32 epoch = 1 #Training tf.reset_default_graph() sess = tf.InteractiveSession() model = Chatbot(size_layer, num_layers, embedded_size, vocabulary_size_from + 4, vocabulary_size_to + 4, learning_rate, batch_size) sess.run(tf.global_variables_initializer()) saver = tf.train.Saver(tf.global_variables(), max_to_keep=2) checkpoint_dir = os.path.abspath(os.path.join('./', "checkpoints_chatbot")) checkpoint_prefix = os.path.join(checkpoint_dir, "model") def str_idx(corpus, dic): X = [] for i in corpus: ints = [] for k in i.split(): try: ints.append(dic[k]) except Exception as e: print(e) ints.append(2) X.append(ints) return X def pad_sentence_batch(sentence_batch, pad_int): padded_seqs = [] seq_lens = [] max_sentence_len = 50 for sentence in sentence_batch: padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence))) seq_lens.append(50) return padded_seqs, seq_lens def check_accuracy(logits, Y): acc = 0 for i in range(logits.shape[0]): internal_acc = 0 for k in range(len(Y[i])): if Y[i][k] == logits[i][k]: internal_acc += 1 acc += (internal_acc / len(Y[i])) return acc / logits.shape[0] X = str_idx(text_from, dictionary_from) Y = str_idx(text_to, dictionary_to) for i in range(epoch): total_loss, total_accuracy = 0, 0 for k in range(0, (len(text_from) // batch_size) * batch_size, batch_size): batch_x, seq_x = pad_sentence_batch(X[k: k+batch_size], PAD) batch_y, seq_y = pad_sentence_batch(Y[k: k+batch_size], PAD) predicted, loss, _ = sess.run([tf.argmax(model.logits,2), model.cost, model.optimizer], feed_dict={model.X:batch_x, model.Y:batch_y, model.X_seq_len:seq_x, model.Y_seq_len:seq_y}) total_loss += loss total_accuracy += check_accuracy(predicted,batch_y) # print 'output:', [rev_dictionary_to[i] for i in predicted[0]] # print 'input:', [rev_dictionary_to[i] for i in batch_x[0]] total_loss /= (len(text_from) // batch_size) total_accuracy /= (len(text_from) // batch_size) print('epoch: %d, avg loss: %f, avg accuracy: %f'%(i+1, total_loss, total_accuracy)) path = saver.save(sess, checkpoint_prefix, global_step=i+1) #Evaluation def predict(sentence): X_in = [] for word in sentence.split(): try: X_in.append(dictionary_from[word]) except: X_in.append(PAD) pass test, seq_x = pad_sentence_batch([X_in], PAD) input_batch = np.zeros([batch_size,seq_x[0]]) input_batch[0] =test[0] log = sess.run(tf.argmax(model.logits,2), feed_dict={ model.X:input_batch, model.X_seq_len:seq_x, model.Y_seq_len:seq_x } ) result=' '.join(rev_dictionary_to[i] for i in log[0]) return result checkpoint_file = tf.train.latest_checkpoint(os.path.join('./', 'checkpoints_chatbot')) saver = tf.train.import_meta_graph("{}.meta".format(checkpoint_file)) saver.restore(sess, checkpoint_file) print predict('how are you ?')
StarcoderdataPython
1961431
import torch import numpy as np from collections import Counter def _pairwise_distances(embeddings, squared=False): # Get the dot product between all embeddings # shape (batch_size, batch_size) dot_product = torch.matmul(embeddings, torch.transpose(embeddings, 0, 1)) # Get squared L2 norm for each embedding. We can just take the diagonal of `dot_product`. # This also provides more numerical stability (the diagonal of the result will be exactly 0). # shape (batch_size,) square_norm = torch.diag(dot_product) # Compute L2 # shape (batch_size, batch_size) distances = torch.unsqueeze(square_norm, 1) - 2.0 * dot_product + torch.unsqueeze(square_norm, 0) # Because of computation errors, some distances might be negative so we put everything >= 0.0 distances = torch.max(distances, torch.zeros_like(distances)) if not squared: mask = torch._cast_Float(torch.eq(distances, 0.0)) distances = distances + mask * 1e-16 # for sqrt(0) distances = torch.sqrt(distances) # Correct the epsilon added: set the distances on the mask to be exactly 0.0 distances = distances * (1.0 - mask) return distances.cpu() def _get_anchor_positive_triplet_mask(labels): labels = labels.cpu() # Check that i and j are distinct indices_equal = torch.eye(labels.shape[0]).type(torch.BoolTensor) indices_not_equal = torch.logical_not(indices_equal) # Check if labels[i] == labels[j] # Uses broadcasting where the 1st argument has shape (1, batch_size) and the 2nd (batch_size, 1) labels_equal = torch.eq(torch.unsqueeze(labels, 0), torch.unsqueeze(labels, 1)) # Combine the two masks mask = indices_not_equal & labels_equal return mask def _get_anchor_negative_triplet_mask(labels): # Check if labels[i] != labels[k] # Uses broadcasting where the 1st argument has shape (1, batch_size) and the 2nd (batch_size, 1) labels = labels.cpu() labels_equal = torch.eq(torch.unsqueeze(labels, 0), torch.unsqueeze(labels, 1)) mask = torch.logical_not(labels_equal) return mask def batch_hard_triplet_loss(labels, embeddings, margin=0.3, squared=False): # Get the pairwise distance matrix pairwise_dist = _pairwise_distances(embeddings, squared=squared) # For each anchor, get the hardest positive # First, we need to get a mask for every valid positive (they should have same label) mask_anchor_positive = _get_anchor_positive_triplet_mask(labels) mask_anchor_positive = torch._cast_Float(mask_anchor_positive) # We put to 0 any element where (a, p) is not valid (valid if a != p and label(a) == label(p)) anchor_positive_dist = torch.mul(mask_anchor_positive, pairwise_dist) # shape (batch_size, 1) hardest_positive_dist, _ = torch.max(anchor_positive_dist, dim=1, keepdim=True) # torch.summary.scalar("hardest_positive_dist", torch.mean(hardest_positive_dist)) # For each anchor, get the hardest negative # First, we need to get a mask for every valid negative (they should have different labels) mask_anchor_negative = _get_anchor_negative_triplet_mask(labels) mask_anchor_negative = torch._cast_Float(mask_anchor_negative) # We add the maximum value in each row to the invalid negatives (label(a) == label(n)) max_anchor_negative_dist, _ = torch.max(pairwise_dist, dim=1, keepdim=True) anchor_negative_dist = pairwise_dist + max_anchor_negative_dist * ( torch.ones_like(mask_anchor_negative) - mask_anchor_negative) # shape (batch_size,) hardest_negative_dist, _ = torch.min(anchor_negative_dist, dim=1, keepdim=True) # Combine biggest d(a, p) and smallest d(a, n) into final triplet loss triplet_loss = torch.max(hardest_positive_dist - hardest_negative_dist + margin, torch.zeros_like(hardest_positive_dist)) # Get final mean triplet loss triplet_loss = torch.mean(triplet_loss) return triplet_loss def _get_triplet_mask(labels): labels = labels.cpu() # Check that i, j and k are distinct indices_equal = torch.eye(labels.shape[0]).type(torch.BoolTensor) indices_not_equal = torch.logical_not(indices_equal) i_not_equal_j = torch.unsqueeze(indices_not_equal, 2) i_not_equal_k = torch.unsqueeze(indices_not_equal, 1) j_not_equal_k = torch.unsqueeze(indices_not_equal, 0) distinct_indices = (i_not_equal_j & i_not_equal_k) & j_not_equal_k # Check if labels[i] == labels[j] and labels[i] != labels[k] label_equal = torch.eq(torch.unsqueeze(labels, 0), torch.unsqueeze(labels, 1)) i_equal_j = torch.unsqueeze(label_equal, 2) i_equal_k = torch.unsqueeze(label_equal, 1) valid_labels = i_equal_j & torch.logical_not(i_equal_k) # Combine the two masks mask = distinct_indices & valid_labels return mask def accuracy(labels, embeddings, squared=False, T=np.array([0.55, 0.6, 0.7, 0.8, 0.9])): labels = labels.cpu() pairwise_dist = _pairwise_distances(embeddings, squared=squared) mask = np.array(_get_triplet_mask(labels)) x, y, z = np.where(mask == True) n_triplets = len(x) if not n_triplets: return np.zeros_like(T) true = np.zeros_like(T) for i in range(len(x)): x_i, y_i, z_i = x[i], y[i], z[i] anchor_pos_dist = pairwise_dist[x_i, y_i] anchor_neg_dist = pairwise_dist[x_i, z_i] if anchor_pos_dist < anchor_neg_dist: true += anchor_pos_dist.item() < T return true / n_triplets def batch_hard_quadriplet_loss(class_labels, scene_labels, embeddings, margin_class=0.3, margin_scene=0.05, beta=0.4, squared=False): ''' Computes quadriplet loss: triplet_loss_class + beta*triplet_loss_scene :param class_labels: :param scene_labels: :param embeddings: :param margin_class: :param margin_scene: :param beta: :return: ''' loss = batch_hard_triplet_loss(class_labels, embeddings, margin=margin_class) if len(np.unique(scene_labels)) != len(scene_labels): loss += beta * batch_hard_triplet_loss(scene_labels, embeddings, margin=margin_scene) return loss
StarcoderdataPython
3309272
<gh_stars>1-10 # Part of web_progress. See LICENSE file for full copyright and licensing details. from odoo import models, api, registry, fields, _ import uuid class IrCron(models.Model): _inherit = 'ir.cron' @api.model def _callback(self, cron_name, server_action_id, job_id): """ Add web progress code if it does not exist. This allows to report progress of cron-executed jobs """ new_self = 'progress_code' in self._context and self or self.with_context(progress_code=str(uuid.uuid4())) return super(IrCron, new_self)._callback(cron_name, server_action_id, job_id)
StarcoderdataPython
5030519
#!/usr/bin/env python3 #******************************************************************************* #* reducer.py #* #* Copyright (C) 2018 <NAME> <<EMAIL>> #* #* All rights reserved. Published under the BSD-2 license in the LICENSE file. #******************************************************************************/ import argparse import subprocess import copy import random parser = argparse.ArgumentParser() parser.add_argument('filename') parser.add_argument('cmd', nargs=argparse.REMAINDER) args = parser.parse_args() RF = "REDUCEFILE" LRF = "LAST_REDUCEFILE" def read_binary(path): with open(path, 'rb') as file: inp = file.read() return inp def write_binary(path, data): with open(path, 'wb') as file: file.write(data) file.flush() test = read_binary(path) assert test == data def run(cmd, current): print(cmd) print("Input size: {}".format(len(current))) write_binary(RF, current) print("------------------------------------") res = subprocess.run(cmd) print("------------------------------------") if res.returncode != 0: return True else: return False inp = read_binary(args.filename) write_binary(RF, inp) cmd = list(args.cmd) prev = copy.deepcopy(inp) current = copy.deepcopy(inp) while True: print("====================================") if run(cmd, current): # reduce further prev = copy.deepcopy(current) write_binary(LRF, prev) ri = random.randrange(0, len(current)) rl = random.randrange(0, (int(len(current) / 10)) + 1) + 1 left = current[:ri] right = current[(ri+rl):] current = left + right else: print("Did not fail, try something different") if prev == current: print("Got stuck") exit(1) current = copy.deepcopy(prev)
StarcoderdataPython
264560
from functools import wraps from flask import abort, request def validate_json(f): """ Checks if a requests content-type is "application/json" """ @wraps(f) def decorated_function(*args, **kwargs): if request.is_json: return f(*args, **kwargs) else: return abort(400) return decorated_function
StarcoderdataPython
6640373
# # Copyright Logimic,s.r.o., www.logimic.com # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import asyncio import websockets import json import time # This is IQRFBB-10 node address in IQRF network boardAddr = 1 # JSON messages by "https://docs.iqrfsdk.org/iqrf-gateway-daemon/api.html" GET_PERIPHERIAL = { "mType": "iqrfRawHdp", "data": { "msgId": "testRawHdp", "req": { "nAdr": boardAddr, "pNum": 0x20, "pCmd": 0 }, "returnVerbose": True } } async def hello(): # Connect websockets async with websockets.connect('ws://localhost:1338') as websocket: count = 0 while (count < 50): print(f"The count is:{count}") count = count + 1 # Read all pins await websocket.send(json.dumps(GET_PERIPHERIAL)) #print(f"Sent > {GET_PERIPHERIAL}") response = await websocket.recv() #print(f"Received < {response}") data = json.loads(response) tempH = data["data"]["rsp"]["pData"][0] tempL = data["data"]["rsp"]["pData"][1] temp = (tempH << 8 | tempL) & 0xFFFC dtemp = temp / 65536.0 dtepm = -46.85 + (175.72 * dtemp) humH = data["data"]["rsp"]["pData"][3] humL = data["data"]["rsp"]["pData"][4] hum = (tempH << 8 | tempL) & 0xFFFC dhum = hum / 65536.0 dhum = -6.0 + (125.0 * dhum) print(f"Temperature = {dtepm:3.3f} Humidity = {dhum:3.3f}") print("DONE....") asyncio.get_event_loop().run_until_complete(hello())
StarcoderdataPython
4973863
<reponame>andreymal/certbot-dns-sweb #!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import time import random import logging import zope.interface from certbot import errors, interfaces from certbot.plugins import dns_common from .sweb_client import SWebClient from .sweb_api import SWebAPI try: from typing import Any, Optional, List except ImportError: from acme.magic_typing import Any, Optional, List # type: ignore logger = logging.getLogger(__name__) @zope.interface.implementer(interfaces.IAuthenticator) @zope.interface.provider(interfaces.IPluginFactory) class Authenticator(dns_common.DNSAuthenticator): """DNS Authenticator for SpaceWeb""" description = ( "Obtain certificates using a DNS TXT record (if you are using SpaceWeb for DNS)." ) def __init__(self, *args, **kwargs): # type: (Any, Any) -> None super(Authenticator, self).__init__(*args, **kwargs) self.credentials = None # type: Any self._client = None # type: Optional[SWebAPI] self._my_tokens = [] # type: List[str] @classmethod def add_parser_arguments(cls, add): # pylint: disable=arguments-differ # type: (Any) -> None super(Authenticator, cls).add_parser_arguments(add, default_propagation_seconds=1200) add("credentials", help="SpaceWeb credentials INI file.") def more_info(self): # type: () -> str return ( "This plugin configures a DNS TXT record to respond to a dns-01 challenge " "using the SpaceWeb unofficial API." ) def _setup_credentials(self): # type: () -> None self.credentials = self._configure_credentials( "credentials", "SpaceWeb credentials INI file", required_variables={ "username": "SpaceWeb username", "password": "<PASSWORD>", }, ) @classmethod def _get_subdomain(cls, domain, validation_name): # type: (str, str) -> str # ("example.com", "_acme-challenge.example.com") -> "_acme-challenge" if validation_name == domain or validation_name.endswith("." + domain): return validation_name[:-(len(domain) + 1)] or "@" return validation_name def _i_am_human(self, tm=5.0, rnd=1.15): # type: (float, float) -> None t = tm n = int(rnd * 100) if n: t += random.randrange(-n, n + 1) / 100.0 # https://www.youtube.com/watch?v=fsF7enQY8uI time.sleep(t) def _drop_old_txt(self, domain, validation_name): # type: (str, str) -> int subdomain = self._get_subdomain(domain, validation_name) removed_count = 0 while True: self._i_am_human() old_txt = self._get_client().domains_dns_info_find( domain=domain, subdomain=subdomain, type="TXT", ) old_txt = [x for x in old_txt if x["value"] not in self._my_tokens] if not old_txt: break x = old_txt[-1] logger.info( "Removing outdated TXT record for %s (%d left)", validation_name, len(old_txt), ) self._i_am_human() self._get_client().domains_dns_edit_txt( domain=domain, action="del", subdomain=subdomain, index=x["index"], ) removed_count += 1 logger.info("Removed %d old TXT records", removed_count) return removed_count def _perform(self, domain, validation_name, validation): # type: (str, str, str) -> None self._my_tokens.append(validation) if self.credentials.conf("drop_old_txt") == "1": self._drop_old_txt(domain, validation_name) logger.info("Adding TXT record for %s", validation_name) self._i_am_human() self._get_client().domains_dns_edit_txt( domain=domain, action="add", subdomain=self._get_subdomain(domain, validation_name), value=validation, ) def _cleanup(self, domain, validation_name, validation): # type: (str, str, str) -> None subdomain = self._get_subdomain(domain, validation_name) self._i_am_human() for x in self._get_client().domains_dns_info_find( domain=domain, subdomain=subdomain, type="TXT", ): if x["value"] == validation: logger.info("Removing TXT record for %s", validation_name) self._i_am_human() self._get_client().domains_dns_edit_txt( domain=domain, action="del", subdomain=subdomain, index=x["index"], ) break def _get_client(self): # type: () -> SWebAPI if self._client is not None: return self._client assert self.credentials is not None logger.info("Authenticate on SpaceWeb...") c = SWebClient( username=self.credentials.conf("username"), password=<PASSWORD>.conf("password"), user_agent=self.credentials.conf("user_agent"), ) logger.info("Successfully authenticated; api version %s", c.jsonrpc_api_version) self._client = SWebAPI(c) return self._client
StarcoderdataPython
3593331
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2021, <NAME> (@anvitha-jain) <<EMAIL>> # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = r''' --- module: aci_cloud_external_epg_selector short_description: Manage Cloud Endpoint Selector for External EPGs (cloud:ExtEPSelector) description: - Decides which endpoints belong to the EPGs based on several parameters. options: name: description: - The name of the Cloud Endpoint selector. aliases: [ selector, cloud_external_epg_selector, external_epg_selector, extepg_selector, selector_name ] type: str subnet: description: - IP address of the Cloud Subnet. aliases: [ ip ] type: str tenant: description: - The name of tenant. type: str ap: description: - The name of the cloud application profile. aliases: [ app_profile, app_profile_name ] type: str cloud_external_epg: description: - Name of Object cloud_external_epg. type: str state: description: - Use C(present) or C(absent) for adding or removing. - Use C(query) for listing an object or multiple objects. choices: [ absent, present, query ] default: present type: str extends_documentation_fragment: - cisco.aci.aci notes: - More information about the internal APIC class B(cloud:ExtEPSelector) from L(the APIC Management Information Model reference,https://developer.cisco.com/docs/apic-mim-ref/). author: - <NAME> (@anvitha-jain) ''' EXAMPLES = r''' - name: Add a new cloud external EPG selector cisco.aci.aci_cloud_external_epg_selector: host: apic username: admin password: <PASSWORD> tenant: tenant1 ap: ap1 cloud_external_epg: ext_epg name: subnet_name subnet: 10.0.0.0/16 state: present delegate_to: localhost - name: Remove a cloud external EPG selector cisco.aci.aci_cloud_external_epg_selector: host: apic username: admin password: <PASSWORD> validate_certs: no tenant: tenant1 ap: ap1 cloud_external_epg: ext_epg name: subnet_name subnet: 10.0.0.0/16 state: absent delegate_to: localhost - name: Query all cloud external EPG selectors cisco.aci.aci_cloud_external_epg_selector: host: apic username: admin password: <PASSWORD> tenant: tenant1 ap: ap1 cloud_external_epg: ext_epg state: query delegate_to: localhost ''' from ansible_collections.cisco.aci.plugins.module_utils.aci import ACIModule, aci_argument_spec from ansible.module_utils.basic import AnsibleModule def main(): argument_spec = aci_argument_spec() argument_spec.update({ 'name': dict(type='str', aliases=['selector', 'cloud_external_epg_selector', 'external_epg_selector', 'extepg_selector', 'selector_name']), 'subnet': dict(type='str', aliases=['ip']), 'tenant': dict(type='str'), 'cloud_external_epg': dict(type='str'), 'ap': dict(type='str', aliases=['app_profile', 'app_profile_name']), 'state': dict(type='str', default='present', choices=['absent', 'present', 'query']), }) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, required_if=[ ['state', 'absent', ['subnet', 'tenant', 'ap', 'cloud_external_epg']], ['state', 'present', ['subnet', 'tenant', 'ap', 'cloud_external_epg']], ], ) name = module.params.get('name') subnet = module.params.get('subnet') tenant = module.params.get('tenant') ap = module.params.get('ap') cloud_external_epg = module.params.get('cloud_external_epg') state = module.params.get('state') child_configs = [] aci = ACIModule(module) aci.construct_url( root_class={ 'aci_class': 'fvTenant', 'aci_rn': 'tn-{0}'.format(tenant), 'target_filter': 'eq(fvTenant.name, "{0}")'.format(tenant), 'module_object': tenant }, subclass_1={ 'aci_class': 'cloudApp', 'aci_rn': 'cloudapp-{0}'.format(ap), 'target_filter': 'eq(cloudApp.name, "{0}")'.format(ap), 'module_object': ap }, subclass_2={ 'aci_class': 'cloudExtEPg', 'aci_rn': 'cloudextepg-{0}'.format(cloud_external_epg), 'target_filter': 'eq(cloudExtEPg.name, "{0}")'.format(cloud_external_epg), 'module_object': cloud_external_epg }, subclass_3={ 'aci_class': 'cloudExtEPSelector', 'aci_rn': 'extepselector-[{0}]'.format(subnet), 'target_filter': 'eq(cloudExtEPSelector.name, "{0}")'.format(subnet), 'module_object': subnet }, child_classes=[] ) aci.get_existing() if state == 'present': aci.payload( aci_class='cloudExtEPSelector', class_config={ 'name': name, 'subnet': subnet, }, child_configs=child_configs ) aci.get_diff(aci_class='cloudExtEPSelector') aci.post_config() elif state == 'absent': aci.delete_config() aci.exit_json() if __name__ == "__main__": main()
StarcoderdataPython
6614944
#!/usr/bin/env python # -*- coding: utf-8 -*- import pandas as pd import numpy as np import matplotlib.pyplot as plt from datetime import datetime, date sample_size = 500 sigma_e = 3.0 # true value of parameter error sigma random_num_generator = np.random.RandomState(0) x = 10.0 * random_num_generator.rand(sample_size) e = random_num_generator.normal(0, sigma_e, sample_size) y = 1.0 + 2.0 * x + e # a = 1.0; b = 2.0; y = a + b*x plt.scatter(x, y, color='blue') # normal equation to estimate the model parameters X = np.vstack((np.ones(sample_size), x)).T params_closed_form = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(y) print('pamameters: %.7f, %.7f' %(params_closed_form[0], params_closed_form[1])) from sklearn.linear_model import LinearRegression # The next two lines does the regression lm_model = LinearRegression(copy_X=True, fit_intercept=True, normalize=False) lm_model.fit(x.reshape(-1,1), y) # fit() expects 2D array print('pamameters: %.7f, %.7f' %(lm_model.intercept_, lm_model.coef_)) # present the graph xfit = np.linspace(0, 10, sample_size) yfit = lm_model.predict(xfit.reshape(-1,1)) ytrue = 2.0 * xfit + 1.0 # we know the true value of slope and intercept plt.scatter(x, y, color='blue') plt.plot(xfit, yfit, color='red', label='fitted line', linewidth=3) plt.plot(xfit, ytrue, color='green', label='true line', linewidth=3) plt.legend() # R-Square r_square = lm_model.score(x.reshape(-1,1), y) print('R-Square %.7f' %(r_square)) from scipy.stats.stats import pearsonr # The square root of R-Square is correlation coefficient print('Its square root is Pearson correlation coefficient: %.7f == %.7f' %(np.sqrt(r_square), pearsonr(x, y)[0]))
StarcoderdataPython
1725218
<gh_stars>10-100 class User(): def __init__(self,first_name,last_name,username,email,number,age): self.first_name = first_name self.last_name = last_name self.username = username self.email = email self.number = number self.age = age def describe_user(self): print(" NAME: ", self.first_name) print(" LAST NAME: ", self.last_name) print(" USERNAME: ", self.username) print(" EMAIL: ", self.email) print(" NUMBER: ", self.number) print(" AGE: ", self.age) print("") def greet_user(self): print("Welcome ", self.username) user1 = User("Anahi", "<NAME>", "Elvanana", "<EMAIL>", "8441234567", "16") user1.greet_user() user1.describe_user() user2 = User("Jesus", "<NAME>", "Jisus", "<EMAIL>", "8447894561", "22") user2.greet_user() user2.describe_user() user3 = User("Josh", "Peck", "JoshPeck", "<EMAIL>", "8424569312", "34") user3.greet_user() user3.describe_user() user4 = User("Drake", "Bell", "DrakeBell", "DrakeBell", "8449631483", "35") user4.greet_user() user4.describe_user()
StarcoderdataPython
139031
<reponame>NOAO/astroquery """ CSIRO ASKAP Science Data Archive (CASDA) """ from astropy import config as _config class Conf(_config.ConfigNamespace): """ Configuration parameters for `astroquery.casda`. """ server = _config.ConfigItem( ['https://casda.csiro.au/casda_vo_tools/sia2/query'], 'Name of the CASDA SIA server to use.' ) timeout = _config.ConfigItem( 30, 'Time limit for connecting to CASDA server.' ) conf = Conf() from .core import Casda, CasdaClass __all__ = ['Casda', 'CasdaClass', 'conf']
StarcoderdataPython
43901
""" sphinx_c_autodoc is a package which provide c source file parsing for sphinx. It is composed of multiple directives and settings: .. rst:directive:: .. c:module:: filename A directive to document a c file. This is similar to :rst:dir:`py:module` except it's for the C domain. This can be used for both c source files as well as c header files. """ import json import os import re from dataclasses import dataclass, field from itertools import groupby from typing import Any, List, Optional, Tuple, Dict from docutils.statemachine import ViewList, StringList from docutils import nodes from sphinx.domains.c import CObject from sphinx.application import Sphinx from sphinx.util import logging from sphinx.util.docstrings import prepare_docstring from sphinx.ext.autodoc import ( Documenter, members_option, bool_option, member_order_option, ) from sphinx.ext.autodoc.directive import DocumenterBridge from sphinx_c_autodoc import loader from sphinx_c_autodoc.domains.c import patch_c_domain # TODO not real fond of this being here in the main c autodoc file, need to # find a way to make it easier to cache the documented files. @dataclass class ViewCodeListing: """ A data structure used for constructing a viewcode source listing. Attributes: raw_listing: The plain text representation of the code. This should be basically the output of file.read(). ast (Dict): A dictionary like representation of the code constructs. See :ref:`developer_notes:Common Terms`. doc_links (Dict): To be used by the consumers, i.e. viewcode. """ raw_listing: str ast: Dict doc_links: Dict = field(default_factory=dict) logger = logging.getLogger(__name__) class CObjectDocumenter(Documenter): # pylint: disable=line-too-long """ A C object autodocument class to work with `autodoc <https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html#module-sphinx.ext.autodoc>`_ extension for sphinx. """ # pylint: enable=line-too-long domain = "c" # Filler type, this base class isn't used directly directivetype = "object" # must be higher than the AttributeDocumenter, else it will steal the c # objects priority = 11 option_spec = { "members": members_option, "noindex": bool_option, "private-members": bool_option, "member-order": member_order_option, "undoc-members": bool_option, } @classmethod def can_document_member( cls, member: Any, membername: str, isattr: bool, parent: Any ) -> bool: """ Parameters: member (object): The member item to document. This type is specific to the item being processed by autodoc. These classes will only attempt to process :class:`sphinx_c_autodoc.loader.CObjectDocumenter` members. membername (str): The name of the item to document. For example if this is a function then this will be the name of the function, no return types, no arguments. isattr (bool): Is the member an attribute. This is unused for c documenation. parent (object): The parent item of this `member`. Returns: bool: True if this class can document the `member`. """ return ( isinstance(parent, CObjectDocumenter) and member.type == cls.directivetype ) def parse_name(self) -> bool: """Determine what module to import and what attribute to document. .. note:: Sphinx autodoc supports args and return anotation, since this is targeting C and it isn't currently needed, these won't be supported by this implementation. Returns: bool: True if successfully parsed and sets :attr:`modname`, :attr:`objpath`, :attr:`fullname`. False if the signature couldn't be parsed. """ c_autodoc_re = re.compile(r"^([\w\/\\.]+)(::([\w.]+\.)?(\w+))?\s*$") try: match = c_autodoc_re.match(self.name) fullname, _, path, base = match.groups() # type: ignore except AttributeError: logger.warning( "invalid signature for auto%s (%r)" % (self.objtype, self.name), type="c_autodoc", ) return False parents: List[str] if path is None: parents = [] else: parents = path.rstrip(".").split(".") self.modname, self.objpath = self.resolve_name(fullname, parents, path, base) self.fullname = self.modname return True def resolve_name( self, modname: str, parents: List[str], path: Optional[str], base: str ) -> Tuple[str, List[str]]: """ Resolve the module and object name of the object to document. This can be derived in two ways: - Naked: Where the argument is only the file/module name `my_file.c` - Double colons: Where the argument to the directive is of the form `my_file.c::some_func`. Args: modname (str): The filename of the c file (module) parents (list): The list split('.') version of path. - The filename without the extension when naked argument is used. - Any parents when double colon argument is used. For example structs or unions of `my_struct.field_name` would have a parents entry of ['my_struct'] path (str): Two possible states: - None if `parents` is the empty list. - The ``'.'.join()`` version of `parents`, with a trailing ``.``. base (str): The name of the object to document. This will be None when the object to document is the c module Returns: tuple: (str, [str]) The module name, and the object names (if any). """ if base: return modname, parents + [base] return modname, [] def import_object(self, raiseerror: bool = False) -> bool: """Load the C file and build up the document structure. This will load the C file's documented structure into :attr:`object` Args: raiseerror (bool): Raise error, this is ignored for the c implementation as import errors don't happen. Returns: bool: True if the file was imported, false otherwise. """ for source_dir in self.env.config.c_autodoc_roots: filename = os.path.join(source_dir, self.get_real_modname()) # Prefixing with "/" will force "absolute" path which is relative # to the source directory. rel_filename, filename = self.env.relfn2path(f"/{filename}") if os.path.isfile(filename): break else: logger.warning( "Unable to find file, %s, in any of the directories %s " "all directories are relative to the top documentation source directory" % (self.get_real_modname(), self.env.config.c_autodoc_roots), location=(self.env.docname, self.directive.lineno), ) return False self.env.note_dependency(rel_filename) source_dict = getattr(self.env, "_viewcode_c_modules", {}) self.env._viewcode_c_modules = source_dict # type: ignore # TODO The :attr:`temp_data` is reset for each document ideally want to # use or make an attribute on `self.env` that is reset per run or just # not pickled. modules_dict = self.env.temp_data.setdefault("c:loaded_modules", {}) if filename not in modules_dict: with open(filename) as f: contents = [f.read()] # let extensions preprocess files self.env.app.emit("c-autodoc-pre-process", filename, contents) compilation_db = self.get_compilation_database() compilation_args = self.env.config.c_autodoc_compilation_args modules_dict[filename] = loader.load( filename, contents[0], compilation_db, compilation_args ) ast = json.loads(str(modules_dict[filename])) source_dict.setdefault( self.get_real_modname(), ViewCodeListing(contents[0], ast) ) self.module = modules_dict[filename] self.object = self.module self.object_name = self.name # objpath is set when double colons are used in :meth:`resolve_name`. # i.e. this is a node or sub-node in a module. if self.objpath: for obj in self.objpath: self.object_name = obj self.object = self.object.children[self.object_name] # type: ignore return True def get_compilation_database(self) -> Optional[str]: """ Get's the compilation database from the environment `c_autodoc_compilation_database` Returns: str: The full path to the compilation database to use. None if there is no compilation database. """ database = self.env.config.c_autodoc_compilation_database if not database: return None # Prefixing with "/" will force "absolute" path which is relative # to the source directory. _, filename = self.env.relfn2path(f"/{database}") if os.path.isfile(filename): return filename logger.warning( 'Compilation database "%s" not found.' % (filename,), location=(self.env.docname, self.directive.lineno), ) return None def get_doc(self, ignore: int = None) -> Optional[List[List[str]]]: """Decode and return lines of the docstring(s) for the object.""" docstring = self.object.get_doc() tab_width = self.directive.state.document.settings.tab_width return [prepare_docstring(docstring, ignore, tab_width)] def get_object_members(self, want_all: bool) -> Tuple[bool, List[Tuple[str, Any]]]: """Return `(members_check_module, members)` where `members` is a list of `(membername, member)` pairs of the members of *self.object*. If *want_all* is True, return all members. Else, only return those members given by *self.options.members* (which may also be none). """ if want_all: return False, list(self.object.children.items()) # The caller sets `want_all` if :attr:`options.members` is ALL, so it # should be safe to assume this is a list or None at this point. desired_members = self.options.members or [] object_members: List[Tuple[str, Any]] = [] for member in desired_members: if member in self.object.children: object_members.append((member, self.object.children[member])) else: logger.warning( 'Missing member "%s" in object "%s"' % (member, self.fullname), type="c_autodoc", ) return False, object_members def filter_members( # type: ignore[override] self, members: List[Tuple[str, Any]], want_all: bool ) -> List[Tuple[str, Any, bool]]: """Filter the given member list. :meth:`filter_members` is called *after* :meth:`get_object_members`, this means if `want_all` is False then only private members which were explicitly requested will be in this list. Only when `want_all` is True do we need to actually condition on private member. Members are skipped if - they are private (except if given explicitly or the private-members option is set) - they are undocumented (except if the undoc-members option is set) TODO not implemented yet. The user can override the skipping decision by connecting to the ``autodoc-skip-member`` event. """ ret = [] isattr = False for (membername, member) in members: if not want_all: ret.append((membername, member, isattr)) elif member.doc or self.options.undoc_members: if member.is_public() or self.options.private_members: ret.append((membername, member, isattr)) return ret def format_name(self) -> str: """Format the name of *self.object*. This normally should be something that can be parsed by the generated directive, but doesn't need to be (Sphinx will display it unparsed then). For things like functions and others this will include the return type. """ return self.object.format_name() def format_args(self, **kwargs: Any) -> str: """ Creates the parenthesis version of the function signature. i.e. this will be the `(int hello, int what)` portion of the header. """ return self.object.format_args(**kwargs) class CModuleDocumenter(CObjectDocumenter): """ This auto documenter will be registered as a directive named `autocmodule`, there may be a way to override the python `automodule`, just not sure yet... """ objtype = "cmodule" directivetype = "module" @classmethod def can_document_member( cls, member: Any, membername: str, isattr: bool, parent: Any ) -> bool: """ Modules are top levels so should never be included as a child of another c object. Parameters: member (object): The member item to document. This type is specific to the item being processed by autodoc. These instances will only attempt to process :class:`sphinx_c_autodoc.loader.CObjectDocumenter`. membername (str): The name of the item to document. For example if this is a function then this will be the name of the function, no return types, no arguments. isattr (bool): Is the member an attribute. This is unused for c documenation. parent (object): The parent item of this `member`. Returns: bool: True if this class can document the `member`. """ return False class CTypeDocumenter(CObjectDocumenter): """ The documenter for the autoctype directive. """ objtype = "ctype" directivetype = "type" def __init__( self, directive: DocumenterBridge, name: str, indent: str = "" ) -> None: """ Override the :attr:`directive` so that some post processing can be performed in :meth:`generate` """ super().__init__(directive, name, indent) self._original_directive = self.directive self.directive = DocumenterBridge( self.directive.env, self.directive.reporter, self.directive.genopt, self.directive.lineno, self.directive.state, ) def generate( self, more_content: Optional[StringList] = None, real_modname: Optional[str] = None, check_module: bool = False, all_members: bool = False, ) -> None: """ generate stuff """ super().generate( more_content=more_content, real_modname=real_modname, check_module=check_module, all_members=all_members, ) self._original_directive.result.append(self.consolidate_members()) def _find_member_directives(self, name: str) -> List[Tuple[str, str, int]]: """ Find all directive lines which start with `` ..c:<name>::``. Creates a sequence of: - The short name of the item documented by the directive. - The full signature of the item documented. - The line number in :attr:`directive.results`. For instnace a directive of ``..c:some_directive word1 word2 word3`` would result in ``word3`` being the short name and ``word1 word2 word3`` being the full signature. Args: name (str): The name of the directive(s) to search for. Returns: list(tuple(str, str, int)): The short name, the full signature, and the line in :attr:`directive.results` where the directive occured. """ members = [] directive_string = f".. c:{name}::" for line_no, line in enumerate(self.directive.result): if not line.startswith(self.indent): continue if line.lstrip().startswith(directive_string): _, signature = line.split(directive_string) # members may document array types so break on the brace # `int member_name [some_size][maybe_2nd_dimension]` type_and_name, *(_) = signature.strip().partition("[") sig_parts = type_and_name.strip().split() members.append((sig_parts[-1], signature, line_no)) return members def _remove_directive(self, line: int) -> StringList: """ Remove the directive which starts at `line_no` from :attr:`directive.results`. The locations in :attr:`directive.results` will be replaced with empty lines so that the total line count of :attr:`directive.results` is unaffected. Args: line (int): The starting line to remove the directive from. Returns: :class:`StringList`: The removed directive which started at `line_no` """ # Just need to do at least one more indentation than the actual # directive to not end up grabbing the next directive. directive_line = self.directive.result[line] block_indent = (len(directive_line) - len(directive_line.lstrip())) + 1 directive, _, _ = self.directive.result.get_indented( line, first_indent=0, block_indent=block_indent, strip_indent=False ) directive.disconnect() # Setting slices need viewlists/stringlists so just iterate through and # set indices which can take strings directive_length = len(directive) for line_no in range(line, line + directive_length): self.directive.result[line_no] = self.indent return directive @staticmethod def _merge_directives(directives: List[StringList]) -> StringList: """ The last directive heading will be used to represent the heading for the entire group of directives. Args: directives (list(StringList)): The list of directives to merge. Returns: StringList: One directive """ merged_heading = StringList() merged_directive = StringList() merged_options = StringList() for directive in directives: options, _, _ = directive.get_indented( 1, until_blank=True, strip_indent=False ) if options: merged_options.extend(options) del directive[1 : 1 + len(options)] directive_heading = directive[0] del directive[0] merged_directive.extend(directive) merged_heading = directive_heading merged_directive.insert(0, merged_options) merged_directive.insert(0, merged_heading, source=merged_directive.source(0)) return merged_directive def consolidate_members(self) -> StringList: """ Take any duplicate autodoc member directives and consolidate them into one directive. The subsequent contents of duplicate directives will be added as additional paragraphs on the first occurrence of the directive. Returns: StringList: The entire rst contents for this directive instance. """ # Grab any constructs that could be declared inside of a struct, union or enum. members = [] for sub_type in ("member", "struct", "union", "enumerator"): members += self._find_member_directives(sub_type) # Group all the items by their name. This sort logic here leverages the order # preservation that python sort has, in that napoleon documented constructs are # always "member" however the actual c constructs will come after as "struct" # or similar. members.sort(key=lambda m: m[0]) data_blocks = [] for _, member_group in groupby(members, lambda m: m[0]): start_line = len(self.directive.result) directives = [] for _, _, line in member_group: directives.append(self._remove_directive(line)) if line < start_line: start_line = line original_length = len(directives[-1]) merged_directive = self._merge_directives(directives) data_blocks.append((start_line, original_length, merged_directive)) data_blocks.sort() delta_length = 0 for line, original_length, directive in data_blocks: start = line + delta_length end = start + original_length self.directive.result[start:end] = directive delta_length += len(directive) - original_length return self.directive.result def format_name(self) -> str: """Format the name of *self.object*. Sphinx doesn't like the typedef keyword being in typedef signatures so strip them off here. """ raw_name = self.object.format_name() cleaned_name = raw_name.replace("typedef ", "") return cleaned_name class CStructDocumenter(CTypeDocumenter): """ The documenter for the autocstruct directive. """ objtype = "cstruct" directivetype = "struct" def filter_members( # type: ignore[override] self, members: List[Tuple[str, Any]], want_all: bool ) -> List[Tuple[str, Any, bool]]: """Filter the given member list. For structures if they are documented then all members provided are documented. """ ret = [] isattr = False for (membername, member) in members: ret.append((membername, member, isattr)) return ret class CEnumDocumenter(CTypeDocumenter): """ The documenter for the autocenum directive. """ objtype = "cenum" directivetype = "enum" class CUnionDocumenter(CStructDocumenter): """ The documenter for the autocunion directive. """ objtype = "cunion" directivetype = "union" class CMemberDocumenter(CObjectDocumenter): """ The documenter for the autocmember directive. This handles structure and union fields. """ objtype = "cmember" directivetype = "member" class CFunctionDocumenter(CObjectDocumenter): """ The documenter for the autocfunction directive. """ objtype = "cfunction" directivetype = "function" class CMacroDocumenter(CObjectDocumenter): """ The documenter for the autocmacro directive. """ objtype = "cmacro" directivetype = "macro" class CEnumeratorDocumenter(CObjectDocumenter): """ The documenter for the autocenumerator directive. These are enumerator constants, versus the enum (type). """ objtype = "cenumerator" directivetype = "enumerator" class CDataDocumenter(CObjectDocumenter): """ The documenter for the autocdata directive. """ objtype = "cdata" directivetype = "var" @classmethod def can_document_member( cls, member: Any, membername: str, isattr: bool, parent: Any ) -> bool: """ Parameters: member (object): The member item to document. This type is specific to the item being processed by autodoc. These classes will only attempt to process :class:`sphinx_c_autodoc.loader.CObjectDocumenter` members. membername (str): The name of the item to document. For example if this is a function then this will be the name of the function, no return types, no arguments. isattr (bool): Is the member an attribute. This is unused for c documenation. parent (object): The parent item of this `member`. Returns: bool: True if this class can document the `member`. """ # Handle the mapping of c land `variable` to sphinx land `data`. The c # domain in sphinx seems inconsistent the directive is called # ``.. c:var::``, yet the role is ``:c:data:``. return isinstance(parent, CObjectDocumenter) and member.type == "variable" class CModule(CObject): """ Module directive for C files """ has_content = True required_arguments = 1 object_type = "module" def run(self) -> nodes.Node: """ Not sure yet """ state = self.state node = nodes.section() rst = ViewList(self.content, "testing") # Parse the restructured text into nodes. state.nested_parse(rst, 0, node, match_titles=1) return node.children def setup(app: Sphinx) -> None: """ Setup function for registering this with sphinx """ app.require_sphinx("2.0") app.setup_extension("sphinx.ext.autodoc") app.add_autodocumenter(CModuleDocumenter) app.add_autodocumenter(CFunctionDocumenter) app.add_autodocumenter(CTypeDocumenter) app.add_autodocumenter(CStructDocumenter) app.add_autodocumenter(CUnionDocumenter) app.add_autodocumenter(CEnumDocumenter) app.add_autodocumenter(CMemberDocumenter) app.add_autodocumenter(CMacroDocumenter) app.add_autodocumenter(CEnumeratorDocumenter) app.add_autodocumenter(CDataDocumenter) app.add_directive_to_domain("c", "module", CModule) app.add_config_value("c_autodoc_roots", [""], "env") app.add_config_value("c_autodoc_compilation_database", None, "env") app.add_config_value("c_autodoc_compilation_args", [""], "env") app.add_event("c-autodoc-pre-process") patch_c_domain()
StarcoderdataPython
1824141
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # pylint: disable=E1102 # python3 """Retrieves customer data from our companies "internal" customer data serivce. This data service is meant to be illustrative for demo purposes, as its just hard coded data. This can be any internal or on-premise data store. """ class CustomerDataService(object): _CUSTOMER_DATA = { 'mars': { 'customer_name': '<NAME>.', 'customer_logo': 'https://upload.wikimedia.org/wikipedia/commons/thumb/0/02/' + 'OSIRIS_Mars_true_color.jpg/550px-OSIRIS_Mars_true_color.jpg', 'curr_q': 'Q2', 'curr_q_total_sales': '$2,532,124', 'curr_q_qoq': '0.054', 'prev_q': 'Q1', 'prev_q_total_sales': '$2,413,584', 'next_q': 'Q3', 'next_q_total_sales_proj': '$2,634,765', 'next_q_qoq_proj': '0.041', 'top1_sku': 'Phobos', 'top1_sales': '$334,384', 'top2_sku': 'Deimos', 'top2_sales': '$315,718', 'top3_sku': 'Charon', 'top3_sales': '$285,727', 'top4_sku': 'Nix', 'top4_sales': '$264,023', 'top5_sku': 'Hydra', 'top5_sales': '$212,361', }, 'jupiter': { 'customer_name': '<NAME>', 'customer_logo': 'https://upload.wikimedia.org/wikipedia/commons/thumb/2/2b/' + 'Jupiter_and_its_shrunken_Great_Red_Spot.jpg/660px-Jupiter_' + 'and_its_shrunken_Great_Red_Spot.jpg', 'curr_q': 'Q2', 'curr_q_total_sales': '$1,532,124', 'curr_q_qoq': '0.031', 'prev_q': 'Q1', 'prev_q_total_sales': '$1,413,584', 'next_q': 'Q3', 'next_q_total_sales_proj': '$1,634,765', 'next_q_qoq_proj': '0.021', 'top1_sku': 'Io', 'top1_sales': '$234,384', 'top2_sku': 'Europa', 'top2_sales': '$215,718', 'top3_sku': 'Ganymede', 'top3_sales': '$185,727', 'top4_sku': 'Callisto', 'top4_sales': '$164,023', 'top5_sku': 'Amalthea', 'top5_sales': '$112,361', }, 'saturn': { 'customer_name': 'Saturn', 'customer_logo': 'https://upload.wikimedia.org/wikipedia/commons/thumb/c/c7/' + 'Saturn_during_Equinox.jpg/800px-Saturn_during_Equinox.jpg', 'curr_q': 'Q2', 'curr_q_total_sales': '$2,532,124', 'curr_q_qoq': '0.032', 'prev_q': 'Q1', 'prev_q_total_sales': '$2,413,584', 'next_q': 'Q3', 'next_q_total_sales_proj': '$2,634,765', 'next_q_qoq_proj': '0.029', 'top1_sku': 'Mimas', 'top1_sales': '$334,384', 'top2_sku': 'Enceladus', 'top2_sales': '$315,718', 'top3_sku': 'Tethys', 'top3_sales': '$285,727', 'top4_sku': 'Dione', 'top4_sales': '$264,023', 'top5_sku': 'Rhea', 'top5_sales': '$212,361', }, 'neptune': { 'customer_name': 'Neptune', 'customer_logo': 'https://upload.wikimedia.org/wikipedia/commons/thumb/5/56/' + 'Neptune_Full.jpg/600px-Neptune_Full.jpg', 'curr_q': 'Q2', 'curr_q_total_sales': '$2,532,124', 'curr_q_qoq': '0.027', 'prev_q': 'Q1', 'prev_q_total_sales': '$2,413,584', 'next_q': 'Q3', 'next_q_total_sales_proj': '$2,634,765', 'next_q_qoq_proj': '0.039', 'top1_sku': 'Triton', 'top1_sales': '$334,384', 'top2_sku': 'Nereid', 'top2_sales': '$315,718', 'top3_sku': 'Naiad', 'top3_sales': '$285,727', 'top4_sku': 'Thalassa', 'top4_sales': '$264,023', 'top5_sku': 'Despina', 'top5_sales': '$212,361', }, } def GetCustomerData(self, customer_id, properties): customer_data = self._CUSTOMER_DATA[customer_id] return [customer_data[p.lower()] for p in properties]
StarcoderdataPython
1708240
<reponame>zakness1/painel<gh_stars>1-10 import requests from data import ui def consultar(token='2<PASSWORD>',self=0): Sair = False while(Sair == False): if self == 1: ip_input = '' else: ip_input = ui.input_dialog() if len(ip_input) < 1: ui.error_dialog('Insira algo para consultar.');break try: api=requests.get('http://ipwhois.app/json/'+ip_input).json() #lat = api['latitude'] #lon = api['longitude'] #api2 = requests.get('http://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={token[2]}') except: msg = "erro no servidor" try: msg=f''' IP: {api['ip']} TIPO: {api['type']} CONTINENTE: {api['continent']} C?DIGO DO CONTINENTE: {api['continent_code']} PAIS: {api['country']} C?DIGO DO PA?S: {api['country']} CAPITAL DO PAIS: {api['country_capital']} C?DIGO TELEF?NICO DO PA?S: {api['country_phone']} PAISES VIZINHOS: {api['country_neighbours']} REGI?O: {api['region']} CIDADE: {api['city']} LATITUDE: {api['latitude']} LONGITUDE: {api['longitude']} ASN: {api['asn']} ORG: {api['org']} ISP: {api['isp']} HOR?RIO PADR?O: {api['timezone']} NOME DO HOR?RIO PADR?O: {api['timezone_name']} GMT: {api['timezone_gmt']} MOEDA: {api['currency']} CODIGO DA MOEDA: {api['currency_code']} SIMBOLO DA MOEDA: {api['currency_symbol']} ''' #TEMPERATURA: {api2["weather"][0]["main"]} except: msg = 'Ip invalido.' choice = int(ui.dialog_choice(msg)) if choice == 1: pass elif choice == 2: Sair = True else: ui.error_dialog()
StarcoderdataPython
1630703
<reponame>kavyapnaik/PythonRemoteServer<gh_stars>100-1000 from __future__ import print_function import sys class Logging(object): def logging(self, message, level='', evaluate=False, stderr=False): if evaluate and evaluate != 'False': message = eval(message) if level: message = '*%s* %s' % (level, message) stream = sys.stdout if not stderr else sys.stderr print(message, file=stream) def multiple_messages_with_different_levels(self): print('Info message') print('*DEBUG* Debug message') print('*INFO* Second info') print('this time with two lines') print('*INFO* Third info') print('*TRACE* This is ignored') print('*WARN* Warning') def logging_and_failing(self): print('*INFO* This keyword will fail!') print('*WARN* Run for your lives!!') raise AssertionError('Too slow') def logging_and_returning(self, logged, returned): print(logged) return returned def logging_both_to_stdout_and_stderr(self, *messages): for index, msg in enumerate(messages): stream = sys.stdout if index % 2 == 0 else sys.stderr stream.write(msg) if __name__ == '__main__': from robotremoteserver import RobotRemoteServer RobotRemoteServer(Logging(), '127.0.0.1', *sys.argv[1:])
StarcoderdataPython
5144225
<reponame>minMaximilian/webdev2<gh_stars>0 #!/usr/bin/python3 import os import sys restricted = "../restricted" sys.path.append(os.path.abspath(restricted)) from cgi import FieldStorage from html import escape import pymysql as db import passwords import funcs from os import environ from http.cookies import SimpleCookie def retrieve_incoming(uname): txt = "<section><h2 class=\"incoming\"> In coming game requests</h2>" txt_2 = "" connection = db.connect(passwords.serverip, passwords.servername, passwords.serverpass, passwords.db_name) cursor = connection.cursor(db.cursors.DictCursor) cursor.execute("""SELECT player_1, game_id FROM chess_games WHERE player_2 = %s AND confirmed = 0 AND win = 0""", (uname)) for row in cursor.fetchall(): txt_2 += ("""<form class="game-request" action="../game/mm_handler.py" method="post"> Game request from %s: <button name="accept" type="submit" id="accept" value="%s"> Accept </button> <button name="decline" type="submit" id="decline" value="%s"> Decline </button> </form>""" % (row["player_1"], row["game_id"], row["game_id"])) if txt_2 == "": txt += "<p> No game requests from other players!</p>" txt += txt_2 txt += "</section>" return txt def retrieve_outgoing(uname): txt = "<section><h2 class=\"outgoing\"> Out going game requests</h2>" txt_2 = "" connection = db.connect(passwords.serverip, passwords.servername, passwords.serverpass, passwords.db_name) cursor = connection.cursor(db.cursors.DictCursor) cursor.execute("""SELECT player_2, game_id FROM chess_games WHERE player_1 = %s AND confirmed = 0 AND win = 0""", (uname)) for row in cursor.fetchall(): txt_2 += ("""<form class="game-request" action="../game/mm_handler.py" method="post"> Game request to %s: <button name="cancel" type="submit" id="cancel" value="%s"> Cancel </button> </form>""" % (row["player_2"], row["game_id"])) if txt_2 == "": txt += "<p> No game requests to other players!</p>" txt += txt_2 txt += "</section>" return txt def challenge(uname): connection = db.connect(passwords.serverip, passwords.servername, passwords.serverpass, passwords.db_name) cursor = connection.cursor(db.cursors.DictCursor) cursor.execute("""SELECT uname FROM users WHERE uname = """, (uname)) for row in cursor.fetchall(): connection.commit() cursor.close() connection.close() return row["uname"] cursor.close() connection.close() def retrieve_elo(uname): connection = db.connect(passwords.serverip, passwords.servername, passwords.serverpass, passwords.db_name) cursor = connection.cursor(db.cursors.DictCursor) cursor.execute("""SELECT elo, numgames FROM elo WHERE uname = %s""", (uname)) row = cursor.fetchone() txt = ("<p> You have achieved an ELO of %s over the course of %s games" % (row["elo"], row["numgames"])) connection.commit() cursor.close() connection.close() return txt def retrieve_stats(uname): txt = "<section><h2 class=\"game-history\"> Game History </h2>" txt_2 = "" connection = db.connect(passwords.serverip, passwords.servername, passwords.serverpass, passwords.db_name) cursor = connection.cursor(db.cursors.DictCursor) cursor.execute("""SELECT player_1, player_2, win FROM chess_games WHERE (player_1 = %s OR player_2 = %s) AND confirmed = 1 AND win != 0""", (uname, uname)) for row in cursor.fetchall(): if row["player_1"] == uname and row["win"] == 1: txt_2 += ("<p> You have won against %s </p>" % (row["player_2"])) elif row["player_2"] == uname and row["win"] == 2: txt_2 += ("<p> You have won against %s </p>" % (row["player_1"])) else: if uname == row["player_1"]: txt_2 += ("<p> You have lost against %s </p>" % (row["player_2"])) else: txt_2 += ("<p> You have lost against %s </p>" % (row["player_1"])) if txt_2 == "": txt += "<p> No past games </p>" txt += txt_2 txt += "</section>" return txt result = "" result_2 = "" incoming = "No incoming requests to play games" outgoing = "No outgoing requests to play games" form = """<form class="find-opponent" action="index.py" method="post"> <label for="opponent"> Who do you want to challenge today?</label> <input type="text" id="opponent" name="opponent" value=""> <button type="submit"> Throw the gauntlet </button> <p>%s</p> </form>""" form_data = FieldStorage() opponent = form_data.getfirst("opponent") cookie = SimpleCookie() http_cookie_header = environ.get("HTTP_COOKIE") if http_cookie_header: cookie.load(http_cookie_header) try: if funcs.check_if_exists(cookie["sessionId"].value): uname = funcs.return_uname(cookie["sessionId"].value) if opponent and not(opponent == uname): opponent = escape(opponent, quote=False) if funcs.check_if_exists_uname(opponent): connection = db.connect(passwords.serverip, passwords.servername, passwords.serverpass, passwords.db_name) cursor = connection.cursor(db.cursors.DictCursor) cursor.execute("""INSERT INTO chess_games (player_1, player_2, confirmed, win) VALUES (%s, %s, 0, 0)""", (uname, opponent)) connection.commit() cursor.close() connection.close() form = (form % ("Succesful request!")) else: form = (form % ("The user doesn't exist or hasn't confirmed their account")) else: form = (form % ("")) if funcs.is_ongoing_game(uname): result = ("""<form class="game-request" action="../game/mm_handler.py" method="post"> Concurrently in a game: <button name="continue" type="submit" id="continue" value="%s"> Continue </button> <button name="forfeit" type="submit" id="forfeit" value="%s"> Forfeit </button> </form>""" % (funcs.is_ongoing_game(uname)[1], funcs.is_ongoing_game(uname)[1])) else: result += form result += retrieve_incoming(uname) result += retrieve_outgoing(uname) result_2 = retrieve_stats(uname) print("Content-Type: text/html") print() print(""" <!DOCTYPE html> <html lang="en"> <head> <title>Leaderboard</title> <link rel="stylesheet" href="../css/index.css" /> <meta charset="UTF-8" /> </head> <body> <header> <a href="../index.py">Nice Chess Games</a> <div ><a href="leaderboard.py">Leaderboard</a ><a href="search.py">Search</a ><a href="logout.py">Logout</a ></div> </header> <section class="user-content"> <section class="requests"> <p> Hello %s, fancy a game? Look up a user in the search and challenge them using the form below! Or you can accept an already incoming request</p> %s </section> <section class="history"> %s Here is a history of games you've played %s </section> </section> </body> </html>""" % (uname, result, retrieve_elo(uname), result_2)) else: funcs.redirect("login.py") except Exception as E: funcs.redirect("login.py") else: funcs.redirect("login.py")
StarcoderdataPython
3220566
import tensorflow as tf from detext.layers.embedding_layer import create_embedding_layer from detext.utils.layer_utils import get_sorted_dict from detext.utils.parsing_utils import InputFtrType, InternalFtrType class LstmLayer(tf.keras.layers.Layer): def __init__(self, bidirectional, rnn_dropout, num_layers, forget_bias, min_len, max_len, embedding_layer_param, embedding_hub_url, **kwargs): """ Initializes the model For more details on parameters, check the argument parser in run_detext.py """ super(LstmLayer, self).__init__() self.min_len = tf.constant(min_len, dtype=tf.dtypes.int32) self.max_len = tf.constant(max_len, dtype=tf.dtypes.int32) self.num_cls_sep = tf.constant(1, dtype=tf.dtypes.int32) self._bidirectional = bidirectional self._forget_bias = forget_bias self._rnn_dropout = rnn_dropout self.forward_only = not bidirectional self.embedding = create_embedding_layer(embedding_layer_param, embedding_hub_url) self._num_units = self.embedding.num_units().numpy() self.text_ftr_size = self._num_units self.text_encoders = [] for _ in range(num_layers): if self.forward_only: encoder = self.create_encoder(self._num_units) else: assert self._num_units % 2 == 0, "num_units must be a multiplier of 2 when bidirectional is True" fw_encoder = self.create_encoder(self._num_units // 2) bw_encoder = self.create_encoder(self._num_units // 2, go_backwards=True) encoder = tf.keras.layers.Bidirectional(fw_encoder, backward_layer=bw_encoder) self.text_encoders.append(encoder) def create_encoder(self, num_units, **kwargs): return tf.keras.layers.LSTM(num_units, bias_initializer=tf.keras.initializers.Constant(self._forget_bias), dropout=self._rnn_dropout, return_sequences=True, return_state=True, **kwargs) def call(self, inputs, training=None, **kwargs): """ Apply LSTM on text fields :param query: Tensor(dtype=string) Shape=[batch_size] :param doc_fields: list(Tensor(dtype=string))/Tensor A list of document fields. Each has shape= [batch_size, max_group_size]. For online scoring, these fields may be precomputed and input as Tensor :param user_fields: list(Tensor(dtype=string))/Tensor A list of user fields. Each has shape= [batch_size]. For online scoring, these fields may be precomputed and input as Tensor :param training: boolean Whether it's under training mode :return: query, document and user features """ query = inputs.get(InputFtrType.QUERY_COLUMN_NAME, None) doc_fields = inputs.get(InputFtrType.DOC_TEXT_COLUMN_NAMES, None) user_fields = inputs.get(InputFtrType.USER_TEXT_COLUMN_NAMES, None) query_ftrs = self.apply_lstm_on_query(query, training) if query is not None else None user_ftrs = self.apply_lstm_on_user(user_fields, training) if user_fields is not None else None doc_ftrs = self.apply_lstm_on_doc(doc_fields, training) if doc_fields is not None else None return query_ftrs, doc_ftrs, user_ftrs def apply_lstm_on_query(self, query, training): """ Applies LSTM on query :return Tensor Query features. Shape=[batch_size, text_ftr_size] """ return self.apply_lstm_on_text(query, training)[InternalFtrType.LAST_MEMORY_STATE] def apply_lstm_on_user(self, user_fields, training): """ Applies LSTM on user fields :return Tensor User features. Shape=[batch_size, num_user_fields, text_ftr_size] """ if type(user_fields) is not list: return user_fields user_ftrs = [] for i, user_field in enumerate(user_fields): user_field_ftrs = self.apply_lstm_on_text(user_field, training)[InternalFtrType.LAST_MEMORY_STATE] user_ftrs.append(user_field_ftrs) user_ftrs = tf.stack(user_ftrs, axis=1) # shape=[batch_size, num_user_fields, text_ftr_size] return user_ftrs def apply_lstm_on_text(self, text, training): """ Applies LSTM on text with params partially filled with class members """ return apply_lstm_on_text(text, self.text_encoders, self.embedding, self._bidirectional, self.min_len, self.max_len, self.num_cls_sep, training) def apply_lstm_on_doc(self, doc_fields, training): """ Applies LSTM on documents :return Tensor Document features. Shape=[batch_size, max_group_size, num_doc_fields, text_ftr_size] """ # doc_fields should be the doc embeddings if type(doc_fields) is not list: return doc_fields doc_ftrs = [] for i, doc_field in enumerate(doc_fields): doc_shape = tf.shape(input=doc_field) # Shape=[batch_size, group_size, sent_length] doc_field = tf.reshape(doc_field, shape=[doc_shape[0] * doc_shape[1]]) doc_field_ftrs = self.apply_lstm_on_text(doc_field, training)[InternalFtrType.LAST_MEMORY_STATE] # Restore batch_size and group_size doc_field_ftrs = tf.reshape(doc_field_ftrs, shape=[doc_shape[0], doc_shape[1], self.text_ftr_size]) doc_ftrs.append(doc_field_ftrs) doc_ftrs = tf.stack(doc_ftrs, axis=2) # Shape=[batch_size, max_group_size, num_doc_fields, text_ftr_size] return doc_ftrs def apply_lstm_on_embedding(input_emb, mask, lstm_encoders, forward_only, training): """Applies LSTM on given embeddings :param input_emb Tensor(dtype=float) Shape=[batch_size, sentence_len, num_units] :return A dictionary containing seq_outputs: Tensor(dtype=float) Shape=[batch_size, sentence_len, num_units] last_memory_state: Tensor(dtype=float) Shape=[batch_size, num_units] last_carry_state: Tensor(dtype=float) Shape=[batch_size, num_units] """ first_encoder = lstm_encoders[0] mask = tf.cast(mask, dtype=tf.dtypes.bool) if forward_only: # Shape(seq_outputs) = [batch_size, seq_len, num_units] seq_outputs, last_memory_state, last_carry_state = first_encoder(input_emb, mask=mask, training=training) for encoder in lstm_encoders[1:]: # Multi layer LSTM seq_outputs, last_memory_state, last_carry_state = encoder(seq_outputs, mask=mask, training=training) else: # Shape(seq_outputs) = [batch_size, seq_len, num_units] seq_outputs, last_fw_memory_state, last_fw_carry_state, last_bw_memory_state, last_bw_carry_state = first_encoder(input_emb, mask=mask, training=training) for encoder in lstm_encoders[1:]: # Multi layer LSTM seq_outputs, last_fw_memory_state, last_fw_carry_state, last_bw_memory_state, last_bw_carry_state = encoder(seq_outputs, mask=mask, training=training) last_memory_state = tf.concat([last_fw_memory_state, last_bw_memory_state], axis=-1) last_carry_state = tf.concat([last_fw_carry_state, last_bw_carry_state], axis=-1) return {InternalFtrType.SEQ_OUTPUTS: seq_outputs, InternalFtrType.LAST_MEMORY_STATE: last_memory_state, InternalFtrType.LAST_CARRY_STATE: last_carry_state} def apply_lstm_on_text(text, lstm_encoders, embedding_layer, bidirectional, min_len, max_len, num_cls_sep, training): """ Applies LSTM on text :param text: Tensor Shape=[batch_size] :param lstm_encoders: List(LSTM) List of LSTMs that stacks sequentially :param embedding_layer Tensor Embedding matrix :param bidirectional boolean Indicator of whether it's bidirectional encoder :param training boolean Indicator of whether it's under training mode :return A dictionary containing seq_outputs: Tensor(dtype=float) Shape=[batch_size, sentence_len, num_units] last_memory_state: Tensor(dtype=float) Shape=[batch_size, num_units] last_carry_state: Tensor(dtype=float) Shape=[batch_size, num_units] """ forward_only = not bidirectional input_seq = text inputs = get_sorted_dict( {InternalFtrType.SENTENCES: input_seq, InternalFtrType.NUM_CLS: num_cls_sep, InternalFtrType.NUM_SEP: num_cls_sep, InternalFtrType.MIN_LEN: min_len, InternalFtrType.MAX_LEN: max_len, } ) embedding_result = embedding_layer(inputs) input_emb = embedding_result[InternalFtrType.EMBEDDED] seq_len = embedding_result[InternalFtrType.LENGTH] max_seq_len = tf.math.reduce_max(seq_len) mask = tf.sequence_mask(seq_len, max_seq_len, dtype=tf.float32) results = apply_lstm_on_embedding(input_emb, mask, lstm_encoders, forward_only, training) return results
StarcoderdataPython
6422046
<gh_stars>100-1000 from typing import TYPE_CHECKING if TYPE_CHECKING: from rotkehlchen.db.dbhandler import DBHandler def upgrade_v16_to_v17(db: 'DBHandler') -> None: """Upgrades the DB from v16 to v17 - Deletes all ethereum transactions and query ranges from the DB so they can be saved again with the new schema. - Deletes ethereum transactions table and creates it with the new schema where primary key also includes the from_address """ cursor = db.conn.cursor() cursor.execute('DELETE FROM ethereum_transactions;') cursor.execute('DELETE FROM used_query_ranges WHERE name LIKE "ethtxs_%";') cursor.execute('DROP TABLE IF EXISTS ethereum_transactions;') # and create the table. Same schema as was in launch of v1.7.0 cursor.execute(""" CREATE TABLE IF NOT EXISTS ethereum_transactions ( tx_hash BLOB, timestamp INTEGER, block_number INTEGER, from_address TEXT, to_address TEXT, value TEXT, gas TEXT, gas_price TEXT, gas_used TEXT, input_data BLOB, nonce INTEGER, /* we determine uniqueness for ethereum internal transactions by using an increasingly negative number */ PRIMARY KEY (tx_hash, nonce, from_address) );""")
StarcoderdataPython
8040038
#!/usr/bin/env python """ Locate libpython associated with this Python executable. """ # https://pypi.org/project/find-libpython/ # License # # Copyright 2018, <NAME> # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. from __future__ import print_function, absolute_import from logging import getLogger import ctypes.util import functools import os import sys import sysconfig logger = getLogger("find_libpython") is_windows = os.name == "nt" is_apple = sys.platform == "darwin" SHLIB_SUFFIX = sysconfig.get_config_var("SHLIB_SUFFIX") if SHLIB_SUFFIX is None: if is_windows: SHLIB_SUFFIX = ".dll" else: SHLIB_SUFFIX = ".so" if is_apple: # sysconfig.get_config_var("SHLIB_SUFFIX") can be ".so" in macOS. # Let's not use the value from sysconfig. SHLIB_SUFFIX = ".dylib" def linked_libpython(): """ Find the linked libpython using dladdr (in *nix). Calling this in Windows always return `None` at the moment. Returns ------- path : str or None A path to linked libpython. Return `None` if statically linked. """ if is_windows: return None return _linked_libpython_unix() class Dl_info(ctypes.Structure): _fields_ = [ ("dli_fname", ctypes.c_char_p), ("dli_fbase", ctypes.c_void_p), ("dli_sname", ctypes.c_char_p), ("dli_saddr", ctypes.c_void_p), ] def _linked_libpython_unix(): libdl = ctypes.CDLL(ctypes.util.find_library("dl")) libdl.dladdr.argtypes = [ctypes.c_void_p, ctypes.POINTER(Dl_info)] libdl.dladdr.restype = ctypes.c_int dlinfo = Dl_info() retcode = libdl.dladdr( ctypes.cast(ctypes.pythonapi.Py_GetVersion, ctypes.c_void_p), ctypes.pointer(dlinfo)) if retcode == 0: # means error return None path = os.path.realpath(dlinfo.dli_fname.decode()) if path == os.path.realpath(sys.executable): return None return path def library_name(name, suffix=SHLIB_SUFFIX, is_windows=is_windows): """ Convert a file basename `name` to a library name (no "lib" and ".so" etc.) >>> library_name("libpython3.7m.so") # doctest: +SKIP 'python3.7m' >>> library_name("libpython3.7m.so", suffix=".so", is_windows=False) 'python3.7m' >>> library_name("libpython3.7m.dylib", suffix=".dylib", is_windows=False) 'python3.7m' >>> library_name("python37.dll", suffix=".dll", is_windows=True) 'python37' """ if not is_windows and name.startswith("lib"): name = name[len("lib"):] if suffix and name.endswith(suffix): name = name[:-len(suffix)] return name def append_truthy(list, item): if item: list.append(item) def uniquifying(items): """ Yield items while excluding the duplicates and preserving the order. >>> list(uniquifying([1, 2, 1, 2, 3])) [1, 2, 3] """ seen = set() for x in items: if x not in seen: yield x seen.add(x) def uniquified(func): """ Wrap iterator returned from `func` by `uniquifying`. """ @functools.wraps(func) def wrapper(*args, **kwds): return uniquifying(func(*args, **kwds)) return wrapper @uniquified def candidate_names(suffix=SHLIB_SUFFIX): """ Iterate over candidate file names of libpython. Yields ------ name : str Candidate name libpython. """ LDLIBRARY = sysconfig.get_config_var("LDLIBRARY") if LDLIBRARY: yield LDLIBRARY LIBRARY = sysconfig.get_config_var("LIBRARY") if LIBRARY: yield os.path.splitext(LIBRARY)[0] + suffix dlprefix = "" if is_windows else "lib" sysdata = dict( v=sys.version_info, # VERSION is X.Y in Linux/macOS and XY in Windows: VERSION=(sysconfig.get_config_var("VERSION") or "{v.major}.{v.minor}".format(v=sys.version_info)), ABIFLAGS=(sysconfig.get_config_var("ABIFLAGS") or sysconfig.get_config_var("abiflags") or ""), ) for stem in [ "python{VERSION}{ABIFLAGS}".format(**sysdata), "python{VERSION}".format(**sysdata), "python{v.major}".format(**sysdata), "python", ]: yield dlprefix + stem + suffix @uniquified def candidate_paths(suffix=SHLIB_SUFFIX): """ Iterate over candidate paths of libpython. Yields ------ path : str or None Candidate path to libpython. The path may not be a fullpath and may not exist. """ yield linked_libpython() # List candidates for directories in which libpython may exist lib_dirs = [] append_truthy(lib_dirs, sysconfig.get_config_var('LIBPL')) append_truthy(lib_dirs, sysconfig.get_config_var('srcdir')) append_truthy(lib_dirs, sysconfig.get_config_var("LIBDIR")) # LIBPL seems to be the right config_var to use. It is the one # used in python-config when shared library is not enabled: # https://github.com/python/cpython/blob/v3.7.0/Misc/python-config.in#L55-L57 # # But we try other places just in case. if is_windows: lib_dirs.append(os.path.join(os.path.dirname(sys.executable))) else: lib_dirs.append(os.path.join( os.path.dirname(os.path.dirname(sys.executable)), "lib")) # For macOS: append_truthy(lib_dirs, sysconfig.get_config_var("PYTHONFRAMEWORKPREFIX")) lib_dirs.append(sys.exec_prefix) lib_dirs.append(os.path.join(sys.exec_prefix, "lib")) lib_basenames = list(candidate_names(suffix=suffix)) for directory in lib_dirs: for basename in lib_basenames: yield os.path.join(directory, basename) # In macOS and Windows, ctypes.util.find_library returns a full path: for basename in lib_basenames: yield ctypes.util.find_library(library_name(basename)) # Possibly useful links: # * https://packages.ubuntu.com/bionic/amd64/libpython3.6/filelist # * https://github.com/Valloric/ycmd/issues/518 # * https://github.com/Valloric/ycmd/pull/519 def normalize_path(path, suffix=SHLIB_SUFFIX, is_apple=is_apple): """ Normalize shared library `path` to a real path. If `path` is not a full path, `None` is returned. If `path` does not exists, append `SHLIB_SUFFIX` and check if it exists. Finally, the path is canonicalized by following the symlinks. Parameters ---------- path : str ot None A candidate path to a shared library. """ if not path: return None if not os.path.isabs(path): return None if os.path.exists(path): return os.path.realpath(path) if os.path.exists(path + suffix): return os.path.realpath(path + suffix) if is_apple: return normalize_path(_remove_suffix_apple(path), suffix=".so", is_apple=False) return None def _remove_suffix_apple(path): """ Strip off .so or .dylib. >>> _remove_suffix_apple("libpython.so") 'libpython' >>> _remove_suffix_apple("libpython.dylib") 'libpython' >>> _remove_suffix_apple("libpython3.7") 'libpython3.7' """ if path.endswith(".dylib"): return path[:-len(".dylib")] if path.endswith(".so"): return path[:-len(".so")] return path @uniquified def finding_libpython(): """ Iterate over existing libpython paths. The first item is likely to be the best one. Yields ------ path : str Existing path to a libpython. """ logger.debug("is_windows = %s", is_windows) logger.debug("is_apple = %s", is_apple) for path in candidate_paths(): logger.debug("Candidate: %s", path) normalized = normalize_path(path) if normalized: logger.debug("Found: %s", normalized) yield normalized else: logger.debug("Not found.") def find_libpython(): """ Return a path (`str`) to libpython or `None` if not found. Parameters ---------- path : str or None Existing path to the (supposedly) correct libpython. """ for path in finding_libpython(): return os.path.realpath(path) def print_all(items): for x in items: print(x) def cli_find_libpython(cli_op, verbose): import logging # Importing `logging` module here so that using `logging.debug` # instead of `logger.debug` outside of this function becomes an # error. if verbose: logging.basicConfig( format="%(levelname)s %(message)s", level=logging.DEBUG) if cli_op == "list-all": print_all(finding_libpython()) elif cli_op == "candidate-names": print_all(candidate_names()) elif cli_op == "candidate-paths": print_all(p for p in candidate_paths() if p and os.path.isabs(p)) else: path = find_libpython() if path is None: return 1 print(path, end="") def main(args=None): import argparse parser = argparse.ArgumentParser( description=__doc__) parser.add_argument( "--verbose", "-v", action="store_true", help="Print debugging information.") group = parser.add_mutually_exclusive_group() group.add_argument( "--list-all", action="store_const", dest="cli_op", const="list-all", help="Print list of all paths found.") group.add_argument( "--candidate-names", action="store_const", dest="cli_op", const="candidate-names", help="Print list of candidate names of libpython.") group.add_argument( "--candidate-paths", action="store_const", dest="cli_op", const="candidate-paths", help="Print list of candidate paths of libpython.") ns = parser.parse_args(args) parser.exit(cli_find_libpython(**vars(ns))) if __name__ == "__main__": main()
StarcoderdataPython
9632871
<filename>tests/converter/test_converter.py import pytest import random from qctools.converter import Converter @pytest.fixture def example_converter(): ''' Returns an example converter ''' converter = Converter.from_dct('example', 'ref', { 'ref': (1, 'direct'), 'eV': (27, 'direct'), 'cm': (27, 'inverse'), }) return converter @pytest.fixture def random_value(): ''' Returns an random value''' return random.uniform(0.00001, 10000000.0) def test_conversion_inverse(example_converter, random_value): '''test conversion for inverse type''' fac = example_converter.container['cm'].factor assert (round(fac/random_value, 8) == round(example_converter.convert(random_value, 'ref', 'cm'), 8)) def test_conversion_direct(example_converter, random_value): '''test conversion for inverse direct''' fac = example_converter.container['eV'].factor assert (round(fac*random_value, 8) == round(example_converter.convert(random_value, 'ref', 'eV'), 8)) def test_add_entry_direct(example_converter, random_value): factor = example_converter.container['eV'].factor example_converter.add_entry('ex1', factor, 'direct') assert round(random_value, 7) == round(example_converter.convert( random_value, 'ex1', 'eV'), 7) def test_add_entry_direct_via_second_direct_element(example_converter): example_converter.add_entry('ex2', 1.0, 'direct', other='eV') for i in range(1, 100): res1 = example_converter.convert(i, 'ref', 'ex2') res2 = example_converter.convert(i, 'ref', 'eV') assert round(res1, 6) == round(res2, 6) def test_add_entry_direct_via_second_inverse_element(example_converter): fac = 3.0 example_converter.add_entry('ex3', fac, 'direct', other='cm') for i in range(1, 100): res1 = example_converter.convert(i, 'eV', 'ex3') res2 = example_converter.convert(i, 'eV', 'cm')*fac assert round(res1, 8) == round(res2, 8) def test_add_entry_inverse_via_second_inverse_element(example_converter): example_converter.add_entry('ex4', 1.0/27.0, 'inverse', other='cm') for i in range(1, 100): res1 = example_converter.convert(i, 'ref', 'ex4') res2 = example_converter.convert(i, 'ref', 'ref') assert round(res1, 8) == round(res2, 8) def test_add_entry_inverse(example_converter): example_converter.add_entry('ex5', 27, 'inverse') for i in range(1, 100): result = example_converter.convert(i, 'ex5', 'cm') assert round(i, 8) == round(result, 8) def test_add_entry(example_converter): example_converter.add_entry('en', 1, 'direct') assert 'en' in example_converter def test_add_entry_fail(example_converter): with pytest.raises(Exception): assert 'en' in example_converter
StarcoderdataPython
299963
<gh_stars>10-100 # -------------------------------- # Testing # -------------------------------- # is it a test run? # test runs reduce the dataset to 100 instances only from enum import IntEnum TEST = False # -------------------------------- # FileTypes # -------------------------------- # Do we only look at production or test files or both? # 0 = only_production, 1 = only_test, 2 = production_and_test FILE_TYPE = 2 # -------------------------------- # Database related # -------------------------------- # do we use the cached results? True=yes, False=no, go always to the db USE_CACHE = True # is the db available? sometimes it's not, but you have all the cache DB_AVAILABLE = True # -------------------------------- # Dataset balancing # -------------------------------- BALANCE_DATASET = True # how to balance the dataset # options = [random, cluster_centroids, nearmiss] BALANCE_DATASET_STRATEGY = "random" # -------------------------------- # Dataset scaling # -------------------------------- # scale using MinMaxScaler? SCALE_DATASET = True # -------------------------------- # Feature reduction # -------------------------------- #Remove all instances where one of process and authorship metrics is -1 (faulty). DROP_FAULTY_PROCESS_AND_AUTHORSHIP_METRICS = True # Use (or drop) process and authorship metrics, this cancels DROP_FAULTY_PROCESS_AND_AUTHORSHIP_METRICS. DROP_PROCESS_AND_AUTHORSHIP_METRICS = False #a list of all process and authorship metrics PROCESS_AND_AUTHORSHIP_METRICS = ["authorOwnership", "bugFixCount", "qtyMajorAuthors", "qtyMinorAuthors", "qtyOfAuthors", "qtyOfCommits", "refactoringsInvolved"] # Drop these metrics as well # TODO: validate this # number of default fields and methods is always 0. Thus, remove them from the data. DROP_METRICS = ["classNumberOfDefaultFields", "classNumberOfDefaultMethods"] # perform feature reduction? FEATURE_REDUCTION = True # number of folds for feature reduction N_CV_FEATURE_REDUCTION = 5 # -------------------------------- # Hyperparameter search # -------------------------------- # what type of search for the best hyper params? # options = [randomized, grid] SEARCH = "grid" # number of iterations (if Randomized strategy is chosen) N_ITER_RANDOM_SEARCH = 100 # number of folds in the search for best parameters N_CV_SEARCH = 5 # -------------------------------- # Evaluation: Cross-validation configuration # -------------------------------- # Specify either a train/ test split, e.g. 0.2 -> 80/ 20 split TEST_SPLIT_SIZE = -1 # Or specify test data sets in the database # NOTE: set TEST_SPLIT_SIZE value to < 0, in order to indicate to use the given datasets instead of a random train/ test split VALIDATION_DATASETS = ["test set github", "validation set github"] # number of folds for the final evaluation N_CV = 10 # number of folds for the DNN N_CV_DNN = 10 # -------------------------------- # Models and datasets # -------------------------------- # models and datasets we have available MODELS = ['svm', 'svm-non-linear', 'decision-tree', 'random-forest', 'logistic-regression', 'naive-bayes', 'extra-trees'] # Empty dataset means 'all datasets' DATASETS = ["github"] # -------------------------------- # Refactorings # -------------------------------- # refactoring levels class Level(IntEnum): NONE = 0 Class = 1 Method = 2 Variable = 3 Field = 4 Other = 5 # Refactorings to study CLASS_LEVEL_REFACTORINGS = ["Extract Class", "Extract Interface", "Extract Subclass", "Extract Superclass", "Move And Rename Class", "Move Class", "Rename Class", "Introduce Polymorphism", "Move And Rename Class", "Convert Anonymous Class To Type"] METHOD_LEVEL_REFACTORINGS = ["Extract And Move Method", "Extract Method", "Inline Method", "Move Method", "Pull Up Method", "Push Down Method", "Rename Method", "Extract And Move Method", "Change Return Type", "Move And Inline Method", "Move And Rename Method", "Change Parameter Type", "Split Parameter", "Merge Parameter"] VARIABLE_LEVEL_REFACTORINGS = ["Extract Variable", "Inline Variable", "Parameterize Variable", "Rename Parameter", "Rename Variable", "Replace Variable With Attribute", "Change Variable Type", "Split Variable", "Merge Variable"] FIELD_LEVEL_REFACTORINGS = ["Move Attribute", "Pull Up Attribute", "Move And Rename Attribute", "Push Down Attribute", "Replace Attribute", "Rename Attribute", "Extract Attribute", "Change Attribute Type"] OTHER_LEVEL_REFACTORINGS = ["Move Source Folder", "Change Package"] levelMap = {Level.NONE: [], Level.Class: CLASS_LEVEL_REFACTORINGS, Level.Method: METHOD_LEVEL_REFACTORINGS, Level.Field: FIELD_LEVEL_REFACTORINGS, Level.Variable: VARIABLE_LEVEL_REFACTORINGS, Level.Other: OTHER_LEVEL_REFACTORINGS} # -------------------------------- # DO NOT CHANGE FROM HERE ON # -------------------------------- if DROP_PROCESS_AND_AUTHORSHIP_METRICS: DROP_METRICS += PROCESS_AND_AUTHORSHIP_METRICS # Let's change some parameters (i.e., make them smaller) if this is a test run if TEST: N_ITER = 1 N_CV = 2 N_ITER_SVM = 1 N_CV_SVM = 2 N_CV_DNN = 2 CV_FEATURE_REDUCTION = 2
StarcoderdataPython
105855
from django.views.generic import TemplateView, ListView from .models import Spool from django.db.models import Q # Create your views here. class HomePageView(TemplateView): template_name = 'home.html' class SearchResultsView(ListView): model = Spool template_name = 'search_results.html' def get_queryset(self): query = self.request.GET.get('q') object_list = Spool.objects.filter( Q(tag=query) | Q(level=query) ) return object_list # to add an or filter see below example: # Q(tag='AS-L00-050') | Q(level='Level 00')
StarcoderdataPython
6499442
# pylint: disable=missing-module-docstring from dataclasses import dataclass from typing import List from league_history_collector.models.player import Player from league_history_collector.utils import CamelCasedDataclass @dataclass class Roster(CamelCasedDataclass): """Contains data for a roster.""" # Using Player objects will duplicate ID, name, and position, but this # helps account for position changes between seasons. starters: List[Player] bench: List[Player]
StarcoderdataPython
4944660
from aiohttp_requests import requests from typing import Optional from dotenv import load_dotenv import json import asyncio import os load_dotenv() APIKEY = os.getenv('APIKEY') def _simplify( url: str ) -> str: return url.replace('http://', '').replace('https://', '') def get_gif_id( url: str ) -> str: base_url = 'tenor.com/view/' url = _simplify(url.casefold()) if not url.startswith(base_url): return None gif_name = url.replace(base_url, '') gif_id = gif_name.split('-')[-1] return gif_id async def get_gif_url( gifid: str ) -> Optional[str]: r = await requests.get( f"https://api.tenor.com/v1/gifs?ids={gifid}&key={APIKEY}" ) if r.status == 200: # load the GIFs using the urls for the smaller GIF sizes gifs = json.loads(await r.text()) return gifs['results'][0]['media'][0]['gif']['url'] else: return None if __name__ == '__main__': loop = asyncio.get_event_loop() url = input("URL: ") gifid = get_gif_id(url) if gifid is None: print("That is not a tenor url!") else: gif_url = loop.run_until_complete(get_gif_url(gifid)) print(f"GIF URL: {gif_url}")
StarcoderdataPython
87683
<reponame>mikesmiley/lzh<gh_stars>1-10 { "targets": [ { "target_name": "lzh", "sources": [ "src/binding.cc", "src/lzh.c" ], "include_dirs": [ "<!(node -e \"require('nan')\")", "<!(node -e \"require('cpp-debug')\")" ] } ] }
StarcoderdataPython
5166020
<reponame>Eve-ning/reamber_base_py from tests.test import algorithms, base, osu, timing __all__ = ['algorithms', 'base', 'osu', 'timing']
StarcoderdataPython
11243013
#!/usr/bin/env python3 """ Describe in this sentence what this program does. Copyright (c) 2019 <NAME>. All rights reserved. """ import argparse import submodule.main def main(): program_options = get_program_options() x = submodule.main.yourfunction() # Continue here return x def get_program_options(): parser = argparse.ArgumentParser(description=__doc__) return parser.parse_args() if __name__ == '__main__': main()
StarcoderdataPython
8142220
<gh_stars>0 from sqlalchemy import create_engine from sqlalchemy.exc import IntegrityError class ClientWrapper(object): """ This class is a Wrapper to pull and push clients from/to the table openidclients in MySQL """ def __init__(self, db_uri): self._db_uri = db_uri def __setitem__(self, key, value): engine = create_engine(self._db_uri) try: engine.execute( "INSERT INTO openidclients (client_id,client_name,application_type," "redirect_uris,client_id_issued_at,client_secret," "client_secret_expires_at,response_types) VALUES ('{}','{}','{}','{}',{},'{}',{},'{}')".format( value.get("client_id"), value.get("client_name"), value.get("application_type"), "|~|".join(value.get("redirect_uris")), value.get("client_id_issued_at"), value.get("client_secret"), value.get("client_secret_expires_at"), "|~|".join(value.get("response_types")), ) ) except IntegrityError: engine.execute( "UPDATE openidclients SET client_name = '{}', application_type = '{}'," "redirect_uris = '{}', client_id_issued_at = {}, client_secret = '{}'," "client_secret_expires_at = {}, response_types = '{}' WHERE client_id = '{}'".format( value.get("client_name"), value.get("application_type"), "|~|".join(value.get("redirect_uris")), value.get("client_id_issued_at"), value.get("client_secret"), value.get("client_secret_expires_at"), "|~|".join(value.get("response_types")), value.get("client_id"), ) ) engine.dispose() def __getitem__(self, key): engine = create_engine(self._db_uri) user = engine.execute( "SELECT client_name,application_type,redirect_uris,client_id_issued_at," "client_secret,client_secret_expires_at,response_types FROM openidclients WHERE client_id = '{}'".format( key ) ).fetchone() if user is not None: res = { "client_id": key, "client_name": user[0], "application_type": user[1], "redirect_uris": user[2].split("|~|"), "client_id_issued_at": user[3], "client_secret": user[4], "client_secret_expires_at": user[5], "response_types": user[6].split("|~|"), } engine.dispose() return res else: engine.dispose() raise KeyError(key) def __delitem__(self, key): pass def __contains__(self, key): engine = create_engine(self._db_uri) user = engine.execute( "SELECT count(client_id) FROM openidclients WHERE client_id = '{}'".format( key ) ).fetchone() count = user[0] engine.dispose() return bool(count) def items(self): engine = create_engine(self._db_uri) users = engine.execute( "SELECT client_id,client_name,application_type,redirect_uris,client_id_issued_at," "client_secret,client_secret_expires_at,response_types FROM openidclients " ).fetchall() for user in users: yield user[0], { "client_id": user[0], "client_name": user[1], "application_type": user[2], "redirect_uris": user[3].split("|~|"), "client_id_issued_at": user[4], "client_secret": user[5], "client_secret_expires_at": user[6], "response_types": user[7].split("|~|"), } def pop(self, key, default=None): pass
StarcoderdataPython
4867235
<reponame>chunlin-pan/DYSTA import json import sympy class BasicNode(object): def __init__(self): self.time_complexity = sympy.Rational(1) self.__children = [] self.col = 0 self.line_number = 0 self.parent = None self.__type = self.__class__.__name__ pass def __iter__(self): for child in self.__children: yield child @property def children(self) -> []: return self.__children @children.setter def children(self, children): self.__children = children def add_children(self, children): if not children: return if type(children) is list: self.__children.extend(children) else: self.__children.append(children) def add_parent_to_children(self): for child in self.__children: child.parent = self child.add_parent_to_children() pass def copy_node_info_from(self, basic_node): self.time_complexity = basic_node.time_complexity self.__children = basic_node.children self.col = basic_node.col self.line_number = basic_node.line_number self.parent = basic_node.parent pass def to_dict(self): d = {'_type': self.__type, 'time_complexity': self.time_complexity, 'col': self.col, 'line_number': self.line_number, 'parent': None} children_list = [] for child in self.__children: children_list.append(child.to_dict()) d.update({'children': children_list}) return d def to_json(self): return json.dumps(self.to_dict(), indent=4, sort_keys=True) class CompilationUnitNode(BasicNode): def __init__(self): super().__init__() pass class ClassNode(BasicNode): def __init__(self): super().__init__() self.name = '' self.inher = [] self.vir_inher = [] pass class FuncDeclNode(BasicNode): def __init__(self): super().__init__() self.recursive = False self.name = '' self.parameter = [] pass def determine_recursion(self): que = [self] while que: node = que.pop(0) if isinstance(node, FuncCallNode): if node.name == self.name: self.recursive = True break for child in node: que.append(child) return self.recursive def to_dict(self): d = super().to_dict() d.update({'recursive': self.recursive}) d.update({'name': self.name}) d.update({'parameter': self.parameter}) return d class FuncCallNode(BasicNode): def __init__(self): super().__init__() self.name = '' self.parameter = [] pass def to_dict(self): d = super().to_dict() d.update({'name': self.name}) d.update({'parameter': self.parameter}) return d class VariableNode(BasicNode): def __init__(self): super().__init__() self.name = '' self.value = '' pass def to_dict(self): d = super().to_dict() d.update({'value': self.name}) return d class ArrayNode(BasicNode): def __init__(self): super().__init__() class ArrayNode(BasicNode): def __init__(self): super().__init__() self.array = [] pass def to_dict(self): d = super().to_dict() d.update({'array': self.array}) return d class ConstantNode(BasicNode): def __init__(self): super().__init__() self.value = 0 pass def to_dict(self): d = super().to_dict() d.update({'value': self.value}) return d class AssignNode(BasicNode): def __init__(self): super().__init__() self.__target = BasicNode() self.__value = BasicNode() pass @property def target(self): return self.__target @target.setter def target(self, target): self.__target = target self.add_children(self.target) @property def value(self): return self.__value @value.setter def value(self, value): self.__value = value self.add_children(self.value) def to_dict(self): d = super().to_dict() d.update({'target': self.target.to_dict()}) d.update({'value': self.value.to_dict()}) return d class Operator(BasicNode): def __init__(self): super().__init__() self.op = '' self.left = BasicNode() self.right = BasicNode() pass def to_dict(self): d = super().to_dict() d.update({'left': self.left.to_dict()}) d.update({'right': self.right.to_dict()}) return d class IfNode(BasicNode): def __init__(self): super().__init__() self.condition = BasicNode() self.true_stmt = [] self.false_stmt = [] pass def __iter__(self): for child in self.condition: yield child for child in self.true_stmt: yield child for child in self.false_stmt: yield child def to_dict(self): d = super().to_dict() d.update({'condition': self.condition.to_dict()}) d.update({'true': self.true_stmt}) d.update({'false': self.false_stmt}) return d class ForNode(BasicNode): def __init__(self): super().__init__() self.variable = None self.init = [] self.term = [] self.update = [] pass def to_dict(self): d = super().to_dict() d.update({'variable': self.variable}) init_list = [] for child in self.init: init_list.append(child.to_dict()) d.update({'init': init_list}) term_list = [] for child in self.init: term_list.append(child.to_dict()) d.update({'terminal': term_list}) update_list = [] for child in self.init: update_list.append(child.to_dict()) d.update({'update': update_list}) return d class ForeachNode(BasicNode): def __init__(self): super().__init__() self.variable = BasicNode() self.target = [] self.iter = [] pass def to_dict(self): d = super().to_dict() target_list = [] for child in self.target: target_list.append(child.to_dict()) d.update({'target': target_list}) iter_list = [] for child in self.iter: iter_list.append(child.to_dict()) d.update({'iter': iter_list}) d.update({'variable': self.variable}) return d class WhileNode(BasicNode): def __init__(self): super().__init__() self.cond = [] pass def to_dict(self): d = super().to_dict() cond_list = [] for clild in self.cond: cond_list.append(child.to_dict()) d.update({'cond': cond_list}) return d
StarcoderdataPython