blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 133 | path stringlengths 2 333 | src_encoding stringclasses 30
values | length_bytes int64 18 5.47M | score float64 2.52 5.81 | int_score int64 3 5 | detected_licenses listlengths 0 67 | license_type stringclasses 2
values | text stringlengths 12 5.47M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
646bc3912e22e02532988ac07332ef03f50ba098 | Python | icesit/p3at_sim | /tools/myzmq/jpeg_compress.py | UTF-8 | 2,406 | 2.84375 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding: utf-8 -*-
## JPEG图像数据压缩解压缩工具集
import sys
import io
from PIL import Image
import numpy as np
## 将numpy的uint数组转成BytesIO
def uint8_to_bytesio(ary):
return io.BytesIO(ary)
## 将BytesIO转成numpy的uint数组
def bytesio_to_uint8(bin_io):
return np.fromstring(bin_io.getvalue(), dtype=np.uint8)
## 将numpy的uint数组转成PIL的图像对象
def uint8_to_pil(ary):
return Image.fromarray(ary)
## 将PIL的图像对象转成numpy的uint数组
def pil_to_uint8(img_pil):
return np.asarray(img_pil, dtype=np.uint8)
## 将RGB图像img_ary(uint8数组)转成JPE格式(uint8数组)
def img_rgb_to_jpeg(img_ary,quality=80):
#img_pil = uint8_to_pil(img_ary) # img_pil是PIL图像对象
img_pil = img_ary
img_io = io.BytesIO() # img_io_jpg是内存流对象
img_pil.save(img_io, format="JPEG", quality=quality)
img_io.seek(0)
bin_jpg=np.fromstring(img_io.getvalue(), dtype=np.uint8)
return bin_jpg
## 将jpg数据(uint8数组)转成RGB图像(uint8数组)
def jpg_to_img_rgb(bin_jpg):
bin_io = uint8_to_bytesio(bin_jpg)
# 以文件方式访问内存流对象(JPEG文件),解码并生成numpy对象表示的RGB图像
img_pil = Image.open(bin_io).convert('RGB')
img_rgb = np.array(img_pil, dtype=np.uint8)
return img_rgb
####################
## 单元测试
####################
if __name__ == '__main__':
sys.path.append('./')
from global_cfg import *
from pygame_viewer import *
viewer=pygame_viewer_c()
# 读取测试图像
img_pil = Image.open("test.png")
if not img_pil.mode == 'RGB': img_pil = img_pil.convert('RGB')
# 测试图像转成uint8数组
img_uint8=pil_to_uint8(img_pil)
#print('img_uint8.shape:',end='')
print(img_uint8.shape)
# 测试图像进行jpeg压缩,得到压缩后的jpeg byte数组
jpg_uint8=img_rgb_to_jpeg(img_uint8)
#print('jpg_uint8.shape:',end='')
print(jpg_uint8.shape)
# 保存为JPEG文件
jpg_uint8.tofile('jpg_uint8.jpg')
# jpeg数据数组转成RGB图像数组(uint8)
img_new=jpg_to_img_rgb(jpg_uint8)
#viewer.show_img_u8(cv2.cvtColor(img_new,cv2.COLOR_BGR2RGB))
viewer.show_img_u8(img_new)
while True:
if not viewer.poll_event():
break
exit()
| true |
0509fc936f6481103a1ee31611f5d2c3bc266cad | Python | zannabianca1997/FieldPlaying | /main.py | UTF-8 | 5,971 | 2.84375 | 3 | [] | no_license | print("Loading setups...")
import json
with open("assets/setup.json") as f:
setup = json.load(f)
def getscenes():
from os import listdir
from os.path import isfile, join
scenepath = "scenes/"
return [f for f in listdir(scenepath) if isfile(join(scenepath, f)) and f[-5:] == ".json"]
print("Benvenuti nel programma di simulazione del campo elettrico")
print("Selezionare la scena dalle scelte seguenti: \n")
i = 0
scenes_available = getscenes()
for scenepath in scenes_available:
i += 1
print(" %i) %s" % (i,scenepath[:-5]))
selected = int(input("\nEnter a number: "))
print("Loading scene...")
from read_scene import read_scene
scene = read_scene("scenes/"+scenes_available[selected - 1])
import numpy as np
print("Creating base coordinate matrix...")
x = np.linspace(scene.graph_setup.x.min, scene.graph_setup.x.max, scene.graph_setup.x.div)
y = np.linspace(scene.graph_setup.y.min, scene.graph_setup.y.max, scene.graph_setup.y.div)
X, Y = np.meshgrid(x, y)
data_shape=X.shape
cellnum= data_shape[0]*data_shape[1]
print("Data shape setted to {}, simulating {} cells".format(data_shape, cellnum))
print("Creating scene...")
Charge = scene.paint(X, Y)
print("Total charge: {}".format(np.sum(Charge)))
print("Creating distance matrices...")
def sqr_dist_matrix(step, dimx, dimy):
x = np.arange(-dimx, dimx + 1) * step #+1 is for safety.. i doubt its usefullness
y = np.arange(-dimy, dimy + 1) * step
X, Y = np.meshgrid(x, y)
sqr_dists = X ** 2 + Y ** 2
return (X, Y, sqr_dists, np.sqrt(sqr_dists))
# L'idea è: calcoliamo tutto, poi transliamo di ciò che ci serve
print(" Creating duble base distance matrices...")
D_X, D_Y, sqr_D, D = sqr_dist_matrix(scene.graph_setup.prec, *data_shape) #squared int distance, D_matrix[datashape] is 0
print(" Preinverting and multiplying by k...")
k = 1/(4*np.pi*8.86e-12)
E_large = k / sqr_D #electric field
P_large = k / D #electric potential
print(" Erasing infinite center value...")
E_large[data_shape] = 0
P_large[data_shape] = 0
print(" Calculating vector components")
E_X_large = np.nan_to_num(E_large * (D_X / D) )
E_Y_large = np.nan_to_num(E_large * (D_Y / D) )
print(" Creating slicing arrays...")
#slices array
slices_array = [ #per tutte le linee
[ # e per turre le colonne
( #crea una tupla con dentro
slice(data_shape[0] - x, 2*data_shape[0] - x),
slice(data_shape[1] - y, 2*data_shape[1] - y)
)
for y in range(data_shape[1])
]
for x in range(data_shape[0])
]
print("Creating starting zero fields...")
E_x = np.zeros(data_shape)
E_y = np.zeros(data_shape) #all separate
P = np.zeros(data_shape)
#needed for progress bars
steps = cellnum // setup["progress_bar_len"]
if setup["electric_field"]:
print("Calculating electrical field ", end="") #not creating newline
count = 0
for ix in range(data_shape[0]):
for iy in range(data_shape[1]):
if Charge[ix,iy] != 0:
E_x += E_X_large[slices_array[ix][iy]] * Charge[ix,iy] #Electrical field of this cell
E_y += E_Y_large[slices_array[ix][iy]] * Charge[ix,iy]
count += 1
if count%steps == 0:
print(".",end="")
print(" Done!")
if setup["potential"]:
print("Calculating potential ", end="") #not creating newline
count = 0
for ix in range(data_shape[0]):
for iy in range(data_shape[1]):
if Charge[ix,iy] != 0:
P += P_large[slices_array[ix][iy]] * Charge[ix,iy] #potential of this cell
count += 1
if count%steps == 0:
print(".",end="")
print(" Done!")
print("Removing Nan values...")
E_x = np.nan_to_num(E_x)
E_y = np.nan_to_num(E_y)
P = np.nan_to_num(P)
print("Calculating electric field module and charge density...")
E = np.sqrt(E_x ** 2 + E_y ** 2)
ChDist = Charge / (scene.graph_setup.prec**2)
print("Creating graphs...")
import plotly
with open("assets/graph_setups/charge_setup.json") as setup_file:
charge_setup = json.load(setup_file)
charge_graph = plotly.graph_objs.Data([
plotly.graph_objs.Contour(x=x, y=y, z=ChDist,
**charge_setup
)
])
if setup["electric_field"]:
with open("assets/graph_setups/electric_field_setup.json") as setup_file:
electric_field_setup = json.load(setup_file)
electric_field_graph = plotly.tools.FigureFactory.create_streamline(
x,y,E_x,E_y,
name="Electrical field",
**electric_field_setup["streamline"]
)
electric_field_graph["data"].append(plotly.graph_objs.Contour(x=x, y=y, z=E,
contours=electric_field_setup["contours"],
colorbar=electric_field_setup["colorbar"])
)
if setup["potential"]:
with open("assets/graph_setups/potential_setup.json") as setup_file:
potential_setup = json.load(setup_file)
potential_graph = plotly.graph_objs.Data([
plotly.graph_objs.Contour(x=x, y=y, z=P,
**potential_setup
)
])
print("Showing off my result...")
import os
scene_name = scenes_available[selected - 1][:-5]
out_path = "output/" + scene_name
if not os.path.exists(out_path):
os.mkdir(out_path)
plotly.offline.plot(charge_graph, filename=out_path + '/' + scene_name + '_ChargeField.html')
if setup["electric_field"]:
plotly.offline.plot(electric_field_graph, filename=out_path + "/" + scene_name + "_ElectricField.html")
if setup["potential"]:
plotly.offline.plot(potential_graph, filename=out_path + '/' + scene_name2 + '_PotentialField.html')
| true |
34c6101ab9eb60dfc3fbbc67713b952dae0aae5a | Python | GreatStephen/MyLeetcodeSolutions | /1contest199/3.py | UTF-8 | 1,387 | 3.046875 | 3 | [] | no_license | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def countPairs(self, root: TreeNode, distance: int) -> int:
# DFS
self.ans = 0
def DFS(node):
dl, dr = {}, {}
dleft, dright = None, None
if node.left: dleft = DFS(node.left)
if node.right: dright = DFS(node.right)
# result from left and right subtree
if dleft:
for n in dleft.keys():
dleft[n]+=1
dl = dleft
else:
if node.left: dl[node.left]=1
if dright:
for n in dright.keys():
dright[n]+=1
dr = dright
else:
if node.right: dr[node.right]=1
# find answers
for ldis in dl.keys():
for rdis in dr.keys():
if dl[ldis]+dr[rdis]<=distance: self.ans+=1
# if node.val==7: print(dl, dr)
# conbime dl and dr, return to parent
# return dict(dl.items()+dr.items())
return {**dl, **dr}
DFS(root)
return self.ans
| true |
bf497fa58f47531cd3ad1562609ff73da198a846 | Python | sgdantas/Prediction-Faulty-Pumps | /pre_processing.py | UTF-8 | 2,882 | 3.09375 | 3 | [] | no_license | import pandas as pd
import numpy as np
def getProcessedData(file_name):
data = pd.read_csv(file_name)
missing_percentage = list()
#choose the relevant variables
#data = data_all[['amount_tsh', 'population', 'funder', 'basin', 'region', 'scheme_management', 'permit','construction_year','extraction_type','management','payment','quality_group','source_type','waterpoint_type']]
"""
Working only with the Independent variables first
"""
###construction_year
#construction year -> age
data['construction_year'] = 2016 - data['construction_year']
data['construction_year'] = data['construction_year'].replace([2016], [0])
#missing data -> mean of the values
medianConstructionFrame = data['construction_year'].replace(0, np.NaN)
data['construction_year'] = data['construction_year'].replace(0, medianConstructionFrame.median())
#normalize
data['construction_year'] = data['construction_year']/data['construction_year'].max()
###amount_tsh
medianConstructionFrame = data['amount_tsh'].replace(0, np.NaN)
data['amount_tsh'] = data['amount_tsh'].replace(0, medianConstructionFrame.median())
#normalize
data['amount_tsh'] = data['amount_tsh']/data['amount_tsh'].max()
###population
medianConstructionFrame = data['population'].replace(0, np.NaN)
data['population'] = data['population'].replace(0, medianConstructionFrame.median())
#normalize
data['population'] = data['population']/data['population'].max()
###funder
###categorical => Government (1); Other(0)
data.loc[data['funder'] != 'Government Of Tanzania', 'funder'] = 0
data.loc[data['funder'] == 'Government Of Tanzania', 'funder'] = 1
###permit
###categorical => True (1); False(0) ; Missing()
data.loc[data['permit'] == True, 'permit'] = 1
data.loc[data['permit'] == False, 'permit'] = -1
data['permit'] = data['permit'].replace(np.NaN, 0)
#normalize
data['latitude'] = data['latitude']/data['latitude'].min()
#normalize
data['longitude'] = data['longitude']/data['longitude'].max()
#choose the relevant variables
categoricalColumns=['public_meeting','quantity','basin','extraction_type','region','scheme_management','water_quality','management_group', 'payment','source_type','waterpoint_type']
dfCatVar = data[categoricalColumns]
#get dummies for the choosen variables
df_dummy = pd.concat([pd.get_dummies(dfCatVar[col]) for col in dfCatVar], axis=1, keys=dfCatVar.columns)
nonCategoricalColumns = ['id','amount_tsh','population','construction_year','latitude','longitude']
#joining together the variables
df_final = pd.concat([df_dummy,data[nonCategoricalColumns]], axis = 1)
return df_final
def getData():
fileName = "trainingSetValues.csv"
return getProcessedData(fileName)
| true |
c80941787ca34c4a8d3a674988268de01ac7f909 | Python | abaek/Algorithms | /graphsSoln.py | UTF-8 | 5,356 | 4.09375 | 4 | [] | no_license | """
You are given these structures:
"""
class TreeNode:
def __init__(self, value=None, left=None, right=None):
self.value = value
self.left = left
self.right = right
class BST:
def __init__(self, root=None):
self.root = root
def add(self, value):
if self.root == None:
self.root = TreeNode(value)
else:
curNode = self.root
while(True):
if (curNode.value > value):
if curNode.left == None:
curNode.left = TreeNode(value)
break
else:
curNode = curNode.left
else:
if curNode.right == None:
curNode.right = TreeNode(value)
break
else:
curNode = curNode.right
bst1 = BST(TreeNode(10, TreeNode(5, TreeNode(3, TreeNode(2, None, None), TreeNode(4, None, None)), TreeNode(7, None, None)), TreeNode(15, TreeNode(11, None, TreeNode(12, None, None)), TreeNode(21, None, None))))
class Graph:
def __init__(self, nodes={}):
self.nodes = nodes
def add(self, val, neighbours):
self.nodes[val] = neighbours
graph1 = Graph({1: [2, 5], 2: [3, 5], 3: [4], 4: [5], 5: []})
"""
1) Given a graph, find all nodes of distance n away from a starting node using DFS
"""
def nodesAwayDFS(graph, start, distance):
#found one answer
if distance == 0:
return [start]
else:
#gather answer recursively
result = []
neighbours = graph.nodes[start]
#recurse through each neighbour
for neighbour in graph.nodes[start]:
result.extend(nodesAwayDFS(graph, neighbour, distance-1))
return result
#tests:
assert nodesAwayDFS(graph1, 1, 2) == [3, 5]
assert nodesAwayDFS(graph1, 1, 3) == [4]
"""
2) Given a graph, find all nodes of distance n away from a starting node using BFS
"""
def nodesAwayBFS(graph, start, distance):
curLevelNodes = [start]
while distance != 0:
children = []
for node in curLevelNodes:
#aggregate all children
children.extend(graph.nodes[node])
curLevelNodes = children
distance -= 1
return curLevelNodes
#tests:
assert nodesAwayBFS(graph1, 1, 2) == [3, 5]
assert nodesAwayBFS(graph1, 1, 3) == [4]
"""
3) Find the nth largest number in a BST
"""
def nthLargest(bst, n):
curNode = bst.root
while (True):
#count all nodes in left (lower than current num)
countLeft = countNodesTree(curNode.left)
#found
if countLeft == n - 1:
return curNode.value
#go smaller
elif countLeft > n - 1:
curNode = curNode.left
#go bigger
else:
curNode = curNode.right
n -= countLeft + 1
#helper to count the nodes
def countNodesTree(bst):
if bst == None:
return 0
else:
return 1 + countNodesTree(bst.left) + countNodesTree(bst.right)
#tests:
assert nthLargest(bst1, 1) == 2
assert nthLargest(bst1, 2) == 3
assert nthLargest(bst1, 3) == 4
assert nthLargest(bst1, 4) == 5
assert nthLargest(bst1, 5) == 7
assert nthLargest(bst1, 6) == 10
assert nthLargest(bst1, 7) == 11
assert nthLargest(bst1, 8) == 12
assert nthLargest(bst1, 9) == 15
assert nthLargest(bst1, 10) == 21
"""
4) Find the distance between 2 nodes in a graph
"""
def distanceApart(graph, start, end):
if start == end:
return 0
else:
#keep track of visited nodes
visited = set()
distance = 1
children = graph.nodes[start]
while(True):
#not connected
if children == []:
return -1
#found end
elif end in children:
return distance
#BFS
else:
newChildren = []
for child in children:
if not child in visited:
newChildren.extend(graph.nodes[child])
visited.add(child)
children = newChildren
distance += 1
#tests:
assert distanceApart(graph1, 1, 3) == 2
assert distanceApart(graph1, 2, 5) == 1
assert distanceApart(graph1, 4, 5) == 1
assert distanceApart(graph1, 2, 1) == -1
"""
5) Implement Djkastra's Algorithm
"""
def Dijkstra(graph, start, end):
#set initial path lengths to each node
pathLengths = [-1 for i in range(len(graph.list))]
#set start node distance to 0
pathLengths[start] = 0
#Also keep track of unvisitedNodes
unvisitedNodes = [-1 for i in range(len(graph.list))]
while(True):
#find min path length
minNode = 0
minNodeDistance = -1
for i in range(len(unvisitedNodes)):
#must be unvisited, yet have a distance and be min distance
if unvisitedNodes[i] == -1 and pathLengths[i] >= 0 and (pathLengths[i] < minNodeDistance or minNodeDistance == -1):
minNodeDistance = pathLengths[i]
minNode = i
neighbours = graph.list[minNode]
#neighbour = (id, distance/weight)
for neighbour in neighbours:
#if neighbour hasnt been touched or greater distance than current route, give it a value
if pathLengths[neighbour[0]] == -1 or pathLengths[neighbour[0]] > minNodeDistance + neighbour[1]:
pathLengths[neighbour[0]] = minNodeDistance + neighbour[1]
#mark node as visited
unvisitedNodes[minNode] = 0
#if end node is visited, break
if minNode == end:
break
print pathLengths
return pathLengths[end]
class Graph2:
#adjList = [ [(2, 3), (3, 4)], [(1, 3), (4, 9)], [(1, 4), (4, 5)], [(2, 9), (3, 5)] ]
#where adjList[2] = [(neighbour, weight), ..]
def __init__(self, adjList=[]):
self.list = adjList
graph2 = Graph2([[], [(2, 3), (3, 4), (5, 4)],
[(1, 3), (4, 9)],
[(1, 4), (4, 5)],
[(2, 9), (3, 5), (4, 4)],
[(1, 4), (6, 4)],
[(5, 4), (4, 4)]])
graph3 = Graph2([[(1, 4), (2, 1)],
[(0, 4), (2, 1)],
[(0, 1), (1, 1)]])
assert Dijkstra(graph2, 1, 4) == 9
assert Dijkstra(graph3, 0, 1) == 2
| true |
c7902ae37286a9fca07cc33587a3f126c7d88465 | Python | alacrity2001/PTSA-public- | /ptsa/ptsa/utils/utility.py | UTF-8 | 23,096 | 2.921875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""A set of utility functions to support outlier detection.
"""
# Author: Yinchen WU <yinchen@uchicago.edu>
from __future__ import division
from __future__ import print_function
import numpy as np
from numpy import percentile
import numbers
import sklearn
from sklearn.metrics import precision_score
from sklearn.preprocessing import StandardScaler
from sklearn.utils import column_or_1d
from sklearn.utils import check_array
from sklearn.utils import check_consistent_length
from sklearn.utils import check_random_state
from sklearn.utils.random import sample_without_replacement
from functools import partial
from multiprocessing import Pool
import random as rn
from collections import Counter
import warnings
MAX_INT = np.iinfo(np.int32).max
MIN_INT = -1 * MAX_INT
def pairwise_distances_no_broadcast(X, Y):
"""Utility function to calculate row-wise euclidean distance of two matrix.
Different from pair-wise calculation, this function would not broadcast.
For instance, X and Y are both (4,3) matrices, the function would return
a distance vector with shape (4,), instead of (4,4).
Parameters
----------
X : array of shape (n_samples, n_features)
First input samples
Y : array of shape (n_samples, n_features)
Second input samples
Returns
-------
distance : array of shape (n_samples,)
Row-wise euclidean distance of X and Y
"""
X = check_array(X)
Y = check_array(Y)
if X.shape[0] != Y.shape[0] or X.shape[1] != Y.shape[1]:
raise ValueError("pairwise_distances_no_broadcast function receive"
"matrix with different shapes {0} and {1}".format(
X.shape, Y.shape))
euclidean_sq = np.square(Y - X)
return np.sqrt(np.sum(euclidean_sq, axis=1)).ravel()
def getSplit(X):
"""
Randomly selects a split value from set of scalar data 'X'.
Returns the split value.
Parameters
----------
X : array
Array of scalar values
Returns
-------
float
split value
"""
xmin = X.min()
xmax = X.max()
return np.random.uniform(xmin, xmax)
def similarityScore(S, node, alpha):
"""
Given a set of instances S falling into node and a value alpha >=0,
returns for all element x in S the weighted similarity score between x
and the centroid M of S (node.M)
Parameters
----------
S : array of instances
Array of instances that fall into a node
node: a DiFF tree node
S is the set of instances "falling" into the node
alpha: float
alpha is the distance scaling hyper-parameter
Returns
-------
array
the array of similarity values between the instances in S and the mean of training instances falling in node
"""
d = np.shape(S)[1]
if len(S) > 0:
d = np.shape(S)[1]
U = (S-node.M)/node.Mstd # normalize using the standard deviation vector to the mean
U = (2)**(-alpha*(np.sum(U*U/d, axis=1)))
else:
U = 0
return U
def EE(hist):
"""
given a list of positive values as a histogram drawn from any information source,
returns the empirical entropy of its discrete probability function.
Parameters
----------
hist: array
histogram
Returns
-------
float
empirical entropy estimated from the histogram
"""
h = np.asarray(hist, dtype=np.float64)
if h.sum() <= 0 or (h < 0).any():
return 0
h = h/h.sum()
return -(h*np.ma.log2(h)).sum()
def weightFeature(s, nbins):
'''
Given a list of values corresponding to a feature dimension, returns a weight (in [0,1]) that is
one minus the normalized empirical entropy, a way to characterize the importance of the feature dimension.
Parameters
----------
s: array
list of scalar values corresponding to a feature dimension
nbins: int
the number of bins used to discretize the feature dimension using an histogram.
Returns
-------
float
the importance weight for feature s.
'''
if s.min() == s.max():
return 0
hist = np.histogram(s, bins=nbins, density=True)
ent = EE(hist[0])
ent = ent/np.log2(nbins)
return 1-ent
def walk_tree(forest, node, treeIdx, obsIdx, X, featureDistrib, depth=0, alpha=1e-2):
'''
Recursive function that walks a tree from an already fitted forest to compute the path length
of the new observations.
Parameters
----------
forest : DiFF_RF
A fitted forest of DiFF trees
node: DiFF Tree node
the current node
treeIdx: int
index of the tree that is being walked.
obsIdx: array
1D array of length n_obs. 1/0 if the obs has reached / has not reached the node.
X: nD array.
array of observations/instances.
depth: int
current depth.
Returns
-------
None
'''
if isinstance(node, LeafNode):
Xnode = X[obsIdx]
f = ((node.size+1)/forest.sample_size) / ((1+len(Xnode))/forest.XtestSize)
if alpha == 0:
forest.LD[obsIdx, treeIdx] = 0
forest.LF[obsIdx, treeIdx] = -f
forest.LDF[obsIdx, treeIdx] = -f
else:
z = similarityScore(Xnode, node, alpha)
forest.LD[obsIdx, treeIdx] = z
forest.LF[obsIdx, treeIdx] = -f
forest.LDF[obsIdx, treeIdx] = z*f
else:
idx = (X[:, node.splitAtt] <= node.splitValue) * obsIdx
walk_tree(forest, node.left, treeIdx, idx, X, featureDistrib, depth + 1, alpha=alpha)
idx = (X[:, node.splitAtt] > node.splitValue) * obsIdx
walk_tree(forest, node.right, treeIdx, idx, X, featureDistrib, depth + 1, alpha=alpha)
def create_tree(X, featureDistrib, sample_size, max_height):
'''
Creates an DiFF tree using a sample of size sample_size of the original data.
Parameters
----------
X: nD array.
nD array with the observations. Dimensions should be (n_obs, n_features).
sample_size: int
Size of the sample from which a DiFF tree is built.
max_height: int
Maximum height of the tree.
Returns
-------
a DiFF tree
'''
rows = np.random.choice(len(X), sample_size, replace=False)
featureDistrib = np.array(featureDistrib)
return DiFF_Tree(max_height).fit(X[rows, :], featureDistrib)
def check_parameter(param, low=MIN_INT, high=MAX_INT, param_name='',
include_left=False, include_right=False):
"""Check if an input is within the defined range.
Parameters
----------
param : int, float
The input parameter to check.
low : int, float
The lower bound of the range.
high : int, float
The higher bound of the range.
param_name : str, optional (default='')
The name of the parameter.
include_left : bool, optional (default=False)
Whether includes the lower bound (lower bound <=).
include_right : bool, optional (default=False)
Whether includes the higher bound (<= higher bound).
Returns
-------
within_range : bool or raise errors
Whether the parameter is within the range of (low, high)
"""
# param, low and high should all be numerical
if not isinstance(param, (numbers.Integral, np.integer, np.float)):
raise TypeError('{param_name} is set to {param} Not numerical'.format(
param=param, param_name=param_name))
if not isinstance(low, (numbers.Integral, np.integer, np.float)):
raise TypeError('low is set to {low}. Not numerical'.format(low=low))
if not isinstance(high, (numbers.Integral, np.integer, np.float)):
raise TypeError('high is set to {high}. Not numerical'.format(
high=high))
# at least one of the bounds should be specified
if low is MIN_INT and high is MAX_INT:
raise ValueError('Neither low nor high bounds is undefined')
# if wrong bound values are used
if low > high:
raise ValueError(
'Lower bound > Higher bound')
# value check under different bound conditions
if (include_left and include_right) and (param < low or param > high):
raise ValueError(
'{param_name} is set to {param}. '
'Not in the range of [{low}, {high}].'.format(
param=param, low=low, high=high, param_name=param_name))
elif (include_left and not include_right) and (
param < low or param >= high):
raise ValueError(
'{param_name} is set to {param}. '
'Not in the range of [{low}, {high}).'.format(
param=param, low=low, high=high, param_name=param_name))
elif (not include_left and include_right) and (
param <= low or param > high):
raise ValueError(
'{param_name} is set to {param}. '
'Not in the range of ({low}, {high}].'.format(
param=param, low=low, high=high, param_name=param_name))
elif (not include_left and not include_right) and (
param <= low or param >= high):
raise ValueError(
'{param_name} is set to {param}. '
'Not in the range of ({low}, {high}).'.format(
param=param, low=low, high=high, param_name=param_name))
else:
return True
def check_detector(detector):
"""Checks if fit and decision_function methods exist for given detector
Parameters
----------
detector : pyod.models
Detector instance for which the check is performed.
"""
if not hasattr(detector, 'fit') or not hasattr(detector,
'decision_function'):
raise AttributeError("%s is not a detector instance." % (detector))
def standardizer(X, X_t=None, keep_scalar=False):
"""Conduct Z-normalization on data to turn input samples become zero-mean
and unit variance.
Parameters
----------
X : numpy array of shape (n_samples, n_features)
The training samples
X_t : numpy array of shape (n_samples_new, n_features), optional (default=None)
The data to be converted
keep_scalar : bool, optional (default=False)
The flag to indicate whether to return the scalar
Returns
-------
X_norm : numpy array of shape (n_samples, n_features)
X after the Z-score normalization
X_t_norm : numpy array of shape (n_samples, n_features)
X_t after the Z-score normalization
scalar : sklearn scalar object
The scalar used in conversion
"""
X = check_array(X)
scaler = StandardScaler().fit(X)
if X_t is None:
if keep_scalar:
return scaler.transform(X), scaler
else:
return scaler.transform(X)
else:
X_t = check_array(X_t)
if X.shape[1] != X_t.shape[1]:
raise ValueError(
"The number of input data feature should be consistent"
"X has {0} features and X_t has {1} features.".format(
X.shape[1], X_t.shape[1]))
if keep_scalar:
return scaler.transform(X), scaler.transform(X_t), scaler
else:
return scaler.transform(X), scaler.transform(X_t)
def score_to_label(pred_scores, outliers_fraction=0.1):
"""Turn raw outlier outlier scores to binary labels (0 or 1).
Parameters
----------
pred_scores : list or numpy array of shape (n_samples,)
Raw outlier scores. Outliers are assumed have larger values.
outliers_fraction : float in (0,1)
Percentage of outliers.
Returns
-------
outlier_labels : numpy array of shape (n_samples,)
For each observation, tells whether or not
it should be considered as an outlier according to the
fitted model. Return the outlier probability, ranging
in [0,1].
"""
# check input values
pred_scores = column_or_1d(pred_scores)
check_parameter(outliers_fraction, 0, 1)
threshold = percentile(pred_scores, 100 * (1 - outliers_fraction))
pred_labels = (pred_scores > threshold).astype('int')
return pred_labels
def precision_n_scores(y, y_pred, n=None):
"""Utility function to calculate precision @ rank n.
Parameters
----------
y : list or numpy array of shape (n_samples,)
The ground truth. Binary (0: inliers, 1: outliers).
y_pred : list or numpy array of shape (n_samples,)
The raw outlier scores as returned by a fitted model.
n : int, optional (default=None)
The number of outliers. if not defined, infer using ground truth.
Returns
-------
precision_at_rank_n : float
Precision at rank n score.
"""
# turn raw prediction decision scores into binary labels
y_pred = get_label_n(y, y_pred, n)
# enforce formats of y and labels_
y = column_or_1d(y)
y_pred = column_or_1d(y_pred)
return precision_score(y, y_pred)
def get_label_n(y, y_pred, n=None):
"""Function to turn raw outlier scores into binary labels by assign 1
to top n outlier scores.
Parameters
----------
y : list or numpy array of shape (n_samples,)
The ground truth. Binary (0: inliers, 1: outliers).
y_pred : list or numpy array of shape (n_samples,)
The raw outlier scores as returned by a fitted model.
n : int, optional (default=None)
The number of outliers. if not defined, infer using ground truth.
Returns
-------
labels : numpy array of shape (n_samples,)
binary labels 0: normal points and 1: outliers
Examples
--------
>>> from pyod.utils.utility import get_label_n
>>> y = [0, 1, 1, 0, 0]
>>> y_pred = [0.1, 0.5, 0.3, 0.2, 0.7]
>>> get_label_n(y, y_pred)
array([0, 1, 0, 0, 1])
"""
# enforce formats of inputs
y = column_or_1d(y)
y_pred = column_or_1d(y_pred)
check_consistent_length(y, y_pred)
y_len = len(y) # the length of targets
# calculate the percentage of outliers
if n is not None:
outliers_fraction = n / y_len
else:
outliers_fraction = np.count_nonzero(y) / y_len
threshold = percentile(y_pred, 100 * (1 - outliers_fraction))
y_pred = (y_pred > threshold).astype('int')
return y_pred
def get_intersection(lst1, lst2):
"""get the overlapping between two lists
Parameters
----------
li1 : list or numpy array
Input list 1.
li2 : list or numpy array
Input list 2.
Returns
-------
difference : list
The overlapping between li1 and li2.
"""
return list(set(lst1) & set(lst2))
def get_list_diff(li1, li2):
"""get the elements in li1 but not li2. li1-li2
Parameters
----------
li1 : list or numpy array
Input list 1.
li2 : list or numpy array
Input list 2.
Returns
-------
difference : list
The difference between li1 and li2.
"""
# if isinstance(li1, (np.ndarray, np.generic)):
# li1 = li1.tolist()
# if isinstance(li2, (np.ndarray, np.generic)):
# li1 = li1.tolist()
return (list(set(li1) - set(li2)))
def get_diff_elements(li1, li2):
"""get the elements in li1 but not li2, and vice versa
Parameters
----------
li1 : list or numpy array
Input list 1.
li2 : list or numpy array
Input list 2.
Returns
-------
difference : list
The difference between li1 and li2.
"""
# if isinstance(li1, (np.ndarray, np.generic)):
# li1 = li1.tolist()
# if isinstance(li2, (np.ndarray, np.generic)):
# li1 = li1.tolist()
return (list(set(li1) - set(li2)) + list(set(li2) - set(li1)))
def argmaxn(value_list, n, order='desc'):
"""Return the index of top n elements in the list
if order is set to 'desc', otherwise return the index of n smallest ones.
Parameters
----------
value_list : list, array, numpy array of shape (n_samples,)
A list containing all values.
n : int
The number of elements to select.
order : str, optional (default='desc')
The order to sort {'desc', 'asc'}:
- 'desc': descending
- 'asc': ascending
Returns
-------
index_list : numpy array of shape (n,)
The index of the top n elements.
"""
value_list = column_or_1d(value_list)
length = len(value_list)
# validate the choice of n
check_parameter(n, 1, length, include_left=True, include_right=True,
param_name='n')
# for the smallest n, flip the value
if order != 'desc':
n = length - n
value_sorted = np.partition(value_list, length - n)
threshold = value_sorted[int(length - n)]
if order == 'desc':
return np.where(np.greater_equal(value_list, threshold))[0]
else: # return the index of n smallest elements
return np.where(np.less(value_list, threshold))[0]
def invert_order(scores, method='multiplication'):
""" Invert the order of a list of values. The smallest value becomes
the largest in the inverted list. This is useful while combining
multiple detectors since their score order could be different.
Parameters
----------
scores : list, array or numpy array with shape (n_samples,)
The list of values to be inverted
method : str, optional (default='multiplication')
Methods used for order inversion. Valid methods are:
- 'multiplication': multiply by -1
- 'subtraction': max(scores) - scores
Returns
-------
inverted_scores : numpy array of shape (n_samples,)
The inverted list
Examples
--------
>>> scores1 = [0.1, 0.3, 0.5, 0.7, 0.2, 0.1]
>>> invert_order(scores1)
array([-0.1, -0.3, -0.5, -0.7, -0.2, -0.1])
>>> invert_order(scores1, method='subtraction')
array([0.6, 0.4, 0.2, 0. , 0.5, 0.6])
"""
scores = column_or_1d(scores)
if method == 'multiplication':
return scores.ravel() * -1
if method == 'subtraction':
return (scores.max() - scores).ravel()
def _get_sklearn_version(): # pragma: no cover
""" Utility function to decide the version of sklearn.
PyOD will result in different behaviors with different sklearn version
Returns
-------
sk_learn version : int
"""
sklearn_version = str(sklearn.__version__)
if int(sklearn_version.split(".")[1]) < 19 or int(
sklearn_version.split(".")[1]) > 23:
raise ValueError("Sklearn version error")
return int(sklearn_version.split(".")[1])
def _sklearn_version_21(): # pragma: no cover
""" Utility function to decide the version of sklearn
In sklearn 21.0, LOF is changed. Specifically, _decision_function
is replaced by _score_samples
Returns
-------
sklearn_21_flag : bool
True if sklearn.__version__ is newer than 0.21.0
"""
sklearn_version = str(sklearn.__version__)
if int(sklearn_version.split(".")[1]) > 20:
return True
else:
return False
def generate_bagging_indices(random_state, bootstrap_features, n_features,
min_features, max_features):
""" Randomly draw feature indices. Internal use only.
Modified from sklearn/ensemble/bagging.py
Parameters
----------
random_state : RandomState
A random number generator instance to define the state of the random
permutations generator.
bootstrap_features : bool
Specifies whether to bootstrap indice generation
n_features : int
Specifies the population size when generating indices
min_features : int
Lower limit for number of features to randomly sample
max_features : int
Upper limit for number of features to randomly sample
Returns
-------
feature_indices : numpy array, shape (n_samples,)
Indices for features to bag
"""
# Get valid random state
random_state = check_random_state(random_state)
# decide number of features to draw
random_n_features = random_state.randint(min_features, max_features)
# Draw indices
feature_indices = generate_indices(random_state, bootstrap_features,
n_features, random_n_features)
return feature_indices
def generate_indices(random_state, bootstrap, n_population, n_samples):
""" Draw randomly sampled indices. Internal use only.
See sklearn/ensemble/bagging.py
Parameters
----------
random_state : RandomState
A random number generator instance to define the state of the random
permutations generator.
bootstrap : bool
Specifies whether to bootstrap indice generation
n_population : int
Specifies the population size when generating indices
n_samples : int
Specifies number of samples to draw
Returns
-------
indices : numpy array, shape (n_samples,)
randomly drawn indices
"""
# Draw sample indices
if bootstrap:
indices = random_state.randint(0, n_population, n_samples)
else:
indices = sample_without_replacement(n_population, n_samples,
random_state=random_state)
return indices
try:
import igraph as ig
except:
warnings.warn("No igraph interface for plotting trees")
def EuclideanDist(x,y):
return np.sqrt(np.sum((x - y) ** 2))
def dist2set(x, X):
l=len(X)
ldist=[]
for i in range(l):
ldist.append(EuclideanDist(x,X[i]))
return ldist
def c_factor(n) :
if(n<2):
n=2
return 2.0*(np.log(n-1)+0.5772156649) - (2.0*(n-1.)/(n*1.0))
def all_branches(node, current=[], branches = None):
current = current[:node.e]
if branches is None: branches = []
if node.ntype == 'inNode':
current.append('L')
all_branches(node.left, current=current, branches=branches)
current = current[:-1]
current.append('R')
all_branches(node.right, current=current, branches=branches)
else:
branches.append(current)
return branches
def branch2num(branch, init_root=0):
num = [init_root]
for b in branch:
if b == 'L':
num.append(num[-1] * 2 + 1)
if b == 'R':
num.append(num[-1] * 2 + 2)
return num
def gen_graph(branches, g = None, init_root = 0, pre = ''):
num_branches = [branch2num(i, init_root) for i in branches]
all_nodes = [j for branch in num_branches for j in branch]
all_nodes = np.unique(all_nodes)
all_nodes = all_nodes.tolist()
if g is None:
g=ig.Graph()
for k in all_nodes : g.add_vertex(pre+str(k))
t=[]
for j in range(len(branches)):
branch = branch2num(branches[j], init_root)
for i in range(len(branch)-1):
pair = [branch[i],branch[i+1]]
if pair not in t:
t.append(pair)
g.add_edge(pre+str(branch[i]),pre+str(branch[i+1]))
return g,max(all_nodes) | true |
e622de5850b299e1248f5d3d968fb7dbe48b2824 | Python | wildenali/Belajar-GUI-dengan-pyQT | /32_TableWidget/main.py | UTF-8 | 1,636 | 2.8125 | 3 | [] | no_license | #!/usr/bin/python3
import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class MainForm(QWidget):
def __init__(self):
super(MainForm, self).__init__()
self.setupUI()
def setupUI(self):
self.resize(800,400)
self.move(300,100)
self.setWindowTitle('Table Widget')
self.table = QTableWidget()
self.table.setRowCount(5)
self.table.setColumnCount(3)
columnHeaders = ['Judul Buku', 'Penulis', 'Penerbit']
self.table.setHorizontalHeaderLabels(columnHeaders)
self.addRow(0, ['Python 3 OOP', 'Dustiy Philips', 'PACKT Publisher'])
self.addRow(1, ['Numerical Python', 'Robert Johansson', 'Apress'])
self.addRow(2, ['A Primer Scientific', 'Peter', 'Springer'])
self.addRow(3, ['Batagor', 'ucup', 'Di Dorong'])
self.addRow(4, ['Siomay', 'entong', 'di tusuk'])
self.lineEdit = QLineEdit()
layout = QVBoxLayout()
layout.addWidget(self.table)
layout.addWidget(self.lineEdit)
self.setLayout(layout)
self.table.itemClicked.connect(self.tableItemClick)
def tableItemClick(self):
item = self.table.currentItem()
self.lineEdit.setText(item.text() + ' [baris: %d, kolom: %d]' % (self.table.currentRow(),self.table.currentColumn()))
def addRow(self, row, itemLabels=[]):
for i in range(0,3):
item = QTableWidgetItem()
item.setText(itemLabels[i])
self.table.setItem(row, i, item)
if __name__ == '__main__':
a = QApplication(sys.argv)
form = MainForm()
form.show()
a.exec_()
| true |
44dec40ff6e40d2da7edad222006664d5a0b5a2a | Python | jenihuang/Coding_problems | /HackerRank/kangaroo.py | UTF-8 | 1,394 | 3.546875 | 4 | [] | no_license | import math
import os
import random
import re
import sys
# Complete the kangaroo function below.
# y = mx + b
# m1x + b1 = m2x + b2
# m1x - m2x = b2 - b1
# x = (b2 - b1)/(m1 - m2)
# def kangaroo(x1, v1, x2, v2):
# if v1 != v2:
# intersection = (x2 - x1) / (v1 - v2)
# else:
# if x1 != x2:
# return 'NO'
# if intersection == int(intersection):
# if v1 > v2 and x1 <= x2:
# return 'YES'
# elif v1 == v2 and x1 == x2:
# return 'YES'
# elif v1 < v2 and x1 >= x2:
# return 'YES'
# else:
# return 'NO'
# else:
# return 'NO'
class Kangaroo(object):
def __init__(self, x, v):
self.start = x
self.speed = v
def compare(self, other):
if self.start <= other.start and self.speed > other.speed:
return 'YES'
elif self.start == other.start and self.speed == other.speed:
return 'YES'
elif self.start >= other.start and self.speed < other.speed:
return 'YES'
else:
return 'NO'
def intersect(self, other):
if self.compare(other) == 'YES':
x = (other.start - self.start) / (self.speed - other.speed)
if x == int(x):
return 'YES'
else:
return 'NO'
else:
return 'NO'
| true |
dfda28ffc317cc2be95343f75c99529d2bf4d6f1 | Python | YanpuLi/LeetCode-Practice-and-Algo | /Easy/350. Intersection of Two Arrays II.py | UTF-8 | 1,023 | 3.125 | 3 | [] | no_license | class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
if len(nums2) > len(nums1):
nums1,nums2 = nums2, nums1
dic1 = {}
ans = []
for i in nums1:
dic1[i] = dic1.get(i,0)+1
for j in nums2:
if j in dic1 and dic1[j] >0:
ans.append(j)
dic1[j] -=1
return ans
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
nums1.sort()
nums2.sort()
i,j = 0,0
ans = []
while i <len(nums1) and j<len(nums2):
if nums1[i] < nums2[j]:
i +=1
elif nums1[i] > nums2[j]:
j +=1
else:
ans.append(nums1[i])
i +=1
j +=1
return ans | true |
7b9913c2424d51841c9f14b4813ba736ad6f7945 | Python | mstall/TASpberryPI | /PI_read-write_PSI.py | UTF-8 | 11,629 | 2.96875 | 3 | [] | no_license | # Learned it here...
# https://www.devdungeon.com/content/gui-programming-python
# https://pyinmyeye.blogspot.com/2012/08/tkinter-menubutton-demo.html
# first import message box stuff
import tkinter
from tkinter import Tk, Label, Y, LEFT, RIGHT, Button
# then pull data from text document "values.txt"
#OPEN FILE TO BE READ
myFile = open('values.txt', 'r')
listoflines = myFile.read().splitlines()
#Laser DC Setpoint read from values.txt
aline = listoflines[0]
lineitems = aline.split('=')
ldcs = lineitems[1]
#print("Laser DC Setpoint")
#print (ldcs)
#Laser temperature setpoint read from values.txt
aline1 = listoflines[1]
lineitems1 = aline1.split('=')
lts = lineitems1[1]
#print ("Laser Temperature")
#print (lts)
#Laser AC setpoint read from values.txt
aline2 = listoflines[2]
lineitems2 = aline2.split('=')
lacs = lineitems2[1]
#print ("Laser AC setpoint")
#print (lacs)
#Laser Tuning Rate read from values.txt
aline3 = listoflines[3]
lineitems3 = aline3.split('=')
ltr = lineitems3[1]
#print ("Laser Tuning Rate")
#print (ltr)
#Laser Calibration Constant read from values.txt
aline4 = listoflines[4]
lineitems4 = aline4.split('=')
lcc = lineitems4[1]
#print ("Laser Calibration Constant")
#print (lcc)
#
#Laser Temperature DAC Offset read from values.txt
aline5 = listoflines[5]
lineitems5 = aline5.split('=')
ltdo = lineitems5[1]
#print ("Laser Temperature DAC Offset")
#print (ltdo)
#Concentration Offset read from values.txt
aline6 = listoflines[6]
lineitems6 = aline6.split('=')
co = lineitems6[1]
#print ("Concentration Offset")
#print (co)
#Photo Current Monitor Threshold read from values.txt
aline7 = listoflines[7]
lineitems7 = aline7.split('=')
pcmt = lineitems7[1]
#print ("Photo Current Monitor Threshold")
#print (pcmt)
#Current Shutdown Record read from values.txt
aline8 = listoflines[8]
lineitems8 = aline8.split('=')
csr = lineitems8[1]
#print ("Current Shutdown Record")
#print (csr)
#Serial Number read from values.txt
aline9 = listoflines[9]
lineitems9 = aline9.split('=')
sn = lineitems9[1]
#print ("Serial Number")
#print (sn)
#Modulator Gain read from values.txt
aline10 = listoflines[10]
lineitems10 = aline10.split('=')
mg = lineitems10[1]
#print ("Modulator Gain")
#print (mg)
#F2 Correction for I read from values.txt
aline11 = listoflines[11]
lineitems11 = aline11.split('=')
f2cfi = lineitems11[1]
#print ("F2 Modulator for I")
#print (f2cfi)
#F2 Correction for Q read from values.txt
aline12 = listoflines[12]
lineitems12 = aline12.split('=')
f2cfq = lineitems12[1]
#print ("F2 Modulator for Q")
#print (f2cfq)
#Minimum F1 read from values.txt
aline13 = listoflines[13]
lineitems13 = aline13.split('=')
mf1 = lineitems13[1]
#print ("Minimum F1")
#print (mf1)
#Minimum F2 read from values.txt
aline14 = listoflines[14]
lineitems14 = aline14.split('=')
mf2 = lineitems14[1]
#print ("Minimum F2")
#print (mf2)
#Startup Lockout read from values.txt
aline15 = listoflines[15]
lineitems15 = aline15.split('=')
sl = lineitems15[1]
#print ("Startup Lockout")
#print (sl)
##########################################################################################
# Read existing values on PSI Board
# mostly taken from J.Bower Ser_Interface_PSI.py
import serial
import time
import csv
import os
def initialize_serialport():
global ser
ser = serial.Serial(port='/dev/ttyUSB0',
baudrate = 57600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1)
### routine to write a string to PSI board
def write_to_PSI(sendCommand):
ser.write((sendCommand).encode('utf-8')) #removed CR LF as PSI board doesnt seem to need them`
### routine to read a line (up to CR LF) from PSI board
### need to figure out how to deal wht the extra '>' prompt character that
### gets sent for some responses
def listen_to_PSI():
ser_bytes = ser.readline()
decoded_bytes = ser_bytes[0:len(ser_bytes)-2].decode('utf-8')
return decoded_bytes
### routine to turn logging mode ON if OFF
def turnLoggingON():
print("turning on logging")
write_to_PSI('l')
output = listen_to_PSI()
if output == 'Log Off':
print("logging was already on... turning it back on")
write_to_PSI('l')
### routine to turn logging mode OFF if ON
def turnLoggingOFF():
print("turning off logging")
write_to_PSI('l')
output = listen_to_PSI()
if output == 'Log On':
print("logging was already off... turning it back off")
write_to_PSI('l')
### routine to turn debug mode ON if OFF
def turnDebugON():
print("turning on debug")
write_to_PSI('o')
output = listen_to_PSI()
print("debug on:", output)
goofything = ser.read() # just read a character to get rid of the '>'
# print(goofything)
time.sleep(0.1)
if output == 'Debug Off':
print("Debug was already on... turning it back on")
write_to_PSI('o')
output = listen_to_PSI()
print("debug on:", output)
goofything = ser.read() # just read a character to get rid of the '>'
### routine to read contents of flash page
### ASSUMES PSI is in Debug Mode ON
def readFlashPage(page):
# print("reading page", page)
write_to_PSI('f')
output = listen_to_PSI()
if output == 'Page To Read:':
write_to_PSI(page)
flash = listen_to_PSI() #PSI echos back the input
# print('flash =',flash)
heading = listen_to_PSI() # the header CONTENTS:
# print(heading)
contents = listen_to_PSI() # the actual flash page contents
# print(contents)
goofything = ser.read() # just read a character to get rid of the '>'
# print(goofything)
list.append(contents)
print(flash + " = " + contents)
### create a list
list=[]
### here is where the main loop starts
def main():
initialize_serialport()
ser.reset_input_buffer()
# turnLoggingOFF() # make sure logging is not running
turnDebugON()
time.sleep(0.5) # just to let the PSI board catch its breath
readFlashPage('00')
time.sleep(0.5) # just to let the PSI board catch its breath
readFlashPage('01')
time.sleep(0.5) # just to let the PSI board catch its breath
readFlashPage('02')
time.sleep(0.5) # just to let the PSI board catch its breath
readFlashPage('03')
time.sleep(0.5) # just to let the PSI board catch its breath
readFlashPage('04')
time.sleep(0.5) # just to let the PSI board catch its breath
readFlashPage('05')
time.sleep(0.5) # just to let the PSI board catch its breath
readFlashPage('06')
time.sleep(0.5) # just to let the PSI board catch its breath
readFlashPage('07')
time.sleep(0.5) # just to let the PSI board catch its breath
readFlashPage('08')
time.sleep(0.5) # just to let the PSI board catch its breath
readFlashPage('09')
time.sleep(0.5) # just to let the PSI board catch its breath
readFlashPage('0A')
time.sleep(0.5) # just to let the PSI board catch its breath
readFlashPage('0B')
time.sleep(0.5) # just to let the PSI board catch its breath
readFlashPage('0C')
time.sleep(0.5) # just to let the PSI board catch its breath
readFlashPage('0D')
time.sleep(0.5) # just to let the PSI board catch its breath
readFlashPage('0E')
time.sleep(0.5) # just to let the PSI board catch its breath
readFlashPage('0F')
print(list)
# turnDebugOFF()
ser.close()
# python bit to figure how who started this
if __name__ == "__main__":
main()
###############################################################################
# Display current existing PSI Board Settings.
root = Tk()
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
#print("Screen width:", screen_width)
#print("Screen height:", screen_height)
#Center on screen
w = 350 # width for the Tk root
h = 600 # height for the Tk root
# get screen width and height
ws = root.winfo_screenwidth()
hs = root.winfo_screenheight()
# calculate x and y coordinates for the Tk root window
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
# set the dimensions of the screen
# and where it is placed
root.geometry('%dx%d+%d+%d' % (w, h, x, y))
# Title tk box
root.title("EXISTING Values on PSI Board")
# Create a label as a child of root window
my_text = Label(root,justify=LEFT, text=
'Laser DC Setpoint = '+ list[0]
+ '\n\nLaser temperature setpoint = '+ list[1]
+ '\n\nLaser AC setpoint = '+ list[2]
+ '\n\nLaser Tuning Rate = '+ list[3]
+ '\n\nLaser Calibration Constant = '+ list[4]
+ '\n\nLaser Temperature DAC Offset = '+ list[5]
+ '\n\nConcentration Offset = '+ list[6]
+ '\n\nPhoto Current Monitor Threshold = '+ list[7]
+ '\n\nCurrent Shutdown Record = '+ list[8]
+ '\n\nSerial Number = '+ list[9]
+ '\n\nModulator Gain = '+ list[10]
+ '\n\nF2 Correction for I = '+ list[12]
+ '\n\nF2 Correction for Q = '+ list[13]
+ '\n\nMinimum F1 = '+ list[14]
+ '\n\nMinimum F2 = '+ list[15]
+ '\n\nStartup Lockout = '+ list[16])
my_text.config(font=('helvetica', 10))
my_text.pack(padx=5, pady=5)
# Understood
Understood_button = Button(root, text='understood', command=root.destroy)
understood_button.pack()
root.mainloop()
##################################################################################
#now display data to be WRITTEN to board with option to continue or cancel.
root = Tk()
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
#print("Screen width:", screen_width)
#print("Screen height:", screen_height)
#Center on screen
w = 350 # width for the Tk root
h = 600 # height for the Tk root
# get screen width and height
ws = root.winfo_screenwidth()
hs = root.winfo_screenheight()
# calculate x and y coordinates for the Tk root window
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
# set the dimensions of the screen
# and where it is placed
root.geometry('%dx%d+%d+%d' % (w, h, x, y))
# Title tk box
root.title("Values to Write to PSI Board")
# Create a label as a child of root window
my_text = Label(root,justify=LEFT, text=
'Laser DC Setpoint = '+ ldcs
+ '\n\nLaser temperature setpoint = '+ lts
+ '\n\nLaser AC setpoint = '+ lacs
+ '\n\nLaser Tuning Rate = '+ ltr
+ '\n\nLaser Calibration Constant = '+ lcc
+ '\n\nLaser Temperature DAC Offset = '+ ltdo
+ '\n\nConcentration Offset = '+ co
+ '\n\nPhoto Current Monitor Threshold = '+ pcmt
+ '\n\nCurrent Shutdown Record = '+ csr
+ '\n\nSerial Number = '+ sn
+ '\n\nModulator Gain = '+ mg
+ '\n\nF2 Correction for I = '+ f2cfi
+ '\n\nF2 Correction for Q = '+ f2cfq
+ '\n\nMinimum F1 = '+ mf1
+ '\n\nMinimum F2 = '+ mf2
+ '\n\nStartup Lockout = '+ sl)
#my_text.config(font=('times', 10))
my_text.config(font=('helvetica', 10))
my_text.pack(padx=5, pady=5)
# continue writing values to PSI board
continue_button = Button(root, text='Continue Writing Values to PSI Board', command=root.destroy)
continue_button.pack()
# if CANCEL, kill program.
Cancel_button = Button(root, text='Stop to change values', command=quit)
Cancel_button.pack()
root.mainloop()
####################################################################################
# Write new values to PSI Board.
print("continuing to write :) ")
| true |
dc561c29ea34144f7baa50a64b1c4dd67f26b68f | Python | 4roses41/COM404 | /1.basics/3-decision/4-modulo-operator/bot.py | UTF-8 | 161 | 3.875 | 4 | [] | no_license | number = int(input("Please input a whole number: "))
number2 = number % 2
if number2 == 0:
print("the number is even")
else:
print("the number is Odd") | true |
390fd332ad95c8ae1815071198599e76d274796c | Python | RedPenguin101/safari-pymc3 | /Chapter3-Linear_Regression.py | UTF-8 | 20,888 | 3.890625 | 4 | [] | no_license |
# coding: utf-8
# # Modelling with Linear Regression
# ML is built on recurring patterns. One of them is the __linear model__.
#
# We'll cover
# * simple LR
# * Robust LR
# * Hierarchical LR
# * Polynomial LR
# * Multiple LR
# * Interactions
# * Variable variance
# In[2]:
import numpy as np
import pymc3 as pm
import arviz as az
import matplotlib.pyplot as plt
plt.style.use('seaborn-darkgrid')
from scipy import stats
import pandas as pd
# ## Simple Linear Regression
# Many problems can be stated in the form: we have a variable $x$ and we want to predict from that $y$. The variables are paried up like $\{(x_1,y_1),(x_2,y_2),\ldots,(x_n,y_n)\}$.
#
# In the simple LR model, bothe x and y and uni-dimensional continuous random variables. $y$ is known as a dependent, predicted or outcome variable, $x$ is the independent, predictor or input variable.
#
# if $x$ is multidimensional (i.e. represetned by a matrix rather than a 1d list), then we have multiple LR.
#
# ### Machine Learning
# An umbrella term for methods for automatically learning patterns from data, then take decisions. ML has a deep dependency on stats. Some jargon busting:
#
# a regression problem is an example of __supervised learning__. Supervised beacuse we know the X-Y pairs - in effect we know the answer and are trying to generalise rules in the dataset.
#
# __Features__ are put in place of variables.
#
# ### Linear regression models
# THe familiar equation $y_u = \alpha + x_i \beta$ is at the core of of LR - there is a linear relationship between $x$ and $y$, with $\beta$ controlling the slope and $\alpha$ the y intercept.
#
# There are several methods for getting to parameters of linear models. One is the __least squares fitting__ to try and find the line which minimises the sum of the square distance between the observations and the line. Alternatively you can think probablistically and generate a probablistic model. This has the advantage that you can get to values for $\alpha$ and $\beta$, but you can also quantify the uncertainty around those values. You can also have more flexibility in how the models are defined.
#
# An LR model can be expressed as
#
# $$y \sim N(\mu=\alpha+x\beta, \epsilon)$$
#
# with y assumed to have a gaussian distribution with mean $\alpha + \beta x$ and SD $\epsilon$
#
# Se we need to set priors for the parameters
#
# $$\alpha \sim N(\mu_\alpha, \sigma_\alpha)$$
#
# $$\beta \sim N(\mu_\beta, \sigma_\beta)$$
#
# $$\epsilon \sim |N(0, \sigma_\epsilon)$$
#
# And set our $\alpha$ prior to be a very flat normal. For $\beta$ you might have a general idea of the slope and how confident you are on it. $\epsilon$ you can set to be flat over a scale on the variable y. Alternatively for a weak prior for the SD you can set $\epsilon$ to be a uniform or half-cauchy. (The unform less so since it has strict boundaries, and that probably isn't a good reflection of the reality of the situation). For a strong priod for the SD you could use Gamma.
#
# The least squares method will generate a point estimate that agrees with the __maximum a posteriori (MAP)__, the mode of the posterior from a Bayesian simple LR model with flat priors.
#
# Let's build a model for this with some synthetic data
# In[2]:
#Data generation
np.random.seed(1)
N = 100
α_real = 2.5
β_real = 0.9
ϵ_real = np.random.normal(0,0.5,size=N)
x = np.random.normal(10,1,N)
y_real = α_real + β_real*x
y = y_real + ϵ_real
_, axes = plt.subplots(1,2,figsize=(8,4))
axes[0].plot(x,y,'C0.')
axes[0].set_xlabel('x')
axes[0].set_ylabel('y', rotation=0)
axes[0].plot(x,y_real,'k')
az.plot_kde(y, ax=axes[1])
axes[1].set_xlabel('y')
plt.tight_layout()
plt.show()
# In[3]:
with pm.Model() as model_g:
α = pm.Normal('α', mu=0, sd=10)
β = pm.Normal('β', mu=0, sd=1)
ϵ = pm.HalfCauchy('ϵ', 5)
μ = pm.Deterministic('μ', α+β*x)
y_pred = pm.Normal('y_pred', mu=μ, sd=ϵ, observed=y)
trace_g = pm.sample(2000, tune=1000)
# Note the new object: `Deterministic`. With this we're telling pyMC3 that mu is defined using a formula, not a probablity distribution.
# In[4]:
az.plot_trace(trace_g, var_names=['α','β','ϵ'])
plt.show()
# ### Autocorrelation for linear models
#
# Linear models lead to highly correlated parameter estimates for alpha and beta (see below plot). This is a consequence of our assumptions, that the result is a straight line passing through the center of the data, and changes to parameters 'spin' that line, meaning alpha and beta move in concert. They are _autocorrelated_.
#
# You can mitigate this autocorrelation by normalising x around the mean, $x' = x - \bar{x}$. This has the bonus side effect that your intercept value, y when x' = 0, is the value of y at the mean of the data, not the arbitrary x=0. More useful.
#
# Taking this a step further, you can fully standardise the data. This makes things easier for the algorithms, and also means you can use the same weakly informative priors without having to think about the scale of the data.
# In[5]:
az.plot_pair(trace_g, var_names=['α','β'], plot_kwargs={'alpha':0.1})
plt.show()
# ### Interpreting the posterior
# For LR, you can plot a line over your data with the mean posterior results of alpha and beta, and also plot the sampled lines. Notice that though the range of the sample lines narrows in the middle, they don't all go through a single point.
#
# Alternatively you can plot the HPD as a band. (2nd plot)
# In[6]:
plt.plot(x,y,'C0.')
alpha_m = trace_g['α'].mean()
beta_m = trace_g['β'].mean()
draws = range(0, len(trace_g['α']), 10)
plt.plot(x, trace_g['α'][draws]+trace_g['β'][draws]
* x[:,np.newaxis], c='gray', alpha = 0.1)
plt.plot(x, alpha_m + beta_m * x, c='k',
label = f'y={alpha_m:.2f} + {beta_m:.2f}*x')
plt.xlabel('x', fontsize=15)
plt.ylabel('y', rotation=0, fontsize=15)
plt.legend(fontsize=15)
plt.xticks(fontsize=15)
plt.yticks(fontsize=15)
plt.show()
# In[7]:
plt.plot(x, alpha_m + beta_m * x, c = 'k',
label = f'y={alpha_m:.2f} + {beta_m:.2f}*x')
sig = az.plot_hpd(x, trace_g['μ'], credible_interval=0.98, color='0.5', plot_kwargs={'alpha':0.1})
plt.xlabel('x', fontsize=15)
plt.ylabel('y', rotation=0, fontsize=15)
plt.legend(fontsize=15)
plt.xticks(fontsize=15)
plt.yticks(fontsize=15)
plt.show()
# Another option is to plot the HPD of the posterior predictive.
# In[8]:
ppc = pm.sample_posterior_predictive(trace_g, samples=2000, model=model_g)
plt.figure(figsize=(8,6))
plt.plot(x,y,'b.')
plt.plot(x, alpha_m + beta_m*x, c='k',
label = f'y={alpha_m:.2f} + {beta_m:.2f}*x')
az.plot_hpd(x, ppc['y_pred'], credible_interval=0.5, color='gray')
az.plot_hpd(x, ppc['y_pred'], color='gray', smooth=False)
# note, plot_hpd is smoothed by default, unsmoothed for illustraion
plt.xlabel('x', fontsize=15)
plt.ylabel('y', rotation=0, fontsize=15)
plt.legend(fontsize=15)
plt.xticks(fontsize=15)
plt.yticks(fontsize=15)
plt.show()
# ### Correlation coefficient
# For measuring the degree of linear dependence between two variables.
#
# The Pearson correlation coefficient $r$ is between -1 and 1. 0 is no correlation, -1 and 1 are perfect correlations in either direction.
#
# Don't confuse $r$ with the slope of the linear regression line. The relationship between the two is
#
# $$r = \beta \frac{\sigma_x}{\sigma_y}$$
#
# i.e. r is equal to the slope $\beta$ only when the standard devations of the variables are the same. That includes when we standardise the data.
#
# The __Coefficient of determination__ (for a _linear_ regression only) is $r^2$. Conceptually, it is the variance of the predicted values divided by the data, or, the proportion of the variance in the dependent variable which predicted from the independent variable.
#
# Using arviz we can get the r2 value and it's SD
# In[9]:
az.r2_score(y, ppc['y_pred'])
# ### Pearson with multivariate Gaussian
# Another route the Pearson is by estimating the covariance matrix ($\Sigma$) of a multi-variate Gaussian D (which is a generalisation of the Gaussian).
#
# For a bivariate gaussian we need 2 means, but instead of 2 SDs we need a 2x2 matrix, the __covariance matrix__.
#
# $$\Sigma = \begin{bmatrix}
# \sigma_{x1}^2 & \rho\sigma_{x1}\sigma_{x2} \\
# \rho\sigma_{x1}\sigma_{x2} & \sigma_{x2}^2
# \end{bmatrix}$$
#
# What this covariance martix represents is (in the top left and bottom right) the variance of each variable, and (in the TR and BL) the __covariance__, the variance _between_ variables. The covariance is expressed in terms of the SDs of the variables (how spread out they are individually) and of $\rho$, the Pearson correlation coefficient between the variables (how closely correlated they are to eachother.)
#
# Not here we have a single value for $\rho$, because 2 dimensions. For more variables we'll have more.
#
# Let's generate contour plots showing the multivariate mass of two normal distributions $x_1$ and $x_2$, both with means of 0. $x_1$ will have an SD of 1, and we'll show $x_2$ with an SD of either 1 (top row of the plot) or 2 (bottom row). The correlation coefficient $r$ will be various values between -0.9 and 0.9.
# In[10]:
sigma_x1 = 1
sigmas_x2 = [1,2]
rhos = [-0.9, -0.5, 0, 0.5, 0.9]
k, l = np.mgrid[-5:5:0.1, -5:5:0.1]
# mgrid(x1:y2:s1, x2:y2:s2) creates a dense mesh grid of size x by y in either direction, with step size s
# k and l are each 2s arrays of 100x100, [[-5. 100 times],[-4.9 100 times],...,[4.9 100 times],[5.0 100 times]]
pos = np.empty(k.shape+(2,))
# creates an empty array of specified size. k is a 100x100 array. the + (2,) adds a 3rd dimension, so shape is (100,100,2)
# i.e. a 100x100 grid where each element is a co-ordinate [x,y]
pos[:,:,0] = k
pos[:,:,1] = l
#
f, ax = plt.subplots(len(sigmas_x2), len(rhos),
sharex=True, sharey=True, figsize=(12,6),
constrained_layout=True)
plt.xticks(fontsize=15)
plt.yticks(fontsize=15)
for i in range(2):
for j in range(5):
sigma_x2 = sigmas_x2[i]
rho = rhos[j]
cov = [[sigma_x1**2, sigma_x1*sigma_x2*rho],
[sigma_x1*sigma_x2*rho, sigma_x2**2]]
rv = stats.multivariate_normal([0,0],cov)
ax[i,j].contour(k, l, rv.pdf(pos), cmap=plt.cm.viridis)
ax[i,j].set_xlim(-8,8)
ax[i,j].set_ylim(-8,8)
ax[i,j].set_yticks([-5,0,5])
ax[i,j].plot(0,0,
label=f'$\\sigma_{{x2}}$ = {sigma_x2:3.2f}\n$\\rho$ = {rho:3.2f}', alpha=0)
ax[i, j].legend(fontsize=15)
f.text(0.5, -0.05, f'$x_1$', ha='center', fontsize=18)
f.text(-0.05, 0.5, f'$x_2$', va='center', fontsize=18, rotation=0)
plt.show()
# Let's use a model to estimate the correlation coefficient.
#
# Since we don't know the values to go into the covariance matrix, put priors on the sigmas and rhos which feed into the covarinace, then manually build the cov matrix (there are other ways to do this, like the Wishart or LKJ priors):
# * mu ~ Norm(mean=(x_bar, y_bar), sd=10)
# * sigmas 1 and 2 ~ HalfNorm(sd=10)
# * rho ~ Uniform(-1,1)
# * r2 = rho**2
# * cov = deterministic on the sigmas and rhos
# * y_pred ~ MVNorm(mu, cov)
# In[11]:
data = np.stack((x,y)).T # creates a list of the coordinates [xi,yi]
with pm.Model() as pearson_model:
μ = pm.Normal('μ', mu=tuple(data.mean(0)), sd=10, shape=2) # mean(0) returns the means of x and y as a 2x1 array
σ_1 = pm.HalfNormal('σ_1', 10)
σ_2 = pm.HalfNormal('σ_2', 10)
ρ = pm.Uniform('ρ', -1.0, 1.0)
r2 = pm.Deterministic('r2', ρ**2)
cov = pm.math.stack(((σ_1**2,σ_1*σ_2*ρ),
(σ_1*σ_2*ρ,σ_2**2)))
y_pred = pm.MvNormal('y_pred', mu=μ, cov=cov, observed=tuple(data))
trace_p = pm.sample(1000)
# In[12]:
az.plot_trace(trace_p, var_names=['r2'])
plt.show()
az.summary(trace_p)
# We get a resulting distribution for r squared which is about 0.8, and an sd of 0.04. Compare this to the result we got from the posterior predictive and you'll see its pretty close.
# ## Robust LR
# We saw earlier that sometimes our assumption of normality fails. We used Student's t to more effectively deal with outliers. We can do the same thing with linear regression.
#
# Let's illustrate this using the 3rd group from the Anscombe quartet
# In[13]:
ans = pd.read_csv('data/anscombe.csv')
x_3 = ans[ans.group == 'III']['x'].values
y_3 = ans[ans.group == 'III']['y'].values
x_3 = x_3 - x_3.mean() # centering the data
_, ax = plt.subplots(1,2, figsize=(10,4))
beta_c, alpha_c = stats.linregress(x_3, y_3)[:2] # finds the linear regression line, returing tuple (slope, int)
ax[0].plot(x_3, (alpha_c+beta_c*x_3), 'k',
label=f'y = {alpha_c:.2f} + {beta_c:.2f} * x')
ax[0].plot(x_3, y_3, 'C0o')
ax[0].set_xlabel('x', fontsize=15)
ax[0].set_ylabel('y',rotation=0, fontsize=15)
ax[0].legend(fontsize=15)
az.plot_kde(y_3, ax=ax[1], rug=True)
ax[1].set_yticks([])
ax[1].set_xlabel('y', fontsize=15)
plt.tight_layout()
plt.show()
# Compare the models we get with a normal model and t model
# In[14]:
# normal model
with pm.Model() as anscombe3_model_g:
α = pm.Normal('α', mu=y_3.mean(), sd=1)
β = pm.Normal('β', mu=0, sd=1)
ϵ = pm.HalfCauchy('ϵ', 5)
μ = pm.Deterministic('μ', α+β*x_3)
y_pred = pm.Normal('y_pred', mu=μ, sd=ϵ, observed=y_3)
trace_anscombe_g = pm.sample(2000)
# In[15]:
# student t model. Using a shifted exponential for ν to avoid values too close to zero, which you'll recall causes issues.
# other common priors for ν are gamma(2,.1) and gamma(20,15)
with pm.Model() as anscombe3_model_t:
α = pm.Normal('α', mu=y_3.mean(), sd=1)
β = pm.Normal('β', mu=0, sd=1)
ϵ = pm.HalfNormal('ϵ', 5)
ν_ = pm.Exponential('ν_', 1/29)
ν = pm.Deterministic('ν', ν_ + 1)
y_pred = pm.StudentT('y_pred', mu=α+β*x_3, sd=ϵ, nu=ν, observed=y_3)
trace_anscombe_t = pm.sample(2000, tune=1000)
# In[16]:
alpha_mean_g = trace_anscombe_g['α'].mean()
beta_mean_g = trace_anscombe_g['β'].mean()
alpha_mean_t = trace_anscombe_t['α'].mean()
beta_mean_t = trace_anscombe_t['β'].mean()
plt.figure(figsize=(8,6))
plt.plot(x_3, y_3, 'o')
plt.plot(x_3, alpha_mean_g + beta_mean_g * x_3, '--', label='normal fit')
plt.plot(x_3, alpha_mean_t + beta_mean_t * x_3, label='student fit')
plt.plot(x_3, alpha_c + beta_c * x_3, '--', label='least squares fit')
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.show()
# Again we see that the Student T is more _robust_, because of its fatter tails it assigns less importance to outliers when fitting
#
# Let's take a look at the summary of the t model
# In[17]:
az.summary(trace_anscombe_t, var_names = ['α','β','ϵ','ν'])
# alpha, beta, and epsilon are very narrowly defined, with standard deviations of 0.0 (epsilon also has a mean of nil). This makes sense given we're fitting basically a straight line, except for the outlier.
#
# Now lets run ppc
# In[18]:
ppc = pm.sample_posterior_predictive(trace_anscombe_t, samples=200,
model=anscombe3_model_t)
data_ppc = az.from_pymc3(trace=trace_anscombe_t, posterior_predictive=ppc)
ax=az.plot_ppc(data_ppc, figsize=(8,5), mean=True)
plt.xlim(0,14)
plt.show()
# ## Hierarchical LR
# We saw hierarchical models in the last chapter. This also can be applied to LR, dealing with inferences at the group level by using hyperpriors.
#
# Lets generate some data
# In[4]:
N = 20
M = 8
idx = np.repeat(range(M-1),N)
idx = np.append(idx,7)
np.random.seed(314)
alpha_real = np.random.normal(2.5,0.5,size=M)
beta_real = np.random.beta(6,1,size=M)
eps_real = np.random.normal(0,0.5,size=len(idx))
y_m = np.zeros(len(idx))
x_m = np.random.normal(10,1,len(idx))
y_m = alpha_real[idx]+beta_real[idx]*x_m+eps_real
_,ax = plt.subplots(2,4,figsize=(10,5),
sharex=True, sharey=True)
ax = np.ravel(ax)
j,k=0,N
for i in range(M):
ax[i].scatter(x_m[j:k], y_m[j:k])
ax[i].set_xlabel(f'$x_{i}$', fontsize=15)
ax[i].set_ylabel(f'$y_{i}$', fontsize=15, rotation=0, labelpad=15)
ax[i].set_xlim(6,15)
ax[i].set_ylim(7,17)
j += N
k += N
plt.tight_layout()
plt.show()
# In[6]:
x_centered = x_m - x_m.mean() # center the data before modelling
with pm.Model() as model_unpooled:
α_tmp = pm.Normal('α_tmp',mu=0,sd=10,shape=M)
β = pm.Normal('β',mu=0,sd=10,shape=M)
ϵ = pm.HalfCauchy('ϵ', 5)
ν = pm.Exponential('ν', 1/30)
y_pred = pm.StudentT('y_pred', mu=α_tmp[idx]+β[idx]*x_centered,
sd=ϵ, nu=ν, observed=y_m)
α = pm.Deterministic('α', α_tmp - β * x_m.mean())
trace_model_unpooled = pm.sample(2000)
# In[7]:
az.plot_forest(trace_model_unpooled, var_names=['α','β'], combined=True)
plt.show()
# $\alpha_7$ and $\beta_7$ are very wide compared to the rest, and if you look at the scatter plots you can see why: x7 and y7 contain only 1 point. And you can't fit a line to s single point.
#
# So lets use the same trick that we used before: use hyper parameters to have the parameters be informed by the entire dataset
#
#
# In[10]:
with pm.Model() as hierarchical_model:
# hyper-priors
α_μ_tmp = pm.Normal('α_μ_tmp', mu=0, sd=10)
α_σ_tmp = pm.HalfNormal('α_σ_tmp', 10)
β_μ = pm.Normal('β_μ', mu=0, sd=10)
β_σ = pm.HalfNormal('β_σ', sd=10)
# priors
α_tmp = pm.Normal('α_tmp', mu=α_μ_tmp, sd=α_σ_tmp, shape=M)
β = pm.Normal('β', mu=β_μ, sd=β_σ, shape=M)
ϵ = pm.HalfCauchy('ϵ', 5)
ν = pm.Exponential('ν', 1/30)
y_pred = pm.StudentT('y_pred',
mu=α_tmp[idx] + β[idx] * x_centered,
sd=ϵ, nu=ν, observed=y_m)
α = pm.Deterministic('α', α_tmp - β * x_m.mean())
α_μ = pm.Deterministic('α_μ', α_μ_tmp - β_μ * x_m.mean())
α_σ = pm.Deterministic('α_sd', α_σ_tmp - β_μ * x_m.mean())
trace_hm = pm.sample(2000, tune=2000)
az.plot_forest(trace_hm, var_names=['α', 'β'], combined=True)
# In[11]:
_, ax = plt.subplots(2, 4, figsize=(10, 5), sharex=True, sharey=True,
constrained_layout=True)
ax = np.ravel(ax)
j, k = 0, N
x_range = np.linspace(x_m.min(), x_m.max(), 10)
for i in range(M):
ax[i].scatter(x_m[j:k], y_m[j:k])
ax[i].set_xlabel(f'x_{i}')
ax[i].set_ylabel(f'y_{i}', labelpad=17, rotation=0)
alpha_m = trace_hm['α'][:, i].mean()
beta_m = trace_hm['β'][:, i].mean()
ax[i].plot(x_range, alpha_m + beta_m * x_range, c='k',
label=f'y = {alpha_m:.2f} + {beta_m:.2f} * x')
plt.xlim(x_m.min()-1, x_m.max()+1)
plt.ylim(y_m.min()-1, y_m.max()+1)
j += N
k += N
plt.show()
# ### Correlation, causation and the messiness of life
# Suppose we want to know how much we will pay for gas to heat our home. Our bill we will call the dependent variable $y$.
#
# We know the the independent variable, the sun radiation, $x$.
#
# Calling the variables independent and dependent is nothing more than a convention, established relative to our model: our model predicts y from x, which dictates which variable we call dependent. We could equally infer the sun radiation from our bill, in which case the nomenclature would be invesrted. But by saying we infer the sin radiation from our bill, that's not to suggest that the amount of sun radiation is _caused_ by our gas bill, only that it is _correlated_ with it. _correlation does not imply causation_. THe model is separate from the phenomenon.
#
# A correlation can _support_ a causal link if you design the experiment well, but is not sufficient. For example global warming is correlated with higher CO2 levels. Just from this fact we can't infer which way the causality goes. It could be that there is a third variable which causes both higher temparatures and higher CO2 levels. We can do an experiment to gain some insight. For example you could do an fill glass bottles with air of different CO2 concentrations, expose them to sunlight, and measure the temperatures in the glass bottles. If the resultant temperatures are higher in the bottles which have more CO2, AND the levels of CO2 have not increased in the bottles, we can infer from this that higher CO2 levels create a greenhouse effect, and that temperature does not cause CO2 levels to increase.
#
# Relationships can be more complicated than they appear. For example higher temparatures can evaporate the oceans more quickly, releasing CO2. CO2 is less soluable in water at higher temperatures. So higher temperatures CAN cause increased levels of CO2 in the real world in a way that our experiment didn't allow for.
#
# In short, the real world is messy.
# ## Polynomial LR
# ## Multiple LR
# ## Interactions
# ## Variable variance
| true |
52aa12ec18089853bb69f1d8f4e4be0eb16be1cf | Python | soonfy/study_python | /crawl_douban/util/fs.py | UTF-8 | 533 | 2.78125 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'file system.'
__author__ = 'soonfy'
# modules
import os
def file_ready(filepath):
"""
judge filepath exists
@param filepath
@return boolean
"""
try:
if os.path.exists(os.path.split(filepath)[0]):
if os.path.isfile(filepath):
print('file exists...')
else:
print('no file...')
else:
os.mkdir(os.path.split(filepath)[0])
print('no file dir...')
return True
except Exception as e:
print(e)
return False
| true |
f03bfb6f48500d2b4b4925328d72f559186954c4 | Python | VitharMe/RCM-VitharMe | /run.py | UTF-8 | 4,112 | 2.546875 | 3 | [] | no_license | import RPi.GPIO as GPIO
import time
import Adafruit_GPIO.SPI as SPI
import Adafruit_SSD1306
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import subprocess
# Input pins:
L_pin = 27
R_pin = 23
C_pin = 4
U_pin = 17
D_pin = 22
A_pin = 5
B_pin = 6
GPIO.setmode(GPIO.BCM)
GPIO.setup(A_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Input with pull-up
GPIO.setup(B_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Input with pull-up
GPIO.setup(L_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Input with pull-up
GPIO.setup(R_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Input with pull-up
GPIO.setup(U_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Input with pull-up
GPIO.setup(D_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Input with pull-up
GPIO.setup(C_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Input with pull-up
# Raspberry Pi pin configuration:
RST = 24
# Note the following are only used with SPI:
DC = 23
SPI_PORT = 0
SPI_DEVICE = 0
# 128x64 display with hardware I2C:
disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)
# Initialize library.
disp.begin()
# Clear display.
disp.clear()
disp.display()
# Create blank image for drawing.
# Make sure to create image with mode '1' for 1-bit color.
width = disp.width
height = disp.height
image = Image.new('1', (width, height))
# Get drawing object to draw on image.
draw = ImageDraw.Draw(image)
# Draw a black filled box to clear the image.
draw.rectangle((0,0,width,height), outline=0, fill=0)
padding = 2
shape_width = 20
top = padding
bottom = height-padding
x = padding
logo = Image.open('rcmvitharme.png').resize((disp.width, disp.height), Image.ANTIALIAS).convert('1')
disp.image(logo)
disp.display()
time.sleep(1)
draw.rectangle((0,0,width,height), outline=0, fill=0)
font = ImageFont.truetype('8.ttf', 8)
fontM = ImageFont.truetype('8.ttf', 12)
fontL = ImageFont.truetype('8.ttf', 12)
draw.text((x, top), 'Choose payload', font=font, fill=255)
draw.text((x, top+20), 'SX OS', font=fontM, fill=255)
draw.text((x, top+40), 'Atmosphere', font=fontM, fill=255)
pu = 0
pd = 0
pb = 0
cmd = "sudo rm /boot/nx/payload.bin &"
subprocess.check_output(cmd, shell = True )
try:
while 1:
if GPIO.input(U_pin): # button is released
draw.rectangle((1,40,65,42), outline=0, fill=pu) #Up
else: # button is pressed:
draw.rectangle((1,40,65,42), outline=255, fill=1) #Up filled
pu = 1
pd = 0
if GPIO.input(D_pin): # button is released
draw.rectangle((1,60,123,62), outline=0, fill=pd) #down
else: # button is pressed:
draw.rectangle((1,60,123,62), outline=255, fill=1) #down filled
pu = 0
pd = 1
if GPIO.input(B_pin): # button is released
pass
else: # button is pressed:
if pu == 1:
draw.rectangle((0,0,width,height), outline=0, fill=0)
draw.text((x, top), 'SX OS', font=fontL, fill=255)
draw.text((x, top+15), 'Loading...', font=fontL, fill=255)
cmd = "sudo cp /boot/nx/payloads/sxos.bin /boot/nx/payload.bin"
subprocess.check_output(cmd, shell = True )
pb = 1
else:
draw.rectangle((0,0,width,height), outline=0, fill=0)
cmd = "sudo cp /boot/nx/payloads/fusee-primary.bin /boot/nx/payload.bin"
subprocess.check_output(cmd, shell = True )
draw.text((x, top), 'Atmosphere', font=fontL, fill=255)
draw.text((x, top+15), 'Loading...', font=fontL, fill=255)
pb = 1
if not GPIO.input(A_pin) and not GPIO.input(B_pin) and not GPIO.input(C_pin):
catImage = Image.open('happycat_oled_64.ppm').convert('1')
disp.image(catImage)
else:
# Display image.
disp.image(image)
disp.display()
time.sleep(.01)
if pb == 1:
time.sleep(20)
cmd = "sudo rm /boot/nx/payload.bin"
subprocess.check_output(cmd, shell = True )
break
except KeyboardInterrupt:
GPIO.cleanup()
| true |
a0e7ff5d566dbf014464724b3ae5a4740433adf0 | Python | tfabiha/Softdev-Semester-2-Final-Project | /ccereal/util/leaderboard.py | UTF-8 | 1,642 | 2.546875 | 3 | [] | no_license | import os, sqlite3
from util import config
def get_wins_losses():
db, c = config.start_db()
command = "SELECT username,wins,losses FROM users;"
c.execute(command)
all = c.fetchall()
config.end_db(db)
users = []
for item in all:
#dict[item[0]] = [item[1],item[2]]
users.append({'username':item[0],'wins':item[1],'losses':item[2]})
return users
def get_wins_losses_user(username):
db, c = config.start_db()
command = "SELECT username,wins,losses FROM users WHERE username = ?;"
c.execute(command,(username,))
all = c.fetchall()
config.end_db(db)
users = []
for item in all:
users.append({'username':item[0],'wins':item[1],'losses':item[2]})
return users[0]
def get_wins(username):
db, c = config.start_db()
command = "SELECT wins FROM users WHERE username = ?;"
c.execute(command,(username,))
wins = c.fetchone()[0]
config.end_db(db)
return wins
def add_wins(username):
db, c = config.start_db()
wins = get_wins(username)
wins += 1
command = "UPDATE users SET wins = ? WHERE username = ?;"
c.execute(command, (wins, username))
config.end_db(db)
def get_losses(username):
db, c = config.start_db()
command = "SELECT losses FROM users WHERE username = ?;"
c.execute(command,(username,))
losses = c.fetchone()[0]
config.end_db(db)
return losses
def add_losses(username):
db, c = config.start_db()
losses = get_losses(username)
losses += 1
command = "UPDATE users SET losses = ? WHERE username = ?;"
c.execute(command, (losses, username))
config.end_db(db)
| true |
5e224cbcb6ef1b78bacb0a997b0fbda1c8e1a458 | Python | duguzanzan/LearnToPython3 | /Lesson27.py | UTF-8 | 3,589 | 3.5625 | 4 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2019-06-10 11:03
# @Author : zan
# @File : Lesson27.py
# @Title : asyncio/async/await
'asyncio是Python3.4引入的标准库'
'asyncio的编程模式就是一个消息循环,从模块中获取一个EventLoop的引用,然后把需要执行的协程扔进EvenLoop中执行,就实现了异步IO'
'''
import asyncio
@asyncio.coroutine#把一个generator标记为coroutine类型,就可以扔到EventLoop中执行
def hello():
print('Hello,world!')
#异步调用asyncio.sleep(1)
r = yield from asyncio.sleep(1)#yield from语法可以让我们方便的调用另一个generator
print('Hello again!')
# 获取Eventloop
loop = asyncio.get_event_loop()
# 执行coroutine
loop.run_until_complete(hello())
loop.close()
'''
'''
asyncio.sleep()也是一个coroutine,所以线程不会等待asyncio.sleep(),而是直接中断并执行下一个消息循环
当asyncio.sleep()返回时,线程就可以从yield from拿到返回值,然后接着执行下一个语句
把asyncio.sleep(1)看成一个耗时1秒的IO操作,在此期间,主线程并未等待,而是去执行EventLoop中其他可以执行的coroutine
'''
'''
import threading
import asyncio
@asyncio.coroutine
def hello():
print('Hello world!(%s)' % threading.current_thread())
yield from asyncio.sleep(1)
print('Hello again!(%s)' % threading.current_thread())
loop = asyncio.get_event_loop()
tasks = [hello(),hello()]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
'''
'''
Hello world!(<_MainThread(MainThread, started 4484511168)>)
Hello world!(<_MainThread(MainThread, started 4484511168)>)
Hello again!(<_MainThread(MainThread, started 4484511168)>)
Hello again!(<_MainThread(MainThread, started 4484511168)>)
多个coroutine可以由一个线程并发执行
'''
'异步网络连接'
'''
import asyncio
@asyncio.coroutine
def wget(host):
print('wget %s...' % host)
connect = asyncio.open_connection(host, 80)
reader, writer = yield from connect
header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host
writer.write(header.encode('utf-8'))
yield from writer.drain()
while True:
line = yield from reader.readline()
if line == b'\r\n':
break
print('%s header > %s' % (host, line.decode('utf-8').rstrip()))
writer.close()
loop = asyncio.get_event_loop()
tasks = [wget(host) for host in ['www.sina.com.cn', 'www.sohu.com', 'www.163.com']]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
'''
'为了简化并更好的标识异步IO,从Python3.5开始引入新的语法,async和await'
'1.把@asyncio.coroutine 替换成 async'
'2.把yield from 替换成 await'
# import asyncio
#
# async def hello():
# print('Hello,world!')
# r = await asyncio.sleep(1)
# print('Hello again!')
#
# loop = asyncio.get_event_loop()
# loop.run_until_complete(hello())
# loop.close()
import asyncio
async def wget(host):
print('wget %s...' % host)
connect = asyncio.open_connection(host, 80)
reader, writer = await connect
header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host
writer.write(header.encode('utf-8'))
await writer.drain()
while True:
line = await reader.readline()
if line == b'\r\n':
break
print('%s header > %s' % (host, line.decode('utf-8').rstrip()))
writer.close()
loop = asyncio.get_event_loop()
tasks = [wget(host) for host in ['www.sina.com.cn', 'www.sohu.com', 'www.163.com']]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
| true |
08585c487ffe972efe8361c023d252c4709b5f30 | Python | PAIka2k/TextBoxespp | /utils/bboxes.py | UTF-8 | 768 | 3.125 | 3 | [] | no_license | import numpy as np
from numpy.linalg import norm
eps = 1e-10
def polygon_to_rbox3(xy):
# two points at the center of the left and right edge plus heigth
tl, tr, br, bl = xy
# length of top and bottom edge
dt, db = tr-tl, bl-br
# height is mean between distance from top to bottom right and distance from top edge to bottom left
h = (norm(np.cross(dt, tl-br)) + norm(np.cross(dt, tr-bl))) / (2*(norm(dt)+eps))
p1 = (tl + bl) / 2.
p2 = (tr + br) / 2.
return np.hstack((p1,p2,h))
def rbox3_to_polygon(rbox):
x1, y1, x2, y2, h = rbox
alpha = np.arctan2(x1-x2, y2-y1)
dx = -h*np.cos(alpha) / 2.
dy = -h*np.sin(alpha) / 2.
xy = np.reshape([x1-dx,y1-dy,x2-dx,y2-dy,x2+dx,y2+dy,x1+dx,y1+dy], (-1,2))
return xy
| true |
d8ae78029f2b4ce0c3cccb1b6426866eca805ecb | Python | jadsm98/holbertonschool-machine_learning | /supervised_learning/0x05-regularization/0-l2_reg_cost.py | UTF-8 | 298 | 2.65625 | 3 | [] | no_license | #!/usr/bin/env python3
"""module"""
import numpy as np
def l2_reg_cost(cost, lambtha, weights, L, m):
"""function"""
W = 0
for i in range(L):
weight = weights['W{}'.format(i+1)]
W += np.linalg.norm(weight)
reg_cost = cost + (lambtha/(2*m))*W
return reg_cost
| true |
a2bfb022f62d7f2b703389ac5fe8562e42c71af8 | Python | CYFFF/DAAF_re-id | /DAAF-Trinet/aggregators.py | UTF-8 | 261 | 2.609375 | 3 | [
"MIT"
] | permissive | import numpy as np
def mean(embs):
return np.mean(embs, axis=0)
def normalized_mean(embs):
embs = mean(embs)
return embs / np.linalg.norm(embs, axis=1, keepdims=True)
AGGREGATORS = {
'mean': mean,
'normalized_mean': normalized_mean,
}
| true |
8cf46337a97bb823482fe4ec7674d9ad1d699893 | Python | globus/globus-sdk-python | /tests/non-pytest/mypy-ignore-tests/get_identities.py | UTF-8 | 711 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | import uuid
from globus_sdk import AuthClient
zero_id = uuid.UUID(int=0)
# ok usages
ac = AuthClient()
ac.get_identities(ids="foo")
ac.get_identities(ids=zero_id)
ac.get_identities(ids=("foo", "bar"))
ac.get_identities(ids=(zero_id,))
ac.get_identities(usernames="foo,bar")
ac.get_identities(usernames=("foo", "bar"))
ac.get_identities(usernames=("foo", "bar"), provision=True)
ac.get_identities(usernames=("foo", "bar"), query_params={"provision": False})
# bad usage
ac.get_identities(usernames=zero_id) # type: ignore[arg-type]
ac.get_identities(usernames=(zero_id,)) # type: ignore[arg-type]
# test the response object is iterable
res = ac.get_identities(usernames="foo")
for x in res:
print(x)
| true |
82c06321c49d1f41af82b4ef1f8cc19667aad44a | Python | esdream/learn-tkinter | /canvas.py | UTF-8 | 1,435 | 3.59375 | 4 | [] | no_license | # _*_ coding: utf-8 _*_
"""Canvas Widget
Canvas widget is the container of image and graph.
"""
import tkinter as tk
from PIL import ImageTk, Image
window = tk.Tk()
window.title('my window')
window.geometry('800x400')
canvas = tk.Canvas(window, bg='blue', height=600, width=400)
# PhotoImage只支持gif或BMP格式图片
image_file = tk.PhotoImage(file='canvas_test.gif')
# anchor参数是图片的锚点,意思是将图片锚点放置到前两个参数规定的点上,例如anchor='center',前两个位置参数为(0, 0),则将图片的中心放置到(0, 0)
tkimage = canvas.create_image(0, 0, anchor='nw', image=image_file)
x0, y0, x1, y1 = 50, 50, 80, 80
# 绘制线条
line = canvas.create_line(x0, y0, x1, y1)
# 绘制圆形
oval = canvas.create_oval(x0, y0, x1, y1, fill='red')
# 绘制弧形,start是启示弧度,extent是终止弧度,按逆时针绘制
arc = canvas.create_arc(x0+30, y0+30, x1+30, y1+30, start=90, extent=210)
# 绘制长方形
rect = canvas.create_rectangle(100, 30, 100+20, 30+20)
# 使用ImageTk在canvas插入jpg格式图片
image_jpg = Image.open('canvas_test.jpg')
canvas.image = ImageTk.PhotoImage(image_jpg)
canvas.create_image(0, 300, image=canvas.image, anchor='nw')
canvas.pack()
def move_it(canvas, move_object):
canvas.move(rect, 1, 2)
move_button = tk.Button(window, text='move',
command=lambda: move_it(canvas, rect)).pack()
window.mainloop()
| true |
1ee8b59f11b176730a6e49704f7573b18623c54a | Python | biologyguy/Evopix | /resources/mutation.py | UTF-8 | 16,971 | 3.203125 | 3 | [] | no_license | #!/usr/bin/python3
from resources.Evo import *
from resources.LineSeg import *
from evp.models import *
from random import random, choice, randint
from math import cos, sin, radians, factorial
from copy import copy
import sys
from scipy.stats import gamma
# Mutation rates are the probability of an event happening per mutable character
mutation_rates = {"path_split": 0.0001, "point_split": 0.001, "del_point": 0.002, "point_move": 0.03,
"gradient_param": 0.01, "stop_split": 0.002, "del_stop": 0.001, "stop_params": 0.03,
"stroke_color": 0.05, "stroke_width": 0.01, "stroke_opacity": 0.01}
# test values for mutation rates.
#mutation_rates = {"path_split": 0.1, "point_split": 0.3, "del_point": 0.1, "point_move": 0.2,
# "gradient_param": 0.1, "stop_split": 0.2, "del_stop": 0.1, "stop_params": 0.5,
# "stroke_color": 0.1, "stroke_width": 0.1, "stroke_opacity": 0.1}
# 'Magnitudes' are coefficients that adjust mutational impact, determined empirically to 'feel' right
magnitudes = {"points": 0.03, "colors": 5, "opacity": 0.03, "max_stroke_width": 0.05, "stroke_width": 0.0005,
"stop_params": 0.015, "gradient_params": 0.015}
# choose() will break when k gets too big. Need to figure something else out.
def choose(n, k): # n = sample size. k = number chosen. ie n choose k
if k == 0 or k == n:
return 1
elif k == 1 or k == n - 1:
return n
else:
return factorial(n) / (factorial(k) * factorial(n - k))
def num_mutations(mu, num_items): # mu = probability of success per item
mutations = 0
test_value = random()
prob_sum = 0.
for k in range(num_items):
prob_sum += choose(num_items, k) * (mu ** k) * ((1. - mu) ** (num_items - k))
if prob_sum < test_value:
mutations += 1
continue
else:
break
return mutations
def pick(option_dict):
check_options = 0.
for option in option_dict:
check_options += option_dict[option]
if check_options != 1.0:
sys.exit("Error: %s, pick(). Options in option_dict must sum to 1")
rand_num = random()
for option in option_dict:
if rand_num < option_dict[option]:
return option
else:
rand_num -= option_dict[option]
def rand_move(coefficient):
# Using the SciPy package here to draw from a gamma distribution. Should try to implement this directly at some point.
distribution = gamma(1.15, loc=0.01, scale=0.4) # values determined empirically
rand_draw = distribution.rvs()
output = rand_draw * coefficient
return output
def move_points(path_size, points): # get path_size with path_size() function, and points is a list
distance_changed = rand_move(magnitudes["points"] * path_size)
direction_change = (random() * 360)
change_x = sin(radians(direction_change)) * distance_changed
change_y = cos(radians(direction_change)) * distance_changed
for point_index in range(len(points)):
points[point_index] = [points[point_index][0] + change_x, points[point_index][1] + change_y]
return points
def move_in_range(cur_value, val_range, magnitude):
dist_moved = rand_move(magnitude) * choice([1, -1])
new_value = dist_moved + cur_value
safety_check = 100
while new_value < min(val_range) or new_value > max(val_range):
if new_value < min(val_range):
new_value = min(val_range) + abs(min(val_range) - new_value)
elif new_value > max(val_range):
new_value = max(val_range) - abs(max(val_range) - new_value)
else:
sys.exit("Error: %s" % new_value)
if safety_check < 0:
import traceback
sys.exit("Popped safety valve on move_in_range()\n%s\n%s, %s, %s" % (traceback.print_stack(), cur_value,
val_range, magnitude))
safety_check -= 1
return new_value
def mutate_color(color): # Colour needs to be RGB hex values
components = [int(color[:2], 16), int(color[2:4], 16), int(color[4:], 16)]
which_component = randint(0, 2)
components[which_component] = round(move_in_range(components[which_component], [0., 255.], magnitudes["colors"]))
output = ""
for comp_index in range(3):
output += hex(components[comp_index])[2:].zfill(2)
return output
def mutate(evopic):
num_points = evopic.num_points()
# Insert new points. This duplicates a point wholesale, which causes the path to kink up. Maybe this behavior
# will need to be changed, but for now let's go with it to see how things unfold.
num_changes = num_mutations(mutation_rates["point_split"], num_points)
split_ids = []
while num_changes > 0:
path_id, point_id = choice(evopic.point_locations()) # using 'point_locations()' ensures proper distribution
if point_id < 0 or point_id in split_ids:
# in the unlikely event that a new point is selected for a split, or a point that has already been
# split, try again.
continue
split_ids.append(point_id)
path = evopic.paths[path_id]
new_point = copy(path.points[point_id])
order_index = path.points_order.index(point_id)
new_position = choice([order_index, order_index + 1])
if new_position == order_index:
new_point[2] = new_point[1]
path.points[point_id][0] = path.points[point_id][1]
else:
new_point[0] = new_point[1]
path.points[point_id][2] = path.points[point_id][1]
point_id *= -1
path.points[point_id] = new_point
path.points_order.insert(new_position, point_id)
evopic.point_locations().append((path_id, point_id))
num_changes -= 1
# delete points
num_changes = num_mutations(mutation_rates["del_point"], num_points)
while num_changes > 0:
path_id, point_id = choice(evopic.point_locations())
evopic.delete_point(path_id, point_id)
num_changes -= 1
# Move points. Points can change by:
# The point of one of the control handles move individually -> single: 70%
# The point and its control handles move equally -> all: 25%
# One of the control handles realigns with the other (smooths curve) -> equalize: 5%
move_rates = {"single": 0.7, "all": 0.25, "equalize": 0.05}
# Point and/or control handle(s)
num_changes = num_mutations(mutation_rates["point_move"], num_points)
while num_changes > 0:
path_id, point_id = choice(evopic.point_locations())
path = evopic.paths[path_id]
point = path.points[point_id]
move_type = pick(move_rates)
if move_type == "single":
which_point = randint(0, 2)
evopic.paths[path_id].points[point_id][which_point] = move_points(path.path_size(), [point[which_point]])[0]
if move_type == "all":
evopic.paths[path_id].points[point_id] = move_points(path.path_size(), point)
if move_type == "equalize":
# Distance between the moving control handle and path point stays the same, but the location of the moving
# handle pivots around the path point until it is on the line created by the path point and static control
# handle. This effectively smooths the Bezier curve.
static_handle = choice([0, 2])
move_handle = 2 if static_handle == 0 else 0
move_length = LineSeg(point[move_handle], point[1]).length()
static_line = LineSeg(point[static_handle], point[1])
# Find the new point by calculating the two intercepts between the Line and a circle of radius 'move_length'
# and then determining which of the two is furthest from 'static_handle'.
x1 = point[1][0] + move_length / (1 + (static_line.slope() ** 2)) ** 0.5
y1 = x1 * static_line.slope() + static_line.intercept()
new_point1 = [x1, y1]
x2 = point[1][0] - move_length / (1 + (static_line.slope() ** 2)) ** 0.5
y2 = x2 * static_line.slope() + static_line.intercept()
new_point2 = [x2, y2]
new_length1 = LineSeg(point[static_handle], new_point1).length()
new_length2 = LineSeg(point[static_handle], new_point2).length()
final_new_point = new_point1 if new_length1 > new_length2 else new_point2
evopic.paths[path_id].points[point_id][move_handle] = final_new_point
num_changes -= 1
# Stroke parameters
num_changes = num_mutations(mutation_rates["stroke_color"], len(evopic.paths))
while num_changes > 0:
path_id = choice(evopic.paths_order)
path = evopic.paths[path_id]
path.stroke[0] = mutate_color(path.stroke[0])
evopic.paths[path_id] = path
num_changes -= 1
num_changes = num_mutations(mutation_rates["stroke_width"], len(evopic.paths))
while num_changes > 0:
path_id = choice(evopic.paths_order)
path = evopic.paths[path_id]
max_range = path.path_size() * magnitudes["max_stroke_width"]
path.stroke[1] = move_in_range(path.stroke[1], [0., max_range], path.path_size() * magnitudes["stroke_width"])
evopic.paths[path_id] = path
num_changes -= 1
num_changes = num_mutations(mutation_rates["stroke_opacity"], len(evopic.paths))
while num_changes > 0:
path_id = choice(evopic.paths_order)
path = evopic.paths[path_id]
path.stroke[2] = move_in_range(path.stroke[2], [0., 1.], magnitudes["opacity"])
evopic.paths[path_id] = path
num_changes -= 1
# Gradient and stop parameters
stop_locations = evopic.stop_locations()
closed_path_ids = []
for path_id in evopic.paths_order:
if evopic.paths[path_id].type != "x":
closed_path_ids.append(path_id)
# Stop splits
num_changes = num_mutations(mutation_rates["stop_split"], len(stop_locations))
split_ids = []
while num_changes > 0:
num_changes -= 1
path_id, pick_stop = choice(stop_locations)
new_stop = copy(evopic.paths[path_id].stops[pick_stop])
if new_stop["stop_id"] < 0 or new_stop["stop_id"] in split_ids:
continue # in the unlikely event that a new stop is selected for another split, try again.
split_ids.append(new_stop["stop_id"])
# Set stop ID to negative of its parent, then I can hook onto neg IDs when it's time to save the new evopic
new_stop["stop_id"] *= -1
stop_position = choice([pick_stop, pick_stop + 1])
evopic.paths[path_id].stops.insert(stop_position, new_stop)
stop_locations = evopic.stop_locations()
# Stop deletions. Min # stops per path is 1.
num_changes = num_mutations(mutation_rates["del_stop"], len(stop_locations) - len(closed_path_ids))
while num_changes > 0:
deletable_stops = []
for path_id in evopic.paths_order:
if len(evopic.paths[path_id].stops) > 1:
for stop_index in range(len(evopic.paths[path_id].stops)):
deletable_stops.append((path_id, stop_index))
deleted_stop = choice(deletable_stops)
del evopic.paths[deleted_stop[0]].stops[deleted_stop[1]]
num_changes -= 1
stop_locations = evopic.stop_locations()
# Len(path_ids) below is * 2 because they can be radial or linear
num_changes = num_mutations(mutation_rates["gradient_param"], len(closed_path_ids) * 2)
while num_changes > 0:
path_id = choice(closed_path_ids)
path = evopic.paths[path_id]
grad_type = choice(["linear", "radial"])
if grad_type == "linear":
position = choice(range(len(path.linear)))
path.linear[position] = move_in_range(path.linear[position], [0., 1.], magnitudes["gradient_params"])
else:
position = choice(range(len(path.radial)))
path.radial[position] = move_in_range(path.radial[position], [0., 1.], magnitudes["gradient_params"])
evopic.paths[path_id] = path
num_changes -= 1
# Mutate the stop parameters
num_changes = num_mutations(mutation_rates["stop_params"], len(stop_locations))
while num_changes > 0:
path_id, stop_pos = choice(stop_locations)
path = evopic.paths[path_id]
stop = path.stops[stop_pos]
position = choice((0, 1, 2))
if position == 0:
stop["params"][0] = mutate_color(stop["params"][0])
else:
stop["params"][position] = move_in_range(stop["params"][position], [0., 1.], magnitudes["stop_params"])
path.stops[stop_pos] = stop
num_changes -= 1
# Path splits. Cuts a path into two pieces, joining each exposed end to its partner if the path is closed,
# or just slicing it otherwise.
# Note that the larger of the two halves gets to keep the original path ID
num_changes = num_mutations(mutation_rates["path_split"], len(evopic.paths_order))
split_ids = []
while num_changes > 0:
num_changes -= 1 # decrement num_changes early to prevent infinite loops
path_id, point_id1 = choice(evopic.point_locations())
if path_id < 0 or (path_id in split_ids): # In case a path has already been split, skip
continue
split_ids.append(path_id)
path = evopic.paths[path_id]
if path.id < 0:
print(path, "\n")
print(path_id, point_id1)
sys.exit()
if len(path.points) == 1: # Can't split a path with only one point.
continue
new_path = copy(path)
new_path.id *= -1
new_path.points = {}
point_index = path.points_order.index(point_id1)
if path.type == "x":
if point_index in [0, (len(path.points_order) - 1)]:
new_path.points_order = [point_id1]
new_path.points[point_id1] = path.points[point_id1]
evopic.delete_point(path_id, point_id1)
else:
new_position = choice([point_index, point_index + 1])
if len(path.points_order[new_position:]) < (len(path.points_order) / 2):
new_path.points_order = path.points_order[new_position:]
else:
new_path.points_order = path.points_order[:new_position]
for point_id in new_path.points_order:
new_path.points[point_id] = path.points[point_id]
evopic.delete_point(path_id, point_id)
else:
# This next bit is for closed paths, where a second point has to be chosen for the split to cut through
while True:
point_id2 = choice(path.points_order)
if point_id1 == point_id2:
continue
else:
break
# Get the points in order from left to right
point1_index, point2_index = [path.points_order.index(point_id1), path.points_order.index(point_id2)]
point1_index, point2_index = [min(point1_index, point2_index), max(point1_index, point2_index)]
point_id1, point_id2 = [path.points_order[point1_index], path.points_order[point2_index]]
if len(path.points_order) > 3:
outer_path = path.points_order[:point1_index] + path.points_order[point2_index + 1:]
inner_path = path.points_order[point1_index:point2_index + 1]
elif len(path.points_order) == 3:
outer_path = [point_id1, point_id2]
for point_id in path.points_order:
if point_id in outer_path:
continue
else:
inner_path = [point_id]
elif len(path.points_order) == 2:
outer_path = [point_id1]
inner_path = [point_id2]
else:
sys.exit("There is an error in closed path splitting")
if len(outer_path) >= len(inner_path):
new_path.points_order = inner_path
else:
new_path.points_order = path.points_order[:point1_index + 1] + path.points_order[point2_index:]
for point_id in new_path.points_order:
new_path.points[point_id] = path.points[point_id]
evopic.delete_point(path_id, point_id)
order_index = evopic.paths_order.index(path_id)
new_position = choice([order_index, order_index + 1])
evopic.paths[new_path.id] = new_path
evopic.paths_order.insert(new_position, new_path.id)
evopic.find_extremes()
return evopic
#-------------------------Sandbox-------------------------------#
if __name__ == '__main__':
with open("../genomes/sue.evp", "r") as infile:
bob = Evopic(infile.read()) | true |
401a912f75237f439c03b057cd7df761a9677b00 | Python | sweetherb100/python | /interviewBit/DynamicProgramming/02_Best_Buy_Sell_Stocks_2.py | UTF-8 | 1,105 | 4.125 | 4 | [] | no_license | '''
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit.
You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times).
However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Example :
Input : [1 2 3]
Return : 2
'''
class Solution:
# @param A : tuple of integers
# @return an integer
def maxProfit(self, A):
# Exception
if len(A) == 0:
return 0
bestprofit = 0
start = A[0]
for i in range(1, len(A), 1):
if start > A[i]: #minimize the start (if starting point is larger, then update the starting point)
start = A[i]
else: # start < A[i]
bestprofit += (A[i] - start) #multiple transaction every time start < A[i]
start = A[i] #updating starting point after finishing transaction
return bestprofit
solution = Solution()
print(solution.maxProfit([1,2,3])) | true |
e2275e98478ae3341d603ec5b6d56b4119e6e0be | Python | scott-gordon72/python_crash_course | /chapter_7/dream_vacation.py | UTF-8 | 356 | 3.703125 | 4 | [] | no_license | dream_vacations = []
vacation = ""
while vacation != 'q':
vacation = input(
f"If you could visit one place in the world, where would you go?")
if vacation != 'q':
dream_vacations.append(vacation)
print("Results of the poll are: ")
if dream_vacations:
for dream_vacation in dream_vacations:
print(f"\t{dream_vacation}")
| true |
fce9b048b89632b7c821582bc1902e766e7b2d76 | Python | Ujjwalgutta/MachineLearningAlgorithms | /ConvolutionalNeuralNetworks/code/maxpool.py | UTF-8 | 3,801 | 2.875 | 3 | [] | no_license | import numpy as np
class MaxPoolLayer(object):
def __init__(self, size=2):
"""
MaxPool layer
Ok to assume non-overlapping regions
"""
self.locs = None # to store max locations
self.size = size # size of the pooling
def forward(self, x):
"""
Compute "forward" computation of max pooling layer
Parameters
----------
x : np.array
The input data of size number of training samples x number
of input channels x number of rows x number of columns
Returns
-------
np.array
The output of the maxpooling
Stores
-------
self.locs : np.array
The locations of the maxes (needed for back propagation)
"""
self.x = np.copy(x)
#self.locs = []
n_s = x.shape[0]
i_c = x.shape[1]
n_r = x.shape[2]
n_c = x.shape[3]
stride = self.size
r1 = np.zeros((n_s,i_c,((n_r-self.size)/stride)+1,((n_c-self.size)/stride)+1))
#self.locs = np.zeros(x.shape)
self.locs = np.zeros((n_s, i_c, ((n_r - self.size) / stride) + 1, ((n_c - self.size) / stride) + 1))
out_max = np.zeros((n_s, i_c, ((n_r - self.size) / stride) + 1, ((n_c - self.size) / stride) + 1))
'''
for l in range(n_s):
for k in range(i_c):
i1=0
for i in range(0,n_r,self.size):
j1=0
for j in range(0,n_c,self.size):
self.locs[l,k,i1,j1] = np.argmax(x[l,k,i:i+self.size,j:j+self.size])
j1 = j1+1
i1 = i1+1
'''
for l in range(n_s):
for i in range(1+(n_r-self.size)/stride):
for j in range(1+(n_c-self.size)/stride):
i1 = i * stride
i2 = i * stride + self.size
j1 = j * stride
j2 = j * stride + self.size
window = self.x[l, :, i1:i2, j1:j2]
out_max[l,:,i,j] = np.max(window.reshape((i_c,self.size*self.size)),axis =1)
self.locs[l,:,i,j] = np.argmax(window.reshape((i_c,self.size*self.size)),axis =1)
return out_max
#raise NotImplementedError
def backward(self, y_grad):
"""
Compute "backward" computation of maxpool layer
Parameters
----------
y_grad : np.array
The gradient at the output
Returns
-------
np.array
The gradient at the input
"""
n_s = self.x.shape[0]
i_c = self.x.shape[1]
n_r = self.x.shape[2]
n_c = self.x.shape[3]
stride=np.copy(self.size)
x_grad = np.zeros(self.x.shape)
for l in range(n_s):
for k in range(i_c):
for i in range(1+(n_r-self.size)/stride):
for j in range(1+(n_c-self.size)/stride):
i1 = i*stride
i2 = i*stride + self.size
j1 = j*stride
j2 = j*stride + self.size
window = self.x[l,k,i1:i2,j1:j2]
window2 = np.reshape(window,(self.size*self.size))
window3 = np.zeros(window2.shape)
a1 = np.where(window2 == np.max(window2))
#window3[np.argmax(window2)] = 1
window3[a1] = 1
x_grad[l,k,i1:i2,j1:j2] = np.reshape(window3,(self.size,self.size)).astype('float64') * y_grad[l,k,i,j].astype('float64')
return x_grad
#raise NotImplementedError
def update_param(self, lr):
pass
| true |
8e0a0d83b19ab6e9dc7045aa40c076b7a21257f9 | Python | GuptAmit725/Stacks | /using_list.py | UTF-8 | 988 | 4.34375 | 4 | [] | no_license | class Stacks():
def __ini__(self):
self.stack = []
def isEmpty(self):
"""
This function checks if the stack is empty or not.
"""
return self.stack is None
def push(self,ele):
"""
Adds the element to the end of the stack.
"""
self.stack.push(ele)
def pop(self):
"""
returns the last element of the stack and deletes the element permanently.
"""
if not self.isEmpty():
return self.stack.pop()
else:
return -1
def peek(self):
"""
this function returns the last,
element withous deleting the elemnet.
"""
if not self.isEmpty():
return self.stack[-1]
else:
return -1
s = Stacks()
print('peek')
print('pop')
print('push')
do = input('What exactly you wan to do?')
if do=='push':
ele = input(int('inter the element you want to add. : '))
s.push(ele)
elif do == 'pop':
s.pop()
elif do == 'peek':
s.peek()
else:
print('Enter the valid operation you want tio do.')
| true |
11e65514740dcd6b8f1dff438f039bb7fc1a7f42 | Python | daniel-reich/ubiquitous-fiesta | /eZ9Fimj4ddpr7Ypof_18.py | UTF-8 | 116 | 3.078125 | 3 | [] | no_license |
def mumbling(s):
return '-'.join([(x*i).capitalize()
for i, x in enumerate(s, start=1)])
| true |
c053d1d21cd37257cb55dc37911ae43495814cb6 | Python | Galsor/stock_autofeature | /src/data/stock.py | UTF-8 | 3,808 | 2.578125 | 3 | [] | no_license | import logging
from typing import Tuple
import pandas as pd
import json
from pathlib import Path
from scipy.sparse import data
import src.config as cfg
from src.data.alpha_vantage_api import get_data_from_alpha_vantage
default_settings = cfg.STOCK_SETTINGS
class Stock:
def __init__(self, symbol:str, save=False) -> None:
self.symbol = symbol
self._dohlcv, metadata = self.load_existing_dataset()
if self._dohlcv is None:
self._dohlcv, metadata = get_data_from_alpha_vantage(symbol= symbol, **default_settings)
self._dohlcv.sort_index(ascending=cfg.SORT_STOCK_ASCENDING, inplace=True)
if save:
self.save(self._dohlcv, metadata)
@property
def ohlc(self) -> pd.DataFrame:
""" Open, Low, High, Close with dates as index"""
return self.dohlcv[cfg.DOHLC].set_index(cfg.DATE)
@property
def ohlcv(self) -> pd.DataFrame:
""" Open, Low, High, Close and volumes with dates as index"""
return self.dohlcv.set_index(cfg.DATE)
@property
def dohlcv(self) -> pd.DataFrame:
""" Dates, Open, Low, High, Close and Volumes with integer indexes"""
return self._dohlcv
@property
def _daily_evolution(self) -> pd.Series:
return self._dohlcv[cfg.CLOSE] - self._dohlcv[cfg.OPEN]
@property
def _next_day_evolution(self) -> pd.Series:
return self._daily_evolution.shift(cfg.SHIFT)
@property
def _next_day_evolution_ratio(self) -> pd.Series:
return self._next_day_evolution/self._dohlcv.shift(cfg.SHIFT)[cfg.OPEN]
# ----------- Data accessors -----------
@property
def labels(self) -> pd.DataFrame:
s_label = self._next_day_evolution_ratio.apply(lambda x : 0 if x < cfg.BREAKEVEN else x/x) # x/x to return nan if needed
return pd.DataFrame(s_label)
@property
def training_data(self) -> Tuple[pd.DataFrame, pd.DataFrame]:
return self.ohlcv.iloc[:-1], self.labels[:-1]
@property
def features(self) -> pd.DataFrame:
return self.load_existing_features()
@property
def last_data(self) -> pd.DataFrame:
return self.ohlcv.iloc[-1]
# ----------- File paths -----------
@property
def data_filepath(self) -> Path:
return Path(cfg.RAW_DATA_DIR) / f"{self.symbol}.csv"
@property
def features_filepath(self) -> Path:
return Path(cfg.PROCESSED_DATA_DIR) / f"{self.symbol}_all_features.csv"
@property
def metadata_filepath(self) -> Path:
return Path(cfg.RAW_DATA_DIR) / f"{self.symbol}_metadata.json"
# ----------- File load & save utils -----------
def load_existing_dataset(self) -> Tuple[pd.DataFrame, pd.DataFrame]:
if self.data_filepath.exists() and self.metadata_filepath.exists():
data = pd.read_csv(self.data_filepath)
with open(self.metadata_filepath, 'r') as fp:
metadata = json.load(fp)
return data
elif self.data_filepath.exists():
return pd.read_csv(self.data_filepath), None
else:
return None, None
def load_existing_features(self) -> pd.DataFrame:
try :
return pd.read_csv(self.features_filepath)
except FileNotFoundError:
logging.warning("No features file found.\
Processed raw data with `make features` to enable this attribute.")
return None
def save(self, data, metadata) -> str:
"""Save Raw DOHLCV data"""
data.to_csv(self.data_filepath, index=False)
with open(self.metadata_filepath, 'w') as fp:
json.dump(metadata, fp)
return self.data_filepath
if __name__ == '__main__':
Stock("aapl", save=True)
| true |
1eaf66c90b3a2c86ce880f619e14c9b3596a43cd | Python | krislitman/CoffeeShopFinderBE | /app/api/tests.py | UTF-8 | 1,763 | 2.609375 | 3 | [] | no_license | from django.test import TestCase
import unittest
import pdb
import json
from rest_framework.test import APIRequestFactory, APIClient, RequestsClient
from .models import CoffeeShop, FavoriteShop
class CoffeeShopTest(unittest.TestCase):
def setUp(self):
CoffeeShop.objects.create(
name='Starbucks',
is_closed=True,
location={"Tampa": "FL"},
yelp_id='fakeid123'
)
CoffeeShop.objects.create(
name='Kahwa Coffee',
is_closed=False,
location={"Tampa": "FL"},
yelp_id='fakeid321'
)
ging = CoffeeShop.objects.create(
name='Gingerbeard Coffee',
is_closed=True,
location={"Tampa": "FL"},
yelp_id='fakeid987'
)
client = RequestsClient()
self.response = client.get('http://localhost:8000/api/v1/coffeeshops/')
self.response_two = client.get(
'http://localhost:8000/api/v1/coffeeshops/{}'.format(ging.id))
def tearDown(self):
CoffeeShop.objects.all().delete()
def test_coffee_shop_can_be_retrieved(self):
shops = json.loads(self.response.content)
self.assertEqual(self.response.status_code, 200)
self.assertEqual(shops[0]['name'], 'Starbucks')
self.assertEqual(shops[1]['name'], 'Kahwa Coffee')
self.assertEqual(shops[2]['name'], 'Gingerbeard Coffee')
self.assertEqual(CoffeeShop.objects.count(), 3)
def test_can_return_a_single_coffee_shop(self):
shop = json.loads(self.response_two.content)
self.assertEqual(self.response_two.status_code, 200)
self.assertEqual(shop['name'], 'Gingerbeard Coffee')
if __name__ == '__main__':
unittest.main()
| true |
03bdebbbdae9e36999d779e5685bea8d95bec8f6 | Python | eserebry/holbertonschool-higher_level_programming | /0x0B-python-input_output/4-append_write.py | UTF-8 | 362 | 3.65625 | 4 | [] | no_license | #!/usr/bin/python3
def append_write(filename="", text=""):
""" appends a string at the end of a text file (UTF8)\
and returns the number of characters added
Args:
filename(str): filename
text(str): text to be written
"""
num = 0
with open(filename, mode="a", encoding="utf-8") as myFile:
return myFile.write(text)
| true |
a861e31e23a1007c598fd211544617c87e3dcb7d | Python | NobuyukiInoue/LeetCode | /Problems/2200_2299/2231_Largest_Number_After_Digit_Swaps_by_Parity/Project_Python3/Largest_Number_After_Digit_Swaps_by_Parity.py | UTF-8 | 2,157 | 3.5 | 4 | [] | no_license | import heapq
import os
import sys
import time
from typing import List, Dict, Tuple
class Solution:
def largestInteger(self, num: int) -> int:
# 24ms - 42ms
len_num = len(str(num))
arr = [int(n) for n in str(num)]
odd, even = [], []
for n in arr:
if n & 1:
odd.append(n)
else:
even.append(n)
odd.sort()
even.sort()
res = 0
for i in range(len_num):
if arr[i] & 1:
res = res*10 + odd.pop()
else:
res = res*10 + even.pop()
return res
def largestInteger_heapq(self, num: int) -> int:
# 31ms - 49ms
len_num = len(str(num))
arr = [int(n) for n in str(num)]
odd, even = [], []
for n in arr:
if n & 1:
heapq.heappush(odd, n)
else:
heapq.heappush(even, n)
res, col = 0, 1
for i in range(len_num - 1, -1, -1):
if arr[i] & 1:
res += heapq.heappop(odd)*col
else:
res += heapq.heappop(even)*col
col *= 10
return res
def main():
argv = sys.argv
argc = len(argv)
if argc < 2:
print("Usage: python {0} <testdata.txt>".format(argv[0]))
exit(0)
if not os.path.exists(argv[1]):
print("{0} not found...".format(argv[1]))
exit(0)
testDataFile = open(argv[1], "r")
lines = testDataFile.readlines()
for temp in lines:
temp = temp.strip()
if temp == "":
continue
print("args = {0}".format(temp))
loop_main(temp)
# print("Hit Return to continue...")
# input()
def loop_main(temp):
flds = temp.replace("\"", "").replace("[", "").replace("]", "").rstrip()
num = int(flds)
print("num = {0:d}".format(num))
sl = Solution()
time0 = time.time()
result = sl.largestInteger(num)
time1 = time.time()
print("result = {0:d}".format(result))
print("Execute time ... : {0:f}[s]\n".format(time1 - time0))
if __name__ == "__main__":
main()
| true |
f3d2b6fc8b9638acc6bc3deb97c767f06d652b0e | Python | McCree23/pictest | /展示灰度化图片.py | UTF-8 | 647 | 2.71875 | 3 | [] | no_license | import os
import cv2
import numpy
pwd=os.getcwd()
name=os.listdir(pwd)
for filename in name:
if(filename[-4:]=='Jpeg'):
img=cv2.imread(pwd+'\\'+filename)#读取一个图片,定义名称为img
cv2.namedWindow('input', cv2.WINDOW_AUTOSIZE)#定义显示窗口尺寸
cv2.imshow('input', img)#展示图片img,窗口名为input
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)#将img转化为cv2.COLOR_BGR2GRAY类型,定义名称为gray
cv2.imwrite('gray.png', gray)#把gary输出为图片,定义名称为gray.png
cv2.imshow('gray', gray)
cv2.waitKey(0)
cv2.destroyAllWindows()
| true |
8f393b60a53c691bc02e984450e290c22586663d | Python | CaseyMiddleton/2021_friendship_algorithm | /Clair_Huffine.py | UTF-8 | 2,585 | 3.6875 | 4 | [] | no_license | import sys
## Function to play friendship algorithm game
def play_game():
## START GAME
# initialize the user input to 0
user_entry = 0
# ask the user to make their own input (1 to play or 2 to exit):
while user_entry != 1 and user_entry != 2: user_entry = input('Select Option!\n1. Play Game\n2. Exit Game\n\nYour Selection: ')
# if the user selects 1, they want to play! Ask them questions and wait for their answers.
while user_entry == 1 :
## STEP 1 HERE
total_points = 0
answer_one = int(input('Do you want to be friends? \n1. Yes \n2. No\n\nYour Selection: '))
## STEP 2&3 HERE
if answer_one == 1 :
print('Sweet! But first, a few important questions...')
elif answer_one == 2 :
print("Well...maybe later!")
break
else total_points += 0
## Q2
answer_two = int(input("Do you absolutely love plants??? \n1. Heck yeah! \n2. Okay maybe not /that/ much...\n\nYour Selection:"))
if answer_two == 1 : total_points += 5
answer_two_one = int(input("Do you want more plants? \n1. Never too many \n2. I already have so many to take care of! \n\nYour Selection:"))
if answer_two_one == 1 : total_points += 5
elif answer_two_one == 2 : total_points += 0
else: total_points += 0
elif answer_two == 2 : total_points =+ 0
else total_points += 0
## Q3
answer_three = int(input("What is your favorite outdoor activity? \n1. Hiking \n2. Rockclimbing \n3. Running \n\nYour Selection:"))
if answer_three == 1 : total_points += 5
elif answer_three == 2 : total_points += 0
elif answer_three == 3 : total_points -= 5
else total_points += 0
## STEP 4 HERE
print(total_points)
if total_points == 15 : print("Let's go hike to a plant shop!")
elif total_points == 10 : print("We will get along just fine (:")
elif total_points == 5 : print("Nice to meet you!")
else: print("Well I am sure we can still make it work")
user_entry = input('Select Option!\n1. Play Game\n2. Exit Game\n\nYour Selection: ')
user_entry = int(user_entry)
## Function call to play friendship algorithm game
play_game()
| true |
fa0dccdc4e1f1959a024c6003bda3b631a9ed4d9 | Python | litao-Albert/spider | /ATM/Dome03.py | UTF-8 | 1,428 | 3.3125 | 3 | [] | no_license | # def add (a,b):
# return a+b
# print(add(34,45))
# def sum (n):
# sum1=0
# for i in range(1,n+1):
# sum1=sum1+i
# i=i+1
# return sum1
# print(sum(100))
# def add(*a):
# return sum(a)
# x=add(1,2)
# print(x)
# def info(i,k,j):
# if k=="+":
# return i+j
# if k=='-':
# return i-j
# if k=='*':
# return i*j
# if k=='/':
# return i/j
#
# print(info(1,"/",2))
#简单的计算器
# def info(a,b,c):
# print(a+b)
# def info1(a,b,c):
# print(a*b)
# def info2(a,b,c):
# print(a-b)
# def info3(a,b,c):
# print(a/b)
# a=float(input('a:'))
# c=input('符号:')
# b=float(input('b:'))
# if c=='+':
# info(a,b,c)
# if c=='*':
# info1(a,b,c)
# if c=='-':
# info2(a,b,c)
# if c=='/':
# info3(a,b,c)
#实现count的方法
# s='kjjjsidjsidjsdsdsd'
# def count(string,str,begin=0,end=0):
# # news=string[begin:end]
# li=string.split(str)
# print(len(li)-1)
# count(s,'j',0,len(s))
# def count(string,substr,begin=0,end=0):
# newstr=string[begin:end]
# sum=0
# l=len(substr)
# for i in range(len(newstr)):
# if newstr[i:i+l]==substr:
# sum+=1
# return sum
# s='hhhkkomjijjm'
# print(count(s,'m',0,len(s)))
# def add (a,*b):
# return a,b
# print(add(1,2,3,4,5))
list1=[2,3,8,4,9,5,7]
list2=[5,6,10,17,11,2]
list3=list1+list2
list3.sort()
s=set(list3)
s1=list(s)
print(s1)
| true |
90bff82367cfc19ef762e8437c35d930cad7d0ff | Python | hayesbh/TaskTreeVisualization | /parse_tabs.py | UTF-8 | 4,924 | 2.671875 | 3 | [
"MIT"
] | permissive | import csv
import json
import os.path
import cgitb
cgitb.enable()
class TaskHTN:
def __init__(self, task_name=None, order=None, action_set=[]):
self._children = []
self._values = {'name': task_name, 'actions': action_set, 'order_invariant': order, 'support_actions': []}
def add_child(self,childHTN):
self._children.append(childHTN)
def remove_child(self,child):
if child in self._children:
self._children.remove(child)
return True
else:
return False
@property
def children(self):
return self._children
@property
def values(self):
return self._values
def is_order_invariant(self):
return self._values['order_invariant'] is True
def is_order_agnostic(self):
return not self.is_order_invariant()
def to_json(self):
return json.dumps(self.to_dict())
def to_dict(self):
self_dict = {'values': self._values, 'children': []}
if len(self._children) > 0:
self_dict['children'] = [c.to_dict() for c in self._children]
return self_dict
def get_path_to_node(target_node, path=[]):
for c in self._children:
next_step = get_path(c, path)
if next_step is not None:
path.extend(next_step)
break
if target_node == self:
return [self]
elif length(path) > 0:
return path
return None
def save(self, filename, overwrite=False):
if os.path.isfile(filename):
if overwrite is False:
return False
print "Overwriting existing file..."
f = open(filename, 'w')
my_json = self.to_json()
f.write(my_json)
f.close()
def load(filename):
if os.path.isfile(filename) is False:
return None
htn_json = None
with open(filename,'r') as f:
htn_json = f.read()
return TaskHTN.from_json(htn_json)
def from_json(json):
root = TaskHTN(None)
root._values = json['values']
for c in json['children']:
root.add_child(TaskHTN.from_json(c))
return root
class State:
def __init__(self, feature_vector):
self._features = feature_vector
def num_of_spaces(string):
spaces = 0
for characters in string:
if bool(characters.isspace()) == True:
spaces += 1
else:
break
return spaces
def retrieve_text(row):
global rows
print "rows"
print rows
r = rows[row].strip()
print "rows[row]"
print rows[row]
print "r"
print r
if r[0] == '*' or r[0] == '-':
r = r.replace('*','')
r = r.replace('-','')
return r
def ordering_class(row):
global rows
prefix = rows[row].strip()
if prefix[0] == '*':
prefix = "clique"
return prefix
elif prefix[0] == '-':
prefix = "chain"
return prefix
else:
prefix = "primitive"
return prefix
def pop_stack_sib(spaces_in_current_row):
global num_spaces_per_row
global stack
for i in range(1, len(num_spaces_per_row)):
print num_spaces_per_row, spaces_in_current_row, i
if spaces_in_current_row >= num_spaces_per_row[-i]:
stack.pop()
num_spaces_per_row.pop()
print "popped"
break
def pop_stack_parent(spaces_in_current_row):
global num_spaces_per_row
global stack
for i in range(1, len(num_spaces_per_row)):
print num_spaces_per_row, spaces_in_current_row, i
if spaces_in_current_row == num_spaces_per_row[-i]:
to_pop = i
for x in range(to_pop):
# print stack[-1]
# print "look"
stack.pop()
num_spaces_per_row.pop()
print "popped"
break
def run():
crs = open("sampleText.txt", "r")
rows = crs.readlines()
row_at = 0
num_rows = len(rows)
num_spaces_per_row = []
stack = [None]
indent_leval = None
p = None
while(True):
if row_at < num_rows:
row = rows[row_at]
last_row = row_at - 1
prev_row = rows[last_row]
clean_row = retrieve_text(row_at)
order = ordering_class(row_at)
print order
new_node = TaskHTN(clean_row, order)
p = stack[-1]
if row_at > 0:
if p == None:
p = new_node
indent_leval = 0
elif num_of_spaces(prev_row) < num_of_spaces(row): #child
p.children.append(new_node)
elif num_of_spaces(prev_row) == num_of_spaces(row): #sibling
pop_stack_sib(num_of_spaces(row))
p = stack[-1]
if p == None:
p = new_node
else:
p.children.append(new_node)
elif num_of_spaces(prev_row) > num_of_spaces(row): #parent
pop_stack_parent(num_of_spaces(row))
p = stack[-1]
if p == None:
p = new_node
else:
p.children.append(new_node)
else:
if p == None:
p = new_node
else:
print '\n'
#print stack[1].to_json()
json_array = stack[1].to_json()
print "Content-Type: application/json"
print "\n"
print "\n"
print stack[1].to_json()
#print json.dumps(json_array, indent=1)
print "\n"
#return json.dumps(json_array)
print '\n'
break
stack.append(new_node)
num_spaces_per_row.append(num_of_spaces(row))
row_at += 1
print "\n\n"
| true |
11142929e3d9425d9a134941f663a895437669c8 | Python | simrankaurkhaira1467/Training-with-Acadview | /assignment8.py | UTF-8 | 1,622 | 4.03125 | 4 | [] | no_license | #ASSIGNMENT ON SOME COMMONLY USED PACKAGES.
#question 1: What is time tuple?
#answer: Python time functions handle time as a tuple of 9 numbers(year,month,day,hour,minute,second,day of week,day of year and daylight savings).
#It basically provides usage of tuple for the ordring and notation of time.
import time
#gmtime shows the time tuples.
print(time.gmtime(time.time()))
#question 2: Write a program to get formatted time.
import time
localtime=time.asctime(time.localtime(time.time()))
print("local current time :",localtime)
#question 3: Extract month from the time.
import datetime
now=datetime.datetime.now()
print("Current month: %d" %now.month)
#question 4: Extract day from the time.
print(time.strftime("%d, %j"))
#question 5: Extract date from the time.
print(time.strftime("%d" in "%d/%m/%y")
#question 6: Write a program to print time using localtime method.
import time
localtime=time.localtime(time.time())
print("local current time :",localtime)
#question 7: Find the factorial of a number input by user using math package functions.
import math
n=int(input("Enter the number:"))
f=math.factorial(n)
print("The factorial of %d is %d." %(n,f))
#question 8: Find the GCD of a number input by user using math package functions.
import math
n=int(input("Enter the first number:"))
m=int(input("Enter the second number:"))
g=math.gcd(n,m)
print("The GCD of %d and %d is %d." %(n,m,g))
#question 9: Use OS package and do:(a)get present working directory. (b)Get the user environment.
import os
print(os.getcwd())
print(os.getenv('TEMP') | true |
7eaf4652055ef338d554ee0d71d18f9a83e85537 | Python | msmkarthik/Udacity-Data-Scientist-Nanodegree | /Disaster_Response_Pipelines /models/train_classifier.py | UTF-8 | 5,076 | 3 | 3 | [] | no_license | import sys
import nltk
nltk.download(['punkt', 'wordnet', 'averaged_perceptron_tagger'])
import numpy as np
import pandas as pd
from sqlalchemy import create_engine
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import GridSearchCV
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.metrics import classification_report
from sklearn.multioutput import MultiOutputClassifier
import joblib
def load_data(database_filepath):
"""
The function loads the table from given database_filepath as a pandas
dataframe. Splits the message column from the category column.
Args:
database_filepath (str): path to the database
Returns:
X (pandas_dataframe): Pandas Dataframe containing the messages
y (pandas_dataframe): Pandas Dataframe the categories
category_names (list): List containing the column names
"""
engine = create_engine('sqlite:///'+ database_filepath)
df = pd.read_sql_table('messages', engine)
X = df['message']
y = df.drop(['id', 'message', 'original', 'genre'], axis = 1)
category_names = list(df.columns[4:])
return X, y, category_names
def tokenize(text):
"""
Function that tokenizes the raw text
Args:
text (str): raw text
Returns:
clean_tokens (list): Text after getting tokenized
"""
tokens = word_tokenize(text)
lemmatizer = WordNetLemmatizer()
clean_tokens = []
for tok in tokens:
clean_tok = lemmatizer.lemmatize(tok).lower().strip()
clean_tokens.append(clean_tok)
return clean_tokens
def build_model():
"""
Initializes the pipeline and parameters for hyperparameter tuning.
GridSearchCV is initialized and the model pipeline is returned
Returns:
cv (GridSearchCV instance): Defined GridSearchCV instance with initialised
pipeline and hyperparameter grid
"""
pipeline = Pipeline([
('vect', CountVectorizer(tokenizer=tokenize)),
('tfidf', TfidfTransformer()),
('clf', MultiOutputClassifier(RandomForestClassifier()) ) ])
parameters = {
# 'tfidf__use_idf': (True, False),
'tfidf__norm':['l2','l1'],
# 'clf__estimator__n_estimators': [200, 400, 600, 800, 1000, 1200, 1400, 1600, 1800, 2000],
'clf__estimator__min_samples_split': [2, 3, 4],
# 'clf__estimator__min_samples_leaf' : [1, 2, 4],
# 'clf__estimator__max_features': ['auto', 'sqrt'],
# 'clf__estimator__max_depth': [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, None],
}
cv = GridSearchCV(pipeline, param_grid=parameters)
return cv
def evaluate_model(model, X_test, Y_test, category_names):
"""
Evaluates the performance of the model in the test data
Args:
model (GridSearchCV instance): Tuned model
X_test (pandas_dataframe): Pandas Dataframe containing the messages in
test data
y_test (pandas_dataframe): Pandas Dataframe containing the targets(categories)
category_names (list): List of category names
"""
y_pred = model.predict(X_test)
for ix, category in enumerate(Y_test):
print(category)
y_pred_col = y_pred[:,ix]
y_true_col = Y_test[category]
print(classification_report(y_true_col, y_pred_col))
def save_model(model, model_filepath):
"""
Saves the model in given path
Args:
model (GridSearchCV instance): Tuned model
model_filepath (str): path in which the data needs to be dumped
"""
joblib.dump(model, model_filepath)
def main():
if len(sys.argv) == 3:
database_filepath, model_filepath = sys.argv[1:]
print('Loading data...\n DATABASE: {}'.format(database_filepath))
X, Y, category_names = load_data(database_filepath)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2)
print('Building model...')
model = build_model()
print('Training model...')
model.fit(X_train, Y_train)
print('Evaluating model...')
evaluate_model(model, X_test, Y_test, category_names)
print('Saving model...\n MODEL: {}'.format(model_filepath))
save_model(model, model_filepath)
print('Trained model saved!')
else:
print('Please provide the filepath of the disaster messages database '\
'as the first argument and the filepath of the pickle file to '\
'save the model to as the second argument. \n\nExample: python '\
'train_classifier.py ../data/DisasterResponse.db classifier.pkl')
if __name__ == '__main__':
main() | true |
49e9b6cca4c75a0c33e411337519c04b03c432ed | Python | eddiejessup/cannock | /mesh.py | UTF-8 | 1,370 | 3.453125 | 3 | [] | no_license | import fipy
gmsh_text = '''
// Define the square that acts as the system boundary.
dx = %(dx)g;
L = %(L)g;
R = %(R)g;
// Define each corner of the square
// Arguments are (x, y, z, dx); dx is the desired cell size near that point.
Point(1) = {L / 2, L / 2, 0, dx};
Point(2) = {-L / 2, L / 2, 0, dx};
Point(3) = {-L / 2, -L / 2, 0, dx};
Point(4) = {L / 2, -L / 2, 0, dx};
// Line is a straight line between points.
// Arguments are indices of points as defined above.
Line(1) = {1, 4};
Line(2) = {4, 3};
Line(3) = {3, 2};
Line(4) = {2, 1};
// Loop is a closed loop of lines.
// Arguments are indices of lines as defined above.
Line Loop(1) = {1, 2, 3, 4};
// Define a circle
// Define the center and compass points of the circle.
Point(5) = {0, 0, 0, dx};
Point(6) = {-R, 0, 0, dx};
Point(7) = {0, R, 0, dx};
Point(8) = {R, 0, 0, dx};
Point(9) = {0, -R, 0, dx};
// Circle is confusingly actually an arc line between points.
// Arguments are indices of: starting point; center of curvature; end point.
Circle(5) = {6, 5, 7};
Circle(6) = {7, 5, 8};
Circle(7) = {8, 5, 9};
Circle(8) = {9, 5, 6};
Line Loop(2) = {5, 6, 7, 8};
// The first argument is the outer loop boundary.
// The remainder are holes in it.
Plane Surface(1) = {1, 2};
//Plane Surface(1) = {1};
'''
def make_circle_mesh(L, dx, R):
return fipy.Gmsh2D(gmsh_text % {'L': L, 'dx': dx, 'R': R})
| true |
9163d10694a115b6a499e5ed90506a721978963d | Python | Emericdefay/OCR_P13 | /lettings/views.py | UTF-8 | 1,619 | 2.71875 | 3 | [] | no_license | # Django Libs:
from django.shortcuts import render
# Local Libs:
from .models import Letting
# Create your views here.
# Aenean leo magna, vestibulum et tincidunt fermentum, consectetur quis velit.
# Sed non placerat massa. Integer est nunc, pulvinar a
# tempor et, bibendum id arcu. Vestibulum ante ipsum primis in faucibus orci
# luctus et ultrices posuere cubilia curae; Cras eget scelerisque
def index(request):
lettings_list = Letting.objects.all()
context = {'lettings_list': lettings_list}
return render(request, 'lettings/index.html', context)
# Cras ultricies dignissim purus, vitae hendrerit ex varius non. In accumsan
# porta nisl id eleifend. Praesent dignissim, odio eu consequat pretium, purus
# urna vulputate arcu, vitae efficitur
# lacus justo nec purus. Aenean finibus faucibus lectus at porta. Maecenas
# auctor, est ut luctus congue, dui enim mattis enim, ac condimentum velit
# libero in magna. Suspendisse potenti. In tempus a nisi sed laoreet.
# Suspendisse porta dui eget sem accumsan interdum. Ut quis urna pellentesque
# justo mattis ullamcorper ac non tellus. In tristique mauris eu velit
# fermentum, tempus pharetra est luctus. Vivamus consequat aliquam libero,
# eget bibendum lorem. Sed non dolor risus. Mauris condimentum auctor
# elementum. Donec quis nisi ligula. Integer vehicula tincidunt enim, ac
# lacinia augue pulvinar sit amet.
def letting(request, letting_id):
letting = Letting.objects.get(id=letting_id)
context = {
'title': letting.title,
'address': letting.address,
}
return render(request, 'lettings/letting.html', context)
| true |
7d1bc9a7e9134ea79bc4aa43bd8520369ad9f1d0 | Python | lukedorney/secureNLP | /entity_recognition_crf.py | UTF-8 | 14,455 | 2.65625 | 3 | [] | no_license | """Creates classifiers for addressing task 2 of named-entity recognition.
Uses sklearn_crfsuite to create a model capable of structured prediction.
Relies on preprocessed data for features and vectors and on task 1 classification probabilities on the sent level.
Scoring comes in two varieties: 'strict' and 'relaxed' F1 scoring, as put forth in the tasks ACL paper.
Strict scoring is based on the full tag in the data (i.e. in BIO format) -- e.g. B-Entity, I-Modifier.
Relaxed scoring is based on the part of the tag following the BIO label -- e.g. Entity, Modifier.
"""
from itertools import chain
import re
import time
from sklearn.metrics import make_scorer
from sklearn.model_selection import RandomizedSearchCV, GridSearchCV
import sklearn_crfsuite
from sklearn_crfsuite import metrics
from config import Config
from utils import str2float, get_predefined_split, read_msgpack, relax
import warnings
warnings.filterwarnings('ignore')
CONFIG = Config()
def featurize(word_index, word, sent, word_vector, sent_prediction):
"""Outputs a feature dict for a specified word
:param word_index: index of the word in the sentence
:param word: features for a word
:param sent: sentence (list of word features) word is located in
:param word_vector: the vector for word
:param sent_prediction: probability provided by the sentence level classifier
:return: a dict of features for a word
"""
# word indexes: 0 token.text, 1 token.pos_, 2 token.tag_, 3 token.dep_, 4 str(token.vector_norm),
# 5 str(token.cluster), 6 str(token.is_oov), 7 str(token.is_stop), 8 token.head.text, 9 token.head.pos_,
# 10 token.lemma, 11 str(token.like_email), 12 str(token.like_url), 13 neglog prob, 14 ent-iob, 15 ent-type,
# 16 shape
word = word.split()
features = {'bias': 1.0,
'word_lower': word[0].lower(),
'word.istitle()': word[0].istitle(),
'pos': word[1],
'tag': word[2],
'dep': word[3],
'vector_norm': float(word[4]),
'cluster': word[5],
'is_stop': bool(word[7]),
'dep_head': word[8],
'dep_head_pos': word[9],
}
if word_index > 0:
prev_word = sent[word_index - 1].split()
features.update({
'prev_word.lower()': prev_word[0].lower(),
'prev_word_pos': prev_word[1],
'prev_word_tag': prev_word[2],
'prev_word_dep': prev_word[3],
'prev_word_cluster': prev_word[5],
'prev_word_is_stop': bool(prev_word[7]),
})
else:
features['BOS'] = True
if word_index < len(sent) - 1:
next_word = sent[word_index + 1].split()
features.update({
'next_word.lower()': next_word[0].lower(),
'next_word_pos': next_word[1],
'next_word_tag': next_word[2],
'next_word_dep': next_word[3],
'next_word_vector_norm': float(next_word[4]),
'next_word_cluster': next_word[5],
'next_word_oov': bool(next_word[6]),
'next_word_is_stop': bool(next_word[7]),
# 'word_dep_comb': next_word[0].lower() + '-' + next_word[3]
})
else:
features['EOS'] = True
if CONFIG.use_word_vec:
for i, elem in enumerate(list(word_vector)):
features['v_' + str(i)] = float(elem)
if CONFIG.use_sentence_prediction:
features['sent_prediction'] = 1.0 - float(sent_prediction)
return features
def get_data():
"""Retrieves data and labels for each section of the data (i.e. train, dev, test)
:return: data, labels -- for each of train, dev, test -- and the set of all labels seen in all sets
"""
train, train_labels, train_label_set = _get_data(CONFIG.train_labels_by_sent, CONFIG.train_feat, CONFIG.train_vec,
CONFIG.train_predict)
if CONFIG.verbose:
print('processed train')
dev, dev_labels, dev_label_set = _get_data(CONFIG.dev_labels_by_sent, CONFIG.dev_feat, CONFIG.dev_vec,
CONFIG.dev_predict)
if CONFIG.verbose:
print('processed dev')
test, test_labels, test_label_set = _get_data(CONFIG.test_labels_by_sent, CONFIG.test_feat, CONFIG.test_vec,
CONFIG.test_predict)
if CONFIG.verbose:
print('processed test')
label_set = set()
label_set.update(*[train_label_set, dev_label_set, test_label_set])
return train, train_labels, dev, dev_labels, test, test_labels, label_set
def _get_data(labels, feat, vec, predict):
"""Gets data, labels for a part of the data set
:param labels: location of compressed labels
:param feat: location of compressed feature file
:param vec: location of compressed vec file
:param predict: location oof compressed file containing predictions from a sentence level classier
:return: data, labels, the set of individual labels seen in this part of the data set
"""
labels = read_msgpack(labels)
label_set = set()
label_set.update(*list(chain(labels)))
tokens = read_msgpack(feat)
vec = read_msgpack(vec)
vec = [str2float(vec) for vec in vec]
sentence_predictions = read_msgpack(predict)
data = [sent2features(s, vec[i], sentence_predictions[i]) for i, s in enumerate(tokens)]
return data, labels, label_set
def predict_test_comb(crf):
"""Makes predictions for combined .in test file.
:param crf: trained crf classifier
"""
tokens = read_msgpack(CONFIG.task_2_comb_tokens)
features = read_msgpack(CONFIG.task_2_comb_feat)
vec = read_msgpack(CONFIG.task_2_comb_vec)
vec = [str2float(v) for v in vec]
sentence_predictions = read_msgpack(CONFIG.test_comb_predict)
data = [sent2features(s, vec[i], sentence_predictions[i]) for i, s in enumerate(features)]
pred_test_comb = crf.predict(data)
write_test_results(tokens, pred_test_comb, CONFIG.task2_out)
def print_relaxed_scores(dev_labels, pred_dev, test_labels, pred_test, content_labels):
"""Prints the relaxed scores, i.e. with out B-'s and I-'s.
:param dev_labels: true labels for the dev set
:param pred_dev: predicted labels for the dev set
:param test_labels: true labels for the test set
:param pred_test: predicted labels for the test set
:param content_labels: all the labels seen in the data set (minus 'O')
"""
relaxed_pred_dev, relaxed_dev, relaxed_pred_test, relaxed_test \
= map(relax, [pred_dev, dev_labels, pred_test, test_labels])
relaxed_content_labels = sorted(list(set([re.sub('[BI]-', '', label) for label in content_labels])))
_print_scores(relaxed_content_labels, relaxed_dev, relaxed_pred_dev, 'relaxed dev')
_print_scores(relaxed_content_labels, relaxed_test, relaxed_pred_test, 'relaxed test')
def print_scores(dev_labels, pred_dev, test_labels, pred_test, label_set):
"""Prints scores for the dev and test sets.
:param dev_labels: true labels for the dev set
:param pred_dev: predicted labels for the dev set
:param test_labels: true labels for the test set
:param pred_test: predicted labels for the test set
:param label_set: set of labels seen in the whole data set
"""
content_labels = list(label_set)
content_labels.remove('O')
content_labels = sorted(
content_labels,
key=lambda name: (name[1:], name[0])
)
print_strict_scores(dev_labels, pred_dev, test_labels, pred_test, content_labels)
print_relaxed_scores(dev_labels, pred_dev, test_labels, pred_test, content_labels)
def print_strict_scores(dev_labels, pred_dev, test_labels, pred_test, content_labels):
"""Prints the (strict) scores for dev and test sets, i.e. keeping BIO format
:param dev_labels: true labels for the dev set
:param pred_dev: predicted labels for the dev set
:param test_labels: true labels for the test set
:param pred_test: predicted labels for the test set
:param content_labels: all the labels seen in the data set (minus 'O')
"""
_print_scores(content_labels, dev_labels, pred_dev, 'dev')
_print_scores(content_labels, test_labels, pred_test, 'test')
def _print_scores(content_labels, true_labels, pred_labels, data_section):
"""
:param content_labels: all the labels seen in the data set (minus 'O')
:param true_labels: the real labels for a section of the data
:param pred_labels: the labels predicted by a classifier for a section of the data
:param data_section: str naming the section of the data being scored, e.g. 'dev', 'relaxed dev'
"""
results = metrics.flat_f1_score(true_labels, pred_labels,
average='weighted', labels=content_labels)
print('{} results:'.format(data_section), results)
if CONFIG.verbose:
print(metrics.flat_classification_report(
true_labels, pred_labels, labels=content_labels, digits=3
))
def sent2features(sent, sent_vecs, sent_prediction):
"""Gets a list features for each word in the sentence
:param sent: list of 'words' (i.e. the features stored during pre-processing)
:param sent_vecs: list of word vectors
:param sent_prediction: probability that the sentence is 'relevant', according to a sentence level classifier
:return: a list of feature dictionaries
"""
return [featurize(i, word, sent, sent_vecs[i], sent_prediction) for i, word in enumerate(sent)]
def train_crf(train, train_labels, dev, dev_labels, test):
"""Trains a crf classifier using sklearn crf_suite.
:param train: training data -- list of list of feature dictionaries
:param train_labels: labels for the training set
:param dev: dev data -- list of list of feature dictionaries
:param dev_labels: labels for the dev set
:param test: test data -- list of list of feature dictionaries
:return: trained crf model, label predictions for dev and test sets
"""
if CONFIG.crf_parameter_search:
# crf = sklearn_crfsuite.CRF(
# algorithm='lbfgs',
# all_possible_transitions=True,
# max_iterations=100,
# c1=.521871212,
# c2=.000395259,
# )
# params_space = {
# 'c1': scipy.stats.expon(scale=0.5),
# 'c2': scipy.stats.expon(scale=0.05),
# # 'linesearch': ('MoreThuente', 'Backtracking', 'StrongBacktracking'),
# # 'max_iterations': (75, 100, 125, 150, 175)
# }
crf = sklearn_crfsuite.CRF(
algorithm='pa',
# max_iterations=150,
# epsilon=1e-5,
# pa_type=1, # 1, 2
# CONFIG=1,
# error_sensitive=True,
# averaging=True,
# all_possible_transitions=True,
all_possible_states=True
)
params_space = {
'CONFIG': [.001, .01, .5, .1, 1, 10, 50, 100],
'max_iterations': [50, 100, 150, 200],
}
f1_scorer = make_scorer(metrics.flat_f1_score, average='weighted') # , labels=labels)
if CONFIG.use_predefined_split:
predefined_split = get_predefined_split(train, dev)
# crf = RandomizedSearchCV(crf, params_space,
# cv=predefined_split,
# # iid=False,
# verbose=1,
# n_jobs=3,
# n_iter=3,
# scoring=f1_scorer)
crf = GridSearchCV(crf, params_space, scoring=f1_scorer, n_jobs=6, cv=predefined_split, verbose=1)
else:
# crf = RandomizedSearchCV(crf, params_space,
# cv=CONFIG.cv_size,
# verbose=1,
# n_jobs=3,
# n_iter=50,
# scoring=f1_scorer)
crf = GridSearchCV(crf, params_space, scoring=f1_scorer, n_jobs=6, cv=CONFIG.cv_size, verbose=1)
t = time.time()
crf.fit(train + dev, train_labels + dev_labels)
print('fit data in ' + str(time.time() - t) + "s")
print('best params:', crf.best_params_)
print('best CV score:', crf.best_score_)
print('model size: {:0.2f}M'.format(crf.best_estimator_.size_ / 1000000))
else:
# optimized for use without word vecs
# crf = sklearn_crfsuite.CRF(
# algorithm='lbfgs',
# c1=.521871212, #0.521871212871677, # c1=0.7508330047195315
# c2=.000395259, #0.0003952592781021964, # c2=0.03347864314032029
# max_iterations=100,
# all_possible_transitions=True,
# # all_possible_states=True
# )
crf = sklearn_crfsuite.CRF(
algorithm='pa',
max_iterations=50,
epsilon=1e-5,
pa_type=2,
c=50,
error_sensitive=True,
averaging=True,
all_possible_transitions=True,
all_possible_states=True
)
t = time.time()
crf.fit(train, train_labels)
print('fit data in ' + str(time.time() - t) + "s")
train_pred = crf.predict(train)
dev_pred = crf.predict(dev)
test_pred = crf.predict(test)
return crf, train_pred, dev_pred, test_pred
def write_test_results(text, predicted, task2_out):
"""Writes to file predictions for combined .in test file.
:param text: list of list of tokens
:param predicted: list of list of labels
:param task2_out: name of output file
:return:
"""
with open(task2_out, 'w', encoding='utf-8') as f:
for sent, sent_labels in zip(text, predicted):
for word, label in zip(sent, sent_labels):
f.write("{}\t{}\n".format(word, label))
f.write('\n')
def main():
train, train_labels, dev, dev_labels, test, test_labels, label_set = get_data()
crf, pred_train, pred_dev, pred_test_comb = train_crf(train, train_labels, dev, dev_labels, test)
print_scores(dev_labels, pred_dev, test_labels, pred_test_comb, label_set)
if CONFIG.write_test_results:
predict_test_comb(crf)
if __name__ == '__main__':
main()
| true |
1ee30f2cba66547491fe3498e4cabd22d7aff095 | Python | LeBron-Jian/BasicAlgorithmPractice | /剑指offer/PythonVersion/39_数组中出现次数超过一半的数字.py | UTF-8 | 5,657 | 4.34375 | 4 | [] | no_license | #_*_coding:utf-8_*_
'''
题目:
剑指offer 39 数组中出现次数超过一半的数字
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
你可以假设数组是非空的,并且给定的数组总是存在多数元素
示例 1:
输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2
限制:
0 <= 数组长度 <= 10000
'''
from typing import List
import collections
class Solution1:
def majorityElement(self, nums: List[int]) -> int:
'''
我的思路是首先统计出现的次数,然后通过哈希表去找对应的大于数组长度一半的数字
这个应该算是哈希表统计法
通过哈希映射来存储每个元素以及出现的次数,对于哈希映射中的每个键值对,键表示
一个元素,值表示该元素出现的次数。
我们使用一个循环遍历数组 nums 并将数组中的每个元素加入哈希映射中,在这之后,我们
遍历哈希映射中所有的键值对,返回值为最大的键。
时间复杂度为O(n)
空间复杂度为O(n)
'''
res = {}
for num in nums:
if num in res.keys():
res[num] +=1
else:
res[num] = 1
for key, value in res.items():
if value > len(nums)/2:
return key
def majorityElement1(self, nums):
counts = collections.Counter(nums)
return max(counts.keys(), key=counts.get)
class Solution2:
def majorityElement(self, nums: List[int]) -> int:
'''
数组排序法,将数组 nums 排序,数组中点的元素一定为众数
如果将数组 nums 中所有元素按照单调递增或单调递减的顺序排序,那么下标为中间
的元素一定是众数。
对于这种算法,我们先将 nums 数组排序,然后返回上文所说中的下标对应的元素
考虑一种情况:
当n为奇数时候: 中位数一般为 中间的一个数
当n为偶数时候: 中位数一般为 中间的两个数
对于每种情况,众数都在中间,所以无论众数是多少,返回第一个中间的数都是对的
复杂度分析:
时间复杂度为 O(nlogn)
空间复杂度为 O(logn)
如果使用语言自带排序算法,则使用O(logn)的栈空间
如果自己编写堆排序,则只需要使用O(1)的额外空间
'''
nums.sort()
return nums[len(nums)//2]
class Solution3:
def majorityElement(self, nums: List[int]) -> int:
'''
摩尔投票法 核心理念为票数正负抵消。此方法时间复杂度为O(N),空间复杂度为O(1)
为本题的最佳解法
思路:
推论1:若记众数的票数为+1,非众数的票数为-1,则一定有所有数字的票数和>0
推论2:若数组的前a个数字的票数和=0,则数组剩余(n-a)个数字的票数和一定
仍然>0,即后(n-a)个数字的众数仍然为x
根据以上推理,假设数组首个元素n1为众数,遍历并统计票数,当发生票数和=0时
剩余数组的众数一定不变,这是由于:
当n1=x:抵消的所有数字,有一半是众数x
当n1!=x:抵消的所有数字,少于或等于一半是众数x
利用此特性,每轮假设发生票数和=0 都可以缩小剩余数组区间,当遍历完成时,最后
一轮假设的数字记为众数
算法流程:
1,初始化,票数统计 votes=0,众数x
2,循环:
遍历数组nums中的每个数字num:
1,票数 votes=0,则假设当前数字 num 是众数
2,当 num=x时,票数 votes自增1,当num !=x,票数votes自减1
3,返回x即可
'''
votes = 0
for num in nums:
if votes == 0:
x = num
if num == x:
votes +=1
else:
votes -=1
return x
def majorityElement1(self, nums: List[int]) -> int:
'''
由于题目说明:给定的数组总是存在多数元素,因此本题不用考虑数组不存在众数的情况
若考虑,则需要加入一个验证环节,即遍历数组nums统计x的数量
若x的数量超过数组长度的一半,则返回x
否则返回未找到众数
这样做后,时间复杂度与空间复杂度不变仍然为O(n)和O(1)
'''
votes, count = 0, 0
for num in nums:
if votes == 0:
x = num
votes += 1 if num == x else -1
# 验证x是否为众数
for num in nums:
if num == x:
count +=1
# 当无众数时返回0
return x if count > len(nums)//2 else 0
nums = [1, 2, 3, 2, 2, 2, 5, 4, 2]
# res = {}
# for num in nums:
# if num in res.keys():
# res[num] += 1
# else:
# res[num] = 1
# print(res)
# for key, value in res.items():
# if value > len(nums)/2:
# print(key)
# counts = collections.Counter(nums)
# print(counts)
# print(counts.keys())
# print(max(counts.keys(), key=counts.get))
| true |
f2e679d7671cf7d54cc80b03e45c9b435cc9d0d5 | Python | SSJIACV/YOLOv2-pytorch | /darknet/datasets/voc.py | UTF-8 | 2,550 | 2.71875 | 3 | [] | no_license | #coding:utf-8
import torch.utils.data as data
from PIL import Image, ImageDraw
import os
import os.path
import sys
if sys.version_info[0] == 2:
import xml.etree.cElementTree as ET
else:
import xml.etree.ElementTree as ET
def default_loader(path):
return Image.open(path).convert('RGB')
class TransformVOCDetectionAnnotation(object):
def __init__(self, keep_difficult=False):
self.keep_difficult = keep_difficult
def __call__(self, target):
res = []
for obj in target.iter('object'):
difficult = int(obj.find('difficult').text) == 1
if not self.keep_difficult and difficult:
continue
name = obj[0].text.lower().strip()
bbox = obj[4]
bndbox = [int(bb.text)-1 for bb in bbox]
res += [bndbox + [name]]
return res
class VOC(data.Dataset):
def __init__(self, root, image_set, transform=None, target_transform=None, loader=default_loader):
self.root = root
self.image_set = image_set
self.transform = transform
self.target_transform = target_transform
self.loader = loader
dataset_name = 'VOC2012'
self._annopath = os.path.join(self.root, dataset_name, 'Annotations', '%s.xml')
self._imgpath = os.path.join(self.root, dataset_name, 'JPEGImages', '%s.jpg')
self._imgsetpath = os.path.join(self.root, dataset_name, 'ImageSets', 'Main', '%s.txt')
with open(self._imgsetpath % self.image_set) as f:
self.ids = f.readlines()
self.ids = [x.strip('\n') for x in self.ids]
def __getitem__(self, index):
img_id = self.ids[index]
target = ET.parse(self._annopath % img_id).getroot()
img = self.loader(os.path.join(self._imgpath % img_id))
if self.transform is not None:
img = self.transform(img)
if self.target_transform is not None:
target = self.target_transform(target)
return img, target
def __len__(self):
return len(self.ids)
def show(self, index):
img, target = self.__getitem__(index)
draw = ImageDraw.Draw(img)
for obj in target:
draw.rectangle(obj[0:4], outline=(255, 0, 0))
draw.text(obj[0:2], obj[4], fill=(0, 255, 0))
img.show()
if __name__ == '__main__':
ds = VOC('G:/Python全套教程/VOCdevkit/', 'train', target_transform=TransformVOCDetectionAnnotation(False))
print(len(ds))
img, target = ds[0]
print(target)
ds.show(0) | true |
2f7dae5c3e62ad855ff97da58747a576dc085764 | Python | wistbean/learn_python3_spider | /stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/stateful.py | UTF-8 | 1,640 | 2.734375 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # -*- test-case-name: twisted.test.test_stateful -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from twisted.internet import protocol
from io import BytesIO
class StatefulProtocol(protocol.Protocol):
"""A Protocol that stores state for you.
state is a pair (function, num_bytes). When num_bytes bytes of data arrives
from the network, function is called. It is expected to return the next
state or None to keep same state. Initial state is returned by
getInitialState (override it).
"""
_sful_data = None, None, 0
def makeConnection(self, transport):
protocol.Protocol.makeConnection(self, transport)
self._sful_data = self.getInitialState(), BytesIO(), 0
def getInitialState(self):
raise NotImplementedError
def dataReceived(self, data):
state, buffer, offset = self._sful_data
buffer.seek(0, 2)
buffer.write(data)
blen = buffer.tell() # how many bytes total is in the buffer
buffer.seek(offset)
while blen - offset >= state[1]:
d = buffer.read(state[1])
offset += state[1]
next = state[0](d)
if self.transport.disconnecting: # XXX: argh stupid hack borrowed right from LineReceiver
return # dataReceived won't be called again, so who cares about consistent state
if next:
state = next
if offset != 0:
b = buffer.read()
buffer.seek(0)
buffer.truncate()
buffer.write(b)
offset = 0
self._sful_data = state, buffer, offset
| true |
7ca9c97aa0d45e179a4230e451bfe411a31c00b6 | Python | pingshiyu/rateme-scraper | /save_faces.py | UTF-8 | 7,361 | 3.453125 | 3 | [] | no_license | '''
Created on 21 Aug 2017
@author: pings
'''
'''
This script will look through the databse with imgur links saved from earlier and
then find faces in each image - creating a new database which contains the faces
alongside its ratings, age and gender
'''
# find faces
import face_recognition
# image processing
from PIL import Image
from scipy.misc import toimage
# web
import requests
from io import BytesIO
import timeout_decorator
# file management
import os
import json
# for debugging / optimizing
import timeit
import pprint as pp
# general misc. use
import numpy as np
# shrink the image down to ``MAX_DIM`` faster processing. Chosen as at this size,
# the face is still visible
# 400 in general results in faces found to be ~50-150px in dimension
MAX_DIM = 400
def get_face(img_url):
'''
Returns images as numpy arrays of the faces found in the image link stored in
``img_url``
Note to save CPU time the image is resized to be smaller
'''
raw_image = _url_to_image(img_url)
if not raw_image: return None # check link is live
image = _shrink_image(raw_image)
if not image: return None # check image is not corrupted
image_arr = _to_numpy(image)
# face_locations returns the locations of the faces on the image
start = timeit.default_timer()
try: # some images cause format errors
face_locations = face_recognition.face_locations(image_arr)
except:
face_locations = []
end = timeit.default_timer()
print('time taken: %.3f' % (end-start))
if face_locations:
# if faces were found, then
t, r, b, l = _find_largest_face(face_locations)
try:
found_face = image_arr[t:b, l:r, :]
except: # array error
return None
print('face & image size:', found_face.shape, image_arr.shape)
return toimage(found_face)
else:
# no faces found
return None
@timeout_decorator.timeout(10)
def _url_to_image(url):
'''
Reads in the image from the url given. Returns an image object.
Returns None otherwise
'''
# request.get(url).content returns in bytes, and BytesIO allows it to be read by
# Image.open
try :
print('Reading link:', url)
image = Image.open(BytesIO(requests.get(url).content))
print('Image read!')
return image
except: # no image found
print('No image found on', url)
return None
def _to_numpy(image):
'''
Takes in an ``image`` and turns it into a numpy array.
'''
image_arr = np.asarray(image)
image_arr.setflags(write = True) # make image writable for face-recognition
return image_arr
def _shrink_image(image):
'''
Takes in an image object and shrinks it, maintaining its aspect ratio. The
shrink is guaranteed to happen, with the largest dimension capped to
``MAX_DIM``
Returns the resized image.
'''
w, h = image.size
shrink_factor = max(w/MAX_DIM, h/MAX_DIM)
if shrink_factor > 1:
try:
return image.resize((int(w/shrink_factor), int(h/shrink_factor)))
except: # bad image - (GIFs, corrupted etc)
print('Image is corrupted')
return None
else:
return image
def _find_largest_face(face_locations):
'''
Given a list of face locations, find the largest face present within the list
``face_locations`` is a list of face locations, represented in tuples of css
format, which is (top, right, bottom, left)
Returns the tuple which represents the location of the largest face
'''
# here 'size' is defined by its area, i.e. (bottom-top)*(right-left)
size_fn = lambda trbl: (trbl[2]-trbl[0])*(trbl[1]-trbl[3])
face_sizes = np.array(list(map(size_fn, face_locations)))
return face_locations[np.argmax(face_sizes)]
def save_post(post):
'''
Input: a ``post`` (structure [links_list, gender, rating, age])
Grabs the links and saves information locally
'''
img_links = post[0]
gender = post[1]; rating = post[2]; age = post[3]
# go through the image links
if not img_links: # make sure there are links to go through
print('No links found on this post.')
return None
for im in img_links:
face = get_face(im)
if face:
# face is found in the image link
save_name = save_dir + str(settings['img_num'])
# save the image
face.save(save_name + '.png')
# save associated information
img_info = [settings['img_num'], gender, rating, age]
with open(save_name + '.csv', 'w+') as f:
json.dump(img_info, f)
settings['img_num'] += 1
def save_data():
'''
Saves dictionary ``settings`` to disk
'''
with open('./config/progress.config', 'w+') as f:
json.dump(settings, f)
print('DATA SAVED!')
print(settings)
if __name__ == '__main__':
# reads links from ./data/image_links/ (json files); save the images to ./image/raw
# json files are a list of lists, with each element corresponding to a 'post'. Each
# post has a few links, and the first element represents the links.
# to store relational data, the data is indexed by ``filenum``
save_dir = './images/raw2/'
# initial settings and database
settings = {'img_num': 0,
'file_path': 'images-10',
'progress_through_file': 0}
# load the settings and database saved previously
with open('./config/progress.config') as f:
settings = json.load(f)
# go through the links; save the images to file
try:
for root, dirs, files in os.walk('./data/image_links'):
# sort files so we always go through the same order of files
files.sort()
# start from last saved checkpoint
checkpoint = settings['file_path']
if checkpoint in files:
# trim the contents before checkpoint
files = files[files.index(checkpoint):]
for file in files:
# update the settings for the most recent accessed file
settings['file_path'] = file
# file's full path
fpath = os.path.join(root, file)
with open(fpath) as f:
link_list = json.load(f)
# load saved progress:
progress = settings['progress_through_file']
link_list = link_list[progress:]
for i, post in enumerate(link_list):
print('Processing post {}'.format(i))
save_post(post)
settings['progress_through_file'] += 1
# done with the current file - reset progress to 0
settings['progress_through_file'] = 0
save_data()
except Exception as e:
print('Ran into exception', e)
finally: # save data if we run into any errors
save_data() | true |
422e784880e4da820edca1cdc72a6b8f89d1d305 | Python | vijay-parasuram/image-proccessing | /opencv3.py | UTF-8 | 486 | 2.546875 | 3 | [] | no_license | import cv2
import numpy as np
def click_event(event,x,y,flags,param) :
if event == cv2.EVENT_LBUTTONDOWN :
print(x,',',y)
font = cv2.FONT_HERSHEY_SIMPLEX
strxy = str(x)+', '+str(y)
cv2.putText(img,strxy,(x,y),font,1,(255,255,0),2)
cv2.imshow('image',img)
img=np.zeros((512,512,3),np.uint8)
cv2.imshow('image',img)
print('1')
cv2.setMouseCallback('image',click_event)
print('2')
cv2.waitKey()
print('3')
cv2.destroyAllWindows() | true |
2b45e6769d6acc2a793b190a6fc509642d127b8e | Python | Ironbrotherstyle/UnVIO | /models/models.py | UTF-8 | 5,415 | 2.546875 | 3 | [
"MIT"
] | permissive | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
import numpy as np
def conv(in_planes, out_planes, kernel_size=3):
return nn.Sequential(
nn.Conv2d(in_planes,
out_planes,
kernel_size=kernel_size,
padding=(kernel_size - 1) // 2,
stride=2), nn.ReLU(inplace=True))
class VisualNet(nn.Module):
'''
Encode imgs into visual features
'''
def __init__(self):
super(VisualNet, self).__init__()
conv_planes = [16, 32, 64, 128, 256, 512, 512]
self.conv1 = conv(6, conv_planes[0], kernel_size=7)
self.conv2 = conv(conv_planes[0], conv_planes[1], kernel_size=5)
self.conv3 = conv(conv_planes[1], conv_planes[2])
self.conv4 = conv(conv_planes[2], conv_planes[3])
self.conv5 = conv(conv_planes[3], conv_planes[4])
self.conv6 = conv(conv_planes[4], conv_planes[5])
self.conv7 = conv(conv_planes[5], conv_planes[6])
self.conv8 = nn.Conv2d(conv_planes[6], conv_planes[6], kernel_size=1)
def init_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):
init.xavier_uniform_(m.weight.data)
if m.bias is not None:
init.zeros_(m.bias)
def forward(self, imgs):
visual_fea = []
for i in range(len(imgs) - 1):
input = torch.cat(imgs[i:i + 2], 1)
out_conv1 = self.conv1(input)
out_conv2 = self.conv2(out_conv1)
out_conv3 = self.conv3(out_conv2)
out_conv4 = self.conv4(out_conv3)
out_conv5 = self.conv5(out_conv4)
out_conv6 = self.conv6(out_conv5)
out_conv7 = self.conv7(out_conv6)
out_conv8 = self.conv8(out_conv7)
visual_fea.append(out_conv8.mean(3).mean(2))
return torch.stack(visual_fea, dim=1)
class ImuNet(nn.Module):
'''
Encode imus into imu feature
'''
def __init__(self, input_size=6, hidden_size=512):
super(ImuNet, self).__init__()
self.rnn = nn.LSTM(input_size=input_size,
hidden_size=hidden_size,
num_layers=2,
batch_first=True)
def init_weights(self):
for m in self.modules():
if isinstance(m, nn.LSTM):
init.xavier_normal_(m.all_weights[0][0], gain=np.sqrt(1))
init.xavier_normal_(m.all_weights[0][1], gain=np.sqrt(1))
init.xavier_normal_(m.all_weights[1][0], gain=np.sqrt(1))
init.xavier_normal_(m.all_weights[1][1], gain=np.sqrt(1))
def forward(self, imus):
self.rnn.flatten_parameters()
x = imus
B, t, N, _ = x.shape # B T N 6
x = x.reshape(B * t, N, -1) # B T*N 6
out, (h, c) = self.rnn(x) # B*T 1000
out = out[:, -1, :]
return out.reshape(B, t, -1)
class FuseModule(nn.Module):
def __init__(self, channels, reduction):
super(FuseModule, self).__init__()
self.fc1 = nn.Linear(channels, channels // reduction)
self.relu = nn.ReLU(inplace=True)
self.fc2 = nn.Linear(channels // reduction, channels)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
module_input = x
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
x = self.sigmoid(x)
return module_input * x
class PoseNet(nn.Module):
'''
Fuse both features and output the 6 DOF camera pose
'''
def __init__(self, input_size=1024):
super(PoseNet, self).__init__()
self.se = FuseModule(input_size, 16)
self.rnn = nn.LSTM(input_size=input_size,
hidden_size=1024,
num_layers=2,
batch_first=True)
self.fc1 = nn.Sequential(nn.Linear(1024, 6))
def init_weights(self):
for m in self.modules():
if isinstance(m, nn.LSTM):
init.xavier_normal_(m.all_weights[0][0], gain=np.sqrt(1))
init.xavier_normal_(m.all_weights[0][1], gain=np.sqrt(1))
init.xavier_normal_(m.all_weights[1][0], gain=np.sqrt(1))
init.xavier_normal_(m.all_weights[1][1], gain=np.sqrt(1))
elif isinstance(m, nn.Linear):
init.xavier_normal_(m.weight.data, gain=np.sqrt(1))
if m.bias is not None:
init.zeros_(m.bias)
def forward(self, visual_fea, imu_fea):
self.rnn.flatten_parameters()
if imu_fea is not None:
B, t, _ = imu_fea.shape
imu_input = imu_fea.view(B, t, -1)
visual_input = visual_fea.view(B, t, -1)
inpt = torch.cat((visual_input, imu_input), dim=2)
else:
inpt = visual_fea
inpt = self.se(inpt)
out, (h, c) = self.rnn(inpt)
out = 0.01 * self.fc1(out)
return out
if __name__ == '__main__':
image_model = VisualNet()
imgs = [torch.rand(4, 3, 256, 832)] * 5
img_fea = image_model(imgs)
print(img_fea.shape)
imu_model = ImuNet()
imus = torch.rand(4, 4, 11, 6)
imu_fea = imu_model(imus)
print(imu_fea.shape)
pose_modle = PoseNet()
pose = pose_modle(img_fea, imu_fea)
print(pose.shape)
| true |
225ec43e48a219f30bba68e795765fcde7e1e748 | Python | tufanturhan/machinelearning | /keras | UTF-8 | 7,395 | 3.28125 | 3 | [] | no_license | #!/usr/bin/env python3
## Veri Açıklaması: Bankanın müşterilerinin bankalarından ayrılıp ayrılmayacağı
# üzerine tahminlemesi
## Importing the libraries
## numpy modülü array çarpımları gibi yüksek işlem gücü isteyen lineer cebir
# işlemlerini bize fonksiyonel olarak sunan bir modül
## pandas modülü verimiz üzerinde işlem yapmamızı sağlayan bir modül. Veriyi
# çekme, ayırma vb. gibi işlemler için kullanılıyor.
import numpy as np
import pandas as pd
## Importing the dataset
## Verisetimizi projemize yüklüyoruz. .csv olması read_csv() fonksiyonunu
# kullandığımız için önemli.
dataset = pd.read_csv('Churn_Modelling.csv')
## Burada veriyi anaconda'da açıp inceledikten sonra gerekli feature'lara karar
# verip, gereksizleri ele almama ve class değişkenine karar verme işi yapılıyor.
# Bu kararlardan sonra 3-13'ün feature, 13'ün de class olacağı
# görülüyor. Alttaki satırda da veri setinin 3-13 arası alınıyor.
X = dataset.iloc[:, 3:13]
## 13. kolon da class olarak alınıyor.
y = dataset.iloc[:, 13]
# Encoding categorical data
## Aşağıdaki kütüphaneden LabelEncoder sınıfını çağırarak "Encoding Categorical
# Data to Numerical Data" işlemini, OneHotEncoder sınıfı ile de nominal veriler
# için gerekli ekstra dummy kolon oluşturma işlemini gerçekleştireceğiz.
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.compose import ColumnTransformer
## OneHotEncoder sınfından oluşturduğumuz nesneler ile gerekli kolonlar yani
# nominal kolonlar için dummy kolon oluşturma işlemini yapıyoruz.
#columntransformer sayesinde birden fazla heterojen kolonu birleştiriyor.
c = ColumnTransformer([("encoder", OneHotEncoder(), [1,2])], remainder = 'passthrough')
X = c.fit_transform(X)
## Feature Scalling
## Veri önişlemenin son aşamalarından olan feature sclaing yapıyoruz. Veri
# setimizde diğer kolonlara baskın çıkabilecek sayısal değerlere sahip
# kolonlar var. Bu durumu bertaraf etmek için feature scale yöntemi olan
# standartlaştırma yöntemini kullanmak adına StandardScaler sınıfını import
# ediyor ve X veri setine uyguluyoruz. y veri setine feature scale uygulayıp
# uygulamamak ise fark edici bir nokta değil ama genelde uygulamak tercih
# edilen seçim
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X = sc.fit_transform(X)
## Splitting the dataset into the Training set and Test set
## Tüm veri ön işleme aşamalarından sonra test-train ayrımı yapılıyor. Bunun için
# aşağıdaki kütüphanenin fonksiyonu kullanılıyor.
from sklearn.model_selection import train_test_split
## Fonksiyon 4 tane değer döndürüyor. Bunlar X yani feature kolonları için
# eğitim ve test, ile y yani class kolonu için eğitim ve test verileri.
# random_state parametresinin 1
# olması bu parametreyi kullanıp 1 yapan herkese karışık ama aynı veri
# setinin geleceğini ifade ediyor.
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 1)
## Artık ANN zamanı.Yapay Sinir Ağı kodlamak için keras kütüphanesini import
# ediyoruz. Bilgisayarımıza terminale 'pip install keras' yazarak kütüphaneyi
# yükleyebiliriz. YSA kodlamak için models ve layers modüllerini de import
# ediyoruz.
import keras
from keras.models import Sequential
from keras.layers import Dense #katmanları oluşturmak için
## models kütüphanesinden import ettiğimiz Sequential sınıfından nesne
# oluşturuyoruz. Bu kod ile genel YSA tanımlamasını yapıyoruz. Katman eklemekten,
# ağı eğitmeye, tahminleri ortaya çıkarmaya kadar tüm işlemleri bu classifier
# nesnesi ile yapacağız.
classifier = Sequential() #yapay sinir ağı objesi oluşturduk.
## classifier nesnesinden add metodu ile ilk katmanı ekliyoruz. add metodu içine
# Dense sınıfı ve bu sınıfın constructor yapısına gerekli parametreleri girerek
# ilk katmanımızı ekliyoruz. dense sayesinde kaç tane gizli katman olacağı
#bias yani düzeltme fonksiyonu olup olmayacağı verilebilir.
#activaiton ile hangi aktivasyon fonkiyonunu kullandığımızı vereceğiz.
# bizim burda 11 tane bağımsız 1 tane bağımlı değişkenimiz var
#burda şimdi units değerimizi yanş kaç tane bağımsız değişken olduğunu verecez.
#bağımsız değişkenlerimizin yarısı olacak şekilde vereceğiz.
#bu değer genelde her problemde 6 verilir.
#init değeri ilk değerimizin atanması için vereceğimiz değer.
#bu değerler sıfıra yakın bir değerler olmalı.
#activasyon da kullanmak istediğimiz fonksiyonu belirticez.
#son paremetre inputta kaç değer olduğu olacak.
classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu', input_dim = 13))
#uniform, agirliklarin 0 yakin random olarak verilmesini saglar
# İkinci gizli katmanımızı da aynı şekilde ekliyoruz. Bu sefer
# input_dim parametresi yok çünkü zaten inputları ekledik.
classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu'))
# Son olarak çıkış katmanımızı ekliyoruz. Kodlama olarak bunu da aynı şekilde
# ekliyoruz, sadece units parametresini 1 yapıyoruz. Tahmin edeceğimiz değerler
# yani labelımız 0 ve 1'den oluşuyordu. İkili değer olduğu için tek çıkış nöronu
# yeterli oluyor.
classifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid'))
#0 ve 1 gibi 2 sinif varken output icin sigmoid kullanmak daha avantajli, diger turlu softmax kullanmali
## YSA için eğitimde gerekli diğer hiperparametreleri belirleme zamanı. optimizer
# parametresi öğrenme fonksiyonu seçimi için, loss parametresi loss fonksiyonu
# seçimi için kullanılıyor. metrics parametresi ise hata kriterini accuracy'e göre
# belirleyeceğimiz anlamına geliyor. Tüm bunları compile metodu ile yapıyoruz.
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
#loss function da 2 deger oldugu icin binary, 2 den fazla olsaydi cross entropi olcakti.
## Artık eğitim zamanı. fit metodu ile eğitimi gerçekleştirceğiz. X_train ve
# y_train'i veriyoruz xten yyi öğren.
#batch_size, epochs ve shuffle parametrelerine de standart
# olarak tercih edilen değerleri giriyoruz.
#epochs kaç seferde öğrenecek
classifier.fit(X_train, y_train, batch_size = 10, epochs = 100, shuffle = True)
#batch size veriyi kacarli egitecegimiz, epoch butun veriyi toplam kac kere egitecegimiz
## Predicting the Test set results
## Algoritmanın eğitimi tamamlandı. Performansını ölçmek adına test için
# ayırdığımız eğitime karışmamış verileri modele veriyoruz ve bize test setindeki
# verilerin tahminlerini yapıyor.
y_pred = classifier.predict(X_test) #bakalım buna
y_pred = (y_pred > 0.5) #0.5 den kucuk olanlari false kabul ediyor.
## Making the Confusion Matrix
## Tahminleri yaptırdıktan sonra doğruluk oranımızı görmek ve modelimizin somut
# çıktısını almak adına Confusion Matrix'i hesaplatıyoruz. Hesaplatmak için
# çağırdığımız kütüphanedeki fonksiyona görüldüğü üzere test setinin gerçek
# verilerini ve modelin tahmin ettiği verileri veriyourz. Bu adım uygulanmadan
# önce öğrencilere Confusion Matrix anlatılabilir.
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
print(cm)
| true |
b797a4ccd973be5ad8d00b78aee7cc1d59f1f556 | Python | erjan/coding_exercises | /coloring_a_border.py | UTF-8 | 3,452 | 3.859375 | 4 | [
"Apache-2.0"
] | permissive | '''
You are given an m x n integer matrix grid, and three integers row, col, and color. Each value in the grid represents the color of the grid square at that location.
Two squares belong to the same connected component if they have the same color and are next to each other in any of the 4 directions.
The border of a connected component is all the squares in the connected component that are either 4-directionally adjacent to a square not in the component, or on the boundary of the grid (the first or last row or column).
You should color the border of the connected component that contains the square grid[row][col] with color.
Return the final grid.
'''
class Solution:
def colorBorder(self, grid: List[List[int]], r0: int, c0: int, color: int) -> List[List[int]]:
def dfs(r, c, current, border, seen):
# if out of range or seen
if r<0 or c<0 or r >= len(grid) or c >= len(grid[0]) or grid[r][c] != current or (r,c) in seen:
return
seen.add((r,c))
# if it is a border
if (r==0 or c==0 or r==len(grid)-1 or c==len(grid[0])-1 or grid[r-1][c] != current or grid[r+1][c] != current or grid[r][c-1] != current or grid[r][c+1] != current):
border.add((r,c))
dfs(r-1, c, current, border, seen)
dfs(r+1, c, current, border, seen)
dfs(r, c-1, current, border, seen)
dfs(r, c+1, current, border, seen)
return
if not grid:
return grid
current = grid[r0][c0]
border = set()
seen = set()
dfs(r0, c0, current, border, seen)
for elem in border:
grid[elem[0]][elem[1]] = color
return grid
-------------------------------------------------------------------------
from queue import Queue
class Solution:
"""
approach: the problem can be tackled using breadth first approach
start the bfs from (row, col) and maintain visited and border_set
"""
def colorBorder(self, grid: List[List[int]], row: int, col: int, color: int) -> List[List[int]]:
m = len(grid)
n = len(grid[0])
start_color = grid[row][col]
visited = set()
def is_valid(index):
i, j = index
if 0 <= i < m and 0 <= j < n:
return True
return False
def is_boundary(index):
i, j = index
if i == 0 or i == m-1 or j == 0 or j == n-1:
return True
return False
def get_neighbors(index):
i, j = index
return [(i+1,j), (i-1,j), (i,j+1), (i,j-1)]
def dfs(index):
visited.add(index)
flag = 0
if is_boundary(index):
flag = 1
for pos in get_neighbors(index):
if is_valid(pos) and pos not in visited:
if grid[pos[0]][pos[1]] == start_color:
dfs(pos)
else:
# it's a border point, index needs to be colored with color
flag = 1
if flag:
grid[index[0]][index[1]] = color
dfs((row, col))
return grid
| true |
90c85510b3ec6757ac7506557b8f2f496113b62c | Python | HiAwesome/python-algorithm | /c02/p058.py | UTF-8 | 1,376 | 4.28125 | 4 | [
"Apache-2.0"
] | permissive | """
我们发现这个时间是相当一致的,执行这段代码平均需要 0.0006 秒。那么如果我们累加到 100,000 会怎么样呢?
又是这样,每次运行所需时间虽然更长,但非常一致,平均约为之前的 10 倍,进一步累加到 1,000,000 我们得到:
在这种情况下,平均时间再次约为之前的 10 倍。
"""
import time
def sum_of_n_2(n):
"""
迭代求和,仅使用加法。
:param n: 1 到 n 的和
:return: 元组(元素的组合),第一位为值,第二位为所花时间
"""
start = time.time()
the_sum = 0
for i in range(1, n + 1):
the_sum = the_sum + i
end = time.time()
return the_sum, end - start
for i in range(5):
print('Sum is %d required %10.7f seconds' % sum_of_n_2(10000))
print()
for i in range(5):
print('Sum is %d required %10.7f seconds' % sum_of_n_2(1000000))
"""
Sum is 50005000 required 0.0006449 seconds
Sum is 50005000 required 0.0006080 seconds
Sum is 50005000 required 0.0006089 seconds
Sum is 50005000 required 0.0006161 seconds
Sum is 50005000 required 0.0006239 seconds
Sum is 500000500000 required 0.0476000 seconds
Sum is 500000500000 required 0.0550399 seconds
Sum is 500000500000 required 0.0564568 seconds
Sum is 500000500000 required 0.0504000 seconds
Sum is 500000500000 required 0.0536993 seconds
"""
| true |
0c6b15b275a42d4b05267cf14f026ebd497c7162 | Python | HCelante/Simulador-Escalonador-de-Processos | /main.py | UTF-8 | 3,412 | 2.78125 | 3 | [] | no_license | # import src.Gerenciador
import sys
import array as arr
from src.models.bcp import BCP
from src.Gerenciador import Manager
def getConfigurations(filename): # pega o tempo de I/O de cada escalonador de um arquivo de configuração
scheduler = ""
RR = [] # vetor com os valores do processamento de I/O utilizando o algoritmo Round Robin
DNMC = [] # // utilizando o escalonador com prioridade dinâmica
SJF = [] # // utilizando o escalonador SJF
flag = 0
with open(filename) as f: # abre o arquivo
while True: # até o fim do arquivo
c = f.read(1) # lê caractere por caractere
if not c: # caso seja o final do arquivo
print ("End of file")
break
# IDENTIFICA COMO NOME DO ESCALONADOR SOMENTE O QUE ESTIVER ENTRE '*' E ':'
if(c == ':'):
flag = 0 # nega a leitura do nome do escalonador
if(flag): # caso esteja autorizado a leitura:
scheduler = scheduler + c # insere caractere por caractere na string
if(c == '*'): # autoriza a leitura do nome do escalonador
flag = 1
scheduler = ""
# i = 0
# -------------------------------------------------------------------------
if(not flag): # pega o valor após o ":"
if(c != ' ' and c != ',' and c != ':' and c != '\n'):
if(scheduler == 'RR'):
RR.append(int(c))
if(scheduler == 'DNMC'):
DNMC.append(int(c))
if(scheduler == 'SJF'):
SJF.append(int(c))
return [RR,DNMC,SJF]
def getProcess(filename): # Adiciona os processos a uma lista de processos
processList = []
singleProcess = []
with open(filename) as f:
for val in f.read().splitlines():
for i in val.strip().split():
singleProcess.append(int(i))
processList.append(singleProcess)
singleProcess = []
return processList
def main():
confs = getConfigurations(sys.argv[1]) # contém as informações de execução do IO de todos os escalonadores
procList = getProcess(sys.argv[2]) # contém os processos a serem escalonados
mainProcess = []
for i in range (len(procList)):
mainProcess.append(BCP(procList[i]))
rrProcess = mainProcess.copy() # cópia dos processos
sjfProcess = mainProcess.copy()
dnmcProcess = mainProcess.copy()
op = ''
while(True):
op = input("1 - DNMC, 2 - RR, 3 - SJF, 4 - Sair")
if(op == '3'):
# # Instanciando a classe Manager
Managed = Manager(1)
# Populando a fila de nao criados
Managed.construc_QNC(sjfProcess)
Managed.exec_loop('SJF', confs)
if(op == '2'):
Managed2 = Manager(1)
Managed2.construc_QNC(rrProcess)
Managed2.exec_loop('RR', confs)
if(op == '1'):
Managed3 = Manager(2)
Managed3.construc_QNC(dnmcProcess)
Managed3.exec_loop('DNMC', confs)
if(op == '4'):
return 0
# Managed.reset_Manager(nfilas)
# Managed2 = Manager(1)
# Managed2.construc_QNC(rrProcess)
# Managed2.exec_loop('RR', confs)
# Managed.reset_Manager(2)
# # Exec DNMC -----------------------
# Managed3 = Manager(2)
# Managed3.construc_QNC(dnmcProcess)
# Managed3.exec_loop('DNMC', confs)
main() | true |
35b52d6776d6a4ab71caa79644f614a569f39ef5 | Python | tchrlton/Learning-Python | /HardWay/ex20.py | UTF-8 | 1,683 | 3.828125 | 4 | [] | no_license | #from the module sys, import the function or paramater argv
from sys import argv
#The two arguments in argv so it has the script (ex20.py) and
#input_file (test.txt or whatever file you input).
script, input_file = argv
#The function that will print the whole txt file after it reads it
def print_all(f):
print(f.read())
#The f.seek(0) brings the readline line back to the beginning in the test
#file so that it doesnt coninture from the end of the file.
def rewind(f):
f.seek(0)
#The function uses the text file (f) and reads a line, then prints the
#current line of the line count
def print_a_line(line_count, f):
print(line_count, f.readline())
#Openss the input_file when the variable current_file is used
current_file = open(input_file)
#prints string out and skips a line at the end
print("First let's print the whole file:\n")
#Runs print_all function which opens input_file and then prints the
#whole txt file
print_all(current_file)
#prints the string
print("Now let's rewind, kind of like a tape.")
#Runs the function rewind using the current_file variable and the brings
#the line back to the beginning with the seek(0) function
rewind(current_file)
#prints the string
print("Let's print three lines:")
#prints the first line while also showing the number the line is on
current_line = 1
print_a_line(current_line, current_file)
#prints the second line while showing the number the line is on which is 2
current_line += 1
print_a_line(current_line, current_file)
#prints the third line of the text file since it is + 1 line of the
#current line which is 2 (it would be 1 if it had seek(0) in it instead)
current_line += 1
print_a_line(current_line, current_file)
| true |
0afb6dffeb2e2aa5c4149e6cd13a6c19a1b98a0b | Python | ninivert/pyinstaller-setup | /pyinstaller_setuptools/setup.py | UTF-8 | 2,391 | 2.53125 | 3 | [
"MIT"
] | permissive | import sys
import os
import inspect
import re
from setuptools import setup as setuptools_setup
ENTRY_POINT_TEMPLATE = """
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
import re
import sys
from {} import {}
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit({}())
"""
class setup(object):
"""
This is intended to run pyinstaller in order to make executables out of
all of the scripts and console script entry points listed in setuptools.setup
Usage:
```
python ./setup.py build
python ./setup.py install
python ./setup.py pyinstaller [-- pyinstaller-opts ...]
```
"""
def __init__(self, scripts=None, entry_points=None, **kwargs):
self.scripts = scripts
self.entry_points = entry_points
if "pyinstaller" in sys.argv:
if "--" in sys.argv and sys.argv.index("--") < len(sys.argv) - 1:
self.flags = " ".join(sys.argv[sys.argv.index("--") + 1 :])
else:
self.flags = ""
if not os.path.exists("./dist"):
os.mkdir("dist")
if self.scripts:
self.install_scripts()
if self.entry_points:
self.install_entry_points()
else:
setuptools_setup(scripts=scripts, entry_points=entry_points, **kwargs)
def pyinstaller(self, name, target):
if os.system("pyinstaller --name {} {} {}".format(name, self.flags, target)):
raise Exception("PyInstaller failed!")
def install_scripts(self):
for script in self.scripts:
self.pyinstaller(os.path.basename(script).replace(".py", ""), script)
def install_entry_points(self):
if "console_scripts" in self.entry_points.keys():
for entry_point in self.entry_points["console_scripts"]:
name, entry = [part.strip() for part in entry_point.split("=")]
module, func = [part.strip() for part in entry.split(":")]
script = inspect.cleandoc(
ENTRY_POINT_TEMPLATE.format(module, func, func)
)
input_file = "dist/{}_entry.py".format(name)
with open(input_file, "w") as outfile:
outfile.write(script)
self.pyinstaller(name, input_file)
| true |
9909e1580b7a49b52688ac82f9c8a78b1f151e0a | Python | Eric-Wonbin-Sang/CS110Manager | /2020F_hw4_submissions/cataniamichael/CS110 HW Capitalize names file due 10_30_2020-1.py | UTF-8 | 546 | 4.4375 | 4 | [] | no_license | # This Program Converts names from lowercase to capital letters
def main():
print("This program converts names from lowercase to capital letters")
infileName = input("What file are the names in? ")
outfileName = input("Place names with all uperecase letters in this file: ")
infile = open(infileName, "r")
outfile = open(outfileName, "w")
for i in infile:
cap = (i.upper())
print(cap, file=outfile)
infile.close()
outfile.close()
print("The capitalized names are in:", outfileName)
main()
| true |
f9fc534491aeaf00b926feb40950f764b98fdb14 | Python | wzhang62/Triangle111 | /testhw1.py | UTF-8 | 934 | 3.578125 | 4 | [] | no_license | import unittest
from hw1 import SortTri
class TestTriangles(unittest.TestCase):
def testRightTriangleA(self):
self.assertEqual(SortTri(3, 4, 5), 'Right Triangle', '3,4,5 is a right triangle')
def testRightTriangleB(self):
self.assertEqual(SortTri(5, 3, 4), 'Right Triangle', '5,3,4 is a right triangle')
def testEquilateralTriangle(self):
self.assertEqual(SortTri(3, 3, 3), 'Equilateral Triangle', '3,3,3 should be equilateral')
def testIsoscelesTriangle(self):
self.assertEqual(SortTri(7, 6, 6), 'Isosceles Triangle', '7,6,6 is a isosceles triangle')
def testScaleneTriangle(self):
self.assertEqual(SortTri(5, 7, 9), 'Scalene Triangle', '3,4,5 is a scalene triangle')
def testLengthError(self):
self.assertEqual(SortTri(1, 7, 2), 'Length error!!', '1,7,2 is length error')
if __name__ == '__main__':
print('Running unit tests')
unittest.main()
| true |
e8d24dc29aaefcc8d6727694a672c997a244f17d | Python | aarthisandhiya/aarthi | /26.py | UTF-8 | 113 | 3.46875 | 3 | [] | no_license | q=int(input())
u=[int(i) for i in input().split()]
t=sorted(u)
for i in range(0,len(u)):
print(t[i],' ',end="")
| true |
25b626b1d1db3089fb8fbd031584c33597be248a | Python | dhruv100691/cs466_project | /word2vec/models.py | UTF-8 | 4,197 | 2.71875 | 3 | [] | no_license | from Bio import SeqIO
from gensim.models import word2vec
import numpy as np
import sys
import os
import gzip
"""
'AGAMQSASM' => [['AGA', 'MQS', 'ASM'], ['GAM','QSA'], ['AMQ', 'SAS']]
"""
def split_ngrams(seq, n):
a, b, c = zip(*[iter(seq)]*n), zip(*[iter(seq[1:])]*n), zip(*[iter(seq[2:])]*n)
str_ngrams = []
for ngrams in [a,b,c]:
x = []
for ngram in ngrams:
x.append("".join(ngram))
str_ngrams.append(x)
return str_ngrams
'''
Args:
corpus_fname: corpus file name
n: the number of chunks to split. In other words, "n" for "n-gram"
out: output corpus file path
Description:
Protvec uses word2vec inside, and it requires to load corpus file
to generate corpus.
'''
def generate_corpusfile(corpus_fname, n, out):
f = open(out, "w")
with gzip.open(corpus_fname, 'rt') as fasta_file:
for r in SeqIO.parse(fasta_file, "fasta"):
ngram_patterns = split_ngrams(r.seq, n)
for ngram_pattern in ngram_patterns:
f.write(" ".join(ngram_pattern) + "\n")
sys.stdout.write(".")
f.close()
def load_protvec(model_fname):
return word2vec.Word2Vec.load(model_fname)
def normalize(x):
return x / np.sqrt(np.dot(x, x))
class ProtVec(word2vec.Word2Vec):
"""
Either fname or corpus is required.
corpus_fname: fasta file for corpus
corpus: corpus object implemented by gensim
n: n of n-gram
out: corpus output file path
min_count: least appearance count in corpus. if the n-gram appear k times which is below min_count, the model does not remember the n-gram
"""
def __init__(self, corpus_fname=None, corpus=None, n=3, size=100,
out="corpus.txt", sg=1, window=25, min_count=1, workers=3):
skip_gram = True
self.n = n
self.size = size
self.corpus_fname = corpus_fname
self.sg = int(skip_gram)
self.window = window
self.min_count = min_count
self.workers = workers
self.out = out
directory = out.split('/')[0]
if not os.path.exists(directory):
os.makedirs(directory)
print("directory(trained_models) created\n")
if corpus is None and corpus_fname is None:
raise Exception("Either corpus_fname or corpus is needed!")
if corpus_fname is not None:
print ('Now we are checking whether corpus file exist')
if not os.path.isfile(out):
print ('INFORM : There is no corpus file. Generate Corpus file from fasta file...')
generate_corpusfile(corpus_fname, n, out)
else:
print( "INFORM : File's Existence is confirmed")
self.corpus = word2vec.Text8Corpus(out)
print ("\n... OK\n")
def word2vec_init(self, ngram_model_fname):
word2vec.Word2Vec.__init__(self, self.corpus, size=self.size, sg=self.sg, window=self.window, min_count=self.min_count, workers=self.workers)
model = word2vec.Word2Vec([line.rstrip().split() for line in open(self.out)], min_count = 1, size=self.size, sg=self.sg, window=self.window)
model.wv.save_word2vec_format(ngram_model_fname)
def to_vecs(self, seq, ngram_vectors):
ngrams_seq = split_ngrams(seq, self.n)
protvec = np.zeros(self.size, dtype=np.float32)
for index in range(len(seq) + 1 - self.n):
ngram = seq[index:index + self.n]
if ngram in ngram_vectors:
ngram_vector = ngram_vectors[ngram]
protvec += ngram_vector
return normalize(protvec)
def get_ngram_vectors(self, file_path):
ngram_vectors = {}
vector_length = None
with open(file_path) as infile:
for line in infile:
line_parts = line.rstrip().split()
# skip first line with metadata in word2vec text file format
if len(line_parts) > 2:
ngram, vector_values = line_parts[0], line_parts[1:]
ngram_vectors[ngram] = np.array(list(map(float, vector_values)), dtype=np.float32)
return ngram_vectors
| true |
24373741350093bcb48886ac8b3e349ac5a54359 | Python | martinferianc/Robotics-EIE3 | /src/drawing_v.py | UTF-8 | 2,217 | 3.15625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
import time
import random
import math
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
def calcX():
return random.gauss(80,3) + 70*(math.sin(t)) # in cm
def calcY():
return random.gauss(70,3) + 60*(math.sin(2*t)) # in cm
def calcW():
return random.random()
def calcTheta():
return random.randint(0,360)
class Canvas:
def __init__(self,map_size=210, virtual=False):
self.map_size = map_size # in cm
self.canvas_size = 768 # in pixels
self.margin = 0.05*map_size
self.scale = self.canvas_size/(map_size+2*self.margin)
self.virtual = virtual
x = np.arange(10)
ys = [i+x+(i*x)**2 for i in range(20)]
self.colors = cm.rainbow(np.linspace(0, 1, len(ys)))
self.counter = 0
def drawLine(self,line):
x1 = self.__screenX(line[0])
y1 = self.__screenY(line[1])
x2 = self.__screenX(line[2])
y2 = self.__screenY(line[3])
if self.virtual:
plt.figure(num=1,figsize=(30,30))
plt.plot([x1,x2],[y1,y2])
print "drawLine:" + str((x1,y1,x2,y2))
def drawParticles(self,data):
display = [(self.__screenX(d[0][0])+d[1],self.__screenY(d[0][1])+d[1]) for d in data]
if self.virtual:
plt.ion()
plt.figure(num=1,figsize=(10,10))
plt.plot([i[0] for i in display],[i[1] for i in display],"ro",c=self.colors[self.counter])
plt.pause(0.05)
self.counter+=1
else:
print "drawParticles:" + str(display)
def __screenX(self,x):
return (x + self.margin)*self.scale
def __screenY(self,y):
return (self.map_size + self.margin - y)*self.scale
class Map:
def __init__(self, canvas):
self.walls = [];
self.canvas = canvas
self.virtual = False
if canvas.virtual:
self.virtual = True
def add_wall(self,wall):
self.walls.append(wall)
def clear(self):
self.walls = []
def draw(self):
for wall in self.walls:
self.canvas.drawLine(wall)
if self.virtual:
plt.show(block=False)
| true |
3f290a78da4833efd279e44489511ba641441ad3 | Python | jij7401/baekjoon_code | /Silver3/구간 합 구하기_pro11659.py | UTF-8 | 443 | 3.15625 | 3 | [] | no_license | import sys
N, M = map(int, sys.stdin.readline().strip().split())
lst = list(map(int, sys.stdin.readline().strip().split()))
# LST to SUM_LST
# LST : 1 2 3 4 5
# SUM : 0 1 3 6 10 15
sum_lst = [0]*(len(lst)+1)
for i in range(1, len(lst)+1):
sum_lst[i] = sum_lst[i-1]+lst[i-1]
# SUM[b] - SUM[a-1]
for i in range(M):
a, b = map(int, sys.stdin.readline().strip().split())
print(sum_lst[b]- sum_lst[a-1])
| true |
39c419afaf373ef1c3c8b4d316b3f84c5fa14f11 | Python | solomonli/PycharmProjects | /Stanford/bridge_riddle.py | UTF-8 | 530 | 3.4375 | 3 | [] | no_license | def f(s):
s.sort() # sort input in place
if len(s) > 3: # loop until len(s) < 3
a = s[0] + s[-1] + min(2*s[1], s[0]+s[-2]) # minimum time according to xnor paper
return a + f(s[:-2]) # recursion on remaining people
else:
return sum(s[len(s) == 2:]) # add last times when len(s) <= 3
'''fuck, this line is genius! False means 0!!!'''
if __name__ == '__main__':
print(f([1]))
| true |
47d2c92e698e39d9eda305e08c6130118612e301 | Python | Pywwo/gomoku | /check_win.py | UTF-8 | 1,604 | 3.546875 | 4 | [] | no_license | #!/usr/bin/env python3
def check_vertically(array, checking, i, j, sizemax):
a = i
while a < i + 5:
if a >= sizemax:
return False
if array[a][j] != checking:
return False
a += 1
return True
def check_horizontally(array, checking, i, j, sizemax):
a = j
while a < j + 5:
if a >= sizemax:
return False
if array[i][a] != checking:
return False
a += 1
return True
def check_diagonally_left(array, checking, i, j, sizemax):
if j - 5 < 0 or i + 5 > sizemax:
return False
a = 0
while a < 5:
if array[i + a][j - a] != checking:
return False
a += 1
return True
def check_diagonally_right(array, checking, i, j, sizemax):
if j + 5 > sizemax or i + 5 > sizemax:
return False
a = 0
while a < 5:
if array[i + a][j + a] != checking:
return False
a += 1
return True
def check_win_five(array, checking):
for i in range(len(array)):
for j in range(len(array[0])):
if array[i][j] == checking:
if check_horizontally(array, checking, i, j, len(array)) == True:
return True
if check_vertically(array, checking, i, j, len(array)) == True:
return True
if check_diagonally_left(array, checking, i, j, len(array)) == True:
return True
if check_diagonally_right(array, checking, i, j, len(array)) == True:
return True
return False | true |
8431e6952576069eb1eb069b80a614f574f68f90 | Python | artbakulev/hse_contest_yandex_1 | /D. The nearest/3.py | UTF-8 | 240 | 3.09375 | 3 | [] | no_license | input()
nums = list(map(int, input().split()))
N = int(input())
diff, diff_idx = abs(N - nums[0]), 0
for i in range(1, len(nums)):
if abs(N - nums[i]) < diff:
diff = abs(N - nums[i])
diff_idx = i
print(nums[diff_idx])
| true |
0d37e11b14f2ea90e67f4da2689ed1502beb9129 | Python | alldevic/tel_bot | /bot/user_manager.py | UTF-8 | 579 | 3.25 | 3 | [] | no_license | def is_user_in_list(user_id):
return user_id in get_users_list()
def get_users_list():
with open('users.list', 'r') as f:
return [i.rstrip('\r\n') for i in f.readlines()]
def add_user_in_list(user_id):
with open('users.list', 'a') as f:
f.write(user_id)
def write_users_list(users_list, mode_destructive=False):
mode = 'w' if mode_destructive else 'a'
with open('users.list', mode=mode) as f:
f.writelines(users_list)
def remove_user_from_list(user_id):
users = get_users_list().remove(user_id)
write_users_list(users)
| true |
50b6da8ab16a1ad316a47c2735e1a2754b8c2fc4 | Python | jinliangXX/LeetCode | /1. Two Sum/solution.py | UTF-8 | 2,666 | 3.546875 | 4 | [] | no_license | class Node:
__init__
class Solution:
def twoSum_one(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
num_list = sorted(nums)
lenght = len(num_list)
# 计算目标值的一半
target_num = target / 2
left = 0
right = 1
result_num = list()
for i, num in enumerate(num_list):
if num == target_num and i + 1 < lenght:
left = i
right = i + 1
break
if num > target_num:
left = i - 1
right = i
break
while left >= 0 and right < lenght:
if num_list[left] + num_list[right] > target:
left -= 1
elif num_list[left] + num_list[right] < target:
right += 1
else:
result_num.append(num_list[left])
result_num.append(num_list[right])
break
if len(result_num) != 2:
return
result = [-1, -1]
for i, num in enumerate(nums):
if result[0] > -1 and result[1] > -1:
break
if result[0] < 0 and num == result_num[0]:
result[0] = i
continue
if result[1] < 0 and num == result_num[1]:
result[1] = i
continue
return result
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
num_list = sorted(nums)
lenght = len(num_list)
# 计算目标值的一半
left = 0
right = lenght - 1
result_num = list()
while left < right:
if num_list[left] + num_list[right] > target:
right -= 1
elif num_list[left] + num_list[right] < target:
left += 1
else:
result_num.append(num_list[left])
result_num.append(num_list[right])
break
if len(result_num) != 2:
return
result = [-1, -1]
for i, num in enumerate(nums):
if result[0] > -1 and result[1] > -1:
break
if result[0] < 0 and num == result_num[0]:
result[0] = i
continue
if result[1] < 0 and num == result_num[1]:
result[1] = i
continue
return result
if __name__ == '__main__':
solution = Solution()
test = [3, 3]
target = 6
print(solution.twoSum(test, target))
| true |
ebb8d88c19da2e3ddc3bd4ce7b11811e7a6aa55c | Python | kazbekkadalashvili/masc-test | /masc/masc_utils.py | UTF-8 | 1,127 | 2.71875 | 3 | [] | no_license | import shutil
import os
import datetime
from masc.constants import CACHE_DIR, LOGS_DIR, BACKUPS_DIR
from masc.print_utils import print_red
class MascUtils:
"""Some utils to perform"""
@staticmethod
def clean_cache():
"""Clean masc cache: logs and clean installation downloaded from the Internet"""
shutil.rmtree(CACHE_DIR)
shutil.rmtree(LOGS_DIR)
os.mkdir(CACHE_DIR)
os.mkdir(LOGS_DIR)
@staticmethod
def list_backups():
"""List backups. These are the local backups that users make any time they scan a website"""
if not os.path.isdir(BACKUPS_DIR):
os.mkdir(BACKUPS_DIR)
backup_count = len(os.listdir(BACKUPS_DIR))
if backup_count == 0:
print_red("no backups")
return
site_list = os.scandir(BACKUPS_DIR)
for site in site_list:
site_parts = site.name.split("_")
print("\t" + site_parts[1] + " : " + site_parts[0])
backups = os.scandir(site)
for backup in backups:
print("\t\t " + "Backup date: " + backup.name)
| true |
5c569b2380ef2e5068955444d190786117851bd3 | Python | Tylerholland12/SPD-2.31-Testing-and-Architecture- | /SPD-2.31-Testing-and-Architecture/lab/refactoring/move_field2.py | UTF-8 | 2,515 | 3.296875 | 3 | [
"MIT"
] | permissive | # Kami Bigdely
# Move Field
class Car:
def __init__(self, engine, wheels, cabin, fuel_tank):
self.engine = engine
# TODO: tpms is better to be in the Wheel class.
# Each wheel has a single tpms attached to it.
# Thus, instead of having a list of tpms in 'Car' class
# have each of the tpms in each 'Wheel'.
# self.tpms_list = tpms_di # Tire Pressure Monitoring System.
self.wheels = wheels
# Set wheels' car reference into each wheel.
for w in wheels:
w.set_car(self)
self.cabin = cabin
self.fuel_tank = fuel_tank
class Wheel:
# TODO: You may add tpms as a method parameter here to
# initilaize the 'Wheel' object or you can create
# a setter method to set the tpms of the wheel. (you can do
# both of course.)
def __init__(self, tmps, car = None, wheel_location = None):
self.car = car
self.wheel_location = wheel_location
self.tmps = tmps
def install_tire(self):
print('remove old tube.')
# TODO: Rewrite the following after moving tpms to the 'Wheel' class
print('cleaned tpms: ',
self.tmps.get_serial_number,
'.')
print('installed new tube.')
def read_tire_pressure(self):
# TODO: After making tpms an attribute of 'Wheel' class,
# rewrite the following.
return self.tmps.get_pressure()
def set_car(self, car):
self.car = car
class Tpms:
"""Tire Pressure Monitoring System.
"""
def __init__(self, serial_number):
self.serial_number = serial_number
self.sensor_transmit_range = 300 # [feet]
self.sensor_pressure_range = (8,300) # [PSI]
self.battery_life = 6 # [year]
def get_pressure(self):
return 3
def get_serial_number(self):
return self.serial_number
class Engine:
def __init__(self):
pass
class FuelTank:
def __init__(self):
pass
class Cabin:
def __init__(self):
pass
engine = Engine()
# TODO: Rewrite the following after moving tpms to the 'Wheel' class.
wheels = [Wheel(Tpms(983408543), None, 'front-right'),
Wheel(Tpms(4343083), None, 'front-left'),
Wheel(Tpms(23654835), None, 'back-right'),
Wheel(Tpms(3498857), None, 'back-left')]
cabin = Cabin()
fuel_tank = FuelTank()
my_car = Car(engine, wheels, cabin, fuel_tank)
| true |
dd0cba5ad83dea9158e767e44ca87cfbb8ceb6a1 | Python | DivyeshMakwana12599/HandGestureRecgontion | /volTest.py | UTF-8 | 421 | 2.84375 | 3 | [] | no_license | from matplotlib import pyplot as plt
def mapVal(x, in_min, in_max, out_min, out_max):
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
db = []
p = []
for i in range(101):
volDB = mapVal(i, 0, 100, -65.25, 0.0)
db.append(volDB)
p.append(i)
plt.plot(db, p, color='green', linestyle='dashed', linewidth = 3,
marker='o', markerfacecolor='blue', markersize=12)
plt.show() | true |
5658687fffc5b98455c38065e9b5f72b437a12c1 | Python | JGMEYER/advent-of-code | /2022/common/input.py | UTF-8 | 1,903 | 2.984375 | 3 | [] | no_license | from typing import List
def read_file(filepath: str) -> List[str]:
"""Read a file"""
with open(filepath) as f:
return f.read().strip().split("\n")
def input_filepath(*, day: int, test: bool = False, suffix=None) -> str:
"""Returns paths to both question and test inputs"""
suffix_str = f"_{str(suffix)}" if suffix else ""
return (
f"tests/test_inputs/test_day{day}{suffix_str}.txt"
if test
else f"inputs/day{day}{suffix_str}.txt"
)
def read_input(*, day: int, test: bool = False) -> List[str]:
"""Read the input file for a particular day"""
import os
import warnings
warnings.warn(
"read_input is deprecated, use auto_read_input instead",
DeprecationWarning,
)
filepath = os.path.abspath(input_filepath(day=day, test=test))
return read_file(filepath)
def read_test_input(*, day: int) -> List[str]:
"""Read the test input file for a particular day"""
import os
import warnings
warnings.warn(
"read_test_input is deprecated, use auto_read_input with test=False instead",
DeprecationWarning,
)
filepath = os.path.abspath(input_filepath(day=day, test=True))
return read_file(filepath)
def auto_read_input(*, suffix=None) -> List[str]:
"""Read the input file for a particular day based on the .py file invoking the function"""
import inspect
import re
# This is generally probably a bad idea...
filename = inspect.stack()[1].filename
file_pattern = r"(test_)?day(\d+)\.py$"
match = re.search(file_pattern, filename)
if not match:
raise Exception(
f'Invoker filename {filename} must match pattern "{file_pattern}"'
)
groups = match.groups()
test, day = bool(groups[0]), int(groups[1])
filepath = input_filepath(day=day, test=test, suffix=suffix)
return read_file(filepath)
| true |
c1f69d07c96fe66089a04d26bc8e0f8523d6b916 | Python | TzuYun0221/72app_test | /testcase/Android/test_2_4_about_us_關於創富.py | UTF-8 | 1,813 | 2.5625 | 3 | [] | no_license | import unittest
import time, os
from Parameter import *
class WebDriverTests(unittest.TestCase):
def setUp(self):
#開啟app的參數
self.driver = webdriver.Remote(Remote_url, desired_caps)
#跳過廣告(Parameter)
skip_ads(self)
#設置隱性等待10秒
self.driver.implicitly_wait(10)
print(" -- set up finished -- ")
def tearDown(self):
#關閉app
self.driver.quit()
print('-- tear down finished -- ')
def test_2_4_about_us_關於創富(self):
print('==========test_2_4_about_us_關於創富==========')
#我的
#self.driver.find_element_by_xpath("//*[@text='我的']").click()
press_my_button(self)
#关于创富
self.driver.find_element_by_xpath("//*[@text='关于创富']").click()
#檢查关于创富H5頁面
tab_list = [about_us_expect,'安全保障','运营数据','荣誉奖项','联系我们']
#check_list = [about_us_expect,'安全保障让您的投资安全无忧','安全运营','荣誉奖项屡获殊荣 我们一同见证','客服邮箱']
#算list長度
length = len(tab_list)
for i in range(length):
#檢查各個tab
try:
self.driver.find_element_by_accessibility_id(tab_list[i]).click()
print('正確!"'+tab_list[i]+'"tab正常顯示')
except NoSuchElementException:
print('錯誤!"'+tab_list[i]+'"沒有顯示')
raise AssertionError('錯誤!"'+tab_list[i]+'"沒有顯示')
'''#跳過'关于神龙科技'頁面的檢查,因抓不到元素
if(i==0):
continue
#檢查各個tab的頁面
try:
self.driver.find_element_by_xpath("//*[@text='"+check_list[i]+"']")
print('正確!"'+tab_list[i]+'"顯示:',check_list[i])
except NoSuchElementException:
print('錯誤!"'+tab_list[i]+'"沒有顯示',check_list[i])
raise AssertionError('錯誤!"'+tab_list[i]+'"沒有顯示',check_list[i])'''
| true |
acd00473d9e1abb965a047a1735ea9c78612f8e9 | Python | sontek-archive/code-fun | /is-stringreduction/sr.py | UTF-8 | 1,398 | 3.453125 | 3 | [] | no_license | length = int(raw_input())
swap = {
'bc': 'a',
'ac': 'b',
'ab': 'c',
}
for index in range(1, length+1):
test = raw_input()
def solve(t, best_match):
if len(t) < best_match:
best_match = len(t)
for index, s in enumerate(t):
# if we aren't at the end of the string
if index != len(t)-1:
# if the 2 characters next to each other don't match
if s != t[index+1]:
match = s + t[index+1]
for key in swap.keys():
# check which letter to swap the match with
if match == key or match == key[::-1]:
# replace the first occurance of the match
result = t.replace(match, swap[key], 1)
current_len = len(result)
if current_len < best_match:
best_match = current_len
# our current match is better than current best_match
# return this match
new_len = solve(result, best_match)
if new_len < best_match:
best_match = new_len
return best_match
return best_match
print solve(test, 99)
| true |
8a0c5350a702a001c5cd2968cf3667ae6c513230 | Python | diogoabnunes/FPRO | /REs/RE07 - Tuples/translate.py | UTF-8 | 727 | 3.328125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 12 23:57:47 2018
@author: diogo
"""
def translate(astring,table):
result = astring
for i in range(len(table)):
result = result.replace(str(table[i][0]),str(table[i][1]))
return result
print(translate("Hello world!",(("a",1),
("e",2),
("i",3),
("o",4),
("u",5),
("!"," :)"))))
print(translate("Testing this string...",((' ', '--'),
('.','!'),
('i', 'o'),
('t', 'tt')))) | true |
0bf5a8d99e222bea0f264e238312999a5c45e21b | Python | here0009/LeetCode | /Python/KokoEatingBananas.py | UTF-8 | 1,987 | 4.0625 | 4 | [] | no_license | """
Koko loves to eat bananas. There are N piles of bananas, the i-th pile has piles[i] bananas. The guards have gone and will come back in H hours.
Koko can decide her bananas-per-hour eating speed of K. Each hour, she chooses some pile of bananas, and eats K bananas from that pile. If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour.
Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back.
Return the minimum integer K such that she can eat all the bananas within H hours.
Example 1:
Input: piles = [3,6,7,11], H = 8
Output: 4
Example 2:
Input: piles = [30,11,23,4,20], H = 5
Output: 30
Example 3:
Input: piles = [30,11,23,4,20], H = 6
Output: 23
Note:
1 <= piles.length <= 10^4
piles.length <= H <= 10^9
1 <= piles[i] <= 10^9
"""
import math
class Solution:
def minEatingSpeed(self, piles, H):
"""
use binary search to find K
"""
def caclTime(k):
res = 0
for p in piles:
res += math.ceil(p/k)
return res
piles = sorted(piles)
N = len(piles)
d = H//N
left = math.ceil(piles[0]/d)
right = math.ceil(piles[-1]/d)
# print(left, right)
while left < right:
mid = (left+right)//2
if caclTime(mid) > H:
left = mid+1
else:
right = mid
return left
s = Solution()
piles = [3,6,7,11]
H = 8
#Output: 4
print(s.minEatingSpeed(piles,H))
piles = [30,11,23,4,20]
H = 5
#Output: 30
print(s.minEatingSpeed(piles,H))
piles = [30,11,23,4,20]
H = 6
#Output: 23
print(s.minEatingSpeed(piles,H))
piles = [332484035, 524908576, 855865114, 632922376, 222257295, 690155293, 112677673, 679580077, 337406589, 290818316, 877337160, 901728858, 679284947, 688210097, 692137887, 718203285, 629455728, 941802184]
H = 823855818
print(s.minEatingSpeed(piles,H)) | true |
2360dd7ae77d03788cd4a7d71d1cadb77578f37b | Python | Priyanshu-Garg/CodeWorld | /Python/Merge Sort.py | UTF-8 | 909 | 3.828125 | 4 | [
"MIT"
] | permissive | def mergeSort(arr):
if len(arr) > 1:
r = len(arr)//2
leftArr = arr[:r]
rightArr = arr[r:]
mergeSort(leftArr)
mergeSort(rightArr)
i = j = k = 0
while i < len(leftArr) and j < len(rightArr):
if leftArr[i] < rightArr[j]:
arr[k] = leftArr[i]
i += 1
else:
arr[k] = rightArr[j]
j += 1
k += 1
while i < len(leftArr):
arr[k] = leftArr[i]
i += 1
k += 1
while j < len(rightArr):
arr[k] = rightArr[j]
j += 1
k += 1
def display(arr):
for i in range(len(arr)):
print(arr[i], end=" ")
print()
if __name__ == '__main__':
arr = [6, 5, 12, 10, 9, 1]
print("Original array")
display(arr)
mergeSort(arr)
print("Sorted array")
display(arr)
| true |
26ec2c8b38a8f2624d46716e5815620698ad50d6 | Python | inkayat/AoC | /2020/11-Seating-System/part2.py | UTF-8 | 4,270 | 3.046875 | 3 | [] | no_license | from collections import defaultdict
import copy
def search(container, row, col, direction):
is_find = False
if direction == 'up':
while row>=1:
if container[row-1][col] == '#':
is_find = True
break
elif container[row-1][col] == 'L':
break
row -= 1
elif direction == 'up-left':
while row>=1 and col>=1:
if container[row-1][col-1] == '#':
is_find = True
break
elif container[row-1][col-1] == 'L':
break
row -= 1
col -= 1
elif direction == 'left':
while col>=1:
if container[row][col-1] == '#':
is_find = True
break
elif container[row][col-1] == 'L':
break
col -= 1
elif direction == 'left-down':
while row+1<len(container) and col>=1:
if container[row+1][col-1] == '#':
is_find = True
break
elif container[row+1][col-1] == 'L':
break
row += 1
col -= 1
elif direction == 'down':
while row+1<len(container):
if container[row+1][col] == '#':
is_find = True
break
elif container[row+1][col] == 'L':
break
row += 1
elif direction == 'down-right':
while row+1<len(container) and col+1<len(container[0]):
if container[row+1][col+1] == '#':
is_find = True
break
elif container[row+1][col+1] == 'L':
break
col += 1
row += 1
elif direction == 'right':
while col+1<len(container[0]):
if container[row][col+1] == '#':
is_find = True
break
elif container[row][col+1] == 'L':
break
col += 1
elif direction == 'right-up':
while col+1<len(container[0]) and row>=1:
if container[row-1][col+1] == '#':
is_find = True
break
elif container[row-1][col+1] == 'L':
break
col += 1
row -= 1
return is_find
def process(seat_list):
change = 0
next_state = copy.deepcopy(seat_list)
for row in range(len(seat_list)):
for col in range(len(seat_list[row])):
occupied = 0
if seat_list[row][col] == '.':
continue
if search(seat_list, row, col, 'up'):
occupied += 1
if search(seat_list, row, col, 'up-left'):
occupied += 1
if search(seat_list, row, col, 'left'):
occupied += 1
if search(seat_list, row, col, 'left-down'):
occupied += 1
if search(seat_list, row, col, 'down'):
occupied += 1
if search(seat_list, row, col, 'down-right'):
occupied += 1
if search(seat_list, row, col, 'right'):
occupied += 1
if search(seat_list, row, col, 'right-up'):
occupied += 1
if seat_list[row][col] == 'L' and occupied == 0:
next_state[row][col] = '#'
change += 1
elif seat_list[row][col] == '#' and occupied >= 5:
change += 1
next_state[row][col] = 'L'
if change > 0:
return next_state
else:
return -1
if __name__ == "__main__":
layout = list()
memo = defaultdict(lambda:-1)
with open('input.txt') as fp:
lines = fp.readlines()
for line in lines:
layout.append([i for i in line if i!='\n'])
while True:
ret = process(layout)
if ret == -1:
break
else:
layout = copy.deepcopy(ret)
result = 0
for row in range(len(layout)):
for col in range(len(layout[row])):
if layout[row][col] == '#':
result += 1
print(result)
| true |
01443b27b756e797dee8cde08c76698a2eaf833e | Python | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_62/160.py | UTF-8 | 1,171 | 2.984375 | 3 | [] | no_license | #! /usr/bin/python
import sys
mainD={}
def main():
file1=open(sys.argv[1])
a=file1.readlines()
cases=int(a.pop(0))
values=[]
a.reverse()
while len(a)>0:
blah=a.pop().split()
num=int(blah[0])
XY=[]
for x in range(num):
blah=a.pop().split()
b=int(blah[0])
c=int(blah[1])
XY.append((b,c))
values.append(findval(XY))
strings=[]
for x in range(cases):
string1="Case #"+str(x+1)
string1+=": "+str(values[x])
strings.append(string1)
f=open("OutputLarge.txt","w")
for x in strings:
f.write(x+"\n")
def findval(XY):
if len( XY)==1:
return 0
if len(XY)==2:
if XY[0][0]>XY[1][0] and XY[0][1]<XY[1][1] or XY[0][0]<XY[1][0] and XY[0][1]>XY[1][1]:
return 1
return 0
count=0
for i in range(len(XY)):
for j in range(i+1,len(XY)):
if XY[i][0]>XY[j][0] and XY[i][1]<XY[j][1] or XY[i][0]<XY[j][0] and XY[i][1]>XY[j][1]:
count+=1
return count
if __name__ == "__main__":
main()
| true |
4fb4e1c7c5d90a25cd6650c2a689c848e40c3f4a | Python | nehak0601/Covid-19 | /covid_data/covid.py | UTF-8 | 1,347 | 2.8125 | 3 | [] | no_license | from sqlalchemy import create_engine
import requests
import pandas as pd
from urllib.parse import urlencode
from requests.exceptions import ConnectionError
import os
script_dir = os.path.dirname(__file__) #<-- absolute dir the script is in
def db_connect():
API_URL = "https://covid-19-coronavirus-statistics.p.rapidapi.com/v1/stats"
URL = API_URL
return URL
def fetch_data():
URL=""
headers = {
'x-rapidapi-host': "covid-19-coronavirus-statistics.p.rapidapi.com",
'x-rapidapi-key': "b01f036d64msh1d0ff32e4912881p162983jsnbd99ccf2be75"
}
r = requests.get(url = db_connect(),headers=headers)
data1=r.json()
# df = pd.DataFrame(data1['data'])
df = pd.DataFrame(data1['data'])
df=df['covid19Stats'].to_list()
df1=pd.DataFrame(df)
# df['lastChecked'] = df['lastChecked'].apply(lambda v: pd.to_datetime(v))
return df1
# db connection:
def sql_connection():
rel_path = "covid19.db"
abs_file_path = os.path.join(script_dir, rel_path)
# print(abs_file_path)
try:
con = create_engine('sqlite:///' + abs_file_path)
return con
except Error:
print(Error)
#Insert API_Data into table:
def sql_insert(data):
con = sql_connection()
result = data.to_sql('covid4', con, index=False, if_exists='replace')
print(result)
if __name__ == '__main__':
#Function call:
db_connect()
data = fetch_data()
sql_insert(data) | true |
4292aa77ab375c1a22623b840e9dcb9a03068851 | Python | otisiokechukwumonday/Hackthebox | /Challenges/Forensics/image_modifier.py | UTF-8 | 448 | 3.046875 | 3 | [] | no_license | from PIL import Image
if __name__=="__main__":
img=Image.open('file2.png')
in_pixels = list(img.getdata())
out_pixels = list()
for i in range(len(in_pixels)):
r=in_pixels[i][0]
g=in_pixels[i][1]
b=in_pixels[i][2]
if r!=0 or r!=255:
r=150-r
if g!=0 or g!=255:
g=150-g
if b!=0 or b!=255:
b=150-b
out_pixels.append((r,g,b))
out_img=Image.new(img.mode,img.size)
out_img.putdata(out_pixels)
out_img.save("file1.png","PNG")
| true |
47a0161aca923b4c1e591d287e308fc92d553151 | Python | ddm-j/StudioQuoting | /quote.py | UTF-8 | 4,948 | 2.84375 | 3 | [] | no_license | import os
from tools import STLUtils
import pandas as pd
pd.set_option('display.max_columns', None)
def getSTLs():
cwd = os.getcwd()
onlyfiles = [os.path.join(cwd, f) for f in os.listdir(cwd) if os.path.isfile(os.path.join(cwd, f))]
paths = [i for i in onlyfiles if ".stl" in i or ".STL" in i]
names = [i.split('\\')[-1] for i in paths]
#print(names)
#print(paths)
return names, paths
def yesNo(input):
d = {
'y':True,
'n':False,
"":False
}
if input not in ["y","n", ""]:
raise ValueError("Invalid input. Please specify 'y' or 'n'")
return d[input]
def main():
# Initialize STLUtility Class
stlutils = STLUtils()
# Initialize Results Data Structure
table = {}
# Detect files in folder
names, paths = getSTLs()
files = {i:j for i,j in zip(names,paths)}
# Get input
print("\n\n*** DM Quoting Tool ***\n")
materials = ['316L', '17-4PH', '4140', 'H13']
print("Select Material:")
material = int(input("(1) 316L, (2) 17-4 PH, (3) 4140, (4) H13: "))
material = materials[material]
single_cycle = input("\nQuote single cycle? This will assume all parts under a single cycle; requires \n"
"inputting custom part quantities. (y/n): ")
print(single_cycle)
single_cycle = yesNo(single_cycle)
#if single_cycle:
# input_qtys = input("\nSpecify individual part quantities? (y/n): ")
# input_qtys = yesNo(input_qtys)
#else:
# input_qtys = False
if single_cycle:#input_qtys:
print("\nSpecify quantities for {0} STLs".format(len(names)))
custom_qtys = {}
for name in names:
qty = int(input("{0}: ".format(name)))
custom_qtys.update({name:qty})
# Calculate Model Volumes
print("\n\nCalculating model volumes.")
volumes = {}
boundingVolumes = {}
for name,path in zip(names,paths):
#print('Calculating model volume for {0}'.format(name))
vol, bVol = stlutils.calculateVolume(path,material)
volumes.update({name:vol})
boundingVolumes.update({name: bVol})
table.update({name:[vol,*bVol]})
# Calculate Maximum Part Quantities for Each Step
print('Calculating maximum part quantity per cycle.')
quantities = {}
for name in names:
#print('Calculating quantities for {0}, with bv: {1}'.format(name,boundingVolumes[name]))
qtys = stlutils.calculateQuantities(boundingVolumes[name],volumes[name],material)
quantities.update({name:qtys})
table[name] += [qtys['printer'],qtys['debinder'],qtys['furnace']]
# Calculate Cycles
print('Calculating cycles & costs.')
cycles = {}
cycleCosts = {}
for name in names:
#print('Calculating equipment cycle counts for {0}'.format(name))
cycle,cost = stlutils.calculateCycles(quantities[name])
cycles.update({name:cycle})
cycleCosts.update({name: cost})
table[name] += [cycle['printer'], cycle['debinder'], cycle['furnace']]
table[name] += [cost['printer'], cost['debinder'], cost['furnace']]
print("\n\n*** Calculations Complete ***\n\n")
print('--- PART & CYCLE SUMMARY ---')
# Formatting Data for Output
headers = ['Volume (cm^3)', 'dx (mm)', 'dy (mm)', 'dz (mm)', 'perPrint', 'perDebind', 'perSinter', 'nPrints', 'nDebinds', 'nSinters', 'costPrint', 'costDebind', 'costSinter']
table = pd.DataFrame.from_dict(table,orient='index')
table.columns = headers
# Unit Corrections
table['Volume (cm^3)'] = table['Volume (cm^3)']/1000
table.insert(1,'Material Unit Cost',table['Volume (cm^3)']*stlutils.materials[material]['cost'],allow_duplicates=True)
table = table.round(2)
# Output table
print(table)
table.to_csv('partSummary.csv')
print('\n\n--- MANUFACTURING SUMMARY ---')
summary = pd.DataFrame(index=table.index)
if single_cycle:
# Using Custom Quantities for Mfg. Summary
summary['Quantity'] = pd.Series(custom_qtys)
else:
summary['Quantity'] = table['perSinter']
summary['Total Material Cost'] = summary['Quantity']*table['Material Unit Cost']
summary['Print Cost'] = [stlutils.equipment['printer']['cost']]*len(names)
summary['Debind Cost'] = [stlutils.equipment['debinder']['cost']] * len(names)
summary['Sinter Cost'] = [stlutils.equipment['furnace']['cost']] * len(names)
summary['Cycle Cost'] = summary['Print Cost'] + summary['Debind Cost'] + summary['Sinter Cost']
summary['Total Cost'] = summary['Cycle Cost'] + summary['Total Material Cost']
summary['Unit Cost'] = summary['Total Cost']/summary['Quantity']
print(summary)
summary.to_csv('manufacturingSummary.csv')
if __name__ == "__main__":
main()
| true |
3adc4456c3bd8b3da0499d188f02d0ffac7e80c1 | Python | redstorm45/word-solver | /main.py | UTF-8 | 2,624 | 2.796875 | 3 | [
"MIT"
] | permissive |
from board import Board
from words import WordMatcher
from solver import Solver
from interface import GraphicalInterface
import threading
class Prog:
def __init__(self):
self.board = Board()
self.matcher = WordMatcher()
self.solver = Solver()
self.thread = None
self.stopping = True
self.stopped = True
self.loaded = False
self.cb_progress = None
self.cb_options = None
self.cb_intermediate = None
def attach_interface(self, cb_progress, cb_options):
self.cb_progress = cb_progress
self.cb_options = cb_options
def launch_load(self):
self._launch(target=self._load)
def launch_compute(self, letters):
if not self.loaded:
return
self._launch(target=lambda:self._compute(letters))
def _launch(self, target):
if self.thread is not None:
self.stop()
self.stopping = False
self.stopped = False
def wrapped():
target()
self.stopped = True
self.thread = threading.Thread(target=wrapped)
self.thread.start()
def stop(self):
self.stopping = True
if self.thread is not None:
self.thread.join()
def try_stop_compute(self):
self.stopping = True
if self.stopped:
self.thread.join()
self.thread = None
return True
return False
def _load(self):
def cb_stop():
return self.stopping
with open("dico.txt") as file:
W = file.readlines()
W = [w.strip().lower() for w in W]
#W = W[:len(W)//8]
self.matcher.set_dict(W, self.cb_progress, cb_stop)
if self.cb_progress is not None:
self.cb_progress(100, 100)
self.loaded = True
print('complete')
def _compute(self, letters):
if self.cb_options is None:
return
if self.cb_progress is not None:
self.cb_progress(-1, 30)
def cb_stop():
return self.stopping
def cb_intermediate(opt):
self.cb_intermediate( (opt, self.board.get_score(opt)) )
self.cb_options([])
opts = self.solver.get_options(self.board, self.matcher, letters, lambda:self.cb_progress(-1, 1), cb_stop, cb_intermediate)
pairs = [(op, self.board.get_score(op)) for op in opts]
self.cb_options(pairs)
if self.cb_progress is not None:
self.cb_progress(100, 100)
def main():
prog = Prog()
itf = GraphicalInterface(prog)
itf.run()
main()
| true |
9b8861898aa6b14afa5db36bd9095d366c5dc1dd | Python | Promisey/LearningPython | /P178.py | UTF-8 | 348 | 3.515625 | 4 | [] | no_license | import time
def decorator_timer(old_function):
def new_function(*args, **dict_arg):
t1 = time.time()
result = old_function(*args, **dict_arg)
t2 = time.time()
print("time:", t2 - t1)
return result
return new_function
@decorator_timer
def add(a, b):
return a**99+b**99
print(add(9999, 9999))
| true |
d541a8557239facd3ccd54797a0e739498e3fd6a | Python | stchris/irctk | /tests/test_threadpool.py | UTF-8 | 1,483 | 2.671875 | 3 | [
"BSD-3-Clause"
] | permissive | import unittest
import Queue
from irctk.threadpool import ThreadPool, Worker
class WorkerTestCase(unittest.TestCase):
'''This test case tests the Worker class methods.'''
def setUp(self):
def foo():
pass
q = Queue.Queue()
q.put([foo, [], {}])
self.tasks = q
self.logger = None
self.worker = Worker(self.tasks, self.logger)
self.assertEquals(self.worker.logger, None)
self.assertTrue(self.worker.daemon)
def test_run(self):
pass
class ThreadPoolTestCase(unittest.TestCase):
'''This test case tests the ThreadPool class methods.'''
def setUp(self):
self.min_workers = 3
self.logger = None
self.tp = ThreadPool(self.min_workers, self.logger)
self.assertEquals(self.tp.min_workers, 3)
self.assertEquals(self.tp.logger, None)
self.assertEquals(self.tp.wait, 0.01)
self.assertTrue(self.tp.daemon)
def test_enqueue_task(self):
self.tp.enqueue_task('foo', 'bar')
task = self.tp.tasks.get()
self.assertEquals(('foo', ('bar',), {}), task)
test = 'test'
self.tp.enqueue_task('foo', 'bar', test=True)
task = self.tp.tasks.get()
self.assertEquals(('foo', ('bar',), {'test': True}), task)
def test_worker(self):
pass
def test_run(self):
pass
if __name__ == '__main__':
unittest.main()
| true |
131d0f612d2ac7dcaed4889dca77fbdb7b8f06db | Python | pkoluguri/json-encode-and-decode | /hw.py | UTF-8 | 1,623 | 3.3125 | 3 | [] | no_license | import json
leaders_objects = ""
class leaders:
def __init__(self,name,age,country,continent):
self.age = age
self.name = name
self.country = country
self.continent = continent
def read():
f = open("Book1.csv","r")
leaders_list = []
line = f.readline()
while line != "":
details = line.split(",")
leader = leaders(details[0],details[1],details[2],details[3].strip('\n'))
leaders_list.append(leader)
line = f.readline()
return leaders_list
def input1(leaders_list):
continent = input("enter the leader's name:")
for i in range(len(leaders_list)):
if continent == leaders_list[i].continent:
print(leaders_list[i].country)
print(leaders_list[i].name)
def encode_leaders(leader):
if isinstance(leader,leaders):
data = {"name":leader.name,
"country":leader.country,
"continent":leader.continent,
"age":leader.age}
print(type(data))
return data
else:
return f"{type(leader)} is not an leaders object"
def decode_leaders(dct):
return leaders(dct["name"],dct["age"],dct["country"],dct["continent"])
leaders_list= read()
with open("leaders.json","w") as file:
json.dump(leaders_list,file,default=encode_leaders)
with open("leaders.json","r") as file:
s = file.readline()
s = json.loads(s,object_hook=decode_leaders)
for ss in s:
print(ss.name,":")
print(" age: ",ss.age)
print(" country: ",ss.country)
print(" continent:",ss.continent)
| true |
8b7918b5e3a5d10be94fdd5fc45b3799e3f7794b | Python | sami-one/mooc-ohjelmointi-21 | /osa09-06_lemmikki/src/lemmikki.py | UTF-8 | 569 | 3.765625 | 4 | [] | no_license |
class Lemmikki:
def __init__(self, nimi: str, kuvaus: str):
self.nimi = nimi
self.kuvaus = kuvaus
def __repr__(self):
return f"{self.nimi} ({self.kuvaus})"
class Henkilo:
def __init__(self, nimi: str, lemmikki: Lemmikki):
self.nimi = nimi
self.lemmikki = lemmikki
def __repr__(self):
return f"{self.nimi}, kaverina {self.lemmikki.nimi}, joka on {self.lemmikki.kuvaus}"
if __name__ == "__main__":
hulda = Lemmikki("Hulda", "sekarotuinen koira")
leevi = Henkilo("Leevi", hulda)
print(leevi) | true |
b077c9ba2f306229e2448c221e1b5f91fd823c7f | Python | merklel/coughanalyzer2 | /src/autoanalyzer.py | UTF-8 | 2,321 | 2.65625 | 3 | [] | no_license | import librosa
import matplotlib.pyplot as plt
from scipy.fft import fft
from scipy import signal
import numpy as np
import pandas as pd
import math
def plotter(y_husten, y_husten_fft, N, SAMPLERATE, start, end, flag_husten):
# spectrogram
fxx, txx, Sxx = signal.spectrogram(y_husten, SAMPLERATE, window=('tukey', 0.25), nperseg=1000, noverlap=500)
# plot
f, axs = plt.subplots(3, 1)
f.suptitle("Timecode: {}:{} to {}:{}. Husten: {}".format(math.floor(start/SAMPLERATE/60),(start/SAMPLERATE)%60, math.floor(end/SAMPLERATE/60),(end/SAMPLERATE)%60, flag_husten))
axs[0].plot(y_husten)
xfft = np.linspace(0.0, N // 2, N // 2)
axs[1].plot(xfft, 2.0 / N * np.abs(y_husten_fft[0:N // 2]))
axs[1].set_xlim(0, 1000)
axs[1].set_ylim(0, 0.01)
axs[1].grid()
axs[2].pcolormesh(txx, fxx, Sxx)
axs[2].set_ylabel('Frequency [Hz]')
axs[2].set_xlabel('Time [sec]')
axs[2].set_ylim(0, 1500)
AUDIO_FILE = "/home/ga36raf/Documents/coughanalyzer/Joseph Haydn - Piano Concerto No 11 in D major, Hob XVIII_11 - Mikhail Pletnev/Joseph Haydn - Piano Concerto No. 11 in D major, Hob. XVIII_11 - Mikhail Pletnev (152kbit_Opus).ogg"
SAMPLERATE = 48000
# Load audio file
y, sr = librosa.load(AUDIO_FILE, sr=SAMPLERATE, mono=True)
# cut applaus
y = y[0:22*60*SAMPLERATE+15*SAMPLERATE]
CHUNKSIZE = 2 # seconds
N_audio = len(y)
# N_audio=2000000
# loop through audio
for i in range(0,N_audio-SAMPLERATE*CHUNKSIZE, SAMPLERATE*CHUNKSIZE):
# slice
start = i
end = start + SAMPLERATE*CHUNKSIZE
if end>N_audio: end = N_audio
y_chunk = y[start:end]
N_chunk = len(y_chunk)
print(start, end)
#fft
y_chunk_fft = fft(y_chunk)
y_chunk_fft_proc = 2.0 / N_chunk * np.abs(y_chunk_fft[0:N_chunk // 2])
xfft = np.linspace(0.0, N_chunk // 2, N_chunk // 2)
df_fft = pd.DataFrame({"frequency": xfft, "amplitude": y_chunk_fft_proc})
# analyze
df_fft_200 = df_fft[df_fft["frequency"] < 200]
df_fft_200_thresh = df_fft_200[df_fft_200["amplitude"] > 0.001]
n_thresh = int(df_fft_200_thresh["amplitude"].count())
print(n_thresh)
if n_thresh >50:
plotter(y_chunk, y_chunk_fft, N_chunk, SAMPLERATE, start, end, n_thresh)
# plotter(y_chunk, y_chunk_fft, N_chunk, SAMPLERATE, start, end, res)
#
# if i > 15*SAMPLERATE:
# break
| true |
072a53ba59547151b9fdb4ede3fd584e0d427994 | Python | jcGourcuff/Uliege | /nilm/appliance_tracker_V3.py | UTF-8 | 18,545 | 2.875 | 3 | [] | no_license | from dataManager.load import DataSets
from utils.compute import Functions, Metrics
import numpy as np
import pandas as pd
from utils.NN_modules import data_manager, AppNet
import torch
import torch.nn as nn
from nilm.solvers import Solver
from sklearn.preprocessing import StandardScaler
import copy
import time
"""
### V.3 ###
On this version, a neural network is shared by all the appliances. When it comes to adding or removing one
from the dictionnary, an output is dynamically added or removed from the network.
"""
class Appliance():
"""
Class to represent an appliance.
:param clock: Integer. +1 for each step since the last change of state
:param clok_log: List of Integers. Updated every change of state. If the appliance was on, we log the clock positively, negatively otherwise.
:param sate: Boolean. True if appliance is on, False otherwise.
:param power_mean: Any number. Mean power of the single state appliance.
:param power_std: Any positive number. Power level standard deviation of the single state appliance.
:param observed_alone: Boolean. True if the appliance has been observed alone.
:param prediction_log: Array like. Holds the historic of predictions for this appliance.
:param gt_log: Array-like. Holds the historic of ground truths for this appliance.
"""
def __init__(self, dy, std):
"""
Instanciate an appliance of power level dy.
:param dy: power_mean.
:param std: power_std.
"""
assert dy > 0
self.prediction_log = []
self.gt_log = []
self.clock = 0
self.clock_log = []
self.state = False
self.observed_alone = False
self.power_mean = dy
self.power_std = std
def get_power_sample(self):
"""
Returns an array of values sampled from the inffered power distribution of the appliance.
"""
return np.array([self.power_mean - self.power_std, self.power_mean, self.power_mean + self.power_std])
def turn_on(self):
"""
Turns the appliance on. Reset internal clock.
"""
self.reset_clock()
self.state = True
def turn_off(self):
"""
Turns the appliance off. Reset internal clock.
"""
self.reset_clock()
self.state = False
def reset_clock(self):
"""
If the appliance was on, we log the clock positively, negatively otherwise.
Clock set to 0.
"""
if self.state:
self.clock_log.append(self.clock)
else:
self.clock_log.append(-self.clock)
self.clock = 0
def pass_time(self):
"""
Increments the clock value.
"""
self.clock += 1
class Tracker():
"""
Class that implements an appliance tracker.
:param dictionary: List of dictionary of appliance.
:param n_app: Integer. Number of recorded appliances.
:param power: Float. Last recorded power value by the tracker.
:param min_value: Minimum value within the aggregated signal.
:param buffer: NN_modules.data_manager. Buffer to hold training data.
:param model: Dynamic Appnet.
:param optimizer: Model optimizer.
:param loss_fn: Criterion used to train the model.
:param learning_rate: Learning rate used to train the model.
:param preds: Arry like to hold the predictions.
"""
def __init__(self, aggregated, T_detect=60, T_error=.05, buffer_size=1440, train_window=15):
"""
:param aggregated: Pandas Series. The aggregated signal on which the tracker is set.
:param T_detect: Any number. Treshold above which transitions are taken into account. Default 60.
:param T_error: Float within (0,1). Maximum error authorized before considering new app.
For instance T_error = .05 would mean that power is ecpected to matched in 5 percent range.
:param train_window: Integer. Number of past data given as an input to the appliances model.
:param buffer_size: Integer. Size of the data buffer.
"""
self.aggregated = aggregated
self.min_value = min(aggregated)
self.buffer_size = buffer_size
self.buffer = data_manager(df_size=buffer_size)
self.model = None
self.optimizer = None
self.loss_fn = nn.BCEWithLogitsLoss(reduction='sum')
self.learning_rate = 1e-3
self.preds = []
self.T_error = T_error
self.T_detect = T_detect
self.train_window = train_window
self.clock = 0 # time since instanciation
self.dictionary = []
self.power = 0
def add_new_data(self, aggregated):
"""
Redefine self.aggregated.
"""
self.aggregated = aggregated
@property
def n_app(self):
return len(self.dictionary)
def fit_scaler(self, data):
"""
Fits a scaler on data.
"""
self.scaler = StandardScaler().fit(np.array(data).reshape(-1, 1))
def add_output(self):
"""
Adds an output to the model.
"""
if self.n_app == 0:
self.model = AppNet(self.train_window)
else:
self.model.eval()
new = AppNet(self.train_window)
new.common_layers = copy.deepcopy(self.model.common_layers)
new.fc = copy.deepcopy(self.model.fc)
with torch.no_grad():
last_layer = nn.Linear(
self.model.fc[5].weight.shape[1], self.model.fc[5].weight.shape[0] + 1)
last_layer.weight[:-1] = self.model.fc[5].weight
last_layer.bias[:-1] = self.model.fc[5].bias
new.fc[5] = last_layer
del self.model
self.model = new
self.optimizer = torch.optim.Adam(
self.model.parameters(), lr=self.learning_rate)
self.buffer.update_data(option='add')
self.preds = [x + [0] for x in self.preds]
def remove_output(self, k):
"""
Remove the k-th output of the model.
"""
self.model.eval()
new = AppNet(self.train_window)
new.common_layers = copy.deepcopy(self.model.common_layers)
new.fc = copy.deepcopy(self.model.fc)
with torch.no_grad():
last_layer = nn.Linear(
self.model.fc[5].weight.shape[1], self.model.fc[5].weight.shape[0] - 1)
last_layer.weight[:] = torch.cat(
[self.model.fc[5].weight[0:k], self.model.fc[5].weight[k + 1:]])
last_layer.bias[:] = torch.cat(
[self.model.fc[5].bias[0:k], self.model.fc[5].bias[k + 1:]])
new.fc[5] = last_layer
del self.model
self.model = new
self.optimizer = torch.optim.Adam(
self.model.parameters(), lr=self.learning_rate)
self.buffer.update_data(option='remove', index=k)
self.preds = [x[:k] + x[k + 1:] for x in self.preds]
def train_model(self, batch_size, n_train_loop):
"""
Trains the model n_train_loop times on batches of size batch_size.
"""
start_time = time.time()
train_loss = []
if self.buffer.get_size() > batch_size:
self.model.train()
for _ in range(min(n_train_loop, self.buffer.get_size() // batch_size)):
batch = self.buffer.get_random_batch(batch_size=batch_size)
inputs = torch.FloatTensor(batch[:, :-1].tolist())
targets = torch.FloatTensor(batch[:, -1].tolist())
outputs = self.model(inputs)
loss = self.loss_fn(outputs, targets)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
l = loss.data.item()
train_loss.append(l)
#print("Training model - {} seconds -".format(time.time() - start_time))
return train_loss
def add(self, dy):
"""
Adds to the dictionnary an appliance of power level dy.
:param dy: Ay number. Expeceted to be positive.
"""
self.add_output()
self.dictionary.append(Appliance(dy, std=dy * .05))
def pass_time(self):
"""
Increments the internal clock state of all appliances.
"""
for app in self.dictionary:
app.pass_time()
self.clock += 1
def update_dictionnary(self):
"""
Not used in code. Method to remove appliances based on how well the model performs on predictions for it.
"""
to_del = []
for k, a in enumerate(self.dictionary):
m, _ = Metrics.evaluate(a.gt_log, np.array(a.prediction_log) > .5)
if np.mean(m) < tresh:
to_del.append(k)
for k in to_del[::-1]:
del self.dictionary[k]
def track(self, verbose=False, train_rate=10, batch_size=10, n_batch=10, matching_window=60, new_app_bound=1, power_sample_size=10):
"""
Takes a signal as input and dissagregates it.
:param verbose: True to display debugging messages.
:param train_rate: Integer. Number of power value reading before the model is trained.
:param batch_size: Integer. Size of the batches used for training.
:param n_batch: Integer. Number of batches the model is trained on.
:param matching_window: See Solver.KP_with_constraint.
:param new_app_bound: Integer. See parameter M from Solver.KP_with_constraint.
:power_sample_size: Number of power sample per appliance for the multiple knpasack problem.
:return: Pandas DataFrame. One column for each tracked appliance.
"""
if verbose :
print("tracking...", end='\n')
index = self.aggregated.index[self.train_window:]
dissagregated = []
n_to_track = self.aggregated.shape[0] - self.train_window + 1
for k in range(self.train_window, self.aggregated.shape[0]):
track_pct = np.round(100 * k / n_to_track, decimals=2)
#print("{}%...".format(track_pct), end = '\r')
power_sample_size = min(50, self.n_app * 10)
self.next_step(k, matching_window, new_app_bound,
power_sample_size, verbose=verbose)
dissagregated.append(self.get_power_vector())
if (k - self.train_window + 1) % train_rate == 0:
self.train_model(batch_size=batch_size, n_train_loop=n_batch)
tp_concat = [pd.Series(a) for a in dissagregated]
result = pd.concat(tp_concat, axis=1).transpose().fillna(0)
result.index = index
return result
def MCKP(self, input_model, c, power_sample_size, matching_window, new_app_bound, nominal_weights=None, verbose=False):
"""
Multiple Knapsack Problem. The methods is a variant from the KP problem where it is solved for multiple nominal values for each entity.
:param input_model: Input for the model to outputs the profits of the KP problemes.
:param c: Power value. Upper bound for the KP problem.
:param power_sample_size: Number of power sample per appliance for the multiple knpasack problem.
:param matching_window: See Solver.KP_with_constraint.
:param new_app_bound: Integer. See parameter M from Solver.KP_with_constraint.
:nominal_weights: If not none, a single KP problem is solved using these values as weights.
:return: Tuple. The predicted states for the appliances, the actual prediction of the model, the weights retained after the mckp.
"""
start_time = time.time()
self.model.eval()
profits = torch.sigmoid(self.model(
torch.FloatTensor([input_model]))).detach().numpy()[0]
weights = np.array([a.get_power_sample().tolist()
for a in self.dictionary]).transpose()
if verbose :
print(weights)
print(profits)
if nominal_weights is not None:
profits = nominal_weights
weights = [nominal_weights]
negate_previous_states = ~self.compute_previous_states(
matching_window=matching_window)
KP_sols = [Solver.KP_with_constraint(
w, profits, c, negate_previous_states, new_app_bound) for w in weights]
index_best = min(range(len(KP_sols)),
key=lambda i: np.abs(KP_sols[i][1] - c))
retained_weights = weights[index_best]
X_pred, y_pred = KP_sols[index_best]
if verbose:
print("GT : {} | PRED : {} | NOM {}".format(
c, y_pred, nominal_weights is not None))
return X_pred, y_pred, retained_weights
def next_step(self, k, matching_window, new_app_bound, power_sample_size, verbose=False, pass_time=True):
"""
Reads new value y and run one step of the tracking algorithm.
"""
y = self.aggregated.iloc[k] - self.min_value + 0.01
x_final = []
input = self.make_input(
np.array(self.aggregated.iloc[k - self.train_window + 1:k + 1]))
dy = y - self.power
if dy > self.T_detect:
if self.n_app > 0:
x_pred, y_pred, w_pred = self.MCKP(
input, y, power_sample_size, matching_window, new_app_bound, verbose=verbose)
error = np.abs(y_pred - y) / y
if error < self.T_error:
x_final = x_pred
else:
nominal_weights = [a.power_mean for a in self.dictionary]
x_ssp, y_ssp, w_ssp = self.MCKP(
input, y, power_sample_size, matching_window, new_app_bound, nominal_weights=nominal_weights, verbose=verbose)
error_ssp = np.abs(y_pred - y) / y
if error_ssp < self.T_error:
x_final = x_ssp
else:
x_final = self.get_state() + [1]
self.add(dy)
else:
x_final = [1]
self.add(dy)
elif dy < - self.T_detect:
x_pred, y_pred, w_pred = self.MCKP(
input, y, power_sample_size, matching_window, new_app_bound, verbose=verbose)
error = np.abs(y_pred - y) / y
if error < self.T_error:
x_final = x_pred
else:
nominal_weights = [a.power_mean for a in self.dictionary]
x_ssp, y_ssp, w_ssp = self.MCKP(
input, y, power_sample_size, matching_window, new_app_bound, nominal_weights=nominal_weights, verbose=verbose)
error_ssp = np.abs(y_pred - y) / y
if error_ssp < self.T_error:
x_final = x_ssp
else:
self.power = y
self.update_states(x_ssp)
x_final = self.next_step(
k, matching_window, new_app_bound, power_sample_size, verbose=False, pass_time=False)
else:
x_final = self.get_state()
if pass_time:
self.make_n_save_data(input, x_final)
self.update_states(x_final)
self.preds.append(x_final)
self.pass_time()
self.power = y
return x_final
def get_power_vector(self, option='default'):
"""
Returns a vector of length nb_app. Each paramater is set to the power
value if the corresponding appliance is on, 0 otherwise.
:param option: String. 'default' or 'negate'. 'default' corresponds to
behavior described above. If 'negate', off appliances numbers ar set to
the power level, and the on appliances are set to 0.
:return: list. The power vector.
"""
vec = []
for a in self.dictionary:
bool = a.state
if option == 'negate':
bool = not bool
if bool:
vec.append(a.power_mean)
else:
vec.append(0)
return vec
def get_state(self, option='default'):
"""
Returns boolean array with True if the corresponding appliance is on.
:param option: String. 'default' or 'negate'. 'default' corresponds to
behavior described above. If 'negate', the off
applinaces are set to True and on appliances to off.
"""
vec = []
for a in self.dictionary:
bool = a.state
if option == 'negate':
bool = not bool
vec.append(bool)
return vec
def update_states(self, bools):
"""
Update the states of each appliances given the array of boolean.
:param bools: Array like. Booleans, True if app must be on, False otherwise.
"""
for a, b in zip(self.dictionary, bools):
if a.state and (not b):
a.turn_off()
elif (not a.state) and b:
a.turn_on()
if np.sum(self.get_state()) == 1:
self.dictionary[np.argmax(self.get_state())].observed_alone = True
def make_input(self, data):
"""
Builds and scale a formated input for the model.
"""
line = self.scaler.transform(
np.array(data).reshape(-1, 1)).reshape(1, -1)[0]
return line
def make_n_save_data(self, input, output):
"""
Fills the buffer.
"""
line = np.array(input.tolist() + [output])
if self.buffer.is_full():
self.buffer.dump(.1)
self.buffer.add(line)
def compute_previous_states(self, matching_window):
"""
Computes which appliances within the previous frames, in the range of matching_window.
Returns the negated vector.
"""
if len(self.preds) > 0:
previous_states = [self.preds[-1]]
k = 2
while k <= min(len(self.preds) - 1, matching_window):
previous_states.append(self.preds[k])
k += 1
represented_apps = previous_states[0]
for s in previous_states[1:]:
represented_apps = np.logical_or(represented_apps, s)
return represented_apps
else:
return np.array([True] * self.n_app)
| true |
570f559a9c0410290b5f420569df7502751b7956 | Python | anurag5398/DSA-Problems | /Hashing/ReplicatingSubstring.py | UTF-8 | 773 | 3.984375 | 4 | [] | no_license | """
Given a string B, find if it is possible to re-order the characters of the string B so that it can be represented as a concatenation of A similar strings.
Eg: B = aabb and A = 2, then it is possible to re-arrange the string as "abab" which is a concatenation of 2 similar strings "ab".
If it is possible, return 1, else return -1.
"""
class Solution:
def adddict(self, value, tempdict):
if value in tempdict:
tempdict[value]+=1
else:
tempdict[value] = 1
def solve(self, A, B):
freq = dict()
for i in range(len(B)):
self.adddict(B[i], freq)
for vals in freq.values():
if vals%A != 0:
return -1
return 1
a = Solution()
A = "bc"
print(a.solve(1, A)) | true |
1e11eea930c7065cf86e5aaa180b521ef8d2048e | Python | sammitjain/openCV_python | /loadimg.py | UTF-8 | 569 | 3.46875 | 3 | [] | no_license | # Basic program with OpenCV in Python
# Loading and writing images + scaling
import cv2
import numpy as np
import matplotlib.pyplot as plt
testImg = cv2.imread('testImg.jpg', cv2.IMREAD_GRAYSCALE)
testImg = cv2.resize(testImg,None,fx=0.3,fy=0.3) #it's imresize in MATLAB. NOTE.
#Showing with cv2
cv2.imshow('Original Image',testImg)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite('grayImg.jpg',testImg)
#Showing the image with matplotlib
##plt.imshow(testImg, cmap='gray', interpolation='bicubic')
##plt.plot([50,100],[80,100],'c',linewidth=5)
##plt.show()
| true |
8daef943f4eb9f3623d372c678e5db0f81ff1b4d | Python | juhideshpande/Geospatial-Vision | /a2/probe.py | UTF-8 | 15,257 | 3.09375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 7 16:52:08 2018
@author: Naveenkumar Sivasubramanian
"""
import math
from collections import defaultdict
#Global variables used for the code (collection defaultdict is used to handle error in list)
pointDataList = defaultdict(list)
linkDataList = defaultdict(list)
#class used to find the latitude and longitude for fiven points
class Find_LatitudeAndLongitude():
def __init__(self, shapeInfo):
self.ID = shapeInfo
shape_attributes = shapeInfo.split("/")
self.longitude, self.latitude = map(float, (shape_attributes[0], shape_attributes[1]))
#class used to package the LinkData csv into a package object
class PackageLinkID():
#The start and end data points are passed to the class which packages it into the class variables
def __init__(self, ID, start, end):
self.id = ID
self.point_one, self.point_two = Find_LatitudeAndLongitude(start), Find_LatitudeAndLongitude(end)
self.vector_longitude, self.vector_latitude = self.point_two.longitude - self.point_one.longitude, self.point_two.latitude - self.point_one.latitude
self.length = math.sqrt(self.vector_longitude ** 2 + self.vector_latitude ** 2)
if self.vector_latitude != 0:
self.radian = math.atan(self.vector_longitude / self.vector_latitude)
elif self.vector_longitude > 0:
self.radian = math.pi / 2
else:
self.radian = math.pi * 3 / 2
#Function used to calculate the distance between a packed linkData and a new probe-point
def calculateDistance(self, point):
target_longitude, target_latitude = point.longitude - self.point_one.longitude, point.latitude - self.point_one.latitude
dist_point_refnode = (target_longitude ** 2) + (target_latitude ** 2)
projection = (target_longitude * self.vector_longitude + target_latitude * self.vector_latitude) / self.length
if projection < 0:
return dist_point_refnode
pro_squre = projection ** 2
if pro_squre > self.length ** 2:
return (point.longitude - self.point_two.longitude) ** 2 + (point.latitude - self.point_two.latitude) ** 2
return (target_longitude**2 + target_latitude**2) - projection**2
#Function used to calculate distance between two links (linkData is passed)
def calculateDistanceFromLink(self, point):
target_longitude, target_latitude = point.longitude - self.point_one.longitude, point.latitude - self.point_one.latitude
return math.sqrt(target_longitude**2 + target_latitude**2)
#Class used to package the sample ID data set into an object
class PackageSampleID(object):
def __init__(self, line):
self.sampleID, \
self.dateTime, \
self.sourceCode, \
self.latitude, \
self.longitude, \
self.altitude, \
self.speed, \
self.heading = line.strip().split(',')
self.direction = ""
self.linkID = None
self.distFromRef = None
self.distFromLink = None
self.slope = None
# Function used to find the direction (F/T)
def getDirection(self, A, B):
self.direction = "F" if ((math.cos(A) * math.cos(B) + math.sin(A) * math.sin(B)) > 0) else "T"
#Function used to convert the object to string and return the required format
def toString(self):
return '{}, {}, {}, {}, {}, {}, {}, {}, {}, {} ,{}, {}\n' \
.format(self.sampleID,
self.dateTime,
self.sourceCode,
self.latitude,
self.longitude,
self.altitude,
self.speed,
self.heading,
self.linkID,
self.direction,
self.distFromRef,
self.distFromLink)
#Class used to package the sample ID data set into an object with scope object appended to the return list
class PackageProbeSlope(object):
def __init__(self, line):
self.sampleID , \
self.dateTime , \
self.sourceCode , \
self.latitude , \
self.longitude , \
self.altitude , \
self.speed , \
self.heading , \
self.linkID , \
self.direction , \
self.distFromRef, \
self.distFromLink = line.split(',')
self.elevation = None
self.slope = None
#Function used to convert the object to string and return the required format with scope appended
def toString(self):
'''
Function to convert data into comma seperated string
'''
return '{}, {}, {}, {}, {}, {}, {}, {}, {}, {} , {}, {}\n' \
.format(self.sampleID,
self.dateTime,
self.sourceCode,
self.latitude,
self.longitude,
self.altitude,
self.speed,
self.heading,
self.linkID,
self.direction,
self.distFromRef,
#self.distFromLink,
self.slope)
#Class used to package the linkData used to calculate the slope and evaluate it
class PackageLink(object):
def __init__(self, line):
self.linkID ,\
self.refNodeID ,\
self.nrefNodeID ,\
self.length ,\
self.functionalClass ,\
self.directionOfTravel,\
self.speedCategory ,\
self.fromRefSpeedLimit,\
self.toRefSpeedLimit ,\
self.fromRefNumLanes ,\
self.toRefNumLanes ,\
self.multiDigitized ,\
self.urban ,\
self.timeZone ,\
self.shapeInfo ,\
self.curvatureInfo ,\
self.slopeInfo = line.strip().split(',')
self.ReferenceNodeLat,self.ReferenceNodeLong,_ = self.shapeInfo.split('|')[0].split('/')
self.ReferenceNode = map(float, (self.ReferenceNodeLat,self.ReferenceNodeLong))
self.ProbePoints = []
#Function used to read the linkData from the csv and create linkDataList/pointDataList
def readLinkData():
print("Processing LinkData....")
for line in open("Partition6467LinkData.csv").readlines():
columns = line.strip().split(",")
shapeInfo = columns[14].split("|")
#Iterate through the link data to form the package by passing into the class
for iterator in range(len(shapeInfo)-1):
tempShape = PackageLinkID(columns[0], shapeInfo[iterator], shapeInfo[iterator+1])
linkDataList[columns[0]].append(tempShape)
pointDataList[shapeInfo[iterator]].append(tempShape)
pointDataList[shapeInfo[iterator + 1]].append(tempShape)
print("linkDataList and pointDataList created....");
#Function used to match the linkDataList with the probe data, find the shortest distance and create the Partition6467MatchedPoints.csv
def matchData():
matchedPoints = open("Partition6467MatchedPoints.csv", "w+")
previousID = None
matchPackageDataArray = []
print("Processing Partition6467MatchedPoints CSV....");
recordCount=0;
#Loop to check every data in the linkDataList with the probe data from the csv in order to find [sampleID, dateTime, sourceCode, latitude, longitude, altitude, speed, heading, linkPVID, direction, distFromRef, distFromLink]
for line in open("Partition6467ProbePoints.csv").readlines():
if recordCount < 1048576:
recordCount=recordCount+1;
probePoints = PackageSampleID(line)
latitude_longitude = Find_LatitudeAndLongitude(probePoints.latitude + "/" + probePoints.longitude)
#Check if the previous value is repeated
if probePoints.sampleID != previousID:
previousID = probePoints.sampleID
#Looping through every element in the linkDataList
for key in linkDataList.keys():
for link in linkDataList[key]:
distance = link.calculateDistance(latitude_longitude)
#If the probe point is empty or less than the distance find the direction b/w the point and the linkdata
if not probePoints.distFromRef or distance < probePoints.distFromRef:
probePoints.distFromRef, probePoints.linkID = distance, link.id
probePoints.distFromLink = linkDataList[probePoints.linkID][0].calculateDistanceFromLink(latitude_longitude)
probePoints.getDirection(float(probePoints.heading), link.radian)
matchPackageDataArray = [link.point_one, link.point_two]
else:
#Looping through the array of match data when the repeation occurs
for candidate_point in matchPackageDataArray:
for link in pointDataList[candidate_point.ID]:
distance = link.calculateDistance(latitude_longitude)
if not probePoints.distFromRef or distance < probePoints.distFromRef:
probePoints.distFromRef, probePoints.linkID = distance, link.id
probePoints.distFromLink = linkDataList[probePoints.linkID][0].calculateDistanceFromLink(latitude_longitude)
probePoints.getDirection(float(probePoints.heading), link.radian)
else:
break;
#Finding the distance from the reference
probePoints.distFromRef = math.sqrt(probePoints.distFromRef) * (math.pi / 180 * 6371000)
#Finding the distance from the link
probePoints.distFromLink = probePoints.distFromLink * (math.pi / 180 * 6371000)
matchedPoints.write(probePoints.toString())
matchedPoints.close()
print("Done loading the Partition6467MatchedPoints CSV....");
#Function used to distance between two data points (latitude and longitude) with respect to earth avg rad
def distance(longitude_point_one, latitude_point_one, longitude_point_two, latitude_point_two):
longitude_point_one, latitude_point_one, longitude_point_two, latitude_point_two = list(map(math.radians, [longitude_point_one, latitude_point_one, longitude_point_two, latitude_point_two]))
distance_longitude, distance_latitude = longitude_point_two - longitude_point_one , latitude_point_two - latitude_point_one
#Calculating the distance
raw_distance = math.sin(distance_latitude/2)**2 + math.cos(latitude_point_one) * math.cos(latitude_point_two) * math.sin(distance_longitude/2)**2
#Converting in Km with respect with earth radius
distance_kilometers = 6371 * 2 * math.asin(math.sqrt(raw_distance))
return distance_kilometers
#Function used to find the slope of the road link
def calculateSlopeData():
slopeArray = []
recordCount=0;
slope_csv = open("slope_data.csv", 'w')
#test2 = open("test2.txt", 'w')
previousProbe = None
print("Calculating slope data....")
#creating the linkArray with linkdata csv (converted in respective package)
for line in open("Partition6467LinkData.csv").readlines():
slopeArray.append(PackageLink(line))
print("Comparing the match data....")
#Looping through matched point csv to find the slope and create slope csv
with open("Partition6467MatchedPoints.csv") as each_data:
for line in each_data:
if recordCount < 1200000:
recordCount=recordCount+1;
current_probe = PackageProbeSlope(line)
#checking previous value for repetation
if not previousProbe or current_probe.linkID != previousProbe.linkID:
current_probe.slope = ''
else:
try:
start, end = list(map(float, [current_probe.longitude, current_probe.latitude])), list(map(float, [previousProbe.longitude, previousProbe.latitude]))
hypotenuse_angle = distance(start[0], start[1], end[0], end[1]) / 1000
opposite_angle = float(current_probe.altitude) - float(previousProbe.altitude)
current_probe.slope = (2 * math.pi * math.atan(opposite_angle / hypotenuse_angle)) / 360
except ZeroDivisionError:
current_probe.slope = 0.0
#Looping through each linkArray
for link in slopeArray:
if current_probe.linkID.strip() == link.linkID.strip() and link.slopeInfo != '':
link.ProbePoints.append(current_probe)
break
#Writing to the slope csv
slope_csv.write(current_probe.toString())
previousProbe = current_probe
else:
break;
#closing the slope csv and returning the array
slope_csv.close()
print("Done calculating slope data....")
return slopeArray
#Function used to evaluate the derived road slope with the surveyed road slope in the link data file
def slope_evaluation(scope_data):
print("Processing evaluation....")
evaluationCsv = open("evaluation.csv", 'w')
#Creating the header for the csv file
#evaluationCsv.write('ID, Given Slope, Calculated Slope' + "\n")
#looping through each element in the scope array
for node in scope_data:
# checking for matched point in the node
if len(node.ProbePoints) > 0:
summation = 0.0
#Splitting the slopeInfo to form an array of slopes
slopeGroupArray = node.slopeInfo.strip().split('|')
#Looping through each element and finding the sum in the slope group
for eachSlope in slopeGroupArray:
summation += float(eachSlope.strip().split('/')[1])
#calculating the average
slope = summation / len(slopeGroupArray)
calculatedSum, probCount = 0.0, 0
# Calculating the mean of calculated slope info for the link
for eachProbe in node.ProbePoints:
#If direction is towards turn the slope value to negative
if eachProbe.direction == "T":
eachProbe.slope = -eachProbe.slope
#Incrementing the count
if eachProbe.slope != '' and eachProbe.slope != 0:
calculatedSum += eachProbe.slope
probCount += 1
evaluatedSlope = calculatedSum / probCount if probCount != 0 else 0
evaluationCsv.write('{}, {}, {}\n'
.format(node.linkID,
slope,
evaluatedSlope))
print("Done evaluating slope....")
evaluationCsv.close()
#Function which maeks the start of the script
if __name__ == '__main__':
#Function called to create linkdata array
readLinkData()
#Function called to create the Partition6467MatchedPoints csv
matchData()
#Function used to calculate the slope
slope_data = calculateSlopeData()
#Function called to do the evaluation process
slope_evaluation(slope_data)
| true |
2aed8259a18a204a10f7b8ebc1d65f6dd4ea0b25 | Python | kevin851066/Leetcode | /Python/455.py | UTF-8 | 394 | 2.921875 | 3 | [] | no_license | class Solution:
def findContentChildren(self, g, s):
'''
type: g: List[int]
type: s: List[int]
rtype: int
'''
s, g = sorted(s), sorted(g)
idx_g = 0
output = 0
for j in range(len(s)):
if idx_g < len(g) and g[idx_g] <= s[j]:
idx_g += 1
output += 1
return output | true |
b3d267ec92b64fb7f752d18256142f7d14c03cbb | Python | minhtoando0899/baitap | /control_structures/unit_2/bai10.py | UTF-8 | 708 | 3.6875 | 4 | [] | no_license | # kiem tra 1 so nguyen co phai la so nguyen to khong
import math
while True:
class Check:
def __init__(self):
self.n = int
def get(self):
self.n = int(input("Nhập số nguyên: "))
def che(self):
if self.n < 2:
print("Nhập số lớn hơn 2")
if self.n >= 2:
for x in range(2, int(math.sqrt(self.n) + 1)):
if self.n % x == 0:
print("%s không phải là số nguyên tố!!!" % self.n)
break
else:
print("%s là số nguyên tố!!!" % self.n)
C1 = Check()
C1.get()
C1.che()
| true |
8119977354ad4d9632c265217b61bbe42e42a4e4 | Python | mclear73/Useful-Bioinformatics-Scripts | /Python_BioInformatics_Library.py | UTF-8 | 24,908 | 2.921875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 25 13:46:09 2020
@author: mclea
"""
##General function used by split_fasta##
#############################################################################
def batch_iterator(iterator, batch_size):
"""Returns lists of length batch_size.
This can be used on any iterator, for example to batch up
SeqRecord objects from Bio.SeqIO.parse(...), or to batch
Alignment objects from Bio.AlignIO.parse(...), or simply
lines from a file handle.
This is a generator function, and it returns lists of the
entries from the supplied iterator. Each list will have
batch_size entries, although the final list may be shorter.
"""
entry = True # Make sure we loop once
while entry:
batch = []
while len(batch) < batch_size:
try:
entry = next(iterator)
except StopIteration:
entry = None
if entry is None:
# End of file
break
batch.append(entry)
if batch:
yield batch
##Split protein FASTA for input into isoelectric point calculator##
#This function requires the full path and filename of the protein fasta
#File that you wish to divide
#This function is necessary because IPC2 has a file size limit
#It will deposit .csv files in your downloads folder as if you had manually
#used IPC2
#############################################################################
def split_fasta(File, outputPrefix, length=50):
from Bio import SeqIO
import os
direct = os.getcwd()
record_iter = SeqIO.parse(open(File), "fasta")
for i , batch in enumerate(batch_iterator(record_iter, length)):
filename = direct + "\\" + outputPrefix +"ISO_%i.fasta" % (i + 1)
with open(filename, "w") as handle:
count = SeqIO.write(batch, handle, "fasta")
print("Wrote %i records to %s" % (count, filename))
#Add column that designates if protein may be a small secreted protein based
# off of SingalP output and peptide length
def getSSP(DF, signalPname):
secreteList = []
for a , b in zip(DF['AA Length'], DF[signalPname]):
if a <= 400 and b == 'SP(Sec/SPI)':
secreteList.append('SSP')
elif a > 400 and b == 'SP(Sec/SPI)':
secreteList.append('Secreted')
else:
secreteList.append('Not Exciting')
DF['Secreted'] = secreteList
newDF = DF
return newDF
##Selenium for isoelectric point##
#############################################################################
#This function will run IPC2 on all of the protein fasta files in a directory
#You must run this function within the directory containing the "*.fasta"
#output files from split_fasta()
#peptide sequences. You must also provide the path for the selenium chrome
#driver on your computer. For more information, see Python Library Manual
#and selenium docs
#Note: my executable path is 'C:/Users/mclea/OneDrive/Desktop/chromedriver.exe'
def queryIPC2(executablePath):
from selenium import webdriver
import os
import time
for filename in os.listdir(os.getcwd()):
if filename.endswith(".fasta"):
try:
driver = webdriver.Chrome(executable_path=executablePath)
my_file = open(filename)
file_contents = my_file.read()
driver.get("http://ipc2.mimuw.edu.pl/index.html")
element = driver.find_element_by_name('protein')
element.send_keys(file_contents)
my_file.close()
driver.find_element_by_name('protein').submit()
driver.get("http://ipc2.mimuw.edu.pl/result.csv")
time.sleep(3)
driver.close()
except Exception as e:
print("something went wrong: ")
print(e)
driver.quit()
##Compile IPC2 Files##
#############################################################################
#This function compiles all of the .csv files generated by queryIPC2()
#This function also parses specific transcript names
#Run this function in the directory where all of your IPC2 output files are
#stored.
#NOTE: all "*.csv" files in the directory must be IPC2 output files
#The output is a single .xlsx file with two sheets. One sheet contains
#parsed protein names and the other sheet is the full, unparsed list
#of all combined IPC2 outputs in the directory
def combineIPC2output():
import os
import glob
import pandas as pd
#need to parse the header column in the new dataframe
path = os.getcwd()
all_files = glob.glob(os.path.join(path, "*.csv"))
df_from_each_file = (pd.read_csv(f) for f in all_files)
concatenated_df = pd.concat(df_from_each_file, ignore_index=True)
concatenated_df = concatenated_df[['header', 'molecular_weight', 'IPC2_protein', 'IPC2_peptide']].drop_duplicates()
#Split dataframe by organism this is necessary because we need to parse the headers
#Differently
if concatenated_df[concatenated_df['header'].str.contains('Neucr')]:
neurDF = concatenated_df[concatenated_df['header'].str.contains('Neucr')]
#Parse the header column
nParse = neurDF["header"].str.split("|", expand = True).drop(columns=[0,1,2]).rename(columns={3:'header'})
nParse['match'] = neurDF['header']
nParse = nParse.merge(neurDF, how='left', left_on='match', right_on='header').drop(columns=['match', 'header_y'])
else:
nParse = pd.DataFrame()
if concatenated_df[concatenated_df['header'].str.contains('Aspnid')]:
aspDF = concatenated_df[concatenated_df['header'].str.contains('Aspnid')]
#Parse the header column
aParse = aspDF["header"].str.split("|", expand = True).drop(columns=[0,1,2]).rename(columns={3:'header'})
aParse['match'] = aspDF['header']
aParse = aParse.merge(aspDF, how='left', left_on='match', right_on='header').drop(columns=['match', 'header_y'])
else:
aParse = pd.DataFrame()
if concatenated_df[concatenated_df['header'].str.contains('Cre')]:
chlamDF = concatenated_df[concatenated_df['header'].str.contains('Cre')]
#Parse the header column
cParse = chlamDF["header"].str.split(" ", expand = True).drop(columns=[1,2,3,4,5]).rename(columns={0:'header'})
cParse['match'] = chlamDF['header']
cParse = cParse.merge(chlamDF, how='left', left_on='match', right_on='header').drop(columns=['match', 'header_y'])
else:
cParse = pd.DataFrame()
#Concatenate modified dataframes
fixedDF = pd.concat([nParse, aParse, cParse])
#Export file containing the modified dataframes and original concatenated DF
#Export Excel File
writer = pd.ExcelWriter('IPC2 Output.xlsx')
fixedDF.to_excel(writer,'IPC2_forAnnot', index=False)
concatenated_df.to_excel(writer,'IPC2_FULL', index=False)
writer.save()
#Compiles all annotations files available from mycocosum and outputs it to a single
#.xlsx file denoted by "outputFile"
#Note: outputFile and pep must be used!!!
def compileMycocosum(outputFile, pep, trans="None", KOG="None", KEGG="None",
GO="None", InterPro="None", SignalP="None", IPC2="None",
CAZy="None", FTFDB="None", Secretome="None"):
import pandas as pd
from Bio import SeqIO
#Extract protein ID and gene names from protein FASTA file
record = list(SeqIO.parse(pep, "fasta"))
rec = [rec.id for rec in record]
aa = [rec.seq for rec in record]
aspDF = pd.DataFrame(rec)
aspDF = aspDF[0].str.split("|", expand = True).rename(columns={0:'Source', 1:'Genome', 2:'Protein ID', 3:'Protein Name'})
aspDF['Protein ID'] = aspDF['Protein ID'].astype(str)
#Add amino acid sequence
aspDF['AA Seq'] = aa
aspDF['AA Length'] = aspDF['AA Seq'].str.len()
if KOG != "None":
aspKOG = pd.read_csv(KOG, sep = '\t')
aspKOG['proteinId'] = aspKOG['proteinId'].astype(str)
aspKOG = aspKOG.drop(columns='#transcriptId')
#Add KOG data
aspDF = aspDF.merge(aspKOG, how='left', left_on='Protein ID', right_on='proteinId').drop(columns= ['proteinId'])
if KEGG != "None":
aspKEGG = pd.read_csv(KEGG, sep = '\t')
aspKEGG['#proteinId'] = aspKEGG['#proteinId'].astype(str)
#Add KEGG data
aspDF = aspDF.merge(aspKEGG, how='left', left_on='Protein ID', right_on='#proteinId').drop(columns= ['#proteinId'])
if GO != "None":
aspGO = pd.read_csv(GO, sep = '\t')
aspGO['#proteinId'] = aspGO['#proteinId'].astype(str)
#Add GO data
aspDF = aspDF.merge(aspGO, how='left', left_on='Protein ID', right_on='#proteinId').drop(columns= ['#proteinId'])
if InterPro != "None":
aspInterPro = pd.read_csv(InterPro, sep = '\t')
aspInterPro['#proteinId'] = aspInterPro['#proteinId'].astype(str)
#Add InterPro data
aspDF = aspDF.merge(aspInterPro, how='left', left_on='Protein ID', right_on='#proteinId').drop(columns= ['#proteinId'])
if SignalP != "None":
aspSignalP = pd.read_csv(SignalP)
aspSignalP['Protein'] = aspSignalP['Protein'].astype(str)
#Add signalP data
aspDF = aspDF.merge(aspSignalP, how='left', left_on='Protein Name', right_on='Protein').drop(columns= ['Protein'])
if trans != "None":
#Extract transcript IDs and gene names from transcript FASTA file
record = list(SeqIO.parse(trans, "fasta"))
rec = [rec.id for rec in record]
aspTrans = pd.DataFrame(rec)
aspTrans = aspTrans[0].str.split("|", expand = True).rename(columns={0:'Source', 1:'Genome', 2:'Transcript ID', 3:'Protein Name'})
aspTrans['Transcript ID'] = aspTrans['Transcript ID'].astype(str)
aspDF = aspDF.merge(aspTrans, how='left', left_on='Protein Name', right_on='Protein Name').drop(columns = ['Source_y','Genome_y'])
if FTFDB != "None":
aspTFDB = pd.read_csv(FTFDB)
aspTFDB[' Locus Name'] = aspTFDB[' Locus Name'].astype(str)
aspTFDB = aspTFDB.drop(columns=' Species Name')
#Add Fungal TFDB data
aspDF = aspDF.merge(aspTFDB, how='left', left_on='Protein Name', right_on=' Locus Name').drop(columns=[' Locus Name'])
#Add IPC2 data
if IPC2 != "None":
ipc2 = pd.ExcelFile(IPC2)
ipc2DF = pd.read_excel(ipc2, 'IPC2_forAnnot')
aspDF = aspDF.merge(ipc2DF, how='left', left_on='Protein Name', right_on='header_x').drop(columns= ['header_x'])
if CAZy != "None":
caz = pd.ExcelFile(CAZy)
cazDF = pd.read_excel(caz, 'Sheet1')
if aspDF['Protein Name'].str.contains('NCU').any():
aspDF['Gene Name'] = aspDF['Protein Name'].str[:-2]
aspDF = aspDF.merge(cazDF, how='left', left_on='Gene Name', right_on='Gene').drop(columns= ['Gene'])
else:
aspDF = aspDF.merge(cazDF, how='left', left_on='Protein Name', right_on='Gene').drop(columns= ['Gene'])
if Secretome != "None":
print("You included a secretomeDB file. It may take a while to compile.")
record = list(SeqIO.parse(Secretome, "fasta"))
rec = [rec.id for rec in record]
aa = [rec.seq for rec in record]
secDF = pd.DataFrame(rec)
secDF = secDF[0].str.split("|", expand = True).rename(columns={0:'Source',
1:'ref#', 2:'ref', 3:'NCBI Name',
4:'SecretomeDB Description'})
secDF['SecretomeDB Description'] = secDF['SecretomeDB Description'].astype(str)
secDF['AA Seq'] = aa
aspDF = aspDF.merge(secDF[['AA Seq', 'SecretomeDB Description']],
how='left', left_on='AA Seq',
right_on='AA Seq', indicator=True)
tempDF = aspDF.drop_duplicates(subset=['Protein Name'])
length = len(tempDF[tempDF['_merge'] == 'both'])
aspDF = aspDF.drop(columns=['_merge'])
print("You matched ",length, "peptides of ",len(aa), "present in the secretomeDB.")
#Determine secreted and SSP based of signalP data and peptide length
if SignalP != 'None':
getSSP(aspDF, 'Prediction')
#Add Lipid binding
# gpsLipid = pd.read_csv(gpsLipid, sep='\t')
# names = gpsLipid["ID"].str.split("|", expand = True).drop(columns=[0,1,2]).rename(columns={3:'ID'})
# names['match'] = gpsLipid['ID']
# newgpsLipid = names.merge(gpsLipid, how='left', left_on='match', right_on='ID').drop(columns=['match', 'ID_y'])
# aspDF = aspDF.merge(newgpsLipid, how='left', left_on='Protein Name', right_on='ID_x').drop(columns=['ID_x'])
#Output the final annotation file
filename = outputFile + '.xlsx'
writer = pd.ExcelWriter(filename)
aspDF.to_excel(writer,'FULL', index=False)
writer.save()
#Compiles all of the annotation data for Chlamydomonas reinhardtii
#This function is specific to C. reinhardtii and is not meant to be adapted
#to a different organisms
#This function will also plot the amino acid length distribution and
#Output some basic statistics about the predict protein length distribution
def compileChlamAnnot(outputFile, trans, geneName, description, definition, annotation, protFasta,
signalP, Delaux, IPC2, PlantTFDB):
import pandas as pd
from Bio import SeqIO
from scipy import stats
import numpy as np
import matplotlib.pyplot as plt
#Import relevant files
chlamName = pd.read_csv(trans, skiprows=[0], delim_whitespace=True)
chlamGeneName = pd.read_csv(geneName, sep='\t',
names=['Transcript ID', 'Gene Name', 'Alt. Gene Name'])
chlamDescription = pd.read_csv(description, sep='\t',
names=['Transcript ID', 'Description'])
chlamDefline = pd.read_csv(definition, sep='\t',
names=['Transcript ID', 'defLine/pdef', 'Details'])
chlamAnnotation = pd.read_csv(annotation, sep='\t')
CHLAMrecord = list(SeqIO.parse(protFasta, "fasta"))
# predXLS = pd.ExcelFile(predAlgo)
delaux = pd.ExcelFile(Delaux)
#Add Gene Name
chlamName = chlamName.merge(chlamGeneName, how='left', left_on= '#5.5', right_on='Transcript ID').drop(columns=['Transcript ID'])
#Add Gene Description
chlamName = chlamName.merge(chlamDescription, how='left', left_on= '#5.5', right_on='Transcript ID').drop(columns=['Transcript ID'])
#Add defline/pdef
chlamName = chlamName.merge(chlamDefline, how='left', left_on= '#5.5', right_on='Transcript ID').drop(columns=['Transcript ID'])
#Add annotation
chlamName = chlamName.merge(chlamAnnotation, how='left', left_on= '#5.5', right_on='transcriptName').drop(columns=['transcriptName'])
CHLAMrec = [rec.id for rec in CHLAMrecord]
CHLAMaa = [rec.seq for rec in CHLAMrecord]
CHLAMDFpep = pd.DataFrame(CHLAMrec)
CHLAMDFpep['AA Seq'] = CHLAMaa
CHLAMDFpep['AA Length'] = CHLAMDFpep['AA Seq'].str.len()
CHLAMDFpep = CHLAMDFpep[(np.abs(stats.zscore(CHLAMDFpep['AA Length'])) < 3)]
proteinTotal = len(CHLAMDFpep)
avgProtLength = CHLAMDFpep['AA Length'].mean()
f= open("Creinhardtii.txt", "w")
print("Total Predicted Proteins = " + str(proteinTotal), file=f)
print("Average Protein Length = " + str(avgProtLength), file=f)
f.close()
CHLAMDFpep.boxplot(column=['AA Length'])
plt.savefig("Creinhardtii_AALength.pdf")
chlamName = chlamName.merge(CHLAMDFpep, how='left', left_on='#5.5', right_on=0)
chlamName =chlamName.drop(columns=[0])
#Add PredAlgo, removed because PredAlgo appears to be drepecated
# predDF = pd.read_excel(predXLS, 'Sheet1')
# chlamName = chlamName.merge(predDF, how='left', left_on='3.1', right_on='full ID (most v3)')
# chlamName = chlamName.drop(columns=['full ID (most v3)'])
#Add Delaux annotation for CSSP
delauxGenes = pd.read_excel(delaux, 'Sheet1')
chlamName = chlamName.merge(delauxGenes, how='left', left_on='#5.5', right_on='#5.5')
#Add SignalP
sigP = pd.read_csv(signalP)
chlamName = chlamName.merge(sigP, how='left', left_on='#5.5', right_on='# ID')
#Add IPC2
ipc2 = pd.ExcelFile(IPC2)
ipc2DF = pd.read_excel(ipc2, 'IPC2_forAnnot')
chlamName = chlamName.merge(ipc2DF, how='left', left_on='#5.5', right_on='header_x').drop(columns= ['header_x'])
#Add Plant TFDB
TFDF = pd.read_csv(PlantTFDB)
chlamName = chlamName.merge(TFDF, how='left', left_on='#5.5', right_on='TF_ID').drop(columns= ['TF_ID'])
#Determine secreted and SSP based of signalP data and peptide length
getSSP(chlamName, 'Prediction')
#Generate the output file, 'Creinhardtii_Annotation.xlsx'
writer = pd.ExcelWriter(outputFile)
chlamName.to_excel(writer,'FULL', index=False)
writer.save()
#This function takes a .csv file of gene names (or any other shared identifier)
#And will make a venn diagram for up to 6 comparisons and create a union
#output file that includes the genes that are shared in all of the categories
#included in the comparison
#Note: Column headings are automatically category labels
#If more than 6 columns are included, only the first 6 columns will be
#compared
def makeVenn(csvFilePath):
import pandas as pd
from venn import venn
DF = pd.read_csv(csvFilePath)
catList = list(DF.columns.values)
if len(catList) == 2:
set1 = set()
set2 = set()
for i in DF.iloc[:,0]:
set1.add(i)
for i in DF.iloc[:,1]:
set2.add(i)
unionDict = dict([(catList[0], set1), (catList[1],set2)])
union = set1.intersection(set2)
elif len(catList) == 3:
set1 = set()
set2 = set()
set3 = set()
for i in DF.iloc[:,0]:
set1.add(i)
for i in DF.iloc[:,1]:
set2.add(i)
for i in DF.iloc[:,2]:
set3.add(i)
unionDict = dict([(catList[0], set1), (catList[1],set2),
(catList[2],set3)])
union = set1.intersection(set2, set3)
elif len(catList) == 4:
set1 = set()
set2 = set()
set3 = set()
set4 = set()
for i in DF.iloc[:,0]:
set1.add(i)
for i in DF.iloc[:,1]:
set2.add(i)
for i in DF.iloc[:,2]:
set3.add(i)
for i in DF.iloc[:,3]:
set4.add(i)
unionDict = dict([(catList[0], set1), (catList[1], set2),
(catList[2], set3), (catList[3], set4)])
union = set1.intersection(set2, set3, set4)
elif len(catList) == 5:
set1 = set()
set2 = set()
set3 = set()
set4 = set()
set5 = set()
for i in DF.iloc[:,0]:
set1.add(i)
for i in DF.iloc[:,1]:
set2.add(i)
for i in DF.iloc[:,2]:
set3.add(i)
for i in DF.iloc[:,3]:
set4.add(i)
for i in DF.iloc[:,4]:
set5.add(i)
unionDict = dict([(catList[0], set1), (catList[1], set2),
(catList[2], set3), (catList[3], set4),
(catList[4], set5)])
union = set1.intersection(set2, set3, set4, set5)
elif len(catList) == 6:
set1 = set()
set2 = set()
set3 = set()
set4 = set()
set5 = set()
set6 = set()
for i in DF.iloc[:,0]:
set1.add(i)
for i in DF.iloc[:,1]:
set2.add(i)
for i in DF.iloc[:,2]:
set3.add(i)
for i in DF.iloc[:,3]:
set4.add(i)
for i in DF.iloc[:,4]:
set5.add(i)
for i in DF.iloc[:,5]:
set6.add(i)
unionDict = dict([(catList[0], set1), (catList[1], set2),
(catList[2], set3), (catList[3], set4),
(catList[4], set5), (catList[5], set6)])
union = set1.intersection(set2, set3, set4, set5, set6)
if len(catList) >=2:
unionDF = pd.DataFrame(union)
figure = venn(unionDict)
writer = pd.ExcelWriter('Venn Output.xlsx')
unionDF.to_excel(writer,'Union', index=False)
writer.save()
return figure, unionDF
if len(catList) > 6:
print("More than 6 columns were included in dataset. Only the first 6 columns are included in this analysis.")
elif len(catList) == 1:
print("Only one column is included. There is nothing to compare.")
#This function will extract keywords provided in the form of a dataframe column
#From an annotation dataframe
#The geneIdentifier value should be the column in the annotation file that will
#be used to match with the differential expression data
###NOTE: This is supposed to be used as part fo the extractFromCSV() function
###It is not recommended to use this function outside of the extractFromCSV() function
def KeywordExtract(annotationDF, DFColumn, geneIdentifier):
import pandas as pd
DFColumn = DFColumn.dropna()
DFColumn = DFColumn.astype(str)
listString = '|'.join(DFColumn)
DF = annotationDF[annotationDF.apply(lambda row: row.astype(str).str.contains(listString,
case=False).any(), axis=1)]
DF = DF.drop_duplicates(subset=[geneIdentifier])
# geneList = pd.DataFrame()
# geneList[geneIdentifier] = DF[geneIdentifier]
return DF
#This function will extract key genes of interest based on a string match. This
#Can be used to extract groups of genes of interest from an annotation file
#This function requires 1) an annotation file in .csv format. 2) A .csv file with
#column headings being the gene group names of interest and the values underneath the column
#the extraction keywords. 3) A geneIdentifier value that specifies the column name
#to be used to match with differential expression data downstream. 4) Full output
#file name as .xlsx. and 5) [optional] specify whether SYM pathway are desired to be extracted
def extractFromCSV(annotationCSV, genesCSV, geneIdentifier, outputFile, delaux='None'):
import pandas as pd
AnnotDF = pd.read_csv(annotationCSV)
genesDF = pd.read_csv(genesCSV)
cols = list(genesDF)
writer = pd.ExcelWriter('Genes of Interest.xlsx')
for i in cols:
temp = KeywordExtract(AnnotDF, genesDF[i], geneIdentifier)
temp.to_excel(writer, i, index=False)
ssps = AnnotDF[AnnotDF['Secreted'] == 'SSP'].drop_duplicates(subset=[geneIdentifier])
secreted = AnnotDF[AnnotDF['Secreted'] == 'Secreted'].drop_duplicates(subset=[geneIdentifier])
if delaux != 'None':
SYM = AnnotDF.dropna(subset=['Delaux et al. 2015']).drop_duplicates(subset=[geneIdentifier])
SYM.to_excel(writer, 'SYM', index=False)
ssps.to_excel(writer, 'SSPs', index=False)
secreted.to_excel(writer, 'Secrted', index=False)
writer.save()
| true |
b26ceb3579bbe9617481f0cd98ee7c1ff957f392 | Python | betidav/tangla_mec | /PythonModules/Main.py | UTF-8 | 1,672 | 2.765625 | 3 | [] | no_license | import os
import numpy as np
from numpy import loadtxt
#Import all the layers
from Layer1SelectWafer import SelectWafer
from Layer2SelectMeasurementType import SelectMeasurementType
from Layer3SelectProcessFabricationType import ProcessFabrication
#Main class
class MainClass:
def __init__(self):
e=2.71828183
WaferListObject = SelectWafer.MilabWafers()
self.ListOfMilabWafers = WaferListObject.Wafers()
def ListOfWafers(self):
#return all the possible wafers that have been measured
return self.ListOfMilabWafers
"""
class to load the type of measurment to be investigated e.g GC losses, WG losses, etc
"""
class LoadMeasurementType:
def __init__(self):
self.cwd = os.getcwd()
e=2.71828183
#return all the measurements that have been performed on a particular lot e.g WG losses, MMI losses, GC, etc
def MeasurementPurposeList(self, WaferType):
self.MeasurementList = np.array(SelectMeasurementType.MilabMeasurementTypes().MType(self.cwd+"\Layer2SelectMeasurementType\MeasurementType/"+str(WaferType)+".txt"))
#print self.MeasurementList
return self.MeasurementList
class SelectMeasurement:
def __init__(self):
e=2.71828183
#self.measurements = np.array(SelectMeasurementType.MilabMeasurementTypes().MType(self.cwd+"\Layer2SelectMeasurementType\MeasurementType/"+str(WaferType)+".txt"))
def measurement(self):
return self.measurements
#if __name__ == "__main__":
#MainObject = MainClass()
#Wafers = MainObject.ListOfWafers()
#MeasurementTypes = (LoadMeasurementType().MeasurementPurposeList("Octopus")) # Ray, Manta, Nemo, Nemo2, etc
#print Wafers
#print MeasurementTypes[0]
| true |
1726be41015cd6c26dfcce8b7d85ca561265517a | Python | tangentlabs/django-url-tracker | /url_tracker/tests.py | UTF-8 | 7,409 | 2.8125 | 3 | [
"BSD-2-Clause"
] | permissive | """
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from mock import Mock
from django.http import Http404
from django.test import TestCase
import url_tracker
from url_tracker.models import URLChangeRecord
class TestTracking(TestCase):
def setUp(self):
class DoesNotExist(BaseException):
pass
self.model_mock = Mock
self.model_mock.get_absolute_url = Mock(method='get_absolute_url')
self.tracked_model = self.model_mock(name='TrackedModel')
self.tracked_model._get_tracked_url = lambda: u'/the/new/one/'
def raise_exception(*args, **kwargs):
raise self.tracked_model.__class__.DoesNotExist
class_objects = Mock(name="MockModelManager")
class_objects.get = raise_exception
self.tracked_model.__class__.objects = class_objects
self.tracked_model.__class__.DoesNotExist = DoesNotExist
self.tracked_db_model = self.model_mock(name='TrackeDatabaseModel')
self.tracked_db_model._get_tracked_url = lambda: u'/the/old/one/'
def test_tracking_model_without_url_method(self):
class EmptyModel(object):
pass
self.assertRaises(
url_tracker.URLTrackingError,
url_tracker.track_url_changes_for_model,
EmptyModel(),
)
def test__lookup_url_with_new_instance(self):
url_tracker.track_url_changes_for_model(Mock)
url_tracker.lookup_previous_url(self.tracked_model)
self.assertEquals(self.tracked_model._old_url, None)
def test_lookup_url_with_existing_instance(self):
def return_instance(pk):
return self.tracked_db_model
class_objects = Mock(name='MockModelManager')
class_objects.get = return_instance
self.tracked_model.__class__.objects = class_objects
url_tracker.track_url_changes_for_model(Mock)
url_tracker.lookup_previous_url(self.tracked_model)
self.assertEquals(self.tracked_model._old_url, u'/the/old/one/')
def test_track_changed_url_with_new_instance(self):
instance = self.tracked_model
instance._old_url = None
url_tracker.track_changed_url(instance)
self.assertEquals(URLChangeRecord.objects.count(), 0)
def test_track_changed_url_with_unchanged_url(self):
instance = self.tracked_model
instance._old_url = '/the/new/one/'
url_tracker.track_changed_url(instance)
self.assertEquals(URLChangeRecord.objects.count(), 0)
def test_track_changed_url_without_existing_records(self):
instance = self.tracked_model
instance._old_url = '/the/old/one/'
url_tracker.track_changed_url(instance)
self.assertEquals(URLChangeRecord.objects.count(), 1)
record = URLChangeRecord.objects.all()[0]
self.assertEquals(record.new_url, u'/the/new/one/')
self.assertEquals(record.old_url, u'/the/old/one/')
self.assertEquals(record.deleted, False)
def test_track_changed_url_with_existing_records(self):
URLChangeRecord.objects.create(old_url='/the/oldest/one/', new_url='/the/old/one/')
URLChangeRecord.objects.create(old_url='/one/', new_url='/the/')
instance = self.tracked_model
instance._old_url = '/the/old/one/'
url_tracker.track_changed_url(instance)
self.assertEquals(URLChangeRecord.objects.count(), 3)
record = URLChangeRecord.objects.get(pk=1)
self.assertEquals(record.old_url, u'/the/oldest/one/')
self.assertEquals(record.new_url, u'/the/new/one/')
self.assertEquals(record.deleted, False)
record = URLChangeRecord.objects.get(pk=3)
self.assertEquals(record.old_url, u'/the/old/one/')
self.assertEquals(record.new_url, u'/the/new/one/')
self.assertEquals(record.deleted, False)
def test_track_changed_url_with_existing_records_and_old_url(self):
URLChangeRecord.objects.create(old_url='/the/oldest/one/', new_url='/the/old/one/')
URLChangeRecord.objects.create(old_url='/the/old/one/', new_url='/the/')
instance = self.tracked_model
instance._old_url = '/the/old/one/'
url_tracker.track_changed_url(instance)
self.assertEquals(URLChangeRecord.objects.count(), 2)
record = URLChangeRecord.objects.get(pk=1)
self.assertEquals(record.old_url, u'/the/oldest/one/')
self.assertEquals(record.new_url, u'/the/new/one/')
self.assertEquals(record.deleted, False)
record = URLChangeRecord.objects.get(pk=2)
self.assertEquals(record.old_url, u'/the/old/one/')
self.assertEquals(record.new_url, u'/the/new/one/')
self.assertEquals(record.deleted, False)
def test_track_changed_url_with_existing_deleted_record(self):
URLChangeRecord.objects.create(old_url='/the/oldest/one/',
new_url='/the/old/one/',
deleted=True)
URLChangeRecord.objects.create(old_url='/one/', new_url='/the/')
instance = self.tracked_model
instance._old_url = '/the/old/one/'
url_tracker.track_changed_url(instance)
record = URLChangeRecord.objects.get(pk=3)
self.assertEquals(record.old_url, u'/the/old/one/')
self.assertEquals(record.new_url, u'/the/new/one/')
self.assertEquals(record.deleted, False)
def test_track_deleted_url_without_existing_records(self):
instance = self.tracked_model
instance._old_url = '/the/old/one/'
url_tracker.track_deleted_url(instance)
self.assertEquals(URLChangeRecord.objects.count(), 1)
record = URLChangeRecord.objects.all()[0]
self.assertEquals(record.new_url, None)
self.assertEquals(record.old_url, '/the/old/one/')
self.assertEquals(record.deleted, True)
def test_track_changed_url_deleting_exsiting_record_with_new_url(self):
URLChangeRecord.objects.create(old_url='/the/new/one/', new_url='/the/')
instance = self.tracked_model
instance._old_url = '/the/old/one/'
url_tracker.track_changed_url(instance)
self.assertEquals(URLChangeRecord.objects.count(), 1)
record = URLChangeRecord.objects.get(pk=1)
self.assertEquals(record.old_url, u'/the/old/one/')
self.assertEquals(record.new_url, u'/the/new/one/')
self.assertEquals(record.deleted, False)
class TestUrlChanges(TestCase):
def test_invalid_url(self):
response = self.client.get('/work/an-invalid-project/')
self.assertEquals(response.status_code, 404)
def test_changed_url(self):
url_change = URLChangeRecord.objects.create(
old_url='/the/old-url/',
new_url='/the/new/url/',
)
response = self.client.get('/the/old-url/')
self.assertEquals(response.status_code, 301)
self.assertEquals(response['location'], 'http://testserver/the/new/url/')
def test_deleted_url(self):
url_change = URLChangeRecord.objects.create(
old_url='/the/old-url/',
new_url='',
deleted=True
)
response = self.client.get('/the/old-url/')
self.assertEquals(response.status_code, 410)
| true |
93411f1b3164245c69b9ddb06d7bebf8fd0f865a | Python | ashokmurthy13/python-projects | /generators_demo/generators.py | UTF-8 | 620 | 4.09375 | 4 | [] | no_license | def week():
weeks = ["Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday"]
for day in weeks:
try:
yield day
except:
StopIteration
days = week()
print(next(days))
print(next(days))
print(next(days))
print(next(days))
print(next(days))
print(next(days))
print(next(days))
print(next(days))
def yes_or_no():
start = "yes"
while True:
yield start
start = "no" if start == "yes" else "yes"
gen = yes_or_no()
print(next(gen)) # 'yes'
print(next(gen)) # 'no'
print(next(gen)) # 'yes'
print(next(gen)) # 'no'
| true |
051a87ebb06e47309b90447c5c1f1b24db2a29a8 | Python | Budapest-Quantum-Computing-Group/piquasso | /tests/backends/fock/general/test_state.py | UTF-8 | 3,858 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | #
# Copyright 2021-2023 Budapest Quantum Computing Group
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import piquasso as pq
def test_FockState_reduced():
with pq.Program() as program:
pq.Q() | pq.DensityMatrix(ket=(0, 1), bra=(0, 1)) / 4
pq.Q() | pq.DensityMatrix(ket=(0, 2), bra=(0, 2)) / 4
pq.Q() | pq.DensityMatrix(ket=(2, 0), bra=(2, 0)) / 2
pq.Q() | pq.DensityMatrix(ket=(0, 2), bra=(2, 0)) * np.sqrt(1 / 8)
pq.Q() | pq.DensityMatrix(ket=(2, 0), bra=(0, 2)) * np.sqrt(1 / 8)
simulator = pq.FockSimulator(d=2)
state = simulator.execute(program).state
with pq.Program() as reduced_program:
pq.Q() | pq.DensityMatrix(ket=(1,), bra=(1,)) / 4
pq.Q() | pq.DensityMatrix(ket=(2,), bra=(2,)) / 4
pq.Q() | pq.DensityMatrix(ket=(0,), bra=(0,)) / 2
reduced_program_simulator = pq.FockSimulator(d=1)
reduced_program_state = reduced_program_simulator.execute(reduced_program).state
expected_reduced_state = reduced_program_state
reduced_state = state.reduced(modes=(1,))
assert expected_reduced_state == reduced_state
def test_FockState_fock_probabilities_map():
with pq.Program() as program:
pq.Q() | pq.DensityMatrix(ket=(0, 1), bra=(0, 1)) / 4
pq.Q() | pq.DensityMatrix(ket=(0, 2), bra=(0, 2)) / 4
pq.Q() | pq.DensityMatrix(ket=(2, 0), bra=(2, 0)) / 2
pq.Q() | pq.DensityMatrix(ket=(0, 2), bra=(2, 0)) * np.sqrt(1 / 8)
pq.Q() | pq.DensityMatrix(ket=(2, 0), bra=(0, 2)) * np.sqrt(1 / 8)
simulator = pq.FockSimulator(d=2)
state = simulator.execute(program).state
expected_fock_probabilities = {
(0, 0): 0.0,
(0, 1): 0.25,
(1, 0): 0.0,
(0, 2): 0.25,
(1, 1): 0.0,
(2, 0): 0.5,
(0, 3): 0.0,
(1, 2): 0.0,
(2, 1): 0.0,
(3, 0): 0.0,
}
actual_fock_probabilities = state.fock_probabilities_map
for occupation_number, expected_probability in expected_fock_probabilities.items():
assert np.isclose(
actual_fock_probabilities[occupation_number],
expected_probability,
)
def test_FockState_quadratures_mean_variance():
with pq.Program() as program:
pq.Q() | pq.Vacuum()
pq.Q(0) | pq.Displacement(r=0.2, phi=0)
pq.Q(1) | pq.Squeezing(r=0.1, phi=1.0)
pq.Q(2) | pq.Displacement(r=0.2, phi=np.pi / 2)
simulator = pq.FockSimulator(d=3, config=pq.Config(cutoff=8, hbar=2))
result = simulator.execute(program)
mean_on_0th, variance_on_0th = result.state.quadratures_mean_variance(modes=(0,))
mean_on_1st, variance_on_1st = result.state.quadratures_mean_variance(modes=(1,))
mean_on_2nd, variance_on_2nd = result.state.quadratures_mean_variance(
modes=(0,), phi=np.pi / 2
)
mean_on_3rd, variance_on_3rd = result.state.quadratures_mean_variance(
modes=(2,), phi=np.pi / 2
)
assert np.isclose(mean_on_0th, 0.4, rtol=1e-5)
assert mean_on_1st == 0.0
assert np.isclose(mean_on_2nd, 0.0)
assert np.isclose(mean_on_3rd, 0.4, rtol=1e-5)
assert np.isclose(variance_on_0th, 1.0, rtol=1e-5)
assert np.isclose(variance_on_1st, 0.9112844, rtol=1e-5)
assert np.isclose(variance_on_2nd, 1, rtol=1e-5)
assert np.isclose(variance_on_3rd, 1, rtol=1e-5)
| true |
525188d97178c755c9d06bfe4e88eb96a9473481 | Python | stuart727/edx | /edx600x/L06_Objects/L6_3_concatenation.py | UTF-8 | 1,683 | 3.109375 | 3 | [] | no_license | L1 = [1,2,3]
L2 = ['a','b','c']
#alliasing
allias_L1_L2 = [L1, L2] #does *not create a new list* BUt it makes a *new empty list that points* in the existing L1 and L2; if L1 changes, then allias changes as well
allias_L1 = L1 # does *not create a new list* BUT an *empty list that points* in to existing L1 list
allias3 = [['k','l','m'],['a','b','c']]
print 'allias_L1_L2 = [L1, L2] ',allias_L1_L2
print 'allias_L1 = L1 ',allias_L1
print 'allias3 ',allias3
#flattening mesw concatenate (+)
flat = L1 + L2 #creates *new independent list* *without pointers* to previous L1, L2
print 'flat = L1 + L2 ', flat
#cloning
clon = L1[:] #creates a total *new list* *without pointers*
print 'clon =L1[:] ',clon
print '====================[ MUTATION ]====================='
z = allias3[0]
print 'z = allias3[0] ',z
L1.append(666)
print 'L1.append(666)'
allias_L1.append(777)
print 'allias_L1.append(777)'
allias_L1_L2[1][-1] = 'zzzz'
print 'allias_L1_L2[1][-1] = zzzz'
allias3[0].append(888)
print 'allias3[0].append(888)'
print '======================================================'
print 'L1 after mutation (appending) ',L1
print '======================================================'
print 'allias_L1_L2 after appending to L1 ',allias_L1_L2
print 'allias_L1 after appending to allias_L1 ',allias_L1
print 'allias3 after appending to allia3 ',allias3
print 'flat after appending to L1 ',flat
print 'clon after appending 6 to L1 ',clon
print 'z after appending on allias3 ',z
| true |
86982b92b808ea57127e2dbac680f144057035e8 | Python | GCES-Pydemic/pydemic | /tests/test_mixins.py | UTF-8 | 2,010 | 2.890625 | 3 | [
"MIT"
] | permissive | from pandas.testing import assert_series_equal, assert_frame_equal
from pytest import approx
import mundi
from pydemic.models import SIR
from pydemic.utils import flatten_dict
class TestInfoMixin:
def test_model_to_json(self):
m = SIR()
def _test_regional_model_to_json(self):
m = SIR(region="BR")
br = mundi.region("BR")
assert m.info.to_dict() == {
"demography.population": br.population,
"demography.age_distribution": br.age_distribution,
"demography.age_pyramid": br.age_pyramid,
}
assert m.info.to_dict(flat=True) == flatten_dict(m.info.to_dict())
class TestRegionMixin:
def test_initialization_options(self):
br = mundi.region("BR")
it = mundi.region("IT")
# Initialize with no region
m = SIR()
assert m.population == 1_000_000
assert m.region is None
assert m.age_distribution is None
assert m.age_pyramid is None
# Use a region
m = SIR(region="BR")
assert m.population == br.population
assert_series_equal(m.age_distribution, br.age_distribution, check_names=False)
assert_frame_equal(m.age_pyramid, br.age_pyramid)
# Mix parameters a region
tol = 1e-6
m = SIR(region="BR", population=1000)
assert m.population == 1000
assert abs(m.age_distribution.sum() - 1000) < tol
assert abs(m.age_pyramid.sum().sum() - 1000) < tol
ratio = br.age_distribution / m.age_distribution
assert ((ratio - br.population / 1000).dropna().abs() < tol).all()
# Mixed values: brazilian population with the age_distribution proportions
# from Italy
m = SIR(region="BR", age_distribution="IT")
assert m.population == br.population
assert m.age_distribution.sum() == approx(br.population)
assert list(m.age_distribution / m.population) == approx(
it.age_distribution / it.population
)
| true |
d0c5bda256cdddd8bf448502a50929158b559ee7 | Python | crja73/port_scanner | /portttt.py | UTF-8 | 2,275 | 3.765625 | 4 | [] | no_license | import socket
def ports():
try:
a = input('Введите ip адресс, или домен->')
b = input('До какого порта сканировать->')
print('Это займет примерно {} секунд'.format(0.004 * int(b)))
spis = []
for i in range(1, int(b)):
s = socket.socket()
s.settimeout(0)
ip = a
response = s.connect_ex((ip, i))
if response:
print ('порт {} закрыт'.format(i))
else:
print ('порт {} открыт'.format(i))
spis.append(i)
s.close()
print('Все открытые порты: {}'.format(spis))
except:
print('Вы ввели некоректные данные')
def one():
try:
a = input('Введите ip адресс, или домен->')
b = input('Какой порт сканировать->')
s = socket.socket()
s.settimeout(0)
ip = a
response = s.connect_ex((ip, int(b)))
except:
print('Вы ввели некоректные данные')
def all():
try:
spis = []
a = input('Введите ip адресс, или домен->')
for i in range(1, 65535):
s = socket.socket()
s.settimeout(0)
ip = a
response = s.connect_ex((ip, i))
if response:
print ('порт {} закрыт'.format(i))
else:
print ('порт {} открыт'.format(i))
spis.append(i)
s.close()
print('Все открытые порты: {}'.format(spis))
except:
print('Вы ввели некоректные данные')
def main():
print("Если вы хотите просканировать до определенного порта, введите цифру 1, если вы хотите просканировать отдельно один порт, введите цифру 2, если вы хотите просканировать все 65535 портов, введите цифру 3, введите 4, если хотите прекратить работу программы")
new = input()
if new == '1':
ports()
elif new == '2':
one()
elif new == '3':
all()
else:
print('Выберите: 1 / 2 / 3')
main() | true |
42819c6536223cda3987b3d4cc974a15d69816a6 | Python | SvetlanaSumets11/nix_project | /services/web/project/operation_film/sorting.py | UTF-8 | 1,045 | 2.96875 | 3 | [] | no_license | """
Module for sorting films by rating and release date
"""
import logging
from sqlalchemy import desc
from flask_restx import Resource
from ..models.films import Film
from . import valid_return
def film_sort(arg: str) -> list:
"""
Function for sorting films by rating and release date
:param arg: sort argument - rating or date
:return: all relevant objects of the class Film
"""
sorting = {'rating': Film.query.order_by(desc(Film.rating)).all(),
"date": Film.query.order_by(desc(Film.release_date)).all()}
return sorting.get(arg)
class Sort(Resource):
"""Class for sorting films by rating and release date"""
@classmethod
def get(cls, arg_sort: str) -> dict:
"""
Get method
:param arg_sort: sort argument - rating or date
:return: all relevant objects of the class Film in JSON format
"""
films = film_sort(arg_sort)
logging.info("Sorted list of movies by %s", arg_sort)
return valid_return(films, arg_sort, 'sort/')
| true |
8df1ac36cee37b483c1ccb6e3fc8f111971ec180 | Python | kflmiami420/Aqua-Pi | /Data-Collection/logger_aws.py | UTF-8 | 1,806 | 3.375 | 3 | [] | no_license | import psycopg2 as pg
class Logger:
def __init__(self, user, password, host='aquapi.c5uh7gzya75b.us-east-2.rds.amazonaws.com'):
'''
A data logger that connects and insert data into an AWS PostgreSQL server
Parameters
----------
user : `string`
The user name to access the database
password : `string`
The password to access the database
host : 'string' (optional)
The connection path where the datbase resides. The default is the 'aquapi' database on the AWS server
'''
self.user = user
self.password = password
self.host = host
def log_data(self, data):
'''
Insert data into PostgreSQL database
Parameters
----------
data : `dict`
The data that you want to insert into the database; where the pattern is {table:table_data}
Returns
----------
`boolean`
Indicates if the data connection and insert was successful
'''
try:
conn = pg.connect(user=self.user, password=self.password, host=self.host)
except:
print("!CONNECTION ERROR! Invalid credentials OR no connection available!")
return False
cursor = conn.cursor()
for table, values in data.items():
# calc the number of params to insert
cnt = len(values[0])
params = "%s" + ",%s"*(cnt-1)
cursor.executemany("INSERT INTO {0} VALUES({1})".format(table, params), values)
conn.commit()
conn.close()
print("\n!ALERT! Data uploaded into SQL database")
return True | true |
effe52fabe4fe853f4a664895554b46b91a158d7 | Python | open-goal/jak-project | /scripts/gsrc/lint-gsrc-file.py | UTF-8 | 5,294 | 2.703125 | 3 | [
"ISC"
] | permissive | import re
import argparse
from utils import get_gsrc_path_from_filename
from colorama import just_fix_windows_console, Fore, Back, Style
just_fix_windows_console()
parser = argparse.ArgumentParser("lint-gsrc-file")
parser.add_argument("--game", help="The name of the game", type=str)
parser.add_argument("--file", help="The name of the file", type=str)
args = parser.parse_args()
class LintMatch:
def __init__(self, src_path, offending_lineno, context):
self.src_path = src_path
self.offending_lineno = offending_lineno
self.context = context
def __str__(self):
output = (
Style.BRIGHT
+ Fore.MAGENTA
+ "@ {}:{}\n".format(self.src_path, self.offending_lineno)
+ Fore.RESET
+ Style.RESET_ALL
)
for line in self.context:
# skip lines that are just brackets
if line.strip() == ")" or line.strip() == "(":
continue
output += "\t{}\n".format(line)
return output
class LinterRule:
def __init__(self, level, rule_name, regex_pattern, context_size):
self.level = level
self.rule_name = rule_name
self.regex_pattern = regex_pattern
self.context_size = context_size
self.matches = []
def __str__(self):
level_color = Fore.LIGHTBLUE_EX
if self.level == "WARN":
level_color = Fore.YELLOW
elif self.level == "ERROR":
level_color = Fore.RED
return (
level_color
+ "[{}]{} - {} - {}/{}/g".format(
self.level,
Fore.RESET,
level_color + self.rule_name + Fore.RESET,
Fore.CYAN,
self.regex_pattern.pattern,
)
+ Fore.RESET
+ ":"
)
# Construct all rules
linter_rules = []
# Infos
# Warnings
linter_rules.append(
LinterRule("WARN", "method_splits", re.compile("method-of-(?:type|object)"), 3)
)
linter_rules.append(
LinterRule("WARN", "func_splits", re.compile("\(t9-\d+(?:\s+[^\s]+\s*)?\)"), 3)
)
linter_rules.append(
LinterRule("WARN", "missing_arg", re.compile("local-vars.*[at].*\s+none\)"), 1)
)
# Errors
linter_rules.append(LinterRule("ERROR", "missing_res_tag", re.compile(".pcpyud"), 1))
linter_rules.append(LinterRule("ERROR", "decomp_error", re.compile(";; ERROR"), 1))
linter_rules.append(
LinterRule(
"ERROR", "casting_stack_var", re.compile("the-as\s+[^\s]*\s+.*\(new 'stack"), 2
)
)
src_path = get_gsrc_path_from_filename(args.game, args.file)
# Iterate through the file line by line, check against each rule
# if the rule is violated (it matches) then we append the match with useful details
print("Linting GOAL_SRC File...")
def get_context(lines, match_span, idx, amount_inclusive):
lines_grabbed = []
# Strip left pad, while maintaining indent
last_line_indent_width = -1
last_line_indent = -1
while len(lines_grabbed) < amount_inclusive and len(lines) > idx + len(
lines_grabbed
):
# TODO - first line, colorize the match
# if len(lines_grabbed) == 0:
# line = lines[idx + len(lines_grabbed)]
# line = line[:match_span[0]] + Back.RED + line[:match_span[1]] + Back.RESET + line[match_span[1]:]
# line = line.rstrip()
line = lines[idx + len(lines_grabbed)].rstrip()
indent_width = len(line) - len(line.lstrip())
if last_line_indent_width == -1:
lines_grabbed.append(line.lstrip())
elif last_line_indent == -1:
# calculate the difference
indent_diff = indent_width - last_line_indent_width
last_line_indent = indent_diff
stripped_line = line.lstrip()
lines_grabbed.append(stripped_line.rjust(indent_diff + len(stripped_line)))
else:
stripped_line = line.lstrip()
lines_grabbed.append(
stripped_line.rjust(last_line_indent + len(stripped_line))
)
last_line_indent_width = indent_width
return lines_grabbed
with open(src_path) as f:
src_lines = f.readlines()
for lineno, line in enumerate(src_lines):
adjusted_lineno = lineno + 1
for rule in linter_rules:
match = rule.regex_pattern.search(line)
if match:
rule.matches.append(
LintMatch(
src_path,
adjusted_lineno,
get_context(src_lines, match.span(), lineno, rule.context_size),
)
)
# Iterate through all our linter rules, printing nicely in groups with the
# context surrounding the match
#
# If we find any violations at warning or above, we will ultimately return exit(1)
throw_error = False
for rule in linter_rules:
# Iterate through violations
if len(rule.matches) > 0:
print(rule)
for match in rule.matches:
if rule.level == "ERROR" or rule.level == "WARN":
throw_error = True
print(match)
if throw_error:
print(Fore.RED + "Found potential problems, exiting with code 1!" + Fore.RESET)
exit(1)
else:
print(Fore.GREEN + "Looks good!" + Fore.RESET)
| true |