seq_id
string
text
string
repo_name
string
sub_path
string
file_name
string
file_ext
string
file_size_in_byte
int64
program_lang
string
lang
string
doc_type
string
stars
int64
dataset
string
pt
string
api
list
7414775356
from __future__ import unicode_literals, print_function, division __author__ = "mozman <mozman@gmx.at>" import os import zipfile import random from datetime import datetime from .xmlns import etree, CN from .manifest import Manifest from .compatibility import tobytes, bytes2unicode, is_bytes, is_zipfile from .compatibility import is_stream, StringIO FNCHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' class FileObject(object): __slots__ = ['element', 'media_type', 'zipinfo'] def __init__(self, name, element, media_type=""): self.element = element self.media_type = media_type now = datetime.now().timetuple() self.zipinfo = zipfile.ZipInfo(name, now[:6]) self.zipinfo.compress_type = zipfile.ZIP_DEFLATED def tobytes(self): if hasattr(self.element, 'tobytes'): if self.media_type == 'text/xml': return self.element.tobytes(xml_declaration=True) else: return self.element.tobytes() else: return tobytes(self.element) @property def filename(self): return self.zipinfo.filename class FileManager(object): def __init__(self, zipname=None): self.directory = dict() self.zipname = zipname self.manifest = Manifest(self.get_bytes('META-INF/manifest.xml')) self.register('META-INF/manifest.xml', self.manifest, 'text/xml') def has_zip(self): if self.zipname is not None: return is_zipfile(self.zipname) return False def _open_bytestream(self): return open(self.zipname, 'rb') def tmpfilename(self, basefile=None): def randomname(count): return ''.join(random.sample(FNCHARS, count)) folder = "" if basefile is None else os.path.dirname(basefile) while True: filename = os.path.abspath(os.path.join(folder, randomname(8)+'.tmp')) if not os.path.exists(filename): return filename def register(self, name, element, media_type=""): self.directory[name] = FileObject(name, element, media_type) # 'mimetype' need not to be in the manifest.xml file, but it seems # not to break the vadility of the manifest file: # if name != 'mimetype: # self.manifest.add(name, media_type) self.manifest.add(name, media_type) def save(self, filename, backup=True): # always create a new zipfile write_to_memory = False if is_stream(filename): write_to_memory = True if write_to_memory: tmpfilename = filename else: tmpfilename = self.tmpfilename(filename) zippo = zipfile.ZipFile(tmpfilename, 'w', zipfile.ZIP_DEFLATED) self._tozip(zippo) zippo.close() if write_to_memory: # job done return if os.path.exists(filename): if backup: # existing document becomes the backup file bakfilename = filename+'.bak' # remove existing backupfile if os.path.exists(bakfilename): os.remove(bakfilename) os.rename(filename, bakfilename) else: # just remove the existing document os.remove(filename) # rename the new created document os.rename(tmpfilename, filename) self.zipname = filename def get_bytes(self, filename): """ Returns a byte stream or None. """ filecontent = None if self.has_zip(): bytestream = self._open_bytestream() zipfile_ = zipfile.ZipFile(bytestream, 'r') try: filecontent = zipfile_.read(filename) except KeyError: pass zipfile_.close() bytestream.close() return filecontent def get_text(self, filename, default=None): """ Retuns a str or 'default'. """ filecontent = self.get_bytes(filename) if filecontent is not None: return bytes2unicode(filecontent) else: return default def get_xml_element(self, filename): filecontent = self.get_bytes(filename) if filecontent: return etree.XML(filecontent) else: return None def _tozip(self, zippo): # mimetype file should be the first & uncompressed file in zipfile mimetype = self.directory.pop('mimetype') mimetype.zipinfo.compress_type = zipfile.ZIP_STORED zippo.writestr(mimetype.zipinfo, mimetype.tobytes()) processed = [mimetype.filename] for file in self.directory.values(): zippo.writestr(file.zipinfo, file.tobytes()) processed.append(file.filename) # push mimetype back to directory self.directory['mimetype'] = mimetype self._copy_zip_to(zippo, processed) def _copy_zip_to(self, newzip, ignore=[]): """ Copy all files like pictures and settings except the files in 'ignore'. """ if not self.has_zip(): return # nothing to copy try: bytestream = self._open_bytestream() except IOError: return # nothing to copy origzip = zipfile.ZipFile(bytestream) try: self._copy_from_zip_to_zip(origzip, newzip, ignore) finally: origzip.close() bytestream.close() @staticmethod def _copy_from_zip_to_zip(fromzip, tozip, ignore): for zipinfo in fromzip.filelist: if zipinfo.filename not in ignore: tozip.writestr(zipinfo, fromzip.read(zipinfo.filename)) def tobytes(self): iobuffer = StringIO() zippo = zipfile.ZipFile(iobuffer, 'w', zipfile.ZIP_DEFLATED) self._tozip(zippo) zippo.close() buffer = iobuffer.getvalue() del iobuffer return buffer def check_zipfile_for_oasis_validity(filename, mimetype): """ Checks the zipfile structure and least necessary content, but not the XML validity of the document. """ def check_manifest(stream): xmltree = etree.XML(stream) directory = dict([ (e.get(CN('manifest:full-path')), e) for e in xmltree.findall(CN('manifest:file-entry')) ]) for name in ('content.xml', 'meta.xml', 'styles.xml', '/'): if name not in directory: return False if bytes2unicode(mimetype) != directory['/'].get(CN('manifest:media-type')): return False return True assert is_bytes(mimetype) if not is_zipfile(filename): return False # The first file in an OpenDocumentFormat zipfile should be the uncompressed # mimetype file, in a regular zipfile this file starts at byte position 30. # see also OASIS OpenDocument Specs. Chapter 17.4 # LibreOffice ignore this requirement and opens all documents with # valid content (META-INF/manifest.xml, content.xml). with open(filename, 'rb') as f: buffer = f.read(38 + len(mimetype)) if buffer[30:] != b'mimetype'+mimetype: return False zf = zipfile.ZipFile(filename) names = zf.namelist() if 'META-INF/manifest.xml' in names: manifest = zf.read('META-INF/manifest.xml') else: manifest = None zf.close() if manifest is None: return False # meta.xml and styles.xml are not required, but I think they should for filename in ['content.xml', 'meta.xml', 'styles.xml', 'mimetype']: if filename not in names: return False result = check_manifest(manifest) return result
T0ha/ezodf
ezodf/filemanager.py
filemanager.py
py
7,721
python
en
code
61
github-code
1
[ { "api_name": "datetime.datetime.now", "line_number": 22, "usage_type": "call" }, { "api_name": "datetime.datetime", "line_number": 22, "usage_type": "name" }, { "api_name": "zipfile.ZipInfo", "line_number": 23, "usage_type": "call" }, { "api_name": "zipfile.ZIP_D...
23466715421
#!/usr/bin/python3 from brownie import CallMeChallenge from scripts.deploy import deploy from scripts.helpful_scripts import get_account from colorama import Fore # * colours green = Fore.GREEN red = Fore.RED blue = Fore.BLUE magenta = Fore.MAGENTA reset = Fore.RESET def print_colour(target, solved=False): if solved: print(f"{blue}Is complete: {green}{target.isComplete()}{reset}") else: print(f"{blue}Is complete: {red}{target.isComplete()}{reset}") def hack(contract_address=None, attacker=None): if not contract_address: target, _ = deploy() _, attacker = get_account() else: target = CallMeChallenge.at(contract_address) # print(target.address) print_colour(target, target.isComplete()) tx = target.callme({"from": attacker}) tx.wait(1) # print(f"{blue}Is complete: {green}{target.isComplete()}{reset}") print_colour(target, target.isComplete()) assert target.isComplete() == True def main(contract_address=None): if contract_address: hack(contract_address, get_account()) else: hack() if __name__ == "__main__": main()
Aviksaikat/Blockchain-CTF-Solutions
capturetheether/warmup/CallMe_DONE/scripts/hack.py
hack.py
py
1,151
python
en
code
1
github-code
1
[ { "api_name": "colorama.Fore.GREEN", "line_number": 8, "usage_type": "attribute" }, { "api_name": "colorama.Fore", "line_number": 8, "usage_type": "name" }, { "api_name": "colorama.Fore.RED", "line_number": 9, "usage_type": "attribute" }, { "api_name": "colorama.F...
39906386971
from sklearn.model_selection import train_test_split import tensorflow as tf import keras import os import numpy as np from PIL import Image import matplotlib.pyplot as plt from os import listdir from matplotlib import image import random from keras.utils import np_utils from keras import callbacks # batch_size = higher batch size could be better, but I haven't got enough gpu memory batch_size = 32 epochs = 50 train_dir = 'chest_xray/chest_xray/train/' val_folder = 'chest_xray/chest_xray/val/' test_folder = 'chest_xray/chest_xray/test/' pneumonia_str = "PNEUMONIA/" normal_str = "NORMAL/" train_p_dir = train_dir + pneumonia_str train_n_dir = train_dir + normal_str val_p_dir = val_folder + pneumonia_str val_n_dir = val_folder + normal_str test_p_dir = test_folder + pneumonia_str test_n_dir = test_folder + normal_str filenames = tf.io.gfile.glob(str('chest_xray/chest_xray/train/*/*')) filenames.extend(tf.io.gfile.glob(str('chest_xray/chest_xray/val/*/*'))) train_filenames, val_filenames = train_test_split(filenames, test_size=0.2) COUNT_NORMAL = len([filename for filename in train_filenames if "NORMAL" in filename]) print("Normal images count in training set: " + str(COUNT_NORMAL)) COUNT_PNEUMONIA = len([filename for filename in train_filenames if "PNEUMONIA" in filename]) print("Pneumonia images count in training set: " + str(COUNT_PNEUMONIA)) train_list_ds = tf.data.Dataset.from_tensor_slices(train_filenames) val_list_ds = tf.data.Dataset.from_tensor_slices(val_filenames) # Print few file names for f in train_list_ds.take(5): print(f.numpy()) # Check if there is good ratio between train and val photos number TRAIN_IMG_COUNT = tf.data.experimental.cardinality(train_list_ds).numpy() print("Training images count: " + str(TRAIN_IMG_COUNT)) VAL_IMG_COUNT = tf.data.experimental.cardinality(val_list_ds).numpy() print("Validating images count: " + str(VAL_IMG_COUNT)) CLASS_NAMES = np.array([str(tf.strings.split(item, os.path.sep)[-1].numpy())[2:-1] for item in tf.io.gfile.glob(str("chest_xray/chest_xray/train/*"))]) print(CLASS_NAMES) def get_label(file_path): # convert the path to a list of path components parts = tf.strings.split(file_path, os.path.sep) # The second to last is the class-directory return parts[-2] == "PNEUMONIA" IMAGE_SIZE = [180, 180] input_shape = (IMAGE_SIZE[0], IMAGE_SIZE[1], 3) def decode_img(img): # convert the compressed string to a 3D uint8 tensor img = tf.image.decode_jpeg(img, channels=3) # Use `convert_image_dtype` to convert to floats in the [0,1] range. img = tf.image.convert_image_dtype(img, tf.float32) # resize the image to the desired size. return tf.image.resize(img, IMAGE_SIZE) def process_path(file_path): label = get_label(file_path) # load the raw data from the file as a string img = tf.io.read_file(file_path) img = decode_img(img) return img, label AUTOTUNE = tf.data.experimental.AUTOTUNE train_ds = train_list_ds.map(process_path, num_parallel_calls=AUTOTUNE) val_ds = val_list_ds.map(process_path, num_parallel_calls=AUTOTUNE) test_list_ds = tf.data.Dataset.list_files(str('chest_xray/chest_xray/test/*/*')) TEST_IMAGE_COUNT = tf.data.experimental.cardinality(test_list_ds).numpy() test_ds = test_list_ds.map(process_path, num_parallel_calls=AUTOTUNE) test_ds = test_ds.batch(batch_size) def prepare_for_training(ds, cache=True, shuffle_buffer_size=1000): # This is a small dataset, only load it once, and keep it in memory. # use `.cache(filename)` to cache preprocessing work for datasets that don't # fit in memory. if cache: if isinstance(cache, str): ds = ds.cache(cache) else: ds = ds.cache() ds = ds.shuffle(buffer_size=shuffle_buffer_size) # Repeat forever ds = ds.repeat() ds = ds.batch(batch_size) # `prefetch` lets the dataset fetch batches in the background while the model # is training. ds = ds.prefetch(buffer_size=AUTOTUNE) return ds train_ds = prepare_for_training(train_ds) val_ds = prepare_for_training(val_ds) test_ds = prepare_for_training(test_ds)
jansowa/pneumonia-model
load_data.py
load_data.py
py
4,145
python
en
code
0
github-code
1
[ { "api_name": "tensorflow.io.gfile.glob", "line_number": 34, "usage_type": "call" }, { "api_name": "tensorflow.io", "line_number": 34, "usage_type": "attribute" }, { "api_name": "tensorflow.io.gfile.glob", "line_number": 35, "usage_type": "call" }, { "api_name": "...
40529127357
import bpy from bpy.types import NodeSocket from . import ProkitekturaContainerNode class ProkitekturaDemoAdvancedAttr(ProkitekturaContainerNode, bpy.types.Node): # make ProkitekturaNode the first super() in multiple inheritance # Optional identifier string. If not explicitly defined, the python class name is used. bl_idname = "ProkitekturaDemoAdvancedAttr" # Label for nice name display bl_label = "Advanced Attr" # Icon identifier bl_icon = 'SOUND' # list for iteration over advanced properties def declareProperties(self, propList): super().declareProperties(propList) propList.extend(( {"type":"std", "name":"countGroundLevel","check":"activateProp1", "text":"count ground level", "pythName":"groundLevel" }, {"type":"std", "name":"specificLevel", "check":"activateProp2", "text":"levels", "pythName":"levels" }, {"type":"adv", "name":"prop1", "check":"activateProp3", "text":"str", "pythName":"strProp" }, {"type":"adv", "name":"prop2", "check":"activateProp4", "text":"check", "pythName":"boolProp" }, {"type":"adv", "name":"prop3", "check":"activateProp5", "text":"int", "pythName":"intProp" }, {"type":"adv", "name":"prop4", "check":"activateProp6", "text":"levels", "pythName":"enumProp" } )) # list for iteration over advanced properties def declareCheckedSockets(self, socketList): super().declareCheckedSockets(socketList) socketList.extend(( {"type":"std", "class":"ProkitekturaSocketEnum", "text":"std1", "pythName":"std1"}, {"type":"std", "class":"ProkitekturaSocketEnum", "text":"std2", "pythName":"std2"}, {"type":"adv", "class":"ProkitekturaSocketEnum", "text":"adv1", "pythName":"adv1"}, {"type":"adv", "class":"ProkitekturaSocketEnum", "text":"adv2", "pythName":"adv2"} )) optionsList = ( ("all", "all levels", "All"), ("ground", "ground level only", "Ground level only"), ("allButLast", "all but last one", "All levels but the last one"), ("last", "last level", "The last level"), ("specific", "specific level", "Specific level"), ("even", "even levels", "Even levels"), ("odd", "odd levels", "Odd levels") ) propList = [] socketList = [] # examples of mandatory attributes countGroundLevel: bpy.props.BoolProperty(name = "Count Ground Level",description = "Shall we count the the ground level for the setting below",default = False) specificLevel: bpy.props.IntProperty(name = "Specific Level",description = "The number of the specific level",subtype = 'UNSIGNED',default = 1,min = 0) # examples of advanced properties prop1: bpy.props.StringProperty(name = "Property1", description = "Name for property1",default = 'prop1') prop2: bpy.props.BoolProperty(name = "Property2", description = "Name for property2",default = False) prop3: bpy.props.IntProperty(name = "Property3", description = "Value for property1",default = 1) prop4: bpy.props.EnumProperty(name = "Property4", description = "Level for property1",items = optionsList,default = "all") # example of activation checks for advanced properties activateProp1: bpy.props.BoolProperty(name = "Activate1", description = "activate1", default = True) activateProp2: bpy.props.BoolProperty(name = "Activate2", description = "activate2", default = True) activateProp3: bpy.props.BoolProperty(name = "Activate3", description = "activate3", default = False) activateProp4: bpy.props.BoolProperty(name = "Activate4", description = "activate4", default = False) activateProp5: bpy.props.BoolProperty(name = "Activate5", description = "activate5", default = False) activateProp6: bpy.props.BoolProperty(name = "Activate6", description = "activate6", default = False) def init(self, context): if not self.propList: self.declareProperties(self.propList) if not self.socketList: self.declareCheckedSockets(self.socketList) self.init_sockets_checked(context,self.socketList) super().init(context) def draw_buttons(self, context, layout): self.draw_buttons_common(context, layout) self.draw_buttons_checked(context, layout, self.propList) # self.draw_buttons_container(context, layout)
vvoovv/blosm-nodes
node/demoNode.py
demoNode.py
py
4,620
python
en
code
1
github-code
1
[ { "api_name": "bpy.types", "line_number": 7, "usage_type": "attribute" }, { "api_name": "bpy.props.BoolProperty", "line_number": 51, "usage_type": "call" }, { "api_name": "bpy.props", "line_number": 51, "usage_type": "attribute" }, { "api_name": "bpy.props.IntProp...
16625738937
""" GLPointCloudPlotItem.py - extension of pyqtgraph for plotting pointclouds This file implements an extension of pyqtgraph for visualizing PointClouds. Last update: 04/10/2013, Tadewos Somano(tadewos85@gmail.com) """ from OpenGL.GL import * from pyqtgraph.opengl.GLGraphicsItem import GLGraphicsItem __all__ = ['GLPointCloudPlotItem'] class GLPointCloudPlotItem(GLGraphicsItem): """ Plotting a 3D point cloud using pyqtgraph Parameters: points = a numpy array with shape [n,3] with the 3D-point coordinates color = a solid floating point (r,g,b,a), a is the alpha component colors = an array of (r,g,b,a) colors with the same size of points point_size = the dimension of each point in the visualization (in pixels) """ def __init__(self, **kwds): GLGraphicsItem.__init__(self) glopts = kwds.pop('glOptions', 'opaque') self.setGLOptions(glopts) self.points = None self.colors = None self.width = 1. self.color = (1.0,1.0,1.0,1.0) self.setData(**kwds) def setData(self, **kwds): """ Update the data displayed by this item """ args = ['points', 'color', 'colors', 'point_size' ] for k in kwds.keys(): if k not in args: raise Exception('Invalid keyword argument: %s (allowed: %s)'%(k, str(args))) for arg in args: if arg in kwds: setattr(self, arg, kwds[arg]) self.update() def initializeGL(self): pass def paint(self): """ Paint the pointcloud """ if self.points is None: return self.setupGLState() try: # Set the color state if self.colors is None: glColor4f(*self.color) else: glEnableClientState(GL_COLOR_ARRAY) glColorPointerf( self.colors ) glPointSize(self.point_size) # Draw an array of points glEnableClientState(GL_VERTEX_ARRAY) glVertexPointerf(self.points) glDrawArrays(GL_POINTS, 0, self.points.size/self.points.shape[-1]) finally: glDisableClientState(GL_VERTEX_ARRAY) if not self.colors is None: glDisableClientState(GL_COLOR_ARRAY)
GeoDTN/Communication-Technologies-Multimedia
GLPointCloudPlotItem.py
GLPointCloudPlotItem.py
py
2,544
python
en
code
0
github-code
1
[ { "api_name": "pyqtgraph.opengl.GLGraphicsItem.GLGraphicsItem", "line_number": 14, "usage_type": "name" }, { "api_name": "pyqtgraph.opengl.GLGraphicsItem.GLGraphicsItem.__init__", "line_number": 28, "usage_type": "call" }, { "api_name": "pyqtgraph.opengl.GLGraphicsItem.GLGraphics...
4538885674
# Helper functions for stochastic raytracer import numpy as np import pickle import matplotlib.pyplot as plt from scipy import interpolate from sklearn import preprocessing # Create a linear interpolant in each of the x, y, z directions def create_interpolant(xyz, g): fx = interpolate.RegularGridInterpolator(xyz, g[0]) fy = interpolate.RegularGridInterpolator(xyz, g[1]) fz = interpolate.RegularGridInterpolator(xyz, g[2]) return (fx, fy, fz) # def get_sdf_components(dict_name, xyz, space_subdivs): with open(dict_name, 'rb') as dictionary_file: r = pickle.load(dictionary_file) # Compute interpolant of the sdf phi = interpolate.RegularGridInterpolator(xyz, r) # Compute gradient (2/space_subdivs corresponds to the step size since r is space_subdivs subdivisions over an interval of 2) g = np.gradient(r, 2/space_subdivs) # Interpolant of gradient in each of x,y,z directions fx, fy, fz = create_interpolant(xyz, g) return (phi, fx, fy, fz) # Closest point operator def cp(points, phi, fx, fy, fz): """ points - a point in R^3 as a 3 ndarray, or multiple points as a 3xN ndarray phi - interpolant of the sdf given by the array fu - interpolant of gradient in the direction of u for u in [x,y,z] Returns the closest point on the level set 0 """ phi_points = phi(points).reshape(len(points), 1) # reshaping to (N, 1) for broadcasting with points_grad px, py, pz = fx(points), fy(points), fz(points) # the gradient of the generated points in each direction points_grad = np.transpose(np.array([px, py, pz])) closest = points - phi_points * points_grad return closest # Find the points traced on the plane when tracing back to camera def get_points_on_plane(cam, closest, k, n, D): """ See report for justification as to why this works! cam - location of camera closest - array of the closest points k - vector normal to plane n - normalized vector normal to plane D - scalar parameter of plane """ b = preprocessing.normalize(cam - closest) # Normalized vectors in direction of closest points to camera cos = b @ (-n) # Cosine of the angle between n (in other direction) and b, simply the dot product since they are unit vectors d_plane = (closest @ k + D)/np.linalg.norm(k) # Distance from point to plane that is the screen (using standard point to plane formula) scale = (d_plane/cos).reshape(-1,1) # Scale to find the vector from point to plane via vector to camera points_plane = closest + scale * b # Points on the return points_plane, scale # Rotate the screen such that the camera vector is along x, then remove the x dimension def get_rotation_matrix(k, cam): """ Note: This only works if the plane passes through the z-axis. It can be generalized be changing the value of u. k - vector normal to plane cam - position of camera Returns A_mat, the inverse of T_mat, and T_mat, which brings the camera to the x-axis. """ d_cam = np.linalg.norm(cam) # Distance from origin to camera D_alt = - k @ cam # Alternate D that create the plane Ax + By + Cz + D_alt = 0 and cam lies on the plane u = np.array([0, 0, -D_alt/k[2]]) # A point on this new plane (see notes above) v = u - cam # A vector perpendicular to cam beta = v*(d_cam/np.linalg.norm(v)) # Renormalize to have magnitude of cam gamma = np.cross(cam, beta)/d_cam # Another vector parallel to both cam and beta with magnitude of cam A_mat = np.transpose(np.array([cam, beta, gamma]))/d_cam # The matrix A which transform the standard coordinates with length d_cam to (cam, beta, gamma) T_mat = np.linalg.inv(A_mat) # The transform T as a matrix return (A_mat, T_mat) # Perform the rotation def rotate_and_kill_x(T_mat, points_plane): """ T_mat - the transformation (rotation) matrix points_plane - the points on the plane """ rotated = np.transpose(T_mat @ np.transpose(points_plane)) # Apply rotation T to align screen to x-axis scrn = rotated[:,1:] # Kill off x dimension return scrn # Get positions of unfilled pixels on the screen def get_not_filled_positions(not_filled, n_x, n_y): count_not_filled = np.sum(not_filled) not_filled_pos = np.zeros((count_not_filled, 2)) # list of unfilled pixels by position not_filled_counter = 0 # counter for not filled for it_x in range(n_x): for it_y in range(n_y): if not_filled[it_x][it_y] == 1: not_filled_pos[not_filled_counter] = np.array([it_x, it_y]) not_filled_counter += 1 return not_filled_pos # Get the direction in physical space of vectors from camera to missing pixels (this should be working) def get_directional_vectors(not_filled_pos, n_x, n_y, a_x, a_y, b_x, b_y, A_mat, T_mat, cam): """ not_filled - list of unfilled pixels All other parameters are standard as per its name Returns a list of unit vectors in physical space, which, when originating from cam, would pass through an unfilled pixel """ not_filled_counter = not_filled_pos.shape[0] # number of not filled pixels cam_in_flat = T_mat @ cam # location of camera in the rotated space not_filled_x_pos = not_filled_pos[:, 0] # x-coordinate in the screen (this corresponds to y-space) not_filled_y_pos = not_filled_pos[:, 1] # y-coordinate in the screen (this corresponds to z-space) # (approximate) real coordinates of pixels in rotated space unshifted_x = not_filled_x_pos*(b_x - a_x)/n_x + a_x + (b_x - a_x)/(2*n_x) # this last term is to re-center unshifted_y = not_filled_y_pos*(b_y - a_y)/n_y + a_y + (b_y - a_y)/(2*n_y) unshifted_coords = np.array([np.zeros(not_filled_counter), unshifted_x, unshifted_y]) cam_to_pixels_in_rot = unshifted_coords - np.repeat(cam_in_flat.reshape(3,1), not_filled_counter, axis=1) # vectors originating from camera to pixels ctp_in_rot_normal = cam_to_pixels_in_rot/np.linalg.norm(cam_to_pixels_in_rot, axis=0) # normalize ctp_in_space = A_mat @ ctp_in_rot_normal # return to physical space - these are the directions for sphere tracing return ctp_in_space # Perform sphere tracing given a vector def perform_sphere_tracing(cam, direction, phi, dist_threshold = 10e-5, t_max = 5): t = 0 # distance along the ray try: while(t < t_max): radius = phi(direction*t + cam) # radius at current point if radius < dist_threshold: break t += radius if t < t_max: return t else: return np.inf except: return np.inf # this will happen if the evaluation of the interpolant phi is outside the interpolation range
Bryden38/579_project_code
stochastic_raytracer_helper.py
stochastic_raytracer_helper.py
py
7,495
python
en
code
0
github-code
1
[ { "api_name": "scipy.interpolate.RegularGridInterpolator", "line_number": 11, "usage_type": "call" }, { "api_name": "scipy.interpolate", "line_number": 11, "usage_type": "name" }, { "api_name": "scipy.interpolate.RegularGridInterpolator", "line_number": 12, "usage_type": ...
73910447714
__author__ = 'Victor Olaya' __date__ = 'August 2012' __copyright__ = '(C) 2012, Victor Olaya' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' import os import codecs import datetime from processing.tools.system import userFolder from processing.core.ProcessingConfig import ProcessingConfig from qgis.core import QgsMessageLog from qgis.PyQt.QtCore import QCoreApplication class ProcessingLog: LOG_ERROR = 'ERROR' LOG_INFO = 'INFO' LOG_WARNING = 'WARNING' LOG_ALGORITHM = 'ALGORITHM' DATE_FORMAT = "%Y-%m-%d %H:%M:%S" recentAlgs = [] @staticmethod def logFilename(): logFilename = userFolder() + os.sep + 'processing.log' if not os.path.isfile(logFilename): logfile = codecs.open(logFilename, 'w', encoding='utf-8') logfile.write('Started logging at ' + datetime.datetime.now().strftime(ProcessingLog.DATE_FORMAT) + '\n') logfile.close() return logFilename @staticmethod def addToLog(msgtype, msg): try: # It seems that this fails sometimes depending on the msg # added. To avoid it stopping the normal functioning of the # algorithm, we catch all errors, assuming that is better # to miss some log info than breaking the algorithm. if msgtype == ProcessingLog.LOG_ALGORITHM: line = msgtype + '|' + datetime.datetime.now().strftime( ProcessingLog.DATE_FORMAT) + '|' \ + msg + '\n' logfile = codecs.open(ProcessingLog.logFilename(), 'a', encoding='utf-8') logfile.write(line) logfile.close() algname = msg[len('Processing.runalg("'):] algname = algname[:algname.index('"')] if algname not in ProcessingLog.recentAlgs: ProcessingLog.recentAlgs.append(algname) recentAlgsString = ';'.join(ProcessingLog.recentAlgs[-6:]) ProcessingConfig.setSettingValue( ProcessingConfig.RECENT_ALGORITHMS, recentAlgsString) else: if isinstance(msg, list): msg = '\n'.join([m for m in msg]) msgtypes = {ProcessingLog.LOG_ERROR: QgsMessageLog.CRITICAL, ProcessingLog.LOG_INFO: QgsMessageLog.INFO, ProcessingLog.LOG_WARNING: QgsMessageLog.WARNING, } QgsMessageLog.logMessage(msg, ProcessingLog.tr("Processing"), msgtypes[msgtype]) except: pass @staticmethod def getLogEntries(): entries = {} errors = [] algorithms = [] warnings = [] info = [] with open(ProcessingLog.logFilename()) as f: lines = f.readlines() for line in lines: line = line.strip('\n').strip() tokens = line.split('|') text = '' for i in range(2, len(tokens)): text += tokens[i] + '|' if line.startswith(ProcessingLog.LOG_ERROR): errors.append(LogEntry(tokens[1], text)) elif line.startswith(ProcessingLog.LOG_ALGORITHM): algorithms.append(LogEntry(tokens[1], tokens[2])) elif line.startswith(ProcessingLog.LOG_WARNING): warnings.append(LogEntry(tokens[1], text)) elif line.startswith(ProcessingLog.LOG_INFO): info.append(LogEntry(tokens[1], text)) entries[ProcessingLog.LOG_ALGORITHM] = algorithms return entries @staticmethod def getRecentAlgorithms(): recentAlgsSetting = ProcessingConfig.getSetting( ProcessingConfig.RECENT_ALGORITHMS) try: ProcessingLog.recentAlgs = recentAlgsSetting.split(';') except: pass return ProcessingLog.recentAlgs @staticmethod def clearLog(): os.unlink(ProcessingLog.logFilename()) @staticmethod def saveLog(fileName): entries = ProcessingLog.getLogEntries() with codecs.open(fileName, 'w', encoding='utf-8') as f: for k, v in entries.iteritems(): for entry in v: f.write('%s|%s|%s\n' % (k, entry.date, entry.text)) @staticmethod def tr(string, context=''): if context == '': context = 'ProcessingLog' return QCoreApplication.translate(context, string) class LogEntry: def __init__(self, date, text): self.date = date self.text = text
nextgis/nextgisqgis
python/plugins/processing/core/ProcessingLog.py
ProcessingLog.py
py
4,717
python
en
code
27
github-code
1
[ { "api_name": "processing.tools.system.userFolder", "line_number": 29, "usage_type": "call" }, { "api_name": "os.sep", "line_number": 29, "usage_type": "attribute" }, { "api_name": "os.path.isfile", "line_number": 30, "usage_type": "call" }, { "api_name": "os.path...
33402238582
import functools words=input().split() def validate(word): letters=[] for i in word: if i.upper() not in letters: letters.append(i.upper()) if len(letters)>3: return True return False if __name__=='__main__': answer1=list(filter(validate, words)) print(list(map(lambda a: a[0].swapcase()+a[1:], answer1))) answer2 = list(filter(lambda x: 'foo' in x, words)) print(len(functools.reduce(lambda a,b: a+b, answer2)))
Bulka148/IsmagilovB_11105
task004.py
task004.py
py
472
python
en
code
0
github-code
1
[ { "api_name": "functools.reduce", "line_number": 15, "usage_type": "call" } ]
17360106168
from datetime import datetime from sqlalchemy import Column from sqlalchemy.sql.sqltypes import Integer, Text, Date, Boolean from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Follower(Base): __tablename__ = 'follower' id = Column(Integer, primary_key=True) name = Column(Text) screen_name = Column(Text) twitter_id = Column(Integer) is_following = Column(Boolean) last_following = Column(Date) def __repr__(self): return "<Follower %s #%s>" % \ (self.name, self.twitter_id)
MickaelBergem/unfollower
models.py
models.py
py
573
python
en
code
6
github-code
1
[ { "api_name": "sqlalchemy.ext.declarative.declarative_base", "line_number": 7, "usage_type": "call" }, { "api_name": "sqlalchemy.Column", "line_number": 13, "usage_type": "call" }, { "api_name": "sqlalchemy.sql.sqltypes.Integer", "line_number": 13, "usage_type": "argument...
28416232124
#!/usr/bin/env python2 # [Ordered Dictionary for Py2.4 « Python recipes « ActiveState Code] # (http://code.activestate.com/recipes/576693/) from collections import OrderedDict od = OrderedDict() od["a"] = 1 od["b"] = 2 od["c"] = 4 od["d"] = 5 del od["a"] od["a"] = 3 for k, v in od.iteritems(): print("{},{}".format(k,v)) print("") # print: # b,2 # c,4 # d,5 # a,3 # OrderedDict is FIFO for k in reversed(od) : # reversed is not destructive print("{},{}".format(k,od[k])) print("") # a,3 # d,5 # c,4 # b,2 for k, v in od.iteritems(): print("{},{}".format(k,v)) print("") # b,2 # c,4 # d,5 # a,3
10sr/junks
python/ordereddict.py
ordereddict.py
py
627
python
en
code
0
github-code
1
[ { "api_name": "collections.OrderedDict", "line_number": 8, "usage_type": "call" } ]
13806395486
""" Yo que se ya """ import argparse import mido import logging from timeit import default_timer as timer from video import Video # from moviepy.editor import * DEBUG = True def print_d(msg): if DEBUG: print(msg) def maxSymNotes(notes): curr = max = 0 for note in notes: if note[2] == 0: curr+=1 if curr > max: max = curr else: curr = 0 return max def keep_only_highest(notes): curr = 0 highest = -1 highest_t = 0 h_v = 0 new = [] for (note, vel, t) in notes: if vel == 0: #stop note new += [(note, vel, t)] # v.addNote(note, vel, t) if t == 0: highest = max(highest, note) highest_t = t h_v = vel else: curr += t # print("now at: ", curr) if highest != -1: # print("adding:", highest) new += [(highest, h_v, highest_t)] highest = -1 highest_t = 0 h_v = 0 return new def misirlou(low = 52, c = 4, duration = 0.05, vel=10): """ Returns a sequence like misirlou kinda """ notes = ([low+0]*c*3 + [low+1]*c + [low+4]*c*2 + [low+5]*c*2 + [low+7]*c*3 + [low+8]*c + [low+11]*c*2 + [low+8]*c*2 + [low+7]*c*8) notes = (notes*2 + [low+8]*c*2 + [low+7]*c + [low+8]*c + [low+7]*c*2 + [low+5]*c*2 + [low+7]*c*2 + [low+5]*c + [low+7]*c + [low+5]*c*2 + [low+4]*c + [low+1]*c + [low+4]*c*8 + [low+7]*c*2 + [low+5]*c + [low+7]*c + [low+5]*c*2 + [low+4]*c*2 + [low+5]*c*2 + [low+4]*c + [low+5]*c + [low+4]*c*2 + [low+1]*c*2 + [low+0]*c*8) msgs = [] print(notes) # notes = [note for n in notes for note in n] for note in notes: msgs += [(note, vel, 0)] # start msgs += [(note, 0, duration)] # stop duration secs later return msgs def chromatic(lowest=52, highest=76, duration = 0.5, vel=10): """ chromatic scale from from lowest to highest """ notes = [n for n in range(lowest, highest+1)] msgs = [] # print(notes) # notes = [note for n in notes for note in n] for note in notes: msgs += [(note, vel, 0)] # start msgs += [(note, 0, duration)] # stop duration secs later return msgs def octaves(lowest=52, highest=76, duration = 0.5, vel=10): """ each octave of each note, lowest to highest """ notes = [] for n in range(12): note = lowest + n while note <= highest: notes += [note] note +=12 msgs = [] # print(notes) # notes = [note for n in notes for note in n] for note in notes: msgs += [(note, vel, 0)] # start msgs += [(note, 0, duration)] # stop duration secs later return msgs def merge_parse(mid, ignore = [6,7,8, 10, 11, 12]): """ Merges all tracks then returns the notes as [(notecode, vel, t)]. Tempo changes are translated to (-1,tempo,t), unknown messages to (-2,0,t) """ tracks = [] for i, track in enumerate(mid.tracks): print_d('Track {}: {}'.format(i, track.name)) if i not in ignore: tracks += [track] else: # fake track only to keep times print('(ignoring this one)') newtrack = mido.MidiTrack() for msg in track: newtrack.append(mido.Message('program_change', program=0, time=msg.time)) tracks += [newtrack] track = mido.merge_tracks(tracks) notes = [] bpm = 120 # default tempo = 500000 total_ticks = 0 for msg in track: total_ticks += msg.time if msg.is_meta: # print(msg) if msg.type == 'set_tempo': print('tempo msg:',msg) notes += [(-1, msg.tempo * args.slow, msg.time)] if tempo == 500000: tempo = msg.tempo * args.slow # only the first one else: # print('unknown meta msg:', msg) notes += [(-2, 0, msg.time)] # only add time elif msg.type == 'note_off': # convert to note_on with vel = 0 notes += [(msg.note, 0, msg.time)]#mido.tick2second(msg.time, mid.ticks_per_beat, tempo))] elif msg.type == 'note_on': notes += [(msg.note, msg.velocity, msg.time)]# mido.tick2second(msg.time, mid.ticks_per_beat, tempo))] else: # print('unknown msg:', msg) notes += [(-2, 0, msg.time)] return notes, tempo, total_ticks def print_notes(notes): all_notes = {n[0] for n in notes if n[0]>=0} # set, remove repetitions for note in sorted(all_notes): # sorted print(note) def parseMidi(mid, args): """ returns the notes as [(notecode, vel, t)] """ notes = [] bpm = 120 # default tempo = 500000 total_ticks = 0 for i, track in enumerate(mid.tracks): print_d('Track {}: {}'.format(i, track.name)) for msg in track: total_ticks += msg.time if i != args.track: break # TODO: this is bad!! if msg.is_meta: # print(msg) if msg.type == 'set_tempo': print('tempo msg:',msg) notes += [(-1, msg.tempo * args.slow, msg.time)] if tempo == 500000: tempo = msg.tempo * args.slow # only the first one # tempos += 1 # tempo = args.slow * msg.tempo # bpm = mido.tempo2bpm(tempo) # print("bpm: ", bpm) else: # print('unknown meta msg:', msg) notes += [(-2, 0, msg.time)] elif msg.type == 'note_off': notes += [(msg.note, 0, msg.time)]#mido.tick2second(msg.time, mid.ticks_per_beat, tempo))] elif msg.type == 'note_on': notes += [(msg.note, msg.velocity, msg.time)]# mido.tick2second(msg.time, mid.ticks_per_beat, tempo))] else: # print('unknown msg:', msg) notes += [(-2, 0, msg.time)] # video.addNote(msg.note, msg.velocity, mido.tick2second(msg.time)) # print(msg, msg.type) # print("note: ", msg.note, " vel: ", msg.velocity, "t: ", msg.time) # print('tempo changes:', tempos) return notes, tempo, total_ticks def main(args): program_times = {} do_chromatic = args.lowest_note != -1 # --------------------------------------------------------------------- # Parse the midi file: start = timer() mid = mido.MidiFile(args.midi_file) ignore = [] if args.track != -1: # print() ignore = [i for i in range(1,50) if i != args.track] print("ignore:",ignore) notes, tempo, total_ticks = merge_parse(mid, ignore) # else parseMidi(mid, args) end = timer() if args.print_track: print_notes(notes) exit(0) program_times['midi'] = end - start print("----------------------------\nMidi parsed in:", program_times['midi'], "s") #exit(0) # --------------------------------------------------------------------- # Initialize the video: start = timer() # rows = args.voices v = Video(args.clip, args.timestamps, rows=args.voices,cols=args.voices,text=do_chromatic,quality=args.quality,do_fade=True,only_audio=False) end = timer() program_times['initialize'] = end - start print("----------------------------\nVideo initialized in:", program_times['initialize'], "s") print(len(notes), "notes") #################### misirlou test: #notes = misirlou() #################### Chromatic test: # min 50 if do_chromatic: notes = chromatic(lowest = args.lowest_note, highest = 76, duration = 1) # notes = chromatic(lowest = args.lowest_note, highest = args.lowest_note+12, duration = 1) #################### Octaves test: # min 50 #notes = octaves(lowest = 50, highest = 96, duration = 0.5) # print(notes) # print('120 ticks = ', mido.tick2second(120, mid.ticks_per_beat, tempo)) # --------------------------------------------------------------------- # Add notes to video (generate clips) start = timer() curr = 0 # ticks curr_s = 0 # secs full = mid.length msg_freq = 0.01 next_msg = msg_freq desired_length = args.max_duration # sec for (note, vel, ticks) in notes: curr += ticks t = mido.tick2second(ticks, mid.ticks_per_beat, tempo) if not do_chromatic else ticks curr_s += t # just some feedback: # curr_s = mido.tick2second(curr, mid.ticks_per_beat, tempo) if curr_s >= next_msg*min(full, desired_length): # percentage advanced print("now at:", int(100*next_msg), "% processed: ", curr_s, "s") next_msg += msg_freq if curr_s >= desired_length: break if note == -1: # tempo change!! tempo = vel v.add_time(t) elif note == -2: # unknown msg, only add time v.add_time(t) elif curr_s>=args.initial_t: # normal notes v.addNote(note, vel, t) # this is the important stuff # tick_converted= mido.second2tick(full, mid.ticks_per_beat, tempo) # if tick_converted != full: # print('1??', tick_converted,total_ticks) if curr != total_ticks: print('Warning: Wrong ticks!!', curr, '!=', total_ticks) if v.current_time != full: print('Warning: Wrong time!! (video != expected):', v.current_time, '!=', full) # exit(1) if curr_s != full: print('Warning: Wrong time!! (current != expected):', curr_s, '!=', full) # exit(1) end = timer() program_times['clips'] = end - start print("----------------------------\nClips generated in:", program_times['clips'], "s") print("Compiling... ", end="") # --------------------------------------------------------------------- # Merge clips and save: start = timer() v.compile(args.output) end = timer() program_times['join'] = end - start print("----------------------------\nVideo joined in:", program_times['join'], "s") total_t = sum(program_times.values()) print('----------------------------\nTotal:', total_t, '\nTime in each step:') for name, t in program_times.items(): print(name, '->', 100 * t / total_t, "%") if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('-m', '--midi_file', help='Midi file', type=str, default="bumble_bee.mid") # TODO: permitir usar todas las tracks!! parser.add_argument('-tr', '--track', help='Number of the track from the midi to generate (default: all)', type=int, default=-1) parser.add_argument('-c', '--clip', help='original video', type=str, default="original/escala.mp4") # parser.add_argument('-i2', '--input2', help='Input video file 2', type=str, default="") parser.add_argument('-t', '--timestamps', help='timestamps for each note in the video', type=str, default="original/times-escala.csv") parser.add_argument('-o', '--output', help='output file', type=str, default="out.mp4") parser.add_argument('-v', '--voices', help='output file', type=int, default=1) parser.add_argument('-s', '--slow', help='slow mo (-s 2 makes it twice as slow)', type=float, default=1) parser.add_argument('-ini', '--initial_t', help='initial time (s) in midi to start video', type=float, default=0) parser.add_argument('-max', '--max_duration', help='max output duration', type=float, default=100000) parser.add_argument('-q', '--quality', help='reduce quality (e.g. 0.5)', type=float, default=1) parser.add_argument('-low', '--lowest_note', help='make a chromatic scale starting at this note', type=int, default=-1) parser.add_argument('-pt', '--print_track', help='Print the notes from the track', dest='print_track', action='store_true') parser.set_defaults(print_track=False) args = parser.parse_args() main(args)
nestor98/pymidi2vid
editor.py
editor.py
py
12,213
python
en
code
1
github-code
1
[ { "api_name": "mido.MidiTrack", "line_number": 122, "usage_type": "call" }, { "api_name": "mido.Message", "line_number": 124, "usage_type": "call" }, { "api_name": "mido.merge_tracks", "line_number": 126, "usage_type": "call" }, { "api_name": "timeit.default_timer...
34573074614
import os from os import getenv from dotenv import load_dotenv if os.path.exists("local.env"): load_dotenv("local.env") API_ID = int(getenv("API_ID", "6435225")) #optional API_HASH = getenv("API_HASH", "") #optional SUDO_USERS = list(map(int, getenv("SUDO_USERS", "").split())) OWNER_ID = int(getenv("OWNER_ID")) MONGO_URL = getenv("MONGO_URL") BOT_TOKEN = getenv("BOT_TOKEN", "") ALIVE_PIC = getenv("ALIVE_PIC", 'https://telegra.ph/file/3c52a01057865f7511168.jpg') ALIVE_TEXT = getenv("ALIVE_TEXT") PM_LOGGER = getenv("PM_LOGGER") LOG_GROUP = getenv("LOG_GROUP") GIT_TOKEN = getenv("GIT_TOKEN") #personal access token REPO_URL = getenv("REPO_URL", "https://github.com/ITZ-ZAID/ZAID-USERBOT") BRANCH = getenv("BRANCH", "master") #don't change STRING_SESSION1 = getenv("STRING_SESSION1", "") STRING_SESSION2 = getenv("STRING_SESSION2", "") STRING_SESSION3 = getenv("STRING_SESSION3", "") STRING_SESSION4 = getenv("STRING_SESSION4", "") STRING_SESSION5 = getenv("STRING_SESSION5", "") STRING_SESSION6 = getenv("STRING_SESSION6", "") STRING_SESSION7 = getenv("STRING_SESSION7", "") STRING_SESSION8 = getenv("STRING_SESSION8", "") STRING_SESSION9 = getenv("STRING_SESSION9", "") STRING_SESSION10 = getenv("STRING_SESSION10", "")
ITZ-ZAID/ZAID-USERBOT
config.py
config.py
py
1,235
python
en
code
167
github-code
1
[ { "api_name": "os.path.exists", "line_number": 5, "usage_type": "call" }, { "api_name": "os.path", "line_number": 5, "usage_type": "attribute" }, { "api_name": "dotenv.load_dotenv", "line_number": 6, "usage_type": "call" }, { "api_name": "os.getenv", "line_num...
26661499475
# -*- coding: utf-8 -*- from scrapy import Spider, Request, FormRequest from MobaiSpider.items import MobaispiderItem import numpy as np import json import time class MobaiSpider(Spider): name = 'mobai' # allowed_domains = ['mobike.com'] # start_urls = ['http://mobike.com/'] url = "https://mwx.mobike.com/mobike-api/rent/nearbyBikesInfo.do" headers = { 'charset': "utf-8", 'platform': "4", "referer": "https://servicewechat.com/wx80f809371ae33eda/144/page-frame.html", 'content-type': "application/x-www-form-urlencoded", 'user-agent': "MicroMessenger/6.5.4.1000 NetType/WIFI Language/zh_CN", 'host': "mwx.mobike.com", 'connection': "Keep-Alive", 'accept-encoding': "gzip", 'cache-control': "no-cache", } def start_requests(self): left = 32.2418440767 top = 118.5623931885 right = 31.8892185988 bottom = 119.0059661865 # 32.2418440767, 118.5623931885 左上 # 31.8892185988, 119.0059661865 右下 offset = 0.002 print("Start") self.total = 0 lat_range = np.arange(left, right, -offset) for lat in lat_range: lon_range = np.arange(top, bottom, offset) for lon in lon_range: self.total += 1 # self.get_nearby_bikes(lat, lon) item = MobaispiderItem() item['currentX'] = lat item['currentY'] = lon item['timestamp'] = time.time() yield FormRequest( self.url, headers=self.headers, formdata = { 'accuracy': '30', 'citycode': '025', 'errMsg': 'getLocation:ok', 'horizontalAccuracy': '30', 'latitude': str(lat), 'longitude': str(lon), 'speed': '-1', 'verticalAccuracy': '0', 'wxcode': '021Ay5DV0LUt2V1bRUDV0E8ICV0Ay5DN' }, callback=self.parse, meta={'item': item} ) def parse(self, response): print(response.text) data = json.loads(response.text) bikes = data['object'] if bikes: for bike in bikes: item = response.meta['item'] item['bikeIds'] = bike['bikeIds'] item['bikeType'] = bike['biketype'] item['distX'] = bike['distX'] item['distY'] = bike['distY'] item['distId'] = bike['distId'] item['distance'] = bike['distance'] item['boundary'] = bike['boundary'] yield item
jllan/spiders_mess
MobaiSpider/MobaiSpider/spiders/mobai.py
mobai.py
py
2,846
python
en
code
0
github-code
1
[ { "api_name": "scrapy.Spider", "line_number": 9, "usage_type": "name" }, { "api_name": "numpy.arange", "line_number": 41, "usage_type": "call" }, { "api_name": "numpy.arange", "line_number": 43, "usage_type": "call" }, { "api_name": "MobaiSpider.items.MobaispiderI...
42447368963
""" Preprocess the ISBI data set. """ __author__ = "Mike Pekala" __copyright__ = "Copyright 2015, JHU/APL" __license__ = "Apache 2.0" import argparse, os.path import numpy as np from scipy.stats.mstats import mquantiles import scipy.io import emlib def get_args(): """Command line parameters for the 'deploy' procedure. You will probably want to override the train/valid/test split to better suit your problem of interest... """ parser = argparse.ArgumentParser() parser.add_argument('-X', dest='dataFileName', type=str, required=True, help='EM data file') parser.add_argument('-Y', dest='labelsFileName', type=str, required=True, help='Ground truth labels for X') parser.add_argument('--train-slices', dest='trainSlices', type=str, default='range(10)', help='which slices to use for training') parser.add_argument('--valid-valid', dest='validSlices', type=str, default='range(10,20)', help='which slices to use for validation') parser.add_argument('--test-valid', dest='testSlices', type=str, default='range(20,30)', help='which slices to use for test') parser.add_argument('--brightness-quantile', dest='brightQuant', type=float, default=0.97, help='top quantile for non-membrane pixels.') parser.add_argument('--out-dir', dest='outDir', type=str, default='./', help='output directory') args = parser.parse_args() assert(args.brightQuant <= 1.0) assert(args.brightQuant > 0) # map strings to python objects (XXX: a cleaner way than eval) args.trainSlices = eval(args.trainSlices) args.validSlices = eval(args.validSlices) args.testSlices = eval(args.testSlices) return args if __name__ == "__main__": args = get_args(); #outDir = os.path.split(args.dataFileName)[0] if not os.path.isdir(args.outDir): os.mkdir(args.outDir) X = emlib.load_cube(args.dataFileName, np.uint8) Y = emlib.load_cube(args.labelsFileName, np.uint8) # remap Y labels from ISBI convention to membrane-vs-non-membrane Y[Y==0] = 1; # membrane Y[Y==255] = 0; # non-membrane # change type of Y so can use -1 as a value. Y = Y.astype(np.int8) Xtrain = X[args.trainSlices,:,:]; Ytrain = Y[args.trainSlices,:,:] Xvalid = X[args.validSlices,:,:]; Yvalid = Y[args.validSlices,:,:] Xtest = X[args.testSlices,:,:]; Ytest = Y[args.testSlices,:,:] # brightness thresholding thresh = mquantiles(np.concatenate((Xtrain[Ytrain==1], Xvalid[Yvalid==1])), args.brightQuant) pctOmitted = 100.0*np.sum(X > thresh) / np.prod(np.size(X)) print('[preprocess]: percent of pixels omitted by brightness filter: %0.2f' % pctOmitted) Ytrain[Xtrain > thresh] = -1 Yvalid[Xvalid > thresh] = -1 Ytest[Xtest > thresh] = -1 # EM data preprocessing # For now, do nothing. # save results np.save(os.path.join(outDir, 'Xtrain.npy'), Xtrain) np.save(os.path.join(outDir, 'Ytrain.npy'), Ytrain) np.save(os.path.join(outDir, 'Xvalid.npy'), Xvalid) np.save(os.path.join(outDir, 'Yvalid.npy'), Yvalid) np.save(os.path.join(outDir, 'Xtest.npy'), Xtest) np.save(os.path.join(outDir, 'Ytest.npy'), Ytest) print('[preprocess]: done!')
iscoe/coca
Experiments/CcT/preprocess.py
preprocess.py
py
3,303
python
en
code
6
github-code
1
[ { "api_name": "argparse.ArgumentParser", "line_number": 25, "usage_type": "call" }, { "api_name": "os.path.path.isdir", "line_number": 70, "usage_type": "call" }, { "api_name": "os.path.path", "line_number": 70, "usage_type": "attribute" }, { "api_name": "os.path"...
185545694
import pickle import struct from pathlib import Path from interact import interact as io from utils import Path_utils import samplelib.SampleHost from samplelib import Sample packed_faceset_filename = 'faceset.pak' class PackedFaceset(): VERSION = 1 @staticmethod def pack(samples_path): samples_dat_path = samples_path / packed_faceset_filename if samples_dat_path.exists(): io.log_info(f"{samples_dat_path} : file already exists !") io.input_bool("Press enter to continue and overwrite.", False) of = open(samples_dat_path, "wb") image_paths = Path_utils.get_image_paths(samples_path) samples = samplelib.SampleHost.load_face_samples(image_paths) samples_len = len(samples) samples_configs = [] for sample in samples: sample.filename = str(Path(sample.filename).relative_to(samples_path)) samples_configs.append ( sample.get_config() ) samples_bytes = pickle.dumps(samples_configs, 4) of.write ( struct.pack ("Q", PackedFaceset.VERSION ) ) of.write ( struct.pack ("Q", len(samples_bytes) ) ) of.write ( samples_bytes ) sample_data_table_offset = of.tell() of.write ( bytes( 8*(samples_len+1) ) ) #sample data offset table data_start_offset = of.tell() offsets = [] for sample in io.progress_bar_generator(samples, "Packing"): try: with open( samples_path / sample.filename, "rb") as f: b = f.read() offsets.append ( of.tell() - data_start_offset ) of.write(b) except: raise Exception(f"error while processing sample {sample.filename}") offsets.append ( of.tell() ) of.seek(sample_data_table_offset, 0) for offset in offsets: of.write ( struct.pack("Q", offset) ) of.seek(0,2) of.close() for filename in io.progress_bar_generator(image_paths,"Deleting"): Path(filename).unlink() @staticmethod def unpack(samples_path): samples_dat_path = samples_path / packed_faceset_filename if not samples_dat_path.exists(): io.log_info(f"{samples_dat_path} : file not found.") return samples = PackedFaceset.load(samples_path) for sample in io.progress_bar_generator(samples, "Unpacking"): with open(samples_path / sample.filename, "wb") as f: f.write( sample.read_raw_file() ) samples_dat_path.unlink() @staticmethod def load(samples_path): samples_dat_path = samples_path / packed_faceset_filename if not samples_dat_path.exists(): return None f = open(samples_dat_path, "rb") version, = struct.unpack("Q", f.read(8) ) if version != PackedFaceset.VERSION: raise NotImplementedError sizeof_samples_bytes, = struct.unpack("Q", f.read(8) ) samples_configs = pickle.loads ( f.read(sizeof_samples_bytes) ) samples = [] for sample_config in samples_configs: samples.append ( Sample (**sample_config) ) offsets = [ struct.unpack("Q", f.read(8) )[0] for _ in range(len(samples)+1) ] data_start_offset = f.tell() f.close() for i, sample in enumerate(samples): start_offset, end_offset = offsets[i], offsets[i+1] sample.set_filename_offset_size( str(samples_dat_path), data_start_offset+start_offset, end_offset-start_offset ) return samples
jem0101/BigSwag-SQA2022-AUBURN
TestOrchestrator4ML-main/resources/Data/supervised/GITLAB_REPOS/bytehackr@DeepFaceLab/samplelib/PackedFaceset.py
PackedFaceset.py
py
3,627
python
en
code
2
github-code
1
[ { "api_name": "interact.interact.log_info", "line_number": 22, "usage_type": "call" }, { "api_name": "interact.interact", "line_number": 22, "usage_type": "name" }, { "api_name": "interact.interact.input_bool", "line_number": 23, "usage_type": "call" }, { "api_nam...
6468869212
import pandas as pd import numpy as np import matplotlib.pyplot as plt import random def coin(): return random.randrange(0,2) def coins20(): X = [] for i in range(0,20): X.append(coin()) return X def mili(): E = [] for i in range(0,1000000): E.append(coins20()) return E mil_reps = mili() np.shape(mil_reps) def frqs(bs): data = [] a = 0.5 while a < 1.05: count = 0 for i in range(0,1000000): freq = 0.05*sum(bs[i]) if freq >= a: count = count+1 data.append(count) a = a+0.05 return data emp_freqs = frqs(mil_reps) emp_freqs aaaa = [a*0.05 for a in range(10,21)] plt.figure(1) plt.plot(aaaa, emp_freqs, label="Empirical freq. of observations", color="red", linestyle=':') plt.title(" 20 coin flips plot of frequency", color="blue") plt.xlabel("Alpha", color="blue") plt.ylabel("Frequency greater than alpha", color="blue") plt.legend() plt.show() def hoff(es): hoff_bound = [] for e in es: hoff_bound.append(np.exp(-2*20*(e-0.5)**2)*1000000) return hoff_bound def markov(aaaa): mark_bound=[] for a in aaaa: mark_bound.append(1000000*0.5/a); return mark_bound plt.figure(2) plt.plot(aaaa, emp_freqs, label="Empirical frequency", color="red", linestyle=':') plt.plot(aaaa, hoff(aaaa), label = "Hoeffding's Bound", color="blue", linestyle=':') plt.plot(aaaa, markov(aaaa), label = "Markov's Bound", color="green", linestyle=':') plt.title("Hoeffding's and Markov's Bounds", color="blue") plt.xlabel(" alpha", color="red") plt.ylabel("Frequency of average greater than alpha", color="red") plt.legend() plt.axis([0.5,1.0, 0,1000000]) #plt.legend(bbox_to_anchor=(0, -0.15, 1, 0), loc=2, borderaxespad=0) plt.legend() plt.show() #Handling Data locationTrain = 'IrisTrainML.dt' locationTest = 'IrisTestML.dt' dfTrain = pd.read_csv(locationTrain, header=None, sep=' ') dfTest = pd.read_csv(locationTest, header=None, sep=' ') dfTrainNO2 = dfTrain.loc[dfTrain[2] != 2] dfTestNO2 = dfTest.loc[dfTest[2] != 2] irisTrainX = dfTrainNO2.as_matrix(columns=[0,1]) irisTrainY = dfTrainNO2.as_matrix(columns=[2]) irisTestX = dfTestNO2.as_matrix(columns=[0,1]) irisTestY = dfTestNO2.as_matrix(columns=[2]) np.place(irisTrainY, irisTrainY == 0, -1) np.place(irisTestY, irisTestY == 0, -1) def bigX(inputData): if inputData.shape[0] > inputData.shape[1]: inputNoTilde = inputData else: inputNoTilde = np.transpose(inputData) ones = np.ones((len(inputNoTilde), 1), dtype=np.int) inputX = np.hstack((inputNoTilde, ones)) return inputX # Weights def initWeights(data): dimensions = data.shape[1] weights = np.zeros((dimensions)) return weights # Simple Gradient def gradOneSimple(x, y, w): yMULTx = np.multiply(y,x) wDOTx = np.dot(np.transpose(w),x) yMULTwtx = np.multiply(y, wDOTx) exp = np.exp(yMULTwtx) gradient = np.divide(yMULTx, 1 + exp) return gradient # Full Gradient def gradient(dataX, dataY, weights): accum = initWeights(dataX) n = len(dataY) for i in range(len(dataX)): gradient = gradOneSimple(dataX[i], dataY[i], weights) accum += gradient mean = np.divide(accum, n) gradient = np.negative(mean) return gradient # Function for updating weights. def updateWeights(oldWeights, direction, learningRate): newWeight = oldWeights + np.multiply(learningRate, direction) return newWeight # Logistic regression model. Implementation of LFD algorithm. def logReg(dataX, dataY, learningRate): X = bigX(dataX) weights = initWeights(X) for i in range(0,1000): g = gradient(X, dataY, weights) direction = -g weights = updateWeights(weights, direction, learningRate) return weights # Building affine linear model and reporting results. vectorWandB = logReg(irisTrainX, irisTrainY, 0.1) vectorW = np.transpose(vectorWandB[:-1]) b = vectorWandB[-1] print(vectorWandB) print('\n') print('Affine linear model build. w: ' + str(vectorW) + ' b: ' + str(b) + '\n') # Function that computes conditional probability using logistic regression. def conditionalProb(x, vectorW, b): wDOTx = np.dot(vectorW, x) y = wDOTx + b exp = np.exp(y) prob = np.divide(exp, 1 + exp) return prob # Function that classifies using the probability from logistic regression. def linearClassifier(x, vectorW, b ): y = -2 prob = conditionalProb(x, vectorW, b) if prob > 0.5: y = 1 else: y = -1 return y # Function that finds the number of wrong classifications for test data. def testingFalse(trainX, trainY, testX, testY, learningRate): trueCount = 0 falseCount = 0 weights = logReg(trainX, trainY, learningRate) vectorW = weights[:-1] b = weights[-1] for i in range(0,len(testY)): if linearClassifier(testX[i], vectorW, b) == testY.item(i): trueCount += 1 else: falseCount += 1 return falseCount # Finding the empirical loss of linear classification model with a zero-one loss # function. def zeroOneLoss(trainX, trainY, testX, testY, learningRate): N = len(testY) misClassified = testingFalse(trainX, trainY, testX, testY, learningRate) zeroOneLoss = (1/N)*misClassified return zeroOneLoss lossTrain = zeroOneLoss(irisTrainX, irisTrainY, irisTrainX, irisTrainY, 0.1) lossTest = zeroOneLoss(irisTrainX, irisTrainY, irisTestX, irisTestY, 0.1) print("0-1 loss of logistic regression linear classifier on training data: " + str(lossTrain)) print("0-1 loss of logistic regression linear classifier on testing data: " + str(lossTest))
Testosterol/Machine-Learning---Python-2
Assign2.py
Assign2.py
py
5,960
python
en
code
0
github-code
1
[ { "api_name": "random.randrange", "line_number": 7, "usage_type": "call" }, { "api_name": "numpy.shape", "line_number": 22, "usage_type": "call" }, { "api_name": "matplotlib.pyplot.figure", "line_number": 40, "usage_type": "call" }, { "api_name": "matplotlib.pyplo...
39605975671
import pygame as pg from pygame.math import Vector2 from src.camera import Camera from src.game_objects.abstract.tile import Tile from src.game_objects.movable_tile import MovableTile from src.game_objects.selection_box import SelectionBox from src.game_objects.static_tile import StaticTile from src.graphics import SpriteSheet from src.main_loop import MainLoop from src.map import Map from src.settings.constants import ( CAPTION, SCREEN_SIZE, FPS, TILE_SIZE, ACTIVATE_SCROLLING_BORDERS, ACTIVATE_TEST_GRID, BG_COLOR, ) from src.settings.controllers import CONTROLLERS_CAMERA from src.settings.paths import * class GameCore(MainLoop): def __init__(self): super().__init__(CAPTION, SCREEN_SIZE, FPS) self.image_manager = SpriteSheet() self.selection_box = pg.sprite.GroupSingle(None) self.nature_tiles = pg.sprite.Group() self.player1_villages = pg.sprite.Group() self.player1_units = pg.sprite.Group() self.search_order = [ self.nature_tiles, self.player1_villages, self.player1_units, ] self.create_objects() self.mouse_handlers.append(self.handle_mouse_event) def create_objects(self): self._create_test_map() self._create_camera() def _create_camera(self): self.camera = Camera(self.map.width, self.map.height, ACTIVATE_SCROLLING_BORDERS) for key in CONTROLLERS_CAMERA.values(): self.add_up_down_key_handlers(self.camera, key) def _draw_grid(self): width, height = self.main_surface.get_size() for x in range(0, width, TILE_SIZE): pg.draw.line(self.main_surface, "darkgrey", (x, 0), (x, height)) for y in range(0, height, TILE_SIZE): pg.draw.line(self.main_surface, "darkgrey", (0, y), (width, y)) def _create_test_map(self): self.map = Map(TEST_MAP) for row, tiles in enumerate(self.map.get_data): for column, tile in enumerate(tiles): if tile == "1": t = StaticTile(Vector2(column, row), self.image_manager.get_image("grass")) self.nature_tiles.add(t) self.visible_sprites.add(t, layer=0) if tile == "0": t = StaticTile(Vector2(column, row), self.image_manager.get_image("water")) self.nature_tiles.add(t) self.visible_sprites.add(t, layer=0) if tile == "8": t = StaticTile(Vector2(column, row), self.image_manager.get_image("grass")) self.nature_tiles.add(t) self.visible_sprites.add(t, layer=0) t = MovableTile(Vector2(column, row), self.image_manager.get_image("farmer")) self.player1_units.add(t) self.visible_sprites.add(t, layer=2) if tile == "9": # TODO: Remove double sprite on one coordinate t = StaticTile(Vector2(column, row), self.image_manager.get_image("grass")) self.nature_tiles.add(t) self.visible_sprites.add(t, layer=0) t = Tile(Vector2(column, row), self.image_manager.get_image("village")) self.player1_villages.add(t) self.visible_sprites.add(t, layer=1) def handle_mouse_event(self, type_, pos, button=0): pos = self.camera.apply(pos) if type_ == pg.MOUSEMOTION: pass elif type_ == pg.MOUSEBUTTONDOWN: self.handle_mouse_down(pos, button) elif type_ == pg.MOUSEBUTTONUP: pass def left_click(self, clicked_sprite): # select if self.selection_box.sprite is None: sb = SelectionBox(clicked_sprite) self.selection_box.add(sb) self.visible_sprites.add(sb) # unselect elif self.selection_box.sprite.target is clicked_sprite: self.selection_box.sprite.kill() def right_click(self, clicked_sprite): if self.selection_box.sprite is not None: if isinstance(self.selection_box.sprite.target, MovableTile): self.selection_box.sprite.target.move_to(clicked_sprite) def handle_mouse_down(self, mouse_pos, mouse_button): def mouse_button_function(): """Call the appropriate click function with the clicked_sprite parameter depending on the button""" return { 1: self.left_click, 3: self.right_click, }.get(mouse_button, lambda _: None)(clicked_sprite) clicked_sprite = None for group in self.search_order: for sprite in group: if sprite.check_click(mouse_pos) is True: clicked_sprite = sprite break if clicked_sprite is not None: mouse_button_function() def draw(self): for sprite in self.visible_sprites: self.main_surface.blit(sprite.image, self.camera.apply(sprite)) if ACTIVATE_TEST_GRID is True: self._draw_grid() def update(self): self.main_surface.fill(BG_COLOR) super().update() self.camera.update() if __name__ == '__main__': GameCore().run()
tmcgroul/GPD-4X
src/game_core.py
game_core.py
py
5,377
python
en
code
1
github-code
1
[ { "api_name": "src.main_loop.MainLoop", "line_number": 25, "usage_type": "name" }, { "api_name": "src.settings.constants.CAPTION", "line_number": 27, "usage_type": "argument" }, { "api_name": "src.settings.constants.SCREEN_SIZE", "line_number": 27, "usage_type": "argument...
244144573
__author__ = 'nipunbatra' import numpy as np import pandas as pd def read_df(): df = pd.read_csv("../data/input/main-data.csv",index_col=0) dfc = df.copy() df = df.drop(871) df = df.drop(1169) w=df[['aggregate_%d' %i for i in range(1,13)]] df = df.ix[w[w>0].dropna().index] features_individual = {'fraction':["fraction_%d" % i for i in range(1, 25)], 'area': 'area', 'autocorr':'autocorr', 'month': ["aggregate_%d" % i for i in range(1, 13)], 'occupants': 'total_occupants', 'rooms': 'num_rooms', 'seasonal_12':['stdev_seasonal_12','max_seasonal_12'], 'trend_12':['stdev_trend_12','max_trend_12'], 'seasonal_daily':['stdev_seasonal_daily','max_seasonal_daily'], 'trend_daily':['stdev_trend_daily','max_trend_daily'], 'seasonal_weekly':['stdev_seasonal_weekly','max_seasonal_weekly'], 'trend_weekly':['stdev_trend_weekly','max_trend_weekly'], 'cluster_big':'cluster_big', 'cluster_small':'cluster_small', 'diff':['lt_500','bet_500_1000','gt_1000'], 'temp':'temperature_corr', 'week':["fraction_%d" % i for i in range(1, 8)], #'disag_fridge':'disag_fridge'} 'mins_hvac':'mins_hvac', 'month_extract':['variance','ratio_min_max', 'difference_min_max', 'ratio_difference_min_max']} from itertools import combinations features_dict = {} for feature_size in range(1,max(4,len(features_individual))): combinations_size_n = list(combinations(features_individual.keys(), feature_size)) for com in combinations_size_n: features_dict[com] = np.hstack([features_individual[x] for x in com]).tolist() national_average = {"fridge": 0.07, "hvac": 0.18, 'wm': 0.01, 'furnace': 0.09, 'dw': 0.02, 'dr': 0.04, 'light': .11} def scale_0_1(ser, minimum=None, maximum=None): if minimum is not None: pass else: minimum = ser.min() maximum = ser.max() return (ser-minimum).div(maximum-minimum) #Normalising features max_aggregate = df[["aggregate_%d" % i for i in range(1, 13)]].max().max() min_aggregate = df[["aggregate_%d" % i for i in range(1, 13)]].min().min() df[["aggregate_%d" % i for i in range(1, 13)]] = scale_0_1(df[["aggregate_%d" % i for i in range(1, 13)]], min_aggregate, max_aggregate) max_weekly = df[["daily_usage_%d" % i for i in range(1, 8)]].max().max() min_weekly = df[["daily_usage_%d" % i for i in range(1, 8)]].min().min() df[["daily_usage_%d" % i for i in range(1, 8)]] = scale_0_1(df[["daily_usage_%d" % i for i in range(1, 8)]], min_weekly, max_weekly) df['area'] = scale_0_1(df['area']) df['num_rooms'] = scale_0_1(df['num_rooms']) df['total_occupants'] = scale_0_1(df['total_occupants']) df['mins_hvac'] = scale_0_1(df['mins_hvac']) # Adding new feature aa = df[["aggregate_%d" % i for i in range(1, 13)]].copy() df['variance'] = df[["aggregate_%d" % i for i in range(1, 13)]].var(axis=1) df['ratio_min_max'] = aa.min(axis=1)/aa.max(axis=1) df['difference_min_max'] = aa.max(axis=1)-aa.min(axis=1) df['ratio_difference_min_max'] = (aa.max(axis=1)-aa.min(axis=1)).div(aa.max(axis=1)) # Adding skew and kurtosis on monthly aggregate k = {} s ={} p_25 ={} p_75 = {} p_50 = {} for home in df.index: signal = df.ix[home][['aggregate_%d' %i for i in range(1, 13)]] k[home] = signal.kurtosis() s[home] = signal.skew() p_25[home] =np.percentile(signal, 25) p_50[home] =np.percentile(signal, 50) p_75[home] = np.percentile(signal, 75) df['skew'] = pd.Series(s) df['kurtosis']=pd.Series(k) df['p_25']=pd.Series(p_25) df['p_50'] =pd.Series(p_50) df['p_75']=pd.Series(p_75) for col in ["stdev_trend_12","stdev_seasonal_12","max_seasonal_12","max_trend_12", "stdev_trend_daily","stdev_seasonal_daily","max_seasonal_daily","max_trend_daily", "stdev_trend_weekly","stdev_seasonal_weekly","max_seasonal_weekly","max_trend_weekly","disag_fridge", 'stdev_trend','stdev_seasonal','max_seasonal','max_trend', 'cluster_small','cluster_big', 'temperature_corr', 'variance', 'ratio_min_max','ratio_difference_min_max','seasonal_energy_5','seasonal_energy_6', 'seasonal_energy_7','seasonal_energy_8','seasonal_energy_9','seasonal_energy_10', 'fft_1','fft_2','fft_3','fft_4','fft_5','skew','kurtosis','p_25','p_50','p_75']: if col in df.columns: df[col] = scale_0_1(df[col]) dfs = {} total = features_dict.values()[np.array(map(len, features_dict.values())).argmax()] for appliance in ['fridge','hvac','dr','light','dw','wm']: temp=df.ix[df[['%s_%d' %(appliance, i) for i in range(1,13)]].dropna().index] dfs[appliance] =temp.ix[temp[total].dropna().index] appliance_min = {'fridge':5,'hvac':5,'wm':0,'dw':0,'dr':0,'light':0} all_homes = { 'dw':[ 94, 370, 545, 624, 2156, 2242, 2814, 2829, 3723, 4767, 5357,6636, 6910, 7769, 9934], 'wm':[ 94, 370, 545, 624, 2156, 2242, 2814, 3367, 3456, 3723, 3967, 5357, 7769, 9654, 9922, 9934], 'hvac':[ 26, 94, 370, 410, 545, 624, 1283, 1642, 1953, 2129, 2156, 2242, 2470, 2814, 2829, 3367, 3456, 3723, 3967, 4767, 5218, 5357, 5371, 5746, 5785, 5814, 6072, 6636, 6836, 6910, 7731, 7769, 7866, 9609, 9654, 9922, 9933, 9934], 'fridge':[ 94, 370, 410, 545, 624, 1953, 2156, 2242, 2814, 2829, 3367, 3456, 3723, 3967, 4767, 5357, 5371, 6072, 6636, 6910, 7769, 7866], 'light':df.index.tolist(), #[ 624, 1334, 2814, 2925, 2986, 3367, 3456, 3482, 3723, 3967, 4732, # 4767, 5814, 5817, 6072, 6266, 6910, 7016, 7429, 7731, 7769, 7866, # 8317, 8626, 9052, 9654, 9922], 'dr':[ 94, 370, 410, 2156, 2242, 2814, 3456, 3723, 4767, 5785, 5814, 6072, 6636, 6836, 7731, 7769, 7866, 9654, 9922, 9933, 9982] } all_homes = {appliance:dfs[appliance].index for appliance in dfs.keys()} all_homes['fridge'] = np.array(np.setdiff1d(all_homes['fridge'], [26, 1334, 1642, 2233,3482,6836, 5746, 7016, 9982])) ### HVAC ### # 1334 is not used in some months, ideally we can do signal processing and remove it, # Currently removed it manually; similarly 94 all_homes['hvac'] = np.array(np.setdiff1d(all_homes['hvac'], [94, 252, 1334, 2925, 2986, 3482, 4732, 5439, 6266, 8626, 1800, 2233, 5817, 7016, 7429, 8317, 9052, 9982])) all_homes['dw'] = np.array(np.setdiff1d(all_homes['dw'],[2233, 7016])) all_homes['wm'] = [ 94, 370, 545, 624, 2156, 2242, 2814, 3367, 3456, 3723, 3967, 5357, 7769, 9654, 9922, 9934] all_homes['light']=[624, 1334, 3367, 3456, 3723, 5814, 6072, 6910, 7769, 7866, 9654, 9922] return df, dfc, all_homes, appliance_min, national_average
nipunbatra/Gemello
code/create_df.py
create_df.py
py
7,664
python
en
code
18
github-code
1
[ { "api_name": "pandas.read_csv", "line_number": 9, "usage_type": "call" }, { "api_name": "itertools.combinations", "line_number": 50, "usage_type": "call" }, { "api_name": "numpy.hstack", "line_number": 52, "usage_type": "call" }, { "api_name": "numpy.percentile",...
17114049075
from django.urls import reverse_lazy from django.views.generic.edit import FormView from forum.forms import ContactForm class ContactView(FormView): template_name = 'pages/contact.html' form_class = ContactForm success_url = reverse_lazy('forum:home') def form_valid(self, form): form.send_email() return super().form_valid(form)
Projectca-r/it
itacademy-django/forum/views/contact.py
contact.py
py
366
python
en
code
0
github-code
1
[ { "api_name": "django.views.generic.edit.FormView", "line_number": 7, "usage_type": "name" }, { "api_name": "forum.forms.ContactForm", "line_number": 9, "usage_type": "name" }, { "api_name": "django.urls.reverse_lazy", "line_number": 10, "usage_type": "call" } ]
1402617285
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWidgets import QFileDialog, QMessageBox from PyQt5.QtCore import QTimer import sys import time import csv import os import winsound from libs import Track, getShiftRPM, fuelSavingOptimiser, rollOut from libs.IDDU import IDDUThread, IDDUItem from libs.auxiliaries import importExport import numpy as np from libs.setReferenceLap import setReferenceLap from libs.MyLogger import MyLogger import iDDU def decorator(fn): def wrapper(*args, **kwargs): fn_results = fn(*args, **kwargs) return fn_results return wrapper class iDDUGUIThread(IDDUThread): def __init__(self, rate): IDDUThread.__init__(self, rate) def run(self): Gui() def stop(self): QtWidgets.QApplication.exit() class Stream(QtCore.QObject): newText = QtCore.pyqtSignal(str) def write(self, text): self.newText.emit(str(text)) class Gui(IDDUItem): @decorator def closeEvent(self, event): reply = QMessageBox.question(self.iDDU, 'Close iDDU?', "Are you sure to quit iDDU?", QMessageBox.Yes, QMessageBox.No) if reply == QMessageBox.Yes: print("Closing iDDU...") event.accept() # sys.exit(self.exec_()) self.db.done = True else: event.ignore() def __init__(self): IDDUItem.__init__(self) import sys app = QtWidgets.QApplication(sys.argv) iDDU = QtWidgets.QWidget() iDDU.closeEvent = self.closeEvent if os.environ['COMPUTERNAME'] == 'MARC-SURFACE': iDDU.move(self.db.config['rGUI'][0], self.db.config['rGUI'][1]) else: iDDU.move(0, 1080) # change console output to iDDU print window sys.stdout = Stream(newText=self.onUpdateText) sys.stderr = Stream(newText=self.onUpdateText) MyLogger.consoleHandler.setStream(sys.stdout) self.setupUi(iDDU) iDDU.show() # make QTimer iDDU.qTimer = QTimer() # set interval to 1 s iDDU.qTimer.setInterval(1000) # 1000 ms = 1 s # connect timeout signal to signal handler iDDU.qTimer.timeout.connect(self.refreshGUI) # start timer iDDU.qTimer.start() self.getJoystickList() sys.exit(app.exec_()) def setupUi(self, iDDU): self.iDDU = iDDU self.iDDU.setObjectName("iDDU") # self.iDDU.resize(798, 448) self.iDDU.setFixedSize(798, 448) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(self.db.dir + "/files/gui/iRacing_Icon.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off) iDDU.setWindowIcon(icon) self.tabWidget = QtWidgets.QTabWidget(iDDU) self.tabWidget.setGeometry(QtCore.QRect(10, 10, 781, 431)) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tabWidget.sizePolicy().hasHeightForWidth()) self.tabWidget.setSizePolicy(sizePolicy) self.tabWidget.setMaximumSize(QtCore.QSize(781, 16777215)) self.tabWidget.setObjectName("tabWidget") self.tabGeneral = QtWidgets.QWidget() self.tabGeneral.setObjectName("tabGeneral") self.groupBox_2 = QtWidgets.QGroupBox(self.tabGeneral) self.groupBox_2.setGeometry(QtCore.QRect(20, 350, 281, 51)) self.groupBox_2.setObjectName("groupBox_2") self.pushButton_StartDDU = QtWidgets.QPushButton(self.groupBox_2) self.pushButton_StartDDU.setGeometry(QtCore.QRect(40, 20, 75, 23)) self.pushButton_StartDDU.setToolTip("") self.pushButton_StartDDU.setObjectName("pushButton_StartDDU") self.pushButton_StopDDU = QtWidgets.QPushButton(self.groupBox_2) self.pushButton_StopDDU.setGeometry(QtCore.QRect(160, 20, 75, 23)) self.pushButton_StopDDU.setObjectName("pushButton_StopDDU") self.groupBox_3 = QtWidgets.QGroupBox(self.tabGeneral) self.groupBox_3.setGeometry(QtCore.QRect(10, 10, 291, 191)) self.groupBox_3.setObjectName("groupBox_3") self.spinBoxRaceLaps = QtWidgets.QSpinBox(self.groupBox_3) self.spinBoxRaceLaps.setGeometry(QtCore.QRect(140, 20, 101, 22)) self.spinBoxRaceLaps.setMaximum(10000) self.spinBoxRaceLaps.setSingleStep(1) self.spinBoxRaceLaps.setObjectName("spinBoxRaceLaps") self.label_8 = QtWidgets.QLabel(self.groupBox_3) self.label_8.setGeometry(QtCore.QRect(20, 20, 81, 16)) self.label_8.setObjectName("label_8") self.label_14 = QtWidgets.QLabel(self.groupBox_3) self.label_14.setGeometry(QtCore.QRect(20, 80, 101, 16)) self.label_14.setObjectName("label_14") self.doubleSpinBox_P2PActivations = QtWidgets.QDoubleSpinBox(self.groupBox_3) self.doubleSpinBox_P2PActivations.setGeometry(QtCore.QRect(140, 110, 101, 22)) self.doubleSpinBox_P2PActivations.setPrefix("") self.doubleSpinBox_P2PActivations.setSuffix("") self.doubleSpinBox_P2PActivations.setDecimals(0) self.doubleSpinBox_P2PActivations.setMaximum(1000.0) self.doubleSpinBox_P2PActivations.setSingleStep(1.0) self.doubleSpinBox_P2PActivations.setProperty("value", self.db.config['P2PActivationsGUI']) self.doubleSpinBox_P2PActivations.setObjectName("doubleSpinBox_P2PActivations") self.doubleSpinBox_DRSActivations = QtWidgets.QDoubleSpinBox(self.groupBox_3) self.doubleSpinBox_DRSActivations.setGeometry(QtCore.QRect(140, 80, 101, 22)) self.doubleSpinBox_DRSActivations.setPrefix("") self.doubleSpinBox_DRSActivations.setSuffix("") self.doubleSpinBox_DRSActivations.setDecimals(0) self.doubleSpinBox_DRSActivations.setMaximum(1000.0) self.doubleSpinBox_DRSActivations.setSingleStep(1.0) self.doubleSpinBox_DRSActivations.setProperty("value", self.db.config['DRSActivationsGUI']) self.doubleSpinBox_DRSActivations.setObjectName("doubleSpinBox_DRSActivations") self.checkBox_MapHighlight = QtWidgets.QCheckBox(self.groupBox_3) self.checkBox_MapHighlight.setEnabled(True) self.checkBox_MapHighlight.setGeometry(QtCore.QRect(20, 150, 251, 17)) self.checkBox_MapHighlight.setChecked(self.db.config['MapHighlight']) self.checkBox_MapHighlight.setObjectName("checkBox_MapHighlight") self.label_15 = QtWidgets.QLabel(self.groupBox_3) self.label_15.setGeometry(QtCore.QRect(20, 110, 101, 16)) self.label_15.setObjectName("label_15") self.label_NStintLaps = QtWidgets.QLabel(self.groupBox_3) self.label_NStintLaps.setGeometry(QtCore.QRect(20, 50, 81, 16)) self.label_NStintLaps.setObjectName("label_NStintLaps") self.spinBoxStintLaps = QtWidgets.QSpinBox(self.groupBox_3) self.spinBoxStintLaps.setGeometry(QtCore.QRect(140, 50, 101, 22)) self.spinBoxStintLaps.setMaximum(10000) self.spinBoxStintLaps.setSingleStep(1) self.spinBoxStintLaps.setObjectName("spinBoxStintLaps") self.groupBox_5 = QtWidgets.QGroupBox(self.tabGeneral) self.groupBox_5.setGeometry(QtCore.QRect(310, 10, 261, 91)) self.groupBox_5.setObjectName("groupBox_5") self.label_13 = QtWidgets.QLabel(self.groupBox_5) self.label_13.setGeometry(QtCore.QRect(20, 60, 101, 16)) self.label_13.setObjectName("label_13") self.label_12 = QtWidgets.QLabel(self.groupBox_5) self.label_12.setGeometry(QtCore.QRect(20, 20, 101, 16)) self.label_12.setObjectName("label_12") self.doubleSpinBox_JokerLapDelta = QtWidgets.QDoubleSpinBox(self.groupBox_5) self.doubleSpinBox_JokerLapDelta.setGeometry(QtCore.QRect(140, 20, 101, 22)) self.doubleSpinBox_JokerLapDelta.setPrefix("") self.doubleSpinBox_JokerLapDelta.setSuffix("") self.doubleSpinBox_JokerLapDelta.setDecimals(0) self.doubleSpinBox_JokerLapDelta.setMaximum(1000.0) self.doubleSpinBox_JokerLapDelta.setSingleStep(0.1) self.doubleSpinBox_JokerLapDelta.setProperty("value", self.db.config['JokerLapDelta']) self.doubleSpinBox_JokerLapDelta.setObjectName("doubleSpinBox_JokerLapDelta") self.doubleSpinBox_JokerLapsRequired = QtWidgets.QDoubleSpinBox(self.groupBox_5) self.doubleSpinBox_JokerLapsRequired.setGeometry(QtCore.QRect(140, 60, 101, 22)) self.doubleSpinBox_JokerLapsRequired.setPrefix("") self.doubleSpinBox_JokerLapsRequired.setSuffix("") self.doubleSpinBox_JokerLapsRequired.setDecimals(0) self.doubleSpinBox_JokerLapsRequired.setMaximum(1000.0) self.doubleSpinBox_JokerLapsRequired.setSingleStep(1.0) self.doubleSpinBox_JokerLapsRequired.setProperty("value", self.db.config['JokerLapsRequired']) self.doubleSpinBox_JokerLapsRequired.setObjectName("doubleSpinBox_JokerLapsRequired") self.groupBox_7 = QtWidgets.QGroupBox(self.tabGeneral) self.groupBox_7.setGeometry(QtCore.QRect(10, 210, 291, 131)) self.groupBox_7.setObjectName("groupBox_7") self.pushButtonTrackRotateLeft = QtWidgets.QPushButton(self.groupBox_7) self.pushButtonTrackRotateLeft.setGeometry(QtCore.QRect(40, 20, 75, 21)) self.pushButtonTrackRotateLeft.setObjectName("pushButtonTrackRotateLeft") self.pushButtonTrackRotateRight = QtWidgets.QPushButton(self.groupBox_7) self.pushButtonTrackRotateRight.setGeometry(QtCore.QRect(160, 20, 75, 23)) self.pushButtonTrackRotateRight.setObjectName("pushButtonTrackRotateRight") self.pushButtonLoadTrack = QtWidgets.QPushButton(self.groupBox_7) self.pushButtonLoadTrack.setGeometry(QtCore.QRect(40, 60, 75, 21)) self.pushButtonLoadTrack.setObjectName("pushButtonLoadTrack") self.pushButtonSaveTrack = QtWidgets.QPushButton(self.groupBox_7) self.pushButtonSaveTrack.setGeometry(QtCore.QRect(160, 60, 75, 23)) self.pushButtonSaveTrack.setObjectName("pushButtonSaveTrack") self.pushButtonLoadReferenceLap = QtWidgets.QPushButton(self.groupBox_7) self.pushButtonLoadReferenceLap.setGeometry(QtCore.QRect(40, 100, 191, 21)) self.pushButtonLoadReferenceLap.setObjectName("pushButtonLoadReferenceLap") self.groupBox_8 = QtWidgets.QGroupBox(self.tabGeneral) self.groupBox_8.setGeometry(QtCore.QRect(310, 120, 261, 80)) self.groupBox_8.setObjectName("groupBox_8") self.checkBox_BEnableLogger = QtWidgets.QCheckBox(self.groupBox_8) self.checkBox_BEnableLogger.setGeometry(QtCore.QRect(10, 20, 161, 17)) self.checkBox_BEnableLogger.setObjectName("checkBox_BEnableLogger") self.checkBox_BEnableLapLogging = QtWidgets.QCheckBox(self.groupBox_8) self.checkBox_BEnableLapLogging.setGeometry(QtCore.QRect(10, 50, 161, 17)) self.checkBox_BEnableLapLogging.setObjectName("checkBox_BEnableLapLogging") self.checkBox_BEnableLapLogging.setChecked(self.db.config['BEnableLapLogging']) self.groupBox_11 = QtWidgets.QGroupBox(self.tabGeneral) self.groupBox_11.setGeometry(QtCore.QRect(310, 210, 261, 141)) self.groupBox_11.setObjectName("groupBox_11") self.pushButton_MSMapDecrease = QtWidgets.QPushButton(self.groupBox_11) self.pushButton_MSMapDecrease.setGeometry(QtCore.QRect(20, 60, 91, 23)) self.pushButton_MSMapDecrease.setObjectName("pushButton_MSMapDecrease") self.pushButton_MSMapIncrease = QtWidgets.QPushButton(self.groupBox_11) self.pushButton_MSMapIncrease.setGeometry(QtCore.QRect(134, 60, 101, 23)) self.pushButton_MSMapIncrease.setObjectName("pushButton_MSMapIncrease") self.comboBox_MultiSwitch = QtWidgets.QComboBox(self.groupBox_11) self.comboBox_MultiSwitch.setGeometry(QtCore.QRect(20, 20, 211, 22)) self.comboBox_MultiSwitch.setObjectName("comboBox_MultiSwitch") tempDcList = list(dict(self.dcConfig)) for i in range(0, len(tempDcList)): self.comboBox_MultiSwitch.addItem(tempDcList[i]) self.comboBox_MultiSwitch.setMaxVisibleItems(len(tempDcList)) self.comboBox_MultiSwitch.setCurrentIndex(0) self.pushButton_MSDriverMarker = QtWidgets.QPushButton(self.groupBox_11) self.pushButton_MSDriverMarker.setGeometry(QtCore.QRect(20, 100, 211, 23)) self.pushButton_MSDriverMarker.setObjectName("pushButton_MSDriverMarker") self.tabWidget.addTab(self.tabGeneral, "") self.tabPitStops = QtWidgets.QWidget() self.tabPitStops.setObjectName("tabPitStops") self.label_10 = QtWidgets.QLabel(self.tabPitStops) self.label_10.setGeometry(QtCore.QRect(20, 50, 81, 16)) self.label_10.setObjectName("label_10") self.doubleSpinBox_PitStopsRequired = QtWidgets.QDoubleSpinBox(self.tabPitStops) self.doubleSpinBox_PitStopsRequired.setGeometry(QtCore.QRect(140, 90, 101, 22)) self.doubleSpinBox_PitStopsRequired.setPrefix("") self.doubleSpinBox_PitStopsRequired.setSuffix("") self.doubleSpinBox_PitStopsRequired.setDecimals(0) self.doubleSpinBox_PitStopsRequired.setMaximum(1000.0) self.doubleSpinBox_PitStopsRequired.setSingleStep(1.0) self.doubleSpinBox_PitStopsRequired.setProperty("value", 1.0) self.doubleSpinBox_PitStopsRequired.setObjectName("doubleSpinBox_PitStopsRequired") self.spinBox_FuelSetting = QtWidgets.QSpinBox(self.tabPitStops) self.spinBox_FuelSetting.setGeometry(QtCore.QRect(140, 200, 101, 22)) self.spinBox_FuelSetting.setMaximum(200) self.spinBox_FuelSetting.setObjectName("spinBox_FuelSetting") self.spinBox_FuelSetting.setValue(self.db.config['VUserFuelSet']) self.checkBox_ChangeTyres = QtWidgets.QCheckBox(self.tabPitStops) self.checkBox_ChangeTyres.setEnabled(True) self.checkBox_ChangeTyres.setGeometry(QtCore.QRect(20, 130, 121, 17)) self.checkBox_ChangeTyres.setAcceptDrops(False) self.checkBox_ChangeTyres.setObjectName("checkBox_ChangeTyres") self.checkBox_ChangeTyres.setChecked(self.db.config['BChangeTyres']) self.label_17 = QtWidgets.QLabel(self.tabPitStops) self.label_17.setGeometry(QtCore.QRect(20, 200, 101, 21)) self.label_17.setObjectName("label_17") self.doubleSpinBox_PitStopDelta = QtWidgets.QDoubleSpinBox(self.tabPitStops) self.doubleSpinBox_PitStopDelta.setGeometry(QtCore.QRect(140, 50, 101, 22)) self.doubleSpinBox_PitStopDelta.setPrefix("") self.doubleSpinBox_PitStopDelta.setSuffix("") self.doubleSpinBox_PitStopDelta.setDecimals(1) self.doubleSpinBox_PitStopDelta.setMaximum(1000.0) self.doubleSpinBox_PitStopDelta.setSingleStep(0.1) self.doubleSpinBox_PitStopDelta.setProperty("value", 60.0) self.doubleSpinBox_PitStopDelta.setObjectName("doubleSpinBox_PitStopDelta") self.label_16 = QtWidgets.QLabel(self.tabPitStops) self.label_16.setGeometry(QtCore.QRect(20, 160, 101, 21)) self.label_16.setObjectName("label_16") self.checkBox_FuelUp = QtWidgets.QCheckBox(self.tabPitStops) self.checkBox_FuelUp.setGeometry(QtCore.QRect(150, 130, 81, 17)) self.checkBox_FuelUp.setObjectName("checkBox_FuelUp") self.checkBox_FuelUp.setChecked(self.db.config['BBeginFueling']) self.label_11 = QtWidgets.QLabel(self.tabPitStops) self.label_11.setGeometry(QtCore.QRect(20, 90, 101, 16)) self.label_11.setObjectName("label_11") self.comboBox_FuelMethod = QtWidgets.QComboBox(self.tabPitStops) self.comboBox_FuelMethod.setGeometry(QtCore.QRect(140, 160, 101, 22)) self.comboBox_FuelMethod.setObjectName("comboBox_FuelMethod") self.comboBox_FuelMethod.addItem("") self.comboBox_FuelMethod.addItem("") self.checkBox_PitCommandControl = QtWidgets.QCheckBox(self.tabPitStops) self.checkBox_PitCommandControl.setEnabled(True) self.checkBox_PitCommandControl.setGeometry(QtCore.QRect(20, 20, 221, 17)) self.checkBox_PitCommandControl.setAcceptDrops(False) self.checkBox_PitCommandControl.setObjectName("checkBox_PitCommandControl") self.checkBox_PitCommandControl.setChecked(self.db.config['BPitCommandControl']) self.tabWidget.addTab(self.tabPitStops, "") self.tabUpshiftTone = QtWidgets.QWidget() self.tabUpshiftTone.setObjectName("tabUpshiftTone") self.groupBox = QtWidgets.QGroupBox(self.tabUpshiftTone) self.groupBox.setGeometry(QtCore.QRect(10, 10, 301, 391)) self.groupBox.setObjectName("groupBox") self.groupBox_Gear1 = QtWidgets.QGroupBox(self.groupBox) self.groupBox_Gear1.setGeometry(QtCore.QRect(10, 20, 271, 51)) self.groupBox_Gear1.setObjectName("groupBox_Gear1") self.spinBox_Gear1 = QtWidgets.QSpinBox(self.groupBox_Gear1) self.spinBox_Gear1.setGeometry(QtCore.QRect(20, 20, 71, 22)) self.spinBox_Gear1.setMinimum(4000) self.spinBox_Gear1.setMaximum(20000) self.spinBox_Gear1.setSingleStep(10) self.spinBox_Gear1.setObjectName("spinBox_Gear1") self.label = QtWidgets.QLabel(self.groupBox_Gear1) self.label.setGeometry(QtCore.QRect(110, 20, 46, 22)) self.label.setObjectName("label") self.checkBox_Gear1 = QtWidgets.QCheckBox(self.groupBox_Gear1) self.checkBox_Gear1.setEnabled(True) self.checkBox_Gear1.setGeometry(QtCore.QRect(170, 20, 51, 22)) self.checkBox_Gear1.setAcceptDrops(False) self.checkBox_Gear1.setChecked(True) self.checkBox_Gear1.setObjectName("checkBox_Gear1") self.groupBox_Gear2 = QtWidgets.QGroupBox(self.groupBox) self.groupBox_Gear2.setGeometry(QtCore.QRect(10, 70, 271, 51)) self.groupBox_Gear2.setObjectName("groupBox_Gear2") self.spinBox_Gear2 = QtWidgets.QSpinBox(self.groupBox_Gear2) self.spinBox_Gear2.setGeometry(QtCore.QRect(20, 20, 71, 22)) self.spinBox_Gear2.setMinimum(4000) self.spinBox_Gear2.setMaximum(20000) self.spinBox_Gear2.setSingleStep(10) self.spinBox_Gear2.setObjectName("spinBox_Gear2") self.label_2 = QtWidgets.QLabel(self.groupBox_Gear2) self.label_2.setGeometry(QtCore.QRect(110, 20, 46, 22)) self.label_2.setObjectName("label_2") self.checkBox_Gear2 = QtWidgets.QCheckBox(self.groupBox_Gear2) self.checkBox_Gear2.setGeometry(QtCore.QRect(170, 20, 51, 22)) self.checkBox_Gear2.setChecked(True) self.checkBox_Gear2.setObjectName("checkBox_Gear2") self.groupBox_Gear3 = QtWidgets.QGroupBox(self.groupBox) self.groupBox_Gear3.setGeometry(QtCore.QRect(10, 120, 271, 51)) self.groupBox_Gear3.setObjectName("groupBox_Gear3") self.spinBox_Gear3 = QtWidgets.QSpinBox(self.groupBox_Gear3) self.spinBox_Gear3.setGeometry(QtCore.QRect(20, 20, 71, 22)) self.spinBox_Gear3.setMinimum(4000) self.spinBox_Gear3.setMaximum(20000) self.spinBox_Gear3.setSingleStep(10) self.spinBox_Gear3.setObjectName("spinBox_Gear3") self.label_3 = QtWidgets.QLabel(self.groupBox_Gear3) self.label_3.setGeometry(QtCore.QRect(110, 20, 46, 22)) self.label_3.setObjectName("label_3") self.checkBox_Gear3 = QtWidgets.QCheckBox(self.groupBox_Gear3) self.checkBox_Gear3.setGeometry(QtCore.QRect(170, 20, 51, 22)) self.checkBox_Gear3.setChecked(True) self.checkBox_Gear3.setObjectName("checkBox_Gear3") self.groupBox_Gear4 = QtWidgets.QGroupBox(self.groupBox) self.groupBox_Gear4.setGeometry(QtCore.QRect(10, 170, 271, 51)) self.groupBox_Gear4.setObjectName("groupBox_Gear4") self.spinBox_Gear4 = QtWidgets.QSpinBox(self.groupBox_Gear4) self.spinBox_Gear4.setGeometry(QtCore.QRect(20, 20, 71, 22)) self.spinBox_Gear4.setMinimum(4000) self.spinBox_Gear4.setMaximum(20000) self.spinBox_Gear4.setSingleStep(10) self.spinBox_Gear4.setObjectName("spinBox_Gear4") self.label_4 = QtWidgets.QLabel(self.groupBox_Gear4) self.label_4.setGeometry(QtCore.QRect(110, 20, 46, 22)) self.label_4.setObjectName("label_4") self.checkBox_Gear4 = QtWidgets.QCheckBox(self.groupBox_Gear4) self.checkBox_Gear4.setGeometry(QtCore.QRect(170, 20, 51, 22)) self.checkBox_Gear4.setChecked(True) self.checkBox_Gear4.setObjectName("checkBox_Gear4") self.groupBox_Gear2_4 = QtWidgets.QGroupBox(self.groupBox) self.groupBox_Gear2_4.setGeometry(QtCore.QRect(10, 220, 271, 51)) self.groupBox_Gear2_4.setObjectName("groupBox_Gear2_4") self.spinBox_Gear5 = QtWidgets.QSpinBox(self.groupBox_Gear2_4) self.spinBox_Gear5.setGeometry(QtCore.QRect(20, 20, 71, 22)) self.spinBox_Gear5.setMinimum(4000) self.spinBox_Gear5.setMaximum(20000) self.spinBox_Gear5.setSingleStep(10) self.spinBox_Gear5.setObjectName("spinBox_Gear5") self.label_5 = QtWidgets.QLabel(self.groupBox_Gear2_4) self.label_5.setGeometry(QtCore.QRect(110, 20, 46, 22)) self.label_5.setObjectName("label_5") self.checkBox_Gear5 = QtWidgets.QCheckBox(self.groupBox_Gear2_4) self.checkBox_Gear5.setGeometry(QtCore.QRect(170, 20, 51, 22)) self.checkBox_Gear5.setChecked(True) self.checkBox_Gear5.setObjectName("checkBox_Gear5") self.groupBox_Gear6 = QtWidgets.QGroupBox(self.groupBox) self.groupBox_Gear6.setGeometry(QtCore.QRect(10, 270, 271, 51)) self.groupBox_Gear6.setObjectName("groupBox_Gear6") self.spinBox_Gear6 = QtWidgets.QSpinBox(self.groupBox_Gear6) self.spinBox_Gear6.setGeometry(QtCore.QRect(20, 20, 71, 22)) self.spinBox_Gear6.setMinimum(4000) self.spinBox_Gear6.setMaximum(20000) self.spinBox_Gear6.setSingleStep(10) self.spinBox_Gear6.setObjectName("spinBox_Gear6") self.label_6 = QtWidgets.QLabel(self.groupBox_Gear6) self.label_6.setGeometry(QtCore.QRect(110, 20, 46, 22)) self.label_6.setObjectName("label_6") self.checkBox_Gear6 = QtWidgets.QCheckBox(self.groupBox_Gear6) self.checkBox_Gear6.setGeometry(QtCore.QRect(170, 20, 51, 22)) self.checkBox_Gear6.setObjectName("checkBox_Gear6") self.groupBox_Gear7 = QtWidgets.QGroupBox(self.groupBox) self.groupBox_Gear7.setGeometry(QtCore.QRect(10, 330, 271, 51)) self.groupBox_Gear7.setObjectName("groupBox_Gear7") self.spinBox_Gear7 = QtWidgets.QSpinBox(self.groupBox_Gear7) self.spinBox_Gear7.setGeometry(QtCore.QRect(20, 20, 71, 22)) self.spinBox_Gear7.setMinimum(4000) self.spinBox_Gear7.setMaximum(20000) self.spinBox_Gear7.setSingleStep(10) self.spinBox_Gear7.setObjectName("spinBox_Gear7") self.label_7 = QtWidgets.QLabel(self.groupBox_Gear7) self.label_7.setGeometry(QtCore.QRect(110, 20, 46, 22)) self.label_7.setObjectName("label_7") self.checkBox_Gear7 = QtWidgets.QCheckBox(self.groupBox_Gear7) self.checkBox_Gear7.setGeometry(QtCore.QRect(170, 20, 51, 22)) self.checkBox_Gear7.setObjectName("checkBox_Gear7") self.groupBox_6 = QtWidgets.QGroupBox(self.tabUpshiftTone) self.groupBox_6.setGeometry(QtCore.QRect(340, 10, 401, 141)) self.groupBox_6.setObjectName("groupBox_6") self.saveButton = QtWidgets.QPushButton(self.groupBox_6) self.saveButton.setGeometry(QtCore.QRect(100, 100, 41, 23)) self.saveButton.setObjectName("saveButton") self.label_9 = QtWidgets.QLabel(self.groupBox_6) self.label_9.setGeometry(QtCore.QRect(20, 60, 101, 22)) self.label_9.setObjectName("label_9") self.checkBox_UpshiftTone = QtWidgets.QCheckBox(self.groupBox_6) self.checkBox_UpshiftTone.setGeometry(QtCore.QRect(20, 30, 251, 17)) self.checkBox_UpshiftTone.setChecked(self.db.config['ShiftToneEnabled']) self.checkBox_UpshiftTone.setObjectName("checkBox_UpshiftTone") self.openButton = QtWidgets.QPushButton(self.groupBox_6) self.openButton.setGeometry(QtCore.QRect(20, 100, 41, 23)) self.openButton.setObjectName("openButton") self.comboBox = QtWidgets.QComboBox(self.groupBox_6) self.comboBox.setGeometry(QtCore.QRect(150, 60, 131, 22)) self.comboBox.setMaxVisibleItems(5) self.comboBox.setObjectName("comboBox") self.comboBox.addItem("iRacing First RPM") self.comboBox.addItem("iRacing Shift RPM") self.comboBox.addItem("iRacing Last RPM") self.comboBox.addItem("iRacing Blink RPM") self.comboBox.addItem("User defined") self.comboBox.addItem("from Car properties") self.comboBox.setMaxVisibleItems(6) self.comboBox.setCurrentIndex(self.db.config['UpshiftStrategy']) self.comboBox_FuelMethod.setCurrentIndex(self.db.config['NFuelSetMethod']) self.pushButton_calcUpshiftRPM = QtWidgets.QPushButton(self.groupBox_6) self.pushButton_calcUpshiftRPM.setGeometry(QtCore.QRect(180, 100, 201, 23)) self.pushButton_calcUpshiftRPM.setObjectName("pushButton_calcUpshiftRPM") self.groupBox_10 = QtWidgets.QGroupBox(self.tabUpshiftTone) self.groupBox_10.setGeometry(QtCore.QRect(340, 160, 401, 91)) self.groupBox_10.setObjectName("groupBox_10") self.pushButton_testShiftTone = QtWidgets.QPushButton(self.groupBox_10) self.pushButton_testShiftTone.setGeometry(QtCore.QRect(260, 40, 91, 23)) self.pushButton_testShiftTone.setObjectName("pushButton_testShiftTone") self.label_20 = QtWidgets.QLabel(self.groupBox_10) self.label_20.setGeometry(QtCore.QRect(10, 20, 101, 22)) self.label_20.setObjectName("label_20") self.spinBox_ShiftToneFrequency = QtWidgets.QSpinBox(self.groupBox_10) self.spinBox_ShiftToneFrequency.setGeometry(QtCore.QRect(130, 20, 71, 22)) self.spinBox_ShiftToneFrequency.setMinimum(0) self.spinBox_ShiftToneFrequency.setMaximum(2000) self.spinBox_ShiftToneFrequency.setSingleStep(10) self.spinBox_ShiftToneFrequency.setProperty("value", self.db.config['fShiftBeep']) self.spinBox_ShiftToneFrequency.setObjectName("spinBox_ShiftToneFrequency") self.spinBox_ShiftToneDuration = QtWidgets.QSpinBox(self.groupBox_10) self.spinBox_ShiftToneDuration.setGeometry(QtCore.QRect(130, 60, 71, 22)) self.spinBox_ShiftToneDuration.setMinimum(0) self.spinBox_ShiftToneDuration.setMaximum(1000) self.spinBox_ShiftToneDuration.setSingleStep(10) self.spinBox_ShiftToneDuration.setProperty("value", self.db.config['tShiftBeep']) self.spinBox_ShiftToneDuration.setObjectName("spinBox_ShiftToneDuration") self.label_21 = QtWidgets.QLabel(self.groupBox_10) self.label_21.setGeometry(QtCore.QRect(10, 60, 101, 22)) self.label_21.setObjectName("label_21") self.tabWidget.addTab(self.tabUpshiftTone, "") self.tabFuelManagement = QtWidgets.QWidget() self.tabFuelManagement.setObjectName("tabFuelManagement") self.groupBox_9 = QtWidgets.QGroupBox(self.tabFuelManagement) self.groupBox_9.setGeometry(QtCore.QRect(10, 10, 231, 321)) self.groupBox_9.setObjectName("groupBox_9") self.openButton_2 = QtWidgets.QPushButton(self.groupBox_9) self.openButton_2.setGeometry(QtCore.QRect(20, 60, 191, 23)) self.openButton_2.setObjectName("openButton_2") self.calcFuelSavingButton = QtWidgets.QPushButton(self.groupBox_9) self.calcFuelSavingButton.setGeometry(QtCore.QRect(20, 160, 191, 23)) self.calcFuelSavingButton.setObjectName("calcFuelSavingButton") self.calcRollOutButton = QtWidgets.QPushButton(self.groupBox_9) self.calcRollOutButton.setGeometry(QtCore.QRect(20, 110, 191, 23)) self.calcRollOutButton.setObjectName("calcRollOutButton") self.label_VFuelTGT = QtWidgets.QLabel(self.groupBox_9) self.label_VFuelTGT.setGeometry(QtCore.QRect(20, 210, 101, 22)) self.label_VFuelTGT.setObjectName("label_VFuelTGT") self.doubleSpinBox_VFuelTGT = QtWidgets.QDoubleSpinBox(self.groupBox_9) self.doubleSpinBox_VFuelTGT.setGeometry(QtCore.QRect(140, 210, 71, 22)) self.doubleSpinBox_VFuelTGT.setPrefix("") self.doubleSpinBox_VFuelTGT.setSuffix("") self.doubleSpinBox_VFuelTGT.setDecimals(2) self.doubleSpinBox_VFuelTGT.setMinimum(0.0) self.doubleSpinBox_VFuelTGT.setMaximum(20.0) self.doubleSpinBox_VFuelTGT.setSingleStep(0.01) self.doubleSpinBox_VFuelTGT.setProperty("value", self.db.config['VFuelTgt']) self.doubleSpinBox_VFuelTGT.setObjectName("doubleSpinBox_VFuelTGT") self.comboBox_NFuelConsumptionMethod = QtWidgets.QComboBox(self.groupBox_9) self.comboBox_NFuelConsumptionMethod.setGeometry(QtCore.QRect(20, 280, 191, 22)) self.comboBox_NFuelConsumptionMethod.setMaxVisibleItems(3) self.comboBox_NFuelConsumptionMethod.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToMinimumContentsLengthWithIcon) self.comboBox_NFuelConsumptionMethod.setObjectName("comboBox_NFuelConsumptionMethod") self.comboBox_NFuelConsumptionMethod.addItem("Average all laps") self.comboBox_NFuelConsumptionMethod.addItem("Average last 3 laps") self.comboBox_NFuelConsumptionMethod.addItem("Reference lap") self.label_NFuelConsumptionMethod = QtWidgets.QLabel(self.groupBox_9) self.label_NFuelConsumptionMethod.setGeometry(QtCore.QRect(20, 250, 191, 22)) self.label_NFuelConsumptionMethod.setObjectName("label_NFuelConsumptionMethod") self.comboBox_NFuelManagement = QtWidgets.QComboBox(self.groupBox_9) self.comboBox_NFuelManagement.setGeometry(QtCore.QRect(20, 20, 191, 22)) self.comboBox_NFuelManagement.setMaxVisibleItems(4) self.comboBox_NFuelManagement.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToMinimumContentsLengthWithIcon) self.comboBox_NFuelManagement.setObjectName("comboBox_NFuelManagement") self.comboBox_NFuelManagement.addItem("Off") self.comboBox_NFuelManagement.addItem("Static Target") self.comboBox_NFuelManagement.addItem("End of Race") self.comboBox_NFuelManagement.addItem("End of Stint") self.groupBox_4 = QtWidgets.QGroupBox(self.tabFuelManagement) self.groupBox_4.setGeometry(QtCore.QRect(250, 10, 511, 141)) self.groupBox_4.setObjectName("groupBox_4") self.pushButton_testFuelTone = QtWidgets.QPushButton(self.groupBox_4) self.pushButton_testFuelTone.setGeometry(QtCore.QRect(310, 70, 141, 41)) self.pushButton_testFuelTone.setObjectName("pushButton_testFuelTone") self.label_FuelToneFrequency = QtWidgets.QLabel(self.groupBox_4) self.label_FuelToneFrequency.setGeometry(QtCore.QRect(10, 20, 101, 22)) self.label_FuelToneFrequency.setObjectName("label_FuelToneFrequency") self.spinBox_FuelToneFrequency = QtWidgets.QSpinBox(self.groupBox_4) self.spinBox_FuelToneFrequency.setGeometry(QtCore.QRect(150, 20, 71, 22)) self.spinBox_FuelToneFrequency.setMinimum(0) self.spinBox_FuelToneFrequency.setMaximum(2000) self.spinBox_FuelToneFrequency.setSingleStep(10) self.spinBox_FuelToneFrequency.setProperty("value", self.db.config['fFuelBeep']) self.spinBox_FuelToneFrequency.setObjectName("spinBox_FuelToneFrequency") self.spinBox_FuelToneDuration = QtWidgets.QSpinBox(self.groupBox_4) self.spinBox_FuelToneDuration.setGeometry(QtCore.QRect(150, 60, 71, 22)) self.spinBox_FuelToneDuration.setMinimum(0) self.spinBox_FuelToneDuration.setMaximum(1000) self.spinBox_FuelToneDuration.setSingleStep(10) self.spinBox_FuelToneDuration.setProperty("value", self.db.config['tFuelBeep']) self.spinBox_FuelToneDuration.setObjectName("spinBox_FuelToneDuration") self.label_FuelToneDuration = QtWidgets.QLabel(self.groupBox_4) self.label_FuelToneDuration.setGeometry(QtCore.QRect(10, 60, 101, 22)) self.label_FuelToneDuration.setObjectName("label_FuelToneDuration") self.label_tLiftReaction = QtWidgets.QLabel(self.groupBox_4) self.label_tLiftReaction.setGeometry(QtCore.QRect(280, 20, 101, 22)) self.label_tLiftReaction.setObjectName("label_tLiftReaction") self.doubleSpinBox_tLiftReaction = QtWidgets.QDoubleSpinBox(self.groupBox_4) self.doubleSpinBox_tLiftReaction.setGeometry(QtCore.QRect(390, 20, 101, 22)) self.doubleSpinBox_tLiftReaction.setPrefix("") self.doubleSpinBox_tLiftReaction.setSuffix("") self.doubleSpinBox_tLiftReaction.setDecimals(2) self.doubleSpinBox_tLiftReaction.setMinimum(-2.0) self.doubleSpinBox_tLiftReaction.setMaximum(2.0) self.doubleSpinBox_tLiftReaction.setSingleStep(0.01) self.doubleSpinBox_tLiftReaction.setProperty("value", self.db.config['tReactionLift']) self.doubleSpinBox_tLiftReaction.setObjectName("doubleSpinBox_tLiftReaction") self.label_tLiftGap = QtWidgets.QLabel(self.groupBox_4) self.label_tLiftGap.setGeometry(QtCore.QRect(10, 100, 121, 22)) self.label_tLiftGap.setObjectName("label_tLiftGap") self.doubleSpinBox_tLiftGap = QtWidgets.QDoubleSpinBox(self.groupBox_4) self.doubleSpinBox_tLiftGap.setGeometry(QtCore.QRect(150, 100, 71, 22)) self.doubleSpinBox_tLiftGap.setPrefix("") self.doubleSpinBox_tLiftGap.setSuffix("") self.doubleSpinBox_tLiftGap.setDecimals(2) self.doubleSpinBox_tLiftGap.setMinimum(-3.0) self.doubleSpinBox_tLiftGap.setMaximum(3.0) self.doubleSpinBox_tLiftGap.setSingleStep(0.01) self.doubleSpinBox_tLiftGap.setProperty("value", self.db.config['tLiftGap']) self.doubleSpinBox_tLiftGap.setObjectName("doubleSpinBox_tLiftGap") self.tabWidget.addTab(self.tabFuelManagement, "") self.tabDebug = QtWidgets.QWidget() self.tabDebug.setObjectName("tabDebug") self.textEdit = QtWidgets.QTextEdit(self.tabDebug) self.textEdit.setGeometry(QtCore.QRect(10, 40, 756, 331)) self.textEdit.setObjectName("textEdit") self.pushButtonInvoke = QtWidgets.QPushButton(self.tabDebug) self.pushButtonInvoke.setGeometry(QtCore.QRect(670, 380, 101, 23)) self.pushButtonInvoke.setObjectName("pushButtonInvoke") self.lineEditInvoke = QtWidgets.QLineEdit(self.tabDebug) self.lineEditInvoke.setGeometry(QtCore.QRect(10, 380, 651, 20)) self.lineEditInvoke.setObjectName("lineEditInvoke") self.pushButtonSaveSnapshot = QtWidgets.QPushButton(self.tabDebug) self.pushButtonSaveSnapshot.setGeometry(QtCore.QRect(10, 10, 101, 23)) self.pushButtonSaveSnapshot.setObjectName("pushButtonSaveSnapshot") self.pushButtonLoadSnapshot = QtWidgets.QPushButton(self.tabDebug) self.pushButtonLoadSnapshot.setGeometry(QtCore.QRect(120, 10, 101, 23)) self.pushButtonLoadSnapshot.setObjectName("pushButtonLoadSnapshot") self.tabWidget.addTab(self.tabDebug, "") self.tabSettings = QtWidgets.QWidget() self.tabSettings.setObjectName("tabSettings") self.pushButtonSaveConfig = QtWidgets.QPushButton(self.tabSettings) self.pushButtonSaveConfig.setGeometry(QtCore.QRect(10, 10, 75, 23)) self.pushButtonSaveConfig.setObjectName("pushButtonSaveConfig") self.pushButtonLoadConfig = QtWidgets.QPushButton(self.tabSettings) self.pushButtonLoadConfig.setGeometry(QtCore.QRect(100, 10, 75, 23)) self.pushButtonLoadConfig.setObjectName("pushButtonLoadConfig") self.label_22 = QtWidgets.QLabel(self.tabSettings) self.label_22.setGeometry(QtCore.QRect(20, 50, 91, 16)) self.label_22.setObjectName("label_22") self.label_23 = QtWidgets.QLabel(self.tabSettings) self.label_23.setGeometry(QtCore.QRect(20, 90, 91, 16)) self.label_23.setObjectName("label_23") self.lineEditiRPath = QtWidgets.QLineEdit(self.tabSettings) self.lineEditiRPath.setEnabled(True) self.lineEditiRPath.setGeometry(QtCore.QRect(130, 50, 501, 20)) self.lineEditiRPath.setObjectName("lineEditiRPath") self.lineEditTelemPath = QtWidgets.QLineEdit(self.tabSettings) self.lineEditTelemPath.setGeometry(QtCore.QRect(130, 90, 501, 20)) self.lineEditTelemPath.setObjectName("lineEditTelemPath") self.pushButtonSetiRPath = QtWidgets.QPushButton(self.tabSettings) self.pushButtonSetiRPath.setGeometry(QtCore.QRect(660, 50, 101, 23)) self.pushButtonSetiRPath.setObjectName("pushButtonSetiRPath") self.pushButtonSetTelemPath = QtWidgets.QPushButton(self.tabSettings) self.pushButtonSetTelemPath.setGeometry(QtCore.QRect(660, 90, 101, 23)) self.pushButtonSetTelemPath.setObjectName("pushButtonSetTelemPath") self.groupBox_12 = QtWidgets.QGroupBox(self.tabSettings) self.groupBox_12.setEnabled(True) self.groupBox_12.setGeometry(QtCore.QRect(10, 160, 751, 211)) font = QtGui.QFont() font.setKerning(False) self.groupBox_12.setFont(font) self.groupBox_12.setObjectName("groupBox_12") self.pushButtonSaveDDUPage = QtWidgets.QPushButton(self.groupBox_12) self.pushButtonSaveDDUPage.setGeometry(QtCore.QRect(10, 60, 161, 21)) self.pushButtonSaveDDUPage.setObjectName("pushButtonSaveDDUPage") self.lineEditDDUPage = QtWidgets.QLineEdit(self.groupBox_12) self.lineEditDDUPage.setGeometry(QtCore.QRect(190, 60, 541, 20)) self.lineEditDDUPage.setObjectName("lineEditDDUPage") self.pushButtonPreviousMulti = QtWidgets.QPushButton(self.groupBox_12) self.pushButtonPreviousMulti.setGeometry(QtCore.QRect(10, 90, 161, 21)) self.pushButtonPreviousMulti.setObjectName("pushButtonPreviousMulti") self.lineEditPreviousMulti = QtWidgets.QLineEdit(self.groupBox_12) self.lineEditPreviousMulti.setGeometry(QtCore.QRect(190, 90, 541, 20)) self.lineEditPreviousMulti.setObjectName("lineEditPreviousMulti") self.pushButtonNextMulti = QtWidgets.QPushButton(self.groupBox_12) self.pushButtonNextMulti.setGeometry(QtCore.QRect(10, 120, 161, 21)) self.pushButtonNextMulti.setObjectName("pushButtonNextMulti") self.lineEditNextMulti = QtWidgets.QLineEdit(self.groupBox_12) self.lineEditNextMulti.setGeometry(QtCore.QRect(190, 120, 541, 20)) self.lineEditNextMulti.setObjectName("lineEditNextMulti") self.pushButtonMultiDecrease = QtWidgets.QPushButton(self.groupBox_12) self.pushButtonMultiDecrease.setGeometry(QtCore.QRect(10, 150, 161, 21)) self.pushButtonMultiDecrease.setObjectName("pushButtonMultiDecrease") self.lineEditMultiDecrease = QtWidgets.QLineEdit(self.groupBox_12) self.lineEditMultiDecrease.setGeometry(QtCore.QRect(190, 150, 541, 20)) self.lineEditMultiDecrease.setObjectName("lineEditMultiDecrease") self.pushButtonMultiIncrease = QtWidgets.QPushButton(self.groupBox_12) self.pushButtonMultiIncrease.setGeometry(QtCore.QRect(10, 180, 161, 21)) self.pushButtonMultiIncrease.setObjectName("pushButtonMultiIncrease") self.lineEditMultiIncrease = QtWidgets.QLineEdit(self.groupBox_12) self.lineEditMultiIncrease.setGeometry(QtCore.QRect(190, 180, 541, 20)) self.lineEditMultiIncrease.setObjectName("lineEditMultiIncrease") self.label_24 = QtWidgets.QLabel(self.groupBox_12) self.label_24.setGeometry(QtCore.QRect(20, 20, 101, 21)) self.label_24.setObjectName("label_24") self.comboBox_JoystickSelection = QtWidgets.QComboBox(self.groupBox_12) self.comboBox_JoystickSelection.setGeometry(QtCore.QRect(190, 20, 541, 22)) self.comboBox_JoystickSelection.setObjectName("comboBox_JoystickSelection") self.comboBox_JoystickSelection.addItem("") self.comboBox_JoystickSelection.addItem("") self.comboBox_JoystickSelection.addItem("") self.comboBox_JoystickSelection.addItem("") self.comboBox_JoystickSelection.addItem("") self.comboBox_JoystickSelection.addItem("") self.comboBox_JoystickSelection.addItem("") self.comboBox_JoystickSelection.addItem("") self.comboBox_JoystickSelection.addItem("") self.label_25 = QtWidgets.QLabel(self.tabSettings) self.label_25.setGeometry(QtCore.QRect(20, 130, 91, 16)) self.label_25.setObjectName("label_25") self.pushButtonSetMotecPath = QtWidgets.QPushButton(self.tabSettings) self.pushButtonSetMotecPath.setGeometry(QtCore.QRect(660, 130, 101, 23)) self.pushButtonSetMotecPath.setObjectName("pushButtonSetMotecPath") self.lineEditMotecPath = QtWidgets.QLineEdit(self.tabSettings) self.lineEditMotecPath.setGeometry(QtCore.QRect(130, 130, 501, 20)) self.lineEditMotecPath.setObjectName("lineEditMotecPath") self.tabWidget.addTab(self.tabSettings, "") self.checkBox_BEnableLogger.setChecked(self.db.config['BLoggerActive']) self.spinBoxStintLaps.setValue(self.db.config['NLapsStintPlanned']) self.spinBoxRaceLaps.setValue(self.db.config['UserRaceLaps']) self.doubleSpinBox_PitStopDelta.setValue(self.db.config['PitStopDelta']) self.doubleSpinBox_PitStopsRequired.setValue(self.db.config['PitStopsRequired']) self.spinBoxRaceLaps.valueChanged.connect(self.assignRaceLaps) self.spinBoxStintLaps.valueChanged.connect(self.assignStintLaps) self.doubleSpinBox_PitStopDelta.valueChanged.connect(self.assignPitStopDelta) self.doubleSpinBox_PitStopsRequired.valueChanged.connect(self.assignPitStopsRequired) self.checkBox_UpshiftTone.stateChanged.connect(self.EnableShiftTone) self.comboBox.currentIndexChanged.connect(self.UpshiftStrategy) self.spinBox_Gear1.valueChanged.connect(self.UpshiftStrategy) self.checkBox_Gear1.stateChanged.connect(self.UpshiftStrategy) self.spinBox_Gear2.valueChanged.connect(self.UpshiftStrategy) self.checkBox_Gear2.stateChanged.connect(self.UpshiftStrategy) self.spinBox_Gear3.valueChanged.connect(self.UpshiftStrategy) self.checkBox_Gear3.stateChanged.connect(self.UpshiftStrategy) self.spinBox_Gear4.valueChanged.connect(self.UpshiftStrategy) self.checkBox_Gear4.stateChanged.connect(self.UpshiftStrategy) self.spinBox_Gear5.valueChanged.connect(self.UpshiftStrategy) self.checkBox_Gear5.stateChanged.connect(self.UpshiftStrategy) self.spinBox_Gear6.valueChanged.connect(self.UpshiftStrategy) self.checkBox_Gear6.stateChanged.connect(self.UpshiftStrategy) self.spinBox_Gear7.valueChanged.connect(self.UpshiftStrategy) self.checkBox_Gear7.stateChanged.connect(self.UpshiftStrategy) self.pushButtonInvoke.clicked.connect(self.InvokeUserCommand) self.lineEditInvoke.returnPressed.connect(self.InvokeUserCommand) self.pushButton_StartDDU.clicked.connect(self.StartDDU) self.pushButton_StopDDU.clicked.connect(self.StopDDU) self.saveButton.clicked.connect(self.saveShiftToneSettings) self.openButton.clicked.connect(self.loadShiftToneSettings) self.pushButtonLoadSnapshot.clicked.connect(self.loadRTDBSnapshot) self.pushButtonSaveSnapshot.clicked.connect(self.saveRTDBSnapshot) self.pushButtonTrackRotateLeft.clicked.connect(self.rotateTrackLeft) self.pushButtonTrackRotateRight.clicked.connect(self.rotateTrackRight) self.pushButtonLoadTrack.clicked.connect(self.loadTrack) self.pushButtonSaveTrack.clicked.connect(self.saveTrack) self.pushButtonLoadReferenceLap.clicked.connect(self.loadReferenceLap) self.doubleSpinBox_DRSActivations.valueChanged.connect(self.assignDRS) self.doubleSpinBox_JokerLapDelta.valueChanged.connect(self.assignJokerDelta) self.doubleSpinBox_JokerLapsRequired.valueChanged.connect(self.assignJokerLaps) self.doubleSpinBox_P2PActivations.valueChanged.connect(self.assignP2P) self.checkBox_MapHighlight.stateChanged.connect(self.MapHighlight) self.checkBox_BEnableLogger.stateChanged.connect(self.enableLogger) self.checkBox_BEnableLapLogging.stateChanged.connect(self.enableLapLogging) self.checkBox_FuelUp.stateChanged.connect(self.enableFuelUp) self.checkBox_ChangeTyres.stateChanged.connect(self.enableTyreChange) self.spinBox_FuelSetting.valueChanged.connect(self.setUserFuelPreset) self.comboBox_FuelMethod.currentIndexChanged.connect(self.setFuelSetMethod) self.checkBox_PitCommandControl.stateChanged.connect(self.setPitCommandControl) self.spinBox_FuelToneFrequency.valueChanged.connect(self.FuelBeep) self.spinBox_FuelToneDuration.valueChanged.connect(self.FuelBeep) self.pushButton_testFuelTone.clicked.connect(self.testFuelTone) # self.checkBox_EnableFuelManagement.stateChanged.connect(self.enableFuelManagement) self.openButton_2.clicked.connect(self.loadFuelManagementSettings) self.pushButton_testShiftTone.clicked.connect(self.testShiftTone) self.spinBox_ShiftToneFrequency.valueChanged.connect(self.ShiftBeep) self.spinBox_ShiftToneDuration.valueChanged.connect(self.ShiftBeep) self.calcFuelSavingButton.clicked.connect(self.calcFuelSaving) self.pushButton_calcUpshiftRPM.clicked.connect(self.calcUpshiftRPM) self.calcRollOutButton.clicked.connect(self.calcRollOut) self.pushButton_MSMapDecrease.clicked.connect(self.MSMapDecrease) self.pushButton_MSMapIncrease.clicked.connect(self.MSMapIncrease) # self.comboBox_MultiSwitch.clicked.connect(self.retranslateUi) # self.comboBox_MultiSwitch.activated.connect(self.retranslateUi) self.pushButtonLoadConfig.clicked.connect(self.LoadConfig) self.pushButtonSaveConfig.clicked.connect(self.SaveConfig) self.pushButtonSetiRPath.clicked.connect(self.SetiRPath) self.pushButtonSetTelemPath.clicked.connect(self.SetTelemPath) self.pushButtonSetMotecPath.clicked.connect(self.SetMotecPath) self.pushButton_MSDriverMarker.clicked.connect(self.assignDriverMarker) self.pushButtonPreviousMulti.clicked.connect(self.assignButtonPreviousMulti) self.pushButtonNextMulti.clicked.connect(self.assignButtonNextMulti) self.pushButtonMultiDecrease.clicked.connect(self.assignButtonMultiDecrease) self.pushButtonMultiIncrease.clicked.connect(self.assignButtonMultiIncrease) self.pushButtonSaveDDUPage.clicked.connect(self.assignButtonDDUPage) self.doubleSpinBox_tLiftReaction.valueChanged.connect(self.setTLiftReaction) self.doubleSpinBox_tLiftGap.valueChanged.connect(self.setTLift) self.doubleSpinBox_VFuelTGT.valueChanged.connect(self.setVFuelTgt) self.comboBox_NFuelConsumptionMethod.currentIndexChanged.connect(self.NFuelConsumptionMethod) self.comboBox_NFuelManagement.currentIndexChanged.connect(self.NFuelTargetMethod) # finish = self.iDDU.closeEvent() # QtCore.QMetaObject.connectSlotsByName(iDDU) # app.aboutToQuit.connect(self.closeEvent) # # finish = QtWidgets.QAction("Quit", self.iDDU) # finish.triggered.connect(self.closeEvent) self.retranslateUi(iDDU) self.tabWidget.setCurrentIndex(0) self.comboBox.setCurrentIndex(0) self.comboBox_NFuelConsumptionMethod.setCurrentIndex(0) self.comboBox_NFuelManagement.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(iDDU) self.UpshiftStrategy() def retranslateUi(self, iDDU): _translate = QtCore.QCoreApplication.translate iDDU.setWindowTitle(_translate("iDDU", "iDDU")) self.groupBox_2.setTitle(_translate("iDDU", "DDU")) self.pushButton_StartDDU.setText(_translate("iDDU", "Start DDU")) self.pushButton_StopDDU.setText(_translate("iDDU", "Stop DDU")) self.groupBox_3.setTitle(_translate("iDDU", "General")) self.label_8.setText(_translate("iDDU", "Race Laps")) self.label_14.setText(_translate("iDDU", "DRS Activations")) self.checkBox_MapHighlight.setText(_translate("iDDU", "activate Delta on Map")) self.label_15.setText(_translate("iDDU", "P2P Activations")) self.label_NStintLaps.setText(_translate("iDDU", "Stint Laps")) self.groupBox_5.setTitle(_translate("iDDU", "RallyX")) self.label_13.setText(_translate("iDDU", "Required Joker Laps")) self.label_12.setText(_translate("iDDU", "Joker Lap Delta")) self.groupBox_7.setTitle(_translate("iDDU", "Track")) self.pushButtonTrackRotateLeft.setText(_translate("iDDU", "Rotate Left")) self.pushButtonTrackRotateRight.setText(_translate("iDDU", "Rotate Right")) self.pushButtonLoadTrack.setText(_translate("iDDU", "Load")) self.pushButtonSaveTrack.setText(_translate("iDDU", "Save")) self.pushButtonLoadReferenceLap.setText(_translate("iDDU", "Load Reference Lap")) self.groupBox_8.setTitle(_translate("iDDU", "Logging")) self.checkBox_BEnableLogger.setText(_translate("iDDU", "enable Logger")) self.checkBox_BEnableLapLogging.setText(_translate("iDDU", "enable end of lap logging")) self.groupBox_11.setTitle(_translate("iDDU", "Multi Switch")) self.pushButton_MSMapDecrease.setText(_translate("iDDU", "Map Decrease")) self.pushButton_MSMapIncrease.setText(_translate("iDDU", "Map Increase")) self.pushButton_MSDriverMarker.setText(_translate("iDDU", "assign Driver Marker")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabGeneral), _translate("iDDU", "General")) self.label_10.setText(_translate("iDDU", "Pit Stop Delta")) self.checkBox_ChangeTyres.setText(_translate("iDDU", "Change Tyres")) self.label_17.setText(_translate("iDDU", "User fuel pre set")) self.label_16.setText(_translate("iDDU", "Pit stop fuel setting")) self.checkBox_FuelUp.setText(_translate("iDDU", "Fuel up")) self.label_11.setText(_translate("iDDU", "Required Pit Stops")) self.comboBox_FuelMethod.setItemText(0, _translate("iDDU", "User pre set")) self.comboBox_FuelMethod.setItemText(1, _translate("iDDU", "calculated")) self.checkBox_PitCommandControl.setText(_translate("iDDU", "iDDU has control over pit commands")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabPitStops), _translate("iDDU", "Pit Stops")) self.groupBox.setTitle(_translate("iDDU", "Upshift RPM")) self.groupBox_Gear1.setTitle(_translate("iDDU", "Gear 1")) self.label.setText(_translate("iDDU", "RPM")) self.checkBox_Gear1.setText(_translate("iDDU", "active")) self.groupBox_Gear2.setTitle(_translate("iDDU", "Gear 2")) self.label_2.setText(_translate("iDDU", "RPM")) self.checkBox_Gear2.setText(_translate("iDDU", "active")) self.groupBox_Gear3.setTitle(_translate("iDDU", "Gear 3")) self.label_3.setText(_translate("iDDU", "RPM")) self.checkBox_Gear3.setText(_translate("iDDU", "active")) self.groupBox_Gear4.setTitle(_translate("iDDU", "Gear 4")) self.label_4.setText(_translate("iDDU", "RPM")) self.checkBox_Gear4.setText(_translate("iDDU", "active")) self.groupBox_Gear2_4.setTitle(_translate("iDDU", "Gear 5")) self.label_5.setText(_translate("iDDU", "RPM")) self.checkBox_Gear5.setText(_translate("iDDU", "active")) self.groupBox_Gear6.setTitle(_translate("iDDU", "Gear 6")) self.label_6.setText(_translate("iDDU", "RPM")) self.checkBox_Gear6.setText(_translate("iDDU", "active")) self.groupBox_Gear7.setTitle(_translate("iDDU", "Gear 7")) self.label_7.setText(_translate("iDDU", "RPM")) self.checkBox_Gear7.setText(_translate("iDDU", "active")) self.groupBox_6.setTitle(_translate("iDDU", "Strategy")) self.saveButton.setText(_translate("iDDU", "Save")) self.label_9.setText(_translate("iDDU", "Upshift RPM Source")) self.checkBox_UpshiftTone.setText(_translate("iDDU", "activate Upshift Tone")) self.openButton.setText(_translate("iDDU", "Load")) self.comboBox.setItemText(0, _translate("iDDU", "iRacing First RPM")) self.comboBox.setItemText(1, _translate("iDDU", "iRacing Shift RPM")) self.comboBox.setItemText(2, _translate("iDDU", "iRacing Last RPM")) self.comboBox.setItemText(3, _translate("iDDU", "iRacing Blink RPM")) self.comboBox.setItemText(4, _translate("iDDU", "User defined")) self.comboBox.setItemText(5, _translate("iDDU", "from Car properties")) self.comboBox_MultiSwitch.setMaxVisibleItems(6) self.comboBox.setCurrentIndex(self.db.config['UpshiftStrategy']) self.pushButton_calcUpshiftRPM.setText(_translate("iDDU", "Calculate Upshift RPM from data")) self.groupBox_10.setTitle(_translate("iDDU", "Audio Settings")) self.pushButton_testShiftTone.setText(_translate("iDDU", "Play Test Tone")) self.label_20.setText(_translate("iDDU", "Tone Frequency")) self.label_21.setText(_translate("iDDU", "Tone Duration")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabUpshiftTone), _translate("iDDU", "Upshift Tone")) self.groupBox_9.setTitle(_translate("iDDU", "Configuration")) self.openButton_2.setText(_translate("iDDU", "Load Configuration")) self.calcFuelSavingButton.setText(_translate("iDDU", "Calculate fuel saving from data")) self.calcRollOutButton.setText(_translate("iDDU", "Calculate roll-out curves")) self.label_VFuelTGT.setText(_translate("iDDU", "Consumption Target")) self.comboBox_NFuelConsumptionMethod.setItemText(0, _translate("iDDU", "Average Laps")) self.comboBox_NFuelConsumptionMethod.setItemText(1, _translate("iDDU", "Last 3 Laps")) self.comboBox_NFuelConsumptionMethod.setItemText(2, _translate("iDDU", "Reference Lap")) self.label_NFuelConsumptionMethod.setText(_translate("iDDU", "Fuel Consumption Calculation Method")) self.comboBox_NFuelManagement.setItemText(0, _translate("iDDU", "Off")) self.comboBox_NFuelManagement.setItemText(1, _translate("iDDU", "Static Target")) self.comboBox_NFuelManagement.setItemText(2, _translate("iDDU", "End of Race")) self.comboBox_NFuelManagement.setItemText(3, _translate("iDDU", "End of Stint")) self.groupBox_4.setTitle(_translate("iDDU", "Audio Settings")) self.pushButton_testFuelTone.setText(_translate("iDDU", "Play Test Tone")) self.label_FuelToneFrequency.setText(_translate("iDDU", "Tone Frequency")) self.label_FuelToneDuration.setText(_translate("iDDU", "Tone Duration")) self.label_tLiftReaction.setText(_translate("iDDU", "Lift Reaction Time")) self.label_tLiftGap.setText(_translate("iDDU", "Gap between Lift Tones")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabFuelManagement), _translate("iDDU", "Fuel Management")) self.pushButtonInvoke.setText(_translate("iDDU", "Invoke Command")) self.pushButtonSaveSnapshot.setText(_translate("iDDU", "RTDB Snapshot")) self.pushButtonLoadSnapshot.setText(_translate("iDDU", "Load Snapshot")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabDebug), _translate("iDDU", "Debug")) self.checkBox_MapHighlight.setChecked(self.db.config['MapHighlight']) self.pushButtonSaveConfig.setText(_translate("iDDU", "Save Settings")) self.pushButtonLoadConfig.setText(_translate("iDDU", "Load Settings")) self.label_22.setText(_translate("iDDU", "iRacing Path:")) self.label_23.setText(_translate("iDDU", "Telemetry Path:")) self.lineEditiRPath.setText(_translate("iDDU", self.db.config['iRPath'])) self.lineEditTelemPath.setText(_translate("iDDU", self.db.config['TelemPath'])) self.lineEditMotecPath.setText(_translate("iDDU", self.db.config['MotecProjectPath'])) self.pushButtonSetiRPath.setText(_translate("iDDU", "Set iRacing Path")) self.pushButtonSetTelemPath.setText(_translate("iDDU", "Set Telemetry Path")) self.groupBox_12.setTitle(_translate("iDDU", "Button assignments")) self.pushButtonSaveDDUPage.setText(_translate("iDDU", "Change DDU Page")) self.pushButtonPreviousMulti.setText(_translate("iDDU", "Previous Multi Position")) self.pushButtonNextMulti.setText(_translate("iDDU", "Next Multi Position")) self.pushButtonMultiDecrease.setText(_translate("iDDU", "Decrease Multi Value")) self.pushButtonMultiIncrease.setText(_translate("iDDU", "Increase Multi Value")) self.label_24.setText(_translate("iDDU", "Select Joystick")) self.label_25.setText(_translate("iDDU", "Motec Project Path:")) self.pushButtonSetMotecPath.setText(_translate("iDDU", "Set Motec Path")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabSettings), _translate("iDDU", "Settings")) self.spinBoxRaceLaps.setValue(self.db.config['UserRaceLaps']) self.spinBoxStintLaps.setValue(self.db.config['NLapsStintPlanned']) self.checkBox_BEnableLogger.setChecked(self.db.config['BLoggerActive']) self.checkBox_BEnableLapLogging.setChecked(self.db.config['BEnableLapLogging']) self.checkBox_FuelUp.setChecked(self.db.config['BBeginFueling']) self.checkBox_ChangeTyres.setChecked(self.db.config['BChangeTyres']) self.checkBox_PitCommandControl.setChecked(self.db.config['BPitCommandControl']) self.comboBox_FuelMethod.setCurrentIndex(self.db.config['NFuelSetMethod']) self.checkBox_UpshiftTone.setChecked(self.db.config['ShiftToneEnabled']) self.comboBox_NFuelConsumptionMethod.setCurrentIndex(self.db.config['NFuelConsumptionMethod']) self.comboBox_NFuelManagement.setCurrentIndex(self.db.config['NFuelTargetMethod']) self.lineEditDDUPage.setText('Device: {} | Button: {}'.format(self.db.config['ButtonAssignments']['DDUPage']['Joystick'], self.db.config['ButtonAssignments']['DDUPage']['Button'])) self.lineEditNextMulti.setText('Device: {} | Button: {}'.format(self.db.config['ButtonAssignments']['NextMulti']['Joystick'], self.db.config['ButtonAssignments']['NextMulti']['Button'])) self.lineEditPreviousMulti.setText('Device: {} | Button: {}'.format(self.db.config['ButtonAssignments']['PreviousMulti']['Joystick'], self.db.config['ButtonAssignments']['PreviousMulti']['Button'])) self.lineEditMultiDecrease.setText('Device: {} | Button: {}'.format(self.db.config['ButtonAssignments']['MultiDecrease']['Joystick'], self.db.config['ButtonAssignments']['MultiDecrease']['Button'])) self.lineEditMultiIncrease.setText('Device: {} | Button: {}'.format(self.db.config['ButtonAssignments']['MultiIncrease']['Joystick'], self.db.config['ButtonAssignments']['MultiIncrease']['Button'])) dcList = list(self.db.car.dcList.keys()) k = 0 for i in range(0, len(dcList)): if self.db.car.dcList[dcList[i]][1]: # self.comboBox_MultiSwitch.addItem(dcList[i]) self.comboBox_MultiSwitch.setItemText(k, _translate("iDDU", dcList[i])) k += 1 self.comboBox_MultiSwitch.setMaxVisibleItems(len(list(dict(self.dcConfig)))) # self.comboBox_MultiSwitch.setCurrentIndex(0) for i in range(0, len(self.joystickList)): self.comboBox_JoystickSelection.setItemText(i, _translate("iDDU", self.joystickList[i])) self.comboBox_JoystickSelection.setMaxVisibleItems(len(self.joystickList)+5) def assignRaceLaps(self): self.db.config['UserRaceLaps'] = self.spinBoxRaceLaps.value() self.retranslateUi(self.iDDU) def assignStintLaps(self): self.db.config['NLapsStintPlanned'] = self.spinBoxStintLaps.value() self.retranslateUi(self.iDDU) def assignDRS(self): if self.db.SessionInfo['Sessions'][self.db.SessionNum]['SessionType'] == 'Race': self.db.config['DRSActivations'] = self.doubleSpinBox_DRSActivations.value() self.db.config['DRSActivationsGUI'] = self.doubleSpinBox_DRSActivations.value() self.retranslateUi(self.iDDU) def assignJokerDelta(self): self.db.config['JokerLapDelta'] = self.doubleSpinBox_JokerLapDelta.value() self.retranslateUi(self.iDDU) def MapHighlight(self): self.db.config['MapHighlight'] = self.checkBox_MapHighlight.isChecked() self.retranslateUi(self.iDDU) def assignJokerLaps(self): self.db.config['JokerLapsRequired'] = self.doubleSpinBox_JokerLapsRequired.value() self.retranslateUi(self.iDDU) def assignP2P(self): if self.db.SessionInfo['Sessions'][self.db.SessionNum]['SessionType'] == 'Race': self.db.config['P2PActivations'] = self.doubleSpinBox_P2PActivations.value() self.db.config['P2PActivationsGUI'] = self.doubleSpinBox_P2PActivations.value() self.retranslateUi(self.iDDU) def assignPitStopDelta(self): self.db.config['PitStopDelta'] = self.doubleSpinBox_PitStopDelta.value() self.retranslateUi(self.iDDU) def assignPitStopsRequired(self): self.db.config['PitStopsRequired'] = self.doubleSpinBox_PitStopsRequired.value() self.retranslateUi(self.iDDU) def UpshiftStrategy(self): self.db.config['UpshiftStrategy'] = self.comboBox.currentIndex() self.db.config['UserShiftRPM'] = [self.spinBox_Gear1.value(), self.spinBox_Gear2.value(), self.spinBox_Gear3.value(), self.spinBox_Gear4.value(), self.spinBox_Gear5.value(), self.spinBox_Gear6.value(), self.spinBox_Gear7.value()] self.db.config['UserShiftFlag'] = [self.checkBox_Gear1.isChecked(), self.checkBox_Gear2.isChecked(), self.checkBox_Gear3.isChecked(), self.checkBox_Gear4.isChecked(), self.checkBox_Gear5.isChecked(), self.checkBox_Gear6.isChecked(), self.checkBox_Gear7.isChecked()] self.retranslateUi(self.iDDU) def EnableShiftTone(self): self.db.config['ShiftToneEnabled'] = self.checkBox_UpshiftTone.isChecked() self.retranslateUi(self.iDDU) def InvokeUserCommand(self): try: cmd = self.lineEditInvoke.text() print(self.db.timeStr + ": >> " + cmd) if "=" in cmd: exec(cmd) outstr = cmd.split('=') print(self.db.timeStr + ': ' + str(eval(outstr[0]))) else: print(self.db.timeStr + ': ' + str(eval(cmd))) except: print(self.db.timeStr + ': User command not working!') self.retranslateUi(self.iDDU) def onUpdateText(self, text): cursor = self.textEdit.textCursor() cursor.movePosition(QtGui.QTextCursor.End) cursor.insertText(text) self.textEdit.setTextCursor(cursor) self.textEdit.ensureCursorVisible() def StartDDU(self): self.db.StartDDU = True def StopDDU(self): self.db.StopDDU = True def saveShiftToneSettings(self): SaveFileName = QFileDialog.getSaveFileName(self.iDDU, 'Save Shift Tone File', './data/shiftTone', 'CSV(*.csv)') if SaveFileName == ('', ''): print(time.strftime("%H:%M:%S", time.localtime()) + ':\tNo valid path to CSV file provided...aborting!') return with open(SaveFileName[0], 'w', newline='') as f: thewriter = csv.writer(f) for l in range(0, 7): thewriter.writerow([self.db.config['UserShiftRPM'][l], self.db.config['UserShiftFlag'][l], self.db.config['UpshiftStrategy']]) print(self.db.timeStr + ': Saved Shift Tone settings to: ' + SaveFileName[0]) def loadShiftToneSettings(self): OpenFileName = QFileDialog.getOpenFileName(self.iDDU, 'Load Shift Tone File', './data/shiftTone', 'CSV(*.csv)') if OpenFileName == ('', ''): print(time.strftime("%H:%M:%S", time.localtime()) + ':\tNo valid path to CSV file provided...aborting!') return i = 0 UserShiftRPM = [0, 0, 0, 0, 0, 0, 0] UserShiftFlag = [0, 0, 0, 0, 0, 0, 0] with open(OpenFileName[0]) as csv_file: csv_reader = csv.reader(csv_file) for line in csv_reader: UserShiftRPM[i] = float(line[0]) UserShiftFlag[i] = eval(line[1]) UpshiftStrategy = int(line[2]) i = i + 1 csv_file.close() self.checkBox_Gear1.setChecked(UserShiftFlag[0]) self.checkBox_Gear2.setChecked(UserShiftFlag[1]) self.checkBox_Gear3.setChecked(UserShiftFlag[2]) self.checkBox_Gear4.setChecked(UserShiftFlag[3]) self.checkBox_Gear5.setChecked(UserShiftFlag[4]) self.checkBox_Gear6.setChecked(UserShiftFlag[5]) self.checkBox_Gear7.setChecked(UserShiftFlag[6]) self.spinBox_Gear1.setValue(UserShiftRPM[0]) self.spinBox_Gear2.setValue(UserShiftRPM[1]) self.spinBox_Gear3.setValue(UserShiftRPM[2]) self.spinBox_Gear4.setValue(UserShiftRPM[3]) self.spinBox_Gear5.setValue(UserShiftRPM[4]) self.spinBox_Gear6.setValue(UserShiftRPM[5]) self.spinBox_Gear7.setValue(UserShiftRPM[6]) self.comboBox.setCurrentIndex(UpshiftStrategy) self.db.config['UserShiftFlag'] = UserShiftFlag self.db.config['UserShiftRPM'] = UserShiftRPM self.db.config['UpshiftStrategy'] = UpshiftStrategy print(self.db.timeStr + ': Loaded Shift Tone settings from: ' + OpenFileName[0]) self.retranslateUi(self.iDDU) def loadRTDBSnapshot(self): OpenFileName = QFileDialog.getOpenFileName(self.iDDU, 'Load Track JSON file', './data/snapshots', 'JSON(*.json)') if OpenFileName == ('', ''): print(time.strftime("%H:%M:%S", time.localtime()) + ':\tNo valid path to RTDB snapshot file provided...aborting!') return OpenFileName = OpenFileName[0].split('/') OpenFileName = OpenFileName[-1] OpenFileName = OpenFileName.split('.') self.db.loadSnapshot(OpenFileName[0]) def saveRTDBSnapshot(self): self.db.snapshot() def rotateTrackLeft(self): self.db.track.rotate(-5/180*3.142) def rotateTrackRight(self): self.db.track.rotate(5/180*3.142) def saveTrack(self): self.db.track.save(self.db.dir) def enableLogger(self): self.db.config['BLoggerActive'] = self.checkBox_BEnableLogger.isChecked() self.retranslateUi(self.iDDU) def enableLapLogging(self): self.db.config['BEnableLapLogging'] = self.checkBox_BEnableLapLogging.isChecked() self.retranslateUi(self.iDDU) def loadTrack(self): OpenFileName = QFileDialog.getOpenFileName(self.iDDU, 'Load Track JSON file', './data/track', 'JSON(*.json)') if OpenFileName == ('', ''): print(time.strftime("%H:%M:%S", time.localtime()) + ':\tNo valid path to track file provided...aborting!') return NDDUPageTemp = self.db.NDDUPage BResetScreen = False if self.db.NDDUPage == 2: BResetScreen = True self.db.NDDUPage = 1 time.sleep(0.2) self.db.track = Track.Track('default') self.db.track.load(OpenFileName[0]) if BResetScreen: self.db.NDDUPage = NDDUPageTemp def loadReferenceLap(self): print(time.strftime("%H:%M:%S", time.localtime()) + ':\tImporting reference lap') # ibtPath = QFileDialog.getOpenFileName(self.iDDU, 'Load IBT file', self.db.config['TelemPath'], 'IBT(*.ibt)') # # if ibtPath == ('', ''): # print(time.strftime("%H:%M:%S", time.localtime()) + ':\t\tNo valid path to ibt file provided...aborting!') # return setReferenceLap(dirPath=self.db.dir, TelemPath=self.db.config['TelemPath']) # d, _ = importIBT.importIBT(ibtPath[0], # lap='f', # channels=['zTrack', 'LapDistPct', 'rThrottle', 'rBrake', 'QFuel', 'SessionTime', 'VelocityX', 'VelocityY', 'Yaw', 'Gear', 'YawNorth'], # channelMapPath=self.db.dir + '/functionalities/libs/iRacingChannelMap.csv') # # if not d: # print(time.strftime("%H:%M:%S", time.localtime()) + ':\t\tNo valid lap found...aborting!') # return # # d['x'], d['y'] = maths.createTrack(d) # # tempDB = RTDB.RTDB() # tempDB.initialise(d, False, False) # # # check if car available # carList = importExport.getFiles(self.db.dir + '/data/car', 'json') # carName = d['DriverInfo']['Drivers'][tempDB.DriverInfo['DriverCarIdx']]['CarScreenNameShort'] # carPath = d['DriverInfo']['Drivers'][tempDB.DriverInfo['DriverCarIdx']]['CarPath'] # # # load or create car # if carName + '.json' in carList: # self.db.car.load("data/car/" + carName + '.json') # else: # self.db.car = Car.Car(Driver=d['DriverInfo']['Drivers'][tempDB.DriverInfo['DriverCarIdx']]) # self.db.car.createCar(tempDB) # self.db.car.save(self.db.dir) # print(time.strftime("%H:%M:%S", time.localtime()) + ':\tCar has been successfully created') # # # create track # TrackName = d['WeekendInfo']['TrackName'] # track = Track.Track(TrackName) # aNorth = d['YawNorth'][0] # track.createTrack(d['x'], d['y'], d['LapDistPct']*100, aNorth, float(d['WeekendInfo']['TrackLength'].split(' ')[0])*1000) # track.save(self.db.dir) # # print(time.strftime("%H:%M:%S", time.localtime()) + ':\t\tTrack {} has been successfully created.'.format(TrackName)) # # self.db.track.load(self.db.dir + '/data/track/' + TrackName + '.json') # # print(time.strftime("%H:%M:%S", time.localtime()) + ':\t\tAdding reference lap time to car {}'.format(self.db.car.name)) # # # add lap time to car # if maths.strictly_increasing(d['tLap']) and maths.strictly_increasing(d['LapDistPct']): # self.db.car.addLapTime(TrackName, d['tLap'], d['LapDistPct']*100, track.LapDistPct, d['VFuelLap']) # self.db.car.save(self.db.dir) # print(time.strftime("%H:%M:%S", time.localtime()) + ':\t\tReference lap time set successfully!') # else: # print(time.strftime("%H:%M:%S", time.localtime()) + ':\t\tRecorded Laptime is not monotonically increasing. Aborted track creation!') def setUserFuelPreset(self): self.db.config['VUserFuelSet'] = self.spinBox_FuelSetting.value() self.db.BPitCommandUpdate = True self.retranslateUi(self.iDDU) def enableFuelUp(self): self.db.config['BBeginFueling'] = self.checkBox_FuelUp.isChecked() self.db.BPitCommandUpdate = True self.retranslateUi(self.iDDU) def setPitCommandControl(self): self.db.config['BPitCommandControl'] = self.checkBox_PitCommandControl.isChecked() self.db.BPitCommandUpdate = True self.retranslateUi(self.iDDU) def enableTyreChange(self): self.db.config['BChangeTyres'] = self.checkBox_ChangeTyres.isChecked() self.db.BPitCommandUpdate = True self.retranslateUi(self.iDDU) def setFuelSetMethod(self): self.db.config['NFuelSetMethod'] = self.comboBox_FuelMethod.currentIndex() self.db.BPitCommandUpdate = True self.retranslateUi(self.iDDU) def FuelBeep(self): self.db.config['tFuelBeep'] = self.spinBox_FuelToneDuration.value() self.db.config['fFuelBeep'] = self.spinBox_FuelToneFrequency.value() self.retranslateUi(self.iDDU) def ShiftBeep(self): self.db.config['tShiftBeep'] = self.spinBox_ShiftToneDuration.value() self.db.config['fShiftBeep'] = self.spinBox_ShiftToneFrequency.value() self.retranslateUi(self.iDDU) def testFuelTone(self): winsound.Beep(self.db.config['fFuelBeep'], self.db.config['tFuelBeep']) time.sleep(self.db.config['tLiftGap'] - self.db.config['tFuelBeep'] / 1000) winsound.Beep(self.db.config['fFuelBeep'], self.db.config['tFuelBeep']) time.sleep(self.db.config['tLiftGap'] - self.db.config['tFuelBeep'] / 1000) winsound.Beep(self.db.config['fFuelBeep'], self.db.config['tFuelBeep']) def testShiftTone(self): winsound.Beep(self.db.config['fShiftBeep'], self.db.config['tShiftBeep']) def loadFuelManagementSettings(self): OpenFileName = QFileDialog.getOpenFileName(self.iDDU, 'Load Fuel Management Configuration', './data/fuelSaving', 'JSON(*.json)') if OpenFileName == ('', ''): print(time.strftime("%H:%M:%S", time.localtime()) + ':\tNo valid path to fuel saving file provided...aborting!') return self.db.loadFuelTgt(OpenFileName[0]) self.doubleSpinBox_VFuelTGT.setMinimum(np.min(self.db.FuelTGTLiftPoints['VFuelTGT'])) self.doubleSpinBox_VFuelTGT.setMaximum(np.max(self.db.FuelTGTLiftPoints['VFuelTGT'])) self.doubleSpinBox_VFuelTGT.setProperty("value", self.db.config['VFuelTgt']) self.retranslateUi(self.iDDU) def setVFuelTgt(self): self.db.config['VFuelTgt'] = self.doubleSpinBox_VFuelTGT.value() self.retranslateUi(self.iDDU) def calcUpshiftRPM(self): getShiftRPM.getShiftRPM(self.db.dir, self.db.config['TelemPath'], self.db.config['MotecProjectPath']) self.retranslateUi(self.iDDU) def calcFuelSaving(self): fuelSavingOptimiser.optimise(self.db.dir, self.db.config['TelemPath']) self.retranslateUi(self.iDDU) def calcRollOut(self): rollOut.getRollOutCurve(self.db.dir, self.db.config['TelemPath'], self.db.config['MotecProjectPath']) self.retranslateUi(self.iDDU) def MSMapDecrease(self): mapName = self.comboBox_MultiSwitch.currentText() self.pressButton(self.dcConfig[mapName][0]+1, 0.2) self.retranslateUi(self.iDDU) def MSMapIncrease(self): mapName = self.comboBox_MultiSwitch.currentText() self.pressButton(self.dcConfig[mapName][1]+1, 0.2) self.retranslateUi(self.iDDU) def assignDriverMarker(self): self.pressButton(64, 0.2) def getJoystickControl(self): WaitingForEvent = True t = time.time() self.initJoystick(self.joystickList[self.comboBox_JoystickSelection.currentIndex()]) self.pygame.display.get_init() while WaitingForEvent and (time.time()-t) < 10: events = self.pygame.event.get() for event in events: if event.type == self.pygame.JOYBUTTONDOWN: WaitingForEvent = False print('Joystick: ' + str(event.joy)) print('Button: ' + str(event.button)) if WaitingForEvent: print(time.strftime("%H:%M:%S", time.localtime()) + ':\tNo valid Joystick input found....aborting!') else: print(time.strftime("%H:%M:%S", time.localtime()) + ':\tAssigned button {} of Joystick {}!'.format(event.button, event.joy)) return self.pygame.joystick.Joystick(event.joy).get_name(), event.button def assignButtonPreviousMulti(self): self.assignButton('PreviousMulti') def assignButtonNextMulti(self): self.assignButton('NextMulti') def assignButtonMultiIncrease(self): self.assignButton('MultiIncrease') def assignButtonMultiDecrease(self): self.assignButton('MultiDecrease') def assignButtonDDUPage(self): self.assignButton('DDUPage') def assignButton(self, name): joyID, joyButton = self.getJoystickControl() self.db.config['ButtonAssignments'][name]['Joystick'] = joyID self.db.config['ButtonAssignments'][name]['Button'] = joyButton self.SaveConfig() def LoadConfig(self): config = importExport.loadJson(self.db.dir + '/data/configs/config.json') self.db.initialise({'config': config}, False, False) self.retranslateUi(self.iDDU) def SaveConfig(self): importExport.saveJson(self.db.config, self.db.dir + '/data/configs/config.json') self.retranslateUi(self.iDDU) def refreshGUI(self): self.retranslateUi(self.iDDU) if self.db.IsOnTrack: self.iDDU.qTimer.setInterval(30000) else: self.iDDU.qTimer.setInterval(500) def SetiRPath(self): dirPath = QFileDialog.getExistingDirectory(self.iDDU, 'Select iRacing Directory', './') if dirPath == '': return self.db.config['iRPath'] = dirPath self.SaveConfig() def SetTelemPath(self): dirPath = QFileDialog.getExistingDirectory(self.iDDU, 'Select Telemetry Data Directory', './') if dirPath == '': return self.db.config['TelemPath'] = dirPath self.SaveConfig() def SetMotecPath(self): dirPath = QFileDialog.getExistingDirectory(self.iDDU, 'Select Motec Project Directory', './') if dirPath == '': return self.db.config['MotecProjectPath'] = dirPath self.SaveConfig() def setTLift(self): tLiftGap = self.doubleSpinBox_tLiftGap.value() self.db.config['tLiftGap'] = tLiftGap self.db.tLiftTones = [2*tLiftGap, tLiftGap, 0] self.retranslateUi(self.iDDU) def setTLiftReaction(self): self.db.config['tReactionLift'] = self.doubleSpinBox_tLiftReaction.value() self.retranslateUi(self.iDDU) def NFuelConsumptionMethod(self): self.db.config['NFuelConsumptionMethod'] = self.comboBox_NFuelConsumptionMethod.currentIndex() self.retranslateUi(self.iDDU) def NFuelTargetMethod(self): self.db.config['NFuelTargetMethod'] = self.comboBox_NFuelManagement.currentIndex() self.retranslateUi(self.iDDU) def __del__(self): sys.stdout = sys.__stdout__
MarcMatten/iDDU
gui/iDDUgui.py
iDDUgui.py
py
78,820
python
en
code
2
github-code
1
[ { "api_name": "libs.IDDU.IDDUThread", "line_number": 26, "usage_type": "name" }, { "api_name": "libs.IDDU.IDDUThread.__init__", "line_number": 29, "usage_type": "call" }, { "api_name": "libs.IDDU.IDDUThread", "line_number": 29, "usage_type": "name" }, { "api_name"...
15427212046
import random import requests from currency_converter import CurrencyConverter from forex_python.converter import CurrencyRates def get_guess_from_user(): while True: try: guess = float(input("Enter your guess for the value in ILS: ")) break except ValueError: print("Invalid input. Please enter a valid number.") return guess def get_money_interval(difficulty, ran_number): c = CurrencyConverter() new_amount = c.convert(ran_number, 'USD', 'ILS') difficulty_calc = (new_amount - (6 - difficulty), new_amount +(6 - difficulty)) return difficulty_calc # def old_get_money_interval(difficulty, ran_number): # response = requests.get("https://api.exchangerate-api.com/v4/latest/USD") # data = response.json() # rate = data["rates"]["ILS"] # # money_value = ran_number * rate # difficulty_calc = (money_value - (6 - difficulty), money_value +(6 - difficulty)) # # return difficulty_calc def play(difficulty): print('''Currency Roulette Game - Guess the Value in ILS! You will be given a random amount in USD. Your task is to guess the value of that amount in ILS.''') ran_number = random.randint(1, 100) money_interval = get_money_interval(difficulty, ran_number) print(f"Guess the value in ILS for the amount of {ran_number} USD.") user_guess = float(get_guess_from_user()) lower_bound = money_interval[0] upper_bound = money_interval[1] if lower_bound <= user_guess <= upper_bound: print("Congratulations! Your guess is within the correct range.") return True else: print("Sorry, your guess is outside the correct range.") return False
Almonk777/WorldOfGame
CurrencyRouletteGame.py
CurrencyRouletteGame.py
py
1,720
python
en
code
0
github-code
1
[ { "api_name": "currency_converter.CurrencyConverter", "line_number": 16, "usage_type": "call" }, { "api_name": "random.randint", "line_number": 37, "usage_type": "call" } ]
39974834021
from tensorflow import keras import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix import seaborn as sns import numpy as np from custom_models import custom_model, old_model from data_preprocessing import Preprocessing from data_augmentation import DataAugmentation from config import ConstantConfig class TrainModel: encoder = ConstantConfig().ENCODER batch_size = 64 epochs = 50 early_stopping = keras.callbacks.EarlyStopping( monitor="val_accuracy", patience=2) def __init__(self) -> None: self.preprocessing = Preprocessing() self.augmentation = DataAugmentation() img_data = self.augmentation.process_data() self.labels_train, self.labels_test, self.imgs_train, self.imgs_test = self.preprocessing.train_test_split( img_data) self.model = old_model() # model = custom_model() def train_model(self): self.model.fit(self.imgs_train, self.labels_train, batch_size=self.batch_size, epochs=self.epochs, validation_data=(self.imgs_test, self.labels_test), callbacks=[self.early_stopping]) self.save_model() def test_model(self, test_data=None): if test_data: return np.argmax(self.model.predict(test_data), axis=1) return np.argmax(self.model.predict(self.imgs_test), axis=1) def confusion_matrix(self): cm = confusion_matrix(self.labels_test, self.labels_pred, labels=list(self.encoder.inverse.keys())) plt.figure(figsize=(12, 12)) sns.heatmap(cm, annot=True, cbar=False, cmap='Blues', xticklabels=list( self.encoder.keys()), yticklabels=list(self.encoder.keys())) plt.show() def save_model(self, model_name='geo_model.model'): self.model.save(model_name, save_format='h5') if __name__ == '__main__': model_inst = TrainModel() model_inst.train_model()
AnaChikashua/Georgian-OCR
model/train_ocr.py
train_ocr.py
py
1,997
python
en
code
0
github-code
1
[ { "api_name": "config.ConstantConfig", "line_number": 15, "usage_type": "call" }, { "api_name": "tensorflow.keras.callbacks.EarlyStopping", "line_number": 18, "usage_type": "call" }, { "api_name": "tensorflow.keras.callbacks", "line_number": 18, "usage_type": "attribute" ...
3477761372
from flask import Flask, jsonify, request, make_response import torch from transformers import BertTokenizer, BertModel from sklearn.metrics.pairwise import cosine_similarity import numpy as np import pandas as pd app=Flask(__name__) # @app.route('/<string:text1>/<string:text2>') @app.route('/post_json',methods=['POST']) def hello_world(): data1=request.get_json() text1=data1['text1'] text2=data1['text2'] # Load pre-trained BERT model and tokenizer tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') model = BertModel.from_pretrained('bert-base-uncased') # Function to get sentence embeddings using BERT model def get_sentence_embedding(sentence): inputs = tokenizer(sentence, return_tensors='pt', truncation=True, padding=True) with torch.no_grad(): outputs = model(**inputs) return outputs.last_hidden_state.mean(dim=1).squeeze().numpy() # Function to calculate cosine similarity between two sentence embeddings def cosine_similarity_score(embedding1, embedding2): similarity = cosine_similarity([embedding1], [embedding2]) return similarity[0][0] embedding1 = get_sentence_embedding(text1) embedding2 = get_sentence_embedding(text2) similarity_score = cosine_similarity_score(embedding1, embedding2) result={ "similarity_score":str(similarity_score) } return jsonify(result) if __name__=="__main__": app.run(debug=True)
daringsingh22/sementicsimilar
app.py
app.py
py
1,487
python
en
code
0
github-code
1
[ { "api_name": "flask.Flask", "line_number": 8, "usage_type": "call" }, { "api_name": "flask.request.get_json", "line_number": 14, "usage_type": "call" }, { "api_name": "flask.request", "line_number": 14, "usage_type": "name" }, { "api_name": "transformers.BertToke...
72827279715
import sys from collections import deque dx = [1,-1,0,0] dy = [0,0,1,-1] n,m = map(int,sys.stdin.readline().split()) arr = [] for _ in range(m): arr.append(list(sys.stdin.readline().strip())) visit = [[int(1e9)]*n for _ in range(m)] queue = deque([[0,0]]) visit[0][0] = 0 while queue: x,y = queue.popleft() for t in range(4): nx = x + dx[t] ny = y + dy[t] if 0 <= nx < m and 0 <= ny < n: if arr[nx][ny] == '0' and visit[nx][ny] > visit[x][y]: visit[nx][ny] = visit[x][y] queue.append([nx,ny]) elif arr[nx][ny] == '1' and visit[nx][ny] > visit[x][y] + 1: visit[nx][ny] = visit[x][y] + 1 queue.append([nx,ny]) print(visit[m-1][n-1])
clapans/Algorithm_Study
박수근/all_code/1261.py
1261.py
py
767
python
en
code
0
github-code
1
[ { "api_name": "sys.stdin.readline", "line_number": 7, "usage_type": "call" }, { "api_name": "sys.stdin", "line_number": 7, "usage_type": "attribute" }, { "api_name": "sys.stdin.readline", "line_number": 10, "usage_type": "call" }, { "api_name": "sys.stdin", "l...
29062292111
from question_model import Question from data import question_data from quiz_brain import QuizBrain question_bank = [] for question in question_data: question_bank.append(Question(question["text"], question["answer"])) brain = QuizBrain(question_bank) while brain.stillHasQuestions(): brain.next_question() print("You've completed the quiz.") print(f"Your final score was {brain.guessed}/{brain.question_number}")
miklealex/PythonProjects
TrueFalseQuiz/main.py
main.py
py
429
python
en
code
0
github-code
1
[ { "api_name": "data.question_data", "line_number": 7, "usage_type": "name" }, { "api_name": "question_model.Question", "line_number": 8, "usage_type": "call" }, { "api_name": "quiz_brain.QuizBrain", "line_number": 10, "usage_type": "call" } ]
18061408079
from pathlib import Path from tensorflow.keras import layers from tensorflow.keras import models from tensorflow.keras import optimizers from tensorflow.keras.preprocessing.image import ImageDataGenerator import tensorflow as tf from solve_cudnn_error import solve_cudnn_error solve_cudnn_error() base_dir = Path('cats_and_dogs_small') train_dir = base_dir / 'train' validation_dir = base_dir / 'validation' test_dir = base_dir / 'test' train_cats_dir = train_dir / 'cats' train_dogs_dir = train_dir / 'dogs' validation_cats_dir = validation_dir / 'cats' validation_dogs_dir = validation_dir / 'dogs' test_cats_dir = test_dir / 'cats' test_dogs_dir = test_dir / 'dogs' print('total training cat images:', len(list(train_cats_dir.glob('*')))) print('total training dog images:', len(list(train_dogs_dir.glob('*')))) print('total validation cat images:', len(list(validation_cats_dir.glob('*')))) print('total validation dog images:', len(list(validation_dogs_dir.glob('*')))) def create_model(): model = models.Sequential() model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3))) model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Conv2D(64, (3, 3), activation='relu')) model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Conv2D(128, (3, 3), activation='relu')) model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Flatten()) model.add(layers.Dense(64, activation='relu')) model.add(layers.Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer=optimizers.SGD(lr=0.01), metrics=['acc']) return model model = create_model() model.summary() train_datagen = ImageDataGenerator(rescale=1./255,) test_datagen = ImageDataGenerator(rescale=1./255) train_generator = train_datagen.flow_from_directory(train_dir, target_size=(150, 150), batch_size=32, class_mode='binary') validation_generator = test_datagen.flow_from_directory(validation_dir, target_size=(150, 150), batch_size=32, class_mode='binary') callbacks = [] callbacks.append(tf.keras.callbacks.ModelCheckpoint('./checkpoint.h5', save_best_only=True, save_weights_only=False)) history = model.fit_generator(train_generator, steps_per_epoch=train_generator.__len__(), callbacks=callbacks, epochs=30, validation_data=validation_generator, validation_steps=validation_generator.__len__()) # Plot training history import matplotlib.pyplot as plt acc = history.history['acc'] val_acc = history.history['val_acc'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(len(acc)) plt.plot(epochs, acc, 'bo', label='Training acc') plt.plot(epochs, val_acc, 'b', label='Validation acc') plt.title('Training and validation accuracy') plt.legend() plt.savefig('acc.png') plt.figure() plt.plot(epochs, loss, 'bo', label='Training loss') plt.plot(epochs, val_loss, 'b', label='Validation loss') plt.title('Training and validation loss') plt.legend() plt.savefig('loss.png')
enrongtsai/Horovod-practice
original_cat_dog.py
original_cat_dog.py
py
3,594
python
en
code
2
github-code
1
[ { "api_name": "solve_cudnn_error.solve_cudnn_error", "line_number": 9, "usage_type": "call" }, { "api_name": "pathlib.Path", "line_number": 11, "usage_type": "call" }, { "api_name": "tensorflow.keras.models.Sequential", "line_number": 30, "usage_type": "call" }, { ...
33711265867
import pandas as pd from dateutil import parser import numpy as np def load_data(_file, pct_split): """Load test and train data into a DataFrame :return pd.DataFrame with ['test'/'train', features]""" # load train and test data data = pd.read_csv(_file) # split into train and test using pct_split # data_train = ... # data_test = ... # concat and label # data_out = pd.concat([data_train, data_test], keys=['train', 'test']) data_out = data return data_out def preprocess_data(df): """ General element-wise cleanup of full data set :return: df, cleaned data """ # convert time to datetime df['time'] = pd.to_datetime(df['time'], errors='coerce') return df from datetime import timedelta import numpy as np import pandas as pd def create_target(df): def btc_target(row): time_window = df['price'][(df['time'] > row) & (df['time'] <= row + timedelta(minutes=30))].values # return null if nothing is within this time window if len(time_window) == 0: return None # calculate thresholds minY = np.min(time_window) maxY = np.max(time_window) currentY = time_window[0] thresh_low = currentY * (1 - 0.0025) thresh_hi = currentY * (1 + 0.0025) # determine which thresholds are exceeded exceeds_low = minY <= thresh_low exceeds_hi = maxY >= thresh_hi # do Boolean logic to create a target. {neither: 0, high: 1, low: 0, both: 2} if (not exceeds_low) and (not exceeds_hi): target = 0 elif exceeds_low and (not exceeds_hi): target = 1 elif (not exceeds_low) and exceeds_hi: target = 2 else: target = 3 return target df['target'] = df['time'].apply(btc_target) return df def forward_window_vals(time_col, val_col): return
braddeutsch/example_pipeline
btc_battle/data/make_dataset.py
make_dataset.py
py
1,960
python
en
code
0
github-code
1
[ { "api_name": "pandas.read_csv", "line_number": 11, "usage_type": "call" }, { "api_name": "pandas.to_datetime", "line_number": 32, "usage_type": "call" }, { "api_name": "datetime.timedelta", "line_number": 46, "usage_type": "call" }, { "api_name": "numpy.min", ...
26112150368
# This files contains your custom actions which can be used to run # custom Python code. # # See this guide on how to implement these action: # https://rasa.com/docs/rasa/custom-actions # This is a simple example for a custom action which utters "Hello World!" from typing import Any, Text, Dict, List # from rasa_sdk import Action, Tracker from rasa_sdk.executor import CollectingDispatcher # # # class ActionHelloWorld(Action): # # def name(self) -> Text: # return "action_hello_world" # # def run(self, dispatcher: CollectingDispatcher, # tracker: Tracker, # domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: # # dispatcher.utter_message(text="Hello World!") # # return [] class ActionSymptoms(Action): def name(self) -> Text: return "action_symptoms" async def run(self,dispatcher, tracker : Tracker, domain : Dict[Text,Any],) -> List[Dict[Text,Any]]: fever = tracker.get_slot("fever") cough = tracker.get_slot("cough") cold = tracker.get_slot("cold") tiredness = tracker.get_slot("tiredness") loss_of_taste = tracker.get_slot("loss-of-taste") difficulty_in_breathing = tracker.get_slot("difficulty-in-breathing") chest_pain = tracker.get_slot("chest-pain") print(fever, cough, cold, tiredness, loss_of_taste, difficulty_in_breathing, chest_pain) lookup_table = [ fever, cough, cold, tiredness, loss_of_taste, difficulty_in_breathing, chest_pain] slots = [ "fever", "cough", "cold", "tiredness", "loss-of-taste", "difficulty-in-breathing", "chest-pain"] score = 7 print(type(difficulty_in_breathing)) for i in lookup_table: if ( i == False): score =- 1 if (score == 7): dispatcher.utter_message(text="You have high chances of having covid19 , please consult a doctor") elif (score >= 4 and score <= 6): dispatcher.utter_message(text="You have chances of having covid19 , please consult take rest, [medication comes here]") elif (score >= 1 and score <= 3): dispatcher.utter_message(text="You have low chances of having covid19 , please isolate your self and take rest") dispatcher.utter_message(text = "I don't think you may have covid19") return []
RupakBiswas-2304/covid-bot
actions/actions.py
actions.py
py
2,360
python
en
code
1
github-code
1
[ { "api_name": "rasa_sdk.Action", "line_number": 29, "usage_type": "name" }, { "api_name": "typing.Text", "line_number": 30, "usage_type": "name" }, { "api_name": "rasa_sdk.Tracker", "line_number": 33, "usage_type": "name" }, { "api_name": "typing.Dict", "line_...
11373411713
# -*- coding: utf-8 -*- """Implementation of the Airfield class.""" import logging import random import math import pygame from airportgame.runway import Runway from airportgame.utilities import vec2tuple, distance_between class Airfield(): """ Airfield that contains runways. """ FIELD_HEIGHT = 200 FIELD_WIDTH = 400 MINIMUM_DISTANCE = 40 TRANSPARENCY_COLORKEY = (1, 2, 3) EDGE_BUFFER = 15 def __init__(self, offset=(0, 0)): self.logger = logging.getLogger(__name__ + "." + type(self).__name__) # TODO: airfield size based on difficulty self.max_runways = 10 self.min_runways = 3 self.offset = offset # Airfield is created here self.reset_airfield() def reset_airfield(self): """Reset current airfield and create a new one""" self.logger.debug("Resetting airfield") self.runway_list = [] self.create_airfield() self.airfield_map = pygame.Surface( (self.FIELD_WIDTH, self.FIELD_HEIGHT)) self.airfield_map.fill(self.TRANSPARENCY_COLORKEY) self.airfield_map.set_colorkey(self.TRANSPARENCY_COLORKEY) self.update_map() def create_airfield(self): """ Randomly fills the airfield with runways """ number_of_runways = random.randint(self.min_runways, self.max_runways) # Initialize the list of runways runways = [0] * number_of_runways length = 0 for i in range(number_of_runways): # Make sure that there is at least one runway of each length if i <= 2: length += 1 else: length = random.randint(1, 3) # Get the full length of the runway. runway_length = Runway.RUNWAY_LENGTH_ENUM[length] start_point_found = False while not start_point_found: s_x, s_y = self.get_random_point_inside_airfield() start_point_found = self.compare_points((s_x, s_y), i) start = (s_x, s_y) end_point_found = False # Counter to prevent infinite loops temp = 0 while not end_point_found: temp += 1 angle = random.random() * math.pi * 2.0 e_x = math.cos(angle) * runway_length e_y = math.sin(angle) * runway_length # Make sure the endpoints are inside the airfield if s_x + e_x > self.FIELD_WIDTH or s_x + e_x < 0: e_x = s_x - e_x else: e_x = s_x + e_x if s_y + e_y > self.FIELD_HEIGHT or s_y + e_y < 0: e_y = s_y - e_y else: e_y = s_y + e_y e_x = int(e_x) e_y = int(e_y) end = (e_x, e_y) end_point_found = (self.compare_points(end, i) and self.point_inside_airfield(end)) if temp == 1000: # Just use this one if we actually end up here self.logger.warning( "Unoptimal runway end point for runway #%d !", (i + 1)) end_point_found = True # start point should be to the left of end: if e_x < s_x: start, end = end, start runways[i] = (start, end) if not self.point_inside_airfield(start): self.logger.warning("Runway %d start outside airfield!", i+1) if not self.point_inside_airfield(end): self.logger.warning("Runway %d end outside airfield!", i+1) new_runway = Runway(self.add_offset_to_tuple(start), self.add_offset_to_tuple(end), i+1, length) self.runway_list.append(new_runway) return def get_runways(self): """Return a list of the runways on the airfield. Returns: list -- A list of runways. """ return self.runway_list def compare_points(self, point, index): """ Checks that the starting and ending points of all other runways are far enough of the one being tested. """ if index == 0: return True for runway_i in range(index): runway = self.runway_list[runway_i] start, end = runway.get_start_and_end_pos() start = self.remove_offset_from_tuple(start) end = self.remove_offset_from_tuple(end) if (distance_between(point, start) < self.MINIMUM_DISTANCE or distance_between(point, end) < self.MINIMUM_DISTANCE): return False if self.dist_to_segment(start, end, point) < (self.MINIMUM_DISTANCE): return False return True def update_map(self): """Draws and paints the runways on the airfield map.""" for runway in self.runway_list: runway.draw(self.airfield_map, self.get_offset()) for runway in self.runway_list: runway.paint(self.airfield_map, self.get_offset()) def get_airfield_map(self): """Return the map of the airfield. Returns: Surface -- The map of the airfield. """ return self.airfield_map def draw(self, screen): """Draws the airfield. Arguments: screen {Surface} -- Surface to draw on. """ screen.blit(self.airfield_map, self.offset) def get_offset(self): """Return the offset of the airfield. Returns: Vector2 -- Offset """ return pygame.math.Vector2(self.offset) def add_offset_to_tuple(self, point): """Adds elementwise the given point tuple to the offset. Arguments: point {tuple} -- A tuple of two numbers. Returns: x -- New x coordinate y -- New y coordinate """ offset_x, offset_y = self.offset return (point[0] + offset_x, point[1] + offset_y) def remove_offset_from_tuple(self, point): """Subtract elementwise the offset from the given point tuple. Arguments: point {tuple} -- A tuple of two numbers. Returns: x -- New x coordinate y -- New y coordinate """ offset_x, offset_y = self.offset return (point[0] - offset_x, point[1] - offset_y) def point_inside_airfield(self, point, use_buffer=True): """Returns true if the given point is inside the airfield. Arguments: point {tuple} -- Coordinates of a point. Keyword Arguments: use_buffer {bool} -- Whether EDGE_BUFFER should be used. (default: {True}) Returns: bool -- True if point is inside the airfield. """ buffer = self.EDGE_BUFFER if use_buffer else 0 is_inside = ( (buffer <= point[0] <= self.FIELD_WIDTH - buffer) and (buffer <= point[1] <= self.FIELD_HEIGHT - buffer) ) return is_inside def get_random_point_inside_airfield(self): """Pick a random point inside the airfield. Returns: int -- x-coordinate int -- y-coordinate """ x = random.randint( self.EDGE_BUFFER, self.FIELD_WIDTH - self.EDGE_BUFFER) y = random.randint( self.EDGE_BUFFER, self.FIELD_HEIGHT - self.EDGE_BUFFER) return x, y def dist_to_segment(self, start, end, point): """Return the shortest distance between given segment a point. Arguments: start {Vector2} -- Start point of segment end {Vector2} -- End point of segment point {Vector2} -- Point Returns: float -- Shortest distance between segment and point. """ # https://stackoverflow.com/a/1501725 segment_length = distance_between(start, end) if segment_length == 0: return distance_between(start, point) try: vec_a = point - start vec_b = end - start except TypeError: start = pygame.math.Vector2(start) vec_a = pygame.math.Vector2(point) - start vec_b = pygame.math.Vector2(end) - start projection = vec_a.dot(vec_b) / (segment_length ** 2) t = max(0, min(1, projection)) projection_point = start + t * vec_b return distance_between(point, vec2tuple(projection_point))
soikkea/airportgame
airportgame/airfield.py
airfield.py
py
8,706
python
en
code
0
github-code
1
[ { "api_name": "logging.getLogger", "line_number": 27, "usage_type": "call" }, { "api_name": "pygame.Surface", "line_number": 45, "usage_type": "call" }, { "api_name": "random.randint", "line_number": 55, "usage_type": "call" }, { "api_name": "random.randint", ...
1270621755
import requests import pandas as pd from alpha_vantage.timeseries import TimeSeries import numpy as np def sharpe_sortino_beta(ticker='TSLA', market_returns='SPY'): try: ts = TimeSeries(key='SWKZ23Y8HKIF4N4A', output_format='pandas') data, meta_data = ts.get_daily_adjusted(ticker) returns = data['4. close'].pct_change() mar = 0.03 # minimum acceptable return downside_returns = returns[returns < mar] mean_return = returns.mean() std_return = returns.std() downside_std = downside_returns.std() sharpe_ratio = (mean_return - mar) / std_return sortino_ratio = (mean_return - mar) / downside_std data_market, meta_data = ts.get_daily_adjusted(market_returns) market_returns = data_market['4. close'].pct_change() beta_value = returns.cov(market_returns) / market_returns.var() print("Sharpe Ratio:", sharpe_ratio) ### return of asset - market return / stdev print("Sortino Ratio:", sortino_ratio) ### return of asset - market return / stdev of down side print("beta_value:",beta_value) ### measure of volatility return {"Sharpe" : sharpe_ratio, "Sortino" : sortino_ratio,"Beta" : beta_value} except: return 0,0,0 country = 'United States' api_url = 'https://api.api-ninjas.com/v1/inflation?country={}'.format(country) response = requests.get(api_url, headers={'X-Api-Key': 'c7AocO5JS7P7LDykTMtnVA==tdnVQnHKRI0ChLS3'}) if response.status_code == requests.codes.ok: l = eval(response.text)[0] r = float(l['yearly_rate_pct']) print(r) else: print("Error:", response.status_code, response.text) print(sharpe_sortino_beta("VERU"))
HudsonHurtig/TamuHack2023
StockData.py
StockData.py
py
1,756
python
en
code
0
github-code
1
[ { "api_name": "alpha_vantage.timeseries.TimeSeries", "line_number": 10, "usage_type": "call" }, { "api_name": "requests.get", "line_number": 37, "usage_type": "call" }, { "api_name": "requests.codes", "line_number": 38, "usage_type": "attribute" } ]
42654133120
#!/usr/bin/env python3 # Written by Telekrex import pygame import sys import os os.environ['SDL_VIDEO_CENTERED'] = '1' tps = 30 pygame.init() pygame.display.set_caption('Color Calibrator') monitor = (pygame.display.Info().current_w, pygame.display.Info().current_h) clock = pygame.time.Clock() void = pygame.display.set_mode(monitor, pygame.RESIZABLE) colors = ['white', 'blue', 'green', 'red', 'yellow', 'cyan', 'magenta', 'gray', 'black'] index = 0 def update_display(): global void global index global colors void.fill(colors[index]) update_display() r = True while r: clock.tick(tps) for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_RETURN: if index == len(colors)-1: index = 0 else: index += 1 update_display() if event.key == pygame.K_ESCAPE: r = False sys.exit() pygame.display.flip()
telekrex/colorbase
source/colorbase.py
colorbase.py
py
1,018
python
en
code
1
github-code
1
[ { "api_name": "os.environ", "line_number": 6, "usage_type": "attribute" }, { "api_name": "pygame.init", "line_number": 8, "usage_type": "call" }, { "api_name": "pygame.display.set_caption", "line_number": 9, "usage_type": "call" }, { "api_name": "pygame.display", ...
13223932657
from reference_model.Lactose.LactoseCrystallizer import LactoseCrystallizer from data.Data import Data, Batch from domain.Domain import Domain import numpy as np import seaborn as sns from data.Illustration import Illustration import matplotlib.pyplot as plt sns.set() # Construct discretized domain object for hybrid model domain = Domain(name='Domain') domain.add_axis(x_min=5, x_max=150, m=300, disc_by='FeretMean', name='FeretMean') # Construct artificial crystallizer crystallizer = LactoseCrystallizer(domain=domain, save_intermediates=False, verbose=False) # Accumulated data data = Data(case_id='Demo data') for batch_id in range(10): data.add_batch(Batch(batch_id='Demo batch '+str(batch_id))) initial_measurement = crystallizer.start_new_batch(N0=np.concatenate(([100], np.zeros(domain.axis[0].m-1))), C0=0.000445085 + np.random.normal(loc=0, scale=0.00005), T0=50 + np.random.normal(loc=0, scale=5), step_size=5*60, noise_level=0) data.batches[-1].add_measurement(initial_measurement) for _ in range(30): data.batches[-1].add_measurement(crystallizer.get_next_measurement(-0.00444)) data.save_to_pickle('demo_data') illustrator = Illustration(data=data) illustrator.plot_count_time(variable_name='FeretMean', category='particle_analysis') # fig, ax = plt.subplots() # sns.distplot(data.batches[-1].measurements[-1].particle_analysis_sensors[0].value, bins=domain.axis[0].edges(), ax=ax) # plt.show() # print(np.median(data.batches[-1].measurements[-1].particle_analysis_sensors[0].value))
rfjoni/ParticleModel
reference_model/Lactose/demo.py
demo.py
py
1,694
python
en
code
7
github-code
1
[ { "api_name": "seaborn.set", "line_number": 8, "usage_type": "call" }, { "api_name": "domain.Domain", "line_number": 11, "usage_type": "name" }, { "api_name": "domain.Domain.Domain", "line_number": 11, "usage_type": "call" }, { "api_name": "domain.Domain.add_axis"...
24349296351
import json from pprint import pprint import requests import logbook from log_book import init_logger logger = logbook.Logger(__file__) def main(): init_logger('movie-app.log') logbook.info("Starting the omdb search app...") logbook.debug("Getting user's input...") movie_name = get_user_input() logbook.debug("Loading '{0}' data...".format(movie_name)) movie_data = load_movie_data(movie_name) logbook.debug("Displaying Awards...".format(movie_name)) display_awards(movie_data, movie_name) logbook.debug("Displaying Ratings...".format(movie_name)) displays_ratings(movie_data) def get_user_input(): user_input = input('Movie name: ') return user_input def load_movie_data(movie_name): request = requests.get('http://www.omdbapi.com/?apikey=3e6f7dd7&t={}'.format(movie_name)) json_result = json.loads(request.text) return json_result def display_awards(movie_data, movie_name): print("{}'s Awards: {}".format(movie_name, movie_data['Awards'])) def displays_ratings(movie_data): for rating in movie_data['Ratings']: display_rating(rating) def display_rating(rating): value = rating['Value'] value = parse_value(value) print(f"{rating['Source']} - {value}") def parse_value(value: str): logbook.debug("Parsing value '{0}'...".format(value)) if value.endswith('%'): value = value.replace('%','') return '{}/10'.format(int(value) / 10) elif value.endswith('100'): (value, _) = value.split('/') return '{}/10'.format(int(value) / 10) else: (value, _) = value.split('/') return '{}/10'.format(float(value) * 1.0) if __name__ == '__main__': main()
pgmilenkov/100daysofcode-with-python-course
days/40-42-json-data/omdb_parse.py
omdb_parse.py
py
1,714
python
en
code
null
github-code
1
[ { "api_name": "logbook.Logger", "line_number": 7, "usage_type": "call" }, { "api_name": "log_book.init_logger", "line_number": 11, "usage_type": "call" }, { "api_name": "logbook.info", "line_number": 12, "usage_type": "call" }, { "api_name": "logbook.debug", "...
33524555484
from tkinter import * from tkinter.ttk import * from tkinter import scrolledtext import os import tkinter.filedialog as filedialog from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk # Implement the default Matplotlib key bindings. from matplotlib.backend_bases import key_press_handler from matplotlib.figure import Figure import numpy as np from Luna import * # root = tkinter.Tk() # root.wm_title("Embedding in Tk") theme_color = "white" #"#073763" button_color = "#0a70cf" text_color = "white" # style = Style() # style.theme_use('alt') # style.configure('TButton', background = button_color, foreground = text_color, borderwidth=1, focusthickness=3, focuscolor='none') # style.map('TButton', background=[('active',"grey")]) """ Acquired on 9/23/2020 at 13:25:38 Device Descriptor: [none] Number of Scan Averages: 4 Time Domain Window Resolution Bandwidth (pm): 56.212469 Filter Resolution Bandwidth (pm): 19.360054 Convolved Resolution Bandwidth (pm): 59.452951 Channel Width: 25.000 nm """ if 0: gui = Tk() gui.title("Luna Post-Processing Tool") label = Label(gui, text="Current file:").grid() def open(): current_dir = os.getcwd() chosen_file = filedialog.askopenfile(parent=gui, initialdir=current_dir, title='Select a Luna Text File.') print(chosen_file.name) open_button = Button(gui,text="Open",command=open).grid() def save(): pass save_button = Button (gui, text="Save", command=save).grid() fig = Figure(figsize=(7, 5), dpi=100) t = np.arange(0, 3, .01) fig.add_subplot(111).plot(t, 2 * np.sin(2 * np.pi * t)) fig.gca().set_facecolor(theme_color) fig.set_facecolor(theme_color) canvas = FigureCanvasTkAgg(fig, master=gui) # A tk.DrawingArea. canvas.draw() canvas.get_tk_widget().grid(column=1) # NavigationToolbar2TkAgg(canvas, gui).grid() toolbar_frame = Frame(gui) toolbar_frame.grid(column=1) toolbar = NavigationToolbar2Tk( canvas, toolbar_frame ) # label.grid(column=0, row=0) # Dimensions of the window w = 950 # width for the Tk root h = 650 # height for the Tk root ws = gui.winfo_screenwidth() # width of the screen hs = gui.winfo_screenheight() # height of the screen x = (ws/2) - (w/2) y = (hs/2) - (h/2) gui.geometry('%dx%d+%d+%d' % (w, h, x, y)) # Library management # def Check1(): # if chk1State.get() == 1: # txtlib1 = Entry(gui,width=10) # else: # txtlib1 = Entry(gui,width=10,state="disabled") # txtlib1.grid(column=1,row=startRow+1) # def Check2(): # if chk2State.get() == 1: # txtlib2 = Entry(gui,width=10) # else: # txtlib2 = Entry(gui,width=10,state="disabled") # txtlib2.grid(column=1,row=startRow+2) # def Check3(): # if chk3State.get() == 1: # txtlib3 = Entry(gui,width=10) # else: # txtlib3 = Entry(gui,width=10,state="disabled") # txtlib3.grid(column=1,row=startRow+3) # startRow = 2 # versionTxt = Label(gui, text="Version") # versionTxt.grid(column=1, row=startRow) # chk1State = BooleanVar() # chk1State.set(True) # Check1() # chk1 = Checkbutton(gui,text="SiEPIC-Tools",variable=chk1State,command=Check1,) # chk1.grid(column=0,row=startRow+1) # txtlib1 = Entry(gui,width=10) # txtlib1.grid(column=1,row=startRow+1) # chk2State = BooleanVar() # chk2State.set(True) # Check2() # chk2 = Checkbutton(gui,text="SiEPIC EBeam PDK",variable=chk2State,command=Check2) # chk2.grid(column=0, row=startRow+2) # txtlib2 = Entry(gui,width=10) # txtlib2.grid(column=1,row=startRow+2) # chk3State = BooleanVar() # chk3State.set(True) # Check3() # chk3 = Checkbutton(gui,text="Ulaval PDK",variable=chk3State, command=Check3) # chk3State.get() # chk3.grid(column=0, row=startRow+3) # # Users # # usrNum=3 # def addUser(): # userList = np.ones(2,1) # print(allUsrs) # # frame.pack() # newUsr = Entry(gui,width=15).grid(column=3,row=9) # allUsrs.append(newUsr) # return allUsrs # UsersTxt = Label(gui,text="Users").grid(column=3,row=startRow) # usr1 = Entry(gui,width=15).grid(column=3,row=startRow+1) # usr2 = Entry(gui,width=15).grid(column=3,row=startRow+2) # usr3 = Entry(gui,width=15).grid(column=3,row=startRow+3) # usr4 = Entry(gui,width=15).grid(column=3,row=startRow+4) # usr5 = Entry(gui,width=15).grid(column=3,row=startRow+5) # usr6 = Entry(gui,width=15).grid(column=3,row=startRow+6) # # Finalize buttons # def Create(): # gui.destroy() # os.system("python ProjectCreator.py") # successGui = Tk() # successGui.title("Success") # w = 200 # width for the Tk root # h = 100 # height for the Tk root # ws = successGui.winfo_screenwidth() # width of the screen # hs = successGui.winfo_screenheight() # height of the screen # x = (ws/2) - (w/2) # y = (hs/2) - (h/2) # successGui.geometry('%dx%d+%d+%d' % (w, h, x, y)) # label = Label(successGui, text="Project successfully created.") # label.grid(column=0, row=0) # def SuccessOK(): # successGui.destroy() # okBtn = Button(successGui, text=" OK ", width="6", bg="blue", fg="blue",command=SuccessOK) # okBtn.grid(column=0,row=1) # ghost = Label(gui,text=" ").grid(column=2,row=9) # createBtn = Button(gui, text=" Create ", width="8", bg="blue", fg="blue",command=Create) # createBtn.grid(column=1,row=10) # def Cancel(): # gui.destroy() # cancelBtn = Button(gui,text=" Cancel ",width="8", bg="blue", fg="blue",command=Cancel) # cancelBtn.grid(column=3,row=10) gui.configure(bg=theme_color) class LunaGUI: accent_color = "orangered" def __init__(self, root): self.root = root self.root.title("Luna Post-Processing Tool") self.window_geometry() self.make_style() self.tools_frame = Frame(self.root) self.tools_frame.grid(pady=2) self.plot_frame = Frame(self.root) self.plot_frame.grid(row=0, column=1) self.current_file_label = Label(self.plot_frame, text="No file selected") self.current_file_label.grid(column=1) self.open_button = Button(self.tools_frame, text="Open", command=self.open_button).grid(pady=2, padx=5) self.save_button = Button(self.tools_frame, text="Save", command=self.save_button).grid(pady=2) self.file_info = Label(self.tools_frame, text="text \ntext \nsome more text motherfucker") self.file_info.grid(pady=2) self.place_plot() def open_button(self): current_dir = os.getcwd() chosen_file = filedialog.askopenfile(parent=self.root, initialdir=current_dir, title='Select a Luna Text File.') self.file = chosen_file.name self.current_file_label.configure(text="Current file: " + self.file) self.meas = LunaMeasurement(self.file) self.fig.gca().clear() self.fig.gca().plot(self.meas.wavelength, self.meas.insertion_loss) self.figure_canvas.draw() # update file info text # with open(self.file, "r") as f: # self.file_header = [f.readline() for i in range(7)] # header = "" # for line in self.file_header: # header = header + line # self.file_info.configure(text=header) def update_plot(self, x, y): pass def place_plot(self): self.fig = Figure(figsize=(7, 5), dpi=100) t = np.arange(0, 3, .01) self.fig.add_subplot(111).plot(t, 2 * np.sin(2 * np.pi * t), c=self.accent_color) self.fig.gca().set_facecolor("dimgrey") self.fig.set_facecolor("k") self.fig.gca().spines["bottom"].set_color("white") self.fig.gca().spines['top'].set_color('white') self.fig.gca().spines['right'].set_color('white') self.fig.gca().spines['left'].set_color('white') self.fig.gca().xaxis.label.set_color('white') self.fig.gca().grid() self.fig.gca().tick_params(axis='both', colors='white') self.fig.gca().yaxis.label.set_color('white') # self.fig.gca().tick_params(axis='x', colors='white') self.figure_canvas = FigureCanvasTkAgg(self.fig, master=root) # A tk.DrawingArea. self.figure_canvas.draw() self.figure_canvas.get_tk_widget().grid(row=1, column=1, rowspan=9) # NavigationToolbar2TkAgg(canvas, gui).grid() self.toolbar_frame = Frame(self.root) self.toolbar_frame.grid(column=1) self.toolbar = NavigationToolbar2Tk( self.figure_canvas, self.toolbar_frame ) def save_button(self): pass def make_style(self): """ define color and appearance of GUI """ background_color = "black" button_color_1 = "grey26" button_color_2 = "grey70" text_color = "white" self.root.configure(bg=background_color) # background color self.style = Style() self.style.theme_use('alt') # Widget style definitions self.style.configure("TButton", background = button_color_1, foreground = text_color, width=25, padding=20, relief="flat" , borderwidth=0, padx=5, pady=5) self.style.configure("TFrame", background=background_color) self.style.configure("TLabel", foreground="white", background="black") self.style.map('TButton', background=[('active', self.accent_color)]) def window_geometry(self): w = 950 # width for the Tk root h = 650 # height for the Tk root ws = self.root.winfo_screenwidth() # width of the screen hs = self.root.winfo_screenheight() # height of the screen x = (ws/2) - (w/2) y = (hs/2) - (h/2) self.root.geometry('%dx%d+%d+%d' % (w, h, x, y)) # def open(): # current_dir = os.getcwd() # chosen_file = filedialog.askopenfile(parent=gui, initialdir=current_dir, title='Select a Luna Text File.') # print(chosen_file.name) # open_button = Button(gui,text="Open",command=open).grid() # def save(): # pass # save_button = Button (gui, text="Save", command=save).grid() # fig = Figure(figsize=(7, 5), dpi=100) # t = np.arange(0, 3, .01) # fig.add_subplot(111).plot(t, 2 * np.sin(2 * np.pi * t)) # fig.gca().set_facecolor(theme_color) # fig.set_facecolor(theme_color) # canvas = FigureCanvasTkAgg(fig, master=gui) # A tk.DrawingArea. # canvas.draw() # canvas.get_tk_widget().grid(column=1) # # NavigationToolbar2TkAgg(canvas, gui).grid() # toolbar_frame = Frame(gui) # toolbar_frame.grid(column=1) # toolbar = NavigationToolbar2Tk( canvas, toolbar_frame ) # self.greet_button = Button(master, text="Greet", command=self.greet) # self.greet_button.grid() # self.close_button = Button(master, text="Close", command=master.quit) # self.close_button.grid() def greet(self): print("Greetings!") root = Tk() luna_gui = LunaGUI(root) root.mainloop()
JonathanCauchon/LunaUtils
GUI.py
GUI.py
py
11,420
python
en
code
1
github-code
1
[ { "api_name": "os.getcwd", "line_number": 45, "usage_type": "call" }, { "api_name": "tkinter.filedialog.askopenfile", "line_number": 46, "usage_type": "call" }, { "api_name": "tkinter.filedialog", "line_number": 46, "usage_type": "name" }, { "api_name": "matplotli...
19388016465
from audioop import ratecv from pathlib import Path import tkinter as tk from tkinter import ttk from tkinter.filedialog import askopenfilename import PIL.Image import PIL.ImageTk # Defining of global variables... _MODULE_DIR = Path(__file__).resolve().parent class GifAnimationWin(tk.Tk): def __init__( self, res_dir: str | Path, screenName: str | None = None, baseName: str | None = None, className: str = 'Tk', useTk: bool = True, sync: bool = False, use: str | None = None ) -> None: super().__init__(screenName, baseName, className, useTk, sync, use) self.geometry('600x450+200+200') self.title('GIF animation') self._TIME_FRAME_RATE: int = 100 """Specifies the frame rate of the GIF frames.""" self._RES_DIR = res_dir self._frames: list[PIL.ImageTk.PhotoImage] = [] # Resources... self._IMG_BROWSE: PIL.ImageTk.PhotoImage self._LoadRes() self._InitializeGui() def _LoadRes(self) -> None: # Loading images... # Loading 'browse.png'... self._IMG_BROWSE = self._RES_DIR / 'browse.png' self._IMG_BROWSE = PIL.Image.open(self._IMG_BROWSE) self._IMG_BROWSE = self._IMG_BROWSE.resize(size=(24, 24,)) self._IMG_BROWSE = PIL.ImageTk.PhotoImage(image=self._IMG_BROWSE) def _InitializeGui(self) -> None: # self._frm_container = ttk.Frame( master=self) self._frm_container.columnconfigure( index=0, weight=1) self._frm_container.rowconfigure( index=1, weight=1) self._frm_container.pack( fill=tk.BOTH, expand=1) # self._frm_toolbar = ttk.Frame( master=self._frm_container) self._frm_toolbar.rowconfigure( index=0, weight=1) self._frm_toolbar.grid( column=0, row=0, sticky=tk.NW) # self._lbl_browse = ttk.Button( master=self._frm_toolbar, image=self._IMG_BROWSE, command=self._BrowseFiles) self._lbl_browse.grid( column=0, row=0, sticky=tk.W) # self._frm_gif = ttk.Frame( master=self._frm_container) self._frm_gif.columnconfigure( index=0, weight=1) self._frm_gif.rowconfigure( index=0, weight=1) self._frm_gif.grid( column=0, row=1, sticky=tk.NSEW) # self._lbl_gif = ttk.Label( master=self._frm_gif) self._lbl_gif.grid( column=0, row=0) def _BrowseFiles(self) -> None: gifFile = askopenfilename( title='Browse for GIF files', filetypes=[('GIF files', '*.gif')], initialdir=_MODULE_DIR) if gifFile: self._LoadGif(gifFile) def _LoadGif(self, gif_file: str) -> None: gifFile = PIL.Image.open(gif_file) self._frames.clear() frameRates: list[int] = [] idx = 0 while True: try: gifFile.seek(idx) self._frames.append( PIL.ImageTk.PhotoImage(image=gifFile)) frameRates.append(gifFile.info['duration']) idx += 1 except KeyError: idx += 1 except EOFError : break # Calculating the average frame rate... frameRates = [ rate for rate in frameRates if rate] try: self._TIME_FRAME_RATE = round(sum(frameRates) / len(frameRates)) except ZeroDivisionError: # Specifying the default frame rate... self._TIME_FRAME_RATE = 100 # Animating the GIF... self.after( self._TIME_FRAME_RATE, self._AnimateGif, 0) def _AnimateGif(self, frame_index: int) -> int: try: self._lbl_gif['image'] = self._frames[frame_index] except IndexError: frame_index = 0 self._lbl_gif['image'] = self._frames[frame_index] self.after( self._TIME_FRAME_RATE, self._AnimateGif, frame_index + 1) if __name__ == '__main__': gifAnimationWin = GifAnimationWin( res_dir=_MODULE_DIR / 'res') gifAnimationWin.mainloop()
megacodist/a-bit-more-of-an-interest
Image/gif-animation.pyw
gif-animation.pyw
pyw
4,641
python
en
code
0
github-code
1
[ { "api_name": "pathlib.Path", "line_number": 12, "usage_type": "call" }, { "api_name": "tkinter.Tk", "line_number": 15, "usage_type": "attribute" }, { "api_name": "pathlib.Path", "line_number": 18, "usage_type": "name" }, { "api_name": "PIL.Image.ImageTk", "li...
40639476449
from pygame.locals import * import numpy as np import os import pygame import sys import time from source.core.game_objects.bomb.Bomb import Bomb from source.core.game_objects.bomb.Fire import Fire from source.core.game_objects.character.Cpu import Cpu from source.core.ui.GameOver import GameOver from source.core.ui.Map import Map from source.core.ui.Pause import Pause from source.core.utils import Constants from source.core.utils.ObjectEvents import CharacterEvents class Match: """ Class which represents a match. It handles all game objects interactions, user inputs and cpu decisions. """ def __init__(self, characters, sprites): """ Default constructor. It assigns initial values to all variables. :param characters: Tuple of characters, with the first element being the list of players and the second the list of cpus in the match. :param sprites: Dict of sprites previously loaded. """ self.__sprites = sprites # Loading font assets_path = (os.path.dirname(os.path.realpath(__file__)) + '/../../../assets/') self.__menu_font = pygame.font.Font(assets_path + "font/04B_30__.TTF", Constants.FONT_SIZE) # Creating map and game objects self.__map = Map(time.time()) self.__players = characters[0] self.__cpus = characters[1] self.__bombs = list() self.__fires = list() # Array indicating characters which are still alive self.__alive_characters = False * np.ones(4) for player in self.__players: self.__alive_characters[player.id] = True for cpu in self.__cpus: self.__alive_characters[cpu.id] = True # Handles game pausing and game over self.__game_state = Constants.IN_GAME self.__pause = None self.__game_over = None self.__time_pause = 0 def play(self, clock, surface): """ Match loop, which handles different game states. :param clock: Pygame clock object. :param surface: Pygame surface object. :return: Current state the game is in. """ # Draws map and clock self.__map.draw(surface) self.__map.set_is_paused(self.__game_state == Constants.PAUSE or self.__game_state == Constants.OVER) # State machine if self.__game_state == Constants.PAUSE: self.__update_pause_screen(surface) elif self.__game_state == Constants.OVER: self.__update_game_over_screen(clock, surface) elif self.__game_state == Constants.IN_GAME: self.__update_match(clock, surface) elif self.__game_state == Constants.MAIN_MENU: return Constants.STATE_MENU return Constants.STATE_PLAYING def is_over(self): """ Checks if match is over. :return: True if the game state is in OVER. """ return self.__game_state == Constants.OVER def __update_match(self, clock, surface): """ Updates the match itself, handling game object interactions, player inputs and ai decisions. :param clock: Pygame clock object. :param surface: Pygame surface. :return: Match updated state. """ t = time.time() # Handles keyboard events for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYUP: if event.key == K_ESCAPE: self.__game_state = Constants.PAUSE else: for player in self.__players: player.key_up(event.key) if event.type == KEYDOWN: for player in self.__players: player.key_down(event.key) # Decides IA's moves for cpu in self.__cpus: if cpu.is_alive or cpu.get_reward() != 0: cpu.decide(self.__map.get_grid().get_tilemap(), self.__players + self.__cpus, clock) # Updates and draws bombs for bomb in self.__bombs: if bomb.update(clock, self.__map.get_grid().get_tilemap()): bomb.draw(surface) else: self.__fires.append(Fire(bomb.tile, bomb.range, bomb.id, self.__sprites['fire'])) for player in self.__players: if player.id == bomb.id: player.bomb_exploded() for cpu in self.__cpus: if cpu.id == bomb.id: cpu.bomb_exploded() self.__bombs.remove(bomb) # Updates and draws fires for fire in self.__fires: if fire.update(clock, self.__map.get_grid().get_tilemap()): fire.draw(surface) for tile in fire.get_triggered_bombs(): for bomb in self.__bombs: if bomb.tile == tile: bomb.explode() for cpu in self.__cpus: if cpu.id == fire.id: cpu.reward(fire.reward) else: self.__fires.remove(fire) # Updates and draws characters for player in self.__players: if not self.__update_character(player, clock, surface): self.__alive_characters[player.id] = False for cpu in self.__cpus: if not self.__update_character(cpu, clock, surface): self.__alive_characters[cpu.id] = False # Checks if game is over if np.count_nonzero(self.__alive_characters) == 0: self.__game_state = Constants.OVER elif np.count_nonzero(self.__alive_characters) == 1: for i in range(len(self.__alive_characters)): if self.__alive_characters[i]: for player in self.__players: if player.id == i: player.special_event(CharacterEvents.WIN) for cpu in self.__cpus: if cpu.id == i: cpu.special_event(CharacterEvents.WIN) self.__game_state = Constants.OVER if self.__game_state == Constants.OVER: for cpu in self.__cpus: cpu.decide(self.__map.get_grid().get_tilemap(), self.__players + self.__cpus, clock, True) def __update_pause_screen(self, surface): """ Handles the paused screen interface and updates game state. :param surface: Pygame surface. """ if not self.__pause: self.__time_pause = time.time() self.__pause = Pause() self.__pause.draw(surface) self.__game_state = self.__pause.update() if self.__game_state == Constants.IN_GAME: self.__map.increment_delta_pause( time.time() - self.__time_pause) del self.__pause self.__pause = None def __update_game_over_screen(self, clock, surface): """ Handles the game over screen interface and updates game state. It also continues the game objects animations already started. :param clock: Pygame clock object. :param surface: Pygame surface. """ if not self.__game_over: self.__game_over = GameOver() # Updates bombs animations for bomb in self.__bombs: if bomb.update(clock, self.__map.get_grid().get_tilemap()): bomb.draw(surface) # Updates fire animations for fire in self.__fires: if fire.update(clock, self.__map.get_grid().get_tilemap()): fire.draw(surface) # Updates character animations for player in self.__players: self.__update_character(player, clock, surface) for cpu in self.__cpus: self.__update_character(cpu, clock, surface) self.__game_over.draw(surface) self.__game_state = self.__game_over.update() def __update_character(self, character, clock, surface): """ Updates and draws a character according to the map and its events. :param character: Character to be updated. :param clock: Match clock. :param surface: Drawing surface. :return: True if the character is still alive. """ tilemap = self.__map.get_grid().get_tilemap() if character.update(clock, tilemap): # Check if character died if (tilemap[character.tile] == Constants.UNIT_FIRE or tilemap[character.tile] == Constants.UNIT_CENTER_FIRE): self.__reward_kill(character) if isinstance(character, Cpu) and character.is_alive: character.reward(Constants.DEATH_REWARD) character.special_event(CharacterEvents.DIE) character.draw(surface) return False # Check if character picked up a powerup elif tilemap[character.tile] == Constants.UNIT_POWERUP_BOMB_SHOW: character.increase_bomb() tilemap[character.tile] = Constants.UNIT_EMPTY elif tilemap[character.tile] == Constants.UNIT_POWERUP_FIRE_SHOW: character.increase_fire() tilemap[character.tile] = Constants.UNIT_EMPTY elif tilemap[character.tile] == ( Constants.UNIT_POWERUP_VELOCITY_SHOW): character.increase_speed() tilemap[character.tile] = Constants.UNIT_EMPTY # Check if character placed a bomb elif character.placed_bomb(tilemap[character.tile]): self.__bombs.append(Bomb(character.tile, character.fire_range, character.id, self.__sprites['bomb'])) character.draw(surface) return True return False def __reward_kill(self, character_dead): """ Finds the character which placed that bomb and rewards it. :param character_dead: Character object who just died. """ if not character_dead.is_alive: return for fire in self.__fires: if fire.contains(character_dead.tile): for cpu in self.__cpus: if cpu.id == fire.id and character_dead.id != cpu.id: cpu.reward(Constants.KILL_REWARD)
asilvaigor/bomberboy
source/core/engine/Match.py
Match.py
py
10,719
python
en
code
1
github-code
1
[ { "api_name": "os.path.dirname", "line_number": 35, "usage_type": "call" }, { "api_name": "os.path", "line_number": 35, "usage_type": "attribute" }, { "api_name": "os.path.realpath", "line_number": 35, "usage_type": "call" }, { "api_name": "pygame.font.Font", ...
10461388653
""" Модуль для работы с базой данных sqlite3. """ import sqlite3 from typing import Dict import os PATH = 'db' DATABASE = 'db.sqlite3' connect = sqlite3.connect(os.path.join(PATH, DATABASE)) cursor = connect.cursor() def create_db() -> None: """ Создает базу данных и таблицы в ней, если база и таблицы уже существуют, то ничего не делает. """ with open('database/createdb.sql', 'r') as file: sql = file.read() cursor.executescript(sql) connect.commit() def drop(*table_names: str) -> None: """ Очищает таблицы в базе данных. """ for table in table_names: cursor.execute(f"DROP TABLE IF EXISTS {table}") connect.commit() def insert(table: str, data: Dict) -> None: """ Добавляет запись в базу данных. :param table: Название таблицы. :param data: Словарь для записи, где ключ - поле таблицы, а значение - данные для записи. :return: None. """ columns = ', '.join(data.keys()) values = [tuple(data.values())] placeholders = ", ".join("?" * len(data.keys())) cursor.executemany( f"INSERT INTO {table} " f"({columns}) " f"VALUES ({placeholders})", values) connect.commit() def fetch(table: str, columns: list[str]) -> list[tuple | None]: """ Возвращает результаты из одной таблицы базы данных. :param table: Название таблицы. :param columns: Список с полями таблицы. :return: Список кортежей. """ columns_joined = ", ".join(columns) cursor.execute(f"SELECT {columns_joined} FROM {table}") return cursor.fetchall() def execute_sql_fetch(sql: str) -> list[tuple | None]: """ Выполняет sql запрос и возвращает результат. :param sql: SQL запрос. :return: Список кортежей или пустой список. """ cursor.execute(sql) return cursor.fetchall() def execute_sql(sql: str) -> None: """ Выполняет sql команду. :param sql: SQL запрос. :return: None. """ cursor.execute(sql) connect.commit()
darkus007/FlatScrapper
database/db_sqlite.py
db_sqlite.py
py
2,466
python
ru
code
0
github-code
1
[ { "api_name": "sqlite3.connect", "line_number": 12, "usage_type": "call" }, { "api_name": "os.path.join", "line_number": 12, "usage_type": "call" }, { "api_name": "os.path", "line_number": 12, "usage_type": "attribute" }, { "api_name": "typing.Dict", "line_num...
41629028008
from jira import JIRA import pandas as pd from datetime import datetime import plotly import plotly.graph_objs as go import numpy as np from ast import literal_eval from IPython.display import display, HTML pd.set_option('display.max_columns', 999) plotly.offline.init_notebook_mode() def product_closed_time(version): eng_data = pd.read_csv('eng_changelog_clean.csv', encoding='utf_8').drop(['Unnamed: 0'], axis=1) data = pd.read_csv('pm_changelog_clean.csv', encoding='utf_8').drop(['Unnamed: 0', 'remove'], axis=1) # Only include version string in pm_changelog_clean 'fix_version' column for index, row in data.iterrows(): fix = row["fix_version"] try: fix = literal_eval(fix)[0]['name'] data.at[index, "fix_version"] = fix except: data.at[index, "fix_version"] = "None" # Convert timestamps to utc, set index as 'updated_time' and sort index eng_data['updated_time'] = pd.to_datetime(eng_data['updated_time'], utc=True).dt.tz_convert('utc') eng_data = eng_data.set_index(pd.DatetimeIndex(eng_data['updated_time'])).sort_index() eng_data.index.names = ['index'] eng_time_delta = [] # Get time diff for non-PM issues for key in eng_data['eng_key'].unique(): if key.startswith('PM') == False: issue = eng_data.loc[eng_data['eng_key'] == key] issue_diff = issue['updated_time'].diff() issue['time_diff'] = issue_diff # Get Sum of all status change time diffs # *** TO DO: GET SUM OF ALL _RELEVANT_ STATUS CHANGE TIME DIFFS *** issue['time_sum'] = issue['time_diff'].sum() eng_time_delta.append(issue) eng_time = pd.concat(eng_time_delta) eng_time = eng_time.loc[eng_time['fix_version'] == version] #eng_time = eng_time.loc[(eng_time["updated_status"] == "Closed") | (eng_time["updated_status"] == "Done")] ddb = eng_time.loc[eng_time['DDB'] == 1] return ddb def milestone_investment(version): eng_data = pd.read_csv('eng_changelog_clean.csv', encoding='utf_8').drop(['Unnamed: 0'], axis=1) data = pd.read_csv('pm_changelog_clean.csv', encoding='utf_8').drop(['Unnamed: 0', 'remove'], axis=1) for index, row in data.iterrows(): fix = row["fix_version"] try: fix = literal_eval(fix)[0]['name'] data.at[index, "fix_version"] = fix except: data.at[index, "fix_version"] = "None" eng = eng_data.loc[eng_data['fix_version'] == version] eng = eng.loc[(eng["updated_status"] == "Closed") | (eng["updated_status"] == "Done")] total = eng['eng_key'].unique().size ddb = eng.loc[eng['DDB'] == 1]["eng_key"].unique().size crt = eng.loc[(eng['Customer_Priority'] == 1) | (eng['Services_Priority'] == 1)]["eng_key"].unique().size qual = eng.loc[eng['issue_type'] == 'Bug']["eng_key"].unique().size pm = data.loc[data["fix_version"] == version].loc[(data["updated_status"] == "Closed") | (data["updated_status"] == "Done")]['related_key'].unique().size unlabelled = total - (ddb + crt + qual + pm) percentages = { 'PM Backlog': str(format(calc_percent(pm, total), '.2f')) + '%', 'Engineering': str(format(calc_percent(ddb, total), '.2f')) + '%', 'Quality': str(format(calc_percent(qual, total), '.2f')) + '%', 'CRT': str(format(calc_percent(crt, total), '.2f')) + '%', 'Unlabelled': str(format(calc_percent(unlabelled, total), '.2f')) + '%', } issue_count = { 'PM Backlog': pm, 'Engineering': ddb, 'Quality': qual, 'CRT': crt, 'Unlabelled': unlabelled, } inv_list = [ [version, 'CRT', crt], [version, 'Quality', qual], [version, 'Engineering', ddb], [version, 'PM Backlog', pm] ] inv_df = pd.DataFrame(inv_list, columns=['release', 'category', 'closed']) trace = [ go.Bar( name="Investment Breakdown for " + version, y=inv_df['category'], x=inv_df['closed'], orientation='h', marker=go.bar.Marker( color='#374c80', ) ) ] layout = go.Layout( barmode='stack', title='Milestone Investment, ' + version, xaxis=dict( #title='# of Issues', tickmode='linear', titlefont=dict( size=12, ) ), yaxis=dict( #title='Objective', titlefont=dict( size=12, ) ) ) fig = go.Figure(data=trace, layout=layout) plotly.offline.iplot(fig, filename='eng_' + version) display(HTML(''' <i><h4>Nota Bene: Data Veracity</h4></i> <br> <div>For each release, a subset of issues do not include metadata (shown below as <i>Unlabelled</i>) that corresponds to Product Backlog, CRT, Quality or Engineering categories. Accordingly, the percentages listed for categories in each release do not have a sum total of 100%.</div> ''')) display(pd.DataFrame.from_records([percentages])) display(pd.DataFrame.from_records([issue_count])) display(HTML('<i>Total Number of Issues: ' + str(total) + '</i>')) def calc_percent(category, total): return (category / total) * 100 data = pd.read_csv('pm_changelog_clean.csv', encoding='utf_8').drop(['Unnamed: 0', 'remove'], axis=1) def pm_okrs(): okrs_list = ["Cloud_JSX", "Enablement", "JSX", "Product_Performance", "Platform", "RN_Upgrade"] milestones = ["Milestone1", "Milestone2"] okrs = [] for milestone in milestones: for okr in okrs_list: row = [milestone, okr, get_closed(data.loc[data[okr] == 1], milestone), get_total(data.loc[data[okr] == 1], milestone)] okrs.append(row) okrs_df = pd.DataFrame(okrs, columns=["milestone", "label", "closed", "total"]) okrs_df["diff"] = okrs_df["total"].sub(okrs_df['closed'], axis=0) trace = [ go.Bar( name="Closed", y=okrs_df.loc[okrs_df["milestone"] == "Milestone1"]["label"], x=okrs_df.loc[okrs_df["milestone"] == "Milestone1"]["closed"], orientation='h', marker=go.bar.Marker( color='#374c80', ) ), go.Bar( name="Remaining", y=okrs_df.loc[okrs_df["milestone"] == "Milestone1"]["label"], x=okrs_df.loc[okrs_df["milestone"] == "Milestone1"]["diff"], orientation='h', marker=go.bar.Marker( color='#ff764a', ) ), ] layout = go.Layout( barmode='stack', title='Product Objectives, Milestone 1', xaxis=dict( title='# of Issues', tickmode='linear', titlefont=dict( size=12, ) ), yaxis=dict( #title='Objective', titlefont=dict( size=12, ) ) ) fig = go.Figure(data=trace, layout=layout) plotly.offline.iplot(fig, filename='PM_OKRs_M1') trace = [ go.Bar( name="Closed", y=okrs_df.loc[okrs_df["milestone"] == "Milestone2"]["label"], x=okrs_df.loc[okrs_df["milestone"] == "Milestone2"]["closed"], orientation='h', marker=go.bar.Marker( color='#374c80', ) ), go.Bar( name="Remaining", y=okrs_df.loc[okrs_df["milestone"] == "Milestone2"]["label"], x=okrs_df.loc[okrs_df["milestone"] == "Milestone2"]["diff"], orientation='h', marker=go.bar.Marker( color='#ff764a', ) ), ] layout = go.Layout( barmode='stack', title='Product Objectives, Milestone 2', xaxis=dict( title='# of Issues', tickmode='linear', titlefont=dict( size=12, ) ), yaxis=dict( #title='Objective', titlefont=dict( size=12, ) ) ) fig = go.Figure(data=trace, layout=layout) plotly.offline.iplot(fig, filename='PM_OKRs_M2') def get_closed(df, label): return df.loc[(data["updated_status"] == "Closed") | (data["updated_status"] == "Done")].loc[data[label] == 1]["related_key"].unique().size def get_total(df, label): return df.loc[data[label] == 1]["related_key"].unique().size
matthewjwall/youi-product-flow-metrics
scripts/metrics_okrs.py
metrics_okrs.py
py
8,557
python
en
code
0
github-code
1
[ { "api_name": "pandas.set_option", "line_number": 10, "usage_type": "call" }, { "api_name": "plotly.offline.init_notebook_mode", "line_number": 11, "usage_type": "call" }, { "api_name": "plotly.offline", "line_number": 11, "usage_type": "attribute" }, { "api_name"...
26276689512
import pandas as pd import json import dash from dash import dcc,html, callback from dash.dependencies import Input, Output import plotly.graph_objs as go import plotly.express as px import dash_bootstrap_components as dbc import numpy as np import pathlib dash.register_page(__name__, path = '/', name="Accueil") ## Données PATH = pathlib.Path(__file__).parent DATA_PATH = PATH.joinpath("donnees").resolve() with open(DATA_PATH.joinpath("base_finale_lat_long.txt"),'r') as file: dico_produits = json.load(file) Base_produits = pd.DataFrame.from_dict(dico_produits) fig = px.scatter_mapbox( Base_produits, lat="Latitude", lon="Longitude", zoom=4, hover_name="Adresse", hover_data=["CP","Ville"], color="Typologie", labels={'Typologie':'Magasins','CP':'Code postal'}) fig.update_layout(mapbox_style="open-street-map") fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0}) #fig.show() nb_villes = len(pd.unique(Base_produits["Ville"])) nb_produits = len(pd.unique(Base_produits["Nom_produit"])) nb_magasins = len(pd.unique(Base_produits["Adresse"])) # page 0 alerte1 = dbc.Alert([ html.H3(str(nb_magasins), style={"color":"#ffffff"}), html.H5("Magasins enregistrés", style={"color":"#ffffff"}) ],color="#1560bd") alerte2 = dbc.Alert([ html.H3(str(nb_villes), style={"color":"#ffffff"}), html.H5("Communes", style={"color":"#ffffff"}) ],color="#00cccb") alerte3 = dbc.Alert([ html.H3(str(nb_produits), style={"color":"#ffffff"}), html.H5("Produits analysés", style={"color":"#ffffff"}) ],color="#17657d") layout = html.Div([ dbc.Row([ html.H6( "Cette application a pour objectif de suivre et de partager, à partir de la base de données que nous avons construite, les prix de différents biens alimentaires ou ménagers de base, ainsi que d'en fournir quelques statistiques aux consommateurs. Nous nous sommes concentrés dans un premier temps sur la chaine de magasins Carrefour, mais notre objectif est de l'étendre à plusieurs chaines de magasins.", style={"color":"#00005c"} ) ], style = {"padding":"1rem 1rem"}), dbc.Row([ dbc.Col([alerte1],style={"textAlign":"center"}), dbc.Col([alerte2],style={"textAlign":"center"}), dbc.Col([alerte3],style={"textAlign":"center"}) ], style = {"padding":"0rem 1rem"}), dbc.Row([ html.H4("Carte des magasins Carrefour en France",style={'color':"#00005c",'textAlign':"center"}) ]), dbc.Row([ dcc.Graph( id = "graphe_carrefours_france", figure = fig, style={"width":"58rem","margin-left":"1rem"} ) ]) ]) @callback( Output("graphe2","figure"), Input("produit2","children") ) def afficher_p2(produit2): return None
louislat/deployer
pages/pg0.py
pg0.py
py
2,800
python
fr
code
0
github-code
1
[ { "api_name": "dash.register_page", "line_number": 12, "usage_type": "call" }, { "api_name": "pathlib.Path", "line_number": 15, "usage_type": "call" }, { "api_name": "json.load", "line_number": 19, "usage_type": "call" }, { "api_name": "pandas.DataFrame.from_dict"...
70427983394
import pandas as pd import matplotlib.pyplot as plt import os class CoefficientAnalyzer: def __init__(self, data_file): """ Initialize the CoefficientAnalyzer class. """ # Load the data for all trials from the CSV self.data = pd.read_csv(data_file) def calculate_coefficient(self, v_initial, v_final): """ Calculate the coefficient of restitution 'e'. """ return abs(v_final) / abs(v_initial) def calculate_uncertainty(self, v_initial, sigma_vi, v_final, sigma_vf): """ Calculate the uncertainty in the coefficient of restitution 'e' using the error propagation formula. """ partial_e_vi = -v_final / v_initial**2 partial_e_vf = 1 / v_initial return ( (partial_e_vi**2 * sigma_vi**2) + (partial_e_vf**2 * sigma_vf**2) ) ** 0.5 def process_all_trials(self): """Process all trials in the data.""" self.data["e_calculated"] = self.data.apply( lambda row: self.calculate_coefficient( row["v initial"], row["v final"] ), axis=1, ) self.data["e_uncertainty"] = self.data.apply( lambda row: self.calculate_uncertainty( row["v initial"], row["uncertainty vi"], row["v final"], row["uncertainty vf"], ), axis=1, ) # Calculate unweighted mean and standard error on the mean self.e_mean = self.data["e_calculated"].mean() self.sigma = self.data["e_calculated"].std() # standard deviation self.N = len(self.data) self.sigma_mean = self.sigma / (self.N**0.5) # Calculate weighted mean and its standard error weights = 1 / self.data["e_uncertainty"] ** 2 self.e_weighted_mean = sum(self.data["e_calculated"] * weights) / sum(weights) self.sigma_weighted_mean = (sum(weights)) ** -0.5 def display_results(self): """Display the results for all trials.""" print("Trial-wise results:") print(self.data) print("\nUnweighted mean (ē):", self.e_mean) print("Standard deviation (σ):", self.sigma) print("Standard error on the mean (σ̄e):", self.sigma_mean) print("\nWeighted mean (ē_w):", self.e_weighted_mean) print("Standard error on the weighted mean (σ̄_ew):", self.sigma_weighted_mean) def plot_e_vs_vi(self): """Plot e against v_initial and save the figure in the 'figures' folder.""" plt.figure(figsize=(10, 6)) plt.scatter(self.data["v initial"], self.data["e_calculated"], marker='o', color='blue', label="e values") plt.axhline(y=self.e_mean, color='r', linestyle='--', label=f"Unweighted mean $\\bar{{e}}$ = {self.e_mean:.4f}") plt.axhline(y=self.e_weighted_mean, color='g', linestyle='-.', label=f"Weighted mean $\\bar{{e}}_w$ = {self.e_weighted_mean:.4f}") plt.xlabel("Initial Velocity ($v_i$)") plt.ylabel("Coefficient of Restitution (e)") plt.title("Distribution of Coefficient of Restitution values") plt.legend() plt.grid(True) plt.tight_layout() # Create 'figures' directory if not exists if not os.path.exists('figures'): os.makedirs('figures') # Save the plot plt.savefig('experiment1/figures/e_vs_vi_plot.png') plt.show() def plot_histogram(self): """Plot a histogram of e values and overlay vertical lines for e_bar and e_w_bar.""" plt.figure(figsize=(10, 6)) plt.hist(self.data["e_calculated"], bins=10, color='lightblue', edgecolor='black', alpha=0.7, label="Frequency of e values") plt.axvline(x=self.e_mean, color='r', linestyle='--', label=f"Unweighted mean $\\bar{{e}}$ = {self.e_mean:.4f}") plt.axvline(x=self.e_weighted_mean, color='g', linestyle='-.', label=f"Weighted mean $\\bar{{e}}_w$ = {self.e_weighted_mean:.4f}") plt.xlabel("Coefficient of Restitution (e)") plt.ylabel("Frequency") plt.title("Frequency Distribution of Coefficient of Restitution values") plt.legend() plt.grid(True, which='both', linestyle='--', linewidth=0.5) plt.tight_layout() # Save the plot in 'figures' directory plt.savefig('experiment1/figures/e_histogram.png') plt.show() analyzer = CoefficientAnalyzer("experiment1/data.csv") # Adjust the file path analyzer.process_all_trials() analyzer.display_results() analyzer.plot_e_vs_vi() analyzer.plot_histogram()
NolanTrem/phys1494
experiment1/motion_analyzer.py
motion_analyzer.py
py
4,688
python
en
code
1
github-code
1
[ { "api_name": "pandas.read_csv", "line_number": 11, "usage_type": "call" }, { "api_name": "matplotlib.pyplot.figure", "line_number": 72, "usage_type": "call" }, { "api_name": "matplotlib.pyplot", "line_number": 72, "usage_type": "name" }, { "api_name": "matplotlib...
31589162522
import itertools from osgeo import ogr,osr import shapely.geometry # Convert Shapely type to OGR type shapely_to_ogr_type = { shapely.geometry.linestring.LineString: ogr.wkbLineString, shapely.geometry.polygon.Polygon: ogr.wkbPolygon, } def to_datasource(shape): """Converts an in-memory Shapely object to an (open) OGR datasource. shape: A shapely polygon (or LineString, etc) """ # Create an OGR in-memory datasource with our single polygon ds=ogr.GetDriverByName('MEMORY').CreateDataSource('memData') layer = ds.CreateLayer('', None, shapely_to_ogr_type[type(shape)])#ogr.wkbPolygon) feat = ogr.Feature(layer.GetLayerDefn()) feat.SetGeometry(ogr.CreateGeometryFromWkb(shape.wkb)) layer.CreateFeature(feat) return ds def pointify(shapes): """Converts a bunch of shapes into a jumbled list of points in the shapes combined. Shapes could be LineString, Polygon, etc. shapes: Iterable of Shapely shapes """ return shapely.geometry.MultiPoint(list(itertools.chain(*(shape.coords for shape in shapes))))
pism/uafgi
uafgi/util/shapelyutil.py
shapelyutil.py
py
1,095
python
en
code
1
github-code
1
[ { "api_name": "shapely.geometry.geometry", "line_number": 8, "usage_type": "attribute" }, { "api_name": "shapely.geometry", "line_number": 8, "usage_type": "name" }, { "api_name": "shapely.geometry.geometry", "line_number": 9, "usage_type": "attribute" }, { "api_n...
73286444834
from koza.cli_runner import koza_app from loguru import logger source_name = "mimtitles" row = koza_app.get_row(source_name) map = koza_app.get_map(source_name) ### # From OMIM # An asterisk (*) before an entry number indicates a gene. # # A number symbol (#) before an entry number indicates that it is a descriptive entry, # usually of a phenotype, and does not represent a unique locus. The reason for the use # of the number symbol is given in the first paragraph of he entry. Discussion of any gene(s) # related to the phenotype resides in another entry(ies) as described in the first paragraph. # # A plus sign (+) before an entry number indicates that the entry contains the description of # a gene of known sequence and a phenotype. # # A percent sign (%) before an entry number indicates that the entry describes a confirmed # mendelian phenotype or phenotypic locus for which the underlying molecular basis is not known. # # No symbol before an entry number generally indicates a description of a phenotype for which # the mendelian basis, although suspected, has not been clearly established or that the separateness # of this phenotype from that in another entry is unclear. # # A caret (^) before an entry number means the entry no longer exists because it was removed # from the database or moved to another entry as indicated. ### if row['Prefix'] == 'Asterisk': map[row['MIM Number']] = 'gene' elif row['Prefix'] == 'NULL': map[row['MIM Number']] = 'suspected' elif row['Prefix'] == 'Number Sign': map[row['MIM Number']] = 'disease' elif row['Prefix'] == 'Percent': map[row['MIM Number']] = 'heritable_phenotypic_marker' elif row['Prefix'] == 'Plus': map[row['MIM Number']] = 'gene' elif row['Prefix'] == 'Caret': # moved|removed|split -> moved twice map[row['MIM Number']] = 'obsolete' # populating a dict from an omim to a set of omims # Not sure we'll need this so commenting out for now # map['replaced by'] = [] # # if row['Preferred Title; symbol'][:9] == 'MOVED TO ': # token = row['Preferred Title; symbol'].split(' ') # title_symbol = token[2] # if not re.match(r'^[0-9]{6}$', title_symbol): # logger.error(f"Report malformed omim replacement {title_symbol}") # # clean up ones I know about # if title_symbol[0] == '{' and title_symbol[7] == '}': # title_symbol = title_symbol[1:7] # logger.info(f"Repaired malformed omim replacement {title_symbol}") # if len(title_symbol) == 7 and title_symbol[6] == ',': # title_symbol = title_symbol[:6] # logger.info(f"Repaired malformed omim replacement {title_symbol}") # if len(token) > 3: # map['replaced by'] = [title_symbol, token[4]] # else: # map['replaced by'] = [title_symbol] else: logger.error(f"Unknown OMIM type line {row['omim_id']}")
monarch-initiative/monarch-ingest
src/monarch_ingest/maps/mimtitles.py
mimtitles.py
py
2,943
python
en
code
11
github-code
1
[ { "api_name": "koza.cli_runner.koza_app.get_row", "line_number": 8, "usage_type": "call" }, { "api_name": "koza.cli_runner.koza_app", "line_number": 8, "usage_type": "name" }, { "api_name": "koza.cli_runner.koza_app.get_map", "line_number": 9, "usage_type": "call" }, ...
18042327734
# -*- coding: utf-8 -*- from django import forms from ..models import Programacao class ProgramacaoForm(forms.ModelForm): class Meta: model = Programacao fields = ( 'programa', 'data_inicio', 'data_fim' ) def clean(self): cleaned_data = super(ProgramacaoForm, self).clean() if cleaned_data.get('data_inicio') > cleaned_data.get('data_fim'): self.add_error( 'data_inicio', "Data de inicio não pode ser superior a data de fim") return cleaned_data
rbiassusi/grade_programacao
grade_programacao/radio/forms/programacaoform.py
programacaoform.py
py
549
python
pt
code
0
github-code
1
[ { "api_name": "django.forms.ModelForm", "line_number": 6, "usage_type": "attribute" }, { "api_name": "django.forms", "line_number": 6, "usage_type": "name" }, { "api_name": "models.Programacao", "line_number": 9, "usage_type": "name" } ]
23270541963
""" Detection Recipe - 12.0.4.17 References: (1) 'Asteroseismic detection predictions: TESS' by Chaplin (2015) (2) 'On the use of empirical bolometric corrections for stars' by Torres (2010) (3) 'The amplitude of solar oscillations using stellar techniques' by Kjeldson (2008) (4) 'An absolutely calibrated Teff scale from the infrared flux method' by Casagrande (2010) table 4 (5) 'Characterization of the power excess of solar-like oscillations in red giants with Kepler' by Mosser (2011) (6) 'Predicting the detectability of oscillations in solar-type stars observed by Kepler' by Chaplin (2011) (7) 'The connection between stellar granulation and oscillation as seen by the Kepler mission' by Kallinger et al (2014) (8) 'The Transiting Exoplanet Survey Satellite: Simulations of Planet Detections and Astrophysical False Positives' by Sullivan et al. (2015) (9) Astropysics module at https://pythonhosted.org/Astropysics/coremods/coords.html (10) Bill Chaplin's calc_noise IDL procedure for TESS. (11) Bill Chaplin's soldet6 IDL procedure to calculate the probability of detecting oscillations with Kepler. (12) Coordinate conversion at https://ned.ipac.caltech.edu/forms/calculator.html (13) Bedding 1996 (14) 'The Asteroseismic potential of TESS' by Campante et al. 2016 """ import numpy as np from itertools import groupby from operator import itemgetter import sys import pandas as pd from scipy import stats import warnings warnings.simplefilter("ignore") def bv2teff(b_v): # from Torres 2010 table 2. Applies to MS, SGB and giant stars # B-V limits from Flower 1996 fig 5 a = 3.979145106714099 b = -0.654992268598245 c = 1.740690042385095 d = -4.608815154057166 e = 6.792599779944473 f = -5.396909891322525 g = 2.192970376522490 h = -0.359495739295671 lteff = a + b*b_v + c*(b_v**2) + d*(b_v**3) + e*(b_v**4) + f*(b_v**5) + g*(b_v**6) + h*(b_v**7) teff = 10.0**lteff return teff # from F Pijpers 2003. BCv values from Flower 1996 polynomials presented in Torres 2010 # Av is a keword argument. If reddening values not available, ignore it's effect def Teff2bc2lum(teff, parallax, parallax_err, vmag, Av=0): lteff = np.log10(teff) BCv = np.full(len(lteff), -100.5) BCv[lteff<3.70] = (-0.190537291496456*10.0**5) + \ (0.155144866764412*10.0**5*lteff[lteff<3.70]) + \ (-0.421278819301717*10.0**4.0*lteff[lteff<3.70]**2.0) + \ (0.381476328422343*10.0**3*lteff[lteff<3.70]**3.0) BCv[(3.70<lteff) & (lteff<3.90)] = (-0.370510203809015*10.0**5) + \ (0.385672629965804*10.0**5*lteff[(3.70<lteff) & (lteff<3.90)]) + \ (-0.150651486316025*10.0**5*lteff[(3.70<lteff) & (lteff<3.90)]**2.0) + \ (0.261724637119416*10.0**4*lteff[(3.70<lteff) & (lteff<3.90)]**3.0) + \ (-0.170623810323864*10.0**3*lteff[(3.70<lteff) & (lteff<3.90)]**4.0) BCv[lteff>3.90] = (-0.118115450538963*10.0**6) + \ (0.137145973583929*10.0**6*lteff[lteff > 3.90]) + \ (-0.636233812100225*10.0**5*lteff[lteff > 3.90]**2.0) + \ (0.147412923562646*10.0**5*lteff[lteff > 3.90]**3.0) + \ (-0.170587278406872*10.0**4*lteff[lteff > 3.90]**4.0) + \ (0.788731721804990*10.0**2*lteff[lteff > 3.90]**5.0) u = 4.0 + 0.4 * 4.73 - 2.0 * np.log10(parallax) - 0.4 * (vmag - Av + BCv) lum = 10**u # in solar units e_lum = (2.0 / parallax * 10**u)**2 * parallax_err**2 e_lum = np.sqrt(e_lum) return lum, e_lum # calculate seismic parameters def seismicParameters(teff, lum): # solar parameters teff_solar = 5777.0 # Kelvin teffred_solar = 8907.0 #in Kelvin numax_solar = 3090.0 # in micro Hz dnu_solar = 135.1 # in micro Hz cadence = 120 # in s vnyq = (1.0 / (2.0*cadence)) * 10**6 # in micro Hz teffred = teffred_solar*(lum**-0.093) # from (6) eqn 8. red-edge temp rad = lum**0.5 * ((teff/teff_solar)**-2) # Steffan-Boltzmann law numax = numax_solar*(rad**-1.85)*((teff/teff_solar)**0.92) # from (14) return cadence, vnyq, rad, numax, teffred, teff_solar, teffred_solar, numax_solar, dnu_solar # no coordinate conversion before calculating tess field observing time. Only # works with ecliptic coordinates def tess_field_only(e_lng, e_lat): # create a list to append all of the total observing times 'T' in the TESS field to T = [] # units of sectors (0-13) # create a list to append all of the maximum contiguous observations to max_T = [] # units of sectors (0-13) for star in range(len(e_lng)): # 'n' defines the distance between each equidistant viewing sector in the TESS field. n = 360.0/13 # Define a variable to count the total number of sectors a star is observed in. counter = 0 # Define a variable to count all of the observations for each star. # Put each observation sector into sca separately in order to find the largest number # of contiguous observations for each star. sca = [] # 'ranges' stores all of the contiguous observations for each star. ranges = [] # Defines the longitude range of the observing sectors at the inputted stellar latitude lngrange = 24.0/abs(np.cos(np.radians(e_lat[star]))) if lngrange>=360.0: lngrange=360.0 # if the star is in the northern hemisphere: if e_lat[star] >= 0.0: # For each viewing sector. for i in range(1,14): # Define an ra position for the centre of each sector in increasing longitude. # if a hemisphere has an overshoot, replace 0.0 with the value. a = 0.0+(n*(i-1)) # calculate the distances both ways around the # circle between the star and the centre of the sector. # The smallest distance is the one that should be used # to see if the star lies in the observing sector. d1 = abs(e_lng[star]-a) d2 = (360.0 - abs(e_lng[star]-a)) if d1>d2: d1 = d2 # if the star is in the 'overshoot' region for some sectors, calculate d3 and d4; # the distances both ways around the circle bwtween the star and the centre of the # 'overshooting past the pole' region of the sector. # The smallest distance is the one that should be used # to see if the star lies in the observing sector. # the shortest distances between the centre of the sector and star, and the sector's # overshoot and the star should add to 180.0 apart (i.e d1+d3=180.0) d3 = abs(e_lng[star] - (a+180.0)%360.0) d4 = 360.0 - abs(e_lng[star] - (a+180.0)%360.0) if d3>d4: d3 = d4 # check if a star lies in the field of that sector. if (d1<=lngrange/2.0 and 6.0<=e_lat[star]) or (d3<=lngrange/2.0 and 78.0<=e_lat[star]): counter += 1 sca = np.append(sca, i) else: pass # if the star is in the southern hemisphere: if e_lat[star] < 0.0: # For each viewing sector. for i in range(1,14): # Define an ra position for the centre of each sector in increasing longitude. # if a hemisphere has an overshoot, replace 0.0 with the value. a = 0.0+(n*(i-1)) # calculate the distances both ways around the # circle between the star and the centre of the sector. # The smallest distance is the one that should be used # to see if the star lies in the observing sector. d1 = abs(e_lng[star]-a) d2 = (360 - abs(e_lng[star]-a)) if d1>d2: d1 = d2 # if the star is in the 'overshoot' region for some sectors, calculate d3 and d4; # the distances both ways around the circle between the star and the centre of the # 'overshooting past the pole' region of the sector. # The smallest distance of the 2 is the one that should be used # to see if the star lies in the observing sector. d3 = abs(e_lng[star] - (a+180.0)%360.0) d4 = (360 - abs(e_lng[star] - (a+180.0)%360.0)) if d3>d4: d3 = d4 # check if a star lies in the field of that sector. if (d1<=lngrange/2.0 and -6.0>=e_lat[star]) or (d3<=lngrange/2.0 and -78.0>=e_lat[star]): counter += 1 sca = np.append(sca, i) else: pass if len(sca) == 0: ranges = [0] else: for k,g in groupby(enumerate(sca), lambda i_x:i_x[0]-i_x[1]): group = map(itemgetter(1), g) if np.array(group).sum() !=0: ranges.append([len(list(group))]) T=np.append(T, counter) max_T = np.append(max_T, np.max(np.array(ranges))) return T, max_T def calc_noise(imag, exptime, teff, e_lng = 0, e_lat = 30, g_lng = 96, g_lat = -30, subexptime = 2.0, npix_aper = 10, \ frac_aper = 0.76, e_pix_ro = 10, geom_area = 60.0, pix_scale = 21.1, sys_limit = 0): omega_pix = pix_scale**2.0 n_exposures = exptime/subexptime # electrons from the star megaph_s_cm2_0mag = 1.6301336 + 0.14733937*(teff-5000.0)/5000.0 e_star = 10.0**(-0.4*imag) * 10.0**6 * megaph_s_cm2_0mag * geom_area * exptime * frac_aper e_star_sub = e_star*subexptime/exptime # e/pix from zodi dlat = (abs(e_lat)-90.0)/90.0 vmag_zodi = 23.345 - (1.148*dlat**2.0) e_pix_zodi = 10.0**(-0.4*(vmag_zodi-22.8)) * (2.39*10.0**-3) * geom_area * omega_pix * exptime # e/pix from background stars dlat = abs(g_lat)/40.0*10.0**0 dlon = g_lng q = np.where(dlon>180.0) if len(q[0])>0: dlon[q] = 360.0-dlon[q] dlon = abs(dlon)/180.0*10.0**0 p = [18.97338*10.0**0, 8.833*10.0**0, 4.007*10.0**0, 0.805*10.0**0] imag_bgstars = p[0] + p[1]*dlat + p[2]*dlon**(p[3]) e_pix_bgstars = 10.0**(-0.4*imag_bgstars) * 1.7*10.0**6 * geom_area * omega_pix * exptime # compute noise sources noise_star = np.sqrt(e_star) / e_star noise_sky = np.sqrt(npix_aper*(e_pix_zodi + e_pix_bgstars)) / e_star noise_ro = np.sqrt(npix_aper*n_exposures)*e_pix_ro / e_star noise_sys = 0.0*noise_star + sys_limit/(1*10.0**6)/np.sqrt(exptime/3600.0) noise1 = np.sqrt(noise_star**2.0 + noise_sky**2.0 + noise_ro**2.0) noise2 = np.sqrt(noise_star**2.0 + noise_sky**2.0 + noise_ro**2.0 + noise_sys**2.0) return noise2 # calculate the granulation at a set of frequencies from (7) eqn 2 model F def granulation(nu0, dilution, a_nomass, b1, b2, vnyq): # Divide by dilution squared as it affects stars in the time series. # The units of dilution change from ppm to ppm^2 microHz^-1 when going from the # time series to frequency. p6: c=4 and zeta = 2*sqrt(2)/pi Pgran = (((2*np.sqrt(2))/np.pi) * (a_nomass**2/b1) / (1 + ((nu0/b1)**4)) \ + ((2*np.sqrt(2))/np.pi) * (a_nomass**2/b2) / (1 + ((nu0/b2)**4))) / (dilution**2) # From (9). the amplitude suppression factor. Normalised sinc with pi (area=1) eta = np.sinc((nu0/(2*vnyq))) # the granulation after attenuation Pgran = Pgran * eta**2 return Pgran, eta # the total number of pixels used by the highest ranked x number of targets in the tCTL def pixel_cost(x): N = np.ceil(10.0**-5.0 * 10.0**(0.4*(20.0-x))) N_tot = 10*(N+10) total = np.cumsum(N_tot) # want to find: the number of ranked tCTL stars (from highest to lowest rank) that correspond to a pixel cost of 1.4Mpix at a given time per_cam = 26*4 # to get from the total pixel cost to the cost per camera at a given time, divide by this pix_limit = 1.4e6 # the pixel limit per camera at a given time return total[-1], per_cam, pix_limit, N_tot # detection recipe to find whether a star has an observed solar-like Gaussian mode power excess def globalDetections(g_lng, g_lat, e_lng, e_lat, imag, \ lum, rad, teff, numax, max_T, teffred, teff_solar, \ teffred_solar, numax_solar, dnu_solar, sys_limit, dilution, vnyq, cadence, vary_beta=False): dnu = dnu_solar*(rad**-1.42)*((teff/teff_solar)**0.71) # from (14) eqn 21 beta = 1.0-np.exp(-(teffred-teff)/1550.0) # beta correction for hot solar-like stars from (6) eqn 9. if isinstance(teff, float): # for only 1 star if (teff>=teffred): beta = 0.0 else: beta[teff>=teffred] = 0.0 # to remove the beta correction, set Beta=1 if vary_beta == False: beta = 1.0 # modified from (6) eqn 11. Now consistent with dnu proportional to numax^0.77 in (14) amp = 0.85*2.5*beta*(rad**1.85)*((teff/teff_solar)**0.57) # From (5) table 2 values for delta nu_{env}. env_width is defined as +/- some value. env_width = 0.66 * numax**0.88 env_width[numax>100.] = numax[numax>100.]/2. # from (6) p12 total, per_cam, pix_limit, npix_aper = pixel_cost(imag) noise = calc_noise(imag=imag, teff=teff, exptime=cadence, e_lng=e_lng, e_lat=e_lat, \ g_lng=g_lng, g_lat=g_lat, sys_limit=sys_limit, npix_aper=npix_aper) noise = noise*10.0**6 # total noise in units of ppm a_nomass = 0.85 * 3382*numax**-0.609 # multiply by 0.85 to convert to redder TESS bandpass. b1 = 0.317 * numax**0.970 b2 = 0.948 * numax**0.992 # call the function for the real and aliased components (above and below vnyq) of the granulation # the order of the stars is different for the aliases so fun the function in a loop Pgran, eta = granulation(numax, dilution, a_nomass, b1, b2, vnyq) Pgranalias = np.zeros(len(Pgran)) etaalias = np.zeros(len(eta)) # if vnyq is 1 fixed value if isinstance(vnyq, float): for i in range(len(numax)): if numax[i] > vnyq: Pgranalias[i], etaalias[i] = granulation((vnyq - (numax[i] - vnyq)), \ dilution, a_nomass[i], b1[i], b2[i], vnyq) elif numax[i] < vnyq: Pgranalias[i], etaalias[i] = granulation((vnyq + (vnyq - numax[i])), \ dilution, a_nomass[i], b1[i], b2[i], vnyq) # if vnyq varies for each star else: for i in range(len(numax)): if numax[i] > vnyq[i]: Pgranalias[i], etaalias[i] = granulation((vnyq[i] - (numax[i] - vnyq[i])), \ dilution, a_nomass[i], b1[i], b2[i], vnyq[i]) elif numax[i] < vnyq[i]: Pgranalias[i], etaalias[i] = granulation((vnyq[i] + (vnyq[i] - numax[i])), \ dilution, a_nomass[i], b1[i], b2[i], vnyq[i]) Pgrantotal = Pgran + Pgranalias ptot = (0.5*2.94*amp**2.*((2.*env_width)/dnu)*eta**2.) / (dilution**2.) Binstr = 2.0 * (noise)**2. * cadence*10**-6.0 # from (6) eqn 18 bgtot = ((Binstr + Pgrantotal) * 2.*env_width) # units are ppm**2 snr = ptot/bgtot # global signal to noise ratio from (11) fap = 0.05 # false alarm probability pdet = 1.0 - fap pfinal = np.full(rad.shape[0], -99) idx = np.where(max_T != 0) # calculate the indexes where T is not 0 tlen=max_T[idx]*27.4*86400.0 # the length of the TESS observations in seconds bw=1.0 * (10.0**6.0)/tlen nbins=(2.*env_width[idx]/bw).astype(int) # from (11) snrthresh = stats.chi2.ppf(pdet, 2.0*nbins) / (2.0*nbins) - 1.0 pfinal[idx] = stats.chi2.sf((snrthresh+1.0) / (snr[idx]+1.0)*2.0*nbins, 2.*nbins) return pfinal, snr, dnu # snr is needed in TESS_telecon2.py def BV2VI(bv, vmag, g_mag_abs): whole = pd.DataFrame(data={'B-V': bv, 'Vmag': vmag, 'g_mag_abs': g_mag_abs, 'Ai': 0}) # Mg: empirical relation from Tiago to separate dwarfs from giants # note: this relation is observational; it was made with REDDENED B-V and g_mag values whole['Mg'] = 6.5*whole['B-V'] - 1.8 # B-V-to-teff limits from (6) fig 5 whole = whole[(whole['B-V'] > -0.4) & (whole['B-V'] < 1.7)] print(whole.shape, 'after B-V cuts') # B-V limits for dwarfs and giants, B-V conditions from (1) # if a star can't be classified as dwarf or giant, remove it condG = (whole['B-V'] > -0.25) & (whole['B-V'] < 1.75) & (whole['Mg'] > whole['g_mag_abs']) condD1 = (whole['B-V'] > -0.23) & (whole['B-V'] < 1.4) & (whole['Mg'] < whole['g_mag_abs']) condD2 = (whole['B-V'] > 1.4) & (whole['B-V'] < 1.9) & (whole['Mg'] < whole['g_mag_abs']) whole = pd.concat([whole[condG], whole[condD1], whole[condD2]], axis=0) print(whole.shape, 'after giant/dwarf cuts') whole['V-I'] = 100. # write over these values for dwarfs and giants separately # coefficients for giants and dwarfs cg = [-0.8879586e-2, 0.7390707, 0.3271480, 0.1140169e1, -0.1908637, -0.7898824, 0.5190744, 0.5358868] cd1 = [0.8906590e-1, 0.1319675e1, 0.4461807, -0.1188127e1, 0.2465572, 0.8478627e1, 0.1046599e2, 0.3641226e1] cd2 = [-0.5421588e2, 0.8011383e3, -0.4895392e4, 0.1628078e5, -0.3229692e5, 0.3939183e5, -0.2901167e5, 0.1185134e5, -0.2063725e4] # calculate (V-I) for giants x = whole['B-V'][condG] - 1 y = (cg[0] + cg[1]*x + cg[2]*(x**2) + cg[3]*(x**3) + cg[4]*(x**4) +\ cg[5]*(x**5) + cg[6]*(x**6) + cg[7]*(x**7)) whole['V-I'][condG] = y + 1 x, y = [[] for i in range(2)] # calculate (V-I) for dwarfs (1st B-V range) x = whole['B-V'][condD1] - 1 y = (cd1[0] + cd1[1]*x + cd1[2]*(x**2) + cd1[3]*(x**3) + cd1[4]*(x**4) +\ cd1[5]*(x**5) + cd1[6]*(x**6) + cd1[7]*(x**7)) whole['V-I'][condD1] = y + 1 x, y = [[] for i in range(2)] # calculate (V-I) for dwarfs (2nd B-V range) x = whole['B-V'][condD2] - 1 y = (cd2[0] + cd2[1]*x + cd2[2]*(x**2) + cd2[3]*(x**3) + cd2[4]*(x**4) +\ cd2[5]*(x**5) + cd2[6]*(x**6) + cd2[7]*(x**7) + cd2[8]*(x**8)) whole['V-I'][condD2] = y + 1 x, y = [[] for i in range(2)] # calculate Imag from V-I and reredden it whole['Imag'] = whole['Vmag']-whole['V-I'] whole['Imag_reddened'] = whole['Imag'] + whole['Ai'] """ # make Teff, luminosity, Plx and ELat cuts to the data whole = whole[(whole['teff'] < 7700) & (whole['teff'] > 4300) & \ (whole['Lum'] > 0.3) & (whole['lum_D'] < 50) & ((whole['e_Plx']/whole['Plx']) < 0.5) \ & (whole['Plx'] > 0.) & ((whole['ELat']<=-6.) | (whole['ELat']>=6.))] print(whole.shape, 'after Teff/L/Plx/ELat cuts') """ whole.drop(['Ai', 'Imag_reddened', 'Mg'], axis=1, inplace=True) return whole.as_matrix().T # make cuts to the data def cuts(teff, e_teff, metal, e_metal, g_lng, g_lat, e_lng, e_lat, Tmag, e_Tmag, Vmag, e_Vmag, plx, e_plx, lum, star_name): d = {'teff':teff, 'e_teff':e_teff, 'metal':metal, 'e_metal':e_metal, 'g_lng':g_lng, 'g_lat':g_lat, 'e_lng':e_lng, 'e_lat':e_lat, 'Tmag':Tmag, 'e_Tmag':e_Tmag, 'Vmag':Vmag, 'e_Vmag':e_Vmag, 'plx':plx, 'e_plx':e_plx, 'lum':lum, 'star_name':star_name} whole = pd.DataFrame(d, columns = ['teff', 'e_teff', 'metal', 'e_metal', 'g_lng', 'g_lat', 'e_lng', 'e_lat', 'Tmag', 'e_Tmag', 'Vmag', 'e_Vmag', 'plx', 'e_plx', 'lum', 'star_name']) whole = whole[(whole['teff'] < 7700.) & (whole['teff'] > 4300.) & (whole['e_teff'] > 0.) & \ (whole['lum'] > 0.3) & (whole['lum'] < 50.) & ((whole['e_plx']/whole['plx']) < 0.5) & \ (whole['plx'] > 0.) & ((whole['e_lat']<=-6.) | (whole['e_lat']>=6.)) & \ (whole['Tmag'] > 3.5) & (whole['e_metal'] > 0.)] print(whole.shape, 'after cuts to the data') return whole.as_matrix().T if __name__ == '__main__': df = pd.read_csv('files/MAST_Crossmatch_TIC4.csv', header=0, index_col=False) data = df.values # star_name = data[:, 1] teff = pd.to_numeric(data[:, 88]) # e_teff = pd.to_numeric(data[:, 89]) # metal = pd.to_numeric(data[:, 92]) # e_metal = pd.to_numeric(data[:, 93]) # g_lng = pd.to_numeric(data[:, 48]) # g_lat = pd.to_numeric(data[:, 49]) # e_lng = pd.to_numeric(data[:, 50]) # e_lat = pd.to_numeric(data[:, 51]) # Tmag = pd.to_numeric(data[:, 84]) # e_Tmag = pd.to_numeric(data[:, 85]) Vmag = pd.to_numeric(data[:, 54]) # e_Vmag = pd.to_numeric(data[:, 55]) plx = pd.to_numeric(data[:, 45]) e_plx = pd.to_numeric(data[:, 46]) lum, e_lum = Teff2bc2lum(teff, plx, e_plx, Vmag) df[' Luminosity'] = pd.Series(lum) df[' Luminosity Err.'] = pd.Series(e_lum) # teff, e_teff, metal, e_metal, g_lng, g_lat, e_lng, e_lat, Tmag, e_Tmag, \ # Vmag, e_Vmag, plx, e_plx, lum, star_name = cuts(teff, e_teff, metal, e_metal, # g_lng, g_lat, e_lng, e_lat, Tmag, e_Tmag, Vmag, e_Vmag, # plx, e_plx, lum, star_name) # make cuts to the data df = df[(df[' T_eff'] < 7700.) & (df[' T_eff'] > 4300.) & (df[' T_eff Err.'] > 0.) & \ (df[' Luminosity'] > 0.3) & (df[' Luminosity'] < 50.) & ((df[' Parallax Err.']/df[' Parallax']) < 0.5) & \ (df[' Parallax'] > 0.) & ((df[' Ecl. Lat.']<=-6.) | (df[' Ecl. Lat.']>=6.)) & \ (df[' TESS Mag.'] > 3.5) & (df[' Metallicity Err.'] > 0.)] df = df.reset_index(drop=True) print(df.shape, 'after cuts to the data') data = df.values teff = pd.to_numeric(data[:, 88]) lum = pd.to_numeric(data[:, 113]) Tmag = pd.to_numeric(data[:, 84]) Vmag = pd.to_numeric(data[:, 54]) plx = pd.to_numeric(data[:, 45]) g_lng = pd.to_numeric(data[:, 48]) g_lat = pd.to_numeric(data[:, 49]) e_lng = pd.to_numeric(data[:, 50]) e_lat = pd.to_numeric(data[:, 51]) cadence, vnyq, rad, numax, teffred, teff_solar, teffred_solar, \ numax_solar, dnu_solar = seismicParameters(teff, lum) T, max_T = tess_field_only(e_lng, e_lat) pdet, snr, dnu = globalDetections(g_lng=g_lng, g_lat=g_lat, e_lng=e_lng, e_lat=e_lat, \ imag=Tmag, lum=lum, rad=rad, teff=teff, numax=numax, max_T=max_T, \ teffred=teffred, teff_solar=teff_solar, teffred_solar=teffred_solar, \ numax_solar=numax_solar, dnu_solar=dnu_solar, sys_limit=0., dilution=1., \ vnyq=vnyq, cadence=cadence, vary_beta=True) df[' Dnu'] = pd.Series(dnu) e_dnu = dnu * 0.021 df[' Dnu Err.'] = pd.Series(e_dnu) df[' nu_max'] = pd.Series(numax) e_numax = numax * 0.046 df[' nu_max Err.'] = pd.Series(e_numax) df[' P_det'] = pd.Series(pdet) df[' SNR'] = pd.Series(snr) # make new cut to the data (pdet > 0.5) df = df[df[' P_det'] > 0.5] df = df.reset_index(drop=True) print(df.shape, 'after new cut to the data (pdet > 0.5)') # inflating errors on teff and metal data = df.values e_teff = pd.to_numeric(data[:, 89]) e_teff = (e_teff**2 + 59**2)**0.5 df[' T_eff Err.'] = pd.Series(e_teff) e_metal = pd.to_numeric(data[:, 93]) e_metal = (e_metal**2 + 0.062**2)**0.5 df[' Metallicity Err.'] = pd.Series(e_metal) df.to_csv('/Users/Tiago/Work/PostDocBham/KnownHosts_with_TESS/catalog_knownhosts/PARAM_input.csv', index=False)
Fill4/tess-yield
tess-yield/TASC_detection_recipe.py
TASC_detection_recipe.py
py
22,339
python
en
code
0
github-code
1
[ { "api_name": "warnings.simplefilter", "line_number": 35, "usage_type": "call" }, { "api_name": "numpy.log10", "line_number": 58, "usage_type": "call" }, { "api_name": "numpy.full", "line_number": 59, "usage_type": "call" }, { "api_name": "numpy.log10", "line_...
31379366652
from bs4 import BeautifulSoup as bs import csv import requests URL = 'https://kaktus.media/?lable=8&date=2022-10-15&order=time' dict_with_news = {} def get_html(url): response = requests.get(url) return response.text def get_soup(html): soup = bs(html, 'lxml') return soup def get_list_news(): html = get_html(URL) soup = get_soup(html) catalog = soup.find('div', class_='Tag--articles') news = catalog.find_all('div', class_='Tag--article') count = 1 list_news = [] for new in news: dict_with_news[count] = new name = f"{count}. {new.find('a', class_='ArticleItem--name').text.strip()}" list_news.append(name) count += 1 if count == 21: break return '\n'.join(list_news) def get_one_new(int_): url_of_one_new = dict_with_news[int_].find('a', 'ArticleItem--name').get('href') html = get_html(url_of_one_new) soup = get_soup(html) all_about_new = soup.find('div', class_='BbCode').find('p').text return all_about_new def get_photo(int_): photo = dict_with_news[int_].find('img', class_='ArticleItem--image-img lazyload').get('src') return photo
31nkmu/hackathon_bot_kaktus_media
parsing.py
parsing.py
py
1,183
python
en
code
1
github-code
1
[ { "api_name": "requests.get", "line_number": 10, "usage_type": "call" }, { "api_name": "bs4.BeautifulSoup", "line_number": 15, "usage_type": "call" } ]
17828467348
from django.contrib import admin from django.urls import path,include from . import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.index,name='Home'), path('aboutus/',views.aboutus,name='aboutUs'), path('product/<int:prodId>',views.prodDetails,name='prodDetails'), path('emptyCart/',views.emptyCart,name='emptyCart'), path('checkOut/',views.checkOut,name='checkOut'), ]
aman1100/thcProject
thcProject/thcProducts/urls.py
urls.py
py
421
python
en
code
1
github-code
1
[ { "api_name": "django.urls.path", "line_number": 6, "usage_type": "call" }, { "api_name": "django.contrib.admin.site", "line_number": 6, "usage_type": "attribute" }, { "api_name": "django.contrib.admin", "line_number": 6, "usage_type": "name" }, { "api_name": "dja...
5530540643
import config from db import db_config from db import db_users #from calendar import cal from flask import Flask, render_template, request from pymessager.message import Messager client = Messager(config.facebook_access_token) import os import json from msg_handlers import main_handler, notification_handler, responses import traceback from webviews.webviews import webview responses = responses.responses app = Flask(__name__, static_url_path="/static", static_folder="webviews/static") app.register_blueprint(webview, url_prefix='/webviews') @app.route('/') def hello_world(): return 'Hello, World!' @app.route('/msg/webhook', methods=["GET"]) def fb_webhook(): verification_code = 'I_AM_VERIFICIATION_CODE' verify_token = request.args.get('hub.verify_token') if verification_code == verify_token: return request.args.get('hub.challenge') @app.route('/msg/webhook', methods=['POST']) def fb_receive_message(): message_entries = json.loads(request.data.decode('utf8'))['entry'] print(message_entries) for entry in message_entries: for message in entry['messaging']: if message.get('message') and 'attachments' not in message['message']: try: main_handler.handle(message) print("{sender[id]} says {message[text]}".format(**message)) except Exception as e: print('--------------ERROR----------------') print(e) print('-----------------------------------') traceback.print_exc() print('-----------------------------------') client.send_text('1628181117202388', ['Hi boss, \nAn error occured when a user sent the following message:', message['message']['text'], 'Here is the error:','```C\n'+traceback.format_exc()+'\n```']) client.send_text(message['sender']['id'], responses['error']['general']) main_handler.update_state(message['sender']['id'], '') return "Hi", 200 @app.route('/send_notifications') def send_notifications(): notification_handler.handle() return 'hi', 200 if __name__ == '__main__': port = int(os.environ.get('PORT', 443)) app.run(host="0.0.0.0", port=port, ssl_context=('cert.pem', 'key.pem'))
kartikye/sch
run.py
run.py
py
2,339
python
en
code
0
github-code
1
[ { "api_name": "pymessager.message.Messager", "line_number": 7, "usage_type": "call" }, { "api_name": "config.facebook_access_token", "line_number": 7, "usage_type": "attribute" }, { "api_name": "msg_handlers.responses", "line_number": 15, "usage_type": "name" }, { ...
25777861293
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.Utils import COMMASPACE, formatdate # me == my email address # you == recipient's email address #assert type(to)==list def send_mail(to,fro,sub,html,html_text=None): #to = ['Chacha <sakhawat.sobhan@gmail.com>', 'mohua <mohua.amin@gmail.com>'] #fro = "mohua@finder-lbs.com" # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('alternative') msg['Subject'] = sub msg['From'] = fro #formataddr((str(Header(u'Finder Tracking', 'utf-8')), fro)) #fro msg['To'] = COMMASPACE.join(to) # Create the body of the message (a plain-text and an HTML version). #text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org" # html = """\ # <html> # <head> # <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> # <title>html title</title> # <style type="text/css" media="screen"> # table{ # background-color: #FFFFFF; # empty-cells:hide; # } # td.cell{ # background-color: white; # } # </style> # </head> # <body> # Hi there, <br> # I am glad that you have recieved this mail. No need to Reply.<br> # <table style="border: none;"> # <tr><td><img src="https://fbcdn-sphotos-e-a.akamaihd.net/hphotos-ak-xap1/v/t1.0-9/10653783_630992580346934_4425113809694913086_n.png?oh=3d14f24f768faa3304007efec66a491f&oe=554977A4&__gda__=1431036280_82a9361e9479848e96037d3e19055afd" alt="Sample Image" style="float:left;width:45px;height:35px"></td></tr> # </table><br> # <br>Regards<br>The Finder Team <br>Stay in touch ^_^<br> # </body> # </html> # """ # Record the MIME types of both parts - text/plain and text/html. part1 = MIMEText(html_text, 'plain') part2 = MIMEText(html, 'html') # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. msg.attach(part1) msg.attach(part2) # Send the message via local SMTP server. s = smtplib.SMTP('localhost') # sendmail function takes 3 arguments: sender's address, recipient's address # and message to send - here it is sent as one string. s.sendmail(fro, to, msg.as_string()) s.quit()
tanvirraj/hirenow
doc/generic_mail.py
generic_mail.py
py
2,470
python
en
code
1
github-code
1
[ { "api_name": "email.mime.multipart.MIMEMultipart", "line_number": 15, "usage_type": "call" }, { "api_name": "email.Utils.COMMASPACE.join", "line_number": 18, "usage_type": "call" }, { "api_name": "email.Utils.COMMASPACE", "line_number": 18, "usage_type": "name" }, { ...
18455156740
#import libraries from sklearn.model_selection import train_test_split import numpy as np from imblearn.over_sampling import SMOTE from svm_constructdata import constructdata from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import RandomizedSearchCV #generate data features,labels = constructdata('paper_train_data',59) #seed seed = 109 #convert label values from -1 to 0 for ii in range(0,len(labels)): if (labels[ii] == -1): labels[ii] = 0 #split data into test and train X_train, X_test, y_train, y_test = train_test_split(features,labels, test_size=0.25,random_state=seed) #Weighted Random Forest Classifier RF = RandomForestClassifier(random_state=seed,class_weight="balanced") #Create hyperparameter grid # Number of trees in random forest n_estimators = [int(x) for x in np.linspace(start = 200, stop = 2000, num = 10)] # Number of features to consider at every split max_features = ['auto', 'sqrt'] # Maximum number of levels in tree max_depth = [int(x) for x in np.linspace(10, 110, num = 11)] max_depth.append(None) # Minimum number of samples required to split a node min_samples_split = [2, 5, 10] # Minimum number of samples required at each leaf node min_samples_leaf = [1, 2, 4] # Method of selecting samples for training each tree bootstrap = [True, False] # Create the random grid random_grid = {'n_estimators': n_estimators, 'max_features': max_features, 'max_depth': max_depth, 'min_samples_split': min_samples_split, 'min_samples_leaf': min_samples_leaf, 'bootstrap': bootstrap} #Find and output results for best parameters based on scoring metric scores = ['roc_auc','f1'] for score in scores: print() print("# Tuning hyper-parameters for %s" % score) print() clf = RandomizedSearchCV(estimator = RF, param_distributions = random_grid, n_iter = 100, cv = 5, verbose=2, random_state=seed, n_jobs = -1,scoring= score) clf.fit(X_train,y_train) print("Best parameters set found on development set:") print() print(clf.best_params_) print() print("Grid scores on development set:") print() means = clf.cv_results_['mean_test_score'] stds = clf.cv_results_['std_test_score'] for mean, std, params in zip(means, stds, clf.cv_results_['params']): print("%0.3f (+/-%0.03f) for %r" % (mean, std * 2, params))
kksuresh25/Cancer-AI
Random Forest/rf_tunehyperparameters.py
rf_tunehyperparameters.py
py
2,420
python
en
code
1
github-code
1
[ { "api_name": "svm_constructdata.constructdata", "line_number": 10, "usage_type": "call" }, { "api_name": "sklearn.model_selection.train_test_split", "line_number": 21, "usage_type": "call" }, { "api_name": "sklearn.ensemble.RandomForestClassifier", "line_number": 24, "us...
32437306078
# Continuous cart pole using policy gradients (PG) # Running this script does the trick! import gym import numpy as np from gym import wrappers # env = gym.make('InvertedPendulum-v1') env = gym.make('Pendulum-v0') # env = wrappers.Monitor(env, '/home/sid/ccp_pg', force=True) def simulate(policy, steps, graphics=False): observation = env.reset() R = 0 for i in range(steps): if graphics: env.render() a = policy(observation) observation, reward, done, info = env.step(a) R += reward if done: break return R def grad_gaussian_policy(w, sigma, gamma): ''' Computes gradient for a one dimensional continuous action sampled from a gaussian :param w: parameters w of the mean of the gaussian policy a = w^Ts :param sigma: variance of the policy :param gamma: discount factor for variance reduction :return: reward and the gradient ''' R_tau = 0 observation = env.reset() grad = 0 d = 1 for i in range(1000): a = w.dot(observation) + sigma * np.random.randn() # log norm(w^Ts, sigma^2) = log(k/sigma) - (a-w^Ts)/sigma^2 # grad_w log norm(w^Ts, sigma^2) = (a-w^Ts).s/sigma**2 # grad_sigma log norm(w^Ts, sigma^2) = -1/sigma + (a-w^Ts)^2/sigma^3 # append 4x1 grad_w with grad_sigma grad += np.append(1. / sigma ** 2 * (a - w.dot(observation)) * observation, ### 4x1 -1. / sigma + 1. / sigma ** 3 * (a - w.dot(observation)) ** 2) ### 1x1 observation, reward, done, info = env.step([a]) R_tau += d * (reward) d *= gamma if done: break return R_tau, grad def pg(): sigma = 0.3 # noise standard deviation alpha = 0.05 # learning rate alpha_sigma = 0.01 n = env.observation_space.shape[0] w = np.random.randn(n) # initial guess epochs = 50000 n_samples = 20 b = 0 gamma = 1 max_R = -float('inf') if gamma < 1: T = 1. / (1 - gamma) else: T = float('inf') for i in range(epochs): if b < 10: w = np.random.randn(n) # restart R = np.zeros(n_samples) grad = np.zeros((n + 1, n_samples)) for j in range(n_samples): R[j], grad[:, j] = grad_gaussian_policy(w, sigma, gamma) b = np.mean(R) s = np.std(R) if s != 0: A = (R - b) / s # advantage else: A = R if b > min(T, 950): # if done..., we use T because by discounting rewards we can only at most get T return w if b > max_R: max_R = b best_w = w.copy() # some hardcoding for decreasing stepsize when we get higher rewards check_step = min(1, (50.0 / b)) dparam = check_step * alpha * 1. / n_samples * grad.dot(A) w += dparam[:-1] if sigma + alpha_sigma * dparam[-1] > 0: sigma += alpha_sigma * dparam[-1] if i % 100 == 0: print('iteration', i, 'mean return', b) print('bets R', max_R) return best_w w = pg() print('Training is Done, now run evaluations') r = 0 for i in range(100): r += simulate(lambda s: (w.dot(s)), 1000, True) print('average_return over 100 trials:', r / 100.0)
geyang/reinforcement_learning_learning_notes
gym-sessions/ge-baselines/simple_vpg.py
simple_vpg.py
py
3,296
python
en
code
3
github-code
1
[ { "api_name": "gym.make", "line_number": 9, "usage_type": "call" }, { "api_name": "numpy.random.randn", "line_number": 40, "usage_type": "call" }, { "api_name": "numpy.random", "line_number": 40, "usage_type": "attribute" }, { "api_name": "numpy.append", "line...
10361363697
import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator ## 1d example # camera is at origin and looks right # objects have position, importance, transparency ## Formulas # extinction \mu(x) = \alpha_x # optical_depth \tau(d_i) = \sum_j^i - \ln(1-\alpha_j) # = - \ln (\prod_j^i (1 - \alpha_j)) # = - \ln (T) # transmittance T = \exp -(\int_0^t \mu(x) dt) -> gives me wrong result # T = \exp (-\tau(d_i)) # T = \prod_j^i (1 - \alpha_j) class Object: def __init__(self, position, importance, transparency): self.position = position self.importance = importance self.transparency = transparency def calculate_extinction(objects, domain, detail): x = np.linspace(domain[0], domain[1], detail) y = np.zeros(shape=detail) for element in objects: idx = (np.abs(x - element.position)).argmin() y[idx] = element.transparency return x, y # maybe use pos mask + ordered alpha values to calculate this instead def calculate_transmittance(objects, domain, detail): x = np.linspace(domain[0], domain[1], detail) y = np.ones(shape=detail) for element in objects: idx = (np.abs(x - element.position)).argmin() y[idx] -= element.transparency y = np.cumprod(y) return x, y #def calculate_transmittance_optical(optical_depth): # transmittance = np.exp(-optical_depth[1]) # return optical_depth[0], transmittance #def calculate_transmittance_wrong(extinction): # integral = np.cumsum(extinction[1]) # transmittance = np.exp(-integral) # return extinction[0], transmittance def calculate_optical_depth(objects, domain, detail): x = np.linspace(domain[0], domain[1], detail) y = np.zeros(shape=detail) for element in objects: idx = (np.abs(x - element.position)).argmin() y[idx] = -np.log(1 - element.transparency) y = np.cumsum(y) return x, y def plot_extinction_transmittance_optical_depth(extinction, transmittance, optical_depth): fig, axs = plt.subplots(3) axs[0].step(extinction[0], extinction[1], where='mid') axs[0].set_title("Extinction") axs[1].step(transmittance[0], transmittance[1], where='mid') axs[1].set_title("Transmittance") axs[2].step(optical_depth[0], optical_depth[1], where='mid') axs[2].set_title("Optical depth") fig.tight_layout() plt.show() # function per fragment def energy_function_gun17(index, objects, p, q, l, r): object_i = objects[index] alpha_i = object_i.transparency importance_i = object_i.importance t1 = p / 2 * (alpha_i - 1) ** 2 t2 = 0 for obj in objects[index+1:]: # look at occluded objects t2 += (alpha_i * (1 - importance_i) ** l * obj.importance) ** 2 t2 = t2 * q / 2 t3 = 0 for obj in objects[:index]: # look at objects before us t3 += (alpha_i * (1 - importance_i) ** l * obj.importance) ** 2 t3 = t3 * r / 2 energy = t1 + t2 + t3 return energy # function per fragment def energy_function_gun17_array(index, objects, p, q, l, r, detail): importance_i = objects[index].importance alpha = np.linspace(0, 1, detail) t1 = p / 2 * (alpha - 1) ** 2 t2 = 0 for obj in objects[index+1:]: # look at occluded objects t2 += (alpha * (1 - importance_i) ** l * obj.importance) ** 2 t2 = t2 * q / 2 t3 = 0 for obj in objects[:index]: # look at objects before us t3 += (alpha * (1 - importance_i) ** l * obj.importance) ** 2 t3 = t3 * r / 2 energy = t1 + t2 + t3 return alpha, energy def plot_object_energy(objects, p, q, l, r, detail): plots = len(objects) fig, axs = plt.subplots(plots) for index in range(plots): energy = energy_function_gun17_array(index, objects, p, q, l, r, detail) min_idx = energy[1].argmin() axs[index].plot(energy[0], energy[1]) axs[index].plot(energy[0][min_idx], energy[1][min_idx], 'ro') annotation = r'$\alpha_{min}$ = %.2f' % energy[0][min_idx] axs[index].annotate(annotation, (energy[0][min_idx], energy[1][min_idx]), textcoords="offset points", xytext=(0,10), ha='center') axs[index].set_title(f"Energy of Object {index} with importance: {objects[index].importance}") axs[index].set_xlabel("Transparency") axs[index].set_ylabel("Energy") fig.tight_layout() plt.show() # maybe work with a position mask for the object -> n-hot vector -> avoid redundant calculation # position doesnt matter -> order does DOMAIN = 0, 4 DETAIL = 100 objects = [ Object(position=1, importance=0.2, transparency=0.5), Object(position=2, importance=0.5, transparency=0.5), #Object(position=3, importance=0.2, transparency=0.5), ] extinction = calculate_extinction(objects, DOMAIN, DETAIL) transmittance = calculate_transmittance(objects, DOMAIN, DETAIL) optical_depth = calculate_optical_depth(objects, DOMAIN, DETAIL) #plot_extinction_transmittance_optical_depth(extinction, transmittance, optical_depth) P = 1 Q = 50 LAMBDA = 3 R = 100 #plot_object_energy(objects, P, Q, LAMBDA, R, DETAIL) fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) # idea make transmitance energy function -> vector field function # -> input vector of transparencies # -> output vector of transmittance * importance # -> optimization -> find longest arrow in the field # Make data. X = np.linspace(0, 1, DETAIL) Y = np.linspace(0, 1, DETAIL) X, Y = np.meshgrid(X, Y) Z = np.zeros(shape=(DETAIL, DETAIL)) i1 = 0.2 i2 = 1 for x in range(DETAIL): for y in range(DETAIL): Z[y][x] = (1 - X[y][x]) * (1 - Y[y][x]) * i2 min_z = Z.argmin() min_val = Z.min() max_val = Z.max() # Plot the surface. surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False) # Customize the z axis. #ax.set_zlim(-0.5, 0.5) ax.zaxis.set_major_locator(LinearLocator(10)) # A StrMethodFormatter is used automatically ax.zaxis.set_major_formatter('{x:.02f}') # Add a color bar which maps values to colors. fig.colorbar(surf, shrink=0.5, aspect=5) plt.show()
BETuncay/demo-doo
example1d.py
example1d.py
py
6,164
python
en
code
0
github-code
1
[ { "api_name": "numpy.linspace", "line_number": 26, "usage_type": "call" }, { "api_name": "numpy.zeros", "line_number": 27, "usage_type": "call" }, { "api_name": "numpy.abs", "line_number": 29, "usage_type": "call" }, { "api_name": "numpy.linspace", "line_numbe...
5227372260
# 移动止盈止损策略 赢损比自定义 默认1.5:1 import pymysql as sql import pandas as pd import requests as req db = sql.connect(host="localhost", user="root", password="74110", database="quant-trade", port=3307, autocommit=True) sina_url = 'http://hq.sinajs.cn/list=' # 获取新浪财经的指定股票实时数据返回dateframe类型 #参考链接 https://www.jianshu.com/p/108b8110a98c def real_time_stock_price(stock_array): url = sina_url + ",".join(str(i) for i in stock_array) reslut_json = req.get(url).text df = pd.DataFrame(reslut_json) print(df) if __name__ == '__main__': real_time_stock_price(['sz002307', 'sh600928']) # 增删改的sql def sql_fun(sql, args_array): con = db.cursor() result = con.execute(sql, args_array) con.close() return result # 查询的sql def get_sql_fun(select_sql, args_array): con = db.cursor() con.execute(sql, args_array) df = pd.DataFrame(list(con.fetchall())) con.close() return df
ZHAOHUHU/quant-trade
com/quant/trade/zhao/tralling_stop.py
tralling_stop.py
py
1,024
python
en
code
0
github-code
1
[ { "api_name": "pymysql.connect", "line_number": 6, "usage_type": "call" }, { "api_name": "requests.get", "line_number": 15, "usage_type": "call" }, { "api_name": "pandas.DataFrame", "line_number": 16, "usage_type": "call" }, { "api_name": "pandas.DataFrame", "...
1747709397
import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import plotly.graph_objs as go import numpy as np # input N=100 returns_input = np.array([0.04,0.06]) volas_input = np.array([0.06,0.10]) corr_input=0 def covariance(corr_coef, volas): corr = np.array([[1, corr_coef],[corr_coef, 1]]) cov = np.diag(volas) @ corr @ np.diag(volas) return cov # def minvar(returns, cov) # minvar_w = np.divide(np.linalg.inv(cov) @ np.ones(len(returns)), np.ones(len(returns)).T @ np.linalg.inv(cov) @ np.ones(len(returns))) # w1 = np.linspace(0, 1, N) # w2=1-w1 # w = np.array([w1,w2]).T # return w def efffrontier(returns, cov): A = np.array(returns).T @ np.linalg.inv(cov) @ np.ones(len(returns)) B = np.array(returns).T @ np.linalg.inv(cov) @ np.array(returns) C = np.ones(len(returns)).T @ np.linalg.inv(cov) @ np.ones(len(returns)) D = B * C - A**2 exp_return = np.linspace(min(returns), max(returns), num=100) sigma_return = np.sqrt(1/D * (C * np.multiply(exp_return, exp_return) - 2 * A * exp_return + B)) return exp_return, sigma_return cov_input = covariance(corr_input) x, y = efffrontier(returns_input, cov_input) external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets) app.layout = html.Div([ dcc.Graph(id='graph-with-slider'), dcc.Slider( id='corr-slider', min=-1, max=1, value=0, step=0.1 ) ]) @app.callback( Output('graph-with-slider', 'figure'), [Input('corr-slider', 'value')]) def update_figure(selected_corr): cov_updated = covariance(selected_corr) out1, out2 = efffrontier(returns_input, cov_updated) traces = [] traces.append(go.Scatter( x = out2, y = out1, mode='markers', opacity=0.7, marker={ 'size': 15, 'line': {'width': 0.5, 'color': 'white'} }, )) return { 'data': traces, 'layout': go.Layout( xaxis={'title': 'Sigma'}, yaxis={'title': 'Mu'}, margin={'l': 40, 'b': 40, 't': 10, 'r': 10}, legend={'x': 0, 'y': 1}, hovermode='closest' ) } if __name__ == '__main__': app.run_server(debug=True)
investeer-io/markowitz_bokeh
dashEfficientFrontierSlider.py
dashEfficientFrontierSlider.py
py
2,474
python
en
code
0
github-code
1
[ { "api_name": "numpy.array", "line_number": 12, "usage_type": "call" }, { "api_name": "numpy.array", "line_number": 13, "usage_type": "call" }, { "api_name": "numpy.array", "line_number": 18, "usage_type": "call" }, { "api_name": "numpy.diag", "line_number": 1...
1101552482
import torch import torch.optim as optim from torch.autograd import Variable from torchvision import datasets, transforms import os import matplotlib.pyplot as plt from autoencoder import Autoencoder from gmmn import * from constants import * if not os.path.exists(root): os.mkdir(root) if not os.path.exists(model): os.mkdir(model) # use gpu if available device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # dataloader trans = transforms.Compose([transforms.ToTensor()]) train_set = datasets.MNIST(root=root, train=True, transform=trans, download=True) train_loader = torch.utils.data.DataLoader( dataset=train_set, batch_size=BATCH_SIZE, shuffle=True) # train the autoencoder first encoder_net = Autoencoder(N_INP, ENCODED_SIZE).to(device) encoder_optim = optim.Adam(encoder_net.parameters()) if os.path.exists(ENCODER_SAVE_PATH): encoder_net.load_state_dict(torch.load(ENCODER_SAVE_PATH)) print("Loaded saved autoencoder model") else: for ep in range(N_ENCODER_EPOCHS): avg_loss = 0 for idx, (x, _) in enumerate(train_loader): x = x.view(x.size()[0], -1) x = Variable(x).to(device) _, decoded = encoder_net(x) loss = torch.sum((x - decoded) ** 2) encoder_optim.zero_grad() loss.backward() encoder_optim.step() avg_loss += loss.item() avg_loss /= (idx + 1) print("Autoencoder Training: Epoch - [%2d] complete, average loss - [%.4f]" %(ep + 1, avg_loss)) torch.save(encoder_net.state_dict(), ENCODER_SAVE_PATH) print("Autoencoder has been successfully trained") # define the GMMN gmm_net = GMMN(NOISE_SIZE, ENCODED_SIZE).to(device) if os.path.exists(GMMN_SAVE_PATH): gmm_net.load_state_dict(torch.load(GMMN_SAVE_PATH)) print("Loaded previously saved GMM Network") gmmn_optimizer = optim.Adam(gmm_net.parameters(), lr=0.001) def get_scale_matrix(M, N): s1 = (torch.ones((N, 1)) * 1.0 / N).to(device) s2 = (torch.ones((M, 1)) * -1.0 / M).to(device) return torch.cat((s1, s2), 0) def train_one_step(x, samples, sigma=[1]): samples = Variable(samples).to(device) gen_samples = gmm_net(samples) X = torch.cat((gen_samples, x), 0) XX = torch.matmul(X, X.t()) X2 = torch.sum(X * X, 1, keepdim=True) exp = XX - 0.5 * X2 - 0.5 * X2.t() M = gen_samples.size()[0] N = x.size()[0] s = get_scale_matrix(M, N) S = torch.matmul(s, s.t()) loss = 0 for v in sigma: kernel_val = torch.exp(exp / v) loss += torch.sum(S * kernel_val) loss = torch.sqrt(loss) gmmn_optimizer.zero_grad() loss.backward() gmmn_optimizer.step() return loss # training loop for ep in range(N_GEN_EPOCHS): avg_loss = 0 for idx, (x, _) in enumerate(train_loader): x = x.view(x.size()[0], -1) with torch.no_grad(): x = Variable(x).to(device) encoded_x = encoder_net.encode(x) # uniform random noise between [-1, 1] random_noise = torch.rand((BATCH_SIZE, NOISE_SIZE)) * 2 - 1 loss = train_one_step(encoded_x, random_noise) avg_loss += loss.item() avg_loss /= (idx + 1) print("GMMN Training: Epoch - [%3d] complete, average loss - [%.4f]" %(ep, avg_loss)) torch.save(gmm_net.state_dict(), GMMN_SAVE_PATH)
Abhipanda4/GMMN-Pytorch
train.py
train.py
py
3,369
python
en
code
13
github-code
1
[ { "api_name": "os.path.exists", "line_number": 13, "usage_type": "call" }, { "api_name": "os.path", "line_number": 13, "usage_type": "attribute" }, { "api_name": "os.mkdir", "line_number": 14, "usage_type": "call" }, { "api_name": "os.path.exists", "line_numbe...
15278137621
# Hashmap + list from collections import Counter class FindSumPairs: def __init__(self, nums1, nums2): self.n1, self.n2 = Counter(nums1), Counter(nums2) self.n = [i for i in nums2] def add(self, index: int, val: int) -> None: self.n2[self.n[index]] -= 1 # Remove the element from the dict self.n[index] += val # Add the val to the given index self.n2[self.n[index]] += 1 # add the (elem+val) to the dictionary def count(self, tot: int) -> int: res = 0 for j in self.n1: if tot - j in self.n2: # found a pair res += self.n2[tot - j] * self.n1[j] return res # Your FindSumPairs object will be instantiated and called as such: # obj = FindSumPairs(nums1, nums2) # obj.add(index,val) # param_2 = obj.count(tot)
onyxolu/DSA
Bloomberg/Top 100/FindingPairsWithACertainSum.py
FindingPairsWithACertainSum.py
py
827
python
en
code
0
github-code
1
[ { "api_name": "collections.Counter", "line_number": 8, "usage_type": "call" } ]
569319840
from rest_framework import serializers # from departamentos.api.serializers import DepartamentoSerializer # from municipios.api.serializers import MunicipioSerializer from usuarios.models import Usuario class UsuarioSerializer(serializers.ModelSerializer): # municipio = MunicipioSerializer() # departamento = DepartamentoSerializer() class Meta: model = Usuario fields = ['id', 'uid', 'nombre', 'email', 'foto', 'fecha_nacimiento', 'telefono', 'genero', 'telefono', 'departamento', 'municipio' ]
OscarRuiz15/BackendTG
usuarios/api/serializers.py
serializers.py
py
727
python
es
code
0
github-code
1
[ { "api_name": "rest_framework.serializers.ModelSerializer", "line_number": 8, "usage_type": "attribute" }, { "api_name": "rest_framework.serializers", "line_number": 8, "usage_type": "name" }, { "api_name": "usuarios.models.Usuario", "line_number": 13, "usage_type": "name...
15238963233
import json import pickle def getNumToTagsMap(): with open("./metadata/all_tags.cls") as fi: taglist = map(lambda x: x[:-1], fi.readlines()) with open("./metadata/mappings.json") as fi: mapping = json.loads(fi.read()) finalTag = list(map(lambda x: mapping[x], taglist)) return finalTag def bgr2rgb(img): res = img + 0.0 if len(res.shape) == 4: res[:, 0, :, :] = img[:, 2, :, :] res[:, 2, :, :] = img[:, 0, :, :] else: res[0, :, :] = img[2, :, :] res[2, :, :] = img[0, :, :] return res def reverseTransform(img, aud): mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] for i in range(3): img[:, i, :, :] = img[:, i, :, :] * std[i] + mean[i] return img, aud # convert string to boolean variable def stob(bool_str, config_name): if isinstance(bool_str, bool): return bool_str if bool_str == "True" or bool_str == "true": return True elif bool_str == "False" or bool_str == "false": return False else: raise ValueError( "Configuration {} will only accept one among True, true, False, and false.".format(config_name) ) def save_result(path, query, relevant): with open(path, "wb") as f: pickle.dump(query, f) pickle.dump(relevant, f) def load_result(path): """ Description: Return two lists: - list1: query. - list2: top k relevants. Parameters: path: path for pickle file. """ with open(path, "rb") as f: query = pickle.load(f) relevant = pickle.load(f) return query, relevant if __name__ == "__main__": query, rele = load_result("results/results.pickle") print(rele)
kyuyeonpooh/objects-that-sound
utils/util.py
util.py
py
1,765
python
en
code
31
github-code
1
[ { "api_name": "json.loads", "line_number": 10, "usage_type": "call" }, { "api_name": "pickle.dump", "line_number": 53, "usage_type": "call" }, { "api_name": "pickle.dump", "line_number": 54, "usage_type": "call" }, { "api_name": "pickle.load", "line_number": 6...
70107487715
from django.urls import path from . import views urlpatterns = [ path('list_plants/', views.all_plants, name='list_plants'), path('add_plant/', views.add_plant, name='add_plant'), path('edit_plant/<int:plant_id>/', views.edit_plant, name='edit_plant'), path('plant_detail/<int:location_id>/<int:pk>/', views.PlantDetail.as_view(), name='plant_detail'), path('delete_plant/<int:pk>', views.DeletePlant.as_view(), name='delete_plant'), path('common_name_validate/', views.common_name_validate, name='common_name_validate'), path('list_plant_records/', views.list_plant_records, name='list_plant_records'), path('change_plant_state/<int:record_pk>', views.change_plant_state, name='change_plant_state'), path('add_plant_record/', views.AddPlantRecord.as_view(), name='add_plant_record'), path('delete_plant_record/<int:pk>', views.DeletePlantRecord.as_view(), name='delete_plant_record'), ]
Stephen-J-Whitaker/wild-carbon
plants/urls.py
urls.py
py
1,029
python
en
code
0
github-code
1
[ { "api_name": "django.urls.path", "line_number": 5, "usage_type": "call" }, { "api_name": "django.urls.path", "line_number": 6, "usage_type": "call" }, { "api_name": "django.urls.path", "line_number": 7, "usage_type": "call" }, { "api_name": "django.urls.path", ...
19142088501
from . import constants def get_response(url: str, headers: dict = constants.DEFAULT_HEADERS): try: import requests as r except ImportError: raise "Not search a requests module." response = r.get(url=url, headers=headers) if response.status_code != 200: raise "Not response content..." return response def get_html_tags(html: str, pattern: str = r'<([a-z]+)+( [a-z\-]+=[a-z0-9\.\'\"\@\#\$\%\^\&\*\/\:]+)*>'): import re pattern = re.compile(pattern) tags = re.findall(pattern, html) return tags def convert_to_list(v: str): v: list = [val for val in v.split(".") if val] v = list(map(int, v)) try: while not v[-1]: v.pop() except IndexError: pass return v
PavelKrivorotov/Test_Task_python_04_02_2023
main/main/utils.py
utils.py
py
773
python
en
code
0
github-code
1
[ { "api_name": "requests.get", "line_number": 10, "usage_type": "call" }, { "api_name": "re.compile", "line_number": 20, "usage_type": "call" }, { "api_name": "re.findall", "line_number": 21, "usage_type": "call" } ]
43645610632
import pyspark import pyspark.sql from pyspark.sql import * from pyspark.sql.functions import * import json import urllib import argparse conf = pyspark.SparkConf().setMaster("local[*]").setAll([ ('spark.jars.packages', 'com.databricks:spark-xml_2.11:0.8.0'), ('spark.driver.memory','230g'), ('spark.driver.maxResultSize', '32G'), ('spark.local.dir', '/scratch/tmp/'), ('spark.yarn.stagingDir', '/scratch/tmp/') ]) # conf = pyspark.SparkConf().setMaster("yarn") # create the session spark = SparkSession.builder.config(conf=conf).getOrCreate() # create the context sc = spark.sparkContext parser = argparse.ArgumentParser() parser.add_argument('--site', action="store") args = parser.parse_args() site = args.site # 'en' matched_ngrams = spark.read.parquet("datasets/{}/matched_ngrams.parquet".format(site))\ .selectExpr("anchor as ngram", "qid", "occ") ngrams_as_text = matched_ngrams.groupBy("ngram").agg(sum("occ").alias("as_text")) commonness = spark.read.parquet("datasets/{}/anchors_stats.parquet".format(site)) ngram_as_link = commonness.groupBy("anchor").agg(sum("anchor_count").alias("as_link")) ngrams_as_text.registerTempTable("ngrams_as_text") ngram_as_link.registerTempTable("ngram_as_link") query = """ SELECT anchor, as_link, CASE WHEN as_text is NULL THEN 0 ELSE as_text END as as_text FROM ngram_as_link l LEFT JOIN ngrams_as_text t ON t.ngram=l.anchor """ anchors_beta = spark.sql(query).selectExpr("*", "as_link/(as_text+as_link) as beta") anchors_beta.write.mode("overwrite").parquet("datasets/{}/anchors_beta.parquet".format(site))
epfl-dlab/WikiPDA
PaperAndCode/TopicsExtractionPipeline/GetBeta.py
GetBeta.py
py
1,797
python
en
code
10
github-code
1
[ { "api_name": "pyspark.SparkConf", "line_number": 10, "usage_type": "call" }, { "api_name": "argparse.ArgumentParser", "line_number": 25, "usage_type": "call" } ]
27172359979
from django import forms from .models import Tag, Post from django.core.exceptions import ValidationError class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'slug', 'body', 'tags'] widgets = { 'title': forms.TextInput(attrs={'class': 'form-control'}), 'slug': forms.TextInput(attrs={'class': 'form-control'}), 'body': forms.Textarea(attrs={'class': 'form-control'}), 'tags': forms.SelectMultiple(attrs={'class': 'form-control'}) } def clean_slug(self): new_slug = self.cleaned_data['slug'].lower() if new_slug == 'create': raise ValidationError('Slug can\'t be named as "create".') return new_slug class PostCreateForm(forms.Form): title = forms.CharField(max_length=50) slug = forms.SlugField(allow_unicode=True, max_length=50, required=False) body = forms.CharField(widget=forms.Textarea(attrs={})) tags = forms.TypedMultipleChoiceField(choices=list(zip(range(len(Tag.objects.all())), [tag.title for tag in Tag.objects.all()])), coerce=lambda num: Tag.objects.all()[int(num)]) title.widget.attrs.update({'class': 'form-control'}) slug.widget.attrs.update({'class': 'form-control'}) body.widget.attrs.update({'class': 'form-control'}) tags.widget.attrs.update({'class': 'form-control'}) def __init__(self, author=None, *args, **kwargs): self.author = author super().__init__(*args, **kwargs) def clean_slug(self): new_slug = self.cleaned_data['slug'].lower() if new_slug == 'create': raise ValidationError('Slug can\'t be named as "create".') return new_slug def save(self): if self.author: post = Post() post.title = self.cleaned_data['title'] post.slug = self.cleaned_data['slug'] post.body = self.cleaned_data['body'] post.author = self.author post.save() post.tags.add(*self.cleaned_data['tags']) post.save() return post class TagForm(forms.ModelForm): class Meta: model = Tag fields = ['title', 'slug'] widgets = { 'title': forms.TextInput(attrs={'class': 'form-control'}), 'slug': forms.TextInput(attrs={'class': 'form-control'}), } def clean_slug(self): new_slug = self.cleaned_data['slug'].lower() if new_slug == 'create': raise ValidationError('Slug can\'t be named as "create".') # if Tag.objects.filter(slug__iexact=new_slug).exists(): # raise ValidationError("Slug alredy exists.") return new_slug
HolidayMan/pinkerblog
blog/engine/forms.py
forms.py
py
2,745
python
en
code
0
github-code
1
[ { "api_name": "django.forms.ModelForm", "line_number": 6, "usage_type": "attribute" }, { "api_name": "django.forms", "line_number": 6, "usage_type": "name" }, { "api_name": "models.Post", "line_number": 9, "usage_type": "name" }, { "api_name": "django.forms.TextIn...
43687469628
# -*- coding: utf-8 -*- import os,sys,inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(0,parentdir) from PyQt4 import QtGui from PyQt4 import QtCore import os import modules.filter as tableWidgetFilters import modules.tools as tools from modules.tabs.currency.currency import setCurrency try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) def applyLayout(self): self.tabWidget.show() self.tabsStash = QtGui.QWidget() self.tabsStash.setObjectName(_fromUtf8("tab")) self.tabsCurrency = QtGui.QWidget() self.tabsCurrency.setObjectName(_fromUtf8("tabCurrency")) self.verticalLayout = QtGui.QVBoxLayout(self.tabsStash) self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) self.verticalLayoutCurrency = QtGui.QVBoxLayout(self.tabsCurrency) self.verticalLayoutCurrency.setObjectName(_fromUtf8("verticalLayoutCurrency")) self.groupBox = QtGui.QGroupBox(self.tabsStash) self.groupBox.setObjectName(_fromUtf8("groupBox")) self.groupBoxCurrency = QtGui.QGroupBox(self.tabsCurrency) self.groupBoxCurrency.setObjectName(_fromUtf8("groupBoxCurrency")) self.verticalLayout2 = QtGui.QVBoxLayout(self.groupBox) self.verticalLayout2.setObjectName(_fromUtf8("verticalLayout2")) self.verticalLayoutCurrency2 = QtGui.QVBoxLayout(self.groupBoxCurrency) self.verticalLayoutCurrency2.setObjectName(_fromUtf8("verticalLayoutCurrency2")) self.tabWidget.addTab(self.tabsStash, _fromUtf8("")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabsStash), _translate("MainWindow", "Stash", None)) self.tabWidget.addTab(self.tabsCurrency, _fromUtf8("")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabsCurrency), _translate("MainWindow", "Currency", None)) self.verticalLayout.addWidget(self.groupBox) self.verticalLayoutCurrency.addWidget(self.groupBoxCurrency) self.tableWidget = QtGui.QTableWidget(self.groupBox) font = QtGui.QFont() font.setFamily(_fromUtf8("MS Shell Dlg 2")) font.setPointSize(10) self.tableWidget.setFont(font) self.tableWidget.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers) self.tableWidget.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows) self.tableWidget.setShowGrid(True) self.tableWidget.setObjectName(_fromUtf8("tableWidget")) self.tableWidgetCurrency = QtGui.QTableWidget(self.groupBoxCurrency) self.tableWidgetCurrency.setFont(font) self.tableWidgetCurrency.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers) self.tableWidgetCurrency.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows) self.tableWidgetCurrency.setShowGrid(True) self.tableWidgetCurrency.setObjectName(_fromUtf8("tableWidgetCurrency")) self.verticalLayout2.addWidget(self.tableWidget) self.verticalLayoutCurrency2.addWidget(self.tableWidgetCurrency) self.tableWidget.horizontalHeader().setVisible(True) self.tableWidget.verticalHeader().setVisible(True) self.tableWidget.setSortingEnabled(True) self.tableWidget.setEnabled(False) self.tableWidgetCurrency.horizontalHeader().setVisible(True) self.tableWidgetCurrency.verticalHeader().setVisible(True) self.tableWidgetCurrency.setSortingEnabled(True) self.tableWidgetCurrency.setEnabled(False) #add defined columns with headers from global_values for Stash for columns in range (len(self.ig.columnsHeaders)): self.tableWidget.insertColumn(columns) item = QtGui.QTableWidgetItem(self.ig.columnsHeaders[columns]['columnHeader']) self.tableWidget.setHorizontalHeaderItem(columns, item) item = self.tableWidget.horizontalHeaderItem(columns) self.savedFiltersComboBox.currentIndexChanged.connect(lambda: loadAndApplyFilter(self)) #add defined columns with headers from global_values for Currency for columns in range (len(self.ig.columnsHeadersCurrency)): self.tableWidgetCurrency.insertColumn(columns) item = QtGui.QTableWidgetItem(self.ig.columnsHeadersCurrency[columns]['columnHeader']) self.tableWidgetCurrency.setHorizontalHeaderItem(columns, item) item = self.tableWidgetCurrency.horizontalHeaderItem(columns) #self.savedFiltersComboBox.currentIndexChanged.connect(lambda: loadAndApplyFilter(self)) def tableWidgetContentsAutoSize(form): scrollToTopLeftItem(form) form.statusbar.showMessage('Autosizing rows and columns...') form.tableWidget.resizeColumnsToContents() form.tableWidget.resizeRowsToContents() form.tableWidgetCurrency.resizeColumnsToContents() form.tableWidgetCurrency.resizeRowsToContents() form.statusbar.showMessage('Ready') def scrollToTopLeftItem(form): if form.tableWidget.rowCount() > 0: column = None for i in range(len(form.ig.jsonConfig['view']['columns'])): if form.ig.jsonConfig['view']['columns'][i]['isHidden'] == False: column = i break if column == None: return if form.tableWidget.isRowHidden(0): form.tableWidget.showRow(0) form.tableWidget.scrollToItem(form.tableWidget.item(0, i)) form.tableWidget.hideRow(0) else: form.tableWidget.scrollToItem(form.tableWidget.item(0, i)) def tableWidgetSetResizeMode(form): for i in range (form.tableWidget.columnCount()): form.tableWidget.horizontalHeader().setResizeMode(i, QtGui.QHeaderView.ResizeToContents) for j in range (form.tableWidget.rowCount()): form.tableWidget.verticalHeader().setResizeMode(j, QtGui.QHeaderView.ResizeToContents) def setFixedColumnsWidth(self): for i in range (self.tableWidget.columnCount()): self.tableWidget.setColumnWidth(i, 125) self.tableWidget.item(0,2).setTextAlignment(QtCore.Qt.AlignCenter) def tableWidgetDisableResizeToContents(form): for i in range (form.tableWidget.columnCount()): form.tableWidget.horizontalHeader().setResizeMode(i, QtGui.QHeaderView.Interactive) for j in range (form.tableWidget.rowCount()): form.tableWidget.verticalHeader().setResizeMode(j, QtGui.QHeaderView.Interactive) def tableWidgetSetColumnsSelected(form): for i in range (form.tableWidget.columnCount()): if form.ig.jsonConfig['view']['columns'][i]['isHidden']: form.tableWidget.hideColumn(i) def tableWidgetBeforeLoad(form): form.tableWidget.setEnabled(False) form.tableWidget.setRowCount(0) form.tableWidgetCurrency.setRowCount(0) form.tableWidget.setSortingEnabled(False) form.tableWidgetCurrency.setSortingEnabled(False) tableWidgetDisableResizeToContents(form) def tableWidgetAfterLoad(form): setCurrency(form) tableWidgetSetColumnsSelected(form) form.tableWidget.setSortingEnabled(True) form.tableWidgetCurrency.setSortingEnabled(True) loadFiltersToSavedFiltersComboBox(form) form.ig.itemCount = form.tableWidget.rowCount() form.ig.itemFound = form.ig.itemCount form.guideLineEdit.setText(form.guideLineEdit.text() + ' (' + str(form.tableWidget.rowCount()) + ' items)') tableWidgetContentsAutoSize(form) form.tableWidget.setEnabled(True) form.tableWidgetCurrency.setEnabled(True) def loadFiltersToSavedFiltersComboBox(form): form.savedFiltersComboBox.clear() form.savedFiltersComboBox.addItem('Saved filter selection') for file in os.listdir(form.ig.filtersDir): if os.path.isfile(os.path.join(form.ig.filtersDir, file)) and (file.endswith('.filter')): form.savedFiltersComboBox.addItem(os.path.splitext(file)[0]) if not form.savedFiltersComboBox.currentText(): return def loadAndApplyFilter(form): if (form.savedFiltersComboBox.currentText()) and (form.savedFiltersComboBox.currentText() != 'Saved filter selection'): filterJsonFileName = os.path.join(form.ig.filtersDir, unicode(form.savedFiltersComboBox.currentText()) + '.filter') if os.path.isfile(filterJsonFileName): filterJsonData = tools.readJson(filterJsonFileName) applyFilter(form, filterJsonData) def applyFilter(form, filterJsonData): form.statusbar.showMessage('Applying filter...') tableWidgetDisableResizeToContents(form) tableWidgetFilters.resetFilter(form) tableWidgetFilters.applyFilter(form, filterJsonData['filter']['filterLines']) tableWidgetContentsAutoSize(form) form.statusbar.showMessage('Filter applied' + ' (' + str(form.ig.itemFound) + ' items found)')
Doberm4n/POEStashJsonViewer
ui/main_layout.py
main_layout.py
py
8,943
python
en
code
0
github-code
1
[ { "api_name": "os.path.dirname", "line_number": 3, "usage_type": "call" }, { "api_name": "os.path", "line_number": 3, "usage_type": "attribute" }, { "api_name": "os.path.abspath", "line_number": 3, "usage_type": "call" }, { "api_name": "inspect.getfile", "line...
37413122640
import torch import torch.nn as nn import torch.nn.functional as F from model.octconv import * import model.venconv as venconv from model.median_pooling import median_pool_2d class SNRom(nn.Module): def __init__(self, in_channels=1, hide_channels=64, out_channels=1, kernel_size=3, alpha_in=0.5, alpha_out=0.5, stride=1, padding=0, dilation=1, groups=1, bias=False, hide_layers=8): super(SNRom, self).__init__() # parameters self.kernel_size = kernel_size self.alpha_in = alpha_in self.alpha_out = alpha_out self.stride = stride self.padding = padding self.dilation = dilation self.groups = groups self.bias = bias self.hide_layers = hide_layers self.input_layers = 2 self.output_layers = 2 # convolution layers self.octavecons = nn.ModuleList( Conv_BN_ACT(hide_channels, hide_channels, kernel_size, alpha_in, alpha_out, stride, padding, dilation, groups, bias, activation_layer=nn.ReLU) for i in range(hide_layers * 2)) # residual layers self.rescons = nn.ModuleList(ResBlock(hide_channels, hide_channels, kernel_size, alpha_in, alpha_out, stride, padding, dilation, groups) for i in range(hide_layers * 2)) # for input self.downs = nn.AvgPool2d(kernel_size=(2, 2), stride=2) self.proninl = venconv.Conv_BN_ACT(int(in_channels), int(alpha_in * hide_channels), kernel_size, 1, padding, dilation, groups, bias, activation_layer=nn.PReLU) self.proninh = venconv.Conv_BN_ACT(int(in_channels), hide_channels - int(alpha_in * hide_channels), kernel_size, 1, padding, dilation, groups, bias, activation_layer=nn.PReLU) # Pre process layers self.inLowLists = nn.ModuleList( venconv.Conv_BN_ACT(int(alpha_in * hide_channels), int(alpha_in * hide_channels), kernel_size, 1, padding, dilation, groups, bias, activation_layer=nn.PReLU) for i in range(self.input_layers)) self.inHighLists = nn.ModuleList( venconv.Conv_BN_ACT(hide_channels - int(alpha_in * hide_channels), hide_channels - int(alpha_in * hide_channels), kernel_size, 1, padding, dilation, groups, bias, activation_layer=nn.PReLU) for i in range(self.input_layers)) # for output self.proutl = venconv.Conv_BN_ACT(int(alpha_in * hide_channels), out_channels, kernel_size, 1, padding, dilation, groups, bias, activation_layer=nn.ReLU ) self.prouth = venconv.Conv_BN_ACT(hide_channels - int(alpha_in * hide_channels), out_channels, kernel_size, 1, padding, dilation, groups, bias, activation_layer=nn.ReLU ) self.proutc = venconv.Conv_BN_ACT(out_channels, out_channels, kernel_size, 1, padding, dilation, groups, bias, activation_layer=nn.ReLU ) def forward(self, x): # Split input image x_l = self.downs(x) # Channel expansion x_l = self.proninl(x_l) x_h = self.proninh(x) # Pre process for i in range(self.input_layers): x_l = self.inLowLists[i](x_l) x_h = self.inHighLists[i](x_h) for i in range(self.hide_layers * 2): x_h, x_l = self.octavecons[i]((x_h, x_l)) if i < self.hide_layers: x_h = median_pool_2d(x_h, self.kernel_size, self.stride, self.padding, self.dilation) # x_l = median_pool_2d(x_l, self.kernel_size, self.stride, self.padding, self.dilation) x_h, x_l = self.rescons[i]((x_h, x_l)) x_h = self.prouth(x_h) output = self.proutc(x_h) x_l = self.proutl(x_l) return output, x_l
StephenYang190/SpeckleNoisePytorch
model/SNRom.py
SNRom.py
py
4,128
python
en
code
0
github-code
1
[ { "api_name": "torch.nn.Module", "line_number": 9, "usage_type": "attribute" }, { "api_name": "torch.nn", "line_number": 9, "usage_type": "name" }, { "api_name": "torch.nn.ModuleList", "line_number": 26, "usage_type": "call" }, { "api_name": "torch.nn", "line_...
15850354420
import pandas as pd from typing import Union, List, Optional, Tuple from bokeh.io import output_notebook from bokeh.resources import INLINE from bokeh.plotting import figure, gridplot from bokeh.plotting import show as _show from pandas.api.types import is_string_dtype from bokeh.palettes import Set1 output_notebook(INLINE) def _colors(n: int) -> List[str]: assert n <= 8, f"{n} > 8 is not supported" return Set1[8][:n] _StrListLike = Union[str, List[str]] def parse_str_list(s: _StrListLike, sep=",") -> List[str]: if isinstance(s, list): return s elif isinstance(s, str): return s.split(sep) else: raise TypeError(type(s)) def plot(df: pd.DataFrame, *, x: str, y: Union[str, List[str]], hue: Optional[str]=None, hlines: List[float]=[], vlines: List[float]=[], line_types: _StrListLike="line", figsize: Tuple[float]=(800, 500), title: Optional[str]=None, show: bool=True, tools: str="pan,reset,wheel_zoom,box_zoom,save", ): if isinstance(y, list): assert hue is None df = pd.melt(df, id_vars=x, value_vars=y, var_name=" variable", value_name=" value", ) y = " value" hue = " variable" else: df = df.copy() if hue is None: df["dummy"] = y hue = "dummy" if not is_string_dtype(df[hue]): df[hue] = df[hue].astype(str) unique_hues = df[hue].unique() palette = _colors(len(unique_hues)) w, h = figsize if title is None: title = y p = figure(title=title, tools=tools, width=w, height=h) p.toolbar.active_scroll = None line_types = parse_str_list(line_types, sep=",") for color, hue_ in zip(palette, unique_hues): legend_label = hue_ df_hue = df[df[hue] == hue_].copy() for line_type in line_types: line_func = getattr(p, line_type) line_func(df_hue[x], df_hue[y], color=color, legend_label=legend_label) for hl in hlines: p.line(df_hue[x], hl, color="black", line_dash="dashed") for vl in vlines: p.line(df_hue[vl], hl, color="black", line_dash="dashed") if show is True: _show(p) return p def tsplot(df, *, time_var, y: Union[str, List[str]], hue: Optional[str]=None, show: bool=True, **kw, ): p = plot(df, x=time_var, y=y, hue=hue, show=False, **kw) from bokeh.models import DatetimeTickFormatter p.xaxis.formatter = DatetimeTickFormatter( years="%Y", months="%Y%m", days="%Y%m%d", hours="%Y%m%d %Hh", minutes="%Y%m%d-%H:%M") if show is True: _show(p) return p
idiotekk/unknownlib
lib/unknownlib/plt/bk.py
bk.py
py
2,990
python
en
code
0
github-code
1
[ { "api_name": "bokeh.io.output_notebook", "line_number": 10, "usage_type": "call" }, { "api_name": "bokeh.resources.INLINE", "line_number": 10, "usage_type": "argument" }, { "api_name": "bokeh.palettes.Set1", "line_number": 15, "usage_type": "name" }, { "api_name"...
70766232034
from stable_baselines3 import A2C from algos.PlaNet.planet import PlaNet from algos.PlaNet.policies import DiscreteMPCPlanner from algos.PlaNet.world_model import DreamerModel import os from buffers.chunk_buffer import ChunkReplayBuffer from buffers.introspective_buffer import IntrospectiveChunkReplayBuffer from algos.dreamer.dreamer import Dreamer from algos.dreamer.policies import DreamerPolicy __all__ = ['setup_dreamer', 'setup_a2c', 'setup_planet'] def _update_after(cfg): return 'step' if 'update_after' in cfg.training and cfg.training.update_after == 'step' else 'episode' def _get_step_size(cfg, env, update_after): from utils import total_timesteps if 'lr_steps' not in cfg.mpc: return 10000 if update_after == 'step' else 100 ignore_exploration = 'reset_value' in cfg.exploration and cfg.exploration.reset_value if update_after == 'step': return total_timesteps(cfg, False, not ignore_exploration) // cfg.mpc.lr_steps return total_timesteps(cfg, False, not ignore_exploration) // env.unwrapped.max_steps // cfg.mpc.lr_steps def setup_planet(cfg, model_params, env, device): update_after = _update_after(cfg) lr_step_size = _get_step_size(cfg, env, update_after) world_model = DreamerModel.from_args(model_params, device) policy = DiscreteMPCPlanner.from_args(cfg.mpc, env, world_model, lr_step_size=lr_step_size) return PlaNet(policy, env, learning_starts=cfg.training.warmup_steps, gradient_steps=cfg.training.gradient_steps, resample_batch=cfg.training.resample_batch, verbose=1, tensorboard_log=os.path.join(os.getcwd(), 'tensorboard'), seed=cfg.environment.seed, device=device, train_freq=(cfg.training.update_every, update_after), exploration_min=cfg.random_action.exploration_min, exploration_prob=cfg.random_action.exploration_prob, exploration_decay_steps=cfg.random_action.exploration_decay_steps, replay_buffer_class=IntrospectiveChunkReplayBuffer if cfg.training.introspect_buffer else ChunkReplayBuffer, replay_buffer_kwargs={'chunks_can_cross_episodes': cfg.training.sample_across_episodes}) def setup_dreamer(cfg, model_params, env, device): update_after = _update_after(cfg) lr_step_size = _get_step_size(cfg, env, update_after) world_model = DreamerModel.from_args(model_params, device) policy = DreamerPolicy.from_config(cfg.dreamer, model_params, env, world_model, lr_step_size=lr_step_size) return Dreamer(policy, env, learning_starts=cfg.training.warmup_steps, gradient_steps=cfg.training.gradient_steps, resample_batch=cfg.training.resample_batch, verbose=1, tensorboard_log=os.path.join(os.getcwd(), 'tensorboard'), seed=cfg.environment.seed, device=device, train_freq=(1, update_after), exploration_min=cfg.random_action.exploration_min, exploration_prob=cfg.random_action.exploration_prob, exploration_decay_steps=cfg.random_action.exploration_decay_steps, replay_buffer_kwargs={'chunks_can_cross_episodes': cfg.training.sample_across_episodes}) def setup_a2c(cfg, model_params, env, device): return A2C('MlpPolicy', env, verbose=1, tensorboard_log=os.path.join(os.getcwd(), 'tensorboard'), seed=cfg.environment.seed, device=device)
GittiHab/mbrl-thesis-code
algos/setup.py
setup.py
py
3,496
python
en
code
1
github-code
1
[ { "api_name": "utils.total_timesteps", "line_number": 25, "usage_type": "call" }, { "api_name": "utils.total_timesteps", "line_number": 26, "usage_type": "call" }, { "api_name": "algos.PlaNet.world_model.DreamerModel.from_args", "line_number": 32, "usage_type": "call" }...
24154817598
#!/usr/bin/env python ''' Mizoo rename all your photos with a description of what is in them. It uses Microsoft Computer Vision API's to describe what it sees on the image and rename the file to that description. By naming your photos with a description of the content you will never have to dig up an old photo from your library ever again, just search for the content! Warning: Machines are not very good at captioning yet so don't trust this to much... Usage: > mizoo directory key ''' import argparse, os, sys, glob, json, requests, http, urllib uploads_api = "http://uploads.im/api" caption_api = "https://api.projectoxford.ai/vision/v1.0/describe?" def caption(url, key): ''' Return the caption for the imagen on the given url. A valid Microsoft API's key must be given. ----------------------------------------- url: the url of the image to analyze key: a valid Microsoft API's key return: caption for the image ''' headers = { 'Ocp-Apim-Subscription-Key': key, 'Content-Type': 'application/json', } data = json.dumps({"Url": url}, separators=(',',':')) # make request to the api and process the response try: conn = http.client.HTTPSConnection('api.projectoxford.ai') conn.request("POST", "/vision/v1.0/describe?", data, headers) response = conn.getresponse() data = json.loads(response.read().decode()) return(data['description']['captions'][0]["text"]) conn.close() except Exception as e: print(e) def upload(img): ''' Stream the given image to uploads.im api. ----------------------------------------- img: path of the image returns: the url of the uploaded image ''' # post the img to uploads.im request = requests.post(uploads_api, files={'img': open(img, 'rb')}) data = json.loads(request.text)["data"] # return the url of the uploaded image return(data["img_url"]) def rename(path, key): ''' Rename the photo-s in the given path using the Microsoft Computer Vision API's to describe them. ----------------------------------------- path: file/dir of the images to rename key: Microsoft's API key ''' # check if valid path for a file/dir if not os.path.exists(path): sys.exit('file or directory not found') extensions = (".jpg", ".png", ".gif", ".bpm") # check if file/dir is valid and list all the files to process if os.path.isfile(path): if path.lower().endswith(extensions): tocaption = [path] else: sys.exit('file is not a valid image') else: tocaption = [] for extension in extensions: tocaption.extend(glob.glob(path + "*" + extension)) print('Processing...') # print(tocaption) # for each file upload it to uploads.im and send it to caption for img in tocaption: # upload the img to uploads.im and get the url uploaded_url = upload(img) if uploaded_url: caption_text = caption(uploaded_url, key) # get file extension and rename file with the caption file_extension = os.path.splitext(img)[1] prev_path = os.path.dirname(img) os.rename(img, prev_path + "/" + caption_text + file_extension) print('Success') def main(): ''' Parse arguments and start the renaming. ----------------------------------------- path: path of the file or directory to rename key: Microsoft API's key ''' parser = argparse.ArgumentParser() parser.add_argument('path', help='path of the file or directory to use', action='store') parser.add_argument('key', help='Microsoft API\'s key', action='store') args = parser.parse_args() rename(args.path, args.key) if __name__ == '__main__': main()
albertoqa/mizoo
mizoo/mizoo.py
mizoo.py
py
3,866
python
en
code
1
github-code
1
[ { "api_name": "json.dumps", "line_number": 39, "usage_type": "call" }, { "api_name": "http.client.HTTPSConnection", "line_number": 43, "usage_type": "call" }, { "api_name": "http.client", "line_number": 43, "usage_type": "attribute" }, { "api_name": "json.loads", ...
39278591910
import cv2 import numpy as np import imutils PATH_TEMPLATE_MSLOGO = r"C:\Users\ASUS\Desktop\Working\PROJECT\Mybotic Product\mySejahtera Scan\images\template images\mslogo.png" PATH_TEMPLATE_TICKMARK = r"C:\Users\ASUS\Desktop\Working\PROJECT\Mybotic Product\mySejahtera Scan\images\template images\tickmark.png" SIMILARITY_TH = 0.85 IMAGE_SCANNED = 'imagescanned.png' DEBUG = True def ScanMysejahtera(PATH_TEMPLATE): template = cv2.imread(PATH_TEMPLATE,0) #template = cv2.Canny(template, 50, 200) (tH, tW) = template.shape[::] #cv2.imshow("Template", template) # load the image, convert it to grayscale, and initialize the bookkeeping variable to keep track of the matched region image = cv2.imread(IMAGE_SCANNED) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) found = None # loop over the scales of the image for scale in np.linspace(0.2, 1.0, 20)[::-1]: # resize the image according to the scale, and keep track of the ratio of the resizing resized = imutils.resize(gray, width = int(gray.shape[1] * scale)) r = gray.shape[1] / float(resized.shape[1]) #if the resized image is smaller than the template, then break from the loop if resized.shape[0] < tH or resized.shape[1] < tW: break #detect edges in the resized, grayscale image and apply template matching to find the template in the image result = cv2.matchTemplate(resized, template, cv2.TM_CCOEFF_NORMED) (_, maxVal, _, maxLoc) = cv2.minMaxLoc(result) #print(maxVal) if(maxVal >= SIMILARITY_TH): if(DEBUG is True): #if we have found a new maximum correlation value, then update the bookkeeping variable if found is None or maxVal > found[0]: found = (maxVal, maxLoc, r) #unpack the bookkeeping variable and compute the (x, y) coordinates of the bounding box based on the resized ratio (_, maxLoc, r) = found (startX, startY) = (int(maxLoc[0] * r), int(maxLoc[1] * r)) (endX, endY) = (int((maxLoc[0] + tW) * r), int((maxLoc[1] + tH) * r)) #draw a bounding box around the detected result and display the image cv2.rectangle(image, (startX, startY), (endX, endY), (0, 0, 255), 2) cv2.imshow("Image", image) cv2.waitKey() return True def CaptureMysejahteraScan(): cam = cv2.VideoCapture(0) retval, frame = cam.read() cv2.imwrite(IMAGE_SCANNED, frame) #cv2.imshow("IMAGE_SCANNED", frame) return retval retval = CaptureMysejahteraScan() if(retval is True): Tickmark_Scan = ScanMysejahtera(PATH_TEMPLATE_TICKMARK) MSLogo_Scan = ScanMysejahtera(PATH_TEMPLATE_MSLOGO) if(Tickmark_Scan is True and MSLogo_Scan is True): print("Tickmark:", Tickmark_Scan, "; MSLogo:", MSLogo_Scan) else: print("Tickmark:", Tickmark_Scan, "; MSLogo: ", MSLogo_Scan) else: print("Cannot read frame")
Awexander/mySejahtera-scanner
mysejahtera_scan_v1.py
mysejahtera_scan_v1.py
py
3,056
python
en
code
0
github-code
1
[ { "api_name": "cv2.imread", "line_number": 12, "usage_type": "call" }, { "api_name": "cv2.imread", "line_number": 18, "usage_type": "call" }, { "api_name": "cv2.cvtColor", "line_number": 19, "usage_type": "call" }, { "api_name": "cv2.COLOR_BGR2GRAY", "line_num...
38933917008
#!/usr/bin/env python # encoding: utf-8   """  @author: zzz_jq @contact: zhuangjq@stu.xmu.edu.cn @software: PyCharm  @file: data_process.py  @create: 2020/11/30 16:06  """ import re import os from pathlib import Path from tqdm import tqdm import numpy as np import pandas as pd from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer workload_dict = { "Spark ConnectedComponent Application": "CC", "DecisionTree classification Example": "DT", "Spark KMeans Example": "KM", "LinerRegressionApp Example": "LiR", "LogisticRegressionApp Example": "LoR", "Spark LabelPropagation Application": "LP", "MFApp Example": "MF", "Spark PCA Example": "PCA", "Spark PregelOperation Application": "PO", "Spark PageRank Application": "PR", "Spark StronglyConnectedComponent Application": "SCC", "Spark ShortestPath Application": "SP", "Spark SVDPlusPlus Application": "SVD", "SVM Classifier Example": "SVM", "Spark TriangleCount Application": "TC", "TeraSort": "TS" } def clean_code(s): if s is None or str(s).strip() is '': return [] r = '[’!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~\n。!,]+' line = re.sub(r, ' ', str(s)) words = line.split(' ') words = list(filter(None, words)) for word in words: word = word.strip() try: float(word) continue except: pass return words def code2tfidf(code_list): corpus = [] for code in code_list: words = clean_code(code) corpus.append(' '.join(words)) tfidf_vectorizer = TfidfVectorizer(max_features=64) tfidf_vectorizer.fit(corpus) # print(tfidf_vectorizer.vocabulary_) vec_list = [] for code in tqdm(code_list): words = clean_code(code) tfidf_vec = tfidf_vectorizer.transform([' '.join(words)]).toarray() vec_list.append(tfidf_vec) vec_arr = np.array(vec_list) return vec_arr def code2ngram(code_list): corpus = [] for code in code_list: words = clean_code(code) corpus.append(' '.join(words)) cnt_vectorizer = CountVectorizer(max_features=64, ngram_range=(2, 2)) cnt_vectorizer.fit(corpus) # print(cnt_vectorizer.vocabulary_) vec_list = [] for code in tqdm(code_list): words = clean_code(code) cnt_vec = cnt_vectorizer.transform([' '.join(words)]).toarray() vec_list.append(cnt_vec) vec_arr = np.array(vec_list) return vec_arr def read_stage_dataset(dataset_path, code_type): csv_data = pd.read_csv(dataset_path, sep=',', low_memory=False) df = pd.DataFrame(csv_data) # ****code -> TF-IDF if code_type == "tfidf": code_list = df['code'].tolist() vec_arr = code2tfidf(code_list) # ****code -> n-gram elif code_type == "ngram": code_list = df['code'].tolist() vec_arr = code2ngram(code_list) else: vec_arr = None Y = df['duration'] X_df = df.drop(['AppId', 'AppName', 'Duration', 'code', 'duration'], axis=1) # X_df = X_df.drop(['input', 'output', 'read', 'write'], axis=1) # drop metrics X = X_df.values[:, 0:] if vec_arr is not None: vec_arr = vec_arr.squeeze(axis=1) # code tf-idf X = np.concatenate((X, vec_arr), axis=1) return X, Y if __name__ == '__main__': code_type = "none" # tfidf ngram none X, Y = read_stage_dataset('csv_dataset/dataset_by_stage.csv', code_type) # np.save('npy_dataset_one_line/X_' + code_type + '.npy', X) # np.save('npy_dataset_one_line/Y.npy', Y) np.save('npy_dataset_no_code/X_13.npy', X) np.save('npy_dataset_no_code/Y_13.npy', Y)
TsinghuaDatabaseGroup/AI4DBCode
Spark-Tuning/prediction_ml/spark_tuning/by_stage/ml_baselines/data_process_one_line.py
data_process_one_line.py
py
3,683
python
en
code
56
github-code
1
[ { "api_name": "re.sub", "line_number": 45, "usage_type": "call" }, { "api_name": "sklearn.feature_extraction.text.TfidfVectorizer", "line_number": 63, "usage_type": "call" }, { "api_name": "tqdm.tqdm", "line_number": 67, "usage_type": "call" }, { "api_name": "nump...
22039745744
query_variables = { "wallet": "tz1NqA15BLrMFZNsGWBwrq8XkcXfGyCpapU1", "timestart": "2021-07-01", "timeend": "2022-06-30" } buys_start = "2019-01-01" currency = "AUD" import json import os import datetime import csv import requests # Prepare conversion rates # Using the RBA exchange rates spreadsheet cleaned up # and exported in CSV form usd_conv = {} with open('RBAex-2018-2022.csv', mode='r') as csv_file: csv_reader = csv.reader(csv_file) for row in csv_reader: if (len(row) > 1): usd_conv[ row[0] ] = row[1] # Returns a USD to AUD conversion rate # based on the RBA data def audusd_datetime(dt): # Currency conversion to AUD aud_rate = None # backtrack to find the most recent rate # if it doesn't exist for this day for num_days in [0, -1, -2, -3, -4, -5]: matchdt = dt + datetime.timedelta(days=num_days) matchdate = matchdt.strftime('%d-%b-%Y') if matchdate not in usd_conv: continue else: aud_rate = float(usd_conv[matchdate]) break if aud_rate is None: matchdt = dt + datetime.timedelta(days=num_days) matchdate = matchdt.strftime('%d-%b-%Y') raise ValueError("Can't find AUD conversion for {}".format(matchdate)) return aud_rate # ------- Teztok queries def run_query(query, variables): response = requests.post( "https://api.teztok.com/v1/graphql", json={'query': query, 'variables': variables}, ) if response.status_code == 200: return response.json() else: raise Exception(f'Query failed with a {response.status_code}: {response.json()}') # Many thanks for Marius Watz for his example queries which kicked all this off # https://twitter.com/mariuswatz/status/1666715664566874113?s=20 def query_royalties(): query = ''' query royalties($wallet: String!, $timestart: timestamptz!, $timeend: timestamptz!) { events(where: {implements: {_eq: "SALE"}, timestamp: { _gte: $timestart, _lt: $timeend}, seller_address: {_neq: $wallet}, artist_address: {_eq: $wallet}}, order_by: {timestamp: asc}) { buyer_profile { alias } buyer_address token { name token_id royalty_receivers { receiver_address royalties } } timestamp seller_address seller_profile { alias } price price_in_usd price_in_eur } }''' return run_query(query, query_variables) def query_sales(): query = ''' query Sales ($wallet: String!, $timestart: timestamptz!, $timeend: timestamptz!) { events(where: {implements: {_eq: "SALE"}, seller_address: {_eq: $wallet}, timestamp: {_gte: $timestart, _lt: $timeend}}, order_by: {timestamp: asc}) { timestamp price seller_address seller_profile { alias } price_in_usd price_in_eur token { name fa2_address token_id artist_profile { alias } } } }''' return run_query(query, query_variables) def query_buys(): query = ''' query Buys ($wallet: String!, $timestart: timestamptz!, $timeend: timestamptz!) { events(where: {implements: {_eq: "SALE"}, buyer_address: {_eq: $wallet}, timestamp: {_gte: $timestart, _lt: $timeend}}, order_by: {timestamp: asc}) { timestamp price seller_address seller_profile { alias } price_in_usd price_in_eur token { name fa2_address token_id artist_profile { alias } } } }''' buys_variables = query_variables buys_variables['timestart'] = buys_start; return run_query(query, buys_variables) # Prepare transaction data royalties_data = query_royalties()['data']['events'] sales_data = query_sales()['data']['events'] buys_data = query_buys()['data']['events'] # ------- CSV data ouput def write_csv(filename, rownames, rows): with open(filename, "w") as csv_file: csv_writer = csv.writer(csv_file, delimiter=',') csv_writer.writerow(rownames) for r in rows: csv_writer.writerow(r) # ------- Collating the data primary_rows = [] secondary_rows = [] royalty_rows = [] # Go over all the wallet's sales for sale in sales_data: # Find the artist alias if there is one # artist = "" # if 'artist_profile' in sale['token'].keys() and sale['token']['artist_profile'] is not None: # artist = sale['token']['artist_profile']['alias'] # Check if this sale is a secondary sale by scanning over all the wallet's purchased tokens # and grabbing any where the contract address and id match. token_fa2 = sale['token']['fa2_address'] token_id = sale['token']['token_id'] initial_purchases = [buy for buy in buys_data if buy['token']['fa2_address'] == token_fa2 and buy['token']['token_id'] == token_id ] # Find the price at the date that it was sold dt = datetime.datetime.strptime(sale['timestamp'], '%Y-%m-%dT%H:%M:%S+00:00') aud_rate = audusd_datetime(dt) pricetz = float(sale['price']) / 1000000.0 priceusd = float(sale['price_in_usd']) / 1000000.0 priceeur = float(sale['price_in_eur']) / 1000000.0 priceaud = priceusd / aud_rate # data to write to the csv primary_row = [ sale['token']['name'], # name dt.strftime('%d-%m-%Y'), # date "${:.2f}".format(priceaud), # sale price in AUD "${:.2f}".format(priceusd), # sale price in USD "€{:.2f}".format(priceeur), # sale price in EUR "{:.2f}".format(pricetz), # sale price in XTZ ] # If this token was a primary sale we can add this data # and skip over capital gains calculation if len(initial_purchases) == 0: primary_rows.append(primary_row) continue # Calculate capital gains from this sale # Just grab the first initial sale in our list of previous purchases # Note! This will probably be incorrect if you've bought/sold two editions of a single token # I didnt need this in my case buy = initial_purchases[0] purchase_dt = datetime.datetime.strptime(buy['timestamp'], '%Y-%m-%dT%H:%M:%S+00:00') aud_rate = audusd_datetime(purchase_dt) # Find the price at the date that it was sold purchase_pricetz = float(buy['price']) / 1000000.0 purchase_priceusd = float(buy['price_in_usd']) / 1000000.0 purchase_priceeur = float(buy['price_in_eur']) / 1000000.0 purchase_priceaud = purchase_priceusd / aud_rate gain_aud = priceaud - purchase_priceaud # Skip transaction if purchase and sale are zero... # don't care about this for tax purposes if pricetz == 0 and purchase_pricetz == 0: continue # purchase data to write to the csv secondary_row = primary_row + [ purchase_dt.strftime('%d-%m-%Y'), # date "${:.2f}".format(purchase_priceaud), # purchase price in AUD "${:.2f}".format(purchase_priceusd), # purchase price in USD "€{:.2f}".format(purchase_priceeur), # purchase price in EUR "{:.2f}".format(purchase_pricetz), # purchase price in XTZ "${:.2f}".format(gain_aud), # gain in AUD ] secondary_rows.append(secondary_row) # Go over all the wallet's potential royalty events # Note: this may not cover more complex royalties such as collabs for event in royalties_data: dt = datetime.datetime.strptime(event['timestamp'], '%Y-%m-%dT%H:%M:%S+00:00') aud_rate = audusd_datetime(dt) pricetz = float(event['price']) / 1000000.0 priceusd = float(event['price_in_usd']) / 1000000.0 priceeur = float(event['price_in_eur']) / 1000000.0 priceaud = priceusd / aud_rate first_receiver = event['token']['royalty_receivers'][0] royalty_rate = float(first_receiver['royalties']) / 1000000.0 royalty_aud = priceaud * royalty_rate row = [ event['token']['name'], dt.strftime('%d-%m-%Y'), # date "${:.2f}".format(priceaud), # sale price in AUD "${:.2f}".format(priceusd), # sale price in USD "€{:.2f}".format(priceeur), # sale price in EUR "{:.2f}".format(pricetz), # sale price in XTZ royalty_rate*100, # multiplier of sale price "${:.2f}".format(royalty_aud) ] royalty_rows.append(row) # Write out the CSVs primary_names = ['Title', 'Date', 'Sale Price {}'.format(currency), 'Sale Price USD', 'Sale Price EUR', 'Sale Price XTZ'] write_csv("primary-sales.csv", primary_names, primary_rows) secondary_names = ['Title', 'Date', 'Sale Price {}'.format(currency), 'Sale Price USD', 'Sale Price EUR', 'Sale Price XTZ', 'Purchase Date', 'Purchase Price {}'.format(currency), 'Purchase Price USD', 'Purchase Price EUR', 'Purchase Price XTZ', 'Gain {}'.format(currency)] write_csv("secondary-sales.csv", secondary_names, secondary_rows) royalty_names = ['Title', 'Date', 'Sale Price {}'.format(currency), 'Sale Price USD', 'Sale Price EUR', 'Sale Price XTZ', 'Royalty %', 'Royalty {}'.format(currency)] write_csv("royalties.csv", royalty_names, royalty_rows)
mattebb/tezos-nft-tax-report
report.py
report.py
py
8,757
python
en
code
2
github-code
1
[ { "api_name": "csv.reader", "line_number": 22, "usage_type": "call" }, { "api_name": "datetime.timedelta", "line_number": 36, "usage_type": "call" }, { "api_name": "datetime.timedelta", "line_number": 45, "usage_type": "call" }, { "api_name": "requests.post", ...
7409145188
import pandas as pd import numpy as np import loaders as ld import analytics as an def cooc(opens,closes,costs=0.0001,cutoff=1,strength=10000,prec=2,ret=0,sw=0,inv=0): k = opens.shape[1]-opens.isnull().sum(axis=1) CO_ret = np.log(opens/closes.shift(1)) OC_ret = closes/opens-1 #OO_ret = np.log(opens/opens.shift(1)) OC_diff = closes-opens if inv==1: CO_ret.iloc[:,0] = -CO_ret.iloc[:,0] OC_ret.iloc[:,0] = -OC_ret.iloc[:,0] #CO_ret_fut = np.column_stack([futures.ix[1:,0].values/futures.ix[:-1,1].values,futures.ix[1:,2].values/futures.ix[:-1,3].values,futures.ix[1:,4].values/futures.ix[:-1,5].values,futures.ix[1:,6].values/futures.ix[:-1,7].values,futures.ix[1:,8].values/futures.ix[:-1,9].values,]) #does not use index #CO_ret_fut = np.vstack([np.NaN*np.arange(0,5),CO_ret_fut]) #CO_ret_fut = pd.DataFrame(CO_ret_fut, index=futures.index) #CO_ret_fut = pd.concat([futures.ix[:,0]/futures.ix[:,1].shift(1),futures.ix[:,2]/futures.ix[:,3].shift(1),futures.ix[:,4]/futures.ix[:,5].shift(1),futures.ix[:,6]/futures.ix[:,7].shift(1),futures.ix[:,8]/futures.ix[:,9].shift(1)],axis=1)-1 #OC_ret_fut2 = futuresc.shift(1)/futureso.shift(1)-1 #weightOC_fut = 10000*OC_ret_fut2.sub(OC_ret_fut2.mean(axis=1), axis=0).div(-k_fut, axis=0) #portOCCO_fut = CO_ret_fut*weightOC_fut - abs(weightOC_fut.diff(1)).div(1/fut_cost,axis=1) #OO_ret_fut = np.log(futureso/futureso.shift(1)) #weightOO_fut = np.round(300*OO_ret_fut.sub(OO_ret_fut.mean(axis=1), axis=0).div(-k_fut, axis=0),2) #portOOOC_fut = OC_ret_fut*weightOO_fut - abs(weightOO_fut.diff(1)).div(1/fut_cost,axis=1) if sw==0: switch = 1 else: switch = sw*(np.sign(OC_ret.mean(axis=1))+sw)/2 weightCO = np.minimum(cutoff,np.maximum(-cutoff,np.round(strength*CO_ret.sub(CO_ret.mean(axis=1), axis=0).div(-k, axis=0),prec))) #portCOOC = OC_ret*weightCO - abs(weightCO).div(1/costs,axis=1) rel_weights = np.round((1-opens.div(opens.sum(axis=1),axis=0))*weightCO,2) portCOOC = OC_ret*weightCO - (abs(weightCO)/opens).div(1/costs,axis=1) portCOOConDIFF = (OC_diff*rel_weights) - abs(rel_weights)*costs if ret==0: out = an.SR(portCOOConDIFF.mean(axis=1)) else: if ret==1: out = switch*portCOOConDIFF.sum(axis=1) else: if ret==2: out = portCOOC.mean(axis=1) #weightCO else: out = weightCO #weightCO return out def rcooc(opens,closes,highs,lows,costs=0.0001,cutoff=1,strength=10000,prec=2,ret=0,sw=0,inv=0): k = opens.shape[1]-opens.isnull().sum(axis=1) CO_ret = np.log(opens/closes.shift(1)) OC_ret = closes/opens-1 #OO_ret = np.log(opens/opens.shift(1)) #OC_diff = closes-opens if inv==1: CO_ret.iloc[:,0] = -CO_ret.iloc[:,0] OC_ret.iloc[:,0] = -OC_ret.iloc[:,0] if sw==0: switch = 1 else: switch = sw*(np.sign(OC_ret.mean(axis=1))+sw)/2 weightCO = np.minimum(cutoff,np.maximum(-cutoff,np.round(strength*CO_ret.sub(CO_ret.mean(axis=1), axis=0).div(-k, axis=0),prec))) #portCOOC = OC_ret*weightCO - abs(weightCO).div(1/costs,axis=1) rel_weights = np.round((1-opens.div(opens.sum(axis=1),axis=0))*weightCO,2) #portCOOC = OC_ret*weightCO - (abs(weightCO)/opens).div(1/costs,axis=1) if ret<2: lowsy = (lows-opens) #.clip(upper=0) highsy = (highs-opens) #.clip(upper=0) if ret==2: lowsy = (lows/opens-1) #.clip(upper=0) highsy = (highs/opens-1) #.clip(upper=0) long0short1 = pd.concat([lowsy.ix[:,0],highsy.ix[:,1]],axis=1) # lowhigh long1short0 = pd.concat([highsy.ix[:,0],lowsy.ix[:,1]],axis=1) # highlow #portCOOConDIFF = (OC_diff*rel_weights) - abs(rel_weights)*costs loses0 = pd.Series(np.where(rel_weights.ix[:,0] <= 0, long1short0.ix[:,0], long0short1.ix[:,0]),index=long1short0.index) loses1 = pd.Series(np.where(rel_weights.ix[:,1] <= 0, long0short1.ix[:,1], long1short0.ix[:,1]),index=long1short0.index) oldnames = opens.columns loses = pd.concat([loses0,loses1],axis=1) loses.columns = oldnames if ret<2: loses = loses*rel_weights - abs(rel_weights)*costs if ret==2: loses = loses*weightCO - (abs(weightCO)/opens).div(1/costs,axis=1) if ret==0: out = loses else: if ret==1: out = switch*loses.sum(axis=1) else: if ret==2: out = loses.mean(axis=1) #weightCO else: out = weightCO #weightCO return out def dailycc(x,costs=0.0001,cutoff=1,strength=10000,prec=2,ret=0,sw=0): #k = x.shape[1]-x.isnull().sum(axis=1) k = x.shape[1] closes = pd.DataFrame(x, index=pd.to_datetime(x.index)) closes = pd.concat([closes,pd.Series(closes.index.dayofweek, index=closes.index)],axis=1) columns = closes.columns.tolist() columns = columns[0:x.shape[1]] columns.append('dw') closes.columns = columns #y = closes.loc[(closes['dw'] == 0) | (closes['dw'] == 3)] opens = x.loc[(closes['dw'] == 0)] opens.index = opens.index.shift(3,'D') closes = x.loc[(closes['dw'] == 3)] #opens = x.loc[(closes['dw'] == 3)] #opens.index = opens.index.shift(4,'D') #closes = x.loc[(closes['dw'] == 0)] y = pd.concat([opens,closes],axis=1) y.dropna(inplace=True) opens = y.ix[:,0:2] closes = y.ix[:,2:4] CO_ret = np.log(opens/closes.shift(1)) OC_ret = closes/opens-1 #OO_ret = np.log(opens/opens.shift(1)) if sw==0: switch = 1 else: switch = sw*(np.sign(OC_ret.mean(axis=1))+sw)/2 weightCO = np.minimum(cutoff,np.maximum(-cutoff,np.round(strength*CO_ret.sub(CO_ret.mean(axis=1), axis=0).div(-k, axis=0),prec))) portCOOC = OC_ret*weightCO - abs(weightCO).div(1/costs,axis=1) if ret==0: out = an.SR(portCOOC.mean(axis=1),b=52) else: if ret==1: out = switch*portCOOC.mean(axis=1) else: out = weightCO return out
mlabedzki/Fortuna
strategies.py
strategies.py
py
6,008
python
en
code
0
github-code
1
[ { "api_name": "numpy.log", "line_number": 8, "usage_type": "call" }, { "api_name": "numpy.sign", "line_number": 28, "usage_type": "call" }, { "api_name": "numpy.minimum", "line_number": 29, "usage_type": "call" }, { "api_name": "numpy.maximum", "line_number": ...
19586982312
import os, pathlib from pydo import * this_dir = pathlib.Path(__file__).parent try: from . import config except ImportError: log.error('Error: Project is not configured.') exit(-1) try: jobs = int(os.environ['PYDOJOBS'], 10) except Exception: import multiprocessing jobs = multiprocessing.cpu_count() log.warning(f'Setting jobs to {jobs}.') from . import kernel, firmware, raspbian, sysroot, packages kernel_boot_tarballs = [k.boot for k in kernel.kernels] boot = this_dir / 'boot' dnsmasq_conf_in = this_dir / 'dnsmasq.conf.in' dnsmasq_conf = this_dir / 'dnsmasq.conf' @command(produces=[dnsmasq_conf], consumes=[dnsmasq_conf_in]) def build_dnsmasq_conf(): subst(dnsmasq_conf_in, dnsmasq_conf, {'@TFTP_ROOT@': str(boot)}) @command(produces=[boot], consumes=[firmware.target, raspbian.initrd, *kernel_boot_tarballs, dnsmasq_conf]) def build(): call([ f'mkdir -p {boot}', f'rm -rf --one-file-system {boot}/*', f'cp {raspbian.initrd} {boot}', f'tar -xf {firmware.target} -C {boot}', *list(f'tar -xf {kb} -C {boot}' for kb in kernel_boot_tarballs), #f'cd {boot} && zip -qr {boot} *', f'touch {boot}', ], shell=True) @command() def clean(): sysroot.clean() firmware.clean() kernel.clean() raspbian.clean() packages.clean()
ali1234/rpi-ramdisk
__init__.py
__init__.py
py
1,348
python
en
code
79
github-code
1
[ { "api_name": "pathlib.Path", "line_number": 5, "usage_type": "call" }, { "api_name": "os.environ", "line_number": 14, "usage_type": "attribute" }, { "api_name": "multiprocessing.cpu_count", "line_number": 17, "usage_type": "call" } ]
17166477183
# -*- coding: utf-8 -*- """ Created on Thu Jun 3 15:50:28 2021 @author: mozhenling """ import copy import numpy as np import scipy.io as scio import matplotlib.pyplot as plt from dbtpy.filters.afilter import filter_fun from dbtpy.findexes.afindex import findex_fun from dbtpy.findexes.sigto import sig_real_to_env #-- import tools from dbtpy.tools.file_tools import get_time, file_type ############################################################################### #-------------- the objective function for rotating machinery fault diagnosis #-------------- It is a maximization problem !! class Diagnosis(): def __init__(self, sig, fs=1, filter_kwargs={}, findex_kwargs={}, diag_kwargs={}, findex_name=None,filter_name=None): """ fault diagnosis related objective function -sig: the signal -fs: the sampling frequency -filter_kwargs: keyword arguments related to the filter -findex_kwargs: keyword arguments related to the fault index -diag_kwargs: keyword arguments related to this diagnosis class """ self.sig = sig self.fs = fs self.filter_kwargs = filter_kwargs self.findex_kwargs = findex_kwargs self.diag_kwargs = diag_kwargs # you may pass other key word arguments here #-- to name the fault index that will be shown to us if findex_name is None: if findex_kwargs['sigD'] is not None: self.findex_name = findex_kwargs['findexBase'] + '_' + findex_kwargs['sigD'] else: self.findex_name = findex_kwargs['findexBase'] else: self.findex_name = findex_name #-- to name the filter that will be shown to us if filter_name is None: self.filter_name = filter_kwargs['filterBase'] else: self.filter_name = filter_name self.findex_opt = [] # record the optimal fault index self.sig_opt = [] # record the optimal signal self.sig_opt_mfb = [] # for meyer self.full_opt_info = [] # record the optimal variabes and the coressponding obj. values self.full_try_info = [] # record the tried variabes and the coressponding obj. values def pso_vmd(self, variables): """ input: variables: alpha = variables[0], K = round(variables[1]) ideas: -the fitness is the entropy and the kurtosis -minimize entropy to determine the decomposition number k and compactness factor alpha -maximize kurtosis to select a model after the decomposition ref.: Wang, Xian-Bo, Zhi-Xin Yang, and Xiao-An Yan. "Novel particle swarm optimization-based variational mode decomposition method for the fault diagnosis of complex rotating machinery." IEEE/ASME Transactions on Mechatronics 23.1 (2017): 68-79. """ alpha = variables[0] K = round(variables[1]) mode, _, _ = filter_fun(self.sig, alpha=alpha, K=K, **self.filter_kwargs) # the envelope moduel, which will be used to calcualte envelope energy entropy mode_env_list = [sig_real_to_env(mode[i,:]) for i in range(K)] # obtain the envelope energy entropy findex = findex_fun(mode_env_list, **self.findex_kwargs) #-- get the optimal sig of each call mode_kurt_list = [findex_fun(mode[i,:], 'kurt', 'se') for i in range(K)] mode_kurt_max = max(mode_kurt_list) ind_max = mode_kurt_list.index(mode_kurt_max) # record the optimal index if self.findex_opt==[]: self.findex_opt = [[findex, mode_kurt_max]] self.full_opt_info.append({'alpha': alpha, 'K': K, 'entropy_min':-1*findex, 'kurt_max':mode_kurt_max}) elif findex > self.findex_opt[-1][0]: self.findex_opt.append([findex, mode_kurt_max]) self.sig_opt = mode[ind_max,:] self.full_opt_info.append({'alpha': alpha, 'K': K, 'entropy_min':-1*findex, 'kurt_max':mode_kurt_max}) else: self.findex_opt.append(self.findex_opt[-1]) self.full_opt_info.append(self.full_opt_info[-1]) self.full_try_info.append({'alpha': alpha, 'K': K, 'entropy_min':-1*findex, 'kurt_max':mode_kurt_max}) return findex def ovmd_alike(self, variables): """ Optimized variantional mode decomposition and its vairants by maximizing the fualt index input: variables: alpha = variables[0], K = round(variables[1]) outputs: -the largest fault index """ alpha = variables[0] K = round(variables[1]) mode, _, _ = filter_fun(self.sig, alpha=alpha, K=K, **self.filter_kwargs) # the higher the fault index, the more likely a fault has happened findex_list = [ findex_fun( mode[i,:], **self.findex_kwargs ) for i in range(K) ] findex_max = max( findex_list ) ind_max = findex_list.index(findex_max) # save the latest fualt index # record the optimal index if self.findex_opt==[]: self.findex_opt = [findex_max] self.sig_opt = mode[ind_max,:] self.full_opt_info.append({'alpha': alpha, 'K': K, self.findex_name:findex_max}) elif findex_max > self.findex_opt[-1]: self.findex_opt.append(findex_max) self.sig_opt = mode[ind_max,:] self.full_opt_info.append({'alpha': alpha, 'K': K, self.findex_name:findex_max}) else: self.findex_opt.append(self.findex_opt[-1]) self.full_opt_info.append(self.full_opt_info[-1]) self.full_try_info.append({'alpha': alpha, 'K': K, self.findex_name:findex_max}) return findex_max def meyer3_others(self, b): """ The three meyer wavelet filters based objective funtion for fault diagnosis using other optimization algorithms such as those from mealpy inputs: -b # the boundaries for the filter bank -minB # the minimum band width requirements (via diag_kwargs['minB']) outputs: -the largest fault index """ #-- it is convinient if other optimization algorithm only allows one argument minB =self.diag_kwargs['minB'] filter_num = 3 # check the value of bounds regarding the bandwidth constraint if abs(b[1]-b[0]) > minB: b[0], b[1] = min(b), max(b) else: b[0] = np.mean(b) b[1] = b[0] + minB #-- convert to sequence index freq2seq = len(self.sig) / self.fs b = np.array(b) * freq2seq mode, mfb ,boundaries = filter_fun(self.sig, boundaries=b, **self.filter_kwargs) # the higher the fault index, the more likely a fault has happened #--- calcualte findexes of three modes findex_list= [ findex_fun( mode[:,i], **self.findex_kwargs ) for i in range(filter_num) ] findex_max = max( findex_list ) ind_max = findex_list.index(findex_max) # record the optimal index if self.findex_opt == []: # if it is empty self.findex_opt = [findex_max] self.sig_opt = mode[:,ind_max] self.full_opt_info.append({'b1': b[0], 'b2': b[1], self.findex_name:findex_max}) # findex elif findex_max > self.findex_opt[-1]: self.findex_opt.append(findex_max) self.sig_opt = mode[:,ind_max] self.full_opt_info.append({'b1': b[0], 'b2': b[1], self.findex_name:findex_max}) else: self.findex_opt.append(self.findex_opt[-1]) self.full_opt_info.append(self.full_opt_info[-1]) self.full_try_info.append({'b1': b[0], 'b2': b[1], self.findex_name:findex_max}) return findex_max def meyer3_dbt(self, b): """ The three meyer wavelet filters based objective funtion for fault diagnosis using dbtree optimization algorithms inputs: -b # the boundaries for the filter bank -minB # the minimum band width requirements (via obj_kwargs['minB']) outputs: -the largest fault index """ #-- it is convinient if other optimization algorithm only allows one argument minB =self.diag_kwargs['minB'] filter_num = 3 # check the value of bounds regarding the bandwidth constraint if abs(b[1]-b[0]) > minB: b[0], b[1] = min(b), max(b) else: b[0] = np.mean(b) b[1] = b[0] + minB #-- convert to sequence index freq2seq = len(self.sig) / self.fs # np.pi / (self.fs / 2) b = np.array(b) * freq2seq mode, mfb ,boundaries = filter_fun(self.sig, boundaries=b, **self.filter_kwargs) # the higher the fault index, the more likely a fault has happened #--- calcualte findexes of three modes findex_list= [ findex_fun( mode[:,i], **self.findex_kwargs ) for i in range(filter_num) ] findex_max = max( findex_list ) ind_max = findex_list.index(findex_max) # record the optimal index if self.findex_opt == []: # if it is empty self.findex_opt = findex_max self.sig_opt = mode[:,ind_max] self.sig_opt_mfb = mfb elif findex_max > self.findex_opt: self.findex_opt = findex_max self.sig_opt = mode[:,ind_max] self.sig_opt_mfb = mfb else: pass return findex_max def to_2pi(self, freq): """ map a frequency in [0, fs/2] to the corresponding frequency in [0, 2pi] where 2pi = fs, pi = fs / 2 """ return freq * 2 * np.pi / self.fs def to_fs(self, omega): """ map a frequency in [0, pi] to the corresponding frequency in [0, fs/2] where 2pi = fs, pi = fs / 2 """ return omega * self.fs / (2 * np.pi) def show_time(self, sig_real = None, title= '', xlabel = 'Time (s)', ylabel = 'Normalized amplitude', figsize = (3.5, 1.8), dpi = 144, fig_save_path= None, fig_format = 'png', fontsize = 8, linewidth = 1, non_text = False): ''' show time domain waveform only ''' data = sig_real if sig_real is not None else self.sig_opt fs = self.fs plt.figure(figsize=figsize, dpi=dpi) plt.rc('font', size = fontsize) data = data / max(abs(data)) Ns = len(data) n = np.arange(Ns) # start = 0, stop = Ns -1, step = 1 t = n / fs # time index plt.plot(t, data, color = 'xkcd:dark sky blue', linewidth = linewidth) if non_text: ax = plt.gca() ax.axes.xaxis.set_visible(False) ax.axes.yaxis.set_visible(False) else: plt.xlabel(xlabel, fontsize = fontsize + 0.5) plt.ylabel(ylabel, fontsize = fontsize + 0.5) plt.title(title, fontsize = fontsize + 1) plt.tight_layout() if fig_save_path is not None: plt.savefig(fig_save_path, format=fig_format) plt.show() def show_freq(self, sig_real=None, fs = None, title='', xlabel = 'Frequency (Hz)', ylabel = 'Normalized amplitude', f_target=None, figsize = (3.5, 1.8), dpi = 144, fig_save_path= None, fig_format = 'png', fontsize = 8, linewidth = 1, non_text = False): """ show frequency power spectrum only flag = half, 0 to fs // 2 flag = full, -fs//2 to fs //2 """ data = sig_real if sig_real is not None else self.sig_opt fs = fs if fs is not None else self.fs plt.figure(figsize=figsize, dpi=dpi) plt.rc('font', size = fontsize) Ns = len(data) n = np.arange(Ns) # start = 0, stop = Ns -1, step = 1 fn = n * fs / Ns # frequency index if np.iscomplexobj(data): Amp_fn = abs(data) else: Amp_fn = 2 * abs(np.fft.fft(data)) /Ns Amp_fn = Amp_fn / max(Amp_fn) plt.plot(fn[:len(fn)//2], Amp_fn[:len(fn)//2], color = 'xkcd:dark sky blue', linewidth = linewidth) if non_text: ax = plt.gca() ax.axes.xaxis.set_visible(False) ax.axes.yaxis.set_visible(False) else: plt.xlabel(xlabel, fontsize = fontsize + 0.5) plt.ylabel(ylabel, fontsize = fontsize + 0.5) plt.title(title, fontsize = fontsize + 1) plt.tight_layout() if fig_save_path is not None: plt.savefig(fig_save_path, format=fig_format) plt.show() def show_sses(self, sig_real = None, f_target=None, SSES=True, title='', xlabel = 'Frequency (Hz)', ylabel = 'Normalized amplitude', figsize = (3.5, 1.8), dpi = 144, fig_save_path= None, fig_format = 'png', fontsize = 8, linewidth = 1, non_text = False ): """ show the square of the squared envelope spectrum """ sig = sig_real if sig_real is not None else self.sig_opt ses = sig_real_to_ses(sig) #-- normalized by the maximum amplitude sesMax = max(ses) ses = ses / sesMax (sses, label)= (ses**2, 'SES') if SSES else (ses, 'SES') # you may use sses instead # plt.figure() plt.figure(figsize=figsize, dpi=dpi) plt.rc('font', size = fontsize) if f_target is not None: harN = 5 harColor = ['r', 'r', 'r', 'm', 'm'] harLine = ['--', '-.', ':', '--', '-.'] point_num = 10 targetHarAmp = [np.linspace(0, 1.1, point_num ) for i in range(harN) ] targetHar = [[f_target + i*f_target for j in range(point_num)] for i in range(harN) ] for i, (tar, tarAmp) in enumerate(zip(targetHar, targetHarAmp)): plt.plot(tar, tarAmp, harColor[i] + harLine[i], label ='Har'+str(i+1), linewidth=linewidth + 0.3) # raise ValueError plt.ylim([0, 1.1]) plt.xlim([0, 7* f_target]) # (harN + 1) Ns = len(sses) n = np.arange(Ns) # start = 0, stop = Ns -1, step = 1 fn = n * self.fs / Ns # frequency index, Fs / Ns = frequency resoluton plt.plot(fn[:Ns//2], sses[:Ns//2], 'b', label = label , linewidth=linewidth) if non_text: ax = plt.gca() ax.axes.xaxis.set_visible(False) ax.axes.yaxis.set_visible(False) else: plt.xlabel(xlabel, fontsize = fontsize + 0.5) plt.ylabel(ylabel, fontsize = fontsize + 0.5) plt.title(title, fontsize = fontsize + 1) plt.legend(fontsize = fontsize - 1) plt.tight_layout() if fig_save_path is not None: plt.savefig(fig_save_path, format=fig_format) plt.show() def plot_ffts(self, sig, sig_opt, opt_dict, mfb=None, boundaries=None, figsize = (3.5, 1.8), dpi = 144, fig_save_path= None, fig_format = 'png', fontsize = 8, linewidth=1, non_text = False ): """ plot the fft of the original signal and the filtered optimal signal inputs: -sig # the original -sig_opt # the optimal sigal -vars_opt # the optimal decision variables -ffindex # name of the fault index -findex_opt # value of the optimal fault index """ sig_fft_amp = abs(np.fft.fft(sig)) #-- normalized by the maximum amplitude amp_max = max(sig_fft_amp) sig_fft_amp = sig_fft_amp / amp_max sig_opt_fft_amp = abs(np.fft.fft(sig_opt)) / amp_max Ns = len(sig_fft_amp) n = np.arange(Ns) # start = 0, stop = Ns -1, step = 1 fn = n * self.fs / Ns # frequency index, Fs / Ns = frequency resoluton # plt.figure() plt.figure(figsize=figsize, dpi=dpi) plt.plot(fn[:Ns//2], sig_fft_amp[:Ns//2], ':', color = 'xkcd:dark sky blue', label = 'Original' , linewidth=linewidth) plt.plot(fn[:Ns//2], sig_opt_fft_amp[:Ns//2], 'b', label = 'Optimal' , linewidth=linewidth) #-- future use if mfb is not None: mode_len, mode_num = mfb.shape style = ['--', '-.', ':'] for i in range(mode_num): #magenta, light salmon plt.plot(fn[:Ns//2],mfb[:Ns:2, i], style[i], color = 'xkcd:light purple', label = 'filter' + str(i+1), linewidth=linewidth ) if boundaries is not None: style_b = ['r--', 'r-.'] for i in range(len(boundaries)): b_x = boundaries[i] * np.ones(10) b_y = np.linspace(0, 1, 10) plt.plot(b_x, b_y, style_b[i], label = 'b' + str(i+1), linewidth=linewidth) plt.rc('font', size = fontsize) plt.xlim([0, fn[Ns//2]]) if non_text: ax = plt.gca() ax.axes.xaxis.set_visible(False) ax.axes.yaxis.set_visible(False) else: plt.xlabel('Frequency (Hz)', fontsize = fontsize + 0.5) plt.ylabel('Normalized amplitude', fontsize = fontsize + 0.5) plt.title(str(opt_dict), fontsize = fontsize + 0.5) plt.legend(fontsize = fontsize - 2) plt.tight_layout() if fig_save_path is not None: plt.savefig(fig_save_path, format=fig_format) plt.show() if __name__ == '__main__': a = np.zeros((1000))
mozhenling/dbtree
dbtpy/funs/fun_diag.py
fun_diag.py
py
18,106
python
en
code
4
github-code
1
[ { "api_name": "dbtpy.filters.afilter.filter_fun", "line_number": 75, "usage_type": "call" }, { "api_name": "dbtpy.findexes.sigto.sig_real_to_env", "line_number": 77, "usage_type": "call" }, { "api_name": "dbtpy.findexes.afindex.findex_fun", "line_number": 79, "usage_type"...
41495665790
import torch import torch.nn as nn class MASRModel(nn.Module): def __init__(self, **config): super().__init__() self.config = config @classmethod def load(cls, path): package = torch.load(path) state_dict = package["state_dict"] config = package["config"] m = cls(**config) m.load_state_dict(state_dict) return m def to_train(self): from .trainable import TrainableModel self.__class__.__bases__ = (TrainableModel,) return self def predict(self, *args): raise NotImplementedError() # -> texts: list, len(list) = B def _default_decode(self, yp, yp_lens): idxs = yp.argmax(1) texts = [] for idx, out_len in zip(idxs, yp_lens): idx = idx[:out_len] text = "" last = None for i in idx: if i.item() not in (last, self.blank): text += self.vocabulary[i.item()] last = i texts.append(text) return texts def decode(self, *outputs): # texts -> list of size B return self._default_decode(*outputs)
nobody132/masr
models/base.py
base.py
py
1,176
python
en
code
1,754
github-code
1
[ { "api_name": "torch.nn.Module", "line_number": 5, "usage_type": "attribute" }, { "api_name": "torch.nn", "line_number": 5, "usage_type": "name" }, { "api_name": "torch.load", "line_number": 12, "usage_type": "call" }, { "api_name": "trainable.TrainableModel", ...
9293506322
#this model aim to reduce number of rounds but will continue to use random method import random from datetime import datetime start_time = datetime.now() final_state = [1,2,3,4,5,6,7,8] initial_state = [0,0,0,0,0,0,0,0] #random initail state with different position of number while 0 in initial_state: rand = random.randint(1,8) index = random.randint(0,7) if rand not in initial_state and rand - 1 != index: initial_state[index] = rand #heuristic Search for sort list #random swap number with heuristic condition count = 0 num = 0 heuristic = dict() swap = [] while count == 0: num += 1 print(f'Round: {num}') print(f'Before swap: {initial_state}') #define heuristic by if number is correct position give it 1 point if not give it -1 point for i in range(len(initial_state)): if initial_state[i] == final_state[i]: heuristic[i] = 1 else: heuristic[i] = -1 #incorrect position number will be swap to make it correct swap.append(initial_state[i]) less = False while less == False: #random 2 number from swap list swap_items = random.choices(swap, k = 2) index1 = initial_state.index(swap_items[0]) index2 = initial_state.index(swap_items[1]) if index2 > index1 and swap_items[0] > swap_items[1]: initial_state[index1] = swap_items[1] initial_state[index2] = swap_items[0] less = True #print heuristic Search Operation print(f'Heuristic is {heuristic}') print(f'-1 point is number: {swap}') print(f'First number is {swap_items[0]}') print(f'Second number is {swap_items[1]}') print(f'After swap: {initial_state}') print('---------------------------------') #clear swap list to make it can append again swap = [] if initial_state == final_state: count = 'finish' print(f'Done in {num} times') end_time = datetime.now() time = end_time - start_time print(f'Duration: {time}')
Tanisa124/AI-Practice
heuristic_lessRound.py
heuristic_lessRound.py
py
2,058
python
en
code
0
github-code
1
[ { "api_name": "datetime.datetime.now", "line_number": 5, "usage_type": "call" }, { "api_name": "datetime.datetime", "line_number": 5, "usage_type": "name" }, { "api_name": "random.randint", "line_number": 12, "usage_type": "call" }, { "api_name": "random.randint",...
35465861402
import itertools import torch.nn as nn import decoder import encoder import modules from utils import MergeDict class Model(nn.Module): def __init__(self, sample_rate, vocab_size): super().__init__() self.spectra = modules.Spectrogram(sample_rate) # self.encoder = encoder.Conv2dRNNEncoder(in_features=128, out_features=256, num_conv_layers=5, num_rnn_layers=1) # self.decoder = decoder.AttentionRNNDecoder(features=256, vocab_size=vocab_size) self.encoder = encoder.Conv2dAttentionEncoder(in_features=128, out_features=256, num_conv_layers=5) self.decoder = decoder.AttentionDecoder(features=256, vocab_size=vocab_size) for m in itertools.chain( self.encoder.modules(), self.decoder.modules()): if isinstance(m, (nn.Conv1d, nn.Conv2d)): nn.init.kaiming_normal_(m.weight) if m.bias is not None: nn.init.zeros_(m.bias) if isinstance(m, (nn.BatchNorm1d, nn.BatchNorm2d)): nn.init.ones_(m.weight) nn.init.zeros_(m.bias) def forward(self, sigs, seqs, sigs_mask, seqs_mask): spectras = self.spectra(sigs) spectras_mask = modules.downsample_mask(sigs_mask, spectras.size(3)) etc = MergeDict(spectras=spectras[:32]) features, etc.merge['encoder'] = self.encoder(spectras, spectras_mask) features_mask = modules.downsample_mask(spectras_mask, features.size(1)) logits, _, etc.merge['decoder'] = self.decoder(seqs, features, seqs_mask, features_mask) return logits, etc def infer(self, sigs, sigs_mask, **kwargs): spectras = self.spectra(sigs) spectras_mask = modules.downsample_mask(sigs_mask, spectras.size(3)) etc = MergeDict(spectras=spectras[:32]) features, etc.merge['encoder'] = self.encoder(spectras, spectras_mask) features_mask = modules.downsample_mask(spectras_mask, features.size(1)) logits, _, etc.merge['decoder'] = self.decoder.infer(features, features_mask, **kwargs) return logits, etc
vshmyhlo/listen-attend-and-speell-pytorch
model.py
model.py
py
2,131
python
en
code
11
github-code
1
[ { "api_name": "torch.nn.Module", "line_number": 11, "usage_type": "attribute" }, { "api_name": "torch.nn", "line_number": 11, "usage_type": "name" }, { "api_name": "modules.Spectrogram", "line_number": 15, "usage_type": "call" }, { "api_name": "encoder.Conv2dAtten...
27981377485
import requests import json import numpy as np import time import pandas as pd from pymysql import connect import csv from custom_send_email import sendEmail # 获取订单簿数据 class GetData(object): ''' 获取对应api bitmax数据,计算固定比例的数据,监控变化,发送邮件 ''' def __init__(self,url): self.url = url # self.data_all = {} # 返回的是创建对象的时间 self.now_time = time.time() pass def get_data(self): # 从api接口获取数据,返回数据列表(嵌套字典) r = requests.get(self.url) data = json.loads(r.text) return data def slope(self, data_list, coin_name): # 将数据分成sell和buy,分别求斜率(价格步长为0.5时,斜率为本价格仓位数量size). data_all = {} data_all['sell_XBT'] = [] data_all['buy_XBT'] = [] for data_dict in data_list: if data_dict['side'] == 'Sell': data_all['sell_XBT'].append([data_dict['size'],data_dict['price']]) elif data_dict['side'] == 'Buy': data_all['buy_XBT'].append([data_dict['size'],data_dict['price']]) # 获取斜率列表(size列表) slope_sell = [size[0] for size in data_all['sell_XBT']] slope_buy = [size[0] for size in data_all['buy_XBT']] # print('****************',slope_sell,slope_buy) # 获取斜率列表中处于99%的数据(size列表) slope_sell_data = np.percentile(slope_sell, 99) slope_buy_data = np.percentile(slope_buy, 99) # 将斜率列表中大于99%的数据返回 data_sell_list = [] data_buy_list = [] for data_sell in data_all['sell_XBT']: if data_sell[0] > slope_sell_data: data_sell = [str(data_sell[0]),str(data_sell[1])] data_sell_list.append(data_sell) # print('data_sell',data_sell) for data_buy in data_all['buy_XBT']: if data_buy[0] > slope_buy_data: data_buy = [str(data_buy[0]),str(data_buy[1])] data_buy_list.append(data_buy) # data_list 中的参数为 size price time return data_sell_list, data_buy_list pass def data_to_mysql(self, data_list, database_name, table_name, coin_name): # 将获取到的数据列表放到数据库中 #创建数据库连接 conn = connect( host='localhost', port=3306, user='root', password='1783126868@qq.com', database=database_name, charset='utf8' ) # 获取游标 cursor = conn.cursor() if coin_name == 'XBT': sql = 'delete from '+table_name+' where id>=1;' cursor.execute(sql) conn.commit() sql = 'alter table '+table_name+' AUTO_INCREMENT 1;' cursor.execute(sql) conn.commit() # 将数据变为 MySQL 格式 for data_dict in data_list: # print(data_dict) values_data = (data_dict['symbol'],data_dict['side'], data_dict['size'], data_dict['price']) # print(type(data_dict['price'])) # print(values_data) sql = '''insert into '''+table_name+''' (symbol,side,size,price) values'''+str(values_data)+''';''' # print(sql) # 执行sql语句 try: row_count = cursor.execute(sql) except: print('sql执行失败') # 提交到数据库 conn.commit() # 关闭游标 cursor.close() # 关闭连接 conn.close() pass def data_to_csv(self, data_sell_list, data_buy_list, coin_name): #将获取到的>99%的斜率列表数据保存到csv文件里 headers = ['Symbol','Price','Date','Time','Change','Volume'] # 将buy——list数据放入csv rows_buy = data_buy_list with open(coin_name+'_buy.csv', 'w') as f: f_csv = csv.writer(f) # f_csv.writerrow(headers) f_csv.writerows(rows_buy) # 将 sell_list数据放入csv rows_sell = data_sell_list with open(coin_name + '_sell.csv', 'w') as f: f_csv = csv.writer(f) # f_csv.writerrow(headers) f_csv.writerows(rows_sell) def csv_to_data(self, coin_name): # 读取csv文件文件数据,返回coin_name buy 和 sell 数据 # 打开coin_name+'_buy.csv'文件 coin_buy_list = [] with open(coin_name+'_buy.csv') as f: f_csv = csv.reader(f) for row in f_csv: if len(row) == 0: continue # if '.' in row[1]: # row[1] = float(row[1]) # else: # row[1] = int(row[1]) row = [row[0],row[1]] coin_buy_list.append(row) # 打开coin_name+'_sell.csv'文件 coin_sell_list = [] with open(coin_name+'_sell.csv') as f: f_csv = csv.reader(f) for row in f_csv: if len(row) == 0: continue # if '.' in row[1]: # row[1] = float(row[1]) # else: # row[1] = int(row[1]) row = [row[0], row[1]] coin_sell_list.append(row) # print('coin_sell_list:',coin_sell_list,'coin_buy_list:',coin_buy_list) return coin_sell_list, coin_buy_list def data_change(self,slope_sell,data_sell): ''' 参数(二维list)顺序:新数据,老数据。 返回值:改变的完整数据列表,新增的完整数据列表,减少的完整数据列表 ''' change_data = [] # newly_data = [] # lessen_data = [] # 变化的数据 for slope_x, slope_y in slope_sell: for data_x, data_y in data_sell: # 价位相等, 仓位数量不同 if data_y == slope_y and slope_x != data_x: # print('在{0}价位,仓位发生变化{1}----->{2}'.format(data_y,data_x,slope_x)) change_data.append([data_y, data_x, slope_x]) # 新增或减少的数据 # 价格遍布不同 # 价位列表 slope_price_list = [temp[1] for temp in slope_sell] data_price_list = [temp[1] for temp in data_sell] # 新增的价位列表 newly_price_data = list(set(slope_price_list) - set(data_price_list)) # 新增的完整数据 newly_data = [temp for temp in slope_sell if temp[1] in newly_price_data] # 减少的价位列表 lessen_price_data = list(set(data_price_list) - set(slope_price_list)) # 减少的完整数据 lessen_data = [temp for temp in data_sell if temp[1] in lessen_price_data] # change_data = [] # newly_data = [] # lessen_data = [] return change_data,newly_data,lessen_data def compare(self, slope_sell, data_sell, slope_buy, data_buy): # 比较两个列表数据前后的变化,返回变化的数据列表 change_sell_data,newly_sell_data,lessen_sell_data = self.data_change(slope_sell, data_sell) content_sell_list = [change_sell_data,newly_sell_data,lessen_sell_data] # 比较buy数据 slope_buy data_buy change_buy_data,newly_buy_data,lessen_buy_data = self.data_change(slope_buy, data_buy) content_buy_list = [change_buy_data,newly_buy_data,lessen_buy_data] return content_sell_list, content_buy_list def unpack(self,special_list): # 将列表解包,并合成字符串 # 解包修改的数据 content = '' for data in special_list[0]: change_str = '{0}价位的仓位数据发生变化:{1}--->{2}\n'.format(data[0], data[1], data[2]) content += change_str # 解包新增的数据 for data in special_list[1]: newly_str = '{0}价位的仓位数据发生变化:{1}--->{2}\n'.format(data[1], '0', data[0]) content += newly_str # 解包消失的数据 for data in special_list[2]: lessen_str = '{0}价位的仓位数据发生变化:{1}--->{2}\n'.format(data[1], data[0], '0', data[0]) content += lessen_str return content def send_email(self,coin_name, sell_list, buy_list): # 将数据解包并发送邮件 title = coin_name+' order_book_sell 数据发生变化' content = self.unpack(sell_list) sendEmail(content,title) title = coin_name+' order_book_buy 数据发生变化' content = self.unpack(buy_list) sendEmail(content,title) if __name__ == '__main__': # 从bitmex交易所获取不同币种的数据。 coin_list = ['XBT', 'ADA', 'BCT', 'EOS', 'ETH', 'LTC', 'TRX', 'XRP'] # coin_list = ['XBT'] all_num = 0 for coin_name in coin_list: url = 'https://www.bitmex.com/api/v1/orderBook/L2?symbol='+coin_name+'&depth=0' # 创建对象 ob = GetData(url) # 获取url数据 data = ob.get_data() all_num+=len(data) print('*'*50,all_num, coin_name) if len(data) == 0: print(coin_name, '未获取到数据') continue # 将数据存入MySQL数据库 # try: # ob.data_to_mysql(data,database_name='bitmex', table_name='order_book',coin_name=coin_name) # except: # print('存入数据失败') # 获取斜率大于指定值的完整数据列表 slope_sell, slope_buy = ob.slope(data, coin_name) # 从csv文件里读取数据(曾经的数据,大于固定斜率的数据) data_sell, data_buy = ob.csv_to_data(coin_name) # 将刚获取的斜率列表和csv数据进行对比 content_sell_list, content_buy_list = ob.compare(slope_sell,data_sell,slope_buy,data_buy) ob.send_email(coin_name,content_sell_list,content_buy_list) # 将斜率大于指定值的列表放到csv文件里 ob.data_to_csv(slope_sell, slope_buy, coin_name) # print(slope_sell,slope_buy)
jackendoff/bilian_bitmax_data
BITMAX_jackendoff.py
BITMAX_jackendoff.py
py
10,355
python
en
code
1
github-code
1
[ { "api_name": "time.time", "line_number": 21, "usage_type": "call" }, { "api_name": "requests.get", "line_number": 26, "usage_type": "call" }, { "api_name": "json.loads", "line_number": 27, "usage_type": "call" }, { "api_name": "numpy.percentile", "line_number...
29598602871
import numpy as np import keras # from keras.models import Sequential from keras.models import * from keras.layers import * import random from sklearn.model_selection import train_test_split #this one will be used for normalization and standardization from sklearn import preprocessing import scipy.io as sio # We use pandas for easiness of use and representation of data import pandas as pd from casadi import * # Simulates the system's dynamics using the system's equation # Inputs : x, u and disturbance at step k # output : x at step k+1 def system_dynamics(x_k, u_k, d_k): A = np.array([[0.8511, 0],[0, 1]]) B = np.array([[0.0035, 0, 0],[0, -5, 0]]) E = (1e-03)*np.array([[22.217, 1.7912, 42.212],[0, 0, 0]]) # system : x_k+1 = A*x_k + B*u_k + E*d_k x_k_plus = np.dot(A, x_k.reshape((2,1))) + np.dot(B, u_k.reshape((3,1))) + np.dot(E, d_k.reshape((3,1))) print('u_k = ') print(u_k) print('x_k_plus = ') print(x_k_plus) return x_k_plus # Calculates the mixed constraints of the whole simulation # Inputs : the input matrix generated from a controller (MPC or DL) simulation and the disturbance vectors # Output : the computed mixed constraints vector g def generate_mixed_constraints(mpc_u, d_full): D = np.array([[-1, 1, 1], [1, 1, 1]]) G = np.array([[0, 0.5, 0], [0, 0.5, 0]]) mpc_g = np.array([]) for i in range(mpc_u.shape[0]): temp = np.dot(D, mpc_u[i,:]) + np.dot(G, d_full[i,:]) mpc_g = np.append(mpc_g, temp) mpc_g = mpc_g.reshape((mpc_u.shape[0], 2)) return mpc_g # Simulates a trained DNN model as fully functionning DL based controller # Inputs : The DNN already trained model, the disturbances and the number of simulation steps # Outputs : Simulated input u and simulated state x def simulate_DLcontroller(trained_model, d_full, X_test, S=100): X_test_scaled = preprocessing.scale(X_test[:,0:2]) from sklearn.preprocessing import StandardScaler scaler = StandardScaler() print(scaler.fit(X_test[:,0:2])) # X_init_test_scaled = X_test_scaled[0,0:2] # X_init_test = X_test[0,0:2] X_init_test_scaled = scaler.transform(np.array([[20, 50000]])) X_init_test = np.array([[20, 50000]]) d_full_scaled = preprocessing.scale(d_full) Sim_u = np.array([]) Sim_x = np.array([]) Sim_x_scaled = np.array(X_init_test_scaled) Sim_x = np.append(Sim_x, X_init_test) Sim_x = Sim_x.reshape((1,2)) Sim_x_scaled = Sim_x_scaled.reshape((1,2)) for i in range(S): temp = np.array([]) temp = np.append(temp, (Sim_x_scaled[i, :]).reshape((1,2))) temp = np.append(temp, (d_full_scaled[i:i+5, :]).reshape((1,15))) temp = temp.reshape((1, 17)) prediction_u = trained_model.predict(temp) prediction_u = prediction_u.reshape((1,3)) x_plus = system_dynamics(Sim_x[i,:], prediction_u, d_full[i,:]) Sim_x = np.append(Sim_x, x_plus) Sim_x = Sim_x.reshape((i+2, 2)) print('x_plus.shape= ') print(x_plus.shape) x_plus_scaled = scaler.transform(x_plus.reshape((1,2))).reshape((2,1)) Sim_x_scaled = np.append(Sim_x_scaled, x_plus_scaled) Sim_x_scaled = Sim_x_scaled.reshape((i+2, 2)) Sim_u = np.append(Sim_u, prediction_u) print(Sim_u) print(Sim_x) Sim_u = Sim_u.reshape((S,3)) return Sim_u, Sim_x # Creates new disturbances by adding gaussian (normal) noise # Inputs : original disturbance vector # Outputs : disturbance with additive gaussian noise def create_new_disturbance(d_full, noise_level=10): noise = noise_level*np.random.normal(0, 1, d_full.shape) d_full_withNoise = d_full + noise #print('Original disturbance') #plot_disturbance(d_full) return d_full_withNoise def import_disturbance(filepath='external_disturbances.mat'): mat_disturbance = sio.loadmat(filepath) print('disturbance vector loaded') d_full = np.column_stack((mat_disturbance['room_temp'], mat_disturbance['sol_rad'], mat_disturbance['int_gains'])) print('peek into d_full (First 5 elements) :') print(d_full[0:5, :]) return d_full def open_test_csv(filepath='test_data.csv'): data = pd.read_csv(filepath) print('test data loaded from %s'%filepath) return data.values def plot_mpc(mpc_u, mpc_x): """### Plot the results""" # matplotlib to plot the results import matplotlib.pyplot as plt print('*As a reminder, x_init = %s*'%mpc_x[0, :]) # plot the states plt.figure(1) plt.hold = True; plt.plot(mpc_x[:,0]) plt.title('state x[0] (room temp Tr)') plt.xlabel('t') plt.figure(2) plt.hold = True; plt.plot(mpc_x[:,1]) plt.title('state x[1] (Energy in battery Ebat)') plt.xlabel('t') # plot the inputs plt.figure(3) plt.hold = True; for k in range(mpc_u.shape[1]): plt.plot(mpc_u[:,k]) plt.title('inputs') plt.xlabel('t') # show the plots plt.show() def plot_compare(mpc_u, mpc_x, mpc_g_mixed, Sim_u, Sim_x, Sim_g_mixed): """### Plot the results""" # matplotlib to plot both the mpc simulation and the DL simulation on the same graphs import matplotlib.pyplot as plt print('*As a reminder, x_init = %s*'%mpc_x[0, :]) # plot the states plt.figure(1) plt.hold = True; plt.plot(mpc_x[:,0], '--') plt.plot(Sim_x[:,0]) plt.title('state x[0] (room temp Tr)') plt.xlabel('t') plt.legend(('mpc', 'DL')) plt.figure(2) plt.hold = True; plt.plot(mpc_x[:,1], '--') plt.plot(Sim_x[:,1]) plt.title('state x[1] (Energy in battery Ebat)') plt.xlabel('t') plt.legend(('mpc', 'DL')) # plot the inputs plt.figure(3) plt.hold = True; for k in range(mpc_u.shape[1]): plt.plot(mpc_u[:, k], '--') plt.plot(Sim_u[:, k]) plt.title('MPC inputs') plt.xlabel('t') plt.legend(('mpc', 'DL','mpc', 'DL','mpc', 'DL')) # plot the constraints plt.figure(4) plt.hold = True for k in range(mpc_g_mixed.shape[1]): plt.plot(mpc_g_mixed[:, k], '--') plt.plot(Sim_g_mixed[:, k]) plt.title('mixed constraints') plt.xlabel('t') plt.legend(('mpc', 'DL','mpc', 'DL')) # show the plots plt.show() # show the plots # plt.figure(4) # plt.hold = True; # for k in range(mpc_u.shape[1]): # plt.plot(Sim_u[:, k]) # plt.title('DL controller inputs') # plt.xlabel('t') plt.show() def plot_disturbance(d_full, title='Disturbances'): print('Plotting the disturbances') import matplotlib.pyplot as plt plt.figure(1) plt.hold = True; plt.plot(d_full[:,0]) plt.figure(1) plt.hold = True; plt.plot(d_full[:,1]) plt.figure(1) plt.hold = True; plt.plot(d_full[:,2]) plt.xlabel('t') plt.title(title) plt.legend(('Room temp', 'Solar Radiation', 'Internal Gains')) plt.show() # Just added this one in order to plot the mpc controller and compare it to the DL controller def simulate_MPC(d_full, S = 100, N=10, x_init = np.array([[20],[50000]])): ##Define a linear system as a CasADi function""" A = np.array([[0.8511, 0],[0, 1]]) B = np.array([[0.0035, 0, 0],[0, -5, 0]]) E = (1e-03)*np.array([[22.217, 1.7912, 42.212],[0, 0, 0]]) D = np.array([[-1, 1, 1], [1, 1, 1]]) G_mixed = np.array([[0, 0.5, 0], [0, 0.5, 0]]) ## Define the optimization variables for MPC nx = A.shape[1] nu = B.shape[1] nm = D.shape[1] # this is for the mixed variables nd = E.shape[1] # this is for the disturbance variable x = SX.sym("x",nx,1) u = SX.sym("u",nu,1) m = SX.sym("m",nm,1) # Mixed variable d = SX.sym("d",nd,1) # Disturbance variable print('nx=%s'%nx) print('nu=%s'%nu) print('nm=%s'%nm) print('nd=%s'%nd) """## Choose the reference battery energy """ #@title choose Ebat_ref Ebat_ref = 50000 #@param {type:"slider", min:0, max:200000, step:1000} """## Choose the tuning of MPC""" #@title Choose prediction horizon N #N = 7 #@param {type:"slider", min:1, max:15, step:1} #@title Choose number of steps S # S = 100 #@param {type:"slider", min:1, max:144, step:1} #@title Choose the penalty parameter gamma gamma = 4.322 #@param {type:"slider", min:0, max:10, step:0.0001} """# Define the dynamics as a CasADi expression""" # Fill d here from the .mat disturbance file # For collab only #!wget -O external_disturbances.mat https://www.dropbox.com/s/57ta25v9pg94lbw/external_disturbances.mat?dl=0 #!ls #mat_disturbance = sio.loadmat('external_disturbances.mat') #d_full = np.column_stack((mat_disturbance['room_temp'], mat_disturbance['sol_rad'], mat_disturbance['int_gains'])) #print('disturbance vector successfully loaded in vector d_full') print('length of d_full:%i'%(d_full.shape[0])) d_0 = d_full[0, 0] d_1 = d_full[0, 1] d_2 = d_full[0, 2] print('first line of d (3 columns)') print('d[0,0] = %f'%d_0) print('d[0,1] = %f'%d_1) print('d[0,2] = %f'%d_2) # Definition of the system, and the mixed constraint equations output_sys = mtimes(A,x) + mtimes(B,u) + mtimes(E, d) output_mixed = mtimes(D,u) + mtimes(G_mixed,d) system = Function("sys", [x,u,d], [output_sys]) mixed = Function("sys", [u,d], [output_mixed]) """### Construct CasADi objective function""" ### state cost J_stage_exp = u[2] + gamma*mtimes((x[1]-Ebat_ref),(x[1]-Ebat_ref)) J_stage = Function('J_stage',[x,u],[J_stage_exp]) # ### terminal cost ?? How ? # Suggestion : Terminal cost is stage cost function at last x_k (x_k[N]) J_terminal_exp = gamma*mtimes((x[1]-Ebat_ref),(x[1]-Ebat_ref)) J_terminal = Function('J_terminal',[x],[J_terminal_exp]) # J_terminal = Function('J_terminal',[x],[J_terminal_exp]) """## Define optimization variables""" X = SX.sym("X",(N+1)*nx,1) U = SX.sym("U",N*nu,1) # Added by me : Mixed constraints optimization variable M M = SX.sym("M",N*nu,1) """## Define constraints""" # state constraints : 20.0<=Tr<=23 and 0.0 ≤ SoC ≤ 200000 lbx = np.array([[20],[0]]) ubx = np.array([[23],[200000]]) # input constraints lbu = np.array([[-1000],[-500],[-500]]) ubu = np.array([[1000],[500],[500]]) # mixed constraints ? lbm = np.array([[0], [0]]) ubm = np.array([[inf], [inf]]) """## Initialize vectors and matrices""" # Initializing the vectors # initial state vector has to be initialize with a feasible solution ############### Commented out to modularize the code ######## # x_init = np.array([[21],[150000]]) #Arbitrary (random) feasible solution # ############################################################# # Storing u_k and x_k in history matrices mpc_x and mpc_u mpc_x = np.zeros((S+1,nx)) mpc_x[0,:] = x_init.T mpc_u = np.zeros((S,nu)) #added by me to store mixed constraints values at each step mpc_g_mixed = np.zeros((S, G_mixed.shape[0])) """## MPC loop""" for step in range(S): ### formulate optimization problem J = 0 lb_X = [] ub_X = [] lb_U = [] ub_U = [] # Added by me : bound vectors for mixed constraints lb_M = [] ub_M = [] ##################### G = [] lbg = [] ubg = [] ### for k in range(N): d_k = d_full[step + k,:] # check correct index! x_k = X[k*nx:(k+1)*nx,:] x_k_next = X[(k+1)*nx:(k+2)*nx,:] u_k = U[k*nu:(k+1)*nu,:] # objective J += J_stage(x_k,u_k) # equality constraints (system equation) x_next = system(x_k,u_k,d_k) # mixed constraints vector calculation g_mixed = mixed(u_k, d_k) if k == 0: G.append(x_k) lbg.append(x_init) ubg.append(x_init) G.append(x_next - x_k_next) lbg.append(np.zeros((nx,1))) ubg.append(np.zeros((nx,1))) # Added by me : mixed constraints with their bounds G.append(g_mixed) lbg.append(lbm) ubg.append(ubm) # inequality constraints lb_X.append(lbx) ub_X.append(ubx) lb_U.append(lbu) ub_U.append(ubu) # added by me #lb_M.append(lbm) #ub_M.append(ubm) #################### ## Terminal cost and constraints x_k = X[N*nx:(N+1)*nx,:] J += J_terminal(x_k) lb_X.append(lbx) ub_X.append(ubx) ### solve optimization problem lb = vertcat(vertcat(*lb_X),vertcat(*lb_U)) ub = vertcat(vertcat(*ub_X),vertcat(*ub_U)) prob = {'f':J,'x':vertcat(X,U),'g':vertcat(*G)} solver = nlpsol('solver','ipopt',prob) res = solver(lbx=lb,ubx=ub,lbg=vertcat(*lbg),ubg=vertcat(*ubg)) u_opt = res['x'][(N+1)*nx:(N+1)*nx+nu,:] # Ignore this # g_constrained = res['g'][N*2] # print('res["x"] = %s'%res['x']) # print('u_opt = %s'%u_opt) # print('res["g"] = : %s'%g_constrained) #################################### ### simulate the system x_plus = system(x_init.T,u_opt, d_full[step,:]) mpc_x[step+1,:] = x_plus.T mpc_u[step,:] = u_opt.T x_init = x_plus # added by me g_plus = mixed(u_opt, d_full[step,:]) mpc_g_mixed[step, :] = g_plus.T # print(mpc_g_mixed) ###################### return mpc_u, mpc_x, mpc_g_mixed, d_full if __name__ == '__main__': filepath_trained_model = 'Final_model_varDist_20epochs_100000lines.h5' trained_model = load_model(filepath_trained_model) print('loaded trained model loaded from :%s'%filepath_trained_model) # Saving the model to a png representation from keras.utils import plot_model plot_model(trained_model, show_shapes=True, to_file='trained_model.png') # we should load the test data : test_data = open_test_csv(filepath='test_data_not_scaled.csv') print('test_data shape :') print(test_data.shape) X_test = test_data[:, 1:18] y_test = test_data[:, 18:21] print('X_test =') print(X_test.shape) print('y_test =') print(y_test) # Making simple predictions now predictions = np.array([]) for i in range(X_test.shape[0]): # predictions = np.append(predictions, trained_model.predict(np.array([[X_test[i,0], X_test[i,1], X_test[i,2], X_test[i,3], X_test[i,4]]]))) temp = np.array([]) for j in range(X_test.shape[1]): temp = np.append(temp, X_test[i, j]) temp = temp.reshape((1, X_test.shape[1])) predictions = np.append(predictions, trained_model.predict(temp)) predictions = predictions.reshape((X_test.shape[0], y_test.shape[1])) print('X_test:') print(X_test[10:20, :]) print('Prediction matrix :') print(predictions[10:20, :]) print('Compare it to label matrix y_test :') print(y_test[10:20, :]) test_data_scaled = open_test_csv(filepath='test_data_scaled.csv') X_test_scaled = test_data_scaled[:, 1:18] y_test_scaled = test_data_scaled[:, 18:21] print('Metrics of evaluation') print(trained_model.metrics_names) print('Model evaluation : ') print(trained_model.evaluate(X_test_scaled, y_test_scaled)) d_full = import_disturbance() print(d_full.shape) d_full_withNoise = create_new_disturbance(d_full, noise_level=10) plot_disturbance(d_full_withNoise, title='disturbance with additive noise level=10') Sim_u, Sim_x = simulate_DLcontroller(trained_model, d_full_withNoise, X_test, S = 100) print('Sim_u.shape=') print(Sim_u.shape) print('Sim_x.shape=') print(Sim_x.shape) print('\n') print('Sim_x = ') print(Sim_x) print('\n') print('Sim_u = ') print(Sim_u) mpc_u, mpc_x, mpc_g_mixed, _ = simulate_MPC(d_full_withNoise, S = 100, N=5, x_init = np.array([[20],[50000]])) Sim_g_mixed = generate_mixed_constraints(Sim_u, d_full_withNoise) plot_compare(mpc_u, mpc_x, mpc_g_mixed, Sim_u, Sim_x, Sim_g_mixed)
ell-hol/mpc-DL-controller
simulate_DL_controller.py
simulate_DL_controller.py
py
16,307
python
en
code
61
github-code
1
[ { "api_name": "numpy.array", "line_number": 24, "usage_type": "call" }, { "api_name": "numpy.array", "line_number": 25, "usage_type": "call" }, { "api_name": "numpy.array", "line_number": 26, "usage_type": "call" }, { "api_name": "numpy.dot", "line_number": 29...
30296294545
import serial import sys import time def out_gpio(value): f_val = open('/sys/class/gpio/gpio18/value', 'w') f_val.write(value) f_val.close() # первый байт req - ожидаемая длина ответа def make_request(req): out_gpio('1') port.write(req[1:]) time.sleep(0.004) out_gpio('0') while(port.inWaiting() == 0): time.sleep(0.5) res = port.read(req[0]) sys.stdout.write(res) port = serial.Serial("/dev/ttyUSB0", baudrate=9600, timeout=1.0) #req = sys.stdin.read() # команда req = '\x06\x01\x00\x00\x00\x00\x00'; # watchdog (если 3 устройства) req = '\x07\x01\xFF\x00\x00'; make_request(req)
almarkov/quest
test.py
test.py
py
651
python
ru
code
0
github-code
1
[ { "api_name": "time.sleep", "line_number": 14, "usage_type": "call" }, { "api_name": "time.sleep", "line_number": 17, "usage_type": "call" }, { "api_name": "sys.stdout.write", "line_number": 19, "usage_type": "call" }, { "api_name": "sys.stdout", "line_number"...
8707312288
#---------------------------------------------------------------------- # Package Management #---------------------------------------------------------------------- import os import os.path as op import textwrap import argparse import pandas as pd import re import zipfile from tqdm import tqdm, trange import hashlib #---------------------------------------------------------------------- # Perma Variables #---------------------------------------------------------------------- consoleCols = 100 # number of columns to use in console printing #---------------------------------------------------------------------- # Parse Arguments #---------------------------------------------------------------------- # Initialize ArgumentParser parser = argparse.ArgumentParser( prog='studycompressor', formatter_class=argparse.RawDescriptionHelpFormatter, epilog=textwrap.dedent('''\ Appendix -------- ''')) # Specify parser arguments # Mandatory parser.add_argument('input', help='directory path to compress', type=str) parser.add_argument('output', help='directory to output compressed chunks', type=str) # Optional parser.add_argument('-n', '--name', help='name to give to compressed outputs', default='comprssr_archive', type=str) parser.add_argument('-s', '--size', help='file size of each chunk', default='500M', type=str) parser.add_argument('-t', '--type', help='output type to write (excel or csv)', default='csv', type=str) # Process arguments args = parser.parse_args() #---------------------------------------------------------------------- # Validate Arguments #---------------------------------------------------------------------- if not op.isdir(args.input): raise NotADirectoryError('Specified input directory not found. ' 'Please ensure that the directory {} ' 'exists.'.format(input)) if not op.isdir(args.output): raise NotADirectoryError('Specified output directory not found. ' 'Please ensure that the directory {} ' 'exists.'.format(input)) if not args.size[-1].isalpha(): raise Exception('Please specify a size multiple. Specify either ' '"M" or "G".') if not any(x in args.size[-1] for x in ['M', 'G']): raise Exception('Invalid file size multiple. Please use either ' '"M" for megabytes and "G" for gigabytes') if 'csv' not in args.type and 'excel' not in args.type: raise Exception('Invalid output type choce. Please enter either ' ' "csv" or "excel". Otherwise, leave blank.') #---------------------------------------------------------------------- # Print Input Configuration #---------------------------------------------------------------------- tqdm.write('Running comprssr with the following configuration:\n') tqdm.write('File Name: {}'.format(args.name)) tqdm.write('Size Limit: {}'.format(args.size)) tqdm.write('Summery Type: {}'.format(args.type)) tqdm.write('Input Directory: {}'.format(args.input)) tqdm.write('Output Directory: {}\n'.format(args.output)) #---------------------------------------------------------------------- # Declare Variables #---------------------------------------------------------------------- if 'M' in args.size[-1]: bytemul = 1E6 elif 'G' in args.size[-1]: bytemul = 1E9 size = int(args.size[:-1]) sizeLimit = size * bytemul #---------------------------------------------------------------------- # Begin Code #---------------------------------------------------------------------- def compressfile(file): """ Compresses a file into an """ file_dir = [] file_list = [] file_size = [] for root, dirs, files in os.walk( args.input ): file_dir.extend( root for f in files ) file_list.extend( f for f in files ) file_size.extend(int(op.getsize(op.join( root,f))) for f in files ) if sizeLimit < min(file_size): raise Exception('Compression size {} is lower than the smallest ' 'file detected ({}{}). Please update compression ' 'size to accomodate this.'.format(args.size, min(file_size)/bytemul, args.size[-1])) if sizeLimit < max(file_size): raise Exception('It appears that you are attempting to specify ' 'a compression size smaller than the max file ' 'size ({}{}). Please update the filesize ' 'flag.'.format(max(file_size)/bytemul, args.size[-1])) numFiles = len(file_list) tqdm.write('Found a total of {} files'.format(numFiles)) # Compression loop using two while loops # The parent while loop iterates over all files. The child while loop # check filesize of compressed archive. i = 0 zip_name = [] checksum = [] numComp = 0 pbar = tqdm(total=numFiles - 1, desc='Compressing', ncols=consoleCols, unit='file') while i < (numFiles - 1): compSize = 0 zPath = op.join(args.output, args.name + '.part' + str(numComp) + '.zip') tqdm.write('') tqdm.write(('=' * consoleCols)) tqdm.write('Creating {}.part{}.zip\n'.format(args.name, numComp)) filesincomp = 0 # This loop creates a new zipfile, added each while iteratively # and checks its size. Enclosing this in a while loop allows this # process to occur iteratively until the zipfile's size meets the # size limit imposed on it. with zipfile.ZipFile(zPath, 'w') as zipMe: while compSize < sizeLimit: filesincomp += 1 file2comp = op.join(file_dir[i], file_list[i]) tqdm.write(' adding: {}'.format(file2comp)) zipMe.write(file2comp, compress_type=zipfile.ZIP_DEFLATED) # Check size of last file added to archive and add it to this # variable compSize += zipMe.infolist()[-1].file_size zip_name.append(args.name + '.part' + str(numComp) + '.zip') checksum.append(hashlib.md5(open(zPath, 'rb').read()).hexdigest()) i += 1 pbar.update(1) if i == numFiles: break zipMe.close() tqdm.write('') tqdm.write('Archive size: {}{}'. format(op.getsize(zPath)/bytemul, args.size[-1])) tqdm.write('Files in archive: {}'.format(filesincomp)) numComp += 1 # Convert table filesize to same unit as input file_size = [round(i/bytemul, 2) for i in file_size] dFrame = pd.DataFrame({'MD5 Checksum': checksum, 'Archive Name': zip_name, 'Filesize ({})'.format(args.size[-1]): file_size, 'Directory':file_dir, 'Filename': file_list}) tqdm.write('') tqdm.write(('=' * consoleCols)) if 'csv' in args.type: dFrame.to_csv(op.join(args.output, args.name + '.csv'), sep='\t') tqdm.write('File saved: {}'.format(op.join(args.output, args.name + '.csv'))) elif 'excel' in args.type: dFrame.to_excel(op.join(args.output, args.name + '.xlsx')) tqdm.write('File saved: {}'.format(op.join(args.output, args.name + '.xlsx'))) else: raise Exception('Unable to save to the ouput file type.') tqdm.write('Archiving complete!')
muscbridge/comprssr
comprssr.py
comprssr.py
py
7,544
python
en
code
0
github-code
1
[ { "api_name": "argparse.ArgumentParser", "line_number": 24, "usage_type": "call" }, { "api_name": "argparse.RawDescriptionHelpFormatter", "line_number": 26, "usage_type": "attribute" }, { "api_name": "textwrap.dedent", "line_number": 27, "usage_type": "call" }, { ...
24383408411
"""Script to gather IMDB keywords from 2013's top grossing movies.""" import sys from os import path import time from business_logic.compare_prices import ComparePrices import logging from business_logic.logic import Logic logger = logging.getLogger('ftpuploader') hdlr = logging.FileHandler('ftplog.log') formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(logging.INFO) def main(): comp = ComparePrices() logic = Logic() keep_alive = True while keep_alive: try: arbs = comp.pricing_compare() time.sleep(10) if arbs: logger.info(arbs) logic.place_test_orders(arbs) except Exception as e: keep_alive = True print(str(e)) logger.error(str(e)) print(arbs) """Main entry point for the script.""" pass def extend_class_path(): sys.path.append(path.abspath('..')) print(sys.path) if __name__ == '__main__': sys.exit(main())
life-of-pi-thon/crypto_carluccio
lukrative.py
lukrative.py
py
1,077
python
en
code
0
github-code
1
[ { "api_name": "logging.getLogger", "line_number": 8, "usage_type": "call" }, { "api_name": "logging.FileHandler", "line_number": 9, "usage_type": "call" }, { "api_name": "logging.Formatter", "line_number": 10, "usage_type": "call" }, { "api_name": "logging.INFO", ...
19767607746
"""CSV操作 aws cliの初期設定 aws configure 設定の確認 ~/.aws/ boto3 Client APIとResource API Client API・・・リソースを操作する場合も参照系と同様に、対象のリソースIDを引数に加えてメソッドを実行する。 ex) s3 = boto3.client('s3') # バケット一覧を取得 s3.list_buckets() obj = client.get_object(Bucket='test_bucket', Key='test.text') print(obj['body'].read()) Resource API・・・リソースを操作する場合には対象のリソースを「object」として取得してからobjectのもつメソッドを呼び出して操作する。 よりオブジェクト指向っぽく書けるよう用意された高レベルなライブラリです。 必ずしもすべてのサービスで用意されているわけではなくて、S3 などの頻出サービスでのみ利用できます。 目的に応じて resource が使えないか検討してみるとよいでしょう。 ex) s3 = boto3.resource('s3') bucket = s3.Bucket('test_bucket') obj = bucket.Object('test.text').get() print(obj['body'].read()) s3_resource = boto3.resource('s3') clientも取得可能 s3_client = s3_resource.meta.client BytesIO・・・メモリ上でバイナリデータを扱うための機能です。Python の標準ライブラリ io に含まれています。バイナリデータとは主に画像や音声などのデータのことです。コンピューターで扱うデータは全てバイナリデータなのですが、テキストデータと対比して用いられます。 TextIOWrapper・・・テキストモード クラスメソッド・・・インスタンスを作らずともアクセスできる。クラスの属性を触りたい時に使う。 インスタンスメソッド・・・インスタンスからアクセスする。インスタンスの属性をさわりたいとき。 1. s3 bucketの作成 2. 「test.csv」のupload 3. csvファイルの読み込み 4. s3上のcsvファイルから特定の値を抽出 5. 作成したobject,bucketの削除 """ import io import csv import json import boto3 BUCKET_NAME = "yoshiki-s3-2022-bucket" KEY = "test.csv" def s3_client(): s3 = boto3.client('s3') # <botocore.client.S3 object at 0x7fb16d527250> # <class 'botocore.client.S3'> # s3.ServiceResource() # <class 'boto3.resources.factory.s3.ServiceResource'> return s3 def create_bucket(bucket_name): return s3_client().create_bucket( Bucket=bucket_name, CreateBucketConfiguration={ 'LocationConstraint': 'ap-northeast-1' } ) def create_bucket_policy(bucket_name): # IAMポリシーでアクセスする許可と拒否の条件をJSON形式で記述したものがPolicyドキュメント bucket_policy = { # policy statementの現行version "Version": "2012-10-17", "Statement": [ { # Statement ID(任意のID) "Sid": "AddPerm", # リソースへのアクセスを許可するには、Effect 要素を Allow に "Effect": "Allow", # ステートメントのアクションやリソースへのアクセスが許可されているアカウントまたはユーザー "Principal": { "AWS": "arn:aws:iam::068788852374:user/yoshiki.kasama" }, # s3に対する全てのactionを許可 "Action": ["s3:*"], # ステートメントで取り扱う一連のオブジェクトを指定します。 "Resource": ["arn:aws:s3:::yoshiki-s3-2022-bucket/*"] } ] } policy_string = json.dumps(bucket_policy) return s3_client().put_bucket_policy( Bucket=bucket_name, Policy=policy_string ) def upload_file(bucket_name, key): file_path = "./csv_files/test.csv" s3_client().upload_file(file_path, bucket_name, key) def get_csv_file(bucket_name, key): response = s3_client().get_object(Bucket=bucket_name, Key=key) if response['ResponseMetadata']['HTTPStatusCode'] == 200: print('get_object succeeded!') body = io.TextIOWrapper(io.BytesIO(response['Body'].read())) # print(body) # print(type(body)) for row in csv.DictReader(body): print(row) # def select_object(bucket_name, key): # response = s3_client().select_object_content( # Bucket=bucket_name, # Key=key, # Expression='Select name from S3Objects', # ExpressionType='SQL', # InputSerialization={'CSV': {'FileHeaderInfo': 'Use'}}, # OutputSerialization={'JSON': {}} # ) # for event in response['Payload']: # if 'Records' in event: # print(event['Records']['Payload'].decode()) def list_buckets(bucket_name): response = s3_client().list_objects_v2( Bucket=bucket_name ) keys = [] for data in response['Contents']: keys.append(data['Key']) return keys def delete_objects(bucket_name, keys): objects = [] for k in keys: objects.append({ 'Key': k, }) response = s3_client().delete_objects( Bucket=bucket_name, Delete={ 'Objects': objects, } ) if response['ResponseMetadata']['HTTPStatusCode'] == 200: print('delete_objects succeeded') def delete_bucket(bucket_name): response = s3_client().delete_bucket( Bucket=bucket_name ) if response['ResponseMetadata']['HTTPStatusCode'] == 204: print('delete_bucket succeeded') def main(): response = create_bucket(BUCKET_NAME) if response['ResponseMetadata']['HTTPStatusCode'] == 200: print("create bucket succeeded!") create_bucket_policy(BUCKET_NAME) upload_file(BUCKET_NAME, KEY) get_csv_file(BUCKET_NAME, KEY) # select_object(BUCKET_NAME, KEY) keys = list_buckets(BUCKET_NAME) delete_objects(BUCKET_NAME, keys) delete_bucket(BUCKET_NAME) if __name__ == '__main__': main()
yoshikikasama/data_analytics
coding/boto3/tutorials/csv_from_s3.py
csv_from_s3.py
py
6,116
python
ja
code
0
github-code
1
[ { "api_name": "boto3.client", "line_number": 53, "usage_type": "call" }, { "api_name": "json.dumps", "line_number": 92, "usage_type": "call" }, { "api_name": "io.TextIOWrapper", "line_number": 108, "usage_type": "call" }, { "api_name": "io.BytesIO", "line_numb...
39002643737
import sqlite3 DbName = "./db/timing_plan.db" class Cdb: def __init__(self,dbName): self.dbName = dbName #数据库名称 self.conn = None #文件与数据库的连接 self.cursor = None #文件与数据库的交互 self.__connect() def __connect(self): #将数据库与文件连接 try: self.conn = sqlite3.connect(self.dbName) self.cursor = self.conn.cursor() except: print("conn db err!") def exec_query(self,sql,*parms): #执行命令并查询每行 try: self.cursor.execute(sql,parms) values = self.cursor.fetchall() except: print("exec_query error,sql is=",sql) return None return values def exec_cmd(self,sql,*parms): #执行命令并保持更改 try: self.cursor.execute(sql,parms) self.conn.commit() except: print("exec_cmd error,sql is=", sql) def close_connect(self): #断开连接 try: self.cursor.close() self.conn.close() except: print("close db err!") def initDb(): #初始化数据库 cdb = Cdb(DbName) sql = "create table if not exists user (freq integer not null,func integer not null, tp varchar(200))" cdb.exec_cmd(sql) cdb.close_connect() def deleteAccount(freq): #删除指定freq数据 cdb = Cdb(DbName) sql1 = "delete from user where freq=?" cdb.exec_cmd(sql1,freq) cdb.close_connect() def deleteAll(): cdb=Cdb(DbName) sql1="delete from user" cdb.exec_cmd(sql1) cdb.close_connect() def addAccountInfo(freq,func,tp): #添加账号信息 cdb = Cdb(DbName) sql1 = "insert into user (freq,func,tp) values (?,?,?)" cdb.exec_cmd(sql1, freq, func,tp) sql2 = "select max(freq) from user" res = cdb.exec_query(sql2) cdb.close_connect() return res[0][0] def editAccountInfo(freq,func,tp): #编辑账号信息 cdb = Cdb(DbName) sql1 = "update user set func=?,tp =? where freq=?" cdb.exec_cmd(sql1, freq, func, tp) cdb.close_connect() def getData(): #获取账号信息 cdb = Cdb(DbName) sql2 = "select * from user" res = cdb.exec_query(sql2) cdb.close_connect() return res if __name__ == '__main__': # conn=sqlite3.connect('./db/test.db') # c = conn.cursor() # 获取游标 # sql = "create table if not exists opti (freq integer not null,func integer not null, timeplan varchar(200))" # c.execute(sql) # 执行sql语句 # conn.commit() # 提交数据库操作 # conn.close() # print("ok") cdb = Cdb(DbName) initDb() addAccountInfo(1,80,"[20 30]") deleteAll() print(getData())
lx-dtbs/UI-base
sumo_liveUpdate_ui/DbBase.py
DbBase.py
py
2,777
python
en
code
1
github-code
1
[ { "api_name": "sqlite3.connect", "line_number": 11, "usage_type": "call" } ]
22184099208
""" Simple `GIL` released demo. """ import threading import requests from ch01.tools import time_it def simple_request() -> None: """Make a simple request""" response = requests.get("https://www.google.com") print(f"Response status code: {response.status_code}") @time_it def requests_no_threading() -> None: simple_request() simple_request() @time_it def requests_with_threading() -> None: thread_1 = threading.Thread(target=simple_request) thread_2 = threading.Thread(target=simple_request) thread_1.start() thread_2.start() thread_1.join() thread_2.join() if __name__ == "__main__": requests_no_threading() requests_with_threading()
iplitharas/myasyncio
ch01/gil_released_demo.py
gil_released_demo.py
py
700
python
en
code
0
github-code
1
[ { "api_name": "requests.get", "line_number": 13, "usage_type": "call" }, { "api_name": "ch01.tools.time_it", "line_number": 17, "usage_type": "name" }, { "api_name": "threading.Thread", "line_number": 25, "usage_type": "call" }, { "api_name": "threading.Thread", ...
70026443555
import os import datetime import argparse import sys import shutil def run(): parser = argparse.ArgumentParser(description="Delete files each period of time") parser.add_argument("--dir_path", type=str, help="Path to the folder") parser.add_argument("--period", type=int, help="Period of time in days") args = parser.parse_args() print(sys.stdout.write(str(delete_old_files(args)))) def delete_old_files(args): # get the current time print("Files to delete:") now = datetime.datetime.now() try: files = os.listdir(args.dir_path) except FileNotFoundError: print("The directory does not exist or is empty") return # loop through all the files in the directory for file_name in os.listdir(args.dir_path): # get the full path of the file file_path = os.path.join(args.dir_path, file_name) # get the modification time of the file mtime = datetime.datetime.fromtimestamp(os.path.getmtime(file_path)) # calculate the difference between the modification time and the current time diff = now - mtime # if the difference is greater than the period of time, delete the file if diff.seconds > args.period: # delete the file # give permission of root to delete the file os.chmod(file_path, 0o777) try: shutil.rmtree(file_path) except NotADirectoryError: os.remove(file_path) print("- ",file_name) if args.period > 1: print("The function to deleted files each {} days has been executed successfully!".format(args.period)) else: print("Files has been deleted successfully!") if __name__ == "__main__": run()
JassielMG/AutoCleanFolder
main.py
main.py
py
1,778
python
en
code
0
github-code
1
[ { "api_name": "argparse.ArgumentParser", "line_number": 7, "usage_type": "call" }, { "api_name": "sys.stdout.write", "line_number": 11, "usage_type": "call" }, { "api_name": "sys.stdout", "line_number": 11, "usage_type": "attribute" }, { "api_name": "datetime.date...
14621398412
import os import tornado.web from .Util import * from .Core import * class IndexHandler(tornado.web.RequestHandler): def get(self): self.render("index.html", people="skipper") class LogIndexHandler(tornado.web.RequestHandler): def get(self): self.render("log/log_index.html") class LogListHandler(tornado.web.RequestHandler): def get(self): files = os.listdir(self.settings['data_path'] + "/log") self.render('log/log_list.html', rawList=sorted(files)) class DeleteHandler(tornado.web.RequestHandler): def get(self, dtype, filename): dataPath = self.settings['data_path'] if dtype == 'log': os.remove(dataPath + '/log/' + filename) else: #os.remove(dataPath + '/cache/' + dtype + '/' + filename) os.remove(dataPath + '/cache/' + filename) #self.redirect("/log") class UploadHandler(tornado.web.RequestHandler): def post(self): uploadPath = os.path.join(self.settings['data_path'], "log") multiFile = self.request.files['fileUploader'] for f in multiFile: filename = f['filename'] filePath = os.path.join(uploadPath, filename) with open(filePath, 'wb') as upfile: upfile.write(f['body']) self.redirect("/log") class ExtractHandler(tornado.web.RequestHandler): def get(self, etype, filename): data = {} cachePath = self.settings['data_path'] + "/cache/" rawFile = self.settings['data_path'] + "/log/" + filename if etype == 'nginx': data = log2cache(rawFile) filename = filename + "_nginx" elif etype == 'apache': data = log2cache(rawFile) filename = filename + "_apache" json2file(cachePath, data, filename) self.write("Extract Completed") class AnalysisHandler(tornado.web.RequestHandler): def get(self): #self.render('analysis/analysis_index.html', headLine="Access Log") self.render('analysis/analysis_index.html') class CacheListHandler(tornado.web.RequestHandler): def get(self, ctype): #cachePath = self.settings['data_path'] + "/cache/" + ctype cachePath = self.settings['data_path'] + "/cache/" caches = os.listdir(cachePath) #self.render('analysis/cache_list.html', cacheList=sorted(caches), cacheType=ctype) self.render('analysis/cache_list.html', cacheList=sorted(caches), cacheType=ctype) class RenderHandler(tornado.web.RequestHandler): # "aType" and "filename" will be used in JS(window.location.href) def get(self, aType, filename): #url = "" #if aType in ['per_hour', 'req_method', 'status_code', 'top_ip']: # url = "/analysis" #self.render('analysis/render.html', backLink=url) self.render('analysis/render.html') class ChartAjaxHandler(tornado.web.RequestHandler): def get(self, aType, filename): data = get_log_analysis(self.settings['data_path'], aType, filename) self.render('analysis/atype/' + aType + '.html', data=data, filename=filename) # data - contains data which highchart needs to build chart # filename - filename displays on top of chart in red
daddvted/arch1ve
python_code/log2chart_tornado/engine/Handler.py
Handler.py
py
3,264
python
en
code
0
github-code
1
[ { "api_name": "tornado.web.web", "line_number": 8, "usage_type": "attribute" }, { "api_name": "tornado.web", "line_number": 8, "usage_type": "name" }, { "api_name": "tornado.web.web", "line_number": 13, "usage_type": "attribute" }, { "api_name": "tornado.web", ...
72632864993
import json from flask import Flask, render_template, request, jsonify from sklearn.svm import SVC from sklearn.feature_extraction.text import CountVectorizer app = Flask(__name__) # Load the business guidelines from a JSON file with open("business_guidelines.json", "r") as f: guidelines_data = json.load(f) # Create a list of business ideas and their corresponding categories data = [] for category, ideas_dict in guidelines_data.items(): for sub_category, ideas in ideas_dict.items(): for idea in ideas: data.append((category, sub_category, idea)) # Prepare the text data for classification using CountVectorizer vectorizer = CountVectorizer() X = vectorizer.fit_transform([idea for _, _, idea in data]) y = [category for category, _, _ in data] # Create and train an SVM classifier clf = SVC(kernel='linear') clf.fit(X, y) @app.route("/") def index(): return render_template("index.html") @app.route("/predict", methods=["POST"]) def predict(): user_input = request.json.get("user_input", "") result = {} if user_input in guidelines_data: result["category"] = user_input result["data"] = guidelines_data[user_input] elif user_input: X_test = vectorizer.transform([user_input]) predicted_category = clf.predict(X_test)[0] if predicted_category in guidelines_data: result["category"] = predicted_category result["data"] = guidelines_data[predicted_category] else: result["error"] = f"No guidelines found for the predicted category '{predicted_category}'." return jsonify(result) if __name__ == "__main__": app.run(debug=True)
Balakumarmd/Ideavalidator
app.py
app.py
py
1,730
python
en
code
0
github-code
1
[ { "api_name": "flask.Flask", "line_number": 6, "usage_type": "call" }, { "api_name": "json.load", "line_number": 10, "usage_type": "call" }, { "api_name": "sklearn.feature_extraction.text.CountVectorizer", "line_number": 20, "usage_type": "call" }, { "api_name": "...
26358115895
from __future__ import print_function, division #################################################################### ###### Copyright (c) 2022-2023 PGEDGE ########## #################################################################### import argparse, sys, os, tempfile, json, subprocess, getpass import util, startup pgver = "pgXX" MY_HOME = os.getenv("MY_HOME", "") MY_LOGS = os.getenv("MY_LOGS", "") pg_home = os.path.join(MY_HOME, pgver) homedir = os.path.join(MY_HOME, pgver) logdir = os.path.join(homedir, pgver) parser = argparse.ArgumentParser() parser.add_argument("--port", type=int, default=0) parser.add_argument("--autostart", choices=["on", "off"]) parser.add_argument("--datadir", type=str, default="") parser.add_argument("--logdir", type=str, default="") parser.add_argument("--svcname", type=str, default="") parser.add_argument("--setpwd", type=str, default="") parser.add_argument("--getpwd", type=str, default="") parser.usage = parser.format_usage().replace( "--autostart {on,off}", "--autostart={on,off}" ) args = parser.parse_args() autostart = util.get_column("autostart", pgver) app_datadir = util.get_comp_datadir(pgver) port = util.get_comp_port(pgver) ## SECURE SECRETS MANAGMENT ################################### if args.setpwd > "": pwdargs = args.setpwd.split() if len(pwdargs) != 2: util.message("invalid --setpwd args", "error") sys.exit(1) user = pwdargs[0] pwd = pwdargs[1] util.change_pgpassword(pwd, p_user=user, p_port=port, p_ver=pgver) sys.exit(0) if args.getpwd > "": pwdargs = args.getpwd.split() if len(pwdargs) != 1: util.message("invalid --getpwd args", "error") sys.exit(1) user = pwdargs[0] pwd = util.retrieve_pgpassword(p_user=user, p_port=port) if pwd == None: util.message("not found", "error") else: util.message(pwd, "pwd") sys.exit(0) ## IS_RUNNING ############################################### is_running = False if app_datadir != "" and util.is_socket_busy(int(port), pgver): is_running = True msg = "You cannot change the configuration when the server is running." util.message(msg, "error") sys.exit(0) ## DATADIR, PORT , LOGDIR & SVCNAME ########################### if args.datadir > "": util.set_column("datadir", pgver, args.datadir) ## PORT ################################################ if args.port > 0: util.update_postgresql_conf(pgver, args.port, False) if args.logdir > "": util.set_column("logdir", pgver, args.logdir) else: ## DATA ############################################### data_root = os.path.join(MY_HOME, "data") if not os.path.isdir(data_root): os.mkdir(data_root) ## LOGS ############################################### data_root_logs = os.path.join(data_root, "logs") if not os.path.isdir(data_root_logs): os.mkdir(data_root_logs) pg_log = os.path.join(data_root_logs, pgver) if not os.path.isdir(pg_log): os.mkdir(pg_log) util.set_column("logdir", pgver, pg_log) if args.svcname > "": util.set_column("svcname", pgver, args.svcname) ## AUTOSTART ########################################### if (args.autostart is None) or (autostart == args.autostart): sys.exit(0) systemsvc = "pg" + pgver[2:4] if args.autostart == "off": startup.remove_linux(systemsvc, pgver) else: pg_ctl = os.path.join(MY_HOME, pgver, "bin", "pg_ctl") pgdata = util.get_column("datadir", pgver) cmd_start = pg_ctl + " start -D " + pgdata + " -w -t 300" cmd_stop = pg_ctl + " stop -D " + pgdata + " -m fast" cmd_reload = pg_ctl + " reload -D " + pgdata cmd_status = pg_ctl + " status -D " + pgdata cmd_log = "-l " + pgdata + "/pgstartup.log" # svcuser = util.get_column('svcuser', pgver) svcuser = util.get_user() startup.config_linux( pgver, systemsvc, svcuser, cmd_start, cmd_log, cmd_stop, cmd_reload, cmd_status ) util.set_column("svcname", pgver, systemsvc) util.set_column("autostart", pgver, args.autostart) sys.exit(0)
pgEdge/nodectl
src/pgXX/config-pgXX.py
config-pgXX.py
py
4,102
python
en
code
7
github-code
1
[ { "api_name": "os.getenv", "line_number": 12, "usage_type": "call" }, { "api_name": "os.getenv", "line_number": 13, "usage_type": "call" }, { "api_name": "os.path.join", "line_number": 15, "usage_type": "call" }, { "api_name": "os.path", "line_number": 15, ...
43751970541
#!/usr/bin/env python3 """ Scraper for the 'The Flavor Bible'. Created by Jon. """ import json import os import re import sqlite3 import sys import ebooklib from ebooklib import epub from bs4 import BeautifulSoup latest_id = 0 def createTables(c): c.execute('''CREATE TABLE ingredients( id int PRIMARY KEY, name text UNIQUE, season text, taste text, weight text, volume text, vegetarian boolean, dairy boolean, kosher boolean, nuts boolean )''') c.execute('''CREATE TABLE matches( firstIngredient int, secondIngredient int, level int, upvotes int, downvotes int, affinity text, quote text, PRIMARY KEY(firstIngredient, secondIngredient) )''') def fixName(s): s = s.lower() if ' and ' in s: index = s.find(' and ') s = s[:index] if ' —' in s: index = s.find(' —') s = s[:index] if ', esp.' in s: index = s.find(', esp.') s = s[:index] if ', (' in s: index = s.find(', (') s = s[:index] elif ' (' in s: index = s.find(' (') s = s[:index] if ', e.g.' in s: index = s.find(', e.g.') s = s[:index] elif ' (e.g.' in s: index = s.find(' (e.g.') s = s[:index] if bool(re.search('\(.*\)', s)): s = re.sub(r'\s?\(.*\)', '', s) if s.count(',') == 1 and s.count(':') == 0: index = s.find(',') s = s[index+2:]+' '+s[:index] return s def containsBlacklistedString(s): blacklistedStrings = [':', ' and ', ' or ', '/' ] if any(str in s for str in blacklistedStrings): return True elif s.count(','): return True elif not s.strip(): return True else: return False def hasBlacklistedClass(sibling): blacklistedClasses = ['ul3', 'p1', 'ca', 'ca3', 'ep', 'eps', 'h3', 'img', 'boxh', 'ext', 'exts', 'ext4', 'bl', 'bl1', 'bl3', 'sbh', 'sbtx', 'sbtx1', 'sbtx3', 'sbtx4', 'sbtx11', 'sbtx31'] if any(c == sibling['class'] for c in blacklistedClasses): return True else: return False def addMatches(ingredients, matches, ingredient_ids, id, i, s, match_level): global latest_id s = fixName(s) if s in ingredient_ids: match_id = ingredient_ids[s] else: match_id = latest_id ingredients[match_id] = { 'tmpId': match_id, 'name': s.lower(), 'season': '', 'taste': '', 'weight': '', 'volume': '', 'vegetarian': True, 'dairy': False, 'kosher': False, 'nuts': False } ingredient_ids[s] = match_id latest_id += 1 match1 = str(id) + '_' + str(match_id) match2 = str(match_id) + '_' + str(id) if not match1 in matches: matches[match1] = { 'firstIngredient': id, 'secondIngredient': match_id, 'matchName': '', 'level': match_level, 'upvotes': 0, 'downvotes': 0, 'affinity': '', 'quote': '' } if not match2 in matches: matches[match2] = { 'firstIngredient': match_id, 'secondIngredient': id, 'matchName': '', 'level': match_level, 'upvotes': 0, 'downvotes': 0, 'affinity': '', 'quote': '' } def removeExistingFiles(files): for f in files: if os.path.isfile(f): os.remove(f) def writeResultsToJSON(filename, data): results = {} results['results'] = [] for key in data: row = data[key] results['results'].append(row) with open(filename, 'w') as jsonfile: json.dump(results, jsonfile, indent=4) def writeUpdatesToJSON(filename, data): results = {} results['results'] = [] for item in data: results['results'].append(item) with open(filename, 'w') as jsonfile: json.dump(results, jsonfile, indent=4) def loadResultsFromJSON(filename): with open(filename) as file: results = json.load(file) return results['results'] def writeIngredientsToTable(c, data): for key in data: row = data[key] c.execute("INSERT INTO ingredients VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % (row['tmpId'], row['name'], row['season'], row['taste'], row['weight'], row['volume'], row['vegetarian'], row['dairy'], row['kosher'], row['nuts'])) def writeMatchesToTable(c, data): for key in data: row = data[key] c.execute("INSERT INTO matches VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s')" % (row['firstIngredient'], row['secondIngredient'], row['level'], row['upvotes'], row['downvotes'], row['affinity'], row['quote'])) def updateMatchesToUseParseData(matches, parseIngredients): for match in matches: i_ingredient = next( (i for i in parseIngredients if i['tmpId'] == match['firstIngredient']) ) m_ingredient = next( (i for i in parseIngredients if i['tmpId'] == match['secondIngredient']) ) match['firstIngredient'] = { "__type": "Pointer", "className": "Ingredient", "objectId": i_ingredient['objectId'] } match['secondIngredient'] = { "__type": "Pointer", "className": "Ingredient", "objectId": m_ingredient['objectId'] } # match['ingredientId'] = i_ingredient['objectId'] # match['matchId'] = m_ingredient['objectId'] match['matchName'] = m_ingredient['name'] if __name__ == '__main__': if len(sys.argv) > 1 and sys.argv[1] == 'update': parseIngredients = loadResultsFromJSON('Ingredient.json') matches = loadResultsFromJSON('Match_tmp.json') updateMatchesToUseParseData(matches, parseIngredients) writeUpdatesToJSON('Match.json', matches) else: global latest_id ingredients = {} matches = {} ingredient_ids = {} ingredients_fieldnames = ['tmpId', 'name', 'season', 'taste', 'weight', 'volume', 'vegetarian', 'dairy', 'kosher', 'nuts'] matches_fieldnames = ['firstIngredient', 'secondIngredient', 'level', 'upvotes', 'downvotes', 'affinity', 'quote'] removeExistingFiles(['flavorbible.db', 'Ingredient_tmp.json', 'Match_tmp.json']) conn = sqlite3.connect('flavorbible.db') c = conn.cursor() createTables(c) book = epub.read_epub('flavorbible.epub') result = '' for item in book.get_items(): type = item.get_type() if type == ebooklib.ITEM_DOCUMENT: soup = BeautifulSoup(item.content, 'lxml') # Find ingredient listings. for ingredient in soup.find_all('p', {'class' : ['lh', 'lh1']}): print('HEADING: ', ingredient) i = fixName(ingredient.text) if containsBlacklistedString(i): continue if i in ingredient_ids: id = ingredient_ids[i] else: id = latest_id ingredients[id] = { 'tmpId': id, 'name': i, 'season': '', 'taste': '', 'weight': '', 'volume': '', 'vegetarian': True, 'dairy': False, 'kosher': False, 'nuts': False } ingredient_ids[i] = id latest_id += 1 # Find what goes well with these ingredients. sibling = ingredient.find_next_sibling() while sibling != None: s = sibling.text try: if sibling['class'] in (['lh'], ['lh1']): break except: break print('content: ', sibling) # season, taste, weight, volume if s.startswith('Season:'): ingredients[id]['season'] = s[8:] elif s.startswith('Taste:'): ingredients[id]['taste'] = s[7:] elif s.startswith('Weight:'): ingredients[id]['weight'] = s[8:] elif s.startswith('Volume:'): ingredients[id]['volume'] = s[8:] elif s.startswith('Tips:'): sibling = sibling.find_next_sibling() continue elif s.startswith('Techniques:'): sibling = sibling.find_next_sibling() continue elif hasBlacklistedClass(sibling): sibling = sibling.find_next_sibling() continue # flavor affinities elif sibling['class'] == ['h4']: sibling = sibling.find_next_sibling() while sibling != None: try: if sibling.find_next_sibling()['class'] in (['lh'], ['lh1'], ['p1']): break except: break sibling = sibling.find_next_sibling() sibling = sibling.find_next_sibling() continue elif containsBlacklistedString(fixName(s)): sibling = sibling.find_next_sibling() continue if sibling['class'] == ['ul'] or sibling['class'] == ['ul1']: if sibling.find('strong') == None: # match-low addMatches(ingredients, matches, ingredient_ids, id, i, s, 1) elif s.islower(): # match-medium addMatches(ingredients, matches, ingredient_ids, id, i, s, 2) elif s.isupper() and s.startswith('*') == False: # match-high addMatches(ingredients, matches, ingredient_ids, id, i, s, 3) elif s.isupper() and s.startswith('*') == True: # match-holy addMatches(ingredients, matches, ingredient_ids, id, i, s[1:], 4) sibling = sibling.find_next_sibling() print('') writeResultsToJSON('Ingredient_tmp.json', ingredients) writeResultsToJSON('Match_tmp.json', matches) writeIngredientsToTable(c, ingredients) writeMatchesToTable(c, matches) conn.commit() conn.close()
tristanchu/FlavorFinder
dev/scraper.py
scraper.py
py
11,938
python
en
code
2
github-code
1
[ { "api_name": "re.search", "line_number": 75, "usage_type": "call" }, { "api_name": "re.sub", "line_number": 76, "usage_type": "call" }, { "api_name": "os.path.isfile", "line_number": 158, "usage_type": "call" }, { "api_name": "os.path", "line_number": 158, ...
74407308832
from fastapi import Depends, FastAPI app = FastAPI() """ # Dependency injection: a function that abstracts logic and can be provided to # other functions as dependency. Whenever a new request arrives to a function that includes a dependency, fastAPI runs the dependency function with the corresponding parameters, and it then assign the result of this dependency as path parameters to the view func. """ async def common_parameters(q: str = None, skip: int = 0, limit: int = 100): return {"q": q, "skip": skip, "limit": limit} @app.get("/items/") async def read_items(commons: dict = Depends(common_parameters)): """ Declare the dependency in the dependant """ return commons @app.get("/users/") async def read_users(commons: dict = Depends(common_parameters)): return commons """ Dependencies that don't relate to the path parameters, or that don't return anything but still need to be ran before the request, can be added as a list to the decorator """ async def verify_token(x_token: str = Header(...)): if x_token != "fake-super-secret-token": raise HTTPException(status_code=400, detail="X-Token header invalid") async def verify_key(x_key: str = Header(...)): if x_key != "fake-super-secret-key": raise HTTPException(status_code=400, detail="X-Key header invalid") return x_key @app.get("/items/", dependencies=[Depends(verify_token), Depends(verify_key)]) async def read_items(): return [{"item": "Foo"}, {"item": "Bar"}] """ Deependencies with `yield`: if a dependency has some code that needs to run before the response is sent, and some that needs to run after, can use the yield keyword. Everything that is before (and up to) the yield keyword will run before sending the response, and anything that's after will run after """ async def get_db(): db = DBSession() try: # This yielded value is injected into path operations and other deps. yield db finally: db.close()
jcaguirre89/learning-fastapi
another_app/dependency.py
dependency.py
py
1,980
python
en
code
0
github-code
1
[ { "api_name": "fastapi.FastAPI", "line_number": 3, "usage_type": "call" }, { "api_name": "fastapi.Depends", "line_number": 19, "usage_type": "call" }, { "api_name": "fastapi.Depends", "line_number": 25, "usage_type": "call" }, { "api_name": "fastapi.Depends", ...
4832434614
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='PyVerilator', version='0.7.0', description='Python interface to Verilator models', long_description=long_description, url='https://github.com/csail-csg/pyverilator', author='CSAIL CSG', author_email='acwright@mit.edu, bthom@mit.edu', # https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'Topic :: System :: Hardware', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], keywords='Verilator Wrapper Verilog', packages=find_packages(exclude=['examples']), include_package_data=True, install_requires=['tclwrapper>=0.0.1'], setup_requires=['pytest-runner'], tests_require=['pytest'], entry_points={ # If we ever want to add an executable script, this is where it goes }, project_urls={ 'Bug Reports': 'https://github.com/csail-csg/pyverilator/issues', 'Source': 'https://github.com/csail-csg/pyverilator', }, )
csail-csg/pyverilator
setup.py
setup.py
py
1,497
python
en
code
64
github-code
1
[ { "api_name": "os.path.abspath", "line_number": 7, "usage_type": "call" }, { "api_name": "os.path", "line_number": 7, "usage_type": "name" }, { "api_name": "os.path.dirname", "line_number": 7, "usage_type": "call" }, { "api_name": "codecs.open", "line_number":...
24402276077
import os import numpy as np import pandas as pd from catboost import CatBoost, Pool import matplotlib.pylab as plt from model import Model from util import Util class ModelCatBoost(Model): def train(self, tr_x, tr_y, va_x=None, va_y=None): # ハイパーパラメータの設定 params = dict(self.params) cat_features = params.pop("cat_features") print(cat_features.index) # データのセット validation = va_x is not None dtrain = Pool(tr_x, tr_y, cat_features=cat_features) if validation: dvalid = Pool(va_x, va_y, cat_features=cat_features) # 学習 self.model = CatBoost(params) if validation: self.model.fit( dtrain, eval_set=dvalid, use_best_model=True, # 最も精度が高かったモデルを使用するかの設定 ) else: self.model.fit( dtrain, use_best_model=True, # 最も精度が高かったモデルを使用するかの設定 ) def predict(self, te_x): return self.model.predict(te_x,) def save_model(self, model_dir="../model/model"): model_path = os.path.join(model_dir, f"{self.run_fold_name}.model") os.makedirs(os.path.dirname(model_path), exist_ok=True) # best_ntree_limitが消えるのを防ぐため、pickleで保存することとした Util.dump(self.model, model_path) def load_model(self, model_dir="../model/model"): model_path = os.path.join(model_dir, f"{self.run_fold_name}.model") self.model = Util.load(model_path) @classmethod def save_plot_importance( cls, model_path, feature_names, png_path=None, is_Agg=True, height=0.5, figsize=(8, 16), ): """catboostのモデルファイルからモデルロードしてfeature importance plot""" model = Util.load(model_path) if is_Agg: import matplotlib matplotlib.use("Agg") # 特徴量の重要度を取得する feature_importance = model.get_feature_importance() # print(feature_importance) # print(feature_names) # 棒グラフとしてプロットする plt.figure(figsize=figsize) plt.barh( range(len(feature_importance)), feature_importance, tick_label=feature_names, height=height, ) plt.xlabel("importance") plt.ylabel("features") plt.grid() if png_path is not None: plt.savefig( png_path, bbox_inches="tight", pad_inches=0, ) # bbox_inchesなどは余白削除オプション plt.show()
riron1206/lgb_tuning
src/model_catboost.py
model_catboost.py
py
2,770
python
ja
code
0
github-code
1
[ { "api_name": "model.Model", "line_number": 12, "usage_type": "name" }, { "api_name": "catboost.Pool", "line_number": 22, "usage_type": "call" }, { "api_name": "catboost.Pool", "line_number": 24, "usage_type": "call" }, { "api_name": "catboost.CatBoost", "line...
25623285903
""" Google Forms Interaction Module This module provides functionalities to interact with Google Forms, specifically to fetch responses from a designated form. The primary purpose is to retrieve sign-up responses, which are then used in the main application for sending out notifications. Key Features: - Authentication using OAuth2 to ensure secure access to Google Forms data. - Ability to refresh expired tokens automatically. - Parsing of form responses to extract relevant data, such as email addresses and names. Dependencies: - google.oauth2.credentials: For handling OAuth2 credentials. - google.auth.transport.requests: To make authorized requests. - requests: For making HTTP requests to the Google Forms API. - settings.app_secrets: To access application-specific secrets and configurations. Note: Ensure that the 'token.json' file with authentication credentials is present in the root directory before using this module. Additionally, replace placeholders like 'YOUR_FORM_ID' with actual values before deploying. """ import logging import os.path import requests from google.oauth2.credentials import Credentials from google.auth.transport.requests import Request GOOGLE_FORMS_API_BASE_URL = "https://forms.googleapis.com/v1/forms" def _load_credentials(scopes): """ Load or refresh Google API credentials. """ creds = None if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', scopes) return creds def get_sign_up_responses(): """ Fetches sign-up responses from a specified Google Form. This function retrieves form responses using the Google Forms API. It returns a dictionary where the keys are the emails of the respondents and the values are their corresponding names. The method first checks for valid credentials and refreshes them if needed. Then, it queries the Google Forms API and processes the received responses. Returns: dict: A dictionary with emails as keys and names as values. If there are any errors or if no data is found, it'll return an empty dictionary. Raises: ValueError: If there are invalid or missing credentials. requests.HTTPError: If there's an HTTP error when making the request. ConnectionError: If there's a connection issue when making the request. requests.Timeout: If the request times out. """ scopes = ["https://www.googleapis.com/auth/forms.responses.readonly"] creds = _load_credentials(scopes) if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) with open('token.json', 'w', encoding="utf-8") as token: token.write(creds.to_json()) else: raise ValueError("Invalid or missing credentials") url = f"{GOOGLE_FORMS_API_BASE_URL}/{os.environ.get('GOOGLE_SIGN_UP_FORM_ID')}/responses" headers = { 'Authorization': f'Bearer {creds.token}', 'Accept': 'application/json' } try: logging.info("Fetching sign-up responses from Google Form.") response = requests.get(url, headers=headers, timeout=30) response.raise_for_status() data = response.json() responses = data.get('responses', []) email_to_name = {} for resp in responses: email_answer = resp.get('respondentEmail') # Using a placeholder for the key; replace with the actual key from your form name_answer_key = '778b574a' name_answer = resp.get('answers', {}).get(name_answer_key, {}).get('textAnswers', {}).get('answers', [{}])[0].get('value') if email_answer and name_answer: email_to_name[email_answer] = name_answer return email_to_name except (requests.HTTPError, ConnectionError, requests.Timeout) as ex: logging.error('Specific error in get_form_responses: %s', ex) except Exception as ex: logging.error('Unexpected error in get_form_responses: %s', ex) return {}
StevenWangler/snow_day_bot
google_functions/google_forms.py
google_forms.py
py
4,128
python
en
code
0
github-code
1
[ { "api_name": "os.path.path.exists", "line_number": 39, "usage_type": "call" }, { "api_name": "os.path.path", "line_number": 39, "usage_type": "attribute" }, { "api_name": "os.path", "line_number": 39, "usage_type": "name" }, { "api_name": "google.oauth2.credentia...
16239780344
import os import sys import PIL import time import random import logging import datetime import os.path as osp import torch import torch.backends import torch.nn as nn import torch.backends.cudnn import torch.distributed as dist from utils.loss import OhemCELoss from utils.utils import prepare_seed from utils.utils import time_for_file from evaluate_distributed import MscEval from dataloaders import make_data_loader from utils.logger import Logger, setup_logger from utils.optimizer_distributed import Optimizer from config_utils.retrain_config import config_factory from retrain_model.build_autodeeplab import Retrain_Autodeeplab from config_utils.re_train_autodeeplab import obtain_retrain_autodeeplab_args def main(): args = obtain_retrain_autodeeplab_args() torch.cuda.set_device(args.local_rank) cfg = config_factory['resnet_cityscapes'] if not os.path.exists(cfg.respth): os.makedirs(cfg.respth) dist.init_process_group( backend='nccl', init_method='tcp://127.0.0.1:{}'.format(cfg.port), world_size=torch.cuda.device_count(), rank=args.local_rank ) setup_logger(cfg.respth) logger = logging.getLogger() rand_seed = random.randint(0, args.manualSeed) prepare_seed(rand_seed) if args.local_rank == 0: log_string = 'seed-{}-time-{}'.format(rand_seed, time_for_file()) train_logger = Logger(args, log_string) train_logger.log('Arguments : -------------------------------') for name, value in args._get_kwargs(): train_logger.log('{:16} : {:}'.format(name, value)) train_logger.log("Python version : {}".format(sys.version.replace('\n', ' '))) train_logger.log("Pillow version : {}".format(PIL.__version__)) train_logger.log("PyTorch version : {}".format(torch.__version__)) train_logger.log("cuDNN version : {}".format(torch.backends.cudnn.version())) train_logger.log("random_seed : {}".format(rand_seed)) if args.checkname is None: args.checkname = 'deeplab-' + str(args.backbone) # dataset kwargs = {'num_workers': args.workers, 'pin_memory': True, 'drop_last': True} train_loader, args.num_classes, sampler = make_data_loader(args=args, **kwargs) # model model = Retrain_Autodeeplab(args) model.train() model.cuda() model = nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank, ], output_device=args.local_rank, find_unused_parameters=True).cuda() n_min = cfg.ims_per_gpu * cfg.crop_size[0] * cfg.crop_size[1] // 16 criterion = OhemCELoss(thresh=cfg.ohem_thresh, n_min=n_min).cuda() max_iteration = int(cfg.max_epoch * len(train_loader)) # max_iteration = int(1500000 * 4 // cfg.gpus) it = 0 # optimizer optimizer = Optimizer(model, cfg.lr_start, cfg.momentum, cfg.weight_decay, cfg.warmup_steps, cfg.warmup_start_lr, max_iteration, cfg.lr_power) if dist.get_rank() == 0: print('======optimizer launch successfully , max_iteration {:}!======='.format(max_iteration)) # train loop loss_avg = [] start_time = glob_start_time = time.time() # for it in range(cfg.max_iter): if args.resume is not None: checkpoint = torch.load(args.resume, map_location='cpu') if checkpoint['iter'] is not None: args.train_mode = 'iter' start_iter = checkpoint['iter'] n_epoch = checkpoint['epoch'] elif checkpoint['epoch'] is not None: args.train_mode = 'epoch' model.module.load_state_dict(checkpoint['state_dict']) optimizer.load_state_dict(checkpoint['optimizer'], checkpoint['iter']) else: if args.train_mode == 'iter': start_iter = 0 n_epoch = 0 elif args.train_mode == 'epoch': start_epoch = 0 if args.train_mode is 'iter': diter = iter(train_loader) for it in range(start_iter, cfg.max_iter): try: sample = next(diter) except StopIteration: n_epoch += 1 sampler.set_epoch(n_epoch) diter = iter(train_loader) sample = next(diter) im, lb = sample['image'].cuda(), sample['label'].cuda() lb = torch.squeeze(lb, 1) optimizer.zero_grad() logits = model(im) loss = criterion(logits, lb) loss.backward() optimizer.step() loss_avg.append(loss.item()) # print training log message if it % cfg.msg_iter == 0 and not it == 0 and dist.get_rank() == 0: loss_avg = sum(loss_avg) / len(loss_avg) lr = optimizer.lr ed = time.time() t_intv, glob_t_intv = ed - start_time, ed - glob_start_time eta = int((max_iteration - it) * (glob_t_intv / it)) eta = str(datetime.timedelta(seconds=eta)) msg = ', '.join(['iter: {it}/{max_iteration}', 'lr: {lr:4f}', 'loss: {loss:.4f}', 'eta: {eta}', 'time: {time:.4f}', ]).format(it=it, max_iteration=max_iteration, lr=lr, loss=loss_avg, time=t_intv, eta=eta) # TODO : now the logger.info will error if iter > 350000, so use print haha if max_iteration > 350000: logger.info(msg) else: print(msg) loss_avg = [] it += 1 if (cfg.msg_iter is not None) and (it % cfg.msg_iter == 0) and (it != 0): if args.verbose: logger.info('evaluating the model of iter:{}'.format(it)) model.eval() evaluator = MscEval(cfg, args) mIOU, loss = evaluator(model, criteria=criterion, multi_scale=False) logger.info('mIOU is: {}, loss_eval is {}'.format(mIOU, loss)) model.cpu() save_name = 'iter_{}_naive_model.pth'.format(it) save_pth = osp.join(cfg.respth, save_name) state = model.module.state_dict() if hasattr(model, 'module') else model.state_dict() checkpoint = {'state_dict': state, 'epoch': n_epoch, 'iter': it, 'optimizer': optimizer.optim.state_dict()} if dist.get_rank() == 0: torch.save(state, save_pth) logger.info('model of iter {} saved to: {}'.format(it, save_pth)) model.cuda() model.train() elif args.train_mode is 'epoch': for epoch in range(start_epoch, cfg.max_epoch): for i, sample in enumerate(train_loader): im = sample['image'].cuda() lb = sample['label'].cuda() lb = torch.squeeze(lb, 1) optimizer.zero_grad() logits = model(im) loss = criterion(logits, lb) loss.backward() optimizer.step() loss_avg.append(loss.item()) # print training log message if i % cfg.msg_iter == 0 and not (i == 0 and epoch == 0) and dist.get_rank() == 0: loss_avg = sum(loss_avg) / len(loss_avg) lr = optimizer.lr ed = time.time() t_intv, glob_t_intv = ed - start_time, ed - glob_start_time eta = int((max_iteration - it) * (glob_t_intv / it)) eta = str(datetime.timedelta(seconds=eta)) msg = ', '.join(['iter: {it}/{max_iteration}', 'lr: {lr:4f}', 'loss: {loss:.4f}', 'eta: {eta}', 'time: {time:.4f}', ]).format(it=it, max_iteration=max_iteration, lr=lr, loss=loss_avg, time=t_intv, eta=eta) logger.info(msg) loss_avg = [] # save model and optimizer each epoch if args.verbose: logger.info('evaluating the model of iter:{}'.format(it)) model.eval() evaluator = MscEval(cfg, args) mIOU, loss = evaluator(model, criteria=criterion, multi_scale=False) logger.info('mIOU is: {}, loss_eval is {}'.format(mIOU, loss)) model.cpu() save_name = 'iter_{}_naive_model.pth'.format(it) save_pth = osp.join(cfg.respth, save_name) state = model.module.state_dict() if hasattr(model, 'module') else model.state_dict() checkpoint = {'state_dict': state, 'epoch': n_epoch, 'iter': it, 'optimizer': optimizer.state_dict()} if dist.get_rank() == 0: torch.save(state, save_pth) logger.info('model of iter {} saved to: {}'.format(it, save_pth)) model.cuda() model.train() else: raise NotImplementedError if __name__ == "__main__": main()
NoamRosenberg/autodeeplab
train_distributed.py
train_distributed.py
py
8,976
python
en
code
306
github-code
1
[ { "api_name": "config_utils.re_train_autodeeplab.obtain_retrain_autodeeplab_args", "line_number": 29, "usage_type": "call" }, { "api_name": "torch.cuda.set_device", "line_number": 30, "usage_type": "call" }, { "api_name": "torch.cuda", "line_number": 30, "usage_type": "at...
15616079630
import multiprocessing as processing from multiprocessing import pool,Process import math import numpy as np import gzip import pickle import sys from scipy import integrate import time,random import h5py import threading import os.path import _pickle as cpickle from scipy import spatial from multiprocessing import Process import multiprocessing def log10(x): if x > 0: return math.log10(x) else: return -np.inf def exp(x): try: return math.exp(x) except: return np.inf def Mpeak_log_to_Vpeak_log(Mpeak_log): return 0.3349 * Mpeak_log - 1.672 G = 4.301 * 10 ** (-9) cons = (4 * G * np.pi / (3 * (1 / 24 / (1.5 * 10 ** (11))) ** (1 / 3))) ** 0.5 def calculate_v_dispersion(Mh): return Mh ** (1 / 3) * cons exp = np.vectorize(exp) log10 = np.vectorize(log10) plot_path = "/Users/caojunzhi/Downloads/upload_201903_Jeremy/" # data path if os.path.isdir("/Volumes/SSHD_2TB") == True: print("The code is on Spear of Adun") ## Move to Data_10TB data_path = "/Volumes/Data_10TB/" elif os.path.isdir("/mount/sirocco1/jc6933/test") == True: data_path = "/mount/sirocco2/jc6933/Data_sirocco/" print("The code is on Sirocco") # Kratos elif os.path.isdir("/home/jc6933/test_kratos") == True: data_path = "/mount/kratos/jc6933/Data/" print("The code is on Kratos") # Void Seeker elif os.path.isdir("/home/jc6933/test_Void_Seeker") == True: data_path = "/mount/Void_Seeker/Data_remote/" print("The code is on Void Seeker") else: print("The code is on local") data_path = "/Volumes/Extreme_SSD/Data/" print("data_path %s" % data_path) save_path = data_path + "KD/" class KD_search(): def __init__(self): #read data: hf_Bolshoi = h5py.File(data_path + "C250_with_concentration.h5", "r") data_Bolshoi = np.array(hf_Bolshoi["dataset"])[:, 1:7] Mpeak = np.array(hf_Bolshoi["Mpeak"]) Mvir = np.array(hf_Bolshoi["M_vir"]) Vpeak = np.array(hf_Bolshoi["Vpeak"]) upid = np.array(hf_Bolshoi["upid"], dtype=int) halo_concentration = np.array(hf_Bolshoi["halo_concentration"], dtype=float) Acc_Rate_Inst = np.array(hf_Bolshoi["Acc_Rate_Inst"], dtype=float) hf_Bolshoi.close() Mvir_log = log10(Mvir) pkl_file = open(data_path + "R_vir_z0_C250.pkl", 'rb') R_vir = pickle.load(pkl_file) pkl_file.close() pkl_file = open(data_path + "Mpeak/" + "Ms_log_C250_M_peak_combined_v1.pkl", 'rb') Ms_all_log = pickle.load(pkl_file) pkl_file.close() select = random.sample(range(0, len(R_vir) - 1), 100000) Mh_rate = Acc_Rate_Inst fb = 0.16 Ms_rate = fb * Mh_rate sSFR = Ms_rate / Ms_all_log data_250 = data_Bolshoi[:, 0:3] """ print("Constructing KD tree") tree_250 = spatial.KDTree(data_250) raw_250 = pickle.dumps(tree_250) # save it: file_path_250 = save_path + "kd_C250.pkl" max_bytes = 2 ** 31 - 1 print("saving Bolshoi") ## write bytes_out = pickle.dumps(raw_250) with open(file_path_250, 'wb') as f_out: for idx in range(0, len(bytes_out), max_bytes): f_out.write(bytes_out[idx:idx + max_bytes]) ## """ print("reading tree") file_path_250 = save_path + "kd_C250.pkl" pkl_file = open(file_path_250, 'rb') raw = cpickle.load(pkl_file) pkl_file.close() tree_load_250 = cpickle.loads(raw) self.tree_load_250 = tree_load_250 # calculate density: Be careful about the periodic condition: mask_cen = upid < 0 ## Only calculate trees with halo mass bigger than 11.0 and in boundary: x = data_250[:, 0] y = data_250[:, 1] z = data_250[:, 2] self.x = x self.y = y self.z = z # For everything! mask = upid<0 self.data_250_central = data_250[mask,:] N_tot = len(self.data_250_central[:, 0]) self.N_tot = N_tot self.N = N_tot self.data_250 = data_250 self.Ms_all_log = Ms_all_log self.dict_results = {} self.dict_results_mass = {} def calculate_density(self,N_thread,N_start,N_stop): density_array = [] density_array_mass = [] for i in range(N_start, N_stop): if i % 100 == 0: print("Doing %d of %d for thread %d" % (i - N_start, N_stop - N_start, N_thread)) index = self.tree_load_250.query_ball_point(self.data_250_central[i, :], r=10) index = [item for item in index if item not in [i]] Ms_tot = np.nansum(10 ** self.Ms_all_log[index]) density_array_mass.append(Ms_tot) density_array.append(len(index)) density_array = np.array(density_array) density_array_mass = np.array(density_array_mass) final_results[str(N_thread)] = density_array final_results_mass[str(N_thread)] = density_array_mass model = KD_search() input = sys.argv try: thread_to_use = int(input[1]) except: thread_to_use = 24 print("Total threads %d and total numbers %d"%(thread_to_use,model.N_tot)) bin_size = model.N_tot//thread_to_use my_pool = [] manager = multiprocessing.Manager() final_results = manager.dict() manager_2 = multiprocessing.Manager() final_results_mass = manager_2.dict() for ni in range(0,thread_to_use): if ni<thread_to_use-1: pi = Process(target=model.calculate_density, args=(ni, ni * bin_size, ni * bin_size + bin_size)) my_pool.append(pi) pi.start() else: pi = Process(target=model.calculate_density, args=(ni, ni * bin_size, model.N)) my_pool.append(pi) pi.start() # join and wait until all threads are done: for ni in range(0,thread_to_use): my_pool[ni].join() ##Done print("All threads done") # add each chunks together density_array_all = [] for x in range(0, thread_to_use): density_array_all.extend(final_results[str(x)]) density_array_all = np.array(density_array_all) # save in txt is good since the size is not big: np.savetxt(data_path+"KD/"+"density_C250_multithread_v1.txt",density_array_all) density_array_mass_all = [] for x in range(0, thread_to_use): density_array_mass_all.extend(final_results_mass[str(x)]) density_array_mass_all = np.array(density_array_mass_all) # save in txt is good since the size is not big: np.savetxt(data_path+"KD/"+"density_C250_multithread_mass_v1.txt",density_array_mass_all)
peraktong/Multi_thread_examples
0327_calculate_density_Kd_tree_multi_process_doable_v1.py
0327_calculate_density_Kd_tree_multi_process_doable_v1.py
py
6,624
python
en
code
0
github-code
1
[ { "api_name": "math.log10", "line_number": 19, "usage_type": "call" }, { "api_name": "numpy.inf", "line_number": 21, "usage_type": "attribute" }, { "api_name": "math.exp", "line_number": 26, "usage_type": "call" }, { "api_name": "numpy.inf", "line_number": 28,...
27836865388
import regex as re from bs4 import BeautifulSoup import requests import requests_futures import aiohttp import asyncio from requests_futures.sessions import FuturesSession import tree import json trees = [] valid_regex = r"^https?\:\/\/([\w\.]+)wikipedia.org\/wiki\/([\w]+\_?)+" links = dict() loop = asyncio.get_event_loop() def check_valid(link): if re.split(valid_regex, link): respond = requests.get(link) if respond.status_code != 200: return True else: return True def check_valid_int(intvalue): if intvalue>=1 and intvalue<=20: return True """ its my bad tryis without good asyncio async def run_link(link): try: response = await requests.get(link) links = [] soup = BeautifulSoup(response.text, "html.parser") links_ = soup.find(id="bodyContent").find_all("a") for link in links_: if 'href' in link.attrs: if link.attrs['href'].startswith('/wiki/')and check_valid("https://en.wikipedia.org" + link['href']): links.append("https://en.wikipedia.org" + link['href']) elif link.attrs['href'].startswith('https') and check_valid(link['href']): #DO IT WITH WIKIIIIIIIII links.append(link['href']) return links except: print("An exception occurred") finally: return links def appendaslist(links): async_list = [] for i in links: async_list.append(loop.create_task(run_link(i))) return async_list async def main(n,link): #action_item =requestsf.get(link, hooks={'link': run_link}) links[link] = run_link(link) async_list = [] async_list = appendaslist(links[link]) loop.run_until_complete(asyncio.gather(*async_list)) #async_list.append(action_item) for i in range(1,n): # async with aiohttp.ClientSession() as session: tasks = [] for c in list(links.keys()): for j in list(links[c]): if j not in checkset: appendlink =run_link(j) async_list.append(loop.create_task(run_link(j))) loop.run_until_complete(asyncio.gather(*async_list)) links[j] = appendlink checkset.update(appendlink) print(links) print(links) async def check_valida(session,link): async with session.get(link) as resp: if re.split(valid_regex, link): if resp.status_code != 200: return False else: return False """ async def run_linkas(session,link): async with session.get(link) as resp: response = await resp.text() links = [] soup = BeautifulSoup(response, "html.parser") links_ = soup.find(id="bodyContent").find_all('a', href=True) for link1 in links_: if 'href' in link1.attrs: if link1.attrs['href'].startswith('/wiki/'):#and check_valida(session,"https://en.wikipedia.org" + link['href']): links.append("https://en.wikipedia.org" + link1['href']) elif link1.attrs['href'].startswith('https://en.wikipedia') :#and check_valida(session,link['href']): #DO IT WITH WIKIIIIIIIII links.append(link1['href']) return link,links async def mains(url, n): checksett = set() checkset = set() trees = [] allofall = {} async with aiohttp.ClientSession() as session: pokemon_url = [url] checksett.add(url) allofall[url] = [url] for i in range(0,n): tasks=[] for j in pokemon_url: if j not in checkset: tasks.append(asyncio.ensure_future(run_linkas(session, j))) original_pokemon = await asyncio.gather(*tasks) checkset |= checksett for pokemon in original_pokemon: pokemon_url =pokemon[1] #trees += pokemon[1] checksett |= set(pokemon[1]) allofall[pokemon[0]] = pokemon_url # for x in allofall: \\ its to print # print(x) # print(x, ':', allofall[x]) return allofall def savejson(namefile, data): with open(namefile, 'w+') as fp: json.dump(data, fp) if __name__ == "__main__": global checkset checkset = set() input_link = input("Input Wiki link: ") if check_valid(input_link): print("Url is not valid, please enter valid url") else: input_int = int(input("Input Integer link: ")) if check_valid_int(input_int): data = asyncio.run(mains(input_link,input_int)) savejson(r"D:\testtask\testtask\data.json",data) else: print("Int is not valid, please enter valid int from 1 to 20")
LyudmilaTretyakova/testtask
script.py
script.py
py
4,831
python
en
code
0
github-code
1
[ { "api_name": "asyncio.get_event_loop", "line_number": 16, "usage_type": "call" }, { "api_name": "regex.split", "line_number": 18, "usage_type": "call" }, { "api_name": "requests.get", "line_number": 19, "usage_type": "call" }, { "api_name": "bs4.BeautifulSoup", ...
18161161348
import pandas from recordlinkage.preprocessing import clean d = {'col1': ['marry - a', 'kudo::'], 'col2': ['nam vinh', 'okee-']} df = pandas.DataFrame(data=d) s = pandas.Series(df['col1']) df['col1'] = clean(s) print(df) df['col1'][0] = "b" print(df)
aduyphm/data-integration-20212
DataHandle/test.py
test.py
py
252
python
en
code
0
github-code
1
[ { "api_name": "pandas.DataFrame", "line_number": 5, "usage_type": "call" }, { "api_name": "pandas.Series", "line_number": 6, "usage_type": "call" }, { "api_name": "recordlinkage.preprocessing.clean", "line_number": 7, "usage_type": "call" } ]
16547812246
import requests import sys import json def post_predict(host:str): ''' Sends an HTTP POST request to the /predict endpoint. ''' proto = '' if not host.startswith('http'): proto = 'http://' with open('manualtests/manual_predict_data.json', 'r') as f: data = json.loads(f.read()) response = requests.post(proto + host, json=data) return response if __name__ == '__main__': args = sys.argv print('Requesting for a prediction...') response = post_predict(host=args[1]) if response.ok: print(' ...✅ OK:', response.json()) else: print(' ...❌ failed:', response.content)
pugad/ml-golf-demo-app
manualtests/predict_manual.py
predict_manual.py
py
667
python
en
code
0
github-code
1
[ { "api_name": "json.loads", "line_number": 14, "usage_type": "call" }, { "api_name": "requests.post", "line_number": 15, "usage_type": "call" }, { "api_name": "sys.argv", "line_number": 20, "usage_type": "attribute" } ]
37639058519
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import re import sys import argparse __author__ = 'menghao' __mail__ = 'haomeng@genome.cn' bindir = os.path.abspath(os.path.dirname(__file__)) pat1 = re.compile('^\s*$') sys.path.append(bindir + '/../lib') from common import parser_fasta complement = {'A':'T','T':'A','C':'G','G':'C'} def main(): parser = argparse.ArgumentParser(usage='Locating_Restriction_Sites', description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, epilog='author:\t{0}\nmail:\t{1}'.format(__author__, __mail__)) parser.add_argument('-f', '--fasta', help='fasta format file', dest='fasta', required=True) args = parser.parse_args() Seq = parser_fasta(args.fasta).values()[0] rev_com = ''.join([complement[i] for i in Seq]) for index in range(0,len(Seq)): for length in range(4,13): sub = Seq[index:index+length] if (4<=len(sub)<=13) & (length == len(sub)): rev_com = ''.join([complement[i] for i in reversed(sub)]) if sub == rev_com: print(str(index+1) + ' ' + str(length)) if __name__ == "__main__": main()
whenfree/Rosalind
Locating_Restriction_Sites/Locating_Restriction_Sites.py
Locating_Restriction_Sites.py
py
1,287
python
en
code
0
github-code
1
[ { "api_name": "os.path.abspath", "line_number": 10, "usage_type": "call" }, { "api_name": "os.path", "line_number": 10, "usage_type": "attribute" }, { "api_name": "os.path.dirname", "line_number": 10, "usage_type": "call" }, { "api_name": "re.compile", "line_n...
17446433552
"""Tests for the config API.""" import unittest from pygame_assets.exceptions import NoSuchConfigurationParameterError from pygame_assets.configure import Config, ConfigMeta from pygame_assets.configure import get_config, config_exists, remove_config from pygame_assets.configure import get_environ_config, set_environ_config from .utils import change_config, temp_config class TestConfigMeta(unittest.TestCase): """Unit tests for the config._params API.""" def test_get_class_attributes(self): class Foo: a = 1 b = 2 __builtins_are_ignored__ = 'bar' def functions_are_ignored(): return 0 self.assertDictEqual(ConfigMeta.get_class_attributes(Foo), {'a': 1, 'b': 2}) def test_two_config_instances_are_equal(self): config1 = Config() config2 = Config() self.assertEqual(config1, config2) def test_subconfig_inherits_config_meta(self): class SubConfig(Config): name = 'sub' config = Config() subclassed = SubConfig() for param in config._meta: self.assertIn(param, subclassed._meta) self.assertEqual(subclassed._meta[param], config._meta[param]) def test_new_subconfig_parameters_are_saved(self): class SubConfig(Config): name = 'sub' class Meta: base = 'mybase' subclassed = SubConfig() self.assertEqual(subclassed._meta['base'], 'mybase') def test_subconfig_inherits_super_meta(self): with temp_config('custom', 'sub'): class SuperConfig(Config): name = 'custom' class Meta: base = 'custom/base' class SubConfig(SuperConfig): name = 'sub' superconfig = SuperConfig() subconfig = SubConfig() self.assertEqual(subconfig.base, superconfig.base) def test_not_registered_parameter_raises_exception(self): with self.assertRaises(NoSuchConfigurationParameterError): class SubConfig(Config): name = 'sub' class Meta: not_registered = 'will raise an exception' def test_config_has_meta_dict(self): config = get_config() self.assertIsNotNone(config._meta) self.assertIsInstance(config._meta, dict) def test_meta_contains_all_parameters(self): config = get_config() for param in ConfigMeta._allowed_params: self.assertIn(param, config._meta) def test_get_parameter_through_dot_notation(self): config = get_config() for param in config._meta: self.assertEqual(getattr(config, param), config._meta.get(param)) def test_set_parameter_through_dot_notation(self): name = ConfigMeta._allowed_params[0] with change_config(name) as config: setattr(config, name, 'other') self.assertEqual('other', getattr(config, name)) def test_set_parameter_propagates_accross_get_config(self): name = ConfigMeta._allowed_params[0] with change_config(name) as config: setattr(config, name, 'other') self.assertEqual(getattr(get_config(), name), 'other') def test_has_default_font_size(self): config = get_config() self.assertIsNotNone(config.default_font_size) def test_set_config_base(self): with change_config('base') as config: self.assertEqual('./assets', config.base) config.base = 'static' self.assertEqual('static', config.base) class TestConfigureUtils(unittest.TestCase): """Test configuration management utilities.""" def test_remove_config(self): class FooConfig(Config): name = 'foo' self.assertTrue(config_exists('foo')) remove_config('foo') self.assertFalse(config_exists('foo')) def test_config_exists(self): self.assertFalse(config_exists('foo')) class FooConfig(Config): name = 'foo' self.assertTrue(config_exists('foo')) remove_config('foo') class TestConfigureFromEnv(unittest.TestCase): """Test the configuration from OS environment variables.""" def setUp(self): set_environ_config(None) def test_set_environ_config(self): set_environ_config(None) self.assertIsNone(get_environ_config()) set_environ_config('foo') self.assertEqual('foo', get_environ_config()) def test_set_environ_config_to_none_is_explicit(self): with self.assertRaises(TypeError): set_environ_config() set_environ_config(None) def test_get_config_from_env_var(self): class MyConfig(Config): name = 'myconfig' set_environ_config('myconfig') config = get_config() self.assertEqual('myconfig', config.name) class TestConfigDirs(unittest.TestCase): """Unit tests for the search directory configuration.""" def test_config_dirs_is_dict_of_loader_names_and_dirs(self): config = get_config() for loader_name, dirs in config.dirs.items(): self.assertIsInstance(loader_name, str) self.assertIsInstance(dirs, list) def test_search_dirs(self): with change_config('base', 'dirs') as config: config.base = 'assets' config.dirs['spritesheet'] = ['spritesheet', 'sheets'] expected = ['assets/spritesheet', 'assets/sheets'] actual = config.search_dirs('spritesheet') self.assertListEqual(expected, actual) class TestConfigure(unittest.TestCase): """Unit tests for the Config API.""" def setUp(self): set_environ_config(None) def test_load_default_config(self): explicit_config = get_config('default') self.assertEqual(explicit_config.name, 'default') no_args_config = get_config() self.assertEqual(no_args_config.name, 'default') def test_load_test_config(self): config = get_config('test') self.assertEqual(config.name, 'test') def test_new_config_must_have_name(self): with self.assertRaises(ValueError): class ConfigWithoutName(Config): name = '' def test_new_config_is_registered_to_get_config(self): # assert custom config does not exist already with self.assertRaises(KeyError): get_config('custom') class CustomConfig(Config): name = 'custom' base = 'custom/path/to/assets' # custom config should now be available through get_config() config = get_config('custom') self.assertEqual('custom', config.name) self.assertEqual('custom/path/to/assets', config.base)
florimondmanca/pygame-assets
pygame_assets/tests/test_configure.py
test_configure.py
py
6,870
python
en
code
2
github-code
1
[ { "api_name": "unittest.TestCase", "line_number": 12, "usage_type": "attribute" }, { "api_name": "pygame_assets.configure.ConfigMeta.get_class_attributes", "line_number": 25, "usage_type": "call" }, { "api_name": "pygame_assets.configure.ConfigMeta", "line_number": 25, "u...
6048712734
from app.visual_detector.workers import ( FrameReaderThread, TowerDetectorThread, ComponentDetectorThread, DefectDetectorThread, DefectTrackingThread, ResultsProcessorThread, TiltDetectorThread, DumperClassifierThread, WoodCracksDetectorThread ) from app.visual_detector.defect_detectors import ( TowerDetector, ComponentsDetector, DumperClassifier, WoodCrackSegmenter, DefectDetector, LineModifier, ConcretePoleHandler, WoodCracksDetector ) from app.visual_detector.utils import ( Drawer, ResultSaver, ObjectTracker ) from typing import List import queue import os import uuid import time class MainDetector: def __init__( self, save_path: str, batch_size: int, detectors_to_run: List[str], search_defects: bool = True, db=None ): # Path on the server where processed data gets stored self.save_path = save_path self.search_defects = search_defects # To keep track of file processing self.progress = dict() if search_defects: self.check_defects = True # Metadata extractor could be initialized here if required else: self.check_defects = False # Initialize Qs and workers try: # --- video / image processors --- self.files_to_process_Q = queue.Queue() self.frame_to_pole_detector = queue.Queue(maxsize=2) self.pole_to_comp_detector = queue.Queue(maxsize=2) self.comp_to_defect_detector = queue.Queue(maxsize=3) self.defect_det_to_defect_tracker = queue.Queue(maxsize=2) self.defect_tracker_to_writer = queue.Queue(maxsize=2) # --- dumper classifier --- self.to_dumper_classifier = queue.Queue(maxsize=3) self.from_dumper_classifier = queue.Queue(maxsize=3) # --- tilt detector --- self.to_tilt_detector = queue.Queue(maxsize=3) self.from_tilt_detector = queue.Queue(maxsize=3) # --- wood tower cracks --- self.to_wood_cracks_detector = queue.Queue(maxsize=3) self.from_wood_cracks_detector = queue.Queue(maxsize=3) # --- conrete tower cracks --- pass except Exception as e: print(f"Failed during queue initialization. Error: {e}") raise e # Initialize detectors and auxiliary modules try: # Object detectors self.pole_detector = TowerDetector() self.component_detector = ComponentsDetector() # Defect detectors self.defect_detector = DefectDetector( running_detectors=detectors_to_run, tilt_detector=(self.to_tilt_detector, self.from_tilt_detector), dumpers_defect_detector=(self.to_dumper_classifier, self.from_dumper_classifier), wood_crack_detector=(self.to_wood_cracks_detector, self.from_wood_cracks_detector), concrete_cracks_detector=None, insulators_defect_detector=None ) # Auxiliary modules self.drawer = Drawer(save_path=save_path) self.result_saver = ResultSaver() self.object_tracker = ObjectTracker() except Exception as e: print(f"Failed during detectors initialization. Error: {e}") raise e # Initialize threads self.threads_to_run_and_join = list() try: self.frame_reader_thread = FrameReaderThread( batch_size=batch_size, in_queue=self.files_to_process_Q, out_queue=self.frame_to_pole_detector, progress=self.progress ) self.threads_to_run_and_join.append(self.frame_reader_thread) self.pole_detector_thread = TowerDetectorThread( in_queue=self.frame_to_pole_detector, out_queue=self.pole_to_comp_detector, poles_detector=self.pole_detector, progress=self.progress ) self.threads_to_run_and_join.append(self.pole_detector_thread) self.component_detector_thread = ComponentDetectorThread( in_queue=self.pole_to_comp_detector, out_queue=self.comp_to_defect_detector, component_detector=self.component_detector, progress=self.progress ) self.threads_to_run_and_join.append(self.component_detector_thread) self.defect_detector_thread = DefectDetectorThread( in_queue=self.comp_to_defect_detector, out_queue=self.defect_det_to_defect_tracker, defect_detector=self.defect_detector, progress=self.progress, check_defects=search_defects ) self.threads_to_run_and_join.append(self.defect_detector_thread) self.defect_tracker_thread = DefectTrackingThread( in_queue=self.defect_det_to_defect_tracker, out_queue=self.defect_tracker_to_writer, object_tracker=self.object_tracker, results_saver=self.result_saver, progress=self.progress, database=db ) self.threads_to_run_and_join.append(self.defect_tracker_thread) self.results_processor_thread = ResultsProcessorThread( in_queue=self.defect_tracker_to_writer, save_path=save_path, drawer=self.drawer, progress=self.progress ) self.threads_to_run_and_join.append(self.results_processor_thread) # -------------- DEFECT DETECTORS --------------- if "dumper" in detectors_to_run: dumper_classifier = DumperClassifier() self.dumper_classifier_thread = DumperClassifierThread( in_queue=self.to_dumper_classifier, out_queue=self.from_dumper_classifier, dumper_classifier=dumper_classifier, progress=self.progress ) self.threads_to_run_and_join.append(self.dumper_classifier_thread) if "pillar" in detectors_to_run: self.tilt_detector_thread = TiltDetectorThread( in_queue=self.to_tilt_detector, out_queue=self.from_tilt_detector, tilt_detector=ConcretePoleHandler(line_modifier=LineModifier), progress=self.progress ) self.threads_to_run_and_join.append(self.tilt_detector_thread) if "wood" in detectors_to_run: wood_tower_segment = WoodCrackSegmenter() self.wood_cracks_thread = WoodCracksDetectorThread( in_queue=self.to_wood_cracks_detector, out_queue=self.from_wood_cracks_detector, wood_cracks_detector=WoodCracksDetector, wood_tower_segment=wood_tower_segment, progress=self.progress ) self.threads_to_run_and_join.append(self.wood_cracks_thread) except Exception as e: print(f"Failed during workers initialization. Error: {e}") raise e # Start the app by launching all workers self.start() def predict( self, request_id: str, path_to_data: str, pole_number: int ) -> dict: """ API endpoint - parses input data, puts files provided to the Q if of appropriate extension :param request_id: :param path_to_data: :param pole_number: :return: """ file_IDS = {} if os.path.isfile(path_to_data): file_id = self.check_type_and_process( path_to_file=path_to_data, pole_number=pole_number, request_id=request_id ) file_IDS[path_to_data] = file_id return file_IDS elif os.path.isdir(path_to_data): for item in os.listdir(path_to_data): path_to_file = os.path.join(path_to_data, item) file_id = self.check_type_and_process( path_to_file=path_to_file, pole_number=pole_number, request_id=request_id ) file_IDS[path_to_file] = file_id else: print(f"ERROR: Cannot process the file {path_to_data}, neither a folder nor a file") return file_IDS def check_type_and_process( self, path_to_file: str, pole_number: int, request_id: str ) -> str: """ Checks whether a file can be processed :return: file's ID if it was put in the Q or "None" if extension is not supported """ filename = os.path.basename(path_to_file) if any(filename.endswith(ext) for ext in ["jpg", "JPG", "jpeg", "JPEG", "png", "PNG"]): print(f"Added image {filename} to the processing queue") return self.process_file( path_to_file=path_to_file, pole_number=pole_number, file_type="image", request_id=request_id ) elif any(filename.endswith(ext) for ext in ["avi", "AVI", "MP4", "mp4"]): print(f"Added video {filename} to the processing queue") return self.process_file( path_to_file=path_to_file, pole_number=pole_number, file_type="video", request_id=request_id ) else: print(f"ERROR: file {filename}'s extension is not supported") return "None" def process_file( self, path_to_file: str, pole_number: int, file_type: str, request_id: str ) -> str: """ :param path_to_file: :param pole_number: :param file_type: :param request_id: :return: """ # Each file to process gets a unique ID number to track its progress file_id = str(uuid.uuid4()) # Keep track of processing progress self.progress[file_id] = { "status": "Awaiting processing", "request_id": request_id, "file_type": file_type, "pole_number": pole_number, "path_to_file": path_to_file, "total_frames": None, "now_processing": 0, "processed": 0, "defects": [] } self.files_to_process_Q.put(file_id) return file_id def start(self) -> None: for thread in self.threads_to_run_and_join: thread.start() def stop(self) -> None: """Wait until all threads complete their job and exit""" self.files_to_process_Q.put("STOP") for thread in self.threads_to_run_and_join: thread.join()
EvgeniiTitov/defect_detection
app/visual_detector/model.py
model.py
py
11,192
python
en
code
0
github-code
1
[ { "api_name": "typing.List", "line_number": 26, "usage_type": "name" }, { "api_name": "queue.Queue", "line_number": 45, "usage_type": "call" }, { "api_name": "queue.Queue", "line_number": 46, "usage_type": "call" }, { "api_name": "queue.Queue", "line_number": ...