hexsha
stringlengths
40
40
size
int64
7
1.04M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
247
max_stars_repo_name
stringlengths
4
125
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
247
max_issues_repo_name
stringlengths
4
125
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
116k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
247
max_forks_repo_name
stringlengths
4
125
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
1
1.04M
avg_line_length
float64
1.77
618k
max_line_length
int64
1
1.02M
alphanum_fraction
float64
0
1
original_content
stringlengths
7
1.04M
filtered:remove_function_no_docstring
int64
-102
942k
filtered:remove_class_no_docstring
int64
-354
977k
filtered:remove_delete_markers
int64
0
60.1k
40a67136f82d364baf7c724c7f9a11325add874b
934
py
Python
utils.py
PervasiveWellbeingTech/Popbots-Emailing
76a36ee0f92d9852718615c3fc6967e95e1648b4
[ "MIT" ]
null
null
null
utils.py
PervasiveWellbeingTech/Popbots-Emailing
76a36ee0f92d9852718615c3fc6967e95e1648b4
[ "MIT" ]
null
null
null
utils.py
PervasiveWellbeingTech/Popbots-Emailing
76a36ee0f92d9852718615c3fc6967e95e1648b4
[ "MIT" ]
null
null
null
import logging import pickle
26.685714
79
0.736617
import logging import pickle def return_logger(): logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s %(levelname)-4s %(message)s') file_handler = logging.FileHandler('logs/global.log') file_handler.setLevel(logging.ERROR) file_handler.setFormatter(formatter) stream_handler = logging.StreamHandler() stream_handler_formatter = logging.Formatter('[%(levelname)s] %(message)s') stream_handler.setFormatter(stream_handler_formatter) stream_handler.setLevel(logging.DEBUG) logger.addHandler(stream_handler) logger.addHandler(file_handler) return logger def save_object(obj, filename): with open(filename, 'wb') as output: # Overwrites any existing file. pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL) def read_object(filename): with open(filename, 'rb') as input: return pickle.load(input)
834
0
69
121b7486c1fc81dfdf747a1fac6907fdbb9a85f0
715
py
Python
tests_appengine/test_client.py
LeadPages/firechannel
19b5822005f7ef6bb842a183c807a8a9919433e6
[ "MIT" ]
4
2017-10-10T10:49:14.000Z
2022-01-31T18:33:29.000Z
tests_appengine/test_client.py
LeadPages/firechannel
19b5822005f7ef6bb842a183c807a8a9919433e6
[ "MIT" ]
4
2017-11-23T16:35:41.000Z
2021-02-02T21:13:59.000Z
tests_appengine/test_client.py
LeadPages/firechannel
19b5822005f7ef6bb842a183c807a8a9919433e6
[ "MIT" ]
null
null
null
from firechannel import get_client
25.535714
58
0.725874
from firechannel import get_client def test_can_get_default_client(): # Given that I've got a testbed # If I try to get a client # I expect an instance to get created automatically assert get_client() def test_can_build_access_tokens(): # Given that I've got a testbed and a client client = get_client() # That client must be able to generate an access token assert client.access_token def test_can_refresh_access_tokens(): # Given that I've got a testbed and a client client = get_client() # If I remove the auth token from Credentials client.credentials.token = None # I expect the underlying credentials to be refreshed assert client.access_token
608
0
69
303abc13f11516937c5e97b58908cee03171eb99
220
py
Python
apps/files/apps.py
deniskrumko/deniskrumko
613c0c3eac953d2e8482a2e66fce7d3570770b2c
[ "MIT" ]
2
2019-07-09T01:42:04.000Z
2020-04-09T16:44:59.000Z
apps/files/apps.py
deniskrumko/deniskrumko
613c0c3eac953d2e8482a2e66fce7d3570770b2c
[ "MIT" ]
5
2019-12-30T22:16:38.000Z
2020-09-11T18:13:14.000Z
apps/files/apps.py
deniskrumko/deniskrumko
613c0c3eac953d2e8482a2e66fce7d3570770b2c
[ "MIT" ]
1
2019-07-09T01:42:07.000Z
2019-07-09T01:42:07.000Z
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class FilesConfig(AppConfig): """Configuration for ``Files`` app.""" name = 'apps.files' verbose_name = _('Files')
22
55
0.713636
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class FilesConfig(AppConfig): """Configuration for ``Files`` app.""" name = 'apps.files' verbose_name = _('Files')
0
0
0
1573d502e1f5d26892f590673950419a11805db3
10,388
py
Python
live.py
fabiobhl/project-triton
3ac3c1bad26014ebdc0141fd3a7afe60aa9c70f9
[ "MIT" ]
null
null
null
live.py
fabiobhl/project-triton
3ac3c1bad26014ebdc0141fd3a7afe60aa9c70f9
[ "MIT" ]
null
null
null
live.py
fabiobhl/project-triton
3ac3c1bad26014ebdc0141fd3a7afe60aa9c70f9
[ "MIT" ]
null
null
null
#standard libraries import time from datetime import datetime import csv import os import json from concurrent import futures import threading import multiprocessing import math #external libraries import numpy as np import pandas as pd from discord import Webhook, RequestsWebhookAdapter from binance.client import Client from binance.enums import * from matplotlib import pyplot as plt #dash imports import dash import dash_html_components as html import dash_core_components as dcc from dash.dependencies import Input, Output import plotly.express as px import plotly.graph_objects as go #file imports from database import LiveDataBase from actor import NNActor from utils import read_json, read_config, timer if __name__ == "__main__": from pretrain import Network #load in the actor Actor = NNActor(neural_network=Network, load_path="./experiments/testeth2/Run1", epoch=0) bot = Bot(symbol="ETHUSDT", run_path="./experiments/testeth2/Run1", actor=Actor) bot.run()
31.865031
161
0.602137
#standard libraries import time from datetime import datetime import csv import os import json from concurrent import futures import threading import multiprocessing import math #external libraries import numpy as np import pandas as pd from discord import Webhook, RequestsWebhookAdapter from binance.client import Client from binance.enums import * from matplotlib import pyplot as plt #dash imports import dash import dash_html_components as html import dash_core_components as dcc from dash.dependencies import Input, Output import plotly.express as px import plotly.graph_objects as go #file imports from database import LiveDataBase from actor import NNActor from utils import read_json, read_config, timer class Gui(): def __init__(self, hook): #data setup self.hook = hook #app setup self.app = dash.Dash(__name__) title = html.Div(id="title", children=[html.H1(f"Trading {self.hook.ldb.symbol}, on the {self.hook.ldb.market_endpoint} market")]) profit = html.Div(id="profit") live_graph = html.Div(id="live-graph-wrapper") interval = dcc.Interval(id='interval', interval=1*1000, n_intervals=0) self.app.layout = html.Div(children=[title, profit, live_graph, interval]) @self.app.callback(Output('live-graph-wrapper', 'children'), Input('interval', 'n_intervals')) def update_live_graph(n): #get the data data = self.hook.actionlog.get_data_frame(self.hook.ldb.data.iloc[:-1,:]) #create the figure fig = go.Figure() fig.add_trace(go.Scatter(x=data["close_time"], y=data["close"], mode="lines", name="close price", line=dict(color="black"))) fig.add_trace(go.Scatter(x=data["close_time"], y=data["hold"], mode="markers", name="hold", line=dict(color="gray"))) fig.add_trace(go.Scatter(x=data["close_time"], y=data["buy"], mode="markers", name="buy", line=dict(color="green"))) fig.add_trace(go.Scatter(x=data["close_time"], y=data["sell"], mode="markers", name="sell", line=dict(color="red"))) return dcc.Graph(id="live-graph", figure=fig) @self.app.callback(Output('profit', 'children'), Input('interval', 'n_intervals')) def update_profit(n): #get the specific profit specific_profit = self.hook.broker.specific_profit return html.H2(f"Specific Profit since start: {specific_profit}") def run(self): self.app.run_server(host="0.0.0.0", debug=False, dev_tools_silence_routes_logging=True) class ActionLog(): def __init__(self, size=200): self.size = size #action memory self.action = [np.nan]*self.size #actual price memory self.actual_price = [np.nan]*self.size def append(self, action, actual_price): #save the action if action is None: self.action.append(np.nan) elif action == 0 or action == 1 or action == 2: self.action.append(action) else: raise Exception(f"Your chosen action {action} is not valid!") #save the actual price if actual_price is None: self.actual_price.append(np.nan) else: self.actual_price.append(actual_price) #cut the first elements off self.action.pop(0) self.actual_price.pop(0) def get_data_frame(self, df): data = df[["close_time", "close"]].copy() #set the length length = data.shape[0] if length > self.size: length = self.size #shorten the data data = data.iloc[-length:,:] #add the actions data["action"] = np.array(self.action[-length:]) #add the action prices data["hold"] = np.nan data.loc[data["action"] == 0, "hold"] = data.loc[data["action"] == 0, "close"] data["buy"] = np.nan data.loc[data["action"] == 1, "buy"] = data.loc[data["action"] == 1, "close"] data["sell"] = np.nan data.loc[data["action"] == 2, "sell"] = data.loc[data["action"] == 2, "close"] #add the actual prices data["actual_price"] = np.array(self.actual_price[-length:]) #reset the index data.reset_index(inplace=True, drop=True) return data class Broker(): def __init__(self, symbol, testing=True, config_path=None): #save/create neccessary variables self.symbol = symbol self.testing = testing self.profit = 0 self.specific_profit = 0 self.mode = "buy" #load in the config self.config = read_config(path=config_path) #create the client self.client = Client(api_key=self.config["binance"]["key"], api_secret=self.config["binance"]["secret"]) """ Testnet: self.client = Client(api_key=self.config["binance"]["key_testnet"], api_secret=self.config["binance"]["secret_testnet"]) self.client.API_URL = "https://testnet.binance.vision/api" order = self.client.create_order(symbol="ETHUSDT", side=SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=2) print(order) print(self.client.get_asset_balance(asset="ETH")) print(self.client.get_asset_balance(asset="USDT")) """ def _get_current_price(self): market_endpoint = self.config["binance"]["market_endpoint"] if market_endpoint == "spot": price_dict = self.client.get_symbol_ticker(symbol=self.symbol) price = price_dict["price"] elif market_endpoint == "futures": price_dict = self.client.futures_symbol_ticker(symbol=self.symbol) price = price_dict["price"] else: raise Exception(f"Your chosen market endpoint: {market_endpoint} is not available, change in config.json") print(price) return float(price) def buy(self, amount): if self.testing: return self._test_buy(amount=amount) raise Exception("Real buying has not been implemented yet") return def _test_buy(self, amount): if self.mode == "buy": #get the current price price = self._get_current_price() #set as buyprice self.buy_price = price self.mode = "sell" else: return def sell(self): if self.testing: return self._test_sell() raise Exception("Real selling has not been implemented yet") def _test_sell(self): if self.mode == "sell": #get the current price price = self._get_current_price() #calculate profit specific_profit = price/self.buy_price * (1-0.00075)**2 - 1 #add to specific profit count self.specific_profit += specific_profit self.mode = "buy" else: return def trade(self, action, amount): if action == 0: return elif action == 1: self.buy(amount=amount) elif action == 2: self.sell() else: raise Exception(f"Your chosen action: {action} is not valid") class Bot(): def __init__(self, symbol, run_path, actor, config_path=None): #save the variables self.symbol = symbol self.run_path = run_path self.info_path = self.run_path + "/info.json" self.config_path = config_path #config dictionary self.config = read_config(path=config_path) #info dictionary self.info = read_json(path=self.info_path) #setup the ldb self.ldb = LiveDataBase(symbol=self.symbol, run_path=self.run_path, config_path=self.config_path) #save the actor self.actor = actor #setup the actionlog self.actionlog = ActionLog(size=100) #setup the broker self.broker = Broker(symbol=self.symbol, testing=True) #setup the gui self.gui = Gui(hook=self) def update(self): start = time.time() #setup discord webhooks webhook = Webhook.partial(self.config["discord"]["webhook_id"], self.config["discord"]["webhook_token"], adapter=RequestsWebhookAdapter()) prec_webhook = Webhook.partial(self.config["discord"]["prec_webhook_id"], self.config["discord"]["prec_webhook_token"], adapter=RequestsWebhookAdapter()) #update our ldb try: self.ldb.update_data() except Exception as e: print("Unsuccesfull ldb update resetting and conducting no action!") print("Exception: ", e) #reset our database self.ldb = LiveDataBase(symbol=self.symbol, run_path=self.run_path, config_path=self.config_path) #save no action self.actionlog.append(action=None, actual_price=None) #end the update method return #get the new state state = self.ldb.get_state() #get the action for that new state action = self.actor.get_action(state) #do something with this action self.broker.trade(action=action, amount=1000) #save the action self.actionlog.append(action=action, actual_price=100) #calculate update duration duration = time.time()-start print(f"Update took {round(duration,2)} seconds") def run(self): #startup the gui gui_thread = threading.Thread(target=self.gui.run) gui_thread.start() #main loop while True: #wait for time to get to candlestick_interval timer(candlestick_interval=self.info["candlestick_interval"]) #wait a little time time.sleep(2) #update the coins self.update() gui_thread.join() if __name__ == "__main__": from pretrain import Network #load in the actor Actor = NNActor(neural_network=Network, load_path="./experiments/testeth2/Run1", epoch=0) bot = Bot(symbol="ETHUSDT", run_path="./experiments/testeth2/Run1", actor=Actor) bot.run()
8,919
-27
501
bbabccfb5306ecb8d981c84146bd40727b4c9c11
52,514
py
Python
summary/summaryanalyze_old.py
PranavSudersan/Buggee
5767d1c259d3570086d7c389440605fa0f681336
[ "MIT" ]
1
2020-12-18T13:05:41.000Z
2020-12-18T13:05:41.000Z
summary/summaryanalyze_old.py
PranavSudersan/Buggee
5767d1c259d3570086d7c389440605fa0f681336
[ "MIT" ]
null
null
null
summary/summaryanalyze_old.py
PranavSudersan/Buggee
5767d1c259d3570086d7c389440605fa0f681336
[ "MIT" ]
null
null
null
import matplotlib.pyplot as plt import time from datetime import datetime import os import os.path from tkinter import filedialog import tkinter as tk import ast import openpyxl import pandas as pd from pandas.io.json import json_normalize import numpy as np # import random ## #create combined "All" data by taking sum/mean/max among various roi #### if len(self.roi_label_unique) > 1: #ROI names MUST NOT have "All" ot "Dict"! ## columns_all = [a + "_All" for a in header_split] ## self.df_forcedata = pd.concat([self.df_forcedata, ## pd.DataFrame(columns=columns_all)], sort=False) ## self.df_forcedata[columns_all] = self.df_forcedata[columns_all].fillna(0) ## ## for a in self.roi_label_unique: ## if a == 'All': ## print("Change ROI name 'All'") ## break ## for i in range(len(columns_all)): ## if header_split[i] in header_split_add: ## self.df_forcedata[columns_all[i]] += self.df_forcedata[header_split[i] + ## "_" + a].fillna(0) ## elif header_split[i] in header_split_max: ## clist1 = [header_split[i] + "_" + b for b in self.roi_label_unique] ## self.df_forcedata[columns_all[i]] = self.df_forcedata[clist1].max(axis=1) ## elif header_split[i] in header_split_avg: ## clist2 = [header_split[i] + "_" + b for b in self.roi_label_unique] ## self.df_forcedata[columns_all[i]] = self.df_forcedata[clist2].mean(axis=1) ## ## self.roi_label_unique.update(["All"]) ## self.df_final.to_excel('E:/Work/Data/Summary/20200213/Sex/summary_temp_' + ## str(random.randint(1, 90000)) + '.xlsx') #export as excel ## self.df_final = self.df_all.copy() ## self.df_all.to_excel("E:/Work/Codes/Test codes/test5.xlsx") #export as excel # if legend_parameter == "ROI Label": #no filtering as this is already plotted in prepareplot (when leg = None) # self.plotSummary(summaryDict, df_good, df_good) # else: # ## legend_parameter = 'Folder_Name' #choose, same as column names # legend_list = df_good[legend_parameter].unique() # legend_list.sort() # print(legend_list) # markerlist = ["o", "v", "P", "^", "D", "X", "<", ">", "*", "s", # "+", "d", "1", "x", "2", "h"] # figlist = None # i = 0 # ## df_leg = pd.DataFrame(dict(zip([legend_parameter], [legend_list]))) # for lg in legend_list: # print("zxz", lg) # i = 0 if i > 15 else i # df_filtered = df_good[df_good[legend_parameter] == lg] # self.plotSummary(summaryDict, # df_filtered, df_good, legend_parameter, markerlist[i], # figlist, lg) # figlist = self.figdict.copy() # ## df_all_joined = self.df_all.copy() # ## df_all_joined.insert(0, legend_parameter, lg) # ## if i == 0: # ## df_final = df_all_joined.copy() # ## else: # ## df_final = df_final.append(df_all_joined, ignore_index=True, sort=False) # ## print("iter", i) # i += 1 # ## self.df_final = df_final.copy() ##a.combineSummary("Folder_Name") ##if a.list_filepath != "": ## a.showSummaryPlot() ##summary = SummaryAnal() ##summary.importSummary() ##summary.plotSummary(summary.speed_def_unique, ## summary.roi_label_unique, ## summary.df_forcedata, ## summary.df_forcedata) ##summary.showSummaryPlot()
55.336143
144
0.47296
import matplotlib.pyplot as plt import time from datetime import datetime import os import os.path from tkinter import filedialog import tkinter as tk import ast import openpyxl import pandas as pd from pandas.io.json import json_normalize import numpy as np # import random class SummaryAnal: def __init__(self): #initialize self.df_forcedata = None self.figdict = None ## self.eq_count = [1,1,1,1] #fitting equation counter for each subplot self.eq_count = {} self.eq_count["All"] = [1,1,1,1] self.summary_filepath = "" def importSummary(self, filepath = None): #plot summary plots print("import") ## self.eq_count = [1,1,1,1] self.eq_count = {} self.eq_count["All"] = [1,1,1,1] root = tk.Tk() root.withdraw() if filepath == None: self.summary_filepath = filedialog.askopenfilename( title = "Select summary data file") else: self.summary_filepath = filepath if self.summary_filepath != "": with open(self.summary_filepath, 'r', encoding = "utf_8") as f: #open summary data file x = f.read().splitlines() area_max = [[float(i) for i in ast.literal_eval(y.split('\t')[0])] for y in x[1:]] area_pulloff = [[float(i) for i in ast.literal_eval(y.split('\t')[1])] for y in x[1:]] force_adhesion = [[float(i) for i in ast.literal_eval(y.split('\t')[2])] for y in x[1:]] adh_preload = [[float(i) for i in ast.literal_eval(y.split('\t')[3])] for y in x[1:]] contact_time = [float(y.split('\t')[4]) for y in x[1:]] speed = [[float(i) for i in ast.literal_eval(y.split('\t')[5])] for y in x[1:]] steps = [ast.literal_eval(y.split('\t')[6]) for y in x[1:]] force_friction = [[float(i) for i in ast.literal_eval(y.split('\t')[7])] for y in x[1:]] area_friction = [[float(i) for i in ast.literal_eval(y.split('\t')[8])] for y in x[1:]] friction_preload = [[float(i) for i in ast.literal_eval(y.split('\t')[9])] for y in x[1:]] msrmnt_num = [float(y.split('\t')[10]) for y in x[1:]] msrmnt_ok = [y.split('\t')[11] for y in x[1:]] roi_label = [ast.literal_eval(y.split('\t')[12]) for y in x[1:]] speed_def = [(ast.literal_eval(y.split('\t')[13])) for y in x[1:]] #speed definitions error_vert = [float(y.split('\t')[14]) for y in x[1:]] error_lat = [float(y.split('\t')[15]) for y in x[1:]] slideStep = [y.split('\t')[16] for y in x[1:]] roiarea_max = [[float(i) for i in ast.literal_eval(y.split('\t')[17])] for y in x[1:]] roiarea_pulloff = [[float(i) for i in ast.literal_eval(y.split('\t')[18])] for y in x[1:]] length_max = [[float(i) for i in ast.literal_eval(y.split('\t')[19])] for y in x[1:]] length_pulloff = [[float(i) for i in ast.literal_eval(y.split('\t')[20])] for y in x[1:]] roilength_max = [[float(i) for i in ast.literal_eval(y.split('\t')[21])] for y in x[1:]] roilength_pulloff = [[float(i) for i in ast.literal_eval(y.split('\t')[22])] for y in x[1:]] ecc_pulloff = [[float(i) for i in ast.literal_eval(y.split('\t')[23])] for y in x[1:]] contnum_pulloff = [[float(i) for i in ast.literal_eval(y.split('\t')[24])] for y in x[1:]] area_residue = [[float(i) for i in ast.literal_eval(y.split('\t')[25])] for y in x[1:]] slope_header = x[0].split('\t')[26] #check if data exists slope = [float(y.split('\t')[26]) if slope_header[:5] == 'Slope' and y.split('\t')[26] != '' else None for y in x[1:]] self.slope_unit = slope_header.split('[')[1].split(']')[0] if slope_header[:5] == 'Slope' else None k_beam_header = x[0].split('\t')[27] #check if data exists k_beam = [float(y.split('\t')[27]) if k_beam_header[:4] == 'Beam' else None for y in x[1:]] error_k_beam = [float(y.split('\t')[28]) if k_beam_header[:4] == 'Beam' else None for y in x[1:]] deform_init = [float(y.split('\t')[29]) if k_beam_header[:4] == 'Beam' else None for y in x[1:]] deform_pulloff = [float(y.split('\t')[30]) if k_beam_header[:4] == 'Beam' else None for y in x[1:]] energy_adh = [float(y.split('\t')[31]) if k_beam_header[:4] == 'Beam' else None for y in x[1:]] bound_area = [[float(i) for i in ast.literal_eval(y.split('\t')[32])] \ if k_beam_header[:4] == 'Beam' else [None]*len(ast.literal_eval(y.split('\t')[12])) for y in x[1:]] bound_peri = [[float(i) for i in ast.literal_eval(y.split('\t')[33])] \ if k_beam_header[:4] == 'Beam' else [None]*len(ast.literal_eval(y.split('\t')[12])) for y in x[1:]] bound_len = [[float(i) for i in ast.literal_eval(y.split('\t')[34])] \ if k_beam_header[:4] == 'Beam' else [None]*len(ast.literal_eval(y.split('\t')[12])) for y in x[1:]] bound_wid = [[float(i) for i in ast.literal_eval(y.split('\t')[35])] \ if k_beam_header[:4] == 'Beam' else [None]*len(ast.literal_eval(y.split('\t')[12])) for y in x[1:]] area_unit = x[0].split('\t')[0][-5:-1] rownum = len(area_max) data_folderpath = os.path.dirname( os.path.dirname( os.path.dirname( self.summary_filepath))) #data to be split according to roi label header_split_max = ["Adhesion_Force", "Adhesion_Preload", "Friction_Force","Friction_Preload"] #take max in "All" (legacy) header_split_avg = ["Pulloff_Median_Eccentricity"] #take mean in "All" (legacy) header_split_add = ["Max_Area", "Pulloff_Area", "Friction_Area", "ROI_Max_Area", "ROI_Pulloff_Area", "Max_Length", "Pulloff_Length", "ROI_Max_Length", "ROI_Pulloff_Length", "Pulloff_Contact_Number", "Residue_Area", "Max_Bounding_Area", "Max_Bounding_Perimeter", "Max_Bounding_Length", "Max_Bounding_Width"] #take sum in "All" (legacy) header_split = header_split_max + header_split_avg + header_split_add data_split = [force_adhesion, adh_preload, force_friction, friction_preload, ecc_pulloff, area_max, area_pulloff, area_friction, roiarea_max, roiarea_pulloff, length_max, length_pulloff, roilength_max, roilength_pulloff, contnum_pulloff, area_residue, bound_area, bound_peri, bound_len, bound_wid] #data not to be split according to roi label header_nosplit = ["Measurement_Number", "Measurement_OK", "Contact_Time", "Steps","ROI_Labels", "Speed", "Speed_Definition", "Error_Vertical", "Error_Lateral", "Sliding_Step", "Area_Units", "Data_Folder", "Slope", "Beam_Spring_Constant","Error_Beam_Spring_Constant", "Initial_Deformation","Pulloff_Deformation","Adhesion_Energy"] data_nosplit = [msrmnt_num, msrmnt_ok, contact_time, steps, roi_label, speed, speed_def, error_vert,error_lat, slideStep, [area_unit] * rownum, [data_folderpath] * rownum, slope, k_beam, error_k_beam, deform_init, deform_pulloff, energy_adh] header_raw = header_nosplit + header_split data_raw = data_nosplit + data_split #define dictionaries for each step/roi and combine header_dict = [a + "_Dict" for a in header_split] data_dict = [] for j in range(len(header_split)): temp_dict = [dict(zip([header_split[j] + "_" + s for s in roi_label[i]], data_split[j][i])) for i in range(len(roi_label))] data_dict.append(temp_dict) header = header_raw + header_dict datalist = data_raw + data_dict datadict = dict(zip(header, datalist)) df_data = pd.DataFrame(datadict) #split steps into columns and combine df_speed_steps = json_normalize(df_data['Speed_Definition']) #split speed steps df_all_data = [df_data, df_speed_steps] for a in header_dict: df_temp = json_normalize(df_data[a]) df_all_data.append(df_temp) df_combined = pd.concat(df_all_data, join='outer', axis=1).fillna(np.nan) df_combined.drop(header_dict, inplace=True, axis=1) #drop dictionary columns df_good = df_combined[df_combined["Measurement_OK"] == "Y"] ## self.steps_unique = set([a for b in steps_modif for a in b]) roi_label_unique = set([a for b in df_good["ROI_Labels"] for a in b]) ## self.speed_def_unique = set([a for b in df_good["Speed_Definition"] for a in b.keys()]) #reshape and combine roi data into new dataframe header_nocomb = ["ROI Label", "Data_Folder", "Measurement_Number", "Measurement_OK", "Contact_Time", "Detachment Speed", "Attachment Speed", "Sliding Speed", "Sliding_Step", "Error_Vertical", "Error_Lateral", "Area_Units", "Slope", "Beam_Spring_Constant","Error_Beam_Spring_Constant", "Initial_Deformation","Pulloff_Deformation","Adhesion_Energy"] header_comb = ["Adhesion_Force", "Adhesion_Preload", "Friction_Force","Friction_Preload", "Max_Area", "Pulloff_Area", "Friction_Area", "ROI_Max_Area", "ROI_Pulloff_Area", "Max_Length", "Pulloff_Length", "ROI_Max_Length", "ROI_Pulloff_Length", "Pulloff_Contact_Number", "Residue_Area", "Pulloff_Median_Eccentricity", "Max_Bounding_Area", "Max_Bounding_Perimeter", "Max_Bounding_Length", "Max_Bounding_Width"] header_all = header_nocomb + header_comb self.df_forcedata = pd.DataFrame(columns = header_all) for b in roi_label_unique: data_nocomb = [b] + [df_good[x] \ for x in header_nocomb \ if x not in ["ROI Label"]] data_comb = [df_good[x + "_" + b] for x in header_comb] df_nocomb = pd.DataFrame(dict(zip(header_nocomb, data_nocomb))) df_comb = pd.DataFrame(dict(zip(header_comb, data_comb))) df_joined = df_comb.join(df_nocomb) self.df_forcedata = self.df_forcedata.append(df_joined, ignore_index=True, sort=False) self.df_forcedata['Adhesion_Force'].replace('', np.nan, inplace=True) self.df_forcedata.dropna(subset=['Adhesion_Force'], inplace=True) #remove blanks #calculate additional data self.df_forcedata['Adhesion_Stress'] = self.df_forcedata['Adhesion_Force']/self.df_forcedata['Pulloff_Area'] self.df_forcedata['Friction_Stress'] = self.df_forcedata['Friction_Force']/self.df_forcedata['Friction_Area'] self.df_forcedata['Normalized_Adhesion_Force'] = self.df_forcedata['Adhesion_Force']/self.df_forcedata['Max_Area'] self.df_forcedata['Normalized_Adhesion_Energy'] = self.df_forcedata['Adhesion_Energy']/self.df_forcedata['Max_Area'] self.df_forcedata['Date_of_Experiment'] = self.df_forcedata['Data_Folder'].str.split(pat = "/").str[-1].str.slice(start=0, stop=9) self.df_forcedata.reset_index(inplace = True, drop = True) self.df_final = self.df_forcedata.copy() ## #create combined "All" data by taking sum/mean/max among various roi #### if len(self.roi_label_unique) > 1: #ROI names MUST NOT have "All" ot "Dict"! ## columns_all = [a + "_All" for a in header_split] ## self.df_forcedata = pd.concat([self.df_forcedata, ## pd.DataFrame(columns=columns_all)], sort=False) ## self.df_forcedata[columns_all] = self.df_forcedata[columns_all].fillna(0) ## ## for a in self.roi_label_unique: ## if a == 'All': ## print("Change ROI name 'All'") ## break ## for i in range(len(columns_all)): ## if header_split[i] in header_split_add: ## self.df_forcedata[columns_all[i]] += self.df_forcedata[header_split[i] + ## "_" + a].fillna(0) ## elif header_split[i] in header_split_max: ## clist1 = [header_split[i] + "_" + b for b in self.roi_label_unique] ## self.df_forcedata[columns_all[i]] = self.df_forcedata[clist1].max(axis=1) ## elif header_split[i] in header_split_avg: ## clist2 = [header_split[i] + "_" + b for b in self.roi_label_unique] ## self.df_forcedata[columns_all[i]] = self.df_forcedata[clist2].mean(axis=1) ## ## self.roi_label_unique.update(["All"]) ## self.df_final.to_excel('E:/Work/Data/Summary/20200213/Sex/summary_temp_' + ## str(random.randint(1, 90000)) + '.xlsx') #export as excel def filter_df(self, filter_dict): #filter df based on condition print(filter_dict) for k in filter_dict.keys(): col = filter_dict[k][0] cond = filter_dict[k][1] if col in ["Weight","Temperature","Humidity","Contact_Angle-Water", "Contact_Angle-Hexadecane","Measurement_Number","Contact_Time", "Detachment Speed", "Attachment Speed", "Sliding Speed"]: val = float(filter_dict[k][2]) elif col in ["Folder_Name", "Species", "Sex", "Leg", "Pad","Medium", "Substrate","Label", "ROI Label","Sliding_Step"]: val = filter_dict[k][2] elif col in ["Date"]: val = datetime.strptime(filter_dict[k][2], "%d/%m/%Y").date() if cond == 'equal to': print("equal condition") self.df_final = self.df_final[self.df_final[col] == val] elif cond == 'not equal to': self.df_final = self.df_final[self.df_final[col] != val] elif cond == 'greater than': self.df_final = self.df_final[self.df_final[col] > val] print(self.df_final[col].head()) print("greater than", val) elif cond == 'less than': self.df_final = self.df_final[self.df_final[col] < val] elif cond == 'greater than or equal to': self.df_final = self.df_final[self.df_final[col] >= val] elif cond == 'less than or equal to': self.df_final = self.df_final[self.df_final[col] <= val] # return df_filtered def get_units(self, var, df): if var in ["Adhesion_Force", "Adhesion_Preload", "Friction_Force", "Friction_Preload"]: #force unit = ' $(μN)$' elif var in ["Max_Area", "Pulloff_Area", "Friction_Area", "ROI_Max_Area", "ROI_Pulloff_Area", "Max_Bounding_Area"]: #area unit = ' $(' + df["Area_Units"].iloc[0] + ')$' elif var in ["Max_Length", "Pulloff_Length", "ROI_Max_Length", "ROI_Pulloff_Length", "Max_Bounding_Perimeter", "Max_Bounding_Length", "Max_Bounding_Width"]: #length unit = ' $(' + df["Area_Units"].iloc[0][:-2] + ')$' elif var in ["Detachment Speed", "Attachment Speed", "Sliding Speed"]: #speed unit = ' $(μm/s)$' elif var in ["Contact_Time"]: #time unit = ' $(s)$' elif var in ["Slope"]: #slope unit = self.slope_unit elif var in ["Adhesion_Stress", "Friction_Stress", "Normalized_Adhesion_Force"]: unit = ' $(μN' + '/' + df["Area_Units"].iloc[0] + ')$' elif var in ["Beam_Spring_Constant"]: unit = ' $(μN/μm)$' elif var in ["Initial_Deformation", "Pulloff_Deformation"]: unit = ' $(μm)$' elif var in ["Adhesion_Energy"]: unit = ' $(pJ)$' elif var in ["Normalized_Adhesion_Energy"]: unit = ' $(J/m^2)$' elif var in ["Contact_Angle-Water", "Contact_Angle-Hexadecane"]: unit = r' $(°)$' elif var in ["Temperature"]: unit = r' $(°C)$' elif var in ["Humidity"]: unit = ' $(%)$' elif var in ["Weight"]: unit = ' $(g)$' else: unit = '' return unit def get_errordata(self, var, df): #get errorbar data if var in ["Adhesion_Force", "Adhesion_Preload"]: error = df["Error_Vertical"] elif var in ["Friction_Force", "Friction_Preload"]: error = df["Error_Lateral"] elif var in ["Beam_Spring_Constant"]: error = df["Error_Beam_Spring_Constant"] else: error = None return error def plotSummary(self, summaryDict, df_filter, df_full, group = "ROI Label", marker = "o", figlist = None, leg = None): if figlist == None: self.figdict = {} i = 0 ## header_nocomb = ["ROI Label", "Data_Folder", ## "Measurement_Number", "Measurement_OK", ## "Contact_Time", "Detachment Speed", ## "Attachment Speed", "Sliding Speed", "Sliding_Step", ## "Error_Vertical", "Error_Lateral", "Area_Units"] ## header_comb = ["Adhesion_Force", "Adhesion_Preload", ## "Friction_Force","Friction_Preload", ## "Max_Area", "Pulloff_Area", "Friction_Area", ## "ROI_Max_Area", "ROI_Pulloff_Area", ## "Max_Length", "Pulloff_Length", "ROI_Max_Length", ## "ROI_Pulloff_Length", "Pulloff_Contact_Number", ## "Residue_Area", "Pulloff_Median_Eccentricity"] ## header_all = header_nocomb + header_comb ## self.df_all = pd.DataFrame(columns = header_all) markerlist = ["o", "v", "P", "^", "D", "X", "<", ">", "*", "s", "+", "d", "1", "x", "2", "h"] j = 0 print("grp", group) group_unique = list(set(df_filter[group])) group_unique.sort() self.group_list = group_unique #if leg == None else ["All"] #only plot "All" for experiment list ## self.eq_count["All"] = [1,1,1,1] self.violindata = {} self.violinlabels = {} self.violindata["All"] = [[],[],[],[]] self.violinlabels["All"] = [[],[],[],[]] for b in self.group_list: j = 0 if j > 15 else j #reset index ## #combine roi data into dataframe ## data_nocomb = [b] + [df_filter[x] \ ## for x in header_nocomb \ ## if x not in ["ROI Label"]] ## data_comb = [df_filter[x + "_" + b] for x in header_comb] ## ## df_nocomb = pd.DataFrame(dict(zip(header_nocomb, data_nocomb))) ## df_comb = pd.DataFrame(dict(zip(header_comb, data_comb))) ## df_joined = df_comb.join(df_nocomb) ## self.df_all = self.df_all.append(df_joined, ignore_index=True, sort=False) ## self.df_all['Adhesion_Force'].replace('', np.nan, inplace=True) ## self.df_all.dropna(subset=['Adhesion_Force'], inplace=True) #remove blanks ## if leg == None: #data source is summary file df_roi_filter = df_filter[df_filter[group] == b] roilist = [b, "All"] ## else: #data source is experiment list ## df_roi_filter = df_filter ## roilist = [b] ## roilist = [b, "All"] if leg == None else [b]#combine roi plots in 'All' mk = markerlist[j] j += 1 #show variable names for numeric values in legend group_unit = self.get_units(group, df_roi_filter) group_unit_clean = group_unit.split('(')[1].split(')')[0] if group_unit != '' else group_unit self.group_name = group.replace('_', ' ') + group_unit self.group_val = b # if summaryDict['plot type'][0] == "Scatter": b = group.replace('_', ' ') + ' ' + str(b) + group_unit_clean \ if isinstance(b, str) !=True and b!= None else b leg = group.replace('_', ' ') + ' ' + str(leg) + group_unit_clean \ if isinstance(leg, str) !=True and leg!= None else leg # else: # b = str(b) \ # if isinstance(b, str) !=True and b!= None else b # leg = str(leg) \ # if isinstance(leg, str) !=True and leg!= None else leg: ## if leg == None: #initialize fit equation counter self.eq_count[b] = [1,1,1,1] self.violindata[b] = [[],[],[],[]] self.violinlabels[b] = [[],[],[],[]] ## self.eq_count[b] = [1,1,1,1] for c in roilist: c = group.replace('_', ' ') + ' ' + str(c) + group_unit_clean \ if isinstance(c, str) !=True and c!= None else c # adhesion_speed_plots = {} # friction_speed_plots = {} title_a = summaryDict['title'][0] + ' (' + c + ')' ## title_l = 'Adhesion (' + c + ') vs Length' ## for a in speed_def_unique: #loop over speed definitions ## if a in ['Detachment Speed']: p1 = summaryDict['cbar var'][0] #first subplot p1_clean = p1.replace('_', ' ') p1_unit = self.get_units(p1, df_roi_filter) x1 = summaryDict['x var'][0] x1_clean = x1.replace('_', ' ') x1_unit = self.get_units(x1, df_roi_filter) y1 = summaryDict['y var'][0] y1_clean = y1.replace('_', ' ') y1_unit = self.get_units(y1, df_roi_filter) title1 = 'Effect of ' + p1_clean \ if summaryDict['plot type'][0] == "Scatter" else y1_clean fig_a = self.preparePlot(summaryDict['plot type'][0], title1, title_a, df_full, df_roi_filter[x1], df_roi_filter[y1], df_roi_filter[p1], self.get_errordata(y1, df_roi_filter), x1_clean + x1_unit, y1_clean + y1_unit, p1_clean + p1_unit, j, mk if leg == None and c == "All" else marker, figlist[c][0] if c in self.figdict.keys() else None, b if leg == None and c == "All" else leg, subplt = 1, fit_flag = summaryDict['fit'][0], fit_order = summaryDict['order'][0]) ## adhesion_speed_plots[a] = fig_a ## if a in ['Sliding Speed']: ## fig_l = self.preparePlot('Effect of ' + p1_clean, title_l, df_full, ## df_roi_filter["Pulloff_Length"], df_roi_filter["Adhesion_Force"], ## df_roi_filter[p1], df_roi_filter["Error_Vertical"], ## 'Contact Length ($' + df_roi_filter["Area_Units"].iloc[0][:-2] + '$)', ## 'Adhesion Force (μN)', p1_clean + ' ' + p1_unit, ## mk if leg == None and c == "All" else marker, ## figlist[c][1] if c in self.figdict.keys() else None, ## b if leg == None and c == "All" else leg, subplt = 1) ## friction_speed_plots[a] = fig_f p2 = summaryDict['cbar var'][1] #second subplot p2_clean = p2.replace('_', ' ') p2_unit = self.get_units(p2, df_roi_filter) x2 = summaryDict['x var'][1] x2_clean = x2.replace('_', ' ') x2_unit = self.get_units(x2, df_roi_filter) y2 = summaryDict['y var'][1] y2_clean = y2.replace('_', ' ') y2_unit = self.get_units(y2, df_roi_filter) title2 = 'Effect of ' + p2_clean \ if summaryDict['plot type'][0] == "Scatter" else y2_clean fig_a = self.preparePlot(summaryDict['plot type'][0], title2, title_a, df_full, df_roi_filter[x2], df_roi_filter[y2], df_roi_filter[p2], self.get_errordata(y2, df_roi_filter), x2_clean + x2_unit, y2_clean + y2_unit, p2_clean + p2_unit, j, mk if leg == None and c == "All" else marker, fig_a, b if leg == None and c == "All" else leg, subplt = 2, fit_flag = summaryDict['fit'][1], fit_order = summaryDict['order'][1]) ## fig_l = self.preparePlot('Effect of ' + p2_clean, title_l, df_full, ## df_roi_filter["Pulloff_Length"], df_roi_filter["Adhesion_Force"], ## df_roi_filter[p2], df_roi_filter["Error_Vertical"], ## 'Contact Length ($' + df_roi_filter["Area_Units"].iloc[0][:-2] + '$)', ## 'Adhesion Force (μN)', p2_clean + ' ' + p2_unit, ## mk if leg == None and c == "All" else marker, ## fig_l, b if leg == None and c == "All" else leg, subplt = 2) p3 = summaryDict['cbar var'][2] #third subplot p3_clean = p3.replace('_', ' ') p3_unit = self.get_units(p3, df_roi_filter) x3 = summaryDict['x var'][2] x3_clean = x3.replace('_', ' ') x3_unit = self.get_units(x3, df_roi_filter) y3 = summaryDict['y var'][2] y3_clean = y3.replace('_', ' ') y3_unit = self.get_units(y3, df_roi_filter) title3 = 'Effect of ' + p3_clean \ if summaryDict['plot type'][0] == "Scatter" else y3_clean fig_a = self.preparePlot(summaryDict['plot type'][0], title3, title_a, df_full, df_roi_filter[x3], df_roi_filter[y3], df_roi_filter[p3], self.get_errordata(y3, df_roi_filter), x3_clean + x3_unit, y3_clean + y3_unit, p3_clean + p3_unit, j, mk if leg == None and c == "All" else marker, fig_a, b if leg == None and c == "All" else leg, subplt = 3, fit_flag = summaryDict['fit'][2], fit_order = summaryDict['order'][2]) ## fig_l = self.preparePlot('Effect of ' + p3_clean, title_l, df_full, ## df_roi_filter["Pulloff_Length"], df_roi_filter["Adhesion_Force"], ## df_roi_filter[p3], df_roi_filter["Error_Vertical"], ## 'Contact Length ($' + df_roi_filter["Area_Units"].iloc[0][:-2] + '$)', ## 'Adhesion Force (μN)', p3_clean + ' ' + p3_unit, ## mk if leg == None and c == "All" else marker, ## fig_l, b if leg == None and c == "All" else leg, subplt = 3) p4 = summaryDict['cbar var'][3] #fourth subplot p4_clean = p4.replace('_', ' ') p4_unit = self.get_units(p4, df_roi_filter) x4 = summaryDict['x var'][3] x4_clean = x4.replace('_', ' ') x4_unit = self.get_units(x4, df_roi_filter) y4 = summaryDict['y var'][3] y4_clean = y4.replace('_', ' ') y4_unit = self.get_units(y4, df_roi_filter) title4 = 'Effect of ' + p4_clean \ if summaryDict['plot type'][0] == "Scatter" else y4_clean fig_a = self.preparePlot(summaryDict['plot type'][0], title4, title_a, df_full, df_roi_filter[x4], df_roi_filter[y4], df_roi_filter[p4], self.get_errordata(y4, df_roi_filter), x4_clean + x4_unit, y4_clean + y4_unit, p4_clean + p4_unit, j, mk if leg == None and c == "All" else marker, fig_a, b if leg == None and c == "All" else leg, subplt = 4, fit_flag = summaryDict['fit'][3], fit_order = summaryDict['order'][3]) ## fig_l = self.preparePlot('Effect of ' + p4_clean, title_l, df_full, ## df_roi_filter["Pulloff_Length"], df_roi_filter["Adhesion_Force"], ## df_roi_filter[p4], df_roi_filter["Error_Vertical"], ## 'Contact Length ($' + df_roi_filter["Area_Units"].iloc[0][:-2] + '$)', ## 'Adhesion Force (μN)', p4_clean + ' ' + p4_unit, ## mk if leg == None and c == "All" else marker, ## fig_l, b if leg == None and c == "All" else leg, subplt = 4) self.figdict[c] = [fig_a] if i == 0 and c == "All" and figlist == None: #initialise figlist for "All" figlist = {} figlist["All"] = [fig_a] i = 1 ## self.df_final = self.df_all.copy() ## self.df_all.to_excel("E:/Work/Codes/Test codes/test5.xlsx") #export as excel def preparePlot(self, plot_type, ax_title, fig_title, df_full, xdata, ydata, bardata, errdata, xlabel, ylabel, barlabel, grp_num, mk = "o", figname = None, leg = None, subplt = None, fit_flag = False, fit_order = 1): print("preparePlot") group = fig_title.split('(')[1].split(')')[0] #group value ax_num = 2 if plot_type == "Scatter" else 1; #number of axis per subplot if figname == None: #create figure fig = plt.figure(num=fig_title, figsize = [16, 10]) plt.clf() #clear figure cache ## fig.suptitle(fig_title, fontsize=16) ax = fig.add_subplot(2,2,subplt) ax.set_title(ax_title) plt.cla() #clear axis cache ax.set_title(ax_title) # if plot_type == "Scatter": ax.set_xlabel(xlabel) # else: # ax.set_xlabel(self.group_name) ax.set_ylabel(ylabel) labels = [] cbar_flag = True elif subplt > (len(figname.axes))/ax_num: #create subplot print("a", len(figname.axes)) fig = figname ax = fig.add_subplot(2,2,subplt) ax.set_title(ax_title) ## plt.cla() #clear axis cache ## ax.set_title(title) # if plot_type == "Scatter": ax.set_xlabel(xlabel) # else: # ax.set_xlabel(self.group_name) ax.set_ylabel(ylabel) labels = [] cbar_flag = True else: print("b", len(figname.axes)) fig = figname ax = figname.axes[ax_num*(subplt-1)] handles, labels = ax.get_legend_handles_labels() cbar_flag = False #increment for each new data group if fit_flag == True: self.eq_count[group][subplt-1] += 1 print(group, self.eq_count) if plot_type == "Scatter": if leg in labels: leg = "_nolegend_" if bardata.dtype == 'object': #for string type data ticklabels = list(set(df_full[bardata.name])) ticklabels.sort() bardata_full = [ticklabels.index(a) for a in df_full[bardata.name]] bardata_new = [ticklabels.index(a) for a in bardata] cmin, cmax = min(bardata_full), max(bardata_full) else: cmin, cmax = df_full[bardata.name].min(), df_full[bardata.name].max() ticklabels = [] bardata_new = bardata im = ax.scatter(xdata, ydata, marker = mk, s = 100, alpha = None, c = bardata_new, cmap="plasma", label = leg, vmin = cmin, vmax = cmax) if leg != None and leg not in labels: ax.legend(loc = 'upper left') if cbar_flag == True: print(barlabel) if bardata.dtype == 'object': cbar = fig.colorbar(im, ax = ax, ticks = [ticklabels.index(a) \ for a in ticklabels]) cbar.ax.set_yticklabels(ticklabels) else: cbar = fig.colorbar(im, ax = ax) cbar.set_clim(cmin, cmax) cbar.set_label(barlabel) ax.errorbar(xdata, ydata,yerr= errdata, capsize = 3, ecolor = 'k', zorder=0, elinewidth = 1, linestyle="None", label = None) if fit_flag == True: cmap = plt.cm.get_cmap('Set1') vshift = 0.05 data = zip(xdata, ydata) data = np.array(sorted(data, key = lambda x: x[0])) coeff = np.polyfit(data[:,0],data[:,1], fit_order) #fitting coeffients p_fit = np.poly1d(coeff) y_fit = p_fit(data[:,0]) y_avg = np.sum(data[:,1])/len(data[:,1]) r2 = (np.sum((y_fit-y_avg)**2))/(np.sum((data[:,1] - y_avg)**2)) sign = '' if coeff[1] < 0 else '+' eq_id = leg.split(' ')[-1] if leg != None else fig_title.split('(')[1].split(')')[0].split(' ')[-1]#[:2] eq_coff = ["$%.1e"%(coeff[i]) + "x^" + str(len(coeff) - i - 1) + "$"\ if i < len(coeff) - 2 else "%.4fx"%(coeff[i]) for i in range(len(coeff)-1)] eq = "y=" + '+'.join(eq_coff) + "+%.4f"%(coeff[len(coeff)-1]) + "; $R^2$=" + "%.4f"%(r2) eq_clean = eq.replace('+-', '-') x_fit = np.linspace(min(data[:,0]), max(data[:,0]), 100) ax.plot(x_fit, p_fit(x_fit), color = cmap(self.eq_count[group][subplt-1]*0.1), linewidth=1, linestyle='dotted') ax.text(1,0.2 - (vshift * self.eq_count[group][subplt-1]), eq_id + ": " + eq_clean, ha = 'right', transform=ax.transAxes, color = cmap(self.eq_count[group][subplt-1]*0.1), bbox=dict(facecolor='white', edgecolor = 'white', alpha=0.5)) ## self.eq_count[subplt-1] += 1 elif plot_type in ["Box","Violin"]: print("Box",leg) ax.cla() ax.set_ylabel(ylabel) self.violindata[group][subplt-1].append(ydata) datasize = str(len(ydata)) if group == "All": # group_size = len(self.group_list) # boxdata = [[]]*group_size # boxdata[grp_num-1] = ydata # boxlabels = self.group_list # # boxlabels = [[]]*group_size # boxlabels[grp_num-1] = leg # boxpositions = list(range(1,group_size+1)) self.violinlabels[group][subplt-1].append(str(self.group_val) + '\n' + '(n=' + datasize + ')') ax.set_xlabel(self.group_name) else: # boxdata = ydata # boxlabels = [group] # boxpositions = [1] self.violinlabels[group][subplt-1].append(str(group) + '\n' + '(n=' + datasize + ')') ax.set_xlabel(None) violinpositions = list(range(1,len(self.violinlabels[group][subplt-1])+1)) if plot_type == "Box": ax.boxplot(self.violindata[group][subplt-1], positions=violinpositions, labels=self.violinlabels[group][subplt-1]) elif plot_type == "Violin": # self.violindata[group][subplt-1].append(ydata) # self.violinlabels[group][subplt-1].append(leg) # violinpositions = list(range(1,len(self.violinlabels[group][subplt-1])+1)) ax.violinplot(self.violindata[group][subplt-1], positions=violinpositions, showmedians=True) ax.set_xticks(violinpositions) ax.set_xticklabels(self.violinlabels[group][subplt-1]) fig.tight_layout() ## fig.show() ## plt.show() return fig def showSummaryPlot(self): #show summary plots print("showSummaryPlot") if self.summary_filepath != "": keys = list(self.figdict.keys()) for b in keys: print("keys", b) if len(self.figdict.keys())==2 and b == "All": #close "All" figures plt.close(self.figdict[b][0]) ## plt.close(self.figdict[b][1]) ## plt.close(self.figdict[b][2]) ## plt.close(self.figdict[b][3]) ## plt.close(self.figdict[b][4]) ## plt.close(self.figdict[b][5]) ## for a in self.figdict[b][6].values(): ## plt.close(a) ## for a in self.figdict[b][7].values(): ## plt.close(a) else: ## self.figdict[b][0].show() self.show_figure(self.figdict[b][0]) ## self.figdict[b][1].show() ## self.figdict[b][2].show() ## self.figdict[b][3].show() ## self.figdict[b][4].show() ## self.figdict[b][5].show() ## for a in self.figdict[b][6].values(): ## a.show() ## for a in self.figdict[b][7].values(): ## a.show() plt.show() def show_figure(self, fig): # create a dummy figure and use its # manager to display "fig" dummy = plt.figure(num=fig.get_label(), figsize = [16, 10]) new_manager = dummy.canvas.manager new_manager.canvas.figure = fig fig.set_canvas(new_manager.canvas) def saveSummaryPlot(self, plot_format): #save summary plots if self.summary_filepath != "": folderpath = os.path.dirname(self.summary_filepath) if not os.path.exists(folderpath): os.makedirs(folderpath) keys = list(self.figdict.keys()) for b in keys: if len(self.figdict.keys())==2 and b == "All": continue else: self.savePlot(self.figdict[b][0], plot_format) ## self.savePlot(self.figdict[b][1]) ## self.savePlot(self.figdict[b][2]) ## self.savePlot(self.figdict[b][3]) ## self.savePlot(self.figdict[b][4]) ## self.savePlot(self.figdict[b][5]) ## for a in self.figdict[b][6].values(): ## self.savePlot(a) ## for a in self.figdict[b][7].values(): ## self.savePlot(a) self.df_final.to_excel(os.path.dirname(self.summary_filepath) + '/summary_clean_' + time.strftime("%y%m%d%H%M%S") + '.xlsx') #export as excel def savePlot(self, fig, plot_format): #save routine filename = os.path.dirname(self.summary_filepath) + '/' + \ fig.get_label().replace('/','')+ '-' + time.strftime("%y%m%d%H%M%S") + '.' + plot_format fig.savefig(filename, orientation='landscape', transparent = True, dpi = 150) print("save plot", filename) def combineSummary(self, summaryDict, legend_parameter): #combine summary data and plot root = tk.Tk() root.withdraw() self.list_filepath = filedialog.askopenfilename( title = "Select experiment list file") if self.list_filepath != "": list_folderpath = os.path.dirname(self.list_filepath) wb_obj = openpyxl.load_workbook(filename = self.list_filepath, read_only = True)# workbook object is created sheet_obj = wb_obj.active m_row = sheet_obj.max_row date = [] foldername = [] species = [] sex = [] leg = [] pad = [] weight = [] temp = [] hum = [] medium = [] surface = [] ca_w = [] ca_o = [] dataok = [] includedata = [] label = [] header1 = ["Date", "Folder_Name", "Species", "Sex", "Leg", "Pad", "Weight", "Temperature", "Humidity", "Medium", "Substrate","Contact_Angle-Water", "Contact_Angle-Hexadecane", "Data_OK", "Include_Data", "Label"] ## header2 = ["Max_Area", "Pulloff_Area","Adhesion_Force", ## "Preload_Force", "Contact_Time", "Speed", ## "Steps", "Friction_Force", "Friction_Area", ## "Measurement_Number", "Measurement_OK", "ROI_Labels", ## "Area_Units"] ## headerfull = header1 + header2 df = pd.DataFrame(columns = header1) ## steps_unique = [] ## speed_def_unique = [] ## roi_label_unique = [] j = 0 for i in range(3, m_row + 1): #import data ok = sheet_obj.cell(row = i, column = 16).value include = sheet_obj.cell(row = i, column = 17).value if ok == 'No' or include == 'No': #only consider 'Yes' data in Data OK/Include Data continue date.append(sheet_obj.cell(row = i, column = 1).value) foldername.append(sheet_obj.cell(row = i, column = 2).value) species.append(sheet_obj.cell(row = i, column = 3).value) sex.append(sheet_obj.cell(row = i, column = 4).value) leg.append(sheet_obj.cell(row = i, column = 5).value) pad.append(sheet_obj.cell(row = i, column = 6).value) weight.append(sheet_obj.cell(row = i, column = 7).value) temp.append(sheet_obj.cell(row = i, column = 8).value) hum.append(sheet_obj.cell(row = i, column = 9).value) medium.append(sheet_obj.cell(row = i, column = 10).value) surface.append(sheet_obj.cell(row = i, column = 11).value) ca_w.append(sheet_obj.cell(row = i, column = 12).value) ca_o.append(sheet_obj.cell(row = i, column = 13).value) dataok.append(ok) includedata.append(include) label.append(sheet_obj.cell(row = i, column = 18).value) print(foldername[j], m_row) if foldername[j] != None: self.importSummary(list_folderpath + "/" + foldername[j] + "/Analysis/Summary/summary data.txt") ## steps_unique.append(self.steps_unique) ## roi_label_unique.append(self.roi_label_unique) ## roi_label_unique.append(set(self.df_forcedata["ROI Label"])) ## speed_def_unique.append(self.speed_def_unique) rownum = len(self.df_forcedata["Max_Area"]) datalist = [[date[j]]*rownum, [foldername[j]]*rownum, [species[j]]*rownum,[sex[j]]*rownum, [leg[j]]*rownum, [pad[j]]*rownum, [weight[j]]*rownum,[temp[j]]*rownum, [hum[j]]*rownum, [medium[j]]*rownum, [surface[j]]*rownum, [ca_w[j]]*rownum, [ca_o[j]]*rownum, [dataok[j]]*rownum, [includedata[j]]*rownum, [label[j]]*rownum] datadict = dict(zip(header1, datalist)) df_data = pd.DataFrame(datadict) df_joined = df_data.join(self.df_forcedata) df = df.append(df_joined, ignore_index=True, sort=False) ## df.to_excel('E:/Work/Data/Summary/20200213/Sex/summary_comb_' + ## str(random.randint(1, 90000)) + '.xlsx') #export as excel ## print(df.to_string()) else: break j += 1 wb_obj.close() print("import finish") # df['Date'] = df['Date'].dt.strftime('%d/%m/%Y') df['Date'] = pd.to_datetime(df['Date'], format = '%d=%m-%Y').dt.date ## roi_label_unique = list(set([a for b in roi_label_unique for a in b])) ## speed_def_unique = list(set([a for b in speed_def_unique for a in b])) self.df_final = df.copy() #save summary combined excel_folderpath = list_folderpath + '/Summary/' + \ time.strftime("%Y%m%d") + '/' + legend_parameter excel_filepath = excel_folderpath + '/summary_combined_' + \ time.strftime("%Y%m%d%H%M%S") + '.xlsx' ## if not os.path.exists(excel_folderpath): ## os.makedirs(excel_folderpath) ## self.df_all.to_excel(excel_filepath) #export as excel # df_good = self.df_final self.summary_filepath = excel_filepath #to save plots in Summary directory # self.plotSummary(summaryDict, # df_good, # df_good, # legend_parameter) # if legend_parameter == "ROI Label": #no filtering as this is already plotted in prepareplot (when leg = None) # self.plotSummary(summaryDict, df_good, df_good) # else: # ## legend_parameter = 'Folder_Name' #choose, same as column names # legend_list = df_good[legend_parameter].unique() # legend_list.sort() # print(legend_list) # markerlist = ["o", "v", "P", "^", "D", "X", "<", ">", "*", "s", # "+", "d", "1", "x", "2", "h"] # figlist = None # i = 0 # ## df_leg = pd.DataFrame(dict(zip([legend_parameter], [legend_list]))) # for lg in legend_list: # print("zxz", lg) # i = 0 if i > 15 else i # df_filtered = df_good[df_good[legend_parameter] == lg] # self.plotSummary(summaryDict, # df_filtered, df_good, legend_parameter, markerlist[i], # figlist, lg) # figlist = self.figdict.copy() # ## df_all_joined = self.df_all.copy() # ## df_all_joined.insert(0, legend_parameter, lg) # ## if i == 0: # ## df_final = df_all_joined.copy() # ## else: # ## df_final = df_final.append(df_all_joined, ignore_index=True, sort=False) # ## print("iter", i) # i += 1 # ## self.df_final = df_final.copy() ##a.combineSummary("Folder_Name") ##if a.list_filepath != "": ## a.showSummaryPlot() ##summary = SummaryAnal() ##summary.importSummary() ##summary.plotSummary(summary.speed_def_unique, ## summary.roi_label_unique, ## summary.df_forcedata, ## summary.df_forcedata) ##summary.showSummaryPlot()
47,862
-3
390
ac09199a3bcecf7860ff8739a1e4c5bd8c92d9f0
881
py
Python
src/onegov/activity/collections/__init__.py
politbuero-kampagnen/onegov-cloud
20148bf321b71f617b64376fe7249b2b9b9c4aa9
[ "MIT" ]
null
null
null
src/onegov/activity/collections/__init__.py
politbuero-kampagnen/onegov-cloud
20148bf321b71f617b64376fe7249b2b9b9c4aa9
[ "MIT" ]
null
null
null
src/onegov/activity/collections/__init__.py
politbuero-kampagnen/onegov-cloud
20148bf321b71f617b64376fe7249b2b9b9c4aa9
[ "MIT" ]
null
null
null
from onegov.activity.collections.activity import ActivityFilter from onegov.activity.collections.activity import ActivityCollection from onegov.activity.collections.attendee import AttendeeCollection from onegov.activity.collections.booking import BookingCollection from onegov.activity.collections.invoice import InvoiceCollection from onegov.activity.collections.occasion import OccasionCollection from onegov.activity.collections.period import PeriodCollection from onegov.activity.collections.publication_request import \ PublicationRequestCollection from onegov.activity.collections.volunteer import VolunteerCollection __all__ = [ 'ActivityCollection', 'ActivityFilter', 'AttendeeCollection', 'BookingCollection', 'InvoiceCollection', 'OccasionCollection', 'PeriodCollection', 'PublicationRequestCollection', 'VolunteerCollection', ]
38.304348
69
0.830874
from onegov.activity.collections.activity import ActivityFilter from onegov.activity.collections.activity import ActivityCollection from onegov.activity.collections.attendee import AttendeeCollection from onegov.activity.collections.booking import BookingCollection from onegov.activity.collections.invoice import InvoiceCollection from onegov.activity.collections.occasion import OccasionCollection from onegov.activity.collections.period import PeriodCollection from onegov.activity.collections.publication_request import \ PublicationRequestCollection from onegov.activity.collections.volunteer import VolunteerCollection __all__ = [ 'ActivityCollection', 'ActivityFilter', 'AttendeeCollection', 'BookingCollection', 'InvoiceCollection', 'OccasionCollection', 'PeriodCollection', 'PublicationRequestCollection', 'VolunteerCollection', ]
0
0
0
7911c5cf157ef0156fb354e4487de90ddf5950f1
11,396
py
Python
src/ase2sprkkr/sprkkr/sprkkr_atoms.py
ase2sprkkr/ase2sprkkr
5e04f54365e4ab65d97bd11d573b078674548a59
[ "MIT" ]
1
2022-03-14T22:56:11.000Z
2022-03-14T22:56:11.000Z
src/ase2sprkkr/sprkkr/sprkkr_atoms.py
ase2sprkkr/ase2sprkkr
5e04f54365e4ab65d97bd11d573b078674548a59
[ "MIT" ]
1
2022-03-10T09:08:50.000Z
2022-03-10T09:08:50.000Z
src/ase2sprkkr/sprkkr/sprkkr_atoms.py
ase2sprkkr/ase2sprkkr
5e04f54365e4ab65d97bd11d573b078674548a59
[ "MIT" ]
null
null
null
""" This file contains SPRKKRAtoms - an enhanced version of Atoms to be used with SPRKKR """ from ase import Atoms from ..common.unique_values import UniqueValuesMapping import spglib from ase.spacegroup import Spacegroup import numpy as np from ..sprkkr.sites import Site from ..common.misc import numpy_index class SPRKKRAtoms(Atoms): """ ASE Atoms object extended by the data necessary for SPR-KKR calculations """ @staticmethod def promote_ase_atoms(obj, symmetry=None): """ Convert ASE Atoms object to the one usable by SPRKKR. For the case of the usability it is a bit ugly hack: The __class__ attribute is replaced so the extra methods and properties of the objects will be available. Parameters ---------- obj: ase.Atoms The atoms object to be promoted to be used for SPRKKR calculations symmetry: boolean or None The sites property of the resulting object will consider the symmetry of the structure. I.e., the by-symmetry-equal atomic sites will share the same sites object. Default None is the same as True, however it does not change the symmetry of the already promoted obj passed into the routine. """ if obj and not isinstance(obj, SPRKKRAtoms): if obj.__class__ is Atoms: obj.__class__ = SPRKKRAtoms else: if not isinstance(obj, Atoms): raise(f'Can not promote class {obj} of class {obj.__class__} to {SPRKKRAtoms}') obj.__class__ = SprKKrAtomsEx obj._init(True if symmetry is None else symmetry) else: if symmetry is not None: obj.symmetry = symmetry return obj def __init__(self, *args, symmetry=True, potential=None, **kwargs): """ Creates SPRKKRAtoms atoms Parameters ---------- *args: list The positionals arguments of ase.Atoms.__init__ symmetry: boolean The symmetry will be computed when the sites property will be initialized. I.e., the by-symmetry-equal atomic sites will share the same sites object. **kwargs: dict The named arguments of ase.Atoms.__init__ """ self._init(symmetry, potential) super().__init__(*args, **kwargs) def _init(self, symmetry=True, potential=None): """ The initialization of the additional (not-in-ASE) properties. To be used by constructor and by promote_ase_atoms""" self._unique_sites = None self._potential = potential self._symmetry = symmetry @property def symmetry(self): """ Whether the sites property is/will be generated using symmetry, i.e. whether the Sites objects in the sites property will be shared among symmetric atomic sites. """ return self._symmetry @symmetry.setter def symmetry(self, value): """ Recomputes the sites with enabled/disabled symmetry if the value of the property has changed. """ if self._symmetry == value: return self._symmetry = value if self._unique_sites is not None: if value: self._compute_sites_symmetry() else: self._cancel_sites_symmetry() def compute_spacegroup_for_atomic_numbers(self, atomic_numbers=None, symprec=1e-5): """ Return spacegroup that suits to the atoms' cell structure and to the given atomic_numbers (not necessary the real ones, they can be just ''labels''). """ atomic_numbers = atomic_numbers if atomic_numbers is not None else self.get_atomic_numbers() sg = spglib.get_spacegroup((self.get_cell(), self.get_scaled_positions(), atomic_numbers), symprec=symprec) if sg is None: return None sg_no = int(sg[sg.find('(') + 1:sg.find(')')]) spacegroup = Spacegroup(sg_no) return spacegroup def compute_sites_symmetry(self, spacegroup=None, atomic_numbers=None, consider_old=False, symprec=1e-5): """ SPRKKR has some properties shared by all by-symmetry-equal sites. This method initializes _sites property, that holds these properties: makes identical all the atoms on the "symmetry identical positions" with the same atomic number. The method is called automatically when the sites property is firstly accessed. The effect of the method is the nearly same as setting the symmetry property. However, setting the symmetry property on an 'already symmetrized' object has no effect, while this methods always recompute the sites property. Parameters ---------- spacegroup: Spacegroup If not None, the given spacegroup is used for determining the symmetry, instead of the one determined by cell geometry. atomic_numbers: [ int ] Atomic numbers used to determine the spacegroup (if it is not given) to compute the symmetry. The atomic numbers can be ''virtual'', just to denote the equivalence of the sites. The array should have the same length as the number of atoms in the unit cell. If None, self.symbols are used. consider_old: bool If True, and _unique_sites is not None, the non-symmetry-equivalent sites won't be equivalent in the newly computed symmetry. symprec: float A threshold for spatial error for the symmetry computing. See spglib.get_spacegroup """ self._symmetry = True SPRKKRAtoms._compute_sites_symmetry(**locals()) def _compute_sites_symmetry(self, spacegroup=None, atomic_numbers=None, consider_old=False, symprec=1e-5): """ See compute_sites_symmetry - this metod does just the same, but it does not set the symmetry property.""" occupation = self.info.get('occupancy', {}) if not spacegroup and self._symmetry: if atomic_numbers: mapping = UniqueValuesMapping(atomic_numbers) else: mapping = UniqueValuesMapping(self.get_atomic_numbers()) if consider_old and self._unique_sites: mapping = mapping.merge(self._unique_sites) if occupation: mapping = mapping.merge(gen_occ()) spacegroup = self.compute_spacegroup_for_atomic_numbers(mapping.mapping, symprec=symprec) self.info['spacegroup'] = spacegroup if not spacegroup: return self.cancel_sites_symmetry() tags = spacegroup.tag_sites(self.get_scaled_positions()) mapping = mapping.merge( tags ) tags = mapping.mapping sites = np.empty(len(tags), dtype=object) uniq, umap = np.unique(tags, return_inverse = True) used = set() for i in range(len(uniq)): index = umap == i if self._unique_sites is not None: #first non-none of the given index possible = (i for i in self._unique_sites[index]) site = next(filter(None, possible), None) if site in used: site = site.copy() else: used.add(site) else: site = None if not site: symbol = self.symbols[ numpy_index(umap,i)] for ai in np.where(index)[0]: if ai in occupation and occupation[ai]: symbol = occupation[ai] site = Site(self, symbol) sites[index] = site self.sites = sites def cancel_sites_symmetry(self): """ Cancel the use of symmetry in the structure, i.e., makes the Site object uniqe (not shared) for each atomic site. Calling this method is nearly equivalent to the setting the symmetry property to False, however, this method always recompute the sites object, while setting symmetry=False recomputes the sites property only if it was previously set to False. """ self._symmetry = False self._cancel_sites_symmetry() def _cancel_sites_symmetry(self): """ See cancel_sites_symmetry - this metod does just the same, but it does not set the symmetry property.""" sites = np.empty(len(self), dtype=object) used = set() occupation = self.info.get('occupancy', {}) for i in range(len(self)): if self._unique_sites is not None: site=self._unique_sites[i] if site in used: site = site.copy() else: used.add(site) else: symbol = occupation[i] if i in occupation and occupation[i] else \ self.symbols[i] site = Site(self, symbol) sites[i] = site self.sites = sites @property def sites(self): """ The sites property holds all the information for the SPR-KKR package: atomic types (including number of semicore and valence electrons), occupancy, symmetries, meshes... Some of the properties are stored in the ASE atoms properties (e.g. occupancy, atomic symbol), however, ASE is not able to hold them all and/or to describe fully the SPR-KKR options; thus, these properties are hold in this array. The changes made on this array are reflected (as is possible) to the ASE properties, but the opposite does not hold - to reflect the changes in these properties please create a new Atoms object with given properties. """ if self._unique_sites is None: self._compute_sites_symmetry() return self._unique_sites @sites.setter def sites(self, v): """ Set the sites property and update all other dependent properties (symbols, occupancy) according to the sites """ an = np.zeros(len(v), dtype= int) occ = {} for i,j in enumerate(v): occ[i] = j.occupation.as_dict an[i] = j.occupation.primary_atomic_number self.set_atomic_numbers(an) self.info['occupancy'] = occ self._unique_sites = v @property @potential.setter #at the last - to avoid circular imports from ..potentials import potentials
39.161512
117
0.612496
""" This file contains SPRKKRAtoms - an enhanced version of Atoms to be used with SPRKKR """ from ase import Atoms from ..common.unique_values import UniqueValuesMapping import spglib from ase.spacegroup import Spacegroup import numpy as np from ..sprkkr.sites import Site from ..common.misc import numpy_index class SPRKKRAtoms(Atoms): """ ASE Atoms object extended by the data necessary for SPR-KKR calculations """ @staticmethod def promote_ase_atoms(obj, symmetry=None): """ Convert ASE Atoms object to the one usable by SPRKKR. For the case of the usability it is a bit ugly hack: The __class__ attribute is replaced so the extra methods and properties of the objects will be available. Parameters ---------- obj: ase.Atoms The atoms object to be promoted to be used for SPRKKR calculations symmetry: boolean or None The sites property of the resulting object will consider the symmetry of the structure. I.e., the by-symmetry-equal atomic sites will share the same sites object. Default None is the same as True, however it does not change the symmetry of the already promoted obj passed into the routine. """ if obj and not isinstance(obj, SPRKKRAtoms): if obj.__class__ is Atoms: obj.__class__ = SPRKKRAtoms else: if not isinstance(obj, Atoms): raise(f'Can not promote class {obj} of class {obj.__class__} to {SPRKKRAtoms}') class SprKKrAtomsEx(obj.__class__, SPRKKRAtoms): pass obj.__class__ = SprKKrAtomsEx obj._init(True if symmetry is None else symmetry) else: if symmetry is not None: obj.symmetry = symmetry return obj def __init__(self, *args, symmetry=True, potential=None, **kwargs): """ Creates SPRKKRAtoms atoms Parameters ---------- *args: list The positionals arguments of ase.Atoms.__init__ symmetry: boolean The symmetry will be computed when the sites property will be initialized. I.e., the by-symmetry-equal atomic sites will share the same sites object. **kwargs: dict The named arguments of ase.Atoms.__init__ """ self._init(symmetry, potential) super().__init__(*args, **kwargs) def _init(self, symmetry=True, potential=None): """ The initialization of the additional (not-in-ASE) properties. To be used by constructor and by promote_ase_atoms""" self._unique_sites = None self._potential = potential self._symmetry = symmetry @property def symmetry(self): """ Whether the sites property is/will be generated using symmetry, i.e. whether the Sites objects in the sites property will be shared among symmetric atomic sites. """ return self._symmetry @symmetry.setter def symmetry(self, value): """ Recomputes the sites with enabled/disabled symmetry if the value of the property has changed. """ if self._symmetry == value: return self._symmetry = value if self._unique_sites is not None: if value: self._compute_sites_symmetry() else: self._cancel_sites_symmetry() def compute_spacegroup_for_atomic_numbers(self, atomic_numbers=None, symprec=1e-5): """ Return spacegroup that suits to the atoms' cell structure and to the given atomic_numbers (not necessary the real ones, they can be just ''labels''). """ atomic_numbers = atomic_numbers if atomic_numbers is not None else self.get_atomic_numbers() sg = spglib.get_spacegroup((self.get_cell(), self.get_scaled_positions(), atomic_numbers), symprec=symprec) if sg is None: return None sg_no = int(sg[sg.find('(') + 1:sg.find(')')]) spacegroup = Spacegroup(sg_no) return spacegroup def compute_sites_symmetry(self, spacegroup=None, atomic_numbers=None, consider_old=False, symprec=1e-5): """ SPRKKR has some properties shared by all by-symmetry-equal sites. This method initializes _sites property, that holds these properties: makes identical all the atoms on the "symmetry identical positions" with the same atomic number. The method is called automatically when the sites property is firstly accessed. The effect of the method is the nearly same as setting the symmetry property. However, setting the symmetry property on an 'already symmetrized' object has no effect, while this methods always recompute the sites property. Parameters ---------- spacegroup: Spacegroup If not None, the given spacegroup is used for determining the symmetry, instead of the one determined by cell geometry. atomic_numbers: [ int ] Atomic numbers used to determine the spacegroup (if it is not given) to compute the symmetry. The atomic numbers can be ''virtual'', just to denote the equivalence of the sites. The array should have the same length as the number of atoms in the unit cell. If None, self.symbols are used. consider_old: bool If True, and _unique_sites is not None, the non-symmetry-equivalent sites won't be equivalent in the newly computed symmetry. symprec: float A threshold for spatial error for the symmetry computing. See spglib.get_spacegroup """ self._symmetry = True SPRKKRAtoms._compute_sites_symmetry(**locals()) def _compute_sites_symmetry(self, spacegroup=None, atomic_numbers=None, consider_old=False, symprec=1e-5): """ See compute_sites_symmetry - this metod does just the same, but it does not set the symmetry property.""" occupation = self.info.get('occupancy', {}) if not spacegroup and self._symmetry: if atomic_numbers: mapping = UniqueValuesMapping(atomic_numbers) else: mapping = UniqueValuesMapping(self.get_atomic_numbers()) if consider_old and self._unique_sites: mapping = mapping.merge(self._unique_sites) if occupation: def gen_occ(): for i in range(len(mapping)): val = occupation.get(i, None) if val is None: yield val else: yield tuple((k, val[k]) for k in val) mapping = mapping.merge(gen_occ()) spacegroup = self.compute_spacegroup_for_atomic_numbers(mapping.mapping, symprec=symprec) self.info['spacegroup'] = spacegroup if not spacegroup: return self.cancel_sites_symmetry() tags = spacegroup.tag_sites(self.get_scaled_positions()) mapping = mapping.merge( tags ) tags = mapping.mapping sites = np.empty(len(tags), dtype=object) uniq, umap = np.unique(tags, return_inverse = True) used = set() for i in range(len(uniq)): index = umap == i if self._unique_sites is not None: #first non-none of the given index possible = (i for i in self._unique_sites[index]) site = next(filter(None, possible), None) if site in used: site = site.copy() else: used.add(site) else: site = None if not site: symbol = self.symbols[ numpy_index(umap,i)] for ai in np.where(index)[0]: if ai in occupation and occupation[ai]: symbol = occupation[ai] site = Site(self, symbol) sites[index] = site self.sites = sites def cancel_sites_symmetry(self): """ Cancel the use of symmetry in the structure, i.e., makes the Site object uniqe (not shared) for each atomic site. Calling this method is nearly equivalent to the setting the symmetry property to False, however, this method always recompute the sites object, while setting symmetry=False recomputes the sites property only if it was previously set to False. """ self._symmetry = False self._cancel_sites_symmetry() def _cancel_sites_symmetry(self): """ See cancel_sites_symmetry - this metod does just the same, but it does not set the symmetry property.""" sites = np.empty(len(self), dtype=object) used = set() occupation = self.info.get('occupancy', {}) for i in range(len(self)): if self._unique_sites is not None: site=self._unique_sites[i] if site in used: site = site.copy() else: used.add(site) else: symbol = occupation[i] if i in occupation and occupation[i] else \ self.symbols[i] site = Site(self, symbol) sites[i] = site self.sites = sites @property def sites(self): """ The sites property holds all the information for the SPR-KKR package: atomic types (including number of semicore and valence electrons), occupancy, symmetries, meshes... Some of the properties are stored in the ASE atoms properties (e.g. occupancy, atomic symbol), however, ASE is not able to hold them all and/or to describe fully the SPR-KKR options; thus, these properties are hold in this array. The changes made on this array are reflected (as is possible) to the ASE properties, but the opposite does not hold - to reflect the changes in these properties please create a new Atoms object with given properties. """ if self._unique_sites is None: self._compute_sites_symmetry() return self._unique_sites @sites.setter def sites(self, v): """ Set the sites property and update all other dependent properties (symbols, occupancy) according to the sites """ an = np.zeros(len(v), dtype= int) occ = {} for i,j in enumerate(v): occ[i] = j.occupation.as_dict an[i] = j.occupation.primary_atomic_number self.set_atomic_numbers(an) self.info['occupancy'] = occ self._unique_sites = v @property def potential(self): if self._potential is None: self._potential = potentials.Potential.from_atoms(self) return self._potential @potential.setter def potential(self, potential): self._potential = potential def reset_sprkkr_potential(self): for i in self.sites: i.reset() if self._potential: self._potential.reset(update_atoms = False) self._potential.set_from_atoms() #at the last - to avoid circular imports from ..potentials import potentials
607
51
146
6efc4514b8bf5309e10d1c14a895324a8a7222a8
2,369
py
Python
keywords.py
nickdrozd/ecio-lisp
690637f28f81c2e708075c5247d1598756aaadb2
[ "MIT" ]
null
null
null
keywords.py
nickdrozd/ecio-lisp
690637f28f81c2e708075c5247d1598756aaadb2
[ "MIT" ]
null
null
null
keywords.py
nickdrozd/ecio-lisp
690637f28f81c2e708075c5247d1598756aaadb2
[ "MIT" ]
null
null
null
''' It would be nice if this module didn't need to import anything, since it defines (part of) the syntax of the language, and that and that seems like something that should be completely abstract. But macros make it possible to alter the syntax at run-time, meaning that keyword dispatch has to be cognizant of the mutable state of the machine! ### Is it "cheating" to include keyword_dispatch? It would be trivial to unroll it into a big ugly list of branch-if statements, so it doesn't really add any expressive power. Still, to mollify the skeptic, keyword_dispatch can be imagined as a piece of specialized hardware. Further, it can be stipulated that its use is relatively expensive, thereby gaining some advantage for analyze-interpretation. ''' from env import is_macro from stats import dispatch_stats DEFINE_KEYS = 'define', 'def' ASS_KEYS = 'set!', 'ass!' LAMBDA_KEYS = 'lambda', 'λ', 'fun' IF_KEYS = 'if', BEGIN_KEYS = 'begin', 'progn' QUOTE_KEYS = 'quote', QUASIQUOTE_KEYS = 'quasiquote', 'qsq' UNQUOTE_KEYS = 'unquote', 'unq' SPLICE_KEYS = 'splice', 'spl' DEFMACRO_KEYS = 'defmacro', 'defmac' ### @dispatch_stats ### ###
23
73
0.662727
''' It would be nice if this module didn't need to import anything, since it defines (part of) the syntax of the language, and that and that seems like something that should be completely abstract. But macros make it possible to alter the syntax at run-time, meaning that keyword dispatch has to be cognizant of the mutable state of the machine! ### Is it "cheating" to include keyword_dispatch? It would be trivial to unroll it into a big ugly list of branch-if statements, so it doesn't really add any expressive power. Still, to mollify the skeptic, keyword_dispatch can be imagined as a piece of specialized hardware. Further, it can be stipulated that its use is relatively expensive, thereby gaining some advantage for analyze-interpretation. ''' from env import is_macro from stats import dispatch_stats DEFINE_KEYS = 'define', 'def' ASS_KEYS = 'set!', 'ass!' LAMBDA_KEYS = 'lambda', 'λ', 'fun' IF_KEYS = 'if', BEGIN_KEYS = 'begin', 'progn' QUOTE_KEYS = 'quote', QUASIQUOTE_KEYS = 'quasiquote', 'qsq' UNQUOTE_KEYS = 'unquote', 'unq' SPLICE_KEYS = 'splice', 'spl' DEFMACRO_KEYS = 'defmacro', 'defmac' ### @dispatch_stats def keyword_dispatch(expr): if is_var(expr): return 'EVAL_VAR' if is_num(expr): return 'EVAL_NUM' # else tag, *_ = expr keyword_groups = { DEFINE_KEYS : 'EVAL_DEF', ASS_KEYS : 'EVAL_ASS', LAMBDA_KEYS : 'EVAL_LAMBDA', IF_KEYS : 'EVAL_IF', BEGIN_KEYS : 'EVAL_BEGIN', QUOTE_KEYS : 'EVAL_QUOTE', QUASIQUOTE_KEYS : 'EVAL_QUASIQUOTE', DEFMACRO_KEYS : 'EVAL_DEFMACRO', } for group in keyword_groups: if tag in group: return keyword_groups[group] if is_macro(tag): return 'EVAL_MACRO' # default return 'EVAL_FUNC' ### def is_num(exp): try: return isinstance(int(exp), int) except (ValueError, TypeError): return False def is_var(exp): return isinstance(exp, str) def is_simple(expr): return is_num(expr) or is_var(expr) or expr == [] ### def has_tag(expr, tag_keys): try: return expr[0] in tag_keys except (TypeError, IndexError): return False def is_unquoted(expr): return has_tag(expr, UNQUOTE_KEYS) def is_splice(expr): return has_tag(expr, SPLICE_KEYS)
1,005
0
160
a4a01c70d5133fce209a28aa9ecb4130b579eb5e
3,601
py
Python
tests/test_pipelines.py
jtotoole/city-scrapers-core
0c091d91bf8883c6f361a19fbb055abc3b306835
[ "MIT" ]
null
null
null
tests/test_pipelines.py
jtotoole/city-scrapers-core
0c091d91bf8883c6f361a19fbb055abc3b306835
[ "MIT" ]
null
null
null
tests/test_pipelines.py
jtotoole/city-scrapers-core
0c091d91bf8883c6f361a19fbb055abc3b306835
[ "MIT" ]
null
null
null
from datetime import datetime, timedelta from unittest.mock import MagicMock import pytest from scrapy.exceptions import DropItem from city_scrapers_core.constants import CANCELLED from city_scrapers_core.decorators import ignore_jscalendar from city_scrapers_core.items import Meeting from city_scrapers_core.pipelines import ( DiffPipeline, JSCalendarPipeline, MeetingPipeline, ) from city_scrapers_core.spiders import CityScrapersSpider
33.654206
86
0.663982
from datetime import datetime, timedelta from unittest.mock import MagicMock import pytest from scrapy.exceptions import DropItem from city_scrapers_core.constants import CANCELLED from city_scrapers_core.decorators import ignore_jscalendar from city_scrapers_core.items import Meeting from city_scrapers_core.pipelines import ( DiffPipeline, JSCalendarPipeline, MeetingPipeline, ) from city_scrapers_core.spiders import CityScrapersSpider def test_ignore_jscalendar(): TEST_DICT = {"TEST": 1} TEST_JSCALENDAR = {"cityscrapers.org/id": 2} class MockPipeline: @ignore_jscalendar def func(self, item, spider): return TEST_DICT pipeline = MockPipeline() assert pipeline.func({}, None) == TEST_DICT assert pipeline.func(TEST_JSCALENDAR, None) == TEST_JSCALENDAR def test_meeting_pipeline_sets_end(): pipeline = MeetingPipeline() meeting = pipeline.process_item( Meeting(title="Test", start=datetime.now()), CityScrapersSpider(name="test") ) assert meeting["end"] > meeting["start"] now = datetime.now() meeting = pipeline.process_item( Meeting(title="Test", start=now, end=now), CityScrapersSpider(name="test") ) assert meeting["end"] > meeting["start"] def test_jscalendar_pipeline_links(): pipeline = JSCalendarPipeline() assert pipeline.create_links(Meeting(links=[], source="https://example.com")) == { "cityscrapers.org/source": {"href": "https://example.com", "title": "Source"} } assert pipeline.create_links( Meeting( links=[{"href": "https://example.org", "title": "Test"}], source="https://example.com", ) ) == { "https://example.org": {"href": "https://example.org", "title": "Test"}, "cityscrapers.org/source": {"href": "https://example.com", "title": "Source"}, } def test_jscalendar_pipeline_duration(): pipeline = JSCalendarPipeline() start = datetime.now() end_1 = start + timedelta(days=1, hours=2, minutes=3) end_2 = start + timedelta(hours=3, minutes=5, seconds=20) assert pipeline.create_duration(Meeting(start=start, end=end_1)) == "P1DT2H3M" assert pipeline.create_duration(Meeting(start=start, end=end_2)) == "PT3H5M" def test_diff_merges_uids(): spider_mock = MagicMock() spider_mock._previous_map = {"1": "TEST", "2": "TEST"} pipeline = DiffPipeline(None) pipeline.previous_map = {"1": "TEST", "2": "TEST"} items = [{"id": "1"}, Meeting(id="2"), {"id": "3"}, Meeting(id="4")] results = [pipeline.process_item(item, spider_mock) for item in items] assert all("uid" in r for r in results[:2]) and all( "uid" not in r for r in results[2:] ) def test_diff_ignores_previous_items(): now = datetime.now() pipeline = DiffPipeline(None) spider_mock = MagicMock() previous = { "cityscrapers.org/id": "1", "start": (now - timedelta(days=1)).strftime("%Y-%m-%dT%H:%M:%S"), } spider_mock._previous_results = [previous] with pytest.raises(DropItem): pipeline.process_item(previous, spider_mock) def test_diff_cancels_upcoming_previous_items(): now = datetime.now() pipeline = DiffPipeline(None) spider_mock = MagicMock() previous = { "cityscrapers.org/id": "1", "start": (now + timedelta(days=1)).strftime("%Y-%m-%dT%H:%M:%S"), } spider_mock.previous_results = [previous] result = pipeline.process_item(previous, spider_mock) assert result["cityscrapers.org/id"] == "1" assert result["status"] == CANCELLED
2,979
0
161
b694cb291fbb8443812a8b09cce12006b98ee15d
1,746
py
Python
locations/spiders/completecash.py
davidchiles/alltheplaces
6f35f6cd652e7462107ead0a77f322caff198653
[ "MIT" ]
297
2017-12-07T01:29:14.000Z
2022-03-29T06:58:01.000Z
locations/spiders/completecash.py
davidchiles/alltheplaces
6f35f6cd652e7462107ead0a77f322caff198653
[ "MIT" ]
2,770
2017-11-28T04:20:21.000Z
2022-03-31T11:29:16.000Z
locations/spiders/completecash.py
davidchiles/alltheplaces
6f35f6cd652e7462107ead0a77f322caff198653
[ "MIT" ]
111
2017-11-27T21:40:02.000Z
2022-01-22T01:21:52.000Z
# -*- coding: utf-8 -*- import scrapy import json from locations.items import GeojsonPointItem from locations.hours import OpeningHours
34.92
96
0.61512
# -*- coding: utf-8 -*- import scrapy import json from locations.items import GeojsonPointItem from locations.hours import OpeningHours class CompleteCashSpider(scrapy.Spider): name = "completecash" item_attributes = { 'brand': "Complete Cash" } allowed_domains = ["locations.completecash.net"] cc_url = 'https://locations.completecash.net/api/5c1bc42410e9b07c77f0fab5/locations-details' base_url = 'https://locations.completecash.net/' start_urls = (cc_url, ) def get_opening_hours(self, days): o = OpeningHours() for day, hours in days.items(): short_day = day[:2] if hours: hours = hours[0] o.add_range(short_day, hours[0], hours[1]) return o.as_opening_hours() def parse_location(self, location): properties = location['properties'] opening_hours = self.get_opening_hours(properties['hoursOfOperation']) coordinates = location['geometry']['coordinates'] props = { 'addr_full': properties['addressLine1'] + '\n' + properties['addressLine2'], 'lat': coordinates[1], 'lon': coordinates[0], 'city': properties['city'], 'postcode': properties['postalCode'], 'state': properties['province'], 'phone': properties['phoneNumber'], 'ref': self.base_url + properties['slug'], 'website': self.base_url + properties['slug'], 'opening_hours': opening_hours } return GeojsonPointItem(**props) def parse(self, response): locations = json.loads(response.text)['features'] for location in locations: yield self.parse_location(location)
1,172
413
23
6602886e8a75448ee673f2761014a87e1f48330d
3,831
py
Python
morse-stf/unittest/test_module_transform.py
alipay/Antchain-MPC
f6916465e1da5722ca7efadc4eeaca13ec229707
[ "Apache-2.0" ]
33
2021-11-23T09:04:03.000Z
2022-03-14T07:56:31.000Z
morse-stf/unittest/test_module_transform.py
qizhi-zhang/Antchain-MPC
f551170f68b0baff328e6594484e9832230fe719
[ "Apache-2.0" ]
null
null
null
morse-stf/unittest/test_module_transform.py
qizhi-zhang/Antchain-MPC
f551170f68b0baff328e6594484e9832230fe719
[ "Apache-2.0" ]
6
2021-11-25T12:38:41.000Z
2022-02-23T03:29:51.000Z
import unittest from stensorflow.basic.protocol.module_transform import module_transform,\ module_transform_withPRF import numpy as np from stensorflow.basic.basic_class.base import SharedTensorBase, SharedPairBase from stensorflow.global_var import StfConfig import tensorflow as tf from stensorflow.engine.start_server import start_local_server import os start_local_server(os.path.join(os.environ.get("stf_home", ".."), "conf", "config.json")) if __name__ == '__main__': unittest.main()
34.513514
94
0.656487
import unittest from stensorflow.basic.protocol.module_transform import module_transform,\ module_transform_withPRF import numpy as np from stensorflow.basic.basic_class.base import SharedTensorBase, SharedPairBase from stensorflow.global_var import StfConfig import tensorflow as tf from stensorflow.engine.start_server import start_local_server import os start_local_server(os.path.join(os.environ.get("stf_home", ".."), "conf", "config.json")) class MyTestCase(unittest.TestCase): def setUp(self): self.sess = tf.compat.v1.Session("grpc://0.0.0.0:8887") def tearDown(self): self.sess.close() def test_module_transform(self): with tf.device(StfConfig.workerL[0]): a = np.random.random_integers(low=0, high=1, size=[8]) x = SharedTensorBase(module=2, inner_value=tf.constant(a, dtype='int64')) with tf.device(StfConfig.workerR[0]): b = np.random.random_integers(low=0, high=1, size=[8]) y = SharedTensorBase(module=2, inner_value=tf.constant(b, dtype='int64')) z = SharedPairBase(ownerL="L", ownerR="R", fixedpoint=0, xL=x, xR=y) w = module_transform(z, new_module=7, compress_flag=False) init_op = tf.compat.v1.global_variables_initializer() self.sess.run(init_op) self.assertLess(np.sum(np.power(self.sess.run(w.to_tf_tensor("R"))-(a+b)%2, 2)), 1E-3) def test_module_transform_compress(self): with tf.device(StfConfig.workerL[0]): a = np.random.random_integers(low=0, high=1, size=[8]) x = SharedTensorBase(module=2, inner_value=tf.constant(a, dtype='int64')) with tf.device(StfConfig.workerR[0]): b = np.random.random_integers(low=0, high=1, size=[8]) y = SharedTensorBase(module=2, inner_value=tf.constant(b, dtype='int64')) z = SharedPairBase(ownerL="L", ownerR="R", fixedpoint=0, xL=x, xR=y) w = module_transform(z, new_module=7, compress_flag=True) init_op = tf.compat.v1.global_variables_initializer() self.sess.run(init_op) self.assertLess(np.sum(np.power(self.sess.run(w.to_tf_tensor("R"))-(a+b)%2, 2)), 1E-3) def test_module_transform_withPRF(self): with tf.device(StfConfig.workerL[0]): a = np.random.random_integers(low=0, high=1, size=[8]) x = SharedTensorBase(module=2, inner_value=tf.constant(a, dtype='int64')) with tf.device(StfConfig.workerR[0]): b = np.random.random_integers(low=0, high=1, size=[8]) y = SharedTensorBase(module=2, inner_value=tf.constant(b, dtype='int64')) z = SharedPairBase(ownerL="L", ownerR="R", fixedpoint=0, xL=x, xR=y) w = module_transform_withPRF(z, new_module=7, compress_flag=False) init_op = tf.compat.v1.global_variables_initializer() self.sess.run(init_op) self.assertLess(np.sum(np.power(self.sess.run(w.to_tf_tensor("R"))-(a+b)%2, 2)), 1E-3) def test_module_transform_compress_withPRF(self): with tf.device(StfConfig.workerL[0]): a = np.random.random_integers(low=0, high=1, size=[8]) x = SharedTensorBase(module=2, inner_value=tf.constant(a, dtype='int64')) with tf.device(StfConfig.workerR[0]): b = np.random.random_integers(low=0, high=1, size=[8]) y = SharedTensorBase(module=2, inner_value=tf.constant(b, dtype='int64')) z = SharedPairBase(ownerL="L", ownerR="R", fixedpoint=0, xL=x, xR=y) w = module_transform_withPRF(z, new_module=7, compress_flag=True) init_op = tf.compat.v1.global_variables_initializer() self.sess.run(init_op) self.assertLess(np.sum(np.power(self.sess.run(w.to_tf_tensor("R"))-(a+b)%2, 2)), 1E-3) if __name__ == '__main__': unittest.main()
3,117
15
184
6f1949c5cd4540ba7606c03aa6bf62c2b044d07c
9,006
py
Python
examples/tensorflow/nlp/transformer_lt/quantization/ptq/main.py
huggingface/neural-compressor
aaad4c357a86914ffa583753c9a26d949838a2a5
[ "Apache-2.0" ]
172
2021-09-14T18:34:17.000Z
2022-03-30T06:49:53.000Z
examples/tensorflow/nlp/transformer_lt/quantization/ptq/main.py
intel/lp-opt-tool
130eefa3586b38df6c0ff78cc8807ae273f6a63f
[ "Apache-2.0" ]
40
2021-09-14T02:26:12.000Z
2022-03-29T08:34:04.000Z
examples/tensorflow/nlp/transformer_lt/quantization/ptq/main.py
intel/neural-compressor
16a4a12045fcb468da4d33769aff2c1a5e2ba6ba
[ "Apache-2.0" ]
33
2021-09-15T07:27:25.000Z
2022-03-25T08:30:57.000Z
# # -*- coding: utf-8 -*- # # Copyright (c) 2021 Intel Corporation # # 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 time import sys import numpy as np import unicodedata import six import re import tensorflow as tf from absl import app from argparse import ArgumentParser import pandas as pd from utils import tokenizer from utils.tokenizer import Subtokenizer from utils import metrics flags = tf.compat.v1.flags FLAGS = flags.FLAGS flags.DEFINE_integer("batch_size", 64, "run batch size") flags.DEFINE_string("input_graph", None, "The path of input model file.") flags.DEFINE_string("inputs_file", None, "File saved to an output file.") flags.DEFINE_string("reference_file", None, "File containing reference translation.") flags.DEFINE_string("vocab_file", None, "Path to subtoken vocabulary file.") flags.DEFINE_string("config", None, "Config json file") flags.DEFINE_string("output_model", None, "The output model of the quantized model.") flags.DEFINE_string("mode", "tune", "One of three options: 'benchmark'/'accuracy'/'tune'.") flags.DEFINE_integer("iters", -1, "The iteration used for benchmark.") uregex = UnicodeRegex() def collate_fn(batch): """Puts each data field into a pd frame with outer dimension batch size""" elem = batch[0] if isinstance(elem, tuple): batch = zip(*batch) return [collate_fn(samples) for samples in batch] elif isinstance(elem, np.ndarray): return [list(elem) for elem in batch] elif isinstance(elem, str): return batch else: return pd.DataFrame(batch).fillna(0).values.astype(np.int32) if __name__ == "__main__": tf.compat.v1.app.run()
36.314516
89
0.622252
# # -*- coding: utf-8 -*- # # Copyright (c) 2021 Intel Corporation # # 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 time import sys import numpy as np import unicodedata import six import re import tensorflow as tf from absl import app from argparse import ArgumentParser import pandas as pd from utils import tokenizer from utils.tokenizer import Subtokenizer from utils import metrics flags = tf.compat.v1.flags FLAGS = flags.FLAGS flags.DEFINE_integer("batch_size", 64, "run batch size") flags.DEFINE_string("input_graph", None, "The path of input model file.") flags.DEFINE_string("inputs_file", None, "File saved to an output file.") flags.DEFINE_string("reference_file", None, "File containing reference translation.") flags.DEFINE_string("vocab_file", None, "Path to subtoken vocabulary file.") flags.DEFINE_string("config", None, "Config json file") flags.DEFINE_string("output_model", None, "The output model of the quantized model.") flags.DEFINE_string("mode", "tune", "One of three options: 'benchmark'/'accuracy'/'tune'.") flags.DEFINE_integer("iters", -1, "The iteration used for benchmark.") class UnicodeRegex(object): def __init__(self): punctuation = self.property_chars("P") self.nondigit_punct_re = re.compile(r"([^\d])([" + punctuation + r"])") self.punct_nondigit_re = re.compile(r"([" + punctuation + r"])([^\d])") self.symbol_re = re.compile("([" + self.property_chars("S") + "])") def property_chars(self, prefix): return "".join(six.unichr(x) for x in range(sys.maxunicode) if unicodedata.category(six.unichr(x)).startswith(prefix)) uregex = UnicodeRegex() def bleu_tokenize(string): string = uregex.nondigit_punct_re.sub(r"\1 \2 ", string) string = uregex.punct_nondigit_re.sub(r" \1 \2", string) string = uregex.symbol_re.sub(r" \1 ", string) return string.split() class bleu(object): def __init__(self): self.translations = [] self.labels = [] def reset(self): self.translations = [] self.labels = [] def update(self, pred, label): if len(label) != len(pred): raise ValueError("Reference and translation files have different number " "of lines. If training only a few steps (100-200), the " "translation may be empty.") label = [x.lower() for x in label] pred = [x.lower() for x in pred] label = [bleu_tokenize(x) for x in label] pred = [bleu_tokenize(x) for x in pred] self.labels.extend(label) self.translations.extend(pred) def result(self): return metrics.compute_bleu(self.labels, self.translations) * 100 def collate_fn(batch): """Puts each data field into a pd frame with outer dimension batch size""" elem = batch[0] if isinstance(elem, tuple): batch = zip(*batch) return [collate_fn(samples) for samples in batch] elif isinstance(elem, np.ndarray): return [list(elem) for elem in batch] elif isinstance(elem, str): return batch else: return pd.DataFrame(batch).fillna(0).values.astype(np.int32) def load_graph(file_name): tf.compat.v1.logging.info('Loading graph from: ' + file_name) with tf.io.gfile.GFile(file_name, "rb") as f: graph_def = tf.compat.v1.GraphDef() graph_def.ParseFromString(f.read()) with tf.Graph().as_default() as graph: tf.import_graph_def(graph_def, name='') return graph def eval_func(infer_graph, iteration=-1): if isinstance(infer_graph, tf.compat.v1.GraphDef): graph = tf.Graph() with graph.as_default(): tf.import_graph_def(infer_graph, name='') infer_graph = graph subtokenizer = Subtokenizer(FLAGS.vocab_file) input_tensor = infer_graph.get_tensor_by_name('input_tensor:0') output_tensor = infer_graph.get_tensor_by_name(\ 'model/Transformer/strided_slice_19:0') ds = Dataset(FLAGS.inputs_file, FLAGS.reference_file, FLAGS.vocab_file) from neural_compressor.data import DATALOADERS dataloader = DATALOADERS['tensorflow'](ds, batch_size=FLAGS.batch_size, collate_fn=collate_fn) config = tf.compat.v1.ConfigProto() config.use_per_session_threads = 1 config.inter_op_parallelism_threads = 1 sess = tf.compat.v1.Session(graph=infer_graph, config=config) time_list = [] bleu_eval = bleu() predictions = [] labels = [] warmup = 10 if iteration != -1: assert iteration >= warmup, 'iteration must be larger than warmup' for idx, (input_data, label) in enumerate(dataloader): if idx < iteration or iteration == -1: time_start = time.time() out = sess.run([output_tensor], {input_tensor: input_data}) duration = time.time() - time_start time_list.append(duration) predictions.append(out) labels.extend(label) else: break latency = np.array(time_list[warmup: ]).mean() / FLAGS.batch_size print('Batch size = {}'.format(FLAGS.batch_size)) print('Latency: {:.3f} ms'.format(latency * 1000)) print('Throughput: {:.3f} items/sec'.format(1./ latency)) # only calculate accuracy when running out all predictions if iteration == -1: decode = [] for i,tr in enumerate(predictions): for j,itr in enumerate(tr): for k, otr in enumerate(itr): try: index = list(otr).index(tokenizer.EOS_ID) decode.append(subtokenizer.decode(otr[:index])) except: decode.append(subtokenizer.decode(otr)) bleu_eval.update(decode, labels) print('Accuracy is {:.3f}'.format(bleu_eval.result())) return bleu_eval.result() class Dataset(object): def __init__(self, inputs_file, reference_file, vocab_file): with tf.io.gfile.GFile(inputs_file) as f: records = f.read().split("\n") inputs = [record.strip() for record in records] if not inputs[-1]: inputs.pop() self.ref_lines = tokenizer.native_to_unicode( tf.io.gfile.GFile(reference_file).read()).strip().splitlines() subtokenizer = Subtokenizer(vocab_file) self.batch = [] token_lens=[] for i, line in enumerate(inputs): enc = subtokenizer.encode(line, add_eos=True) token_lens.append((i, len(enc))) sorted_by_token_input_lens = sorted(token_lens, key=lambda x: x[1], reverse=True) sorted_inputs = [None] * len(sorted_by_token_input_lens) sorted_keys = [0] * len(sorted_by_token_input_lens) lines = [] for i, (index, _) in enumerate(sorted_by_token_input_lens): sorted_inputs[i] = inputs[index] sorted_keys[index] = i enc=subtokenizer.encode(sorted_inputs[i], add_eos=True) lines.append([enc]) for i in sorted_keys: self.batch.append(lines[i]) def __getitem__(self, index): data = self.batch[index] label = self.ref_lines[index] return data[0], label def __len__(self): return len(self.batch) def main(_): graph = load_graph(FLAGS.input_graph) if FLAGS.mode == 'tune': from neural_compressor.experimental import Quantization, common quantizer = Quantization(FLAGS.config) ds = Dataset(FLAGS.inputs_file, FLAGS.reference_file, FLAGS.vocab_file) quantizer.calib_dataloader = common.DataLoader(ds, collate_fn=collate_fn, \ batch_size=FLAGS.batch_size) quantizer.model = common.Model(graph) quantizer.eval_func = eval_func q_model = quantizer.fit() try: q_model.save(FLAGS.output_model) except Exception as e: print("Failed to save model due to {}".format(str(e))) elif FLAGS.mode == 'benchmark': eval_func(graph, FLAGS.iters) elif FLAGS.mode == 'accuracy': eval_func(graph, -1) if __name__ == "__main__": tf.compat.v1.app.run()
6,212
5
402
8e706fef2a79b9726e6db3ebb5cc1413501da498
185
py
Python
sghymnal/rosters/apps.py
shortnd/sghymnal
c10d9a7e2fda803dcb5046b9f7bc099f32b6c603
[ "MIT" ]
null
null
null
sghymnal/rosters/apps.py
shortnd/sghymnal
c10d9a7e2fda803dcb5046b9f7bc099f32b6c603
[ "MIT" ]
null
null
null
sghymnal/rosters/apps.py
shortnd/sghymnal
c10d9a7e2fda803dcb5046b9f7bc099f32b6c603
[ "MIT" ]
null
null
null
from django.apps import AppConfig from django.utils.translation import gettext_lazy as _
23.125
54
0.767568
from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class RostersConfig(AppConfig): name = "sghymnal.rosters" verbose_name = _("Rosters")
0
72
23
3c5e955fa472b2a174f33607d809afecce7166fb
15,418
py
Python
warmup4ie/warmup4ie.py
8osman/warmup4IE
4f36101c3273bac1d083104d4220902697b7cdf3
[ "Apache-2.0" ]
8
2019-02-23T09:52:00.000Z
2020-04-24T10:51:55.000Z
warmup4ie/warmup4ie.py
8osman/warmup4IE
4f36101c3273bac1d083104d4220902697b7cdf3
[ "Apache-2.0" ]
7
2019-02-23T16:40:24.000Z
2020-02-04T22:14:48.000Z
warmup4ie/warmup4ie.py
8osman/warmup4IE
4f36101c3273bac1d083104d4220902697b7cdf3
[ "Apache-2.0" ]
3
2019-11-08T12:06:13.000Z
2020-02-19T04:32:56.000Z
""" platform that offers a connection to a warmup4ie device. this platform is inspired by the following code: https://github.com/alyc100/SmartThingsPublic/tree/master/devicetypes/alyc100/\ warmup-4ie.src to setup this component, you need to register to warmup first. see https://my.warmup.com/login Then add to your configuration.yaml climate: - platform: warmup4ie name: YOUR_DESCRIPTION username: YOUR_E_MAIL_ADDRESS password: YOUR_PASSWORD location: YOUR_LOCATION_NAME room: YOUR_ROOM_NAME # the following issues are not yet implemented, since i have currently no need # for them # OPEN - holiday mode still missing # - commands for setting/retrieving programmed times missing """ import logging import requests _LOGGER = logging.getLogger(__name__) class Warmup4IEDevice(): """Representation of a warmup4ie device. According to the home assistant documentation this class should be packed and made available on PyPi. Perhaps later.... """ TOKEN_URL = 'https://api.warmup.com/apps/app/v1' URL = 'https://apil.warmup.com/graphql' APP_TOKEN = \ 'M=;He<Xtg"$}4N%5k{$:PD+WA"]D<;#PriteY|VTuA>_iyhs+vA"4lic{6-LqNM:' HEADER = {'user-agent': 'WARMUP_APP', 'accept-encoding': 'br, gzip, deflate', 'accept': '*/*', 'Connection': 'keep-alive', 'content-type': 'application/json', 'app-token': APP_TOKEN, 'app-version': '1.8.1', 'accept-language': 'de-de'} RUN_MODE = {0:'off', 1:'prog', 3:'fixed', 4:'frost', 5:'away'} #pylint: disable-msg=too-many-arguments def __init__(self, user, password, location, room, target_temp): """Initialize the climate device.""" _LOGGER.info("Setting up Warmup4IE component") self._user = user self._password = password self._location_name = location self._room_name = room self._target_temperature = target_temp self._warmup_access_token = None self._loc_id = None self._room = None self._current_temperature = 0 self._away = False self._on = True self.setup_finished = False token_ok = self._generate_access_token() location_ok = self._get_locations() room_ok = self.update_room() if token_ok and location_ok and room_ok: self.setup_finished = True def get_run_mode(self): """return current mode, e.g. 'off', 'fixed', 'prog'.""" if self._room is None: return 'off' return self.RUN_MODE[self._room['runModeInt']] def update_room(self): """Update room/device data for the given room name. """ # make sure the location is already configured if self._loc_id is None or \ self._warmup_access_token is None or \ self._room_name is None: return False body = { "query": "query QUERY{ user{ currentLocation: location { id name rooms{ id roomName runModeInt targetTemp currentTemp thermostat4ies {minTemp maxTemp}} }} } " } header_with_token = self.HEADER.copy() header_with_token['warmup-authorization'] = str(self._warmup_access_token) response = requests.post(url=self.URL, headers=header_with_token, json=body) # check if request was acceppted and if request was successful if response.status_code != 200 or \ response.json()['status'] != 'success': _LOGGER.error("updating new room failed, %s", response) return False # extract and store roomId for later use rooms = response.json()['data']['user']['currentLocation']['rooms'] room_updated = False for room in rooms: if room['roomName'] == self._room_name: self._room = room _LOGGER.info("Successfully updated data for room '%s' " "with ID %s", self._room['roomName'], self._room['id']) room_updated = True break if not room_updated: return False # update temperatures values self._target_temperature = int(self._room['targetTemp'])/10 self._target_temperature_low = int(self._room['thermostat4ies'][0]['minTemp'])/10 self._target_temperature_high = int(self._room['thermostat4ies'][0]['maxTemp'])/10 self._current_temperature = int(self._room['currentTemp'])/10 return True ''' def update_room(self): """Update room/device data for the given room name. """ # make sure the location is already configured if self._loc_id is None or \ self._warmup_access_token is None or \ self._room_name is None: return False body = { "account": { "email": self._user, "token": self._warmup_access_token}, "request": { "method": "getRooms", "locId": self._loc_id} } response = requests.post(url=self.TOKEN_URL, headers=self.HEADER, json=body) # check if request was acceppted and if request was successful if response.status_code != 200 or \ response.json()['status']['result'] != 'success': _LOGGER.error("updating room failed, %s", response) return False # extract and store roomId for later use rooms = response.json()['response']['rooms'] room_updated = False for room in rooms: if room['roomName'] == self._room_name: self._room = room _LOGGER.info("Successfully updated data for room '%s' " "with ID %s", self._room['roomName'], self._room['roomId']) room_updated = True break if not room_updated: return False # update temperatures values self._target_temperature = int(self._room['targetTemp'])/10 self._target_temperature_low = int(self._room['minTemp'])/10 self._target_temperature_high = int(self._room['maxTemp'])/10 self._current_temperature = int(self._room['currentTemp'])/10 return True ''' def get_target_temmperature(self): """return target temperature""" return self._target_temperature def get_current_temmperature(self): """return currrent temperature""" return self._current_temperature def get_target_temperature_low(self): """return minimum temperature""" return self._target_temperature_low def get_target_temperature_high(self): """return maximum temperature""" return self._target_temperature_high def _generate_access_token(self): """retrieve access token from server""" body = {'request': {'email': self._user, 'password': self._password, 'method': 'userLogin', 'appId': 'WARMUP-APP-V001'} } response = requests.post(url=self.TOKEN_URL, headers=self.HEADER, json=body) # check if request was acceppted and if request was successful if response.status_code != 200 or \ response.json()['status']['result'] != 'success': _LOGGER.error("generating AccessToken failed, %s", response) return False # extract and store access token for later use self._warmup_access_token = response.json()['response']['token'] return True def _get_locations(self): """retrieve location ID that corrresponds to self._location_name""" # make sure we have an accessToken if self._warmup_access_token is None: return False body = { "account": { "email": self._user, "token": self._warmup_access_token }, "request": { "method": "getLocations" } } response = requests.post(url=self.TOKEN_URL, headers=self.HEADER, json=body) # check if request was acceppted and if request was successful if response.status_code != 200 or \ response.json()['status']['result'] != 'success': _LOGGER.error("initialising failed, %s", response) return False # extract and store locationId for later use locations = response.json()['response']['locations'] for loc in locations: if loc['name'] == self._location_name: self._loc_id = loc['id'] _LOGGER.info( "Successfully fetched location ID %s for location '%s'", self._loc_id, self._location_name) break if self._loc_id is None: return False return True def set_new_temperature(self, new_temperature): """set new target temperature""" # make sure the room/device is already configured if self._room is None or self._warmup_access_token is None: return body = { "account": { "email": self._user, "token": self._warmup_access_token }, "request": { "method": "setProgramme", "roomId": self._room['id'], "roomMode": "fixed", "fixed": { "fixedTemp": "{:03d}".format(int(new_temperature * 10)) } } } response = requests.post(url=self.TOKEN_URL, headers=self.HEADER, json=body) # check if request was acceppted and if request was successful if response.status_code != 200 or \ response.json()['status']['result'] != 'success': _LOGGER.error( "Setting new target temperature failed, %s", response) return response_temp = response.json()["message"]["targetTemp"] if new_temperature != int(response_temp)/10: _LOGGER.info("Server declined to set new target temperature " "to %.1f°C; response from server: '%s'", new_temperature, response.text) return self._target_temperature = new_temperature _LOGGER.info("Successfully set new target temperature to %.1f°C; " "response from server: '%s'", self._target_temperature, response.text) def set_temperature_to_auto(self): """set device to automatic mode""" # make sure the room/device is already configured if self._room is None or self._warmup_access_token is None: return body = { "account": { "email": self._user, "token": self._warmup_access_token }, "request": { "method": "setProgramme", "roomId": self._room['id'], "roomMode": "prog" } } response = requests.post(url=self.TOKEN_URL, headers=self.HEADER, json=body) # check if request was acceppted and if request was successful if response.status_code != 200 or \ response.json()['status']['result'] != 'success': _LOGGER.error( "Setting new target temperature to auto failed, %s", response) return _LOGGER.info("Successfully set new target temperature to auto, " "response from server: '%s'", response.text) def set_temperature_to_manual(self): """set device to manual mode""" # make sure the room/device is already configured if self._room is None or self._warmup_access_token is None: return body = { "account": { "email": self._user, "token": self._warmup_access_token }, "request": { "method": "setProgramme", "roomId": self._room['id'], "roomMode": "fixed" } } response = requests.post(url=self.TOKEN_URL, headers=self.HEADER, json=body) # check if request was acceppted and if request was successful if response.status_code != 200 or \ response.json()['status']['result'] != 'success': _LOGGER.error( "Setting new target temperature to " "manual failed, %s", response) return _LOGGER.info("Successfully set new target temperature to manual, " "response from server: '%s'", response.text) def set_location_to_frost(self): """set device to frost protection mode""" # make sure the room/device is already configured if self._loc_id is None or self._warmup_access_token is None: return body = { "account": { "email": self._user, "token": self._warmup_access_token }, "request": { "method": "setModes", "values": { "holEnd": "-", "fixedTemp": "", "holStart": "-", "geoMode": "0", "holTemp": "-", "locId": self._loc_id, "locMode": "frost" } } } response = requests.post(url=self.TOKEN_URL, headers=self.HEADER, json=body) # check if request was acceppted and if request was successful if response.status_code != 200 or \ response.json()['status']['result'] != 'success': _LOGGER.error( "Setting location to frost protection failed, %s", response) return _LOGGER.info("Successfully set location to frost protection, response " "from server: '%s'", response.text) def set_location_to_off(self): """ turn off device""" # make sure the room/device is already configured if self._loc_id is None or self._warmup_access_token is None: return body = { "account": { "email": self._user, "token": self._warmup_access_token }, "request": { "method": "setModes", "values": { "holEnd": "-", "fixedTemp": "", "holStart": "-", "geoMode": "0", "holTemp": "-", "locId": self._loc_id, "locMode": "off" } } } response = requests.post(url=self.TOKEN_URL, headers=self.HEADER, json=body) # check if request was acceppted and if request was successful if response.status_code != 200 or \ response.json()['status']['result'] != 'success': _LOGGER.error("Setting location to off mode failed, %s", response) return _LOGGER.info("Successfully set location to off mode, " "response from server: '%s'", response.text)
38.545
176
0.55526
""" platform that offers a connection to a warmup4ie device. this platform is inspired by the following code: https://github.com/alyc100/SmartThingsPublic/tree/master/devicetypes/alyc100/\ warmup-4ie.src to setup this component, you need to register to warmup first. see https://my.warmup.com/login Then add to your configuration.yaml climate: - platform: warmup4ie name: YOUR_DESCRIPTION username: YOUR_E_MAIL_ADDRESS password: YOUR_PASSWORD location: YOUR_LOCATION_NAME room: YOUR_ROOM_NAME # the following issues are not yet implemented, since i have currently no need # for them # OPEN - holiday mode still missing # - commands for setting/retrieving programmed times missing """ import logging import requests _LOGGER = logging.getLogger(__name__) class Warmup4IEDevice(): """Representation of a warmup4ie device. According to the home assistant documentation this class should be packed and made available on PyPi. Perhaps later.... """ TOKEN_URL = 'https://api.warmup.com/apps/app/v1' URL = 'https://apil.warmup.com/graphql' APP_TOKEN = \ 'M=;He<Xtg"$}4N%5k{$:PD+WA"]D<;#PriteY|VTuA>_iyhs+vA"4lic{6-LqNM:' HEADER = {'user-agent': 'WARMUP_APP', 'accept-encoding': 'br, gzip, deflate', 'accept': '*/*', 'Connection': 'keep-alive', 'content-type': 'application/json', 'app-token': APP_TOKEN, 'app-version': '1.8.1', 'accept-language': 'de-de'} RUN_MODE = {0:'off', 1:'prog', 3:'fixed', 4:'frost', 5:'away'} #pylint: disable-msg=too-many-arguments def __init__(self, user, password, location, room, target_temp): """Initialize the climate device.""" _LOGGER.info("Setting up Warmup4IE component") self._user = user self._password = password self._location_name = location self._room_name = room self._target_temperature = target_temp self._warmup_access_token = None self._loc_id = None self._room = None self._current_temperature = 0 self._away = False self._on = True self.setup_finished = False token_ok = self._generate_access_token() location_ok = self._get_locations() room_ok = self.update_room() if token_ok and location_ok and room_ok: self.setup_finished = True def get_run_mode(self): """return current mode, e.g. 'off', 'fixed', 'prog'.""" if self._room is None: return 'off' return self.RUN_MODE[self._room['runModeInt']] def update_room(self): """Update room/device data for the given room name. """ # make sure the location is already configured if self._loc_id is None or \ self._warmup_access_token is None or \ self._room_name is None: return False body = { "query": "query QUERY{ user{ currentLocation: location { id name rooms{ id roomName runModeInt targetTemp currentTemp thermostat4ies {minTemp maxTemp}} }} } " } header_with_token = self.HEADER.copy() header_with_token['warmup-authorization'] = str(self._warmup_access_token) response = requests.post(url=self.URL, headers=header_with_token, json=body) # check if request was acceppted and if request was successful if response.status_code != 200 or \ response.json()['status'] != 'success': _LOGGER.error("updating new room failed, %s", response) return False # extract and store roomId for later use rooms = response.json()['data']['user']['currentLocation']['rooms'] room_updated = False for room in rooms: if room['roomName'] == self._room_name: self._room = room _LOGGER.info("Successfully updated data for room '%s' " "with ID %s", self._room['roomName'], self._room['id']) room_updated = True break if not room_updated: return False # update temperatures values self._target_temperature = int(self._room['targetTemp'])/10 self._target_temperature_low = int(self._room['thermostat4ies'][0]['minTemp'])/10 self._target_temperature_high = int(self._room['thermostat4ies'][0]['maxTemp'])/10 self._current_temperature = int(self._room['currentTemp'])/10 return True ''' def update_room(self): """Update room/device data for the given room name. """ # make sure the location is already configured if self._loc_id is None or \ self._warmup_access_token is None or \ self._room_name is None: return False body = { "account": { "email": self._user, "token": self._warmup_access_token}, "request": { "method": "getRooms", "locId": self._loc_id} } response = requests.post(url=self.TOKEN_URL, headers=self.HEADER, json=body) # check if request was acceppted and if request was successful if response.status_code != 200 or \ response.json()['status']['result'] != 'success': _LOGGER.error("updating room failed, %s", response) return False # extract and store roomId for later use rooms = response.json()['response']['rooms'] room_updated = False for room in rooms: if room['roomName'] == self._room_name: self._room = room _LOGGER.info("Successfully updated data for room '%s' " "with ID %s", self._room['roomName'], self._room['roomId']) room_updated = True break if not room_updated: return False # update temperatures values self._target_temperature = int(self._room['targetTemp'])/10 self._target_temperature_low = int(self._room['minTemp'])/10 self._target_temperature_high = int(self._room['maxTemp'])/10 self._current_temperature = int(self._room['currentTemp'])/10 return True ''' def get_target_temmperature(self): """return target temperature""" return self._target_temperature def get_current_temmperature(self): """return currrent temperature""" return self._current_temperature def get_target_temperature_low(self): """return minimum temperature""" return self._target_temperature_low def get_target_temperature_high(self): """return maximum temperature""" return self._target_temperature_high def _generate_access_token(self): """retrieve access token from server""" body = {'request': {'email': self._user, 'password': self._password, 'method': 'userLogin', 'appId': 'WARMUP-APP-V001'} } response = requests.post(url=self.TOKEN_URL, headers=self.HEADER, json=body) # check if request was acceppted and if request was successful if response.status_code != 200 or \ response.json()['status']['result'] != 'success': _LOGGER.error("generating AccessToken failed, %s", response) return False # extract and store access token for later use self._warmup_access_token = response.json()['response']['token'] return True def _get_locations(self): """retrieve location ID that corrresponds to self._location_name""" # make sure we have an accessToken if self._warmup_access_token is None: return False body = { "account": { "email": self._user, "token": self._warmup_access_token }, "request": { "method": "getLocations" } } response = requests.post(url=self.TOKEN_URL, headers=self.HEADER, json=body) # check if request was acceppted and if request was successful if response.status_code != 200 or \ response.json()['status']['result'] != 'success': _LOGGER.error("initialising failed, %s", response) return False # extract and store locationId for later use locations = response.json()['response']['locations'] for loc in locations: if loc['name'] == self._location_name: self._loc_id = loc['id'] _LOGGER.info( "Successfully fetched location ID %s for location '%s'", self._loc_id, self._location_name) break if self._loc_id is None: return False return True def set_new_temperature(self, new_temperature): """set new target temperature""" # make sure the room/device is already configured if self._room is None or self._warmup_access_token is None: return body = { "account": { "email": self._user, "token": self._warmup_access_token }, "request": { "method": "setProgramme", "roomId": self._room['id'], "roomMode": "fixed", "fixed": { "fixedTemp": "{:03d}".format(int(new_temperature * 10)) } } } response = requests.post(url=self.TOKEN_URL, headers=self.HEADER, json=body) # check if request was acceppted and if request was successful if response.status_code != 200 or \ response.json()['status']['result'] != 'success': _LOGGER.error( "Setting new target temperature failed, %s", response) return response_temp = response.json()["message"]["targetTemp"] if new_temperature != int(response_temp)/10: _LOGGER.info("Server declined to set new target temperature " "to %.1f°C; response from server: '%s'", new_temperature, response.text) return self._target_temperature = new_temperature _LOGGER.info("Successfully set new target temperature to %.1f°C; " "response from server: '%s'", self._target_temperature, response.text) def set_temperature_to_auto(self): """set device to automatic mode""" # make sure the room/device is already configured if self._room is None or self._warmup_access_token is None: return body = { "account": { "email": self._user, "token": self._warmup_access_token }, "request": { "method": "setProgramme", "roomId": self._room['id'], "roomMode": "prog" } } response = requests.post(url=self.TOKEN_URL, headers=self.HEADER, json=body) # check if request was acceppted and if request was successful if response.status_code != 200 or \ response.json()['status']['result'] != 'success': _LOGGER.error( "Setting new target temperature to auto failed, %s", response) return _LOGGER.info("Successfully set new target temperature to auto, " "response from server: '%s'", response.text) def set_temperature_to_manual(self): """set device to manual mode""" # make sure the room/device is already configured if self._room is None or self._warmup_access_token is None: return body = { "account": { "email": self._user, "token": self._warmup_access_token }, "request": { "method": "setProgramme", "roomId": self._room['id'], "roomMode": "fixed" } } response = requests.post(url=self.TOKEN_URL, headers=self.HEADER, json=body) # check if request was acceppted and if request was successful if response.status_code != 200 or \ response.json()['status']['result'] != 'success': _LOGGER.error( "Setting new target temperature to " "manual failed, %s", response) return _LOGGER.info("Successfully set new target temperature to manual, " "response from server: '%s'", response.text) def set_location_to_frost(self): """set device to frost protection mode""" # make sure the room/device is already configured if self._loc_id is None or self._warmup_access_token is None: return body = { "account": { "email": self._user, "token": self._warmup_access_token }, "request": { "method": "setModes", "values": { "holEnd": "-", "fixedTemp": "", "holStart": "-", "geoMode": "0", "holTemp": "-", "locId": self._loc_id, "locMode": "frost" } } } response = requests.post(url=self.TOKEN_URL, headers=self.HEADER, json=body) # check if request was acceppted and if request was successful if response.status_code != 200 or \ response.json()['status']['result'] != 'success': _LOGGER.error( "Setting location to frost protection failed, %s", response) return _LOGGER.info("Successfully set location to frost protection, response " "from server: '%s'", response.text) def set_location_to_off(self): """ turn off device""" # make sure the room/device is already configured if self._loc_id is None or self._warmup_access_token is None: return body = { "account": { "email": self._user, "token": self._warmup_access_token }, "request": { "method": "setModes", "values": { "holEnd": "-", "fixedTemp": "", "holStart": "-", "geoMode": "0", "holTemp": "-", "locId": self._loc_id, "locMode": "off" } } } response = requests.post(url=self.TOKEN_URL, headers=self.HEADER, json=body) # check if request was acceppted and if request was successful if response.status_code != 200 or \ response.json()['status']['result'] != 'success': _LOGGER.error("Setting location to off mode failed, %s", response) return _LOGGER.info("Successfully set location to off mode, " "response from server: '%s'", response.text)
0
0
0
3e3a6bd99c980ea91a4f3725fdd7bbf184965475
322
py
Python
exercises/exercise71.py
djangojeng-e/TIL
bdbe1dfb6ebc48b89067fddda195227cca64b8dc
[ "MIT" ]
null
null
null
exercises/exercise71.py
djangojeng-e/TIL
bdbe1dfb6ebc48b89067fddda195227cca64b8dc
[ "MIT" ]
null
null
null
exercises/exercise71.py
djangojeng-e/TIL
bdbe1dfb6ebc48b89067fddda195227cca64b8dc
[ "MIT" ]
null
null
null
number_list = [x for x in range(1, 21)] print(number_list) filtered_list = filter(lambda x: x%2==0, number_list) filtered_list = list(filtered_list) print(filtered_list) square_list = map(lambda x: x**2, filtered_list) square_list = list(square_list) print(square_list) # filter(func, iterable) # map(func, iterable)
21.466667
53
0.748447
number_list = [x for x in range(1, 21)] print(number_list) filtered_list = filter(lambda x: x%2==0, number_list) filtered_list = list(filtered_list) print(filtered_list) square_list = map(lambda x: x**2, filtered_list) square_list = list(square_list) print(square_list) # filter(func, iterable) # map(func, iterable)
0
0
0
653927e36e6c722e124ad7cab7a4b86aab936ffd
3,822
py
Python
songmass/evaluate/utils.py
hongwen-sun/muzic
50fb349e8ffe37212d9a3bfe6066f4c1e6657f3a
[ "MIT" ]
1,903
2021-09-22T18:43:49.000Z
2022-03-31T08:22:13.000Z
songmass/evaluate/utils.py
hongwen-sun/muzic
50fb349e8ffe37212d9a3bfe6066f4c1e6657f3a
[ "MIT" ]
33
2021-09-24T16:22:18.000Z
2022-03-30T09:35:20.000Z
songmass/evaluate/utils.py
hongwen-sun/muzic
50fb349e8ffe37212d9a3bfe6066f4c1e6657f3a
[ "MIT" ]
124
2021-09-24T08:56:56.000Z
2022-03-29T05:48:03.000Z
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. #
30.094488
113
0.570644
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # def get_pitch_duration_sequence(notes): seq = [] i = 0 while i < len(notes): if notes[i] > 128: i += 1 else: if i + 1 >= len(notes): break if notes[i + 1] <= 128: i += 1 else: pitch = str(notes[i]) duration = str(notes[i + 1]) seq.extend([pitch, duration]) i += 2 return seq def separate_sentences(x, find_structure=False, SEP='[sep]'): z = x.copy() separate_positions = [k for k, v in enumerate(z) if v == SEP] separate_positions.insert(0, -1) sents = [] for i in range(len(separate_positions) - 1): u, v = separate_positions[i] + 1, separate_positions[i + 1] sent = z[u:v] if find_structure: sent = list(map(int, sent)) sent = get_pitch_duration_sequence(sent) sents.append(sent) return sents def get_lyrics(lyric_file): with open(lyric_file, 'r') as input_file: lines = input_file.readlines() lyrics = list(map(lambda x : x.rstrip('\n').split(' '), lines)) return lyrics def get_song_ids(song_id_file): with open(song_id_file, 'r') as input_file: song_ids = input_file.readlines() song_ids = list(map(lambda x : int(x.rstrip('\n')), song_ids)) return song_ids def get_songs( melody_file, lyric_file=None, song_id_file=None, is_generated=False, get_last=False, find_structure=False, cut_exceed_sent=False, beam=5, SEP='[sep]', ALIGN='[align]', ): lyrics = get_lyrics(lyric_file) song_ids = get_song_ids(song_id_file) lyric_sents = list(map(lambda x : x.count(SEP), lyrics)) def to_tuple(x): pitch_duration = [i for i in x if i != SEP and i != ALIGN] pd_tuples = [(pitch_duration[2 * i], pitch_duration[2 * i + 1]) for i in range(len(pitch_duration) // 2)] return pd_tuples with open(melody_file, 'r') as input_file: melodies = input_file.readlines() if is_generated: melodies = list(filter(lambda x : x.startswith('H-'), melodies)) if len(melodies) == len(lyrics) * beam: melodies.sort(key = lambda x : (int(x.split('\t')[0].split('-')[1]), - float(x.split('\t')[1]))) melodies = [x for i, x in enumerate(melodies) if i % beam == 0] else: melodies.sort(key = lambda x : int(x.split('\t')[0].split('-')[1])) melodies = list(map(lambda x : x.rstrip('\n').split('\t')[-1], melodies)) assert len(melodies) == len(lyrics) melody_seqs = list(map(lambda x : x.rstrip('\n').split(' '), melodies)) melody_seqs = [i for i in melody_seqs if i != ALIGN] for i in range(len(melody_seqs)): melody_seqs[i] = list(filter(lambda x : x.isdigit() or x == SEP, melody_seqs[i])) if get_last: for i in range(len(melody_seqs)): if melody_seqs[i][-1] != SEP: melody_seqs[i].append(SEP) melody_seq_sents = list(map(lambda x : separate_sentences(x, find_structure=find_structure), melody_seqs)) song_seqs = [] for i, seq in enumerate(melody_seq_sents): if cut_exceed_sent and len(seq) > lyric_sents[i]: seq = seq[0 : lyric_sents[i]] song_seq = [] for k, sent in enumerate(seq): song_seq.extend(sent) song_seq.append(SEP) song_seqs.append(song_seq) song_num = song_ids[-1] + 1 songs = [[] for _ in range(song_num)] for k, v in enumerate(song_ids): songs[v].extend(song_seqs[k]) songs = list(map(to_tuple, songs)) return songs
3,602
0
115
0a726b63ad1860c147fe1887b629d9e01b8f5aa7
35,420
py
Python
kivymd/uix/textfield.py
surbhicis/KivyMD-1
23378fea5427d8616ed96397d148cb34fbbda73f
[ "MIT" ]
18
2020-03-14T18:26:45.000Z
2022-02-26T13:36:26.000Z
kivymd/uix/textfield.py
surbhicis/KivyMD-1
23378fea5427d8616ed96397d148cb34fbbda73f
[ "MIT" ]
null
null
null
kivymd/uix/textfield.py
surbhicis/KivyMD-1
23378fea5427d8616ed96397d148cb34fbbda73f
[ "MIT" ]
2
2020-03-15T13:09:58.000Z
2020-03-16T20:13:49.000Z
""" Components/Text Field ===================== .. seealso:: `Material Design spec, Text fields <https://material.io/components/text-fields>`_ .. rubric:: Text fields let users enter and edit text. .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-fields.png :align: center `KivyMD` provides the following field classes for use: - MDTextField_ - MDTextFieldRound_ - MDTextFieldRect_ .. Note:: :class:`~MDTextField` inherited from :class:`~kivy.uix.textinput.TextInput`. Therefore, most parameters and all events of the :class:`~kivy.uix.textinput.TextInput` class are also available in the :class:`~MDTextField` class. .. MDTextField: MDTextField ----------- :class:`~MDTextField` can be with helper text and without. Without helper text mode ------------------------ .. code-block:: kv MDTextField: hint_text: "No helper text" .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-no-helper-mode.gif :align: center Helper text mode on ``on_focus`` event -------------------------------------- .. code-block:: kv MDTextField: hint_text: "Helper text on focus" helper_text: "This will disappear when you click off" helper_text_mode: "on_focus" .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-helper-mode-on-focus.gif :align: center Persistent helper text mode --------------------------- .. code-block:: kv MDTextField: hint_text: "Persistent helper text" helper_text: "Text is always here" helper_text_mode: "persistent" .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-helper-mode-persistent.gif :align: center Helper text mode `'on_error'` ---------------------------- To display an error in a text field when using the ``helper_text_mode: "on_error"`` parameter, set the `"error"` text field parameter to `True`: .. code-block:: python from kivy.lang import Builder from kivymd.app import MDApp KV = ''' BoxLayout: padding: "10dp" MDTextField: id: text_field_error hint_text: "Helper text on error (press 'Enter')" helper_text: "There will always be a mistake" helper_text_mode: "on_error" pos_hint: {"center_y": .5} ''' class Test(MDApp): def __init__(self, **kwargs): super().__init__(**kwargs) self.screen = Builder.load_string(KV) def build(self): self.screen.ids.text_field_error.bind( on_text_validate=self.set_error_message, on_focus=self.set_error_message, ) return self.screen def set_error_message(self, instance_textfield): self.screen.ids.text_field_error.error = True Test().run() .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-helper-mode-on-error.gif :align: center Helper text mode `'on_error'` (with required) -------------------------------------------- .. code-block:: kv MDTextField: hint_text: "required = True" required: True helper_text_mode: "on_error" helper_text: "Enter text" .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-required.gif :align: center Text length control ------------------- .. code-block:: kv MDTextField: hint_text: "Max text length = 5" max_text_length: 5 .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-text-length.gif :align: center Multi line text --------------- .. code-block:: kv MDTextField: multiline: True hint_text: "Multi-line text" .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-text-multi-line.gif :align: center Color mode ---------- .. code-block:: kv MDTextField: hint_text: "color_mode = 'accent'" color_mode: 'accent' Available options are `'primary'`, `'accent'` or `'custom`'. .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-color-mode.gif :align: center .. code-block:: kv MDTextField: hint_text: "color_mode = 'custom'" color_mode: 'custom' helper_text_mode: "on_focus" helper_text: "Color is defined by 'line_color_focus' property" line_color_focus: 1, 0, 1, 1 .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-color-mode-custom.gif :align: center .. code-block:: kv MDTextField: hint_text: "Line color normal" line_color_normal: app.theme_cls.accent_color .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-line-color-normal.png :align: center Rectangle mode -------------- .. code-block:: kv MDTextField: hint_text: "Rectangle mode" mode: "rectangle" .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-rectangle-mode.gif :align: center .. MDTextFieldRect: MDTextFieldRect --------------- .. Note:: :class:`~MDTextFieldRect` inherited from :class:`~kivy.uix.textinput.TextInput`. You can use all parameters and attributes of the :class:`~kivy.uix.textinput.TextInput` class in the :class:`~MDTextFieldRect` class. .. code-block:: kv MDTextFieldRect: size_hint: 1, None height: "30dp" .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-rect.gif :align: center .. Warning:: While there is no way to change the color of the border. .. MDTextFieldRound: MDTextFieldRound ---------------- Without icon ------------ .. code-block:: kv MDTextFieldRound: hint_text: 'Empty field' .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-round.gif :align: center With left icon -------------- .. Warning:: The icons in the :class:`~MDTextFieldRound` are static. You cannot bind events to them. .. code-block:: kv MDTextFieldRound: icon_left: "email" hint_text: "Field with left icon" .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-round-left-icon.png :align: center With left and right icons ------------------------- .. code-block:: kv MDTextFieldRound: icon_left: 'key-variant' icon_right: 'eye-off' hint_text: 'Field with left and right icons' .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-round-left-right-icon.png :align: center Control background color ------------------------ .. code-block:: kv MDTextFieldRound: icon_left: 'key-variant' normal_color: app.theme_cls.accent_color .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-round-normal-color.gif :align: center .. code-block:: kv MDTextFieldRound: icon_left: 'key-variant' normal_color: app.theme_cls.accent_color color_active: 1, 0, 0, 1 .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-round-active-color.gif :align: center .. seealso:: See more information in the :class:`~MDTextFieldRect` class. """ __all__ = ( "MDTextField", "MDTextFieldRect", "MDTextFieldRound", ) import sys from kivy.uix.label import Label from kivy.uix.textinput import TextInput from kivy.animation import Animation from kivy.graphics.context_instructions import Color from kivy.lang import Builder from kivy.properties import ( NumericProperty, StringProperty, BooleanProperty, OptionProperty, ListProperty, ObjectProperty, ) from kivy.metrics import dp from kivy.metrics import sp from kivymd.font_definitions import theme_font_styles from kivymd.theming import ThemableBehavior from kivymd.uix.label import MDIcon Builder.load_string( """ #:import images_path kivymd.images_path <MDTextField> canvas.before: Clear Color: rgba: self.line_color_normal if root.mode == "line" else [0, 0, 0, 0] Line: points: self.x, self.y + dp(16), self.x + self.width, self.y + dp(16) width: 1 dash_length: dp(3) dash_offset: 2 if self.disabled else 0 Color: rgba: self._current_line_color if root.mode == "line" else [0, 0, 0, 0] Rectangle: size: self._line_width, dp(2) pos: self.center_x - (self._line_width / 2), self.y + dp(16) Color: rgba: self._current_error_color Rectangle: texture: self._msg_lbl.texture size: self._msg_lbl.texture_size pos: self.x, self.y Color: rgba: self._current_right_lbl_color Rectangle: texture: self._right_msg_lbl.texture size: self._right_msg_lbl.texture_size pos: self.width-self._right_msg_lbl.texture_size[0]+dp(45), self.y Color: rgba: (self._current_line_color if self.focus and not \ self._cursor_blink else (0, 0, 0, 0)) Rectangle: pos: [int(x) for x in self.cursor_pos] size: 1, -self.line_height Color: rgba: self._current_hint_text_color Rectangle: texture: self._hint_lbl.texture size: self._hint_lbl.texture_size pos: self.x, self.y + self.height - self._hint_y Color: rgba: self.disabled_foreground_color if self.disabled else\ (self.hint_text_color if not self.text and not\ self.focus else self.foreground_color) Color: rgba: self._current_line_color Line: width: dp(1) if root.mode == "rectangle" else dp(0.00001) points: ( self.x + root._line_blank_space_right_hint_text, self.top - self._hint_lbl.texture_size[1] // 2, self.right + dp(12), self.top - self._hint_lbl.texture_size[1] // 2, self.right + dp(12), self.y, self.x - dp(12), self.y, self.x - dp(12), self.top - self._hint_lbl.texture_size[1] // 2, self.x + root._line_blank_space_left_hint_text, self.top - self._hint_lbl.texture_size[1] // 2 ) font_name: 'Roboto' foreground_color: app.theme_cls.text_color font_size: sp(16) bold: False padding: 0, dp(16), 0, dp(10) multiline: False size_hint_y: None height: self.minimum_height + dp(8) <TextfieldLabel> size_hint_x: None width: self.texture_size[0] shorten: True shorten_from: "right" <MDTextFieldRect> on_focus: root.anim_rect([root.x, root.y, root.right, root.y, root.right,\ root.top, root.x, root.top, root.x, root.y], 1) if root.focus\ else root.anim_rect([root.x - dp(60), root.y - dp(60),\ root.right + dp(60), root.y - dp(60), root.right + dp(60), root.top + dp(60),\ root.x - dp(60), root.top + dp(60),\ root.x - dp(60), root.y - dp(60)], 0) canvas.after: Color: rgba: root._primary_color Line: width: dp(1.5) points: ( self.x - dp(60), self.y - dp(60), self.right + dp(60), self.y - dp(60), self.right + dp(60), self.top + dp(60), self.x - dp(60), self.top + dp(60), self.x - dp(60), self.y - dp(60) ) <MDTextFieldRound>: multiline: False size_hint: 1, None height: self.line_height + dp(10) background_active: f'{images_path}transparent.png' background_normal: f'{images_path}transparent.png' padding: self._lbl_icon_left.texture_size[1] + dp(10) if self.icon_left else dp(15), \ (self.height / 2) - (self.line_height / 2), \ self._lbl_icon_right.texture_size[1] + dp(20) if self.icon_right else dp(15), \ 0 canvas.before: Color: rgba: self.normal_color if not self.focus else self._color_active Ellipse: angle_start: 180 angle_end: 360 pos: self.pos[0] - self.size[1] / 2, self.pos[1] size: self.size[1], self.size[1] Ellipse: angle_start: 360 angle_end: 540 pos: self.size[0] + self.pos[0] - self.size[1]/2.0, self.pos[1] size: self.size[1], self.size[1] Rectangle: pos: self.pos size: self.size Color: rgba: self.line_color Line: points: self.pos[0] , self.pos[1], self.pos[0] + self.size[0], self.pos[1] Line: points: self.pos[0], self.pos[1] + self.size[1], self.pos[0] + self.size[0], self.pos[1] + self.size[1] Line: ellipse: self.pos[0] - self.size[1] / 2, self.pos[1], self.size[1], self.size[1], 180, 360 Line: ellipse: self.size[0] + self.pos[0] - self.size[1] / 2.0, self.pos[1], self.size[1], self.size[1], 360, 540 # Texture of left Icon. Color: rgba: self.icon_left_color Rectangle: texture: self._lbl_icon_left.texture size: self._lbl_icon_left.texture_size if self.icon_left \ else (0, 0) pos: self.x, \ self.center[1] - self._lbl_icon_right.texture_size[1] / 2 # Texture of right Icon. Color: rgba: self.icon_right_color Rectangle: texture: self._lbl_icon_right.texture size: self._lbl_icon_right.texture_size if self.icon_right \ else (0, 0) pos: (self.width + self.x) - (self._lbl_icon_right.texture_size[1]), \ self.center[1] - self._lbl_icon_right.texture_size[1] / 2 Color: rgba: root.theme_cls.disabled_hint_text_color if not self.focus \ else root.foreground_color """ )
32.3766
119
0.577414
""" Components/Text Field ===================== .. seealso:: `Material Design spec, Text fields <https://material.io/components/text-fields>`_ .. rubric:: Text fields let users enter and edit text. .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-fields.png :align: center `KivyMD` provides the following field classes for use: - MDTextField_ - MDTextFieldRound_ - MDTextFieldRect_ .. Note:: :class:`~MDTextField` inherited from :class:`~kivy.uix.textinput.TextInput`. Therefore, most parameters and all events of the :class:`~kivy.uix.textinput.TextInput` class are also available in the :class:`~MDTextField` class. .. MDTextField: MDTextField ----------- :class:`~MDTextField` can be with helper text and without. Without helper text mode ------------------------ .. code-block:: kv MDTextField: hint_text: "No helper text" .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-no-helper-mode.gif :align: center Helper text mode on ``on_focus`` event -------------------------------------- .. code-block:: kv MDTextField: hint_text: "Helper text on focus" helper_text: "This will disappear when you click off" helper_text_mode: "on_focus" .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-helper-mode-on-focus.gif :align: center Persistent helper text mode --------------------------- .. code-block:: kv MDTextField: hint_text: "Persistent helper text" helper_text: "Text is always here" helper_text_mode: "persistent" .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-helper-mode-persistent.gif :align: center Helper text mode `'on_error'` ---------------------------- To display an error in a text field when using the ``helper_text_mode: "on_error"`` parameter, set the `"error"` text field parameter to `True`: .. code-block:: python from kivy.lang import Builder from kivymd.app import MDApp KV = ''' BoxLayout: padding: "10dp" MDTextField: id: text_field_error hint_text: "Helper text on error (press 'Enter')" helper_text: "There will always be a mistake" helper_text_mode: "on_error" pos_hint: {"center_y": .5} ''' class Test(MDApp): def __init__(self, **kwargs): super().__init__(**kwargs) self.screen = Builder.load_string(KV) def build(self): self.screen.ids.text_field_error.bind( on_text_validate=self.set_error_message, on_focus=self.set_error_message, ) return self.screen def set_error_message(self, instance_textfield): self.screen.ids.text_field_error.error = True Test().run() .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-helper-mode-on-error.gif :align: center Helper text mode `'on_error'` (with required) -------------------------------------------- .. code-block:: kv MDTextField: hint_text: "required = True" required: True helper_text_mode: "on_error" helper_text: "Enter text" .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-required.gif :align: center Text length control ------------------- .. code-block:: kv MDTextField: hint_text: "Max text length = 5" max_text_length: 5 .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-text-length.gif :align: center Multi line text --------------- .. code-block:: kv MDTextField: multiline: True hint_text: "Multi-line text" .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-text-multi-line.gif :align: center Color mode ---------- .. code-block:: kv MDTextField: hint_text: "color_mode = 'accent'" color_mode: 'accent' Available options are `'primary'`, `'accent'` or `'custom`'. .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-color-mode.gif :align: center .. code-block:: kv MDTextField: hint_text: "color_mode = 'custom'" color_mode: 'custom' helper_text_mode: "on_focus" helper_text: "Color is defined by 'line_color_focus' property" line_color_focus: 1, 0, 1, 1 .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-color-mode-custom.gif :align: center .. code-block:: kv MDTextField: hint_text: "Line color normal" line_color_normal: app.theme_cls.accent_color .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-line-color-normal.png :align: center Rectangle mode -------------- .. code-block:: kv MDTextField: hint_text: "Rectangle mode" mode: "rectangle" .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-rectangle-mode.gif :align: center .. MDTextFieldRect: MDTextFieldRect --------------- .. Note:: :class:`~MDTextFieldRect` inherited from :class:`~kivy.uix.textinput.TextInput`. You can use all parameters and attributes of the :class:`~kivy.uix.textinput.TextInput` class in the :class:`~MDTextFieldRect` class. .. code-block:: kv MDTextFieldRect: size_hint: 1, None height: "30dp" .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-rect.gif :align: center .. Warning:: While there is no way to change the color of the border. .. MDTextFieldRound: MDTextFieldRound ---------------- Without icon ------------ .. code-block:: kv MDTextFieldRound: hint_text: 'Empty field' .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-round.gif :align: center With left icon -------------- .. Warning:: The icons in the :class:`~MDTextFieldRound` are static. You cannot bind events to them. .. code-block:: kv MDTextFieldRound: icon_left: "email" hint_text: "Field with left icon" .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-round-left-icon.png :align: center With left and right icons ------------------------- .. code-block:: kv MDTextFieldRound: icon_left: 'key-variant' icon_right: 'eye-off' hint_text: 'Field with left and right icons' .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-round-left-right-icon.png :align: center Control background color ------------------------ .. code-block:: kv MDTextFieldRound: icon_left: 'key-variant' normal_color: app.theme_cls.accent_color .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-round-normal-color.gif :align: center .. code-block:: kv MDTextFieldRound: icon_left: 'key-variant' normal_color: app.theme_cls.accent_color color_active: 1, 0, 0, 1 .. image:: https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/text-field-round-active-color.gif :align: center .. seealso:: See more information in the :class:`~MDTextFieldRect` class. """ __all__ = ( "MDTextField", "MDTextFieldRect", "MDTextFieldRound", ) import sys from kivy.uix.label import Label from kivy.uix.textinput import TextInput from kivy.animation import Animation from kivy.graphics.context_instructions import Color from kivy.lang import Builder from kivy.properties import ( NumericProperty, StringProperty, BooleanProperty, OptionProperty, ListProperty, ObjectProperty, ) from kivy.metrics import dp from kivy.metrics import sp from kivymd.font_definitions import theme_font_styles from kivymd.theming import ThemableBehavior from kivymd.uix.label import MDIcon Builder.load_string( """ #:import images_path kivymd.images_path <MDTextField> canvas.before: Clear Color: rgba: self.line_color_normal if root.mode == "line" else [0, 0, 0, 0] Line: points: self.x, self.y + dp(16), self.x + self.width, self.y + dp(16) width: 1 dash_length: dp(3) dash_offset: 2 if self.disabled else 0 Color: rgba: self._current_line_color if root.mode == "line" else [0, 0, 0, 0] Rectangle: size: self._line_width, dp(2) pos: self.center_x - (self._line_width / 2), self.y + dp(16) Color: rgba: self._current_error_color Rectangle: texture: self._msg_lbl.texture size: self._msg_lbl.texture_size pos: self.x, self.y Color: rgba: self._current_right_lbl_color Rectangle: texture: self._right_msg_lbl.texture size: self._right_msg_lbl.texture_size pos: self.width-self._right_msg_lbl.texture_size[0]+dp(45), self.y Color: rgba: (self._current_line_color if self.focus and not \ self._cursor_blink else (0, 0, 0, 0)) Rectangle: pos: [int(x) for x in self.cursor_pos] size: 1, -self.line_height Color: rgba: self._current_hint_text_color Rectangle: texture: self._hint_lbl.texture size: self._hint_lbl.texture_size pos: self.x, self.y + self.height - self._hint_y Color: rgba: self.disabled_foreground_color if self.disabled else\ (self.hint_text_color if not self.text and not\ self.focus else self.foreground_color) Color: rgba: self._current_line_color Line: width: dp(1) if root.mode == "rectangle" else dp(0.00001) points: ( self.x + root._line_blank_space_right_hint_text, self.top - self._hint_lbl.texture_size[1] // 2, self.right + dp(12), self.top - self._hint_lbl.texture_size[1] // 2, self.right + dp(12), self.y, self.x - dp(12), self.y, self.x - dp(12), self.top - self._hint_lbl.texture_size[1] // 2, self.x + root._line_blank_space_left_hint_text, self.top - self._hint_lbl.texture_size[1] // 2 ) font_name: 'Roboto' foreground_color: app.theme_cls.text_color font_size: sp(16) bold: False padding: 0, dp(16), 0, dp(10) multiline: False size_hint_y: None height: self.minimum_height + dp(8) <TextfieldLabel> size_hint_x: None width: self.texture_size[0] shorten: True shorten_from: "right" <MDTextFieldRect> on_focus: root.anim_rect([root.x, root.y, root.right, root.y, root.right,\ root.top, root.x, root.top, root.x, root.y], 1) if root.focus\ else root.anim_rect([root.x - dp(60), root.y - dp(60),\ root.right + dp(60), root.y - dp(60), root.right + dp(60), root.top + dp(60),\ root.x - dp(60), root.top + dp(60),\ root.x - dp(60), root.y - dp(60)], 0) canvas.after: Color: rgba: root._primary_color Line: width: dp(1.5) points: ( self.x - dp(60), self.y - dp(60), self.right + dp(60), self.y - dp(60), self.right + dp(60), self.top + dp(60), self.x - dp(60), self.top + dp(60), self.x - dp(60), self.y - dp(60) ) <MDTextFieldRound>: multiline: False size_hint: 1, None height: self.line_height + dp(10) background_active: f'{images_path}transparent.png' background_normal: f'{images_path}transparent.png' padding: self._lbl_icon_left.texture_size[1] + dp(10) if self.icon_left else dp(15), \ (self.height / 2) - (self.line_height / 2), \ self._lbl_icon_right.texture_size[1] + dp(20) if self.icon_right else dp(15), \ 0 canvas.before: Color: rgba: self.normal_color if not self.focus else self._color_active Ellipse: angle_start: 180 angle_end: 360 pos: self.pos[0] - self.size[1] / 2, self.pos[1] size: self.size[1], self.size[1] Ellipse: angle_start: 360 angle_end: 540 pos: self.size[0] + self.pos[0] - self.size[1]/2.0, self.pos[1] size: self.size[1], self.size[1] Rectangle: pos: self.pos size: self.size Color: rgba: self.line_color Line: points: self.pos[0] , self.pos[1], self.pos[0] + self.size[0], self.pos[1] Line: points: self.pos[0], self.pos[1] + self.size[1], self.pos[0] + self.size[0], self.pos[1] + self.size[1] Line: ellipse: self.pos[0] - self.size[1] / 2, self.pos[1], self.size[1], self.size[1], 180, 360 Line: ellipse: self.size[0] + self.pos[0] - self.size[1] / 2.0, self.pos[1], self.size[1], self.size[1], 360, 540 # Texture of left Icon. Color: rgba: self.icon_left_color Rectangle: texture: self._lbl_icon_left.texture size: self._lbl_icon_left.texture_size if self.icon_left \ else (0, 0) pos: self.x, \ self.center[1] - self._lbl_icon_right.texture_size[1] / 2 # Texture of right Icon. Color: rgba: self.icon_right_color Rectangle: texture: self._lbl_icon_right.texture size: self._lbl_icon_right.texture_size if self.icon_right \ else (0, 0) pos: (self.width + self.x) - (self._lbl_icon_right.texture_size[1]), \ self.center[1] - self._lbl_icon_right.texture_size[1] / 2 Color: rgba: root.theme_cls.disabled_hint_text_color if not self.focus \ else root.foreground_color """ ) class MDTextFieldRect(ThemableBehavior, TextInput): _primary_color = ListProperty([0, 0, 0, 0]) def __init__(self, **kwargs): super().__init__(**kwargs) self._update_primary_color() self.theme_cls.bind(primary_color=self._update_primary_color) self.root_color = Color() def _update_primary_color(self, *args): self._primary_color = self.theme_cls.primary_color self._primary_color[3] = 0 def anim_rect(self, points, alpha): instance_line = self.canvas.children[-1].children[-1] instance_color = self.canvas.children[-1].children[0] if alpha == 1: d_line = 0.3 d_color = 0.4 else: d_line = 0.05 d_color = 0.05 Animation(points=points, d=d_line, t="out_cubic").start(instance_line) Animation(a=alpha, d=d_color).start(instance_color) class FixedHintTextInput(TextInput): hint_text = StringProperty("") def on__hint_text(self, instance, value): pass def _refresh_hint_text(self): pass class TextfieldLabel(ThemableBehavior, Label): field = ObjectProperty() font_style = OptionProperty("Body1", options=theme_font_styles) def __init__(self, **kwargs): super().__init__(**kwargs) self.font_size = sp(self.theme_cls.font_styles[self.font_style][1]) class MDTextField(ThemableBehavior, FixedHintTextInput): helper_text = StringProperty("This field is required") """ Text for ``helper_text`` mode. :attr:`helper_text` is an :class:`~kivy.properties.StringProperty` and defaults to `'This field is required'`. """ helper_text_mode = OptionProperty( "none", options=["none", "on_error", "persistent", "on_focus"] ) """ Helper text mode. Available options are: `'on_error'`, `'persistent'`, `'on_focus'`. :attr:`helper_text_mode` is an :class:`~kivy.properties.OptionProperty` and defaults to `'none'`. """ max_text_length = NumericProperty(None) """ Maximum allowed value of characters in a text field. :attr:`max_text_length` is an :class:`~kivy.properties.NumericProperty` and defaults to `None`. """ required = BooleanProperty(False) """ Required text. If True then the text field requires text. :attr:`required` is an :class:`~kivy.properties.BooleanProperty` and defaults to `False`. """ color_mode = OptionProperty( "primary", options=["primary", "accent", "custom"] ) """ Color text mode. Available options are: `'primary'`, `'accent'`, `'custom'`. :attr:`color_mode` is an :class:`~kivy.properties.OptionProperty` and defaults to `'primary'`. """ mode = OptionProperty("line", options=["rectangle"]) """ Text field mode. Available options are: `'line'`, `'rectangle'`. :attr:`mode` is an :class:`~kivy.properties.OptionProperty` and defaults to `'line'`. """ line_color_normal = ListProperty() """ Line color normal in ``rgba`` format. :attr:`line_color_normal` is an :class:`~kivy.properties.ListProperty` and defaults to `[]`. """ line_color_focus = ListProperty() """ Line color focus in ``rgba`` format. :attr:`line_color_focus` is an :class:`~kivy.properties.ListProperty` and defaults to `[]`. """ error_color = ListProperty() """ Error color in ``rgba`` format for ``required = True``. :attr:`error_color` is an :class:`~kivy.properties.ListProperty` and defaults to `[]`. """ error = BooleanProperty(False) """ If True, then the text field goes into ``error`` mode. :attr:`error` is an :class:`~kivy.properties.BooleanProperty` and defaults to `False`. """ _text_len_error = BooleanProperty(False) _hint_lbl_font_size = NumericProperty("16sp") _line_blank_space_right_hint_text = NumericProperty(0) _line_blank_space_left_hint_text = NumericProperty(0) _hint_y = NumericProperty("38dp") _line_width = NumericProperty(0) _current_line_color = ListProperty([0.0, 0.0, 0.0, 0.0]) _current_error_color = ListProperty([0.0, 0.0, 0.0, 0.0]) _current_hint_text_color = ListProperty([0.0, 0.0, 0.0, 0.0]) _current_right_lbl_color = ListProperty([0.0, 0.0, 0.0, 0.0]) def __init__(self, **kwargs): self._msg_lbl = TextfieldLabel( font_style="Caption", halign="left", valign="middle", text=self.helper_text, field=self, ) self._right_msg_lbl = TextfieldLabel( font_style="Caption", halign="right", valign="middle", text="", field=self, ) self._hint_lbl = TextfieldLabel( font_style="Subtitle1", halign="left", valign="middle", field=self ) super().__init__(**kwargs) self.line_color_normal = self.theme_cls.divider_color self.line_color_focus = self.theme_cls.primary_color self.error_color = self.theme_cls.error_color self._current_hint_text_color = self.theme_cls.disabled_hint_text_color self._current_line_color = self.theme_cls.primary_color self.bind( helper_text=self._set_msg, hint_text=self._set_hint, _hint_lbl_font_size=self._hint_lbl.setter("font_size"), helper_text_mode=self._set_message_mode, max_text_length=self._set_max_text_length, text=self.on_text, ) self.theme_cls.bind( primary_color=self._update_primary_color, theme_style=self._update_theme_style, accent_color=self._update_accent_color, ) self.has_had_text = False def _update_colors(self, color): self.line_color_focus = color if not self.error and not self._text_len_error: self._current_line_color = color if self.focus: self._current_line_color = color def _update_accent_color(self, *args): if self.color_mode == "accent": self._update_colors(self.theme_cls.accent_color) def _update_primary_color(self, *args): if self.color_mode == "primary": self._update_colors(self.theme_cls.primary_color) def _update_theme_style(self, *args): self.line_color_normal = self.theme_cls.divider_color if not any([self.error, self._text_len_error]): if not self.focus: self._current_hint_text_color = ( self.theme_cls.disabled_hint_text_color ) self._current_right_lbl_color = ( self.theme_cls.disabled_hint_text_color ) if self.helper_text_mode == "persistent": self._current_error_color = ( self.theme_cls.disabled_hint_text_color ) def on_width(self, instance, width): if ( any([self.focus, self.error, self._text_len_error]) and instance is not None ): self._line_width = width self._msg_lbl.width = self.width self._right_msg_lbl.width = self.width def on_focus(self, *args): disabled_hint_text_color = self.theme_cls.disabled_hint_text_color Animation.cancel_all( self, "_line_width", "_hint_y", "_hint_lbl_font_size" ) if self.max_text_length is None: max_text_length = sys.maxsize else: max_text_length = self.max_text_length if len(self.text) > max_text_length or all( [self.required, len(self.text) == 0, self.has_had_text] ): self._text_len_error = True if self.error or all( [ self.max_text_length is not None and len(self.text) > self.max_text_length ] ): has_error = True else: if all([self.required, len(self.text) == 0, self.has_had_text]): has_error = True else: has_error = False if self.focus: if not self._line_blank_space_right_hint_text: self._line_blank_space_right_hint_text = self._hint_lbl.texture_size[ 0 ] - dp( 25 ) Animation( _line_blank_space_right_hint_text=self._line_blank_space_right_hint_text, _line_blank_space_left_hint_text=self._hint_lbl.x - dp(5), _current_hint_text_color=self.line_color_focus, duration=0.2, t="out_quad", ).start(self) self.has_had_text = True Animation.cancel_all( self, "_line_width", "_hint_y", "_hint_lbl_font_size" ) if not self.text: Animation( _hint_y=dp(14), _hint_lbl_font_size=sp(12), duration=0.2, t="out_quad", ).start(self) Animation(_line_width=self.width, duration=0.2, t="out_quad").start( self ) if has_error: Animation( duration=0.2, _current_hint_text_color=self.error_color, _current_right_lbl_color=self.error_color, _current_line_color=self.error_color, ).start(self) if self.helper_text_mode == "on_error" and ( self.error or self._text_len_error ): Animation( duration=0.2, _current_error_color=self.error_color ).start(self) elif ( self.helper_text_mode == "on_error" and not self.error and not self._text_len_error ): Animation( duration=0.2, _current_error_color=(0, 0, 0, 0) ).start(self) elif self.helper_text_mode == "persistent": Animation( duration=0.2, _current_error_color=disabled_hint_text_color, ).start(self) elif self.helper_text_mode == "on_focus": Animation( duration=0.2, _current_error_color=disabled_hint_text_color, ).start(self) else: Animation( duration=0.2, _current_right_lbl_color=disabled_hint_text_color, ).start(self) Animation(duration=0.2, color=self.line_color_focus).start( self._hint_lbl ) if self.helper_text_mode == "on_error": Animation( duration=0.2, _current_error_color=(0, 0, 0, 0) ).start(self) if self.helper_text_mode == "persistent": Animation( duration=0.2, _current_error_color=disabled_hint_text_color, ).start(self) elif self.helper_text_mode == "on_focus": Animation( duration=0.2, _current_error_color=disabled_hint_text_color, ).start(self) else: if not self.text: Animation( _hint_y=dp(38), _hint_lbl_font_size=sp(16), duration=0.2, t="out_quad", ).start(self) Animation( _line_blank_space_right_hint_text=0, _line_blank_space_left_hint_text=0, duration=0.2, t="out_quad", ).start(self) if has_error: Animation( duration=0.2, _current_line_color=self.error_color, _current_hint_text_color=self.error_color, _current_right_lbl_color=self.error_color, ).start(self) if self.helper_text_mode == "on_error" and ( self.error or self._text_len_error ): Animation( duration=0.2, _current_error_color=self.error_color ).start(self) elif ( self.helper_text_mode == "on_error" and not self.error and not self._text_len_error ): Animation( duration=0.2, _current_error_color=(0, 0, 0, 0) ).start(self) elif self.helper_text_mode == "persistent": Animation( duration=0.2, _current_error_color=disabled_hint_text_color, ).start(self) elif self.helper_text_mode == "on_focus": Animation( duration=0.2, _current_error_color=(0, 0, 0, 0) ).start(self) else: Animation(duration=0.2, color=(1, 1, 1, 1)).start( self._hint_lbl ) Animation( duration=0.2, _current_line_color=self.line_color_focus, _current_hint_text_color=disabled_hint_text_color, _current_right_lbl_color=(0, 0, 0, 0), ).start(self) if self.helper_text_mode == "on_error": Animation( duration=0.2, _current_error_color=(0, 0, 0, 0) ).start(self) elif self.helper_text_mode == "persistent": Animation( duration=0.2, _current_error_color=disabled_hint_text_color, ).start(self) elif self.helper_text_mode == "on_focus": Animation( duration=0.2, _current_error_color=(0, 0, 0, 0) ).start(self) Animation(_line_width=0, duration=0.2, t="out_quad").start(self) def on_text(self, instance, text): if len(text) > 0: self.has_had_text = True if self.max_text_length is not None: self._right_msg_lbl.text = f"{len(text)}/{self.max_text_length}" max_text_length = self.max_text_length else: max_text_length = sys.maxsize if len(text) > max_text_length or all( [self.required, len(self.text) == 0, self.has_had_text] ): self._text_len_error = True else: self._text_len_error = False if self.error or self._text_len_error: if self.focus: Animation( duration=0.2, _current_hint_text_color=self.error_color, _current_line_color=self.error_color, ).start(self) if self.helper_text_mode == "on_error" and ( self.error or self._text_len_error ): Animation( duration=0.2, _current_error_color=self.error_color ).start(self) if self._text_len_error: Animation( duration=0.2, _current_right_lbl_color=self.error_color ).start(self) else: if self.focus: disabled_hint_text_color = ( self.theme_cls.disabled_hint_text_color ) Animation( duration=0.2, _current_right_lbl_color=disabled_hint_text_color, ).start(self) Animation( duration=0.2, _current_hint_text_color=self.line_color_focus, _current_line_color=self.line_color_focus, ).start(self) if self.helper_text_mode == "on_error": Animation( duration=0.2, _current_error_color=(0, 0, 0, 0) ).start(self) if len(self.text) != 0 and not self.focus: self._hint_y = dp(14) self._hint_lbl_font_size = sp(12) def on_text_validate(self): self.has_had_text = True if self.max_text_length is None: max_text_length = sys.maxsize else: max_text_length = self.max_text_length if len(self.text) > max_text_length or all( [self.required, len(self.text) == 0, self.has_had_text] ): self._text_len_error = True def _set_hint(self, instance, text): self._hint_lbl.text = text def _set_msg(self, instance, text): self._msg_lbl.text = text self.helper_text = text def _set_message_mode(self, instance, text): self.helper_text_mode = text if self.helper_text_mode == "persistent": disabled_hint_text_color = self.theme_cls.disabled_hint_text_color Animation( duration=0.1, _current_error_color=disabled_hint_text_color ).start(self) def _set_max_text_length(self, instance, length): self.max_text_length = length self._right_msg_lbl.text = f"{len(self.text)}/{length}" def on_color_mode(self, instance, mode): if mode == "primary": self._update_primary_color() elif mode == "accent": self._update_accent_color() elif mode == "custom": self._update_colors(self.line_color_focus) def on_line_color_focus(self, *args): if self.color_mode == "custom": self._update_colors(self.line_color_focus) class MDTextFieldRound(ThemableBehavior, TextInput): icon_left = StringProperty() """Left icon. :attr:`icon_left` is an :class:`~kivy.properties.StringProperty` and defaults to `''`. """ icon_left_color = ListProperty([0, 0, 0, 1]) """Color of left icon in ``rgba`` format. :attr:`icon_left_color` is an :class:`~kivy.properties.ListProperty` and defaults to `[0, 0, 0, 1]`. """ icon_right = StringProperty() """Right icon. :attr:`icon_right` is an :class:`~kivy.properties.StringProperty` and defaults to `''`. """ icon_right_color = ListProperty([0, 0, 0, 1]) """Color of right icon. :attr:`icon_right_color` is an :class:`~kivy.properties.ListProperty` and defaults to `[0, 0, 0, 1]`. """ line_color = ListProperty() """Field line color. :attr:`line_color` is an :class:`~kivy.properties.ListProperty` and defaults to `[]`. """ normal_color = ListProperty() """Field color if `focus` is `False`. :attr:`normal_color` is an :class:`~kivy.properties.ListProperty` and defaults to `[]`. """ color_active = ListProperty() """Field color if `focus` is `True`. :attr:`color_active` is an :class:`~kivy.properties.ListProperty` and defaults to `[]`. """ _color_active = ListProperty() def __init__(self, **kwargs): super().__init__(**kwargs) self._lbl_icon_left = MDIcon(theme_text_color="Custom") self._lbl_icon_right = MDIcon(theme_text_color="Custom") self.cursor_color = self.theme_cls.primary_color if not self.normal_color: self.normal_color = self.theme_cls.primary_light if not self.line_color: self.line_color = self.theme_cls.primary_dark if not self.color_active: self._color_active = [0, 0, 0, 0.5] def on_focus(self, instance, value): if value: self.icon_left_color = self.theme_cls.primary_color self.icon_right_color = self.theme_cls.primary_color else: self.icon_left_color = self.theme_cls.text_color self.icon_right_color = self.theme_cls.text_color def on_icon_left(self, instance, value): self._lbl_icon_left.icon = value def on_icon_left_color(self, instance, value): self._lbl_icon_left.text_color = value def on_icon_right(self, instance, value): self._lbl_icon_right.icon = value def on_icon_right_color(self, instance, value): self._lbl_icon_right.text_color = value def on_color_active(self, instance, value): if value != [0, 0, 0, 0.5]: self._color_active = value self._color_active[-1] = 0.5 else: self._color_active = value
15,620
5,255
115
3e771a0b0c87d5dd39d6a6b61f4ccf622bf37c16
1,586
py
Python
src/accounts/models.py
NamHDT/Django-HDT
1d7803e522fe1962b55a5e68c6208e6ec8562a74
[ "MIT" ]
null
null
null
src/accounts/models.py
NamHDT/Django-HDT
1d7803e522fe1962b55a5e68c6208e6ec8562a74
[ "MIT" ]
null
null
null
src/accounts/models.py
NamHDT/Django-HDT
1d7803e522fe1962b55a5e68c6208e6ec8562a74
[ "MIT" ]
null
null
null
from django.db import models from django.contrib.auth.models import AbstractUser, Group, User # Create your models here.
44.055556
95
0.748424
from django.db import models from django.contrib.auth.models import AbstractUser, Group, User # Create your models here. class Team(models.Model): title_team = models.CharField(max_length=255) status = models.BooleanField(default=True) def __str__(self): return self.title_team class Group(models.Model): title_group = models.CharField(max_length=255) def __str__(self): return self.title_group class Accounts(models.Model): accounts_fullname = models.CharField(max_length=200) user = models.OneToOneField(User,related_name='accounts', on_delete=models.CASCADE) accounts_key = models.CharField(max_length=50, unique=True) birthday = models.DateField(null=True, blank=True) key_vendor = models.CharField(max_length=100, default=None, null=True, blank=True) group = models.ForeignKey(Group, null=True, blank=True, on_delete=models.CASCADE) mobile = models.CharField(max_length=12, default=None, null=True, blank=True) address = models.CharField(max_length=100, default=None, null=True, blank=True) mail = models.CharField(max_length=100, default=None, null=True, blank=True) start_date = models.DateField(null=True, blank=True) link_image_facebook = models.CharField(max_length=100, default=None, null=True, blank=True) link_telegram = models.CharField(max_length=100, default=None, null=True, blank=True) team = models.ForeignKey(Team, on_delete=models.CASCADE, blank=True, null=True) status = models.BooleanField(default=True) def __str__(self): return self.accounts_fullname
92
1,304
69
0971afebbd42210eae9ea7c8dd40303586365e72
1,588
py
Python
stko/calculators/extractors/orca_extractor.py
stevenbennett96/stko
ee340af4fc549d5a2c3e9cba8360661335efe0fd
[ "MIT" ]
8
2020-06-09T16:59:20.000Z
2022-03-18T23:05:38.000Z
stko/calculators/extractors/orca_extractor.py
stevenbennett96/stko
ee340af4fc549d5a2c3e9cba8360661335efe0fd
[ "MIT" ]
60
2020-05-22T13:38:54.000Z
2022-03-25T09:34:22.000Z
stko/calculators/extractors/orca_extractor.py
stevenbennett96/stko
ee340af4fc549d5a2c3e9cba8360661335efe0fd
[ "MIT" ]
4
2020-12-02T10:39:54.000Z
2021-03-01T18:34:07.000Z
""" Orca Extractor ============= #. :class:`.OrcaExtractor` Class to extract properties from Orca output. """ import re from .extractor import Extractor class OrcaExtractor(Extractor): """ Extracts properties from Orca 4.2 output files. Limited to final single point energy for now. Attributes ---------- output_file : :class:`str` Output file to extract properties from. output_lines : :class:`list` : :class:`str` :class:`list` of all lines in as :class:`str` in the output file. total_energy : :class:`float` The total energy in the :attr:`output_file` as :class:`float`. The energy is in units of a.u.. """ def _extract_values(self): """ Extract all properties from Orca output file. Returns ------- None : :class:`NoneType` """ for i, line in enumerate(self.output_lines): if self._check_line(line, 'total_energy'): self._extract_total_energy(line) def _extract_total_energy(self, line): """ Updates :attr:`total_energy`. Parameters ---------- line : :class:`str` Line of output file to extract property from. Returns ------- None : :class:`NoneType` """ nums = re.compile(r"[+-]?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?") string = nums.search(line.rstrip()).group(0) self.total_energy = float(string)
22.055556
67
0.563602
""" Orca Extractor ============= #. :class:`.OrcaExtractor` Class to extract properties from Orca output. """ import re from .extractor import Extractor class OrcaExtractor(Extractor): """ Extracts properties from Orca 4.2 output files. Limited to final single point energy for now. Attributes ---------- output_file : :class:`str` Output file to extract properties from. output_lines : :class:`list` : :class:`str` :class:`list` of all lines in as :class:`str` in the output file. total_energy : :class:`float` The total energy in the :attr:`output_file` as :class:`float`. The energy is in units of a.u.. """ def _extract_values(self): """ Extract all properties from Orca output file. Returns ------- None : :class:`NoneType` """ for i, line in enumerate(self.output_lines): if self._check_line(line, 'total_energy'): self._extract_total_energy(line) def _properties_dict(self): return {'total_energy': 'FINAL SINGLE POINT ENERGY'} def _extract_total_energy(self, line): """ Updates :attr:`total_energy`. Parameters ---------- line : :class:`str` Line of output file to extract property from. Returns ------- None : :class:`NoneType` """ nums = re.compile(r"[+-]?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?") string = nums.search(line.rstrip()).group(0) self.total_energy = float(string)
68
0
27
f7d79c7d9ee2293a7ffb1d260d3e444f2d2708b4
4,017
py
Python
test/test_npu/test_onnx/torch.onnx/export/export_onnx.py
Ascend/pytorch
39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc
[ "BSD-3-Clause" ]
1
2021-12-02T03:07:35.000Z
2021-12-02T03:07:35.000Z
test/test_npu/test_onnx/torch.onnx/export/export_onnx.py
Ascend/pytorch
39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc
[ "BSD-3-Clause" ]
1
2021-11-12T07:23:03.000Z
2021-11-12T08:28:13.000Z
test/test_npu/test_onnx/torch.onnx/export/export_onnx.py
Ascend/pytorch
39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc
[ "BSD-3-Clause" ]
null
null
null
# Copyright (c) 2020 Huawei Technologies Co., Ltd # Copyright (c) 2019, Facebook CORPORATION. # All rights reserved. # # Licensed under the BSD 3-Clause License (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://opensource.org/licenses/BSD-3-Clause # # 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 torch import torchvision from export.cp_parser import *
44.142857
160
0.692806
# Copyright (c) 2020 Huawei Technologies Co., Ltd # Copyright (c) 2019, Facebook CORPORATION. # All rights reserved. # # Licensed under the BSD 3-Clause License (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://opensource.org/licenses/BSD-3-Clause # # 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 torch import torchvision from export.cp_parser import * def getDeviceStr(deviceStr, DeviceNo): #print("cp_getDeviceId test device : ","(", deviceStr," ", DeviceNo, ")") if DeviceNo == None: return deviceStr if deviceStr == 'cpu': return deviceStr elif deviceStr == 'npu' or deviceStr == 'cuda': loc = '{}:{}'.format(deviceStr, DeviceNo) return loc else: return deviceStr def cp2onnx(model,cpfile,onnxfile, input_data, ispth=False,device="cpu",dno=None): if os.path.isfile(cpfile): #model = torchvision.models.resnet50(pretrained=False) model = cp_load(model,cpfile,ispth=ispth,device=device,dno=dno) else : print("warning : \"",cpfile,"\"not exist!") model.state_dict() deviceStr = getDeviceStr(device,dno) print("cp2onnx device: ",deviceStr,"(",device," ",dno,")") #torch.npu.set_device("npu:0") #dummy_input = torch.randn(10, 3, 224, 224, device='npu:0') dummy_input = input_data.to(deviceStr) # Providing input and output names sets the display names for values # within the model's graph. Setting these does not change the semantics # of the graph; it is only for readability. # # The inputs to the network consist of the flat list of inputs (i.e. # the values you would pass to the forward() method) followed by the # flat list of parameters. You can partially specify names, i.e. provide # a list here shorter than the number of inputs to the model, and we will # only set that subset of names, starting from the beginning. input_names = [ "actual_input_1" ] #+ [ "learned_%d" % i for i in range(16) ] output_names = [ "output1" ] model = model.to(deviceStr) torch.onnx.export(model, dummy_input, onnxfile, verbose=True, input_names=input_names, output_names=output_names,opset_version=11) def cp2onnx_dynamic_axes(model,cpfile,onnxfile,device="cuda",dno=None): if os.path.isfile(cpfile): #model = torchvision.models.resnet50(pretrained=False) model = cp_load(model,cpfile) else : print("warning : \"",cpfile,"\"not exist!") model.state_dict() deviceStr = getDeviceStr(device,dno) #torch.npu.set_device("npu:0") #dummy_input = torch.randn(10, 3, 224, 224, device='npu:0') dummy_input = torch.randn(10, 3, 224, 224) dummy_input = dummy_input.to(deviceStr) # Providing input and output names sets the display names for values # within the model's graph. Setting these does not change the semantics # of the graph; it is only for readability. # # The inputs to the network consist of the flat list of inputs (i.e. # the values you would pass to the forward() method) followed by the # flat list of parameters. You can partially specify names, i.e. provide # a list here shorter than the number of inputs to the model, and we will # only set that subset of names, starting from the beginning. input_names = [ "actual_input_1" ] #+ [ "learned_%d" % i for i in range(16) ] output_names = [ "output1" ] model = model.to(deviceStr) dynamic_axes = {'actual_input_1': {0: '-1'}, 'output1': {0: '-1'}} torch.onnx.export(model, dummy_input, onnxfile, verbose=True, input_names=input_names, output_names=output_names,dynamic_axes=dynamic_axes,opset_version=11)
3,224
0
69
8b225a0424899dc60a87321c510aba958c66778c
1,744
py
Python
fabdeploy/uwsgi.py
vmihailenco/fabdeploy
de46f06a45a201b254c5fd745ff00c1b51320456
[ "BSD-3-Clause" ]
2
2016-04-28T17:10:01.000Z
2016-05-05T04:31:19.000Z
fabdeploy/uwsgi.py
vmihailenco/fabdeploy
de46f06a45a201b254c5fd745ff00c1b51320456
[ "BSD-3-Clause" ]
null
null
null
fabdeploy/uwsgi.py
vmihailenco/fabdeploy
de46f06a45a201b254c5fd745ff00c1b51320456
[ "BSD-3-Clause" ]
null
null
null
from fabric.api import sudo, settings from .task import Task from .containers import conf from .utils import upload_config_template from . import system from . import pip __all__ = [ 'install_deps', 'install', 'push_config', 'disable_config', 'emperor', ] install_deps = InstallDeps() install = Install() push_config = PushConfig() disable_config = DisableConfig() emperor = Emperor()
22.075949
79
0.644495
from fabric.api import sudo, settings from .task import Task from .containers import conf from .utils import upload_config_template from . import system from . import pip __all__ = [ 'install_deps', 'install', 'push_config', 'disable_config', 'emperor', ] class InstallDeps(Task): def do(self): system.package_install( packages='build-essential python-dev libxml2-dev') install_deps = InstallDeps() class Install(Task): def do(self): return pip.install('uwsgi') install = Install() class ConfigTask(Task): @conf def sites_available_path(self): return '/etc/uwsgi/sites-available' @conf def sites_enabled_path(self): return '/etc/uwsgi/sites-enabled' @conf def config(self): return '%(sites_available_path)s/%(instance_name)s.ini' % self.conf @conf def enabled_config(self): return '%(sites_enabled_path)s/%(instance_name)s.ini' % self.conf class PushConfig(ConfigTask): def do(self): sudo( 'mkdir --parents %(sites_available_path)s %(sites_enabled_path)s' % self.conf) upload_config_template( 'uwsgi.ini', self.conf.config, context=self.conf, use_sudo=True) with settings(warn_only=True): sudo('ln --symbolic %(config)s %(enabled_config)s' % self.conf) push_config = PushConfig() class DisableConfig(ConfigTask): def do(self): sudo('rm %(enabled_config)s' % self.conf) disable_config = DisableConfig() class Emperor(Task): def do(self): sudo( '%(env_path)s/bin/uwsgi --emperor %(sites_enabled_path)s ' '--daemonize /var/log/uwsgi-emperor.log' % self.conf) emperor = Emperor()
888
169
268
d8a4f0b7118eaacf0f9c5e2fe17dc78a9381ba01
7,017
py
Python
qa/rpc-tests/blockdelay.py
stashpayio/stash
963144989f74c39e7287021d917da0405e237ae7
[ "MIT" ]
1
2019-10-23T06:01:29.000Z
2019-10-23T06:01:29.000Z
qa/rpc-tests/blockdelay.py
stashpayio/stash
963144989f74c39e7287021d917da0405e237ae7
[ "MIT" ]
2
2019-04-29T19:26:56.000Z
2020-02-02T17:41:57.000Z
qa/rpc-tests/blockdelay.py
stashpayio/stash
963144989f74c39e7287021d917da0405e237ae7
[ "MIT" ]
24
2019-05-14T22:31:53.000Z
2020-07-07T21:22:56.000Z
#!/usr/bin/env python2 # Copyright (c) 2014 The Bitcoin Core developers # Copyright (c) 2018 The Zencash developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_framework import BitcoinTestFramework from test_framework.authproxy import JSONRPCException from test_framework.util import assert_equal, initialize_chain_clean, \ start_nodes, start_node, connect_nodes, stop_node, stop_nodes, \ sync_blocks, sync_mempools, connect_nodes_bi, wait_bitcoinds, p2p_port, check_json_precision import traceback import os,sys import shutil from random import randint from decimal import Decimal import logging import time if __name__ == '__main__': blockdelay().main()
38.767956
112
0.64529
#!/usr/bin/env python2 # Copyright (c) 2014 The Bitcoin Core developers # Copyright (c) 2018 The Zencash developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_framework import BitcoinTestFramework from test_framework.authproxy import JSONRPCException from test_framework.util import assert_equal, initialize_chain_clean, \ start_nodes, start_node, connect_nodes, stop_node, stop_nodes, \ sync_blocks, sync_mempools, connect_nodes_bi, wait_bitcoinds, p2p_port, check_json_precision import traceback import os,sys import shutil from random import randint from decimal import Decimal import logging import time class blockdelay(BitcoinTestFramework): alert_filename = None def setup_chain(self, split=False): print("Initializing test directory "+self.options.tmpdir) initialize_chain_clean(self.options.tmpdir, 4) self.alert_filename = os.path.join(self.options.tmpdir, "alert.txt") with open(self.alert_filename, 'w'): pass # Just open then close to create zero-length file def setup_network(self, split=False): self.nodes = [] # -exportdir option means we must provide a valid path to the destination folder for wallet backups ed0 = "-exportdir=" + self.options.tmpdir + "/node0" ed1 = "-exportdir=" + self.options.tmpdir + "/node1" ed2 = "-exportdir=" + self.options.tmpdir + "/node2" ed3 = "-exportdir=" + self.options.tmpdir + "/node3" ''' extra_args = [["-debug","-keypool=100", "-alertnotify=echo %s >> \"" + self.alert_filename + "\"", ed0], ["-debug", "-keypool=100", "-alertnotify=echo %s >> \"" + self.alert_filename + "\"", ed1], ["-debug", "-keypool=100", "-alertnotify=echo %s >> \"" + self.alert_filename + "\"", ed2], ["-debug", "-keypool=100", "-alertnotify=echo %s >> \"" + self.alert_filename + "\"", ed3]] ''' #self.nodes = start_nodes(4, self.options.tmpdir, extra_args) self.nodes = start_nodes(4, self.options.tmpdir) if not split: connect_nodes_bi(self.nodes, 1, 2) sync_blocks(self.nodes[1:3]) sync_mempools(self.nodes[1:3]) connect_nodes_bi(self.nodes, 0, 1) connect_nodes_bi(self.nodes, 2, 3) self.is_network_split = split self.sync_all() def disconnect_nodes(self, from_connection, node_num): ip_port = "127.0.0.1:"+str(p2p_port(node_num)) from_connection.disconnectnode(ip_port) # poll until version handshake complete to avoid race conditions # with transaction relaying while any(peer['version'] == 0 for peer in from_connection.getpeerinfo()): time.sleep(0.1) def split_network(self): # Split the network of four nodes into nodes 0/1 and 2/3. assert not self.is_network_split self.disconnect_nodes(self.nodes[1], 2) self.disconnect_nodes(self.nodes[2], 1) self.is_network_split = True def join_network(self): #Join the (previously split) network halves together. assert self.is_network_split connect_nodes_bi(self.nodes, 0, 3) connect_nodes_bi(self.nodes, 3, 0) connect_nodes_bi(self.nodes, 1, 3) connect_nodes_bi(self.nodes, 3, 1) #sync_blocks(self.nodes[0:3],1,True) #sync_mempools(self.nodes[1:3]) self.sync_all() self.is_network_split = False def run_test(self): blocks = [] blocks.append(self.nodes[0].getblockhash(0)) print("\n\nGenesis block is: " + blocks[0]) # raw_input("press enter to start..") print("\n\nGenerating initial blockchain 4 blocks") blocks.extend(self.nodes[0].generate(1)) # block height 1 self.sync_all() blocks.extend(self.nodes[1].generate(1)) # block height 2 self.sync_all() blocks.extend(self.nodes[2].generate(1)) # block height 3 self.sync_all() blocks.extend(self.nodes[3].generate(1)) # block height 4 self.sync_all() print("Blocks generated") print("\n\nSplit network") self.split_network() print("The network is split") # Main chain print("\n\nGenerating 2 parallel chains with different length") print("\nGenerating 12 honest blocks") blocks.extend(self.nodes[0].generate(6)) # block height 5 -6 -7 -8 - 9 - 10 self.sync_all() blocks.extend(self.nodes[1].generate(6)) # block height 11-12-13-14-15-16 last_main_blockhash=blocks[len(blocks)-1] self.sync_all() print("Honest block generated") assert self.nodes[0].getbestblockhash() == last_main_blockhash # Malicious nodes mining privately faster print("\nGenerating 13 malicious blocks") self.nodes[2].generate(10) # block height 5 - 6 -7 -8 -9-10 -11 12 13 14 self.sync_all() self.nodes[3].generate(3) # block height 15 - 16 - 17 self.sync_all() print("Malicious block generated") print("\n\nJoin network") # raw_input("press enter to join the netorks..") self.join_network() time.sleep(2) print("\nNetwork joined") print("\nTesting if the current chain is still the honest chain") assert self.nodes[0].getbestblockhash() == last_main_blockhash print("Confirmed: malicious chain is under penalty") print("\nGenerating 64 malicious blocks") self.nodes[3].generate(64) print("Malicious block generated") time.sleep(10) print("\nTesting if the current chain is still the honest chain") assert self.nodes[0].getbestblockhash() == last_main_blockhash print("Confirmed: malicious chain is under penalty") print("\nGenerating 65 more honest blocks") self.nodes[0].generate(65) print("Honest block generated") print("\nGenerating 1 more malicious block") last_malicious_blockhash=self.nodes[3].generate(1)[0] print("Malicious block generated") print("\nWaiting that all network nodes are synced with same chain length") sync_blocks(self.nodes, 1, True) print("Network nodes are synced") print("\nTesting if all the nodes/chains have the same best tip") assert (self.nodes[0].getbestblockhash() == self.nodes[1].getbestblockhash() == self.nodes[2].getbestblockhash() == self.nodes[3].getbestblockhash()) print("Confirmed: all the nodes have the same best tip") print("\nTesting if the current chain switched to the malicious chain") assert self.nodes[0].getbestblockhash() == last_malicious_blockhash print("Confirmed: malicious chain is the best chain") time.sleep(2) sync_mempools(self.nodes) if __name__ == '__main__': blockdelay().main()
5,998
209
22
57e33efd6f7be223beeb7a6465536e61f6a9a3c4
145
py
Python
Python/code case/code case 258.py
amazing-2020/pdf
8cd3f5f510a1c1ed89b51b1354f4f8c000c5b24d
[ "Apache-2.0" ]
3
2021-01-01T13:08:24.000Z
2021-02-03T09:27:56.000Z
Python/code case/code case 258.py
amazing-2020/pdf
8cd3f5f510a1c1ed89b51b1354f4f8c000c5b24d
[ "Apache-2.0" ]
null
null
null
Python/code case/code case 258.py
amazing-2020/pdf
8cd3f5f510a1c1ed89b51b1354f4f8c000c5b24d
[ "Apache-2.0" ]
null
null
null
if __name__ == '__main__': a = int(input("input a number: \n")) b = a >> 4 c = ~(~0 << 4) d = b & c print("%o\t%o" % (a, d))
20.714286
40
0.406897
if __name__ == '__main__': a = int(input("input a number: \n")) b = a >> 4 c = ~(~0 << 4) d = b & c print("%o\t%o" % (a, d))
0
0
0
76a9211d33d48baca8d3522bece6b4577e432edc
2,004
py
Python
temp.py
dtuit/twitter_scraper
0b7527bb97ee5b30b6f634d9534223f949aea63f
[ "MIT" ]
6
2016-09-20T13:47:57.000Z
2019-03-31T15:02:31.000Z
temp.py
sahwar/twitter_scraper
0b7527bb97ee5b30b6f634d9534223f949aea63f
[ "MIT" ]
null
null
null
temp.py
sahwar/twitter_scraper
0b7527bb97ee5b30b6f634d9534223f949aea63f
[ "MIT" ]
1
2019-03-07T01:46:19.000Z
2019-03-07T01:46:19.000Z
from celery import Celery, signals, Task from datetime import datetime, timezone, timedelta, date from math import floor import requests import pymssql import json import twitterWebsiteSearch.TwitterWebsiteSearch as twitSearch app = Celery('tasks') app.config_from_object('celeryconfig') ''' ''' @signals.worker_process_init.connect @signals.worker_process_shutdown.connect ''' ''' @app.task(base=TwitSearchTask, bind=True) @app.task ''' input query start date end date For each day in date range create a task (query,day) page through each page in query save each page to database '''
22.266667
122
0.676148
from celery import Celery, signals, Task from datetime import datetime, timezone, timedelta, date from math import floor import requests import pymssql import json import twitterWebsiteSearch.TwitterWebsiteSearch as twitSearch app = Celery('tasks') app.config_from_object('celeryconfig') ''' ''' @signals.worker_process_init.connect def init_worker(**kwargs): global db_conn print('Initializing database connection for worker.') db_conn = get_db_conn() def get_db_conn(): keys = get_keys() return pymssql.connect(server=keys['server'], user=keys['user'], password=keys['password'], database=keys['database']) def get_keys(): with open('keys.json') as keys_file: keys = json.load(keys_file) return keys @signals.worker_process_shutdown.connect def shutdown_worker(**kwargs): global db_conn if db_conn: print('Closing database connectionn for worker.') db_conn.close() ''' ''' class TwitSearchTask(Task): abstract = True # cached requests.Session object _session = None def __init__(self): pass @property def session(self): if self._session is None: session = requests.Session() self._session = session return self._session @app.task(base=TwitSearchTask, bind=True) def call_api(self, query): twitSearch.search(query, session=self.session) @app.task def dispatch_twitter_query_tasks(query): since = date(2016,1,1) until = datetime.utcnow() for day in daterange(start_date, end_date): querystring = "{0} since:{1} until:{2}".format(query, since.strftime("%Y-%m-%d"), until.strftime("%Y-%m-%d")) def daterange(start_date, end_date): for n in range(int ((end_date - start_date).days)): yield end_date - timedelta(n) ''' input query start date end date For each day in date range create a task (query,day) page through each page in query save each page to database '''
1,021
156
180
2173ac94612d7da3c2b3f618e4a1acf5842e7d92
25,022
py
Python
brewtils/pika.py
scott-taubman/brewtils
3478e5ebd6383d7724286c9d0c7afac9ef5d7b45
[ "MIT" ]
null
null
null
brewtils/pika.py
scott-taubman/brewtils
3478e5ebd6383d7724286c9d0c7afac9ef5d7b45
[ "MIT" ]
null
null
null
brewtils/pika.py
scott-taubman/brewtils
3478e5ebd6383d7724286c9d0c7afac9ef5d7b45
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from __future__ import absolute_import import logging import ssl as pyssl from functools import partial from pika import ( BasicProperties, BlockingConnection, ConnectionParameters, PlainCredentials, SelectConnection, SSLOptions, URLParameters, ) from pika.exceptions import AMQPError from pika.spec import PERSISTENT_DELIVERY_MODE from brewtils.errors import DiscardMessageException, RepublishRequestException from brewtils.request_handling import RequestConsumer from brewtils.schema_parser import SchemaParser class PikaClient(object): """Base class for connecting to RabbitMQ using Pika Args: host: RabbitMQ host port: RabbitMQ port user: RabbitMQ user password: RabbitMQ password connection_attempts: Maximum number of retry attempts heartbeat: Time between RabbitMQ heartbeats heartbeat_interval: DEPRECATED, use heartbeat virtual_host: RabbitMQ virtual host exchange: Default exchange that will be used ssl: SSL Options blocked_connection_timeout: If not None, the value is a non-negative timeout, in seconds, for the connection to remain blocked (triggered by Connection.Blocked from broker); if the timeout expires before connection becomes unblocked, the connection will be torn down, triggering the adapter-specific mechanism for informing client app about the closed connection (e.g., on_close_callback or ConnectionClosed exception) with `reason_code` of `InternalCloseReasons.BLOCKED_CONNECTION_TIMEOUT`. """ @property def connection_url(self): """str: Connection URL for this client's connection information""" virtual_host = self._conn_params.virtual_host if virtual_host == "/": virtual_host = "" return "amqp%s://%s:%s@%s:%s/%s" % ( "s" if self._ssl_enabled else "", self._conn_params.credentials.username, self._conn_params.credentials.password, self._conn_params.host, self._conn_params.port, virtual_host, ) def connection_parameters(self, **kwargs): """Get ``ConnectionParameters`` associated with this client Will construct a ``ConnectionParameters`` object using parameters passed at initialization as defaults. Any parameters passed in kwargs will override initialization parameters. Args: **kwargs: Overrides for specific parameters Returns: :obj:`pika.ConnectionParameters`: ConnectionParameters object """ credentials = PlainCredentials( username=kwargs.get("user", self._user), password=kwargs.get("password", self._password), ) conn_params = { "host": kwargs.get("host", self._host), "port": kwargs.get("port", self._port), "ssl_options": kwargs.get("ssl_options", self._ssl_options), "virtual_host": kwargs.get("virtual_host", self._virtual_host), "connection_attempts": kwargs.get( "connection_attempts", self._connection_attempts ), "heartbeat": kwargs.get( "heartbeat", kwargs.get("heartbeat_interval", self._heartbeat) ), "blocked_connection_timeout": kwargs.get( "blocked_connection_timeout", self._blocked_connection_timeout ), "credentials": credentials, } return ConnectionParameters(**conn_params) class TransientPikaClient(PikaClient): """Client implementation that creates new connection and channel for each action""" def setup_queue(self, queue_name, queue_args, routing_keys): """Create a new queue with queue_args and bind it to routing_keys""" with BlockingConnection(self._conn_params) as conn: conn.channel().queue_declare(queue_name, **queue_args) for routing_key in routing_keys: conn.channel().queue_bind( queue_name, self._exchange, routing_key=routing_key ) return {"name": queue_name, "args": queue_args} def publish(self, message, **kwargs): """Publish a message Args: message: Message to publish kwargs: Additional message properties Keyword Arguments: * *routing_key* -- Routing key to use when publishing * *headers* -- Headers to be included as part of the message properties * *expiration* -- Expiration to be included as part of the message properties * *confirm* -- Flag indicating whether to operate in publisher-acknowledgements mode * *mandatory* -- Raise if the message can not be routed to any queues * *priority* -- Message priority """ with BlockingConnection(self._conn_params) as conn: channel = conn.channel() if kwargs.get("confirm"): channel.confirm_delivery() properties = BasicProperties( app_id="beer-garden", content_type="text/plain", headers=kwargs.get("headers"), expiration=kwargs.get("expiration"), delivery_mode=kwargs.get("delivery_mode"), priority=kwargs.get("priority"), ) channel.basic_publish( exchange=self._exchange, routing_key=kwargs["routing_key"], body=message, properties=properties, mandatory=kwargs.get("mandatory"), ) class PikaConsumer(RequestConsumer): """Pika message consumer This consumer is designed to be fault-tolerant - if RabbitMQ closes the connection the consumer will attempt to reopen it. There are limited reasons why the connection may be closed from the broker side and usually indicates permission related issues or socket timeouts. Unexpected channel closures can indicate a problem with a command that was issued. Args: amqp_url: (str) The AMQP url to connect to queue_name: (str) The name of the queue to connect to on_message_callback (func): function called to invoke message processing. Must return a Future. panic_event (threading.Event): Event to be set on a catastrophic failure logger (logging.Logger): A configured Logger thread_name (str): Name to use for this thread max_concurrent: (int) Maximum requests to process concurrently max_reconnect_attempts (int): Number of times to attempt reconnection to message queue before giving up (default -1 aka never) max_reconnect_timeout (int): Maximum time to wait before reconnect attempt starting_reconnect_timeout (int): Time to wait before first reconnect attempt """ def run(self): """Run the consumer This method creates a connection to RabbitMQ and starts the IOLoop. The IOLoop will block and allow the SelectConnection to operate. This means that to stop the PikaConsumer we just need to stop the IOLoop. If the connection closed unexpectedly (the shutdown event is not set) then this will wait a certain amount of time and before attempting to restart it. Finally, if the maximum number of reconnect attempts have been reached the panic event will be set, which will end the PikaConsumer as well as the Plugin. Returns: None """ while not self._panic_event.is_set(): self._connection = self.open_connection() self._connection.ioloop.start() if not self._panic_event.is_set(): if 0 <= self._max_reconnect_attempts <= self._reconnect_attempt: self.logger.warning("Max connection failures, shutting down") self._panic_event.set() return self.logger.warning( "%s consumer has died, waiting %i seconds before reconnecting", self._queue_name, self._reconnect_timeout, ) self._panic_event.wait(self._reconnect_timeout) self._reconnect_attempt += 1 self._reconnect_timeout = min( self._reconnect_timeout * 2, self._max_reconnect_timeout ) def stop(self): """Cleanly shutdown It's a good idea to call stop_consuming before this to prevent new messages from being processed during shutdown. This sets the shutdown_event to let callbacks know that this is an orderly (requested) shutdown. It then schedules a channel close on the IOLoop - the channel's on_close callback will close the connection, and the connection's on_close callback will terminate the IOLoop which will end the PikaConsumer. Returns: None """ self.logger.debug("Stopping request consumer") if self._connection: self._connection.ioloop.add_callback_threadsafe( partial(self._connection.close) ) def is_connected(self): """Determine if the underlying connection is open Returns: True if the connection exists and is open, False otherwise """ return self._connection and self._connection.is_open def on_message(self, channel, basic_deliver, properties, body): """Invoked when a message is delivered from the queueing service Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange, routing key, delivery tag and a redelivered flag for the message. the properties passed in is an instance of BasicProperties with the message properties and the body is the message that was sent. Args: channel (pika.channel.Channel): The channel object basic_deliver (pika.Spec.Basic.Deliver): basic_deliver method properties (pika.Spec.BasicProperties): Message properties body (bytes): The message body """ self.logger.debug( "Received message #%s from %s on channel %s: %s", basic_deliver.delivery_tag, properties.app_id, channel.channel_number, body, ) # Pika gives us bytes, but we want a string to be ok too try: body = body.decode() except AttributeError: pass try: future = self._on_message_callback(body, properties.headers) future.add_done_callback( partial(self.on_message_callback_complete, basic_deliver) ) except Exception as ex: requeue = not isinstance(ex, DiscardMessageException) self.logger.exception( "Exception while trying to schedule message %s, about to nack%s: %s" % (basic_deliver.delivery_tag, " and requeue" if requeue else "", ex) ) self._channel.basic_nack(basic_deliver.delivery_tag, requeue=requeue) def on_message_callback_complete(self, basic_deliver, future): """Invoked when the future returned by _on_message_callback completes. This method will be invoked from the threadpool context. It's only purpose is to schedule the final processing steps to take place on the connection's ioloop. Args: basic_deliver: future: Completed future Returns: None """ self._connection.ioloop.add_callback_threadsafe( partial(self.finish_message, basic_deliver, future) ) def finish_message(self, basic_deliver, future): """Finish processing a message This should be invoked as the final part of message processing. It's responsible for acking / nacking messages back to the broker. The main complexity here depends on whether the request processing future has an exception: - If there is no exception it acks the message - If there is an exception - If the exception is an instance of DiscardMessageException it acks the message and does not requeue it - If the exception is an instance of RepublishRequestException it will construct an entirely new BlockingConnection, use that to publish a new message, and then ack the original message - If the exception is not an instance of either the panic_event is set and the consumer will self-destruct Also, if there's ever an error acking a message the panic_event is set and the consumer will self-destruct. Args: basic_deliver: future: Completed future Returns: None """ delivery_tag = basic_deliver.delivery_tag if not future.exception(): try: self.logger.debug("Acking message %s", delivery_tag) self._channel.basic_ack(delivery_tag) except Exception as ex: self.logger.exception( "Error acking message %s, about to shut down: %s", delivery_tag, ex ) self._panic_event.set() else: real_ex = future.exception() if isinstance(real_ex, RepublishRequestException): try: with BlockingConnection(self._connection_parameters) as c: headers = real_ex.headers headers.update({"request_id": real_ex.request.id}) props = BasicProperties( app_id="beer-garden", content_type="text/plain", headers=headers, priority=1, delivery_mode=PERSISTENT_DELIVERY_MODE, ) c.channel().basic_publish( exchange=basic_deliver.exchange, properties=props, routing_key=basic_deliver.routing_key, body=SchemaParser.serialize_request(real_ex.request), ) self._channel.basic_ack(delivery_tag) except Exception as ex: self.logger.exception( "Error republishing message %s, about to shut down: %s", delivery_tag, ex, ) self._panic_event.set() elif isinstance(real_ex, DiscardMessageException): self.logger.info( "Nacking message %s, not attempting to requeue", delivery_tag ) self._channel.basic_nack(delivery_tag, requeue=False) else: # If request processing throws anything else we terminate self.logger.exception( "Unexpected exception during request %s processing, about " "to shut down: %s", delivery_tag, real_ex, exc_info=False, ) self._panic_event.set() def open_connection(self): """Opens a connection to RabbitMQ This method immediately returns the connection object. However, whether the connection was successful is not know until a callback is invoked (either on_open_callback or on_open_error_callback). Returns: The SelectConnection object """ return SelectConnection( parameters=self._connection_parameters, on_open_callback=self.on_connection_open, on_close_callback=self.on_connection_closed, on_open_error_callback=self.on_connection_closed, ) def on_connection_open(self, connection): """Connection open success callback This method is called by pika once the connection to RabbitMQ has been established. The only thing this actually does is call the open_channel method. Args: connection: The connection object Returns: None """ self.logger.debug("Connection opened: %s", connection) if self._reconnect_attempt: self.logger.info("%s consumer successfully reconnected", self._queue_name) self._reconnect_attempt = 0 self.open_channel() def on_connection_closed(self, connection, *args): """Connection closed callback This method is invoked by pika when the connection to RabbitMQ is closed. If the connection is closed we terminate its IOLoop to stop the PikaConsumer. In the case of an unexpected connection closure we'll wait 5 seconds before terminating with the expectation that the plugin will attempt to restart the consumer once it's dead. Args: connection: The connection args: Tuple of arguments describing why the connection closed For pika < 1: reply_code (Numeric code indicating close reason), reply_text (String describing close reason). For pika >= 1 exc (Exception describing close). Returns: None """ self.logger.debug("Connection %s closed: %s", connection, args) self._connection.ioloop.stop() def open_channel(self): """Open a channel""" self.logger.debug("Opening a new channel") self._connection.channel(on_open_callback=self.on_channel_open) def on_channel_open(self, channel): """Channel open success callback This will add a close callback (on_channel_closed) the channel and will call start_consuming to begin receiving messages. Args: channel: The opened channel object Returns: None """ self.logger.debug("Channel opened: %s", channel) self._channel = channel self._channel.add_on_close_callback(self.on_channel_closed) self.start_consuming() def on_channel_closed(self, channel, *args): """Channel closed callback This method is invoked by pika when the channel is closed. Channels are usually closed as a result of something that violates the protocol, such as attempting to re-declare an exchange or queue with different parameters. This indicates that something has gone wrong, so just close the connection (if it's still open) to reset. Args: channel: The channel args: Tuple of arguments describing why the channel closed For pika < 1: reply_code (Numeric code indicating close reason), reply_text (String describing close reason). For pika >= 1 exc (Exception describing close). Returns: None """ self.logger.debug("Channel %i closed: %s", channel, args) if self._connection.is_open: self._connection.close() def start_consuming(self): """Begin consuming messages The RabbitMQ prefetch is set to the maximum number of concurrent consumers. This ensures that messages remain in RabbitMQ until a consuming thread is available to process them. An on_cancel_callback is registered so that the consumer is notified if it is canceled by the broker. Returns: None """ self.logger.debug("Issuing consumer related RPC commands") self._channel.basic_qos(prefetch_count=self._max_concurrent) self._channel.add_on_cancel_callback(self.on_consumer_cancelled) self._consumer_tag = self._channel.basic_consume( queue=self._queue_name, on_message_callback=self.on_message ) def stop_consuming(self): """Stop consuming messages Sends a Basic.Cancel command to the broker, which causes the broker to stop sending the consumer messages. Returns: None """ if self._channel and self._channel.is_open: self.logger.debug("Stopping message consuming on channel %i", self._channel) self._connection.ioloop.add_callback_threadsafe( partial( self._channel.basic_cancel, consumer_tag=self._consumer_tag, callback=lambda *args: None, ) ) def on_consumer_cancelled(self, method_frame): """Consumer cancelled callback This is only invoked if the consumer is cancelled by the broker. Since that effectively ends the request consuming we close the channel to start the process of terminating the PikaConsumer. Args: method_frame (pika.frame.Method): The Basic.Cancel frame Returns: None """ self.logger.debug("Consumer was cancelled: %r", method_frame) if self._channel: self._connection.close()
37.235119
88
0.618496
# -*- coding: utf-8 -*- from __future__ import absolute_import import logging import ssl as pyssl from functools import partial from pika import ( BasicProperties, BlockingConnection, ConnectionParameters, PlainCredentials, SelectConnection, SSLOptions, URLParameters, ) from pika.exceptions import AMQPError from pika.spec import PERSISTENT_DELIVERY_MODE from brewtils.errors import DiscardMessageException, RepublishRequestException from brewtils.request_handling import RequestConsumer from brewtils.schema_parser import SchemaParser class PikaClient(object): """Base class for connecting to RabbitMQ using Pika Args: host: RabbitMQ host port: RabbitMQ port user: RabbitMQ user password: RabbitMQ password connection_attempts: Maximum number of retry attempts heartbeat: Time between RabbitMQ heartbeats heartbeat_interval: DEPRECATED, use heartbeat virtual_host: RabbitMQ virtual host exchange: Default exchange that will be used ssl: SSL Options blocked_connection_timeout: If not None, the value is a non-negative timeout, in seconds, for the connection to remain blocked (triggered by Connection.Blocked from broker); if the timeout expires before connection becomes unblocked, the connection will be torn down, triggering the adapter-specific mechanism for informing client app about the closed connection (e.g., on_close_callback or ConnectionClosed exception) with `reason_code` of `InternalCloseReasons.BLOCKED_CONNECTION_TIMEOUT`. """ def __init__( self, host="localhost", port=5672, user="guest", password="guest", connection_attempts=3, heartbeat_interval=3600, virtual_host="/", exchange="beer_garden", ssl=None, blocked_connection_timeout=None, **kwargs ): self._host = host self._port = port self._user = user self._password = password self._connection_attempts = connection_attempts self._heartbeat = kwargs.get("heartbeat", heartbeat_interval) self._blocked_connection_timeout = blocked_connection_timeout self._virtual_host = virtual_host self._exchange = exchange ssl = ssl or {} self._ssl_options = None self._ssl_enabled = ssl.get("enabled", False) self._ssl_client_cert = ssl.get("client_cert") if self._ssl_enabled: ssl_context = pyssl.create_default_context(cafile=ssl.get("ca_cert", None)) if ssl.get("ca_verify"): ssl_context.verify_mode = pyssl.CERT_REQUIRED else: ssl_context.check_hostname = False ssl_context.verify_mode = pyssl.CERT_NONE if self._ssl_client_cert: ssl_context.load_cert_chain(self._ssl_client_cert) self._ssl_options = SSLOptions(ssl_context, server_hostname=self._host) # Save the 'normal' params so they don't need to be reconstructed self._conn_params = self.connection_parameters() @property def connection_url(self): """str: Connection URL for this client's connection information""" virtual_host = self._conn_params.virtual_host if virtual_host == "/": virtual_host = "" return "amqp%s://%s:%s@%s:%s/%s" % ( "s" if self._ssl_enabled else "", self._conn_params.credentials.username, self._conn_params.credentials.password, self._conn_params.host, self._conn_params.port, virtual_host, ) def connection_parameters(self, **kwargs): """Get ``ConnectionParameters`` associated with this client Will construct a ``ConnectionParameters`` object using parameters passed at initialization as defaults. Any parameters passed in kwargs will override initialization parameters. Args: **kwargs: Overrides for specific parameters Returns: :obj:`pika.ConnectionParameters`: ConnectionParameters object """ credentials = PlainCredentials( username=kwargs.get("user", self._user), password=kwargs.get("password", self._password), ) conn_params = { "host": kwargs.get("host", self._host), "port": kwargs.get("port", self._port), "ssl_options": kwargs.get("ssl_options", self._ssl_options), "virtual_host": kwargs.get("virtual_host", self._virtual_host), "connection_attempts": kwargs.get( "connection_attempts", self._connection_attempts ), "heartbeat": kwargs.get( "heartbeat", kwargs.get("heartbeat_interval", self._heartbeat) ), "blocked_connection_timeout": kwargs.get( "blocked_connection_timeout", self._blocked_connection_timeout ), "credentials": credentials, } return ConnectionParameters(**conn_params) class TransientPikaClient(PikaClient): """Client implementation that creates new connection and channel for each action""" def __init__(self, **kwargs): super(TransientPikaClient, self).__init__(**kwargs) def is_alive(self): try: with BlockingConnection( self.connection_parameters(connection_attempts=1) ) as conn: return conn.is_open except AMQPError: return False def declare_exchange(self): with BlockingConnection(self._conn_params) as conn: conn.channel().exchange_declare( exchange=self._exchange, exchange_type="topic", durable=True ) def setup_queue(self, queue_name, queue_args, routing_keys): """Create a new queue with queue_args and bind it to routing_keys""" with BlockingConnection(self._conn_params) as conn: conn.channel().queue_declare(queue_name, **queue_args) for routing_key in routing_keys: conn.channel().queue_bind( queue_name, self._exchange, routing_key=routing_key ) return {"name": queue_name, "args": queue_args} def publish(self, message, **kwargs): """Publish a message Args: message: Message to publish kwargs: Additional message properties Keyword Arguments: * *routing_key* -- Routing key to use when publishing * *headers* -- Headers to be included as part of the message properties * *expiration* -- Expiration to be included as part of the message properties * *confirm* -- Flag indicating whether to operate in publisher-acknowledgements mode * *mandatory* -- Raise if the message can not be routed to any queues * *priority* -- Message priority """ with BlockingConnection(self._conn_params) as conn: channel = conn.channel() if kwargs.get("confirm"): channel.confirm_delivery() properties = BasicProperties( app_id="beer-garden", content_type="text/plain", headers=kwargs.get("headers"), expiration=kwargs.get("expiration"), delivery_mode=kwargs.get("delivery_mode"), priority=kwargs.get("priority"), ) channel.basic_publish( exchange=self._exchange, routing_key=kwargs["routing_key"], body=message, properties=properties, mandatory=kwargs.get("mandatory"), ) class PikaConsumer(RequestConsumer): """Pika message consumer This consumer is designed to be fault-tolerant - if RabbitMQ closes the connection the consumer will attempt to reopen it. There are limited reasons why the connection may be closed from the broker side and usually indicates permission related issues or socket timeouts. Unexpected channel closures can indicate a problem with a command that was issued. Args: amqp_url: (str) The AMQP url to connect to queue_name: (str) The name of the queue to connect to on_message_callback (func): function called to invoke message processing. Must return a Future. panic_event (threading.Event): Event to be set on a catastrophic failure logger (logging.Logger): A configured Logger thread_name (str): Name to use for this thread max_concurrent: (int) Maximum requests to process concurrently max_reconnect_attempts (int): Number of times to attempt reconnection to message queue before giving up (default -1 aka never) max_reconnect_timeout (int): Maximum time to wait before reconnect attempt starting_reconnect_timeout (int): Time to wait before first reconnect attempt """ def __init__( self, amqp_url=None, queue_name=None, panic_event=None, logger=None, thread_name=None, **kwargs ): self._connection = None self._channel = None self._consumer_tag = None self._queue_name = queue_name self._panic_event = panic_event self._max_concurrent = kwargs.get("max_concurrent", 1) self.logger = logger or logging.getLogger(__name__) self._max_reconnect_attempts = kwargs.get("max_reconnect_attempts", -1) self._max_reconnect_timeout = kwargs.get("max_reconnect_timeout", 30) self._reconnect_timeout = kwargs.get("starting_reconnect_timeout", 5) self._reconnect_attempt = 0 if "connection_info" in kwargs: params = kwargs["connection_info"] # Default to one attempt as the Plugin implements its own retry logic params["connection_attempts"] = params.get("connection_attempts", 1) self._connection_parameters = PikaClient(**params).connection_parameters() else: self._connection_parameters = URLParameters(amqp_url) super(PikaConsumer, self).__init__(name=thread_name) def run(self): """Run the consumer This method creates a connection to RabbitMQ and starts the IOLoop. The IOLoop will block and allow the SelectConnection to operate. This means that to stop the PikaConsumer we just need to stop the IOLoop. If the connection closed unexpectedly (the shutdown event is not set) then this will wait a certain amount of time and before attempting to restart it. Finally, if the maximum number of reconnect attempts have been reached the panic event will be set, which will end the PikaConsumer as well as the Plugin. Returns: None """ while not self._panic_event.is_set(): self._connection = self.open_connection() self._connection.ioloop.start() if not self._panic_event.is_set(): if 0 <= self._max_reconnect_attempts <= self._reconnect_attempt: self.logger.warning("Max connection failures, shutting down") self._panic_event.set() return self.logger.warning( "%s consumer has died, waiting %i seconds before reconnecting", self._queue_name, self._reconnect_timeout, ) self._panic_event.wait(self._reconnect_timeout) self._reconnect_attempt += 1 self._reconnect_timeout = min( self._reconnect_timeout * 2, self._max_reconnect_timeout ) def stop(self): """Cleanly shutdown It's a good idea to call stop_consuming before this to prevent new messages from being processed during shutdown. This sets the shutdown_event to let callbacks know that this is an orderly (requested) shutdown. It then schedules a channel close on the IOLoop - the channel's on_close callback will close the connection, and the connection's on_close callback will terminate the IOLoop which will end the PikaConsumer. Returns: None """ self.logger.debug("Stopping request consumer") if self._connection: self._connection.ioloop.add_callback_threadsafe( partial(self._connection.close) ) def is_connected(self): """Determine if the underlying connection is open Returns: True if the connection exists and is open, False otherwise """ return self._connection and self._connection.is_open def on_message(self, channel, basic_deliver, properties, body): """Invoked when a message is delivered from the queueing service Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange, routing key, delivery tag and a redelivered flag for the message. the properties passed in is an instance of BasicProperties with the message properties and the body is the message that was sent. Args: channel (pika.channel.Channel): The channel object basic_deliver (pika.Spec.Basic.Deliver): basic_deliver method properties (pika.Spec.BasicProperties): Message properties body (bytes): The message body """ self.logger.debug( "Received message #%s from %s on channel %s: %s", basic_deliver.delivery_tag, properties.app_id, channel.channel_number, body, ) # Pika gives us bytes, but we want a string to be ok too try: body = body.decode() except AttributeError: pass try: future = self._on_message_callback(body, properties.headers) future.add_done_callback( partial(self.on_message_callback_complete, basic_deliver) ) except Exception as ex: requeue = not isinstance(ex, DiscardMessageException) self.logger.exception( "Exception while trying to schedule message %s, about to nack%s: %s" % (basic_deliver.delivery_tag, " and requeue" if requeue else "", ex) ) self._channel.basic_nack(basic_deliver.delivery_tag, requeue=requeue) def on_message_callback_complete(self, basic_deliver, future): """Invoked when the future returned by _on_message_callback completes. This method will be invoked from the threadpool context. It's only purpose is to schedule the final processing steps to take place on the connection's ioloop. Args: basic_deliver: future: Completed future Returns: None """ self._connection.ioloop.add_callback_threadsafe( partial(self.finish_message, basic_deliver, future) ) def finish_message(self, basic_deliver, future): """Finish processing a message This should be invoked as the final part of message processing. It's responsible for acking / nacking messages back to the broker. The main complexity here depends on whether the request processing future has an exception: - If there is no exception it acks the message - If there is an exception - If the exception is an instance of DiscardMessageException it acks the message and does not requeue it - If the exception is an instance of RepublishRequestException it will construct an entirely new BlockingConnection, use that to publish a new message, and then ack the original message - If the exception is not an instance of either the panic_event is set and the consumer will self-destruct Also, if there's ever an error acking a message the panic_event is set and the consumer will self-destruct. Args: basic_deliver: future: Completed future Returns: None """ delivery_tag = basic_deliver.delivery_tag if not future.exception(): try: self.logger.debug("Acking message %s", delivery_tag) self._channel.basic_ack(delivery_tag) except Exception as ex: self.logger.exception( "Error acking message %s, about to shut down: %s", delivery_tag, ex ) self._panic_event.set() else: real_ex = future.exception() if isinstance(real_ex, RepublishRequestException): try: with BlockingConnection(self._connection_parameters) as c: headers = real_ex.headers headers.update({"request_id": real_ex.request.id}) props = BasicProperties( app_id="beer-garden", content_type="text/plain", headers=headers, priority=1, delivery_mode=PERSISTENT_DELIVERY_MODE, ) c.channel().basic_publish( exchange=basic_deliver.exchange, properties=props, routing_key=basic_deliver.routing_key, body=SchemaParser.serialize_request(real_ex.request), ) self._channel.basic_ack(delivery_tag) except Exception as ex: self.logger.exception( "Error republishing message %s, about to shut down: %s", delivery_tag, ex, ) self._panic_event.set() elif isinstance(real_ex, DiscardMessageException): self.logger.info( "Nacking message %s, not attempting to requeue", delivery_tag ) self._channel.basic_nack(delivery_tag, requeue=False) else: # If request processing throws anything else we terminate self.logger.exception( "Unexpected exception during request %s processing, about " "to shut down: %s", delivery_tag, real_ex, exc_info=False, ) self._panic_event.set() def open_connection(self): """Opens a connection to RabbitMQ This method immediately returns the connection object. However, whether the connection was successful is not know until a callback is invoked (either on_open_callback or on_open_error_callback). Returns: The SelectConnection object """ return SelectConnection( parameters=self._connection_parameters, on_open_callback=self.on_connection_open, on_close_callback=self.on_connection_closed, on_open_error_callback=self.on_connection_closed, ) def on_connection_open(self, connection): """Connection open success callback This method is called by pika once the connection to RabbitMQ has been established. The only thing this actually does is call the open_channel method. Args: connection: The connection object Returns: None """ self.logger.debug("Connection opened: %s", connection) if self._reconnect_attempt: self.logger.info("%s consumer successfully reconnected", self._queue_name) self._reconnect_attempt = 0 self.open_channel() def on_connection_closed(self, connection, *args): """Connection closed callback This method is invoked by pika when the connection to RabbitMQ is closed. If the connection is closed we terminate its IOLoop to stop the PikaConsumer. In the case of an unexpected connection closure we'll wait 5 seconds before terminating with the expectation that the plugin will attempt to restart the consumer once it's dead. Args: connection: The connection args: Tuple of arguments describing why the connection closed For pika < 1: reply_code (Numeric code indicating close reason), reply_text (String describing close reason). For pika >= 1 exc (Exception describing close). Returns: None """ self.logger.debug("Connection %s closed: %s", connection, args) self._connection.ioloop.stop() def open_channel(self): """Open a channel""" self.logger.debug("Opening a new channel") self._connection.channel(on_open_callback=self.on_channel_open) def on_channel_open(self, channel): """Channel open success callback This will add a close callback (on_channel_closed) the channel and will call start_consuming to begin receiving messages. Args: channel: The opened channel object Returns: None """ self.logger.debug("Channel opened: %s", channel) self._channel = channel self._channel.add_on_close_callback(self.on_channel_closed) self.start_consuming() def on_channel_closed(self, channel, *args): """Channel closed callback This method is invoked by pika when the channel is closed. Channels are usually closed as a result of something that violates the protocol, such as attempting to re-declare an exchange or queue with different parameters. This indicates that something has gone wrong, so just close the connection (if it's still open) to reset. Args: channel: The channel args: Tuple of arguments describing why the channel closed For pika < 1: reply_code (Numeric code indicating close reason), reply_text (String describing close reason). For pika >= 1 exc (Exception describing close). Returns: None """ self.logger.debug("Channel %i closed: %s", channel, args) if self._connection.is_open: self._connection.close() def start_consuming(self): """Begin consuming messages The RabbitMQ prefetch is set to the maximum number of concurrent consumers. This ensures that messages remain in RabbitMQ until a consuming thread is available to process them. An on_cancel_callback is registered so that the consumer is notified if it is canceled by the broker. Returns: None """ self.logger.debug("Issuing consumer related RPC commands") self._channel.basic_qos(prefetch_count=self._max_concurrent) self._channel.add_on_cancel_callback(self.on_consumer_cancelled) self._consumer_tag = self._channel.basic_consume( queue=self._queue_name, on_message_callback=self.on_message ) def stop_consuming(self): """Stop consuming messages Sends a Basic.Cancel command to the broker, which causes the broker to stop sending the consumer messages. Returns: None """ if self._channel and self._channel.is_open: self.logger.debug("Stopping message consuming on channel %i", self._channel) self._connection.ioloop.add_callback_threadsafe( partial( self._channel.basic_cancel, consumer_tag=self._consumer_tag, callback=lambda *args: None, ) ) def on_consumer_cancelled(self, method_frame): """Consumer cancelled callback This is only invoked if the consumer is cancelled by the broker. Since that effectively ends the request consuming we close the channel to start the process of terminating the PikaConsumer. Args: method_frame (pika.frame.Method): The Basic.Cancel frame Returns: None """ self.logger.debug("Consumer was cancelled: %r", method_frame) if self._channel: self._connection.close()
3,220
0
135
90981bee8a0d229ba74215f51d1463d24174a322
2,790
py
Python
norm/executable/schema/type.py
reasoned-ai/norm
5e45d5917ce8745c9a757a0c6b5e689ea0cac19f
[ "Apache-2.0" ]
8
2019-07-22T08:57:20.000Z
2021-03-26T13:51:02.000Z
norm/executable/schema/type.py
xumiao/norm
5e45d5917ce8745c9a757a0c6b5e689ea0cac19f
[ "Apache-2.0" ]
null
null
null
norm/executable/schema/type.py
xumiao/norm
5e45d5917ce8745c9a757a0c6b5e689ea0cac19f
[ "Apache-2.0" ]
1
2019-11-16T13:37:35.000Z
2019-11-16T13:37:35.000Z
from norm.executable import NormError, NormExecutable from norm.models import ListLambda, Lambda, Variable, Status import logging logger = logging.getLogger(__name__)
31
116
0.574194
from norm.executable import NormError, NormExecutable from norm.models import ListLambda, Lambda, Variable, Status import logging logger = logging.getLogger(__name__) class TypeName(NormExecutable): def __init__(self, name, version=None): """ The type qualified name :param name: name of the type :type name: str :param version: version of the type :type version: str """ super().__init__() self.namespace = None self.name = name self.version = version assert(self.name is not None) assert(self.name != '') def __str__(self): s = self.namespace + '.' if self.namespace else '' s += self.name s += self.version if self.version is not None else '$latest' return s def compile(self, context): """ Retrieve the Lambda function by namespace, name, version. Note that user is encoded by the version. :rtype: Lambda """ if self.name == context.THAT_VARIABLE_NAME: self.lam = context.that return self if self.namespace is None: lam = self.try_retrieve_type(context.session, context.context_namespace, self.name, self.version) if lam is None: lam = self.try_retrieve_type(context.session, context.search_namespaces, self.name, self.version, Status.READY) else: if self.namespace == context.context_namespace: lam = self.try_retrieve_type(context.session, self.namespace, self.name, self.version) else: lam = self.try_retrieve_type(context.session, self.namespace, self.name, self.version, Status.READY) self.lam = lam return self class ListType(NormExecutable): def __init__(self, intern): """ The type of List with intern type :param intern: the type of the intern :type intern: TypeName """ super().__init__() self.intern = intern def compile(self, context): """ Return a list type :rtype: ListLambda """ lam = self.intern.lam if lam.id is None: msg = "{} does not seem to be declared yet".format(self.intern) logger.error(msg) raise NormError(msg) q = context.session.query(ListLambda, Variable).join(ListLambda.variables)\ .filter(Variable.type_id == lam.id) llam = q.first() if llam is None: # create a new ListLambda llam = ListLambda(lam) context.session.add(llam) else: llam = llam[0] self.lam = llam return self
165
2,408
46
743583c448133c940588bb31d74e31b932be2609
2,498
py
Python
nutricionistas/users/forms.py
karinamg17/nutricionistas
d7cac627fd25692f9db88525d1b8da326f1dde5f
[ "MIT" ]
null
null
null
nutricionistas/users/forms.py
karinamg17/nutricionistas
d7cac627fd25692f9db88525d1b8da326f1dde5f
[ "MIT" ]
null
null
null
nutricionistas/users/forms.py
karinamg17/nutricionistas
d7cac627fd25692f9db88525d1b8da326f1dde5f
[ "MIT" ]
null
null
null
import re from allauth.account.forms import SignupForm from django import forms as form2 from django.contrib.auth import forms as admin_forms from django.contrib.auth import get_user_model from django.utils.translation import gettext_lazy as _ User = get_user_model()
35.685714
126
0.702162
import re from allauth.account.forms import SignupForm from django import forms as form2 from django.contrib.auth import forms as admin_forms from django.contrib.auth import get_user_model from django.utils.translation import gettext_lazy as _ User = get_user_model() class UserChangeForm(admin_forms.UserChangeForm): class Meta(admin_forms.UserChangeForm.Meta): model = User class UserCreationForm(admin_forms.UserCreationForm): class Meta(admin_forms.UserCreationForm.Meta): model = User error_messages = { "username": {"unique": _("This username has already been taken.")} } class DateInput(form2.DateInput): input_type = 'date' class UserProfileForm(form2.ModelForm): class Meta: model = User fields = 'first_name', 'last_name', 'nro_telefono', 'nro_telefono', 'sexo', 'fecha_nacimiento' widgets = { 'fecha_nacimiento': DateInput(), 'sexo': form2.Select(attrs={'class': 'form-control default-select'}), } class MyCustomSignupForm(SignupForm): TIPO_DOCUMENTO_CHOICES = (('Cédula', 'Cédula'), ('Cédula extranjería', 'Cédula extranjería'), ('Pasaporte', 'Pasaporte'),) first_name = form2.CharField(max_length=30, label='Nombres') last_name = form2.CharField(max_length=30, label='Apellidos') tipo_documento = form2.ChoiceField(choices=TIPO_DOCUMENTO_CHOICES) nro_documento = form2.CharField(max_length=25, label='Nro de documento de identidad', required=True, ) accept_terms = form2.BooleanField(label='Acepto los términos y condiciones',) def clean_nro_documento(self): nro_documento = self.cleaned_data.get("nro_documento") # parse digits from the string nro_documento_list = re.findall("\d+", nro_documento) nro_documento = ''.join(nro_documento_list) if User.objects.filter(nro_documento=nro_documento).exists(): raise form2.ValidationError("Ya existe un cliente con este nro. de documento.") return nro_documento def save(self, request): user = super(MyCustomSignupForm, self).save(request) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.tipo_documento = self.cleaned_data['tipo_documento'] user.nro_documento = self.cleaned_data['nro_documento'] user.accept_terms = self.cleaned_data['accept_terms'] user.validate_unique() user.save() return user
860
1,255
115
3039299991f63413c05107a6c6337f3773775775
420
py
Python
extensions/cencalvm/__init__.py
baagaard-usgs/cencalvm
c6cca356c722f150178416e5f98a1506dd733db6
[ "CC0-1.0" ]
null
null
null
extensions/cencalvm/__init__.py
baagaard-usgs/cencalvm
c6cca356c722f150178416e5f98a1506dd733db6
[ "CC0-1.0" ]
null
null
null
extensions/cencalvm/__init__.py
baagaard-usgs/cencalvm
c6cca356c722f150178416e5f98a1506dd733db6
[ "CC0-1.0" ]
null
null
null
#!/usr/bin/env python # # ---------------------------------------------------------------------- # # Brad T. Aagaard # U.S. Geological Survey # # <LicenseText> # # ---------------------------------------------------------------------- # ## @file cencalvm/__init__.py ## ## @brief Python top-level CenCalVM module initialization __all__ = ['CenCalVMDB'] # End of file
20
72
0.359524
#!/usr/bin/env python # # ---------------------------------------------------------------------- # # Brad T. Aagaard # U.S. Geological Survey # # <LicenseText> # # ---------------------------------------------------------------------- # ## @file cencalvm/__init__.py ## ## @brief Python top-level CenCalVM module initialization __all__ = ['CenCalVMDB'] # End of file
0
0
0
496a4b7bd3a7d0cde01a6dc3362ce52cf77f9222
560
py
Python
config.py
bnguyen2/covid-hackathon
016ce5f0239c8f182840420d4a946da3603775ee
[ "Apache-2.0" ]
1
2020-04-16T05:41:07.000Z
2020-04-16T05:41:07.000Z
config.py
bnguyen2/covid-hackathon
016ce5f0239c8f182840420d4a946da3603775ee
[ "Apache-2.0" ]
27
2020-03-31T02:21:33.000Z
2020-04-12T23:13:43.000Z
config.py
bnguyen2/covid-hackathon
016ce5f0239c8f182840420d4a946da3603775ee
[ "Apache-2.0" ]
1
2020-04-12T16:37:31.000Z
2020-04-12T16:37:31.000Z
""" A bunch of variables that are intended to be shared across the Flask codebase """ from flask import Flask import db import logging MAIN_APP = Flask(__name__) LOGGER = MAIN_APP.logger LOGGER.setLevel(logging.INFO) MAIN_DB = db.Database(MAIN_APP).getDb() POSSIBLE_NEEDS = [ 'N95', 'N95s', 'Gloves', 'Safety Goggles', 'Face Shields', 'Surgical Masks', 'Surgical Mask', 'Disposable Booties', 'Thermometers', 'Thermometer', 'Disinfectant Wipes', 'Disinfectant Wipe', 'Disposable Booties', 'Currency' ]
18.064516
39
0.669643
""" A bunch of variables that are intended to be shared across the Flask codebase """ from flask import Flask import db import logging MAIN_APP = Flask(__name__) LOGGER = MAIN_APP.logger LOGGER.setLevel(logging.INFO) MAIN_DB = db.Database(MAIN_APP).getDb() POSSIBLE_NEEDS = [ 'N95', 'N95s', 'Gloves', 'Safety Goggles', 'Face Shields', 'Surgical Masks', 'Surgical Mask', 'Disposable Booties', 'Thermometers', 'Thermometer', 'Disinfectant Wipes', 'Disinfectant Wipe', 'Disposable Booties', 'Currency' ]
0
0
0
222fdbd75646eb56729f9caa7ba7cb3b9995f45c
26,582
py
Python
events/api_views.py
renzyndrome/lits-crm
32daea8c76f91780b8cc8c3f107d04df606c0ec8
[ "MIT" ]
1
2021-03-01T12:07:10.000Z
2021-03-01T12:07:10.000Z
events/api_views.py
renzyndrome/lits-crm
32daea8c76f91780b8cc8c3f107d04df606c0ec8
[ "MIT" ]
null
null
null
events/api_views.py
renzyndrome/lits-crm
32daea8c76f91780b8cc8c3f107d04df606c0ec8
[ "MIT" ]
null
null
null
from django.db.models import Q from contacts.models import Contact from contacts.serializer import ContactSerializer from common.models import User, Attachments, Comment from common.custom_auth import JSONWebTokenAuthentication from common.serializer import ( UserSerializer, CommentSerializer, AttachmentsSerializer, CommentSerializer, ) from events import swagger_params from events.models import Event from events.serializer import EventSerializer, EventCreateSerializer from events.tasks import send_email from teams.serializer import TeamsSerializer from teams.models import Teams from rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated from rest_framework.pagination import LimitOffsetPagination from drf_yasg.utils import swagger_auto_schema import json from datetime import datetime, timedelta WEEKDAYS = ( ("Monday", "Monday"), ("Tuesday", "Tuesday"), ("Wednesday", "Wednesday"), ("Thursday", "Thursday"), ("Friday", "Friday"), ("Saturday", "Saturday"), ("Sunday", "Sunday"), )
41.212403
88
0.520615
from django.db.models import Q from contacts.models import Contact from contacts.serializer import ContactSerializer from common.models import User, Attachments, Comment from common.custom_auth import JSONWebTokenAuthentication from common.serializer import ( UserSerializer, CommentSerializer, AttachmentsSerializer, CommentSerializer, ) from events import swagger_params from events.models import Event from events.serializer import EventSerializer, EventCreateSerializer from events.tasks import send_email from teams.serializer import TeamsSerializer from teams.models import Teams from rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated from rest_framework.pagination import LimitOffsetPagination from drf_yasg.utils import swagger_auto_schema import json from datetime import datetime, timedelta WEEKDAYS = ( ("Monday", "Monday"), ("Tuesday", "Tuesday"), ("Wednesday", "Wednesday"), ("Thursday", "Thursday"), ("Friday", "Friday"), ("Saturday", "Saturday"), ("Sunday", "Sunday"), ) class EventListView(APIView, LimitOffsetPagination): model = Event authentication_classes = (JSONWebTokenAuthentication,) permission_classes = (IsAuthenticated,) def get_context_data(self, **kwargs): params = ( self.request.query_params if len(self.request.data) == 0 else self.request.data ) queryset = self.model.objects.filter(company=self.request.company) contacts = Contact.objects.filter(company=self.request.company) if self.request.user.role != "ADMIN" and not self.request.user.is_superuser: queryset = queryset.filter( Q(assigned_to__in=[self.request.user]) | Q(created_by=self.request.user) ) contacts = contacts.filter( Q(created_by=self.request.user) | Q(assigned_to=self.request.user) ).distinct() if params: if params.get("name"): queryset = queryset.filter(name__icontains=params.get("name")) if params.get("created_by"): queryset = queryset.filter(created_by=params.get("created_by")) if params.getlist("assigned_users"): queryset = queryset.filter( assigned_to__id__in=json.loads(params.get("assigned_users")) ) if params.get("date_of_meeting"): queryset = queryset.filter( date_of_meeting=params.get("date_of_meeting") ) context = {} search = False if ( params.get("name") or params.get("created_by") or params.get("assigned_users") or params.get("date_of_meeting") ): search = True context["search"] = search results_events = self.paginate_queryset(queryset, self.request, view=self) events = EventSerializer(results_events, many=True).data context["per_page"] = 10 context.update( { "events_count": self.count, "next": self.get_next_link(), "previous": self.get_previous_link(), "page_number": int(self.offset / 10) + 1, } ) if search: context["events"] = events return context context["events"] = events users = [] if self.request.user.role == "ADMIN" or self.request.user.is_superuser: users = User.objects.filter( is_active=True, company=self.request.company ).order_by("email") else: users = User.objects.filter( role="ADMIN", company=self.request.company ).order_by("email") context["recurring_days"] = WEEKDAYS context["users"] = UserSerializer(users, many=True).data if self.request.user == "ADMIN": context["teams_list"] = TeamsSerializer( Teams.objects.filter(company=self.request.company), many=True ).data context["contacts_list"] = ContactSerializer(contacts, many=True).data return context @swagger_auto_schema( tags=["Events"], manual_parameters=swagger_params.event_list_get_params ) def get(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) return Response(context) @swagger_auto_schema( tags=["Events"], manual_parameters=swagger_params.event_create_post_params ) def post(self, request, *args, **kwargs): params = ( self.request.query_params if len(self.request.data) == 0 else self.request.data ) data = {} serializer = EventCreateSerializer(data=params, request_obj=request) if serializer.is_valid(): start_date = params.get("start_date") end_date = params.get("end_date") recurring_days = json.dumps(params.get("recurring_days")) if params.get("event_type") == "Non-Recurring": event_obj = serializer.save( created_by=request.user, company=request.company, date_of_meeting=params.get("start_date"), is_active=True, disabled=False, ) if params.get("contacts"): contacts = json.loads(params.get("contacts")) for contact in contacts: obj_contact = Contact.objects.filter( id=contact, company=request.company ) if obj_contact: event_obj.contacts.add(contact) else: event_obj.delete() data["contacts"] = "Please enter valid contact" return Response({"error": True, "errors": data}) if self.request.user.role == "ADMIN": if params.get("teams"): teams = json.loads(params.get("teams")) for team in teams: teams_ids = Teams.objects.filter( id=team, company=request.company ) if teams_ids: event_obj.teams.add(team) else: event_obj.delete() data["team"] = "Please enter valid Team" return Response({"error": True, "errors": data}) if params.get("assigned_to"): assinged_to_users_ids = json.loads(params.get("assigned_to")) for user_id in assinged_to_users_ids: user = User.objects.filter( id=user_id, company=request.company ) if user: event_obj.assigned_to.add(user_id) else: event_obj.delete() data["assigned_to"] = "Please enter valid User" return Response({"error": True, "errors": data}) assigned_to_list = list( event_obj.assigned_to.all().values_list("id", flat=True) ) send_email.delay( event_obj.id, assigned_to_list, domain=request.get_host(), protocol=request.scheme, ) if params.get("event_type") == "Recurring": recurring_days = params.get("recurring_days") if not recurring_days: return Response( {"error": True, "errors": "Choose atleast one recurring day"} ) end_date = datetime.strptime(end_date, "%Y-%m-%d").date() start_date = datetime.strptime(start_date, "%Y-%m-%d").date() delta = end_date - start_date required_dates = [] for day in range(delta.days + 1): each_date = start_date + timedelta(days=day) if each_date.strftime("%A") in recurring_days: required_dates.append(each_date) for each in required_dates: each = datetime.strptime(str(each), "%Y-%m-%d").date() data = serializer.validated_data event = Event.objects.create( created_by=request.user, start_date=start_date, end_date=end_date, name=data["name"], event_type=data["event_type"], description=data["description"], start_time=data["start_time"], end_time=data["end_time"], date_of_meeting=each, company=request.company, ) if params.get("contacts"): contacts = json.loads(params.get("contacts")) for contact in contacts: obj_contact = Contact.objects.filter( id=contact, company=request.company ) if obj_contact: event.contacts.add(contact) else: event.delete() data["contacts"] = "Please enter valid contact" return Response({"error": True, "errors": data}) if self.request.user.role == "ADMIN": if params.get("teams"): teams = json.loads(params.get("teams")) for team in teams: teams_ids = Teams.objects.filter( id=team, company=request.company ) if teams_ids: event.teams.add(team) else: event.delete() data["team"] = "Please enter valid Team" return Response({"error": True, "errors": data}) if params.get("assigned_to"): assinged_to_users_ids = json.loads( params.get("assigned_to") ) for user_id in assinged_to_users_ids: user = User.objects.filter( id=user_id, company=request.company ) if user: event.assigned_to.add(user_id) else: event.delete() data["assigned_to"] = "Please enter valid User" return Response({"error": True, "errors": data}) assigned_to_list = list( event.assigned_to.all().values_list("id", flat=True) ) send_email.delay( event.id, assigned_to_list, domain=request.get_host(), protocol=request.scheme, ) return Response( {"error": False, "message": "Event Created Successfully"}, status=status.HTTP_200_OK, ) return Response( {"error": True, "errors": serializer.errors}, status=status.HTTP_400_BAD_REQUEST, ) class EventDetailView(APIView): model = Event authentication_classes = (JSONWebTokenAuthentication,) permission_classes = (IsAuthenticated,) def get_object(self, pk): return Event.objects.get(pk=pk) def get_context_data(self, **kwargs): context = {} user_assgn_list = [ assigned_to.id for assigned_to in self.event_obj.assigned_to.all() ] if self.request.user == self.event_obj.created_by: user_assgn_list.append(self.request.user.id) if self.request.user.role != "ADMIN" and not self.request.user.is_superuser: if self.request.user.id not in user_assgn_list: return Response( { "error": True, "errors": "You don't have Permission to perform this action", } ) comments = Comment.objects.filter(event=self.event_obj).order_by("-id") attachments = Attachments.objects.filter(event=self.event_obj).order_by("-id") assigned_data = self.event_obj.assigned_to.values("id", "email") if self.request.user.is_superuser or self.request.user.role == "ADMIN": users_mention = list( User.objects.filter( is_active=True, company=self.request.company ).values("username") ) elif self.request.user != self.event_obj.created_by: users_mention = [{"username": self.event_obj.created_by.username}] else: users_mention = list(self.event_obj.assigned_to.all().values("username")) if self.request.user.role == "ADMIN" or self.request.user.is_superuser: users = User.objects.filter( is_active=True, company=self.request.company ).order_by("email") else: users = User.objects.filter( role="ADMIN", company=self.request.company ).order_by("email") if self.request.user == self.event_obj.created_by: user_assgn_list.append(self.request.user.id) if self.request.user.role != "ADMIN" and not self.request.user.is_superuser: if self.request.user.id not in user_assgn_list: return Response( { "error": True, "errors": "You don't have Permission to perform this action", } ) team_ids = [user.id for user in self.event_obj.get_team_users] all_user_ids = users.values_list("id", flat=True) users_excluding_team_id = set(all_user_ids) - set(team_ids) users_excluding_team = User.objects.filter(id__in=users_excluding_team_id) selected_recurring_days = Event.objects.filter( name=self.event_obj.name ).values_list("date_of_meeting", flat=True) selected_recurring_days = set( [day.strftime("%A") for day in selected_recurring_days] ) context.update( { "event_obj": EventSerializer(self.event_obj).data, "attachments": AttachmentsSerializer(attachments, many=True).data, "comments": CommentSerializer(comments, many=True).data, "selected_recurring_days": selected_recurring_days, "users_mention": users_mention, "assigned_data": assigned_data, } ) context["users"] = UserSerializer(users, many=True).data context["users_excluding_team"] = UserSerializer( users_excluding_team, many=True ).data context["teams"] = TeamsSerializer( Teams.objects.filter(company=self.request.company), many=True ).data return context @swagger_auto_schema( tags=["Events"], manual_parameters=swagger_params.event_delete_params ) def get(self, request, pk, **kwargs): self.event_obj = self.get_object(pk) if self.event_obj.company != request.company: return Response( {"error": True, "errors": "User company doesnot match with header...."} ) context = self.get_context_data(**kwargs) return Response(context) @swagger_auto_schema( tags=["Events"], manual_parameters=swagger_params.event_detail_post_params ) def post(self, request, pk, **kwargs): params = ( self.request.query_params if len(self.request.data) == 0 else self.request.data ) context = {} self.event_obj = Event.objects.get(pk=pk) if self.event_obj.company != request.company: return Response( {"error": True, "errors": "User company does not match with header...."} ) if self.request.user.role != "ADMIN" and not self.request.user.is_superuser: if not ( (self.request.user == self.event_obj.created_by) or (self.request.user in self.event_obj.assigned_to.all()) ): return Response( { "error": True, "errors": "You don't have Permission to perform this action", }, status=status.HTTP_401_UNAUTHORIZED, ) comment_serializer = CommentSerializer(data=params) if comment_serializer.is_valid(): if params.get("comment"): comment_serializer.save( event_id=self.event_obj.id, commented_by_id=self.request.user.id, ) if self.request.FILES.get("event_attachment"): attachment = Attachments() attachment.created_by = self.request.user attachment.file_name = self.request.FILES.get("event_attachment").name attachment.event = self.event_obj attachment.attachment = self.request.FILES.get("event_attachment") attachment.save() comments = Comment.objects.filter(event__id=self.event_obj.id).order_by("-id") attachments = Attachments.objects.filter(event__id=self.event_obj.id).order_by( "-id" ) context.update( { "event_obj": EventSerializer(self.event_obj).data, "attachments": AttachmentsSerializer(attachments, many=True).data, "comments": CommentSerializer(comments, many=True).data, } ) return Response(context) @swagger_auto_schema( tags=["Events"], manual_parameters=swagger_params.event_create_post_params ) def put(self, request, pk, **kwargs): params = ( self.request.query_params if len(self.request.data) == 0 else self.request.data ) data = {} self.event_obj = self.get_object(pk) if self.event_obj.company != request.company: return Response( {"error": True, "errors": "User company doesnot match with header...."} ) serializer = EventCreateSerializer( data=params, instance=self.event_obj, request_obj=request, ) if serializer.is_valid(): event_obj = serializer.save() previous_assigned_to_users = list( event_obj.assigned_to.all().values_list("id", flat=True) ) if params.get("event_type") == "Non-Recurring": event_obj.date_of_meeting = event_obj.start_date event_obj.contacts.clear() if params.get("contacts"): contacts = json.loads(params.get("contacts")) for contact in contacts: obj_contact = Contact.objects.filter( id=contact, company=request.company ) if obj_contact: event_obj.contacts.add(contact) else: data["contacts"] = "Please enter valid Contact" return Response({"error": True, "errors": data}) if self.request.user.role == "ADMIN": event_obj.teams.clear() if params.get("teams"): teams = json.loads(params.get("teams")) for team in teams: teams_ids = Teams.objects.filter( id=team, company=request.company ) if teams_ids: event_obj.teams.add(team) else: event_obj.delete() data["team"] = "Please enter valid Team" return Response({"error": True, "errors": data}) else: event_obj.teams.clear() event_obj.assigned_to.clear() if params.get("assigned_to"): assinged_to_users_ids = json.loads(params.get("assigned_to")) for user_id in assinged_to_users_ids: user = User.objects.filter(id=user_id, company=request.company) if user: event_obj.assigned_to.add(user_id) else: event_obj.delete() data["assigned_to"] = "Please enter valid User" return Response({"error": True, "errors": data}) else: event_obj.assigned_to.clear() assigned_to_list = list( event_obj.assigned_to.all().values_list("id", flat=True) ) recipients = list(set(assigned_to_list) - set(previous_assigned_to_users)) send_email.delay( event_obj.id, recipients, domain=request.get_host(), protocol=request.scheme, ) return Response( {"error": False, "message": "Event updated Successfully"}, status=status.HTTP_200_OK, ) return Response( {"error": True, "errors": serializer.errors}, status=status.HTTP_400_BAD_REQUEST, ) @swagger_auto_schema( tags=["Events"], manual_parameters=swagger_params.event_delete_params ) def delete(self, request, pk, **kwargs): self.object = self.get_object(pk) if ( request.user.role == "ADMIN" or request.user.is_superuser or request.user == self.object.created_by ) and self.object.company == request.company: self.object.delete() return Response( {"error": False, "message": "Event deleted Successfully"}, status=status.HTTP_200_OK, ) return Response( {"error": True, "errors": "you don't have permission to delete this event"}, status=status.HTTP_403_FORBIDDEN, ) class EventCommentView(APIView): model = Comment authentication_classes = (JSONWebTokenAuthentication,) permission_classes = (IsAuthenticated,) def get_object(self, pk): return self.model.objects.get(pk=pk) @swagger_auto_schema( tags=["Events"], manual_parameters=swagger_params.event_comment_edit_params ) def put(self, request, pk, format=None): params = request.query_params if len(request.data) == 0 else request.data obj = self.get_object(pk) if ( request.user.role == "ADMIN" or request.user.is_superuser or request.user == obj.commented_by ): serializer = CommentSerializer(obj, data=params) if params.get("comment"): if serializer.is_valid(): serializer.save() return Response( {"error": False, "message": "Comment Submitted"}, status=status.HTTP_200_OK, ) return Response( {"error": True, "errors": serializer.errors}, status=status.HTTP_400_BAD_REQUEST, ) else: return Response( { "error": True, "errors": "You don't have Permission to perform this action", } ) @swagger_auto_schema( tags=["Events"], manual_parameters=swagger_params.event_delete_params ) def delete(self, request, pk, format=None): self.object = self.get_object(pk) if ( request.user.role == "ADMIN" or request.user.is_superuser or request.user == self.object.commented_by ): self.object.delete() return Response( {"error": False, "message": "Comment Deleted Successfully"}, status=status.HTTP_200_OK, ) else: return Response( { "error": True, "errors": "You don't have Permission to perform this action", } ) class EventAttachmentView(APIView): model = Attachments authentication_classes = (JSONWebTokenAuthentication,) permission_classes = (IsAuthenticated,) @swagger_auto_schema( tags=["Events"], manual_parameters=swagger_params.event_delete_params ) def delete(self, request, pk, format=None): self.object = self.model.objects.get(pk=pk) if ( request.user.role == "ADMIN" or request.user.is_superuser or request.user == self.object.created_by ): self.object.delete() return Response( {"error": False, "message": "Attachment Deleted Successfully"}, status=status.HTTP_200_OK, ) else: return Response( { "error": True, "errors": "You don't have Permission to perform this action", } )
23,411
1,922
92
eaeeb28af3bda10f0466a2aa6dc8fbf50e68d9c8
264
py
Python
ecogvis/signal_processing/tests/test_linenoise_notch.py
jgmakin/ecogVIS
a3aeba07c5f967ad51455506820083548ecfa5d9
[ "BSD-3-Clause" ]
4
2019-10-12T00:17:03.000Z
2020-05-08T03:05:05.000Z
ecogvis/signal_processing/tests/test_linenoise_notch.py
jgmakin/ecogVIS
a3aeba07c5f967ad51455506820083548ecfa5d9
[ "BSD-3-Clause" ]
7
2019-10-12T00:20:48.000Z
2019-12-07T01:39:45.000Z
ecogvis/signal_processing/tests/test_linenoise_notch.py
jgmakin/ecogVIS
a3aeba07c5f967ad51455506820083548ecfa5d9
[ "BSD-3-Clause" ]
1
2020-08-10T19:37:06.000Z
2020-08-10T19:37:06.000Z
import numpy as np from ecog.signal_processing import linenoise_notch def test_linenoise_notch_return(): """ Test the return shape. """ X = np.random.randn(32, 1000) rate = 200 Xh = linenoise_notch(X, rate) assert Xh.shape == X.shape
20.307692
50
0.670455
import numpy as np from ecog.signal_processing import linenoise_notch def test_linenoise_notch_return(): """ Test the return shape. """ X = np.random.randn(32, 1000) rate = 200 Xh = linenoise_notch(X, rate) assert Xh.shape == X.shape
0
0
0
480b5a5b150b0bf552bd882a4d4d83c6361fe676
3,049
py
Python
data/getdataset.py
NikolaySokolov152/Unet_multiclass
d07f6809b422519097560b07f67d0f139e718381
[ "MIT" ]
null
null
null
data/getdataset.py
NikolaySokolov152/Unet_multiclass
d07f6809b422519097560b07f67d0f139e718381
[ "MIT" ]
null
null
null
data/getdataset.py
NikolaySokolov152/Unet_multiclass
d07f6809b422519097560b07f67d0f139e718381
[ "MIT" ]
null
null
null
#Splitter import cv2 import numpy.random as random import numpy as np import os import time import skimage.io as io from AGCWD import* #borders #mitochondria #mitochondria borders #PSD #vesicles file_dir_arr = ["axon", "mitochondria", "PSD", "vesicles", "boundaries","mitochondrial boundaries"] name_list = [] mask_list = [] out_dir = "cutting data" size_data_arr = [256,512,768] size_step_arr = [128,256,256] for i in range(len(size_data_arr)): size_data = size_data_arr[i] size_step = size_step_arr[i] if not os.path.isdir(out_dir): print("создаю out_dir:" + out_dir) os.makedirs(out_dir) dir_input_img = "original data/original/" dir_input_mask ="original data/" for img_name in os.listdir(dir_input_img): count = 0 if is_Img(os.path.join(dir_input_img, img_name)): img = io.imread(os.path.join(dir_input_img, img_name)) if len(img.shape) == 3: img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = agcwd(img) h,w = img.shape[0:2] if not os.path.isdir(out_dir+"/original"): print("создаю out_dir:" + "original") os.makedirs(out_dir+"/original") for start_y in range(0,h, size_step): if (h - start_y < size_data): continue for start_x in range(0,w, size_step): if (w - start_x < size_data): continue cutting_img = img[start_y:start_y+size_data, start_x:start_x+size_data] cv2.imwrite(out_dir + "/original/" + img_name + "_" + str(size_data) +"_" + str(size_step) +"_" +str(count)+".png", cutting_img) count+=1 else: continue for i,dir_name in enumerate(file_dir_arr): for img_name in os.listdir(dir_input_mask + dir_name): if is_Img(os.path.join(dir_input_mask + dir_name, img_name)): img = cv2.imread(os.path.join(dir_input_mask +dir_name, img_name), 0) img[img < 128] = 0 img[img > 127] = 255 if name_list.count(img_name) == 0: name_list.append(img_name) mask_list.append(np.zeros((len(file_dir_arr),)+ img.shape, np.uint8)) index = name_list.index(img_name) mask_list[index][i] = img else: continue print(name_list) for index, mask_stack in enumerate(mask_list): count = 0 for i,dir_name in enumerate(file_dir_arr): local_count = count mask_write = mask_stack[i] h,w = mask_write.shape[0:2] if not os.path.isdir(out_dir+"/"+dir_name): print("создаю out_dir:" + "mask") os.makedirs(out_dir+"/"+dir_name ) for start_y in range(0,h, size_step): if (h - start_y < size_data): continue for start_x in range(0,w, size_step): if (w - start_x < size_data): continue cutting_mask = mask_write[start_y:start_y+size_data, start_x:start_x+size_data] cv2.imwrite(out_dir+"/"+dir_name +"/" + name_list[index] + "_" + str(size_data) +"_" + str(size_step) +"_" +str(local_count)+".png", cutting_mask) local_count+=1
25.408333
151
0.656281
#Splitter import cv2 import numpy.random as random import numpy as np import os import time import skimage.io as io from AGCWD import* #borders #mitochondria #mitochondria borders #PSD #vesicles def is_Img(name): img_type = ('.png', '.jpg', '.jpeg') if name.endswith((img_type)): return True else: return False file_dir_arr = ["axon", "mitochondria", "PSD", "vesicles", "boundaries","mitochondrial boundaries"] name_list = [] mask_list = [] out_dir = "cutting data" size_data_arr = [256,512,768] size_step_arr = [128,256,256] for i in range(len(size_data_arr)): size_data = size_data_arr[i] size_step = size_step_arr[i] if not os.path.isdir(out_dir): print("создаю out_dir:" + out_dir) os.makedirs(out_dir) dir_input_img = "original data/original/" dir_input_mask ="original data/" for img_name in os.listdir(dir_input_img): count = 0 if is_Img(os.path.join(dir_input_img, img_name)): img = io.imread(os.path.join(dir_input_img, img_name)) if len(img.shape) == 3: img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = agcwd(img) h,w = img.shape[0:2] if not os.path.isdir(out_dir+"/original"): print("создаю out_dir:" + "original") os.makedirs(out_dir+"/original") for start_y in range(0,h, size_step): if (h - start_y < size_data): continue for start_x in range(0,w, size_step): if (w - start_x < size_data): continue cutting_img = img[start_y:start_y+size_data, start_x:start_x+size_data] cv2.imwrite(out_dir + "/original/" + img_name + "_" + str(size_data) +"_" + str(size_step) +"_" +str(count)+".png", cutting_img) count+=1 else: continue for i,dir_name in enumerate(file_dir_arr): for img_name in os.listdir(dir_input_mask + dir_name): if is_Img(os.path.join(dir_input_mask + dir_name, img_name)): img = cv2.imread(os.path.join(dir_input_mask +dir_name, img_name), 0) img[img < 128] = 0 img[img > 127] = 255 if name_list.count(img_name) == 0: name_list.append(img_name) mask_list.append(np.zeros((len(file_dir_arr),)+ img.shape, np.uint8)) index = name_list.index(img_name) mask_list[index][i] = img else: continue print(name_list) for index, mask_stack in enumerate(mask_list): count = 0 for i,dir_name in enumerate(file_dir_arr): local_count = count mask_write = mask_stack[i] h,w = mask_write.shape[0:2] if not os.path.isdir(out_dir+"/"+dir_name): print("создаю out_dir:" + "mask") os.makedirs(out_dir+"/"+dir_name ) for start_y in range(0,h, size_step): if (h - start_y < size_data): continue for start_x in range(0,w, size_step): if (w - start_x < size_data): continue cutting_mask = mask_write[start_y:start_y+size_data, start_x:start_x+size_data] cv2.imwrite(out_dir+"/"+dir_name +"/" + name_list[index] + "_" + str(size_data) +"_" + str(size_step) +"_" +str(local_count)+".png", cutting_mask) local_count+=1
101
0
23
fbaa739b2ca7579baf049b4c78522a9593d65f92
2,944
py
Python
src/backend/common/models/tests/api_auth_access_test.py
guineawheek/ftc-data-take-2
337bff2077eadb3bd6bbebd153cbb6181c99516f
[ "MIT" ]
266
2015-01-04T00:10:48.000Z
2022-03-28T18:42:05.000Z
src/backend/common/models/tests/api_auth_access_test.py
guineawheek/ftc-data-take-2
337bff2077eadb3bd6bbebd153cbb6181c99516f
[ "MIT" ]
2,673
2015-01-01T20:14:33.000Z
2022-03-31T18:17:16.000Z
src/backend/common/models/tests/api_auth_access_test.py
guineawheek/ftc-data-take-2
337bff2077eadb3bd6bbebd153cbb6181c99516f
[ "MIT" ]
230
2015-01-04T00:10:48.000Z
2022-03-26T18:12:04.000Z
import pytest from backend.common.consts.auth_type import AuthType from backend.common.models.api_auth_access import ApiAuthAccess
30.350515
87
0.753736
import pytest from backend.common.consts.auth_type import AuthType from backend.common.models.api_auth_access import ApiAuthAccess def test_read_type_put() -> None: auth = ApiAuthAccess(auth_types_enum=[AuthType.EVENT_INFO, AuthType.READ_API]) with pytest.raises( Exception, match="Cannot combine AuthType.READ_API with other write auth types" ): auth.put() auth.auth_types_enum = [AuthType.EVENT_INFO] auth.put() auth.auth_types_enum = [AuthType.READ_API] auth.put() def test_can_edit_event_info() -> None: auth = ApiAuthAccess(auth_types_enum=[]) assert not auth.can_edit_event_info auth.auth_types_enum = [AuthType.EVENT_INFO] assert auth.can_edit_event_info def test_can_edit_event_teams() -> None: auth = ApiAuthAccess(auth_types_enum=[]) assert not auth.can_edit_event_teams auth.auth_types_enum = [AuthType.EVENT_TEAMS] assert auth.can_edit_event_teams def test_can_edit_event_matches() -> None: auth = ApiAuthAccess(auth_types_enum=[]) assert not auth.can_edit_event_matches auth.auth_types_enum = [AuthType.EVENT_MATCHES] assert auth.can_edit_event_matches def test_can_edit_event_rankings() -> None: auth = ApiAuthAccess(auth_types_enum=[]) assert not auth.can_edit_event_rankings auth.auth_types_enum = [AuthType.EVENT_RANKINGS] assert auth.can_edit_event_rankings def test_can_edit_event_alliances() -> None: auth = ApiAuthAccess(auth_types_enum=[]) assert not auth.can_edit_event_alliances auth.auth_types_enum = [AuthType.EVENT_ALLIANCES] assert auth.can_edit_event_alliances def test_can_edit_event_awards() -> None: auth = ApiAuthAccess(auth_types_enum=[]) assert not auth.can_edit_event_awards auth.auth_types_enum = [AuthType.EVENT_AWARDS] assert auth.can_edit_event_awards def test_can_edit_match_video() -> None: auth = ApiAuthAccess(auth_types_enum=[]) assert not auth.can_edit_match_video auth.auth_types_enum = [AuthType.MATCH_VIDEO] assert auth.can_edit_match_video def test_can_edit_zebra_motionworks() -> None: auth = ApiAuthAccess(auth_types_enum=[]) assert not auth.can_edit_zebra_motionworks auth.auth_types_enum = [AuthType.ZEBRA_MOTIONWORKS] assert auth.can_edit_zebra_motionworks def test_is_read_key() -> None: auth = ApiAuthAccess(auth_types_enum=[]) assert not auth.is_read_key auth.auth_types_enum = [AuthType.READ_API] assert auth.is_read_key auth.auth_types_enum = [ AuthType.READ_API, AuthType.ZEBRA_MOTIONWORKS, ] # Should not happen - but testing just in case assert not auth.is_read_key def test_is_write_key() -> None: auth = ApiAuthAccess(auth_types_enum=[AuthType.READ_API]) assert not auth.is_write_key auth.auth_types_enum = [] assert auth.is_write_key auth.auth_types_enum = [AuthType.ZEBRA_MOTIONWORKS] assert auth.is_write_key
2,548
0
253
c2b85d2194f2b1222991d379355fd5d790589d5d
9,211
py
Python
Module.py
mVento3/SteelEngineBuildSystem
b750822edf61bbb7898134e4692ea318ec278ede
[ "MIT" ]
null
null
null
Module.py
mVento3/SteelEngineBuildSystem
b750822edf61bbb7898134e4692ea318ec278ede
[ "MIT" ]
null
null
null
Module.py
mVento3/SteelEngineBuildSystem
b750822edf61bbb7898134e4692ea318ec278ede
[ "MIT" ]
null
null
null
import os import hashlib
36.551587
166
0.447617
import os import hashlib def sha512(fname): hash = hashlib.sha512() with open(fname, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash.update(chunk) return hash.hexdigest() class Module: def __init__(self, name, type, cwd, compile_config, working_directory, modules, hashes): self.name = name self.type = type self.source_files = [] self.header_files = [] self.object_files = [] self.reflection_src_files = [] self.cwd = cwd self.compile_config = compile_config self.working_directory = working_directory self.modules = modules self.hashes = hashes self.directory = '' self.generated_reflection_objs = [] self.forceCompile = False def generateReflection(self): for h in self.header_files: # try: # subprocess.call(['bin/ReflectionGenerator.exe', '-b bin', '-i ' + h, '-cwd ' + self.cwd]) # except: # print(os.sys.exc_info()) splitted = h.split(os.sep) res = '' for i in range(1, len(splitted) - 1): res += splitted[i] + '\\' res += splitted[len(splitted) - 1].split('.')[0] + '.Generated.cpp' if os.path.isfile(self.cwd + '/__generated_reflection__/' + res): self.reflection_src_files.append(res) def compileWhole(self, lib_updated, process): flags = '' defs = '' whole_compile = False includes = '' libs = '' for key in self.compile_config['flags']: flags += key + ' ' for key in self.compile_config['definitions']: defs += '/D' + key + ' ' for key in self.compile_config['includes']: key = key.replace('$CWD$', self.cwd) includes += '/I"' + key + '" ' for key in self.compile_config['lib_paths']: key = key.replace('$CWD$', self.cwd) libs += '/LIBPATH:"' + key + '" ' for key in self.compile_config['libs']: libs += key + ' ' for key in self.modules: if key['type'] == 'lib': libs += key['name'] + '.lib ' for src in self.reflection_src_files: splitted = src.split(os.sep) dir_ = self.cwd + '/' + self.working_directory obj_dir = '' for s in range(0, len(splitted) - 1): dir_ += '/' + splitted[s] obj_dir += splitted[s] + '/' if os.path.isdir(dir_): process.WriteInput('cd ' + dir_) process.Wait() else: os.mkdir(dir_) process.WriteInput('cd ' + dir_) process.Wait() compile = True found = False res = '' for i in range(0, len(splitted) - 1): res += splitted[i] if i < len(splitted) - 2: res += '/' for key in self.hashes: if key['folder'] == res: found = True found2 = False for f in key['files']: if f['filename'] == os.path.basename(src): found2 = True if f['hash'] == sha512(self.cwd + '/__generated_reflection__/' + src): compile = False break else: f['hash'] = sha512(self.cwd + '/__generated_reflection__/' + src) if not found2: key['files'].append({ 'filename': os.path.basename(src), 'hash': sha512(self.cwd + '/__generated_reflection__/' + src) }) else: break if not found: self.hashes.append({ 'folder': res, 'files': [{ 'filename': os.path.basename(src), 'hash': sha512(self.cwd + '/__generated_reflection__/' + src) }] }) if compile or not os.path.isfile(dir_ + '/' + splitted[len(splitted) - 1].split('.')[0] + '.Generated.obj'): whole_compile = True process.WriteInput('cl ' + flags + ' ' + defs + ' ' + includes + ' /c ' + self.cwd + '/__generated_reflection__/' + src) process.Wait() if process.WasError(): print("Error while compiling gen obj:", process.GetErrorMessage()) process.SetError(False) process.WriteInput('cd ' + self.cwd + '/' + self.working_directory) process.Wait() obj = self.working_directory + '/' + obj_dir + splitted[len(splitted) - 1].split('.')[0] + '.Generated.obj' self.object_files.append(obj) self.generated_reflection_objs.append(obj) for src in self.source_files: splitted = src.split(os.sep) dir_ = self.cwd + '/' + self.working_directory obj_dir = '' for s in range(1, len(splitted) - 1): dir_ += '/' + splitted[s] obj_dir += splitted[s] + '/' if os.path.isdir(dir_): process.WriteInput('cd ' + dir_) process.Wait() else: os.mkdir(dir_) process.WriteInput('cd ' + dir_) process.Wait() compile = True found = False res = '' for i in range(0, len(splitted) - 1): res += splitted[i] if i < len(splitted) - 2: res += '/' for key in self.hashes: if key['folder'] == res: found = True found2 = False for f in key['files']: if f['filename'] == os.path.basename(src): found2 = True if f['hash'] == sha512(src): compile = False break else: f['hash'] = sha512(src) if not found2: key['files'].append({ 'filename': os.path.basename(src), 'hash': sha512(src) }) else: break if not found: self.hashes.append({ 'folder': res, 'files': [{ 'filename': os.path.basename(src), 'hash': sha512(src) }] }) if compile or not os.path.isfile(dir_ + '/' + splitted[len(splitted) - 1].split('.')[0] + '.obj'): whole_compile = True process.WriteInput('cl ' + flags + ' ' + defs + ' ' + includes + ' /c ' + self.cwd + '/' + src) process.Wait() if process.WasError(): print("Error while compiling obj:", process.GetErrorMessage()) process.SetError(False) process.WriteInput('cd ' + self.cwd + '/' + self.working_directory) process.Wait() self.object_files.append(self.working_directory + '/' + obj_dir + splitted[len(splitted) - 1].split('.')[0] + '.obj') if whole_compile or lib_updated or self.forceCompile: obj_files = '' for o in self.object_files: obj_files += self.cwd + '/' + o + ' ' process.WriteInput('cd ' + self.cwd + '/' + self.working_directory + '/' + self.name) process.Wait() if self.type == 'lib': lib_updated = True process.WriteInput('lib ' + obj_files + '/OUT:' + self.cwd + '/bin/' + self.name + '.lib') process.Wait() if process.WasError(): print("Error while compiling lib:", process.GetErrorMessage()) process.SetError(False) elif self.type == 'dll': for key in self.compile_config['dll']: flags += key + ' ' process.WriteInput('cl ' + flags + ' ' + defs + ' ' + includes + ' ' + ' /Fe' + self.cwd + '/bin/' + self.name + '.dll ' + obj_files + '/link ' + ' ' + libs ) process.Wait() if process.WasError(): print("Error while compiling dll:", process.GetErrorMessage()) process.SetError(False) elif self.type == 'exe': process.WriteInput('cl ' + flags + ' ' + defs + ' ' + includes + ' ' + '/Fe' + self.cwd + '/bin/' + self.name + '.exe ' + obj_files + ' /link ' + ' ' + libs ) process.Wait() if process.WasError(): print("Error while compiling exe:", process.GetErrorMessage()) process.SetError(False) return lib_updated
9,069
-8
126
603acea854d10a36c84d3110d4f9949345cb622c
3,089
py
Python
zappa_manage/manage.py
edx/zappa-manage
eb26f039a74a8cf9ade4a0905ac983a1c8e8cecc
[ "MIT" ]
null
null
null
zappa_manage/manage.py
edx/zappa-manage
eb26f039a74a8cf9ade4a0905ac983a1c8e8cecc
[ "MIT" ]
1
2019-10-25T18:32:03.000Z
2019-10-25T21:56:54.000Z
zappa_manage/manage.py
edx/zappa-manage
eb26f039a74a8cf9ade4a0905ac983a1c8e8cecc
[ "MIT" ]
null
null
null
#!/usr/bin/python import boto3 import click from pybase64 import b64encode from asym_crypto_yaml import ( load, Encrypted, decrypt_value, load_private_key_from_file, load_private_key_from_string ) def perform_deploy_lambda_envs(config_file_path, private_key_content, private_key_path, kms_key_arn, lambda_name): """ Loads private key to deploy the application's secret values to corresponding lambda :config_file_path = path to config file :private_key_content = content of private key :private_key_path = path to the private key :kms_key_arn = arn for an aws kms_key :lambda_name = name of an aws lambda function """ private_key = None if private_key_path is not None: private_key = load_private_key_from_file(private_key_path) elif private_key_content is not None: # GoCD will mangle the encrypted key when it is passed in this way # The following lines unmangle the key. private_key_content = private_key_content.replace(' ', '\n') private_key_content = private_key_content.replace('-----BEGIN\nRSA\nPRIVATE\nKEY-----', '-----BEGIN RSA PRIVATE KEY-----') private_key_content = private_key_content.replace('-----END\nRSA\nPRIVATE\nKEY-----', '-----END RSA PRIVATE KEY-----') private_key = load_private_key_from_string(private_key_content.encode('utf-8')) if private_key is None: raise ValueError('You must specify the private key either by PRIVATE_KEY ENV, or with private-key-path') push_config_and_secrets_to_lambda_env(config_file_path, private_key, kms_key_arn, lambda_name) def push_config_and_secrets_to_lambda_env(config_file_path, private_key, kms_key_arn, lambda_name): """ Pushes the application's configurations and secret (encrypted) values to the corresponding lambda function. The application will have to decrypt value :config_file_path = path to config file :private_key = private key of application :kms_key_arn = arn for an aws kms_key :lambda_name = name of an aws lambda function """ with open(config_file_path) as f: config = load(f) if config is None: config = {} for key, value in config.items(): if type(value) == Encrypted: config[key] = kms_encrypt(kms_key_arn, decrypt_value(value, private_key)) client = boto3.client('lambda') response = client.update_function_configuration( FunctionName=lambda_name, Environment={ 'Variables': config } ) def kms_encrypt(kms_key_arn, value): """ Uses AWS KMS to encrypt the value of an environment variable :kms_key_arn = arn for an aws kms_key :value = the value of an environment variable """ client = boto3.client('kms') response = client.encrypt( KeyId=kms_key_arn, Plaintext=value, ) # returns the encrypted 64 bit string return b64encode(response['CiphertextBlob']).decode()
36.341176
114
0.679832
#!/usr/bin/python import boto3 import click from pybase64 import b64encode from asym_crypto_yaml import ( load, Encrypted, decrypt_value, load_private_key_from_file, load_private_key_from_string ) def perform_deploy_lambda_envs(config_file_path, private_key_content, private_key_path, kms_key_arn, lambda_name): """ Loads private key to deploy the application's secret values to corresponding lambda :config_file_path = path to config file :private_key_content = content of private key :private_key_path = path to the private key :kms_key_arn = arn for an aws kms_key :lambda_name = name of an aws lambda function """ private_key = None if private_key_path is not None: private_key = load_private_key_from_file(private_key_path) elif private_key_content is not None: # GoCD will mangle the encrypted key when it is passed in this way # The following lines unmangle the key. private_key_content = private_key_content.replace(' ', '\n') private_key_content = private_key_content.replace('-----BEGIN\nRSA\nPRIVATE\nKEY-----', '-----BEGIN RSA PRIVATE KEY-----') private_key_content = private_key_content.replace('-----END\nRSA\nPRIVATE\nKEY-----', '-----END RSA PRIVATE KEY-----') private_key = load_private_key_from_string(private_key_content.encode('utf-8')) if private_key is None: raise ValueError('You must specify the private key either by PRIVATE_KEY ENV, or with private-key-path') push_config_and_secrets_to_lambda_env(config_file_path, private_key, kms_key_arn, lambda_name) def push_config_and_secrets_to_lambda_env(config_file_path, private_key, kms_key_arn, lambda_name): """ Pushes the application's configurations and secret (encrypted) values to the corresponding lambda function. The application will have to decrypt value :config_file_path = path to config file :private_key = private key of application :kms_key_arn = arn for an aws kms_key :lambda_name = name of an aws lambda function """ with open(config_file_path) as f: config = load(f) if config is None: config = {} for key, value in config.items(): if type(value) == Encrypted: config[key] = kms_encrypt(kms_key_arn, decrypt_value(value, private_key)) client = boto3.client('lambda') response = client.update_function_configuration( FunctionName=lambda_name, Environment={ 'Variables': config } ) def kms_encrypt(kms_key_arn, value): """ Uses AWS KMS to encrypt the value of an environment variable :kms_key_arn = arn for an aws kms_key :value = the value of an environment variable """ client = boto3.client('kms') response = client.encrypt( KeyId=kms_key_arn, Plaintext=value, ) # returns the encrypted 64 bit string return b64encode(response['CiphertextBlob']).decode()
0
0
0
0faa476f54f9622d9910da74917eee9d1f62c54d
9,842
py
Python
python/util/data_processing_ipynb.py
debajyotidatta/multiNLI_mod
d94e30ddd628a2df65859424ebec7d212d3227b5
[ "Apache-2.0" ]
null
null
null
python/util/data_processing_ipynb.py
debajyotidatta/multiNLI_mod
d94e30ddd628a2df65859424ebec7d212d3227b5
[ "Apache-2.0" ]
null
null
null
python/util/data_processing_ipynb.py
debajyotidatta/multiNLI_mod
d94e30ddd628a2df65859424ebec7d212d3227b5
[ "Apache-2.0" ]
null
null
null
import numpy as np import re import random import json import collections import parameters as params import pickle import nltk # args = params.argparser("lstm petModel-0 --keep_rate 0.9 --seq_length 25 --emb_train") # FIXED_PARAMETERS = params.load_parameters(args) FIXED_PARAMETERS = params.load_parameters() LABEL_MAP = { "entailment": 0, "neutral": 1, "contradiction": 2, "hidden": 0 } PADDING = "<PAD>" UNKNOWN = "<UNK>" def load_nli_data(path, snli=False): """ Load MultiNLI or SNLI data. If the "snli" parameter is set to True, a genre label of snli will be assigned to the data. """ data = [] with open(path) as f: for line in f: loaded_example = json.loads(line) if loaded_example["gold_label"] not in LABEL_MAP: continue loaded_example["label"] = LABEL_MAP[loaded_example["gold_label"]] if snli: loaded_example["genre"] = "snli" data.append(loaded_example) random.seed(1) random.shuffle(data) return data def load_nli_data_genre(path, genre, snli=True): """ Load a specific genre's examples from MultiNLI, or load SNLI data and assign a "snli" genre to the examples. If the "snli" parameter is set to True, a genre label of snli will be assigned to the data. If set to true, it will overwrite the genre label for MultiNLI data. """ data = [] j = 0 with open(path) as f: for line in f: loaded_example = json.loads(line) if loaded_example["gold_label"] not in LABEL_MAP: continue loaded_example["label"] = LABEL_MAP[loaded_example["gold_label"]] if snli: loaded_example["genre"] = "snli" if loaded_example["genre"] == genre: data.append(loaded_example) random.seed(1) random.shuffle(data) return data def build_dictionary(training_datasets): """ Extract vocabulary and build dictionary. """ word_counter = collections.Counter() for i, dataset in enumerate(training_datasets): for example in dataset: word_counter.update(tokenize(example['sentence1_binary_parse'])) word_counter.update(tokenize(example['sentence2_binary_parse'])) vocabulary = set([word for word in word_counter]) vocabulary = list(vocabulary) vocabulary = [PADDING, UNKNOWN] + vocabulary word_indices = dict(zip(vocabulary, range(len(vocabulary)))) return word_indices def build_dictionary_ngrams(training_datasets): """ Extract vocabulary and build bi and trigram dictionaries. """ word_counter_unigrams = collections.Counter() word_counter_bigrams = collections.Counter() word_counter_trigrams = collections.Counter() for i, dataset in enumerate(training_datasets): for example in dataset: sent1_tokenized = tokenize(example['sentence1_binary_parse']) sent2_tokenized = tokenize(example['sentence2_binary_parse']) bigrams1 = nltk.bigrams(sent1_tokenized) bigrams2 = nltk.bigrams(sent2_tokenized) trigrams1 = nltk.trigrams(sent1_tokenized) trigrams2 = nltk.trigrams(sent2_tokenized) word_counter_bigrams.update(bigrams1) word_counter_bigrams.update(bigrams2) word_counter_trigrams.update(trigrams1) word_counter_trigrams.update(trigrams2) word_counter_unigrams.update(sent1_tokenized) word_counter_unigrams.update(sent2_tokenized) vocabulary_uni = set([word for word in word_counter_unigrams]) vocabulary_uni = list(vocabulary_uni) vocabulary_uni = [PADDING, UNKNOWN] + vocabulary_uni word_indices_uni = dict(zip(vocabulary_uni, range(len(vocabulary_uni)))) vocabulary_bi = set([word for word in word_counter_bigrams]) vocabulary_bi = list(vocabulary_bi) vocabulary_bi = [PADDING, UNKNOWN] + vocabulary_bi word_indices_bi = dict(zip(vocabulary_bi, range(len(vocabulary_bi)))) vocabulary_tri = set([word for word in word_counter_trigrams]) vocabulary_tri = list(vocabulary_tri) vocabulary_tri = [PADDING, UNKNOWN] + vocabulary_tri word_indices_tri = dict(zip(vocabulary_tri, range(len(vocabulary_tri)))) return word_indices_uni, word_indices_bi, word_indices_tri def sentences_to_padded_index_sequences(word_indices, datasets): """ Annotate datasets with feature vectors. Adding right-sided padding. """ for i, dataset in enumerate(datasets): for example in dataset: for sentence in ['sentence1_binary_parse', 'sentence2_binary_parse']: # print("sentence is", sentence) example[sentence + '_index_sequence'] = np.zeros((FIXED_PARAMETERS["seq_length"]), dtype=np.int32) token_sequence = tokenize(example[sentence]) padding = FIXED_PARAMETERS["seq_length"] - len(token_sequence) for i in range(FIXED_PARAMETERS["seq_length"]): if i >= len(token_sequence): index = word_indices[PADDING] else: if token_sequence[i] in word_indices: index = word_indices[token_sequence[i]] else: index = word_indices[UNKNOWN] example[sentence + '_index_sequence'][i] = index def sentences_to_padded_index_sequences_ngrams(word_indices, word_indices_bi, word_indices_tri, datasets): """ Annotate datasets with feature vectors. Adding right-sided padding. """ for i, dataset in enumerate(datasets): for example in dataset: for sentence in ['sentence1_binary_parse', 'sentence2_binary_parse']: # print("sentence is", sentence) example[sentence + '_index_sequence'] = np.zeros((FIXED_PARAMETERS["seq_length"]), dtype=np.int32) example[sentence + '_index_sequence_bi'] = np.zeros((FIXED_PARAMETERS["seq_length"]), dtype=np.int32) example[sentence + '_index_sequence_tri'] = np.zeros((FIXED_PARAMETERS["seq_length"]), dtype=np.int32) token_sequence = tokenize(example[sentence]) padding = FIXED_PARAMETERS["seq_length"] - len(token_sequence) for i in range(FIXED_PARAMETERS["seq_length"]): if i >= len(token_sequence): index = word_indices[PADDING] else: if token_sequence[i] in word_indices: index = word_indices[token_sequence[i]] else: index = word_indices[UNKNOWN] example[sentence + '_index_sequence'][i] = index token_sequence_bi = list(nltk.bigrams(token_sequence)) padding_bi = FIXED_PARAMETERS["seq_length"] - len(token_sequence_bi) for i in range(FIXED_PARAMETERS["seq_length"]): if i >= len(token_sequence_bi): index = word_indices_bi[PADDING] else: if token_sequence_bi[i] in word_indices_bi: index = word_indices_bi[token_sequence_bi[i]] else: index = word_indices_bi[UNKNOWN] example[sentence + '_index_sequence_bi'][i] = index token_sequence_tri = list(nltk.trigrams(token_sequence)) padding_tri = FIXED_PARAMETERS["seq_length"] - len(token_sequence_tri) for i in range(FIXED_PARAMETERS["seq_length"]): if i >= len(token_sequence_tri): index = word_indices_tri[PADDING] else: if token_sequence_tri[i] in word_indices_tri: index = word_indices_tri[token_sequence_tri[i]] else: index = word_indices_tri[UNKNOWN] example[sentence + '_index_sequence_tri'][i] = index def loadEmbedding_zeros(path, word_indices): """ Load GloVe embeddings. Initializng OOV words to vector of zeros. """ emb = np.zeros((len(word_indices), FIXED_PARAMETERS["word_embedding_dim"]), dtype='float32') with open(path, 'r') as f: for i, line in enumerate(f): if FIXED_PARAMETERS["embeddings_to_load"] != None: if i >= FIXED_PARAMETERS["embeddings_to_load"]: break s = line.split() if s[0] in word_indices: emb[word_indices[s[0]], :] = np.asarray(s[1:]) return emb def loadEmbedding_rand(path, word_indices): """ Load GloVe embeddings. Doing a random normal initialization for OOV words. """ n = len(word_indices) m = FIXED_PARAMETERS["word_embedding_dim"] emb = np.empty((n, m), dtype=np.float32) emb[:,:] = np.random.normal(size=(n,m)) # Explicitly assign embedding of <PAD> to be zeros. emb[0:2, :] = np.zeros((1,m), dtype="float32") with open(path, 'r') as f: for i, line in enumerate(f): if FIXED_PARAMETERS["embeddings_to_load"] != None: if i >= FIXED_PARAMETERS["embeddings_to_load"]: break s = line.split() if s[0] in word_indices: emb[word_indices[s[0]], :] = np.asarray(s[1:]) return emb
39.055556
164
0.602621
import numpy as np import re import random import json import collections import parameters as params import pickle import nltk # args = params.argparser("lstm petModel-0 --keep_rate 0.9 --seq_length 25 --emb_train") # FIXED_PARAMETERS = params.load_parameters(args) FIXED_PARAMETERS = params.load_parameters() LABEL_MAP = { "entailment": 0, "neutral": 1, "contradiction": 2, "hidden": 0 } PADDING = "<PAD>" UNKNOWN = "<UNK>" def load_nli_data(path, snli=False): """ Load MultiNLI or SNLI data. If the "snli" parameter is set to True, a genre label of snli will be assigned to the data. """ data = [] with open(path) as f: for line in f: loaded_example = json.loads(line) if loaded_example["gold_label"] not in LABEL_MAP: continue loaded_example["label"] = LABEL_MAP[loaded_example["gold_label"]] if snli: loaded_example["genre"] = "snli" data.append(loaded_example) random.seed(1) random.shuffle(data) return data def load_nli_data_genre(path, genre, snli=True): """ Load a specific genre's examples from MultiNLI, or load SNLI data and assign a "snli" genre to the examples. If the "snli" parameter is set to True, a genre label of snli will be assigned to the data. If set to true, it will overwrite the genre label for MultiNLI data. """ data = [] j = 0 with open(path) as f: for line in f: loaded_example = json.loads(line) if loaded_example["gold_label"] not in LABEL_MAP: continue loaded_example["label"] = LABEL_MAP[loaded_example["gold_label"]] if snli: loaded_example["genre"] = "snli" if loaded_example["genre"] == genre: data.append(loaded_example) random.seed(1) random.shuffle(data) return data def tokenize(string): string = re.sub(r'\(|\)', '', string) return string.split() def build_dictionary(training_datasets): """ Extract vocabulary and build dictionary. """ word_counter = collections.Counter() for i, dataset in enumerate(training_datasets): for example in dataset: word_counter.update(tokenize(example['sentence1_binary_parse'])) word_counter.update(tokenize(example['sentence2_binary_parse'])) vocabulary = set([word for word in word_counter]) vocabulary = list(vocabulary) vocabulary = [PADDING, UNKNOWN] + vocabulary word_indices = dict(zip(vocabulary, range(len(vocabulary)))) return word_indices def build_dictionary_ngrams(training_datasets): """ Extract vocabulary and build bi and trigram dictionaries. """ word_counter_unigrams = collections.Counter() word_counter_bigrams = collections.Counter() word_counter_trigrams = collections.Counter() for i, dataset in enumerate(training_datasets): for example in dataset: sent1_tokenized = tokenize(example['sentence1_binary_parse']) sent2_tokenized = tokenize(example['sentence2_binary_parse']) bigrams1 = nltk.bigrams(sent1_tokenized) bigrams2 = nltk.bigrams(sent2_tokenized) trigrams1 = nltk.trigrams(sent1_tokenized) trigrams2 = nltk.trigrams(sent2_tokenized) word_counter_bigrams.update(bigrams1) word_counter_bigrams.update(bigrams2) word_counter_trigrams.update(trigrams1) word_counter_trigrams.update(trigrams2) word_counter_unigrams.update(sent1_tokenized) word_counter_unigrams.update(sent2_tokenized) vocabulary_uni = set([word for word in word_counter_unigrams]) vocabulary_uni = list(vocabulary_uni) vocabulary_uni = [PADDING, UNKNOWN] + vocabulary_uni word_indices_uni = dict(zip(vocabulary_uni, range(len(vocabulary_uni)))) vocabulary_bi = set([word for word in word_counter_bigrams]) vocabulary_bi = list(vocabulary_bi) vocabulary_bi = [PADDING, UNKNOWN] + vocabulary_bi word_indices_bi = dict(zip(vocabulary_bi, range(len(vocabulary_bi)))) vocabulary_tri = set([word for word in word_counter_trigrams]) vocabulary_tri = list(vocabulary_tri) vocabulary_tri = [PADDING, UNKNOWN] + vocabulary_tri word_indices_tri = dict(zip(vocabulary_tri, range(len(vocabulary_tri)))) return word_indices_uni, word_indices_bi, word_indices_tri def sentences_to_padded_index_sequences(word_indices, datasets): """ Annotate datasets with feature vectors. Adding right-sided padding. """ for i, dataset in enumerate(datasets): for example in dataset: for sentence in ['sentence1_binary_parse', 'sentence2_binary_parse']: # print("sentence is", sentence) example[sentence + '_index_sequence'] = np.zeros((FIXED_PARAMETERS["seq_length"]), dtype=np.int32) token_sequence = tokenize(example[sentence]) padding = FIXED_PARAMETERS["seq_length"] - len(token_sequence) for i in range(FIXED_PARAMETERS["seq_length"]): if i >= len(token_sequence): index = word_indices[PADDING] else: if token_sequence[i] in word_indices: index = word_indices[token_sequence[i]] else: index = word_indices[UNKNOWN] example[sentence + '_index_sequence'][i] = index def sentences_to_padded_index_sequences_ngrams(word_indices, word_indices_bi, word_indices_tri, datasets): """ Annotate datasets with feature vectors. Adding right-sided padding. """ for i, dataset in enumerate(datasets): for example in dataset: for sentence in ['sentence1_binary_parse', 'sentence2_binary_parse']: # print("sentence is", sentence) example[sentence + '_index_sequence'] = np.zeros((FIXED_PARAMETERS["seq_length"]), dtype=np.int32) example[sentence + '_index_sequence_bi'] = np.zeros((FIXED_PARAMETERS["seq_length"]), dtype=np.int32) example[sentence + '_index_sequence_tri'] = np.zeros((FIXED_PARAMETERS["seq_length"]), dtype=np.int32) token_sequence = tokenize(example[sentence]) padding = FIXED_PARAMETERS["seq_length"] - len(token_sequence) for i in range(FIXED_PARAMETERS["seq_length"]): if i >= len(token_sequence): index = word_indices[PADDING] else: if token_sequence[i] in word_indices: index = word_indices[token_sequence[i]] else: index = word_indices[UNKNOWN] example[sentence + '_index_sequence'][i] = index token_sequence_bi = list(nltk.bigrams(token_sequence)) padding_bi = FIXED_PARAMETERS["seq_length"] - len(token_sequence_bi) for i in range(FIXED_PARAMETERS["seq_length"]): if i >= len(token_sequence_bi): index = word_indices_bi[PADDING] else: if token_sequence_bi[i] in word_indices_bi: index = word_indices_bi[token_sequence_bi[i]] else: index = word_indices_bi[UNKNOWN] example[sentence + '_index_sequence_bi'][i] = index token_sequence_tri = list(nltk.trigrams(token_sequence)) padding_tri = FIXED_PARAMETERS["seq_length"] - len(token_sequence_tri) for i in range(FIXED_PARAMETERS["seq_length"]): if i >= len(token_sequence_tri): index = word_indices_tri[PADDING] else: if token_sequence_tri[i] in word_indices_tri: index = word_indices_tri[token_sequence_tri[i]] else: index = word_indices_tri[UNKNOWN] example[sentence + '_index_sequence_tri'][i] = index def loadEmbedding_zeros(path, word_indices): """ Load GloVe embeddings. Initializng OOV words to vector of zeros. """ emb = np.zeros((len(word_indices), FIXED_PARAMETERS["word_embedding_dim"]), dtype='float32') with open(path, 'r') as f: for i, line in enumerate(f): if FIXED_PARAMETERS["embeddings_to_load"] != None: if i >= FIXED_PARAMETERS["embeddings_to_load"]: break s = line.split() if s[0] in word_indices: emb[word_indices[s[0]], :] = np.asarray(s[1:]) return emb def loadEmbedding_rand(path, word_indices): """ Load GloVe embeddings. Doing a random normal initialization for OOV words. """ n = len(word_indices) m = FIXED_PARAMETERS["word_embedding_dim"] emb = np.empty((n, m), dtype=np.float32) emb[:,:] = np.random.normal(size=(n,m)) # Explicitly assign embedding of <PAD> to be zeros. emb[0:2, :] = np.zeros((1,m), dtype="float32") with open(path, 'r') as f: for i, line in enumerate(f): if FIXED_PARAMETERS["embeddings_to_load"] != None: if i >= FIXED_PARAMETERS["embeddings_to_load"]: break s = line.split() if s[0] in word_indices: emb[word_indices[s[0]], :] = np.asarray(s[1:]) return emb
68
0
23
b8806e8e829267f46ee86a005b85487da3499661
5,697
py
Python
conllu/parser.py
orenbaldinger/conllu
2f650cb0403b6a73fcf89dbd222400fec57388d1
[ "MIT" ]
null
null
null
conllu/parser.py
orenbaldinger/conllu
2f650cb0403b6a73fcf89dbd222400fec57388d1
[ "MIT" ]
null
null
null
conllu/parser.py
orenbaldinger/conllu
2f650cb0403b6a73fcf89dbd222400fec57388d1
[ "MIT" ]
null
null
null
from __future__ import unicode_literals import re from collections import OrderedDict, defaultdict from conllu.compat import text DEFAULT_FIELDS = ('id', 'form', 'lemma', 'upostag', 'xpostag', 'feats', 'head', 'deprel', 'deps', 'misc') INTEGER = re.compile(r"^0|(\-?[1-9][0-9]*)$") ID_SINGLE = re.compile(r"^[1-9][0-9]*$") ID_RANGE = re.compile(r"^[1-9][0-9]*\-[1-9][0-9]*$") ID_DOT_ID = re.compile(r"^[0-9][0-9]*\.[1-9][0-9]*$") deps_pattern = r"\d+:[a-z][a-z_-]*(:[a-z][a-z_-]*)?" MULTI_DEPS_PATTERN = re.compile(r"^{}(\|{})*$".format(deps_pattern, deps_pattern))
27
105
0.585747
from __future__ import unicode_literals import re from collections import OrderedDict, defaultdict from conllu.compat import text DEFAULT_FIELDS = ('id', 'form', 'lemma', 'upostag', 'xpostag', 'feats', 'head', 'deprel', 'deps', 'misc') def parse_token_and_metadata(data, fields=None): if not data: raise ParseException("Can't create TokenList, no data sent to constructor.") fields = fields or DEFAULT_FIELDS tokens = [] metadata = OrderedDict() for line in data.split('\n'): line = line.strip() if not line: continue if line.startswith('#'): var_name, var_value = parse_comment_line(line) if var_name: metadata[var_name] = var_value else: tokens.append(parse_line(line, fields=fields)) return tokens, metadata def parse_line(line, fields): line = re.split(r"\t| {2,}", line) if len(line) == 1 and " " in line[0]: raise ParseException("Invalid line format, line must contain either tabs or two spaces.") data = OrderedDict() for i, field in enumerate(fields): # Allow parsing CoNNL-U files with fewer columns if i >= len(line): break if field == "id": value = parse_id_value(line[i]) elif field == "xpostag": value = parse_nullable_value(line[i]) elif field == "feats": value = parse_dict_value(line[i]) elif field == "head": value = parse_int_value(line[i]) elif field == "deps": value = parse_paired_list_value(line[i]) elif field == "misc": value = parse_dict_value(line[i]) else: value = line[i] data[field] = value return data def parse_comment_line(line): line = line.strip() if line[0] != '#': raise ParseException("Invalid comment format, comment must start with '#'") stripped = line[1:].strip() if '=' not in line and stripped != 'newdoc' and stripped != 'newpar': return None, None name_value = line[1:].split('=', 1) var_name = name_value[0].strip() var_value = None if len(name_value) == 1 else name_value[1].strip() return var_name, var_value INTEGER = re.compile(r"^0|(\-?[1-9][0-9]*)$") def parse_int_value(value): if value == '_': return None if re.match(INTEGER, value): return int(value) else: raise ParseException("'{}' is not a valid value for parse_int_value.".format(value)) ID_SINGLE = re.compile(r"^[1-9][0-9]*$") ID_RANGE = re.compile(r"^[1-9][0-9]*\-[1-9][0-9]*$") ID_DOT_ID = re.compile(r"^[0-9][0-9]*\.[1-9][0-9]*$") def parse_id_value(value): if not value or value == '_': return None if re.match(ID_SINGLE, value): return int(value) elif re.match(ID_RANGE, value): from_, to = value.split("-") from_, to = int(from_), int(to) if to > from_: return (int(from_), "-", int(to)) elif re.match(ID_DOT_ID, value): return (int(value.split(".")[0]), ".", int(value.split(".")[1])) raise ParseException("'{}' is not a valid ID.".format(value)) deps_pattern = r"\d+:[a-z][a-z_-]*(:[a-z][a-z_-]*)?" MULTI_DEPS_PATTERN = re.compile(r"^{}(\|{})*$".format(deps_pattern, deps_pattern)) def parse_paired_list_value(value): if re.match(MULTI_DEPS_PATTERN, value): return [ (part.split(":", 1)[1], parse_int_value(part.split(":", 1)[0])) for part in value.split("|") ] return parse_nullable_value(value) def parse_dict_value(value): if "=" in value: return OrderedDict([ (part.split("=")[0], parse_nullable_value(part.split("=")[1])) for part in value.split("|") if len(part.split('=')) == 2 ]) return parse_nullable_value(value) def parse_nullable_value(value): if not value or value == "_": return None return value def head_to_token(sentence): if not sentence: raise ParseException("Can't parse tree, need a tokenlist as input.") if "head" not in sentence[0]: raise ParseException("Can't parse tree, missing 'head' field.") head_indexed = defaultdict(list) for token in sentence: # Filter out range and decimal ID:s before building tree if "id" in token and not isinstance(token["id"], int): continue # If HEAD is negative, treat it as child of the root node head = max(token["head"] or 0, 0) head_indexed[head].append(token) return head_indexed def serialize_field(field): if field is None: return '_' if isinstance(field, OrderedDict): fields = [] for key, value in field.items(): if value is None: value = "_" fields.append('='.join((key, value))) return '|'.join(fields) if isinstance(field, tuple): return "".join([text(item) for item in field]) if isinstance(field, list): if len(field[0]) != 2: raise ParseException("Can't serialize '{}', invalid format".format(field)) return "|".join([text(value) + ":" + text(key) for key, value in field]) return "{}".format(field) def serialize(tokenlist): lines = [] if tokenlist.metadata: for key, value in tokenlist.metadata.items(): line = "# " + key + " = " + value lines.append(line) for token_data in tokenlist: line = '\t'.join(serialize_field(val) for val in token_data.values()) lines.append(line) return '\n'.join(lines) + "\n\n" class ParseException(Exception): pass
4,826
20
276
6197f9be27fe01b42dff481e3499f1e16aae24d1
689
py
Python
lib/medialaxis_utils.py
guilyx/FlyingCarUdacity
2e56e3dc99bce7e5e65d884cbfc8e9b49cd9287a
[ "MIT" ]
10
2020-09-21T11:36:12.000Z
2022-03-26T01:45:04.000Z
lib/medialaxis_utils.py
guilyx/FlyingCarUdacity
2e56e3dc99bce7e5e65d884cbfc8e9b49cd9287a
[ "MIT" ]
4
2020-03-28T15:43:03.000Z
2020-04-03T15:19:53.000Z
lib/medialaxis_utils.py
Guilyx/autonomous-uav
2e56e3dc99bce7e5e65d884cbfc8e9b49cd9287a
[ "MIT" ]
2
2020-12-12T20:34:49.000Z
2021-04-13T08:23:50.000Z
import numpy as np from skimage.morphology import medial_axis from skimage.util import invert
28.708333
92
0.743106
import numpy as np from skimage.morphology import medial_axis from skimage.util import invert def create_medial_axis(grid): return medial_axis(invert(grid)) def find_start_goal(skel, start, goal): # return position of start and goal on the nearest medial axis skel_cells = np.transpose(skel.nonzero()) start_min_dist = np.linalg.norm(np.array(start) - np.array(skel_cells), axis=1).argmin() near_start = skel_cells[start_min_dist] goal_min_dist = np.linalg.norm(np.array(goal) - np.array(skel_cells), axis=1).argmin() near_goal = skel_cells[goal_min_dist] return near_start, near_goal def back_to_grid(skel): return(invert(skel).astype(np.int))
523
0
69
20750d8c47027ee70e5de3454f252404ff25ec3b
2,309
py
Python
app/controllers/GithubController.py
DiegoSilva776/linkehub_insigth_api
1909a9c1b28901ab6dc0be6815741aed848b4363
[ "MIT" ]
2
2018-06-25T03:07:28.000Z
2018-06-26T13:52:23.000Z
app/controllers/GithubController.py
DiegoSilva776/linkehub_insigth_api
1909a9c1b28901ab6dc0be6815741aed848b4363
[ "MIT" ]
null
null
null
app/controllers/GithubController.py
DiegoSilva776/linkehub_insigth_api
1909a9c1b28901ab6dc0be6815741aed848b4363
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- import sys import os import json import http.client import urllib sys.path.append('../') from utils.NetworkingUtils import NetworkingUtils from utils.ConstantUtils import ConstantUtils ''' The methods of this class manage requests that are related to the Github information stored in the project database. The ScrapingController also has methods related to Github, however, they are used only to get info from the actual Github API and store it into the dababase of this project. ''' class GithubController(): ''' Returns a list of all Github user ids in the database that are from a location '''
34.984848
138
0.647033
# -*- coding: utf-8 -*- import sys import os import json import http.client import urllib sys.path.append('../') from utils.NetworkingUtils import NetworkingUtils from utils.ConstantUtils import ConstantUtils ''' The methods of this class manage requests that are related to the Github information stored in the project database. The ScrapingController also has methods related to Github, however, they are used only to get info from the actual Github API and store it into the dababase of this project. ''' class GithubController(): def __init__(self): self.TAG = "GithubController" self.netUtils = NetworkingUtils() self.constUtils = ConstantUtils() ''' Returns a list of all Github user ids in the database that are from a location ''' def getGithubUserIdsFromLocation(self, token, location): userIds = [] try: # Update the status of the instances of the service and get the best instance for the next request apiInstance = self.netUtils.getInstanceForRequestToGithubAPI() connection = http.client.HTTPSConnection(apiInstance.getBaseUrl()) headers = self.netUtils.getRequestHeaders(self.constUtils.HEADERS_TYPE_AUTH_TOKEN, token) endpoint = "/get_github_user_ids_from_location/?location={0}".format( urllib.parse.quote(location) ) connection.request("GET", endpoint, headers=headers) res = connection.getresponse() data = res.read() githubUserIdsResponse = json.loads(data.decode(self.constUtils.UTF8_DECODER)) apiInstance.remainingCallsGithub -= 1 # Process the response if githubUserIdsResponse is not None: if "success" in githubUserIdsResponse: if githubUserIdsResponse["success"]: if "github_user_ids" in githubUserIdsResponse: if isinstance(githubUserIdsResponse["github_user_ids"], list): userIds = githubUserIdsResponse["github_user_ids"] except Exception as e: print("{0} Failed to getGithubUserIdsFromLocation: {1}".format(self.TAG, e)) return userIds
1,600
0
53
102754bc5e03a7cc4d110bd6ab78d7bcf766a6c7
2,034
py
Python
PyTorchCML/models/CollaborativeMetricLearning.py
hand10ryo/PyTorchCML
f653b9f7da39061a320e0ab1810ccfe4f909f3f8
[ "MIT" ]
15
2021-12-11T10:57:49.000Z
2022-03-11T05:24:24.000Z
PyTorchCML/models/CollaborativeMetricLearning.py
hand10ryo/PytorchCML
f653b9f7da39061a320e0ab1810ccfe4f909f3f8
[ "MIT" ]
5
2021-09-11T07:25:49.000Z
2021-09-14T14:33:59.000Z
PyTorchCML/models/CollaborativeMetricLearning.py
hand10ryo/PytorchCML
f653b9f7da39061a320e0ab1810ccfe4f909f3f8
[ "MIT" ]
1
2022-02-24T10:31:59.000Z
2022-02-24T10:31:59.000Z
import torch from .BaseEmbeddingModel import BaseEmbeddingModel
30.818182
83
0.606195
import torch from .BaseEmbeddingModel import BaseEmbeddingModel class CollaborativeMetricLearning(BaseEmbeddingModel): def forward( self, users: torch.Tensor, pos_items: torch.Tensor, neg_items: torch.Tensor ) -> dict: """ Args: users : tensor of user indices size (n_batch). pos_items : tensor of item indices size (n_batch, 1) neg_items : tensor of item indices size (n_batch, n_neg_samples) Returns: dict: A dictionary of embeddings. """ # get enmbeddigs embeddings_dict = { "user_embedding": self.user_embedding(users), "pos_item_embedding": self.item_embedding(pos_items), "neg_item_embedding": self.item_embedding(neg_items), } return embeddings_dict def spreadout_distance(self, pos_items: torch.Tensor, neg_itmes: torch.Tensor): """ Args: pos_items : tensor of user indices size (n_batch, 1). neg_itmes : tensor of item indices size (n_neg_candidates) """ # get enmbeddigs pos_i_emb = self.item_embedding(pos_items) # n_batch × 1 × dim neg_i_emb = self.item_embedding(neg_itmes) # n_neg_candidates × dim # coumute dot product prod = torch.einsum("nid,md->nm", pos_i_emb, neg_i_emb) return prod def predict(self, pairs: torch.Tensor) -> torch.Tensor: """ Args: pairs : tensor of indices for user and item pairs size (n_pairs, 2). Returns: dist : distance for each users and item pair size (n_pairs) """ # set users and user users = pairs[:, :1] items = pairs[:, 1:2] # get enmbeddigs u_emb = self.user_embedding(users) i_emb = self.item_embedding(items) # compute distance dist = torch.cdist(u_emb, i_emb).reshape(-1) max_dist = 2 * self.max_norm if self.max_norm is not None else 100 return max_dist - dist
0
1,950
23
1300a4bd098ab78414e9bcd1aec4356e26a1fd28
2,953
py
Python
Exscript/interpreter/regex.py
ShurikMen/exscript
29180fdf447b265ab17ab3c6cac827b19864b7be
[ "MIT" ]
226
2015-01-20T19:59:06.000Z
2022-01-02T11:13:01.000Z
Exscript/interpreter/regex.py
ShurikMen/exscript
29180fdf447b265ab17ab3c6cac827b19864b7be
[ "MIT" ]
155
2015-01-02T07:56:27.000Z
2022-01-09T20:56:19.000Z
Exscript/interpreter/regex.py
ShurikMen/exscript
29180fdf447b265ab17ab3c6cac827b19864b7be
[ "MIT" ]
114
2015-01-03T11:48:17.000Z
2022-01-26T02:50:43.000Z
# # Copyright (C) 2010-2017 Samuel Abels # The MIT License (MIT) # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, # and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. from __future__ import print_function, absolute_import import re from .string import String # Matches any opening parenthesis that is neither preceded by a backslash # nor has a "?:" or "?<" appended. bracket_re = re.compile(r'(?<!\\)\((?!\?[:<])', re.I) modifier_grammar = ( ('modifier', r'[i]'), ('invalid_char', r'.'), ) modifier_grammar_c = [] for thetype, regex in modifier_grammar: modifier_grammar_c.append((thetype, re.compile(regex, re.M | re.S)))
36.45679
77
0.663732
# # Copyright (C) 2010-2017 Samuel Abels # The MIT License (MIT) # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, # and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. from __future__ import print_function, absolute_import import re from .string import String # Matches any opening parenthesis that is neither preceded by a backslash # nor has a "?:" or "?<" appended. bracket_re = re.compile(r'(?<!\\)\((?!\?[:<])', re.I) modifier_grammar = ( ('modifier', r'[i]'), ('invalid_char', r'.'), ) modifier_grammar_c = [] for thetype, regex in modifier_grammar: modifier_grammar_c.append((thetype, re.compile(regex, re.M | re.S))) class Regex(String): def __init__(self, lexer, parser, parent): self.delimiter = lexer.token()[1] # String parser collects the regex. String.__init__(self, lexer, parser, parent) self.n_groups = len(bracket_re.findall(self.string)) self.flags = 0 # Collect modifiers. lexer.set_grammar(modifier_grammar_c) while lexer.current_is('modifier'): if lexer.next_if('modifier', 'i'): self.flags = self.flags | re.I else: modifier = lexer.token()[1] error = 'Invalid regular expression modifier "%s"' % modifier lexer.syntax_error(error, self) lexer.restore_grammar() # Compile the regular expression. try: re.compile(self.string, self.flags) except Exception as e: error = 'Invalid regular expression %s: %s' % ( repr(self.string), e) lexer.syntax_error(error, self) def _escape(self, token): char = token[1] if char == self.delimiter: return char return token def value(self, context): pattern = String.value(self, context)[0] return re.compile(pattern, self.flags) def dump(self, indent=0): print((' ' * indent) + self.name, self.string)
1,222
-1
131
4ecde91c5e3066c0d64c7dcc93e20872e036d52f
2,144
py
Python
src/python/pants/backend/jvm/tasks/javadoc_gen.py
areitz/pants
9bfb3feb0272c05f36e190c9147091b97ee1950d
[ "Apache-2.0" ]
null
null
null
src/python/pants/backend/jvm/tasks/javadoc_gen.py
areitz/pants
9bfb3feb0272c05f36e190c9147091b97ee1950d
[ "Apache-2.0" ]
null
null
null
src/python/pants/backend/jvm/tasks/javadoc_gen.py
areitz/pants
9bfb3feb0272c05f36e190c9147091b97ee1950d
[ "Apache-2.0" ]
null
null
null
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) from pants.backend.jvm.tasks.jvmdoc_gen import Jvmdoc, JvmdocGen from pants.java.distribution.distribution import Distribution from pants.java.executor import SubprocessExecutor from pants.util.memo import memoized
31.529412
97
0.661381
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) from pants.backend.jvm.tasks.jvmdoc_gen import Jvmdoc, JvmdocGen from pants.java.distribution.distribution import Distribution from pants.java.executor import SubprocessExecutor from pants.util.memo import memoized class JavadocGen(JvmdocGen): @classmethod @memoized def jvmdoc(cls): return Jvmdoc(tool_name='javadoc', product_type='javadoc') def execute(self): def is_java(target): return target.has_sources('.java') self.generate_doc(is_java, self.create_javadoc_command) def create_javadoc_command(self, classpath, gendir, *targets): sources = [] for target in targets: sources.extend(target.sources_relative_to_buildroot()) if not sources: return None # Without a JDK/tools.jar we have no javadoc tool and cannot proceed, so check/acquire early. jdk = Distribution.cached(jdk=True) tool_classpath = jdk.find_libs(['tools.jar']) args = ['-quiet', '-encoding', 'UTF-8', '-notimestamp', '-use', '-classpath', ':'.join(classpath), '-d', gendir] # Always provide external linking for java API offlinelinks = {'http://download.oracle.com/javase/6/docs/api/'} def link(target): for jar in target.jar_dependencies: if jar.apidocs: offlinelinks.add(jar.apidocs) for target in targets: target.walk(link, lambda t: t.is_jvm) for link in offlinelinks: args.extend(['-linkoffline', link, link]) args.extend(self.args) args.extend(sources) java_executor = SubprocessExecutor(jdk) runner = java_executor.runner(jvm_options=self.jvm_options, classpath=tool_classpath, main='com.sun.tools.javadoc.Main', args=args) return runner.command
1,497
108
23
e15d08411554ef78bde9fcd517ba0faf62230bb5
131
py
Python
ihela_client/__init__.py
UbuhingaVizion/ihela-pyhton-client
a5f808a0c138ef407416f0d8548e1ddf8957a12a
[ "MIT" ]
2
2020-12-10T13:20:37.000Z
2021-11-15T02:44:16.000Z
ihela_client/__init__.py
UbuhingaVizion/ihela-pyhton-client
a5f808a0c138ef407416f0d8548e1ddf8957a12a
[ "MIT" ]
3
2020-09-19T20:05:23.000Z
2021-06-02T00:46:53.000Z
ihela_client/__init__.py
UbuhingaVizion/ihela-pyhton-client
a5f808a0c138ef407416f0d8548e1ddf8957a12a
[ "MIT" ]
4
2020-09-09T16:40:10.000Z
2021-08-03T09:48:34.000Z
from .merchant_authorization import MerchantAuthorizationClient from .merchant_client import MerchantClient __version__ = "0.0.5"
26.2
63
0.854962
from .merchant_authorization import MerchantAuthorizationClient from .merchant_client import MerchantClient __version__ = "0.0.5"
0
0
0
0ff642dfb890af95565c70ceb8c3c62a42535e1d
8,958
py
Python
airflow_spell/hooks/spell_client.py
healx/airflow-spell
ce1b028af24b7bf26ec973db01e885c4de62ec85
[ "Apache-2.0" ]
1
2020-07-17T15:57:17.000Z
2020-07-17T15:57:17.000Z
airflow_spell/hooks/spell_client.py
healx/airflow-spell
ce1b028af24b7bf26ec973db01e885c4de62ec85
[ "Apache-2.0" ]
39
2020-07-03T12:39:54.000Z
2022-03-29T08:55:56.000Z
airflow_spell/hooks/spell_client.py
healx/airflow-spell
ce1b028af24b7bf26ec973db01e885c4de62ec85
[ "Apache-2.0" ]
null
null
null
from random import uniform from time import sleep from typing import List, Optional, Union from airflow.exceptions import AirflowException from airflow.hooks.base import BaseHook from airflow.utils.log.logging_mixin import LoggingMixin from spell.client import SpellClient as ExternalSpellClient from spell.client.runs import Run as ExternalSpellRun from spell.client.runs import RunsService as ExternalSpellRunsService STILL_RUNNING = [ ExternalSpellRunsService.BUILDING, ExternalSpellRunsService.PUSHING, ExternalSpellRunsService.RUNNING, ExternalSpellRunsService.SAVING, ] def _delay(delay: Union[int, float, None] = None): """ Pause execution for ``delay`` seconds. :param delay: a delay to pause execution using ``time.sleep(delay)``; a small 1 second jitter is applied to the delay. :type delay: Optional[Union[int, float]] .. note:: This method uses a default random delay, i.e. ``random.uniform(DEFAULT_DELAY_MIN, DEFAULT_DELAY_MAX)``; using a random interval helps to avoid AWS API throttle limits when many concurrent tasks request job-descriptions. """ if delay is None: delay = uniform(SpellClient.DEFAULT_DELAY_MIN, SpellClient.DEFAULT_DELAY_MAX) else: delay = _add_jitter(delay) sleep(delay) def _add_jitter( delay: Union[int, float], width: Union[int, float] = 1, minima: Union[int, float] = 0, ) -> float: """ Use delay +/- width for random jitter Adding jitter to status polling can help to avoid Spell API limits for monitoring spell jobs with a high concurrency in Airflow tasks. :param delay: number of seconds to pause; delay is assumed to be a positive number :type delay: Union[int, float] :param width: delay +/- width for random jitter; width is assumed to be a positive number :type width: Union[int, float] :param minima: minimum delay allowed; minima is assumed to be a non-negative number :type minima: Union[int, float] :return: uniform(delay - width, delay + width) jitter and it is a non-negative number :rtype: float """ delay = abs(delay) width = abs(width) minima = abs(minima) lower = max(minima, delay - width) upper = delay + width return uniform(lower, upper)
32.107527
88
0.638647
from random import uniform from time import sleep from typing import List, Optional, Union from airflow.exceptions import AirflowException from airflow.hooks.base import BaseHook from airflow.utils.log.logging_mixin import LoggingMixin from spell.client import SpellClient as ExternalSpellClient from spell.client.runs import Run as ExternalSpellRun from spell.client.runs import RunsService as ExternalSpellRunsService class SpellHook(BaseHook): def __init__(self, spell_conn_id="spell_default", owner: Optional[str] = None): super().__init__() self.spell_conn_id = spell_conn_id self.owner = owner def get_client(self): if self.owner is not None: owner = self.owner else: owner = self._get_owner() return ExternalSpellClient(token=self._get_token(), owner=owner) def _get_token(self): # get_connection is on BaseHook connection_object = self.get_connection(self.spell_conn_id) return connection_object.password def _get_owner(self): connection_object = self.get_connection(self.spell_conn_id) return connection_object.host STILL_RUNNING = [ ExternalSpellRunsService.BUILDING, ExternalSpellRunsService.PUSHING, ExternalSpellRunsService.RUNNING, ExternalSpellRunsService.SAVING, ] class SpellClient(LoggingMixin): MAX_RETRIES = 4200 STATUS_RETRIES = 10 # delays are in seconds DEFAULT_DELAY_MIN = 1 DEFAULT_DELAY_MAX = 10 def __init__( self, spell_conn_id: Optional[str] = None, spell_owner: Optional[str] = None ): super().__init__() self.spell_conn_id = spell_conn_id self.spell_owner = spell_owner self._hook: Optional[SpellHook] = None self._client: Optional[ExternalSpellClient] = None @property def hook(self) -> SpellHook: if self._hook is None: self._hook = SpellHook( spell_conn_id=self.spell_conn_id, owner=self.spell_owner ) return self._hook @property def client(self) -> ExternalSpellClient: if self._client is None: self._client = self.hook.get_client() return self._client def get_run(self, run_id: str) -> ExternalSpellRun: return ExternalSpellRun(self.client.api, self.client.api.get_run(run_id)) def wait_for_run(self, run_id: str, delay: Optional[Union[int, float]] = None): """ Wait for spell run to complete :param run_id: a spell run ID :type run_id: str :param delay: a delay before polling for run status :type delay: Optional[Union[int, float]] :raises: AirflowException """ _delay(delay) self.poll_for_run_running(run_id, delay) self.poll_for_run_complete(run_id, delay) self.log.info(f"Spell run ({run_id}) has completed") def check_run_success(self, run_id: str) -> bool: """ Check the final status of the spell run; return True if the run 'COMPLETE', else raise an AirflowException :param run_id: a spell run ID :type run_id: str :rtype: bool :raises: AirflowException """ run = self.get_run(run_id) run_status = run.status if run_status == ExternalSpellRunsService.COMPLETE: self.log.info(f"Spell run ({run_id}) completed: {run}") return True if run_status == ExternalSpellRunsService.FAILED: raise AirflowException(f"Spell run ({run_id}) failed: {run}") if run_status in STILL_RUNNING: raise AirflowException(f"Spell ({run_id}) is not complete: {run}") raise AirflowException( f"Spell ({run_id}) has unknown status ({run_status}): {run}" ) def poll_for_run_running(self, run_id: str, delay: Union[int, float, None] = None): """ Poll for job running. The status that indicates a job is running or already complete are: 'RUNNING'|'SUCCEEDED'|'FAILED'. So the status options that this will wait for are the transitions from: 'SUBMITTED'>'PENDING'>'RUNNABLE'>'STARTING'>'RUNNING'|'SUCCEEDED'|'FAILED' The completed status options are included for cases where the status changes too quickly for polling to detect a RUNNING status that moves quickly from STARTING to RUNNING to completed (often a failure). :param run_id: a spell run ID :type run_id: str :param delay: a delay before polling for job status :type delay: Optional[Union[int, float]] :raises: AirflowException """ _delay(delay) running_status = [ ExternalSpellRunsService.BUILDING, ExternalSpellRunsService.RUNNING, ExternalSpellRunsService.SAVING, ExternalSpellRunsService.PUSHING, ] self.poll_run_status(run_id, running_status) def poll_for_run_complete(self, run_id: str, delay: Union[int, float, None] = None): """ Poll for job completion. The status that indicates job completion are: 'SUCCEEDED'|'FAILED'. So the status options that this will wait for are the transitions from: 'SUBMITTED'>'PENDING'>'RUNNABLE'>'STARTING'>'RUNNING'>'SUCCEEDED'|'FAILED' :param run_id: a spell run ID :type run_id: str :param delay: a delay before polling for job status :type delay: Optional[Union[int, float]] :raises: AirflowException """ _delay(delay) complete_status = ExternalSpellRunsService.FINAL self.poll_run_status(run_id, complete_status) def poll_run_status(self, run_id: str, match_status: List[str]) -> bool: """ Poll for job status using an exponential back-off strategy (with max_retries). :param run_id: a spell ID :type run_id: str :param match_status: a list of job status to match; the batch job status are: 'SUBMITTED'|'PENDING'|'RUNNABLE'|'STARTING'|'RUNNING'|'SUCCEEDED'|'FAILED' :type match_status: List[str] :rtype: bool :raises: AirflowException """ retries = 0 while True: run = self.get_run(run_id) run_status = run.status self.log.info( f"Spell run ({run_id}) check status ({run_status}) in {match_status}" ) if run_status in match_status: return True if retries >= self.MAX_RETRIES: raise AirflowException( f"Spell run ({run_id}) status checks exceed max_retries" ) retries += 1 pause = _exponential_delay(retries) self.log.info( f"Spell run ({run_id}) status check ({retries} of {self.MAX_RETRIES})" f" in the next {pause:.2f} seconds" ) _delay(pause) def _delay(delay: Union[int, float, None] = None): """ Pause execution for ``delay`` seconds. :param delay: a delay to pause execution using ``time.sleep(delay)``; a small 1 second jitter is applied to the delay. :type delay: Optional[Union[int, float]] .. note:: This method uses a default random delay, i.e. ``random.uniform(DEFAULT_DELAY_MIN, DEFAULT_DELAY_MAX)``; using a random interval helps to avoid AWS API throttle limits when many concurrent tasks request job-descriptions. """ if delay is None: delay = uniform(SpellClient.DEFAULT_DELAY_MIN, SpellClient.DEFAULT_DELAY_MAX) else: delay = _add_jitter(delay) sleep(delay) def _exponential_delay(tries: int) -> float: max_interval = 600.0 # results in 3 to 10 minute delay delay = 1 + pow(tries * 0.6, 2) delay = min(max_interval, delay) return uniform(delay / 3, delay) def _add_jitter( delay: Union[int, float], width: Union[int, float] = 1, minima: Union[int, float] = 0, ) -> float: """ Use delay +/- width for random jitter Adding jitter to status polling can help to avoid Spell API limits for monitoring spell jobs with a high concurrency in Airflow tasks. :param delay: number of seconds to pause; delay is assumed to be a positive number :type delay: Union[int, float] :param width: delay +/- width for random jitter; width is assumed to be a positive number :type width: Union[int, float] :param minima: minimum delay allowed; minima is assumed to be a non-negative number :type minima: Union[int, float] :return: uniform(delay - width, delay + width) jitter and it is a non-negative number :rtype: float """ delay = abs(delay) width = abs(width) minima = abs(minima) lower = max(minima, delay - width) upper = delay + width return uniform(lower, upper)
1,524
4,910
176
eca15d20b2987a3974b33182450d7fd48bd19f5f
767
py
Python
liveproxy/shared.py
frebib/liveproxy
49483579eded7ee4e23cc4b9a9e75ed20a4d62e8
[ "BSD-2-Clause" ]
1
2019-09-08T05:56:14.000Z
2019-09-08T05:56:14.000Z
liveproxy/shared.py
frebib/liveproxy
49483579eded7ee4e23cc4b9a9e75ed20a4d62e8
[ "BSD-2-Clause" ]
null
null
null
liveproxy/shared.py
frebib/liveproxy
49483579eded7ee4e23cc4b9a9e75ed20a4d62e8
[ "BSD-2-Clause" ]
1
2021-03-28T11:50:34.000Z
2021-03-28T11:50:34.000Z
# -*- coding: utf-8 -*- ''' Python classes that are shared between LiveProxy main.py and Kodi service.liveproxy ''' import logging import os import sys import streamlink.logger as logger log = logging.getLogger('streamlink.liveproxy-shared') __all__ = [ 'check_root', 'logger', 'setup_logging', ]
23.242424
102
0.601043
# -*- coding: utf-8 -*- ''' Python classes that are shared between LiveProxy main.py and Kodi service.liveproxy ''' import logging import os import sys import streamlink.logger as logger log = logging.getLogger('streamlink.liveproxy-shared') def check_root(): if hasattr(os, 'getuid'): if os.geteuid() == 0: log.info('LiveProxy is running as root! Be careful!') def setup_logging(stream=sys.stdout, level='debug'): fmt = ("[{asctime},{msecs:0.0f}]" if level == "trace" else "") + "[{name}][{levelname}] {message}" logger.basicConfig(stream=stream, level=level, format=fmt, style="{", datefmt="%H:%M:%S") __all__ = [ 'check_root', 'logger', 'setup_logging', ]
396
0
46
d2b20976e78d5276aa017a04e295b70ecf2c45a1
3,469
py
Python
fbpcs/input_data_validation/validation_runner.py
musebc/fbpcs
e502b708f24ad6403043df59a7517084c0bb5e22
[ "MIT" ]
null
null
null
fbpcs/input_data_validation/validation_runner.py
musebc/fbpcs
e502b708f24ad6403043df59a7517084c0bb5e22
[ "MIT" ]
null
null
null
fbpcs/input_data_validation/validation_runner.py
musebc/fbpcs
e502b708f24ad6403043df59a7517084c0bb5e22
[ "MIT" ]
null
null
null
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # pyre-strict """ This is the main class that runs all of the validations. This class handles the overall logic to: * Copy the file to local storage * Run the validations * Generate a validation report Error handling: * If an unhandled error occurs, it will be returned in the report """ import csv import time from typing import Dict, Optional from fbpcp.service.storage_s3 import S3StorageService from fbpcs.input_data_validation.constants import INPUT_DATA_TMP_FILE_PATH from fbpcs.input_data_validation.enums import ValidationResult from fbpcs.input_data_validation.header_validator import HeaderValidator from fbpcs.input_data_validation.line_ending_validator import LineEndingValidator from fbpcs.private_computation.entity.cloud_provider import CloudProvider
35.762887
88
0.671375
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # pyre-strict """ This is the main class that runs all of the validations. This class handles the overall logic to: * Copy the file to local storage * Run the validations * Generate a validation report Error handling: * If an unhandled error occurs, it will be returned in the report """ import csv import time from typing import Dict, Optional from fbpcp.service.storage_s3 import S3StorageService from fbpcs.input_data_validation.constants import INPUT_DATA_TMP_FILE_PATH from fbpcs.input_data_validation.enums import ValidationResult from fbpcs.input_data_validation.header_validator import HeaderValidator from fbpcs.input_data_validation.line_ending_validator import LineEndingValidator from fbpcs.private_computation.entity.cloud_provider import CloudProvider class ValidationRunner: def __init__( self, input_file_path: str, cloud_provider: CloudProvider, region: str, access_key_id: Optional[str] = None, access_key_data: Optional[str] = None, start_timestamp: Optional[str] = None, end_timestamp: Optional[str] = None, valid_threshold_override: Optional[str] = None, ) -> None: self._input_file_path = input_file_path self._local_file_path: str = self._get_local_filepath() self._cloud_provider = cloud_provider self._storage_service = S3StorageService(region, access_key_id, access_key_data) def _get_local_filepath(self) -> str: now = time.time() filename = self._input_file_path.split("/")[-1] return f"{INPUT_DATA_TMP_FILE_PATH}/{filename}-{now}" def run(self) -> Dict[str, str]: rows_processed_count = 0 try: self._storage_service.copy(self._input_file_path, self._local_file_path) with open(self._local_file_path) as local_file: csv_reader = csv.DictReader(local_file) field_names = csv_reader.fieldnames or [] header_validator = HeaderValidator() header_validator.validate(field_names) with open(self._local_file_path, "rb") as local_file: line_ending_validator = LineEndingValidator() header_line = local_file.readline().decode("utf-8") line_ending_validator.validate(header_line) while raw_line := local_file.readline(): line = raw_line.decode("utf-8") line_ending_validator.validate(line) rows_processed_count += 1 except Exception as e: return self._format_validation_result( ValidationResult.FAILED, f"File: {self._input_file_path} failed validation. Error: {e}", rows_processed_count, ) return self._format_validation_result( ValidationResult.SUCCESS, f"File: {self._input_file_path} was validated successfully", rows_processed_count, ) def _format_validation_result( self, status: ValidationResult, message: str, rows_processed_count: int ) -> Dict[str, str]: return { "status": status.value, "message": message, "rows_processed_count": str(rows_processed_count), }
2,384
2
130
c82848c9cdb6634cd95c6d18fcb749abc104d87e
1,226
py
Python
mitm-websocket.py
ykmattur2005/Websocket_MITM
4117a85da624a5df14738dea36df859ed5a197c2
[ "MIT" ]
null
null
null
mitm-websocket.py
ykmattur2005/Websocket_MITM
4117a85da624a5df14738dea36df859ed5a197c2
[ "MIT" ]
null
null
null
mitm-websocket.py
ykmattur2005/Websocket_MITM
4117a85da624a5df14738dea36df859ed5a197c2
[ "MIT" ]
null
null
null
import argparse from Secure_Server import secure_server_start from Secure_Client import secure_client_start from Server import unsecure_server_start from Client import unsecure_client_start from MITM import mitm_start parser = argparse.ArgumentParser(description='Choose whether to run a client or a server, and whether it should be secure or not') parser.add_argument('--tls', action='store_true', help='run secure server') parser.add_argument('--mitm', action='store_true', help='run man in the middle') group = parser.add_mutually_exclusive_group() group.add_argument('--server', action='store_true', help='run server') group.add_argument('--client', action='store_true', help='run client') args = parser.parse_args() if __name__ == '__main__': if args.mitm: # run man in the middle mitm_start() if args.tls: if args.server: # run secure server # secure_server_start("9999") secure_server_start() elif args.client: # run secure client # secure_client_start("localhost", "9999") secure_client_start() else: if args.server: # run unsecure server unsecure_server_start() elif args.client: # run unsecure client unsecure_client_start()
35.028571
130
0.731648
import argparse from Secure_Server import secure_server_start from Secure_Client import secure_client_start from Server import unsecure_server_start from Client import unsecure_client_start from MITM import mitm_start parser = argparse.ArgumentParser(description='Choose whether to run a client or a server, and whether it should be secure or not') parser.add_argument('--tls', action='store_true', help='run secure server') parser.add_argument('--mitm', action='store_true', help='run man in the middle') group = parser.add_mutually_exclusive_group() group.add_argument('--server', action='store_true', help='run server') group.add_argument('--client', action='store_true', help='run client') args = parser.parse_args() if __name__ == '__main__': if args.mitm: # run man in the middle mitm_start() if args.tls: if args.server: # run secure server # secure_server_start("9999") secure_server_start() elif args.client: # run secure client # secure_client_start("localhost", "9999") secure_client_start() else: if args.server: # run unsecure server unsecure_server_start() elif args.client: # run unsecure client unsecure_client_start()
0
0
0
3ab65e568a203f7ada9c5adecba5e5f909adc336
1,057
py
Python
deployment.py
viniciusao/awscdk-demo
483ea234dc2d8a1bc24b938776f176323bc22060
[ "MIT" ]
1
2022-01-07T21:54:38.000Z
2022-01-07T21:54:38.000Z
deployment.py
viniciusao/awscdk-demo
483ea234dc2d8a1bc24b938776f176323bc22060
[ "MIT" ]
null
null
null
deployment.py
viniciusao/awscdk-demo
483ea234dc2d8a1bc24b938776f176323bc22060
[ "MIT" ]
null
null
null
from typing import cast from aws_cdk import aws_iam as iam from aws_cdk import core as cdk from api.infra import API from db.infra import Database
27.102564
66
0.600757
from typing import cast from aws_cdk import aws_iam as iam from aws_cdk import core as cdk from api.infra import API from db.infra import Database class TibiaCharsManagement(cdk.Stage): def __init__( self, scope: cdk.Construct, id_: str, chalice_app: bool = False ): super().__init__(scope, id_) stateful = cdk.Stack(self, "Stateful") database = Database(stateful, "DynamoDB") stateless = cdk.Stack(self, "Stateless") api = API( "Api", stateless, chalice_app=chalice_app, dynamodb_table_name=database.dynamodb_table.table_name ) if chalice_app: # chalice lambda function role database.dynamodb_table.grant_read_write_data( cast(iam.IGrantable, api.api_handler_iam_role) ) else: # no chalice lambda function role database.dynamodb_table.grant_read_write_data( cast(iam.IGrantable, api.lf.role) )
841
17
49
7d3d92fb69fb42d41aed0da3b166bafa75b36a85
625
py
Python
run_rasa_test_with_ide.py
randywreed/financial-demo
2667b0cb2082719b7cd47cf60396df7f036dea51
[ "Apache-2.0" ]
230
2020-02-28T05:53:25.000Z
2022-03-21T07:49:20.000Z
run_rasa_test_with_ide.py
randywreed/financial-demo
2667b0cb2082719b7cd47cf60396df7f036dea51
[ "Apache-2.0" ]
107
2020-03-09T14:44:22.000Z
2022-02-14T07:44:02.000Z
run_rasa_test_with_ide.py
randywreed/financial-demo
2667b0cb2082719b7cd47cf60396df7f036dea51
[ "Apache-2.0" ]
410
2020-02-28T05:53:29.000Z
2022-03-20T23:49:32.000Z
"""This script allows use of an IDE (Wing, Pycharm, ...) to run the rasa shell: (-) Place this script in root of Rasa bot project (-) Open & run it from within your IDE (-) In Wing, use External Console for better experience. """ import os import sys # insert path of this script in syspath so custom modules will be found sys.path.insert(1, os.path.dirname(os.path.abspath(__file__))) # # This is exactly like issuing the command: # $ rasa shell --debug # # sys.argv.append("shell") sys.argv.append("--enable-api") sys.argv.append("--debug") if __name__ == "__main__": from rasa.__main__ import main main()
21.551724
79
0.6976
"""This script allows use of an IDE (Wing, Pycharm, ...) to run the rasa shell: (-) Place this script in root of Rasa bot project (-) Open & run it from within your IDE (-) In Wing, use External Console for better experience. """ import os import sys # insert path of this script in syspath so custom modules will be found sys.path.insert(1, os.path.dirname(os.path.abspath(__file__))) # # This is exactly like issuing the command: # $ rasa shell --debug # # sys.argv.append("shell") sys.argv.append("--enable-api") sys.argv.append("--debug") if __name__ == "__main__": from rasa.__main__ import main main()
0
0
0
27f35a97ee4f2a972b844159654ae5cb4b930adc
1,078
py
Python
app/__init__.py
samzhangjy/Future-Blog
1bc6f9d80a591a1cc8e14bc778a0ede99ea13689
[ "MIT" ]
1
2020-02-09T03:37:42.000Z
2020-02-09T03:37:42.000Z
app/__init__.py
PythonSamZhang/Future-Blog
1bc6f9d80a591a1cc8e14bc778a0ede99ea13689
[ "MIT" ]
2
2020-03-24T18:11:43.000Z
2020-03-31T11:00:18.000Z
app/__init__.py
samzhangjy/Future-Blog
1bc6f9d80a591a1cc8e14bc778a0ede99ea13689
[ "MIT" ]
null
null
null
#-*-coding:utf-8-*- from flask import Flask, render_template from flask_bootstrap import Bootstrap from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_moment import Moment from flask_login import LoginManager from flask_pagedown import PageDown from config import config import os from flask_uploads import UploadSet, configure_uploads, IMAGES, patch_request_class bootstrap = Bootstrap() db = SQLAlchemy() moment = Moment() login_manager = LoginManager() login_manager.login_view = '.login' pagedown = PageDown() photos = UploadSet('photos', IMAGES)
29.944444
83
0.769944
#-*-coding:utf-8-*- from flask import Flask, render_template from flask_bootstrap import Bootstrap from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_moment import Moment from flask_login import LoginManager from flask_pagedown import PageDown from config import config import os from flask_uploads import UploadSet, configure_uploads, IMAGES, patch_request_class bootstrap = Bootstrap() db = SQLAlchemy() moment = Moment() login_manager = LoginManager() login_manager.login_view = '.login' pagedown = PageDown() photos = UploadSet('photos', IMAGES) def create_app(config_name): os.environ['FLASK_APP'] = 'blog.py' app = Flask(__name__) os.environ['FLASK_APP'] = 'blog.py' app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app) moment.init_app(app) db.init_app(app) login_manager.init_app(app) pagedown.init_app(app) configure_uploads(app, photos) from .main import main as main_blueprint app.register_blueprint(main_blueprint) return app
471
0
23
80361f4bdc161bde187260e75772df7c070dff75
977
py
Python
vim/util/__init__.py
GoNZooo/dragonfly-grammars
22d639d8f86f4f5a7c44caa73e75c4938c0ce199
[ "MIT" ]
3
2020-09-06T10:40:19.000Z
2020-09-29T20:39:52.000Z
vim/util/__init__.py
GoNZooo/dragonfly-grammars
22d639d8f86f4f5a7c44caa73e75c4938c0ce199
[ "MIT" ]
null
null
null
vim/util/__init__.py
GoNZooo/dragonfly-grammars
22d639d8f86f4f5a7c44caa73e75c4938c0ce199
[ "MIT" ]
null
null
null
from dragonfly import Grammar, CompoundRule pythonBootstrap = Grammar("python bootstrap") pythonBootstrap.add_rule(PythonEnabler()) pythonBootstrap.load() pythonGrammar = Grammar("python grammar") pythonGrammar.load() pythonGrammar.disable()
27.138889
85
0.726714
from dragonfly import Grammar, CompoundRule class PythonEnabler(CompoundRule): spec = "Enable Python" # Spoken command to enable the Python grammar. def _process_recognition(self, node, extras): # Callback when command is spoken. pythonBootstrap.disable() pythonGrammar.enable() print("Python grammar enabled") class PythonDisabler(CompoundRule): spec = "switch language" # spoken command to disable the Python grammar. def _process_recognition(self, node, extras): # Callback when command is spoken. pythonGrammar.disable() pythonBootstrap.enable() print("Python grammar disabled") pythonBootstrap = Grammar("python bootstrap") pythonBootstrap.add_rule(PythonEnabler()) pythonBootstrap.load() pythonGrammar = Grammar("python grammar") pythonGrammar.load() pythonGrammar.disable() def unload(): global pythonGrammar if pythonGrammar: pythonGrammar.unload() pythonGrammar = None
426
234
69
cb0683f307b349e0c87f71c2ac334901c13f88c5
1,351
py
Python
Projeto Base (Estudo)/Material/Projeto.py
lucashbdutra/ETL
5455fe3164daa76b03afb33a86b7ec6e66643bf9
[ "MIT" ]
null
null
null
Projeto Base (Estudo)/Material/Projeto.py
lucashbdutra/ETL
5455fe3164daa76b03afb33a86b7ec6e66643bf9
[ "MIT" ]
null
null
null
Projeto Base (Estudo)/Material/Projeto.py
lucashbdutra/ETL
5455fe3164daa76b03afb33a86b7ec6e66643bf9
[ "MIT" ]
null
null
null
import pandas as pd import pandera as pa df = pd.read_csv('ocorrencia.csv', parse_dates=['ocorrencia_dia'], dayfirst=True) #fazer a leitura da tablea, parse_data: faz a conversão para data e dayfirst: faz com que o dia seja o primeiro número df.head(10) schema = pa.DataFrameSchema( #cria um esquema para o data frame para fazer as validações columns = { 'codigo':pa.Column(pa.Int, required=False), # O valor required (necessário) é True por padrao, colocando assim essa passa a ser uma coluna opcional, em caso de ausência não havera erro. 'codigo_ocorrencia':pa.Column(pa.Int),# diz que a primeira coluna tem que ser int 'codigo_ocorrencia2':pa.Column(pa.Int), # e assim por diante, verificando o tipo de cada coluna 'ocorrencia_classificacao':pa.Column(pa.String), 'ocorrencia_cidade':pa.Column(pa.String), 'ocorrencia_uf':pa.Column(pa.String, pa.Check.str_length(2,2)), # verifica o tamanho min e max 'ocorrencia_aerodromo':pa.Column(pa.String), 'ocorrencia_dia':pa.Column(pa.DateTime), 'ocorrencia_hora':pa.Column(pa.String, pa.Check.str_matches(r'([0-1]?[0-9]|[2][0-3]):([0-5][0-9])(:[0-5][0-9])?$'),nullable=True), #nullable é pra permitir valores nulos 'total_recomendacoes':pa.Column(pa.Int) #essa expressão recular acima faz a validação das horas, minutos e segundos } ) schema.validate(df)
61.409091
200
0.72909
import pandas as pd import pandera as pa df = pd.read_csv('ocorrencia.csv', parse_dates=['ocorrencia_dia'], dayfirst=True) #fazer a leitura da tablea, parse_data: faz a conversão para data e dayfirst: faz com que o dia seja o primeiro número df.head(10) schema = pa.DataFrameSchema( #cria um esquema para o data frame para fazer as validações columns = { 'codigo':pa.Column(pa.Int, required=False), # O valor required (necessário) é True por padrao, colocando assim essa passa a ser uma coluna opcional, em caso de ausência não havera erro. 'codigo_ocorrencia':pa.Column(pa.Int),# diz que a primeira coluna tem que ser int 'codigo_ocorrencia2':pa.Column(pa.Int), # e assim por diante, verificando o tipo de cada coluna 'ocorrencia_classificacao':pa.Column(pa.String), 'ocorrencia_cidade':pa.Column(pa.String), 'ocorrencia_uf':pa.Column(pa.String, pa.Check.str_length(2,2)), # verifica o tamanho min e max 'ocorrencia_aerodromo':pa.Column(pa.String), 'ocorrencia_dia':pa.Column(pa.DateTime), 'ocorrencia_hora':pa.Column(pa.String, pa.Check.str_matches(r'([0-1]?[0-9]|[2][0-3]):([0-5][0-9])(:[0-5][0-9])?$'),nullable=True), #nullable é pra permitir valores nulos 'total_recomendacoes':pa.Column(pa.Int) #essa expressão recular acima faz a validação das horas, minutos e segundos } ) schema.validate(df)
0
0
0
f9988e778b5c1c5798f5d46e5b5e0c7dccee459a
4,932
py
Python
python/desc/sims/GCRCatSimInterface/SQLSubCatalog.py
jchiang87/sims_GCRCatSimInterface
320ddc07432bcaa05723944738a6e02b6841b69e
[ "BSD-3-Clause" ]
1
2020-11-02T21:08:39.000Z
2020-11-02T21:08:39.000Z
python/desc/sims/GCRCatSimInterface/SQLSubCatalog.py
jchiang87/sims_GCRCatSimInterface
320ddc07432bcaa05723944738a6e02b6841b69e
[ "BSD-3-Clause" ]
71
2018-01-12T17:12:50.000Z
2021-02-26T23:54:37.000Z
python/desc/sims/GCRCatSimInterface/SQLSubCatalog.py
jchiang87/sims_GCRCatSimInterface
320ddc07432bcaa05723944738a6e02b6841b69e
[ "BSD-3-Clause" ]
5
2018-01-11T18:42:42.000Z
2019-11-15T17:41:22.000Z
import numpy as np import os import sqlite3 from . import SubCatalogMixin __all__ = ["SQLSubCatalogMixin"] class SQLSubCatalogMixin(SubCatalogMixin): """ This is a SubCatalog mixin class that writes its output to a sqlite database, rather than a text file. Note: subcatalogs in the same CompoundInstanceCatalog will all have to write to the same database file. They can, however, write to different tables within that file. Writing the catalog more than once will overwrite the database file. """ _table_name = None # name of the table to write to _file_name = None # name of the file to write to _files_written = set() # these need to be shared among daughter _tables_created = set() # classes, in case multiple catalogs try # writing to the same database def _create_table(self, file_name): """ Create the database table to write to Parameters ---------- file_name is the full path to the file where we will make the database """ if len(self._current_chunk) is 0: return dtype_map = {} dtype_map[float] = ('float', float) dtype_map[np.float] = ('float', float) dtype_map[np.float64] = ('float', float) dtype_map[np.float32] = ('float', float) dtype_map[int] = ('int', int) dtype_map[np.int] = ('int', int) dtype_map[np.int64] = ('int', int) dtype_map[np.int32] = ('int', int) dtype_map[np.str_] = ('text', str) dtype_map[np.object_] = ('text', str) self._type_casting = {} # a dict that stores any casts # needed for the catalog columns with sqlite3.connect(file_name) as conn: cursor = conn.cursor() creation_cmd = '''CREATE TABLE %s ''' % self._table_name creation_cmd += '''(''' # loop over the columns specified for the catalog, # adding them to the table schema for i_col, name in enumerate(self.iter_column_names()): col_type = self.column_by_name(name).dtype.type sql_type = dtype_map[col_type][0] self._type_casting[name] = dtype_map[col_type][1] if i_col>0: creation_cmd += ''', ''' creation_cmd += '''%s %s''' % (name, sql_type) creation_cmd+=''')''' cursor.execute(creation_cmd) conn.commit() # log that we have written to the database and created the table self._files_written.add(file_name) self._tables_created.add(self._table_name) def _write_recarray(self, input_recarray, file_handle): """ Write the recarray currently being processed by the catalog class into the SQLite database Parameters ---------- input_recarray is a recarray of data to be written file_handle is the file handle of the main .txt InstanceCatalog being written """ if self._table_name is None: raise RuntimeError("Cannot call SubCatalogSQLMixin._write_recarray:" "\n_table_name is None") if self._file_name is None: raise RuntimeError("Cannot call SubCatalogSQLMixin._write_recarray:" "\n_file_name is None") self._filter_chunk(input_recarray) file_dir = os.path.dirname(file_handle.name) full_file_name = os.path.join(file_dir, self._file_name) # delete previous iterations of the file if full_file_name not in self._files_written: if os.path.exists(full_file_name): os.unlink(full_file_name) if self._table_name not in self._tables_created: self._create_table(full_file_name) col_dict = {} for name in self.iter_column_names(): arr = self.column_by_name(name) if name in self.transformations: col_dict[name] = self.transformations[name](arr) else: col_dict[name] = arr if len(self._current_chunk) == 0: return with sqlite3.connect(full_file_name) as conn: insert_cmd = '''INSERT INTO %s ''' % self._table_name insert_cmd += '''VALUES(''' for i_col, name in enumerate(self.iter_column_names()): if i_col>0: insert_cmd += ''',''' insert_cmd += '''?''' insert_cmd += ''')''' cursor = conn.cursor() values = (tuple(self._type_casting[name](col_dict[name][i_obj]) for name in self.iter_column_names()) for i_obj in range(len(self._current_chunk))) cursor.executemany(insert_cmd, values) conn.commit()
34.978723
80
0.580089
import numpy as np import os import sqlite3 from . import SubCatalogMixin __all__ = ["SQLSubCatalogMixin"] class SQLSubCatalogMixin(SubCatalogMixin): """ This is a SubCatalog mixin class that writes its output to a sqlite database, rather than a text file. Note: subcatalogs in the same CompoundInstanceCatalog will all have to write to the same database file. They can, however, write to different tables within that file. Writing the catalog more than once will overwrite the database file. """ _table_name = None # name of the table to write to _file_name = None # name of the file to write to _files_written = set() # these need to be shared among daughter _tables_created = set() # classes, in case multiple catalogs try # writing to the same database def _create_table(self, file_name): """ Create the database table to write to Parameters ---------- file_name is the full path to the file where we will make the database """ if len(self._current_chunk) is 0: return dtype_map = {} dtype_map[float] = ('float', float) dtype_map[np.float] = ('float', float) dtype_map[np.float64] = ('float', float) dtype_map[np.float32] = ('float', float) dtype_map[int] = ('int', int) dtype_map[np.int] = ('int', int) dtype_map[np.int64] = ('int', int) dtype_map[np.int32] = ('int', int) dtype_map[np.str_] = ('text', str) dtype_map[np.object_] = ('text', str) self._type_casting = {} # a dict that stores any casts # needed for the catalog columns with sqlite3.connect(file_name) as conn: cursor = conn.cursor() creation_cmd = '''CREATE TABLE %s ''' % self._table_name creation_cmd += '''(''' # loop over the columns specified for the catalog, # adding them to the table schema for i_col, name in enumerate(self.iter_column_names()): col_type = self.column_by_name(name).dtype.type sql_type = dtype_map[col_type][0] self._type_casting[name] = dtype_map[col_type][1] if i_col>0: creation_cmd += ''', ''' creation_cmd += '''%s %s''' % (name, sql_type) creation_cmd+=''')''' cursor.execute(creation_cmd) conn.commit() # log that we have written to the database and created the table self._files_written.add(file_name) self._tables_created.add(self._table_name) def _write_recarray(self, input_recarray, file_handle): """ Write the recarray currently being processed by the catalog class into the SQLite database Parameters ---------- input_recarray is a recarray of data to be written file_handle is the file handle of the main .txt InstanceCatalog being written """ if self._table_name is None: raise RuntimeError("Cannot call SubCatalogSQLMixin._write_recarray:" "\n_table_name is None") if self._file_name is None: raise RuntimeError("Cannot call SubCatalogSQLMixin._write_recarray:" "\n_file_name is None") self._filter_chunk(input_recarray) file_dir = os.path.dirname(file_handle.name) full_file_name = os.path.join(file_dir, self._file_name) # delete previous iterations of the file if full_file_name not in self._files_written: if os.path.exists(full_file_name): os.unlink(full_file_name) if self._table_name not in self._tables_created: self._create_table(full_file_name) col_dict = {} for name in self.iter_column_names(): arr = self.column_by_name(name) if name in self.transformations: col_dict[name] = self.transformations[name](arr) else: col_dict[name] = arr if len(self._current_chunk) == 0: return with sqlite3.connect(full_file_name) as conn: insert_cmd = '''INSERT INTO %s ''' % self._table_name insert_cmd += '''VALUES(''' for i_col, name in enumerate(self.iter_column_names()): if i_col>0: insert_cmd += ''',''' insert_cmd += '''?''' insert_cmd += ''')''' cursor = conn.cursor() values = (tuple(self._type_casting[name](col_dict[name][i_obj]) for name in self.iter_column_names()) for i_obj in range(len(self._current_chunk))) cursor.executemany(insert_cmd, values) conn.commit()
0
0
0
ae39961414a92e04a0aee535a8093bc7fce5d2f8
3,163
py
Python
sphinx_scality/directives/command.py
scality/sphinx_scality
278b45aedc7ebbd0689cc792f0531cc6d1038ad3
[ "Apache-2.0" ]
1
2020-06-18T06:38:14.000Z
2020-06-18T06:38:14.000Z
sphinx_scality/directives/command.py
scality/sphinx_scality
278b45aedc7ebbd0689cc792f0531cc6d1038ad3
[ "Apache-2.0" ]
23
2019-07-26T15:59:07.000Z
2021-12-10T14:59:47.000Z
sphinx_scality/directives/command.py
scality/sphinx_scality
278b45aedc7ebbd0689cc792f0531cc6d1038ad3
[ "Apache-2.0" ]
null
null
null
"""Directives for building command blocks.""" from docutils import nodes from docutils.parsers.rst import directives from sphinx.util.docutils import SphinxDirective class CommandBlockDirective(SphinxDirective): """Generate a container node with a command, its prompt and optional output.""" has_content = True required_arguments = 1 # The command-block ID used in references option_spec = dict( prompt=directives.unchanged, separator=directives.unchanged, )
34.380435
88
0.60607
"""Directives for building command blocks.""" from docutils import nodes from docutils.parsers.rst import directives from sphinx.util.docutils import SphinxDirective class CommandBlockDirective(SphinxDirective): """Generate a container node with a command, its prompt and optional output.""" has_content = True required_arguments = 1 # The command-block ID used in references option_spec = dict( prompt=directives.unchanged, separator=directives.unchanged, ) def run(self): separator = self.options.get( "separator", self.config.command_block_default_separator ) command, output = [], None for line in self.content.data: if output is None: if line == separator: output = [] else: command.append(line) else: if line == separator: raise self.error( "Found multiple separator lines - this is not supported, please" " use multiple `command-block` directives instead" ) output.append(line) # Prompt is a div.literal_block, with "console" highlighting prompt = self.options.get("prompt", self.config.command_block_default_prompt) prompt_node = nodes.literal_block( language="console", classes=["command-block__prompt"] ) prompt_node += nodes.Text(prompt) # Input is the command to copy, where the text itself is a div.literal_block # with "shell" highlighting input_node = nodes.container(classes=["command-block__input"]) input_text_node = nodes.literal_block( language="shell", classes=["command-block__input-text"] ) input_text_node += nodes.Text("\n".join(command)) input_node += input_text_node # Add a placeholder for a copy button input_node += nodes.container(classes=["command-block__copy"]) # Group prompt and input in a container command_node = nodes.container(classes=["command-block__command"]) command_node += prompt_node command_node += input_node # Wrap the command in a container block_node = nodes.container( classes=["command-block"], ids=[f"command-block-{self.arguments[0]}"] ) block_node += command_node # Optionally add an output div.literal_block without highlighting if output: output_node = nodes.literal_block( language="none", classes=["command-block__output"] ) output_node += nodes.Text("\n".join(output)) block_node += output_node return [block_node] def setup(app): app.add_config_value( "command_block_default_prompt", default="[user@host ~]$", rebuild="html", types=[str], ) app.add_config_value( "command_block_default_separator", default="---", rebuild="html", types=[str], ) app.add_directive("command-block", CommandBlockDirective)
2,611
0
50
cff5557da721d77a6ce84cdbaea837fe06f00b51
2,727
py
Python
src/backup_email.py
rajveer10092/kushs-utils-tool
4aa8fa5535f90d6bbb2bf6ecbbb1b708d490c99c
[ "MIT" ]
1
2021-10-01T04:09:57.000Z
2021-10-01T04:09:57.000Z
src/backup_email.py
rajveer10092/kushs-utils-tool
4aa8fa5535f90d6bbb2bf6ecbbb1b708d490c99c
[ "MIT" ]
null
null
null
src/backup_email.py
rajveer10092/kushs-utils-tool
4aa8fa5535f90d6bbb2bf6ecbbb1b708d490c99c
[ "MIT" ]
null
null
null
''' Config example: { "subject" : "Daily backup", "body" : "This is a daily database backup", "sender_email" : "sender@gmail.com", "receiver_email" : "receiver@gmail.com", "password" : "supersecretpassword", "smtp_server" : "smtp.gmail.com", "smtp_host" : 465, "dbname" : "dbname", "file_prefix": "dbname_backup" } ''' import email, smtplib, ssl import datetime import subprocess import shlex import json from email import encoders from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText CONFIG_FILE = 'backup_email.json' with open(CONFIG_FILE, 'r') as f: config = json.load(f) subject = config['subject'] body = config['body'] sender_email = config['sender_email'] receiver_email = config['receiver_email'] password = config['password'] smtp_server = config['smtp_server'] smtp_host = config['smtp_host'] dbname = config['dbname'] file_prefix = config['file_prefix'] cmd1 = "mysqldump {}".format(dbname) cmd2 = "gzip -9" filename = "{}_{}.sql.gz".format(file_prefix, datetime.datetime.now().strftime('%Y%m%d%H%M')) # Backup database print('Backing up database..') with open(filename, 'w') as f: ps1 = subprocess.Popen(shlex.split(cmd1), stdout=subprocess.PIPE) ps2 = subprocess.Popen(shlex.split(cmd2), stdin=ps1.stdout, stdout=f) ps1.wait() ps2.wait() if ps2.returncode == 2: exit(1) # Create a multipart message and set headers message = MIMEMultipart() message["From"] = sender_email message["To"] = receiver_email message["Subject"] = subject message["Bcc"] = receiver_email # Recommended for mass emails # Add body to email message.attach(MIMEText(body, "plain")) # Open PDF file in binary mode with open(filename, "rb") as attachment: # Add file as application/octet-stream # Email client can usually download this automatically as attachment part = MIMEBase("application", "octet-stream") part.set_payload(attachment.read()) # Encode file in ASCII characters to send by email encoders.encode_base64(part) # Add header as key/value pair to attachment part part.add_header( "Content-Disposition", f"attachment; filename= {filename}", ) # Add attachment to message and convert message to string message.attach(part) text = message.as_string() # Log in to server using secure context and send email print('Sending email..') context = ssl.create_default_context() with smtplib.SMTP_SSL(smtp_server, smtp_host, context=context) as server: server.login(sender_email, password) server.sendmail(sender_email, receiver_email, text) print('Done.')
28.40625
94
0.694169
''' Config example: { "subject" : "Daily backup", "body" : "This is a daily database backup", "sender_email" : "sender@gmail.com", "receiver_email" : "receiver@gmail.com", "password" : "supersecretpassword", "smtp_server" : "smtp.gmail.com", "smtp_host" : 465, "dbname" : "dbname", "file_prefix": "dbname_backup" } ''' import email, smtplib, ssl import datetime import subprocess import shlex import json from email import encoders from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText CONFIG_FILE = 'backup_email.json' with open(CONFIG_FILE, 'r') as f: config = json.load(f) subject = config['subject'] body = config['body'] sender_email = config['sender_email'] receiver_email = config['receiver_email'] password = config['password'] smtp_server = config['smtp_server'] smtp_host = config['smtp_host'] dbname = config['dbname'] file_prefix = config['file_prefix'] cmd1 = "mysqldump {}".format(dbname) cmd2 = "gzip -9" filename = "{}_{}.sql.gz".format(file_prefix, datetime.datetime.now().strftime('%Y%m%d%H%M')) # Backup database print('Backing up database..') with open(filename, 'w') as f: ps1 = subprocess.Popen(shlex.split(cmd1), stdout=subprocess.PIPE) ps2 = subprocess.Popen(shlex.split(cmd2), stdin=ps1.stdout, stdout=f) ps1.wait() ps2.wait() if ps2.returncode == 2: exit(1) # Create a multipart message and set headers message = MIMEMultipart() message["From"] = sender_email message["To"] = receiver_email message["Subject"] = subject message["Bcc"] = receiver_email # Recommended for mass emails # Add body to email message.attach(MIMEText(body, "plain")) # Open PDF file in binary mode with open(filename, "rb") as attachment: # Add file as application/octet-stream # Email client can usually download this automatically as attachment part = MIMEBase("application", "octet-stream") part.set_payload(attachment.read()) # Encode file in ASCII characters to send by email encoders.encode_base64(part) # Add header as key/value pair to attachment part part.add_header( "Content-Disposition", f"attachment; filename= {filename}", ) # Add attachment to message and convert message to string message.attach(part) text = message.as_string() # Log in to server using secure context and send email print('Sending email..') context = ssl.create_default_context() with smtplib.SMTP_SSL(smtp_server, smtp_host, context=context) as server: server.login(sender_email, password) server.sendmail(sender_email, receiver_email, text) print('Done.')
0
0
0
94c757d0d32e122e74892e29195ffbc36204cd83
2,146
py
Python
solutions/linked_list.py
edab/DSA_Quick_Reference
827a7d3331d9224e8bb21feb9151a89fc637a649
[ "MIT" ]
3
2021-02-15T15:59:51.000Z
2021-05-02T16:52:17.000Z
solutions/linked_list.py
edab/DSA_Quick_Reference
827a7d3331d9224e8bb21feb9151a89fc637a649
[ "MIT" ]
null
null
null
solutions/linked_list.py
edab/DSA_Quick_Reference
827a7d3331d9224e8bb21feb9151a89fc637a649
[ "MIT" ]
1
2021-06-28T08:50:42.000Z
2021-06-28T08:50:42.000Z
# Test Case linked_list = LinkedList([5, 7, -1, 0.9, 71]) print("Linked List tests:") print (" Initialization: " + "Pass" if (linked_list.to_list() == [5, 7, -1, 0.9, 71]) else "Fail") linked_list.delete(-1) print (" Delete: " + "Pass" if (linked_list.to_list() == [5, 7, 0.9, 71]) else "Fail") print (" Search: " + "Pass" if (linked_list.search(0.9)) else "Fail") print (" Search: " + "Pass" if (not linked_list.search(55)) else "Fail") linked_list.append(91) print (" Append: " + "Pass" if (linked_list.to_list() == [5, 7, 0.9, 71, 91]) else "Fail") print (" Pop: " + "Pass" if (linked_list.pop() == 5) else "Fail")
25.547619
99
0.501864
class Node: def __init__(self, value): self.value = value self.next = None class LinkedList: def __init__(self, values = []): self.head = None for value in values: self.append(value) def append(self, value): if self.head is None: self.head = Node(value) return node = self.head while node.next: node = node.next node.next = Node(value) def search(self, value): if self.head is None: return False node = self.head while node: if node.value == value: return True node = node.next return False def delete(self, value): if self.head is None: return if self.head.value == value: self.head = self.head.next return node = self.head while node.next: if node.next.value == value: node.next = node.next.next return node = node.next def pop(self): if self.head is None: return None node = self.head self.head = self.head.next return node.value def to_list(self): out = [] node = self.head while node is not None: out.append(node.value) node = node.next return out # Test Case linked_list = LinkedList([5, 7, -1, 0.9, 71]) print("Linked List tests:") print (" Initialization: " + "Pass" if (linked_list.to_list() == [5, 7, -1, 0.9, 71]) else "Fail") linked_list.delete(-1) print (" Delete: " + "Pass" if (linked_list.to_list() == [5, 7, 0.9, 71]) else "Fail") print (" Search: " + "Pass" if (linked_list.search(0.9)) else "Fail") print (" Search: " + "Pass" if (not linked_list.search(55)) else "Fail") linked_list.append(91) print (" Append: " + "Pass" if (linked_list.to_list() == [5, 7, 0.9, 71, 91]) else "Fail") print (" Pop: " + "Pass" if (linked_list.pop() == 5) else "Fail")
1,258
-14
234
a2dbadb5c4a33ec0249abadd5a724abedcbc2115
2,973
py
Python
core/tests/test_utils/test_memoize.py
erexer/polyaxon
be14dae1ed56d568983388736bcdaf27a7baa4a4
[ "Apache-2.0" ]
null
null
null
core/tests/test_utils/test_memoize.py
erexer/polyaxon
be14dae1ed56d568983388736bcdaf27a7baa4a4
[ "Apache-2.0" ]
null
null
null
core/tests/test_utils/test_memoize.py
erexer/polyaxon
be14dae1ed56d568983388736bcdaf27a7baa4a4
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/python # # Copyright 2018-2020 Polyaxon, Inc. # # 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. from tests.utils import BaseTestCase from polyaxon.utils.memoize_decorators import memoize class MemoizeMethodTest(BaseTestCase): """ A test case for the `memoize` decorator. """
33.033333
74
0.644467
#!/usr/bin/python # # Copyright 2018-2020 Polyaxon, Inc. # # 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. from tests.utils import BaseTestCase from polyaxon.utils.memoize_decorators import memoize class MemoizeMethodTest(BaseTestCase): """ A test case for the `memoize` decorator. """ def setUp(self): super().setUp() class TestClass: def __init__(self): self.test0_execution_count = 0 self.test1_execution_count = 0 self.test2_execution_count = 0 @memoize def test0(self): self.test0_execution_count += 1 return 42 @memoize def test1(self, a): self.test1_execution_count += 1 return a @memoize def test2(self, a, b): self.test2_execution_count += 1 return a ** b self.obj1 = TestClass() self.obj2 = TestClass() def test_function_is_executed_on_first_request(self): result0 = self.obj1.test0() result1 = self.obj1.test1(1) result2 = self.obj1.test2(2, 3) self.assertEqual(42, result0) self.assertEqual(1, result1) self.assertEqual(8, result2) self.assertEqual(1, self.obj1.test0_execution_count) self.assertEqual(1, self.obj1.test1_execution_count) self.assertEqual(1, self.obj1.test2_execution_count) def test_results_are_cached(self): self.obj1.test0() self.obj1.test1(1) self.obj1.test2(2, 3) result0 = self.obj1.test0() result1 = self.obj1.test1(1) result2 = self.obj1.test2(2, 3) self.assertEqual(42, result0) self.assertEqual(1, result1) self.assertEqual(8, result2) self.assertEqual(1, self.obj1.test0_execution_count) self.assertEqual(1, self.obj1.test1_execution_count) self.assertEqual(1, self.obj1.test2_execution_count) def test_function_is_executed_for_new_parameter_combination(self): self.obj1.test2(2, 3) result = self.obj1.test2(3, 2) self.assertEqual(9, result) self.assertEqual(2, self.obj1.test2_execution_count) def test_result_is_not_cached_across_instances(self): self.obj1.test2(2, 3) self.assertEqual(0, self.obj2.test2_execution_count) self.obj2.test2(2, 3) self.assertEqual(1, self.obj2.test2_execution_count)
2,039
0
135
0792080b49482a1ae7df25e8bab51bd1a5b856d0
3,284
py
Python
tests/hazmat/primitives/test_hmac_vectors.py
glyph/cryptography
43cf688e885668198bc966b1cf3a4a425a60f1a6
[ "Apache-2.0" ]
null
null
null
tests/hazmat/primitives/test_hmac_vectors.py
glyph/cryptography
43cf688e885668198bc966b1cf3a4a425a60f1a6
[ "Apache-2.0" ]
4
2021-03-22T02:00:19.000Z
2021-04-07T07:40:19.000Z
tests/hazmat/primitives/test_hmac_vectors.py
majacQ/cryptography
add8bec357f09aba6609af16577111addec07ef7
[ "Apache-2.0" ]
null
null
null
# 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. from __future__ import absolute_import, division, print_function import pytest from cryptography.hazmat.primitives import hashes from .utils import generate_hmac_test from ...utils import load_hash_vectors @pytest.mark.supported( only_if=lambda backend: backend.hmac_supported(hashes.MD5()), skip_message="Does not support MD5", ) @pytest.mark.hmac @pytest.mark.supported( only_if=lambda backend: backend.hmac_supported(hashes.SHA1()), skip_message="Does not support SHA1", ) @pytest.mark.hmac @pytest.mark.supported( only_if=lambda backend: backend.hmac_supported(hashes.SHA224()), skip_message="Does not support SHA224", ) @pytest.mark.hmac @pytest.mark.supported( only_if=lambda backend: backend.hmac_supported(hashes.SHA256()), skip_message="Does not support SHA256", ) @pytest.mark.hmac @pytest.mark.supported( only_if=lambda backend: backend.hmac_supported(hashes.SHA384()), skip_message="Does not support SHA384", ) @pytest.mark.hmac @pytest.mark.supported( only_if=lambda backend: backend.hmac_supported(hashes.SHA512()), skip_message="Does not support SHA512", ) @pytest.mark.hmac @pytest.mark.supported( only_if=lambda backend: backend.hmac_supported(hashes.RIPEMD160()), skip_message="Does not support RIPEMD160", ) @pytest.mark.hmac
24.507463
71
0.661084
# 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. from __future__ import absolute_import, division, print_function import pytest from cryptography.hazmat.primitives import hashes from .utils import generate_hmac_test from ...utils import load_hash_vectors @pytest.mark.supported( only_if=lambda backend: backend.hmac_supported(hashes.MD5()), skip_message="Does not support MD5", ) @pytest.mark.hmac class TestHMAC_MD5(object): test_hmac_md5 = generate_hmac_test( load_hash_vectors, "HMAC", [ "rfc-2202-md5.txt", ], hashes.MD5(), ) @pytest.mark.supported( only_if=lambda backend: backend.hmac_supported(hashes.SHA1()), skip_message="Does not support SHA1", ) @pytest.mark.hmac class TestHMAC_SHA1(object): test_hmac_sha1 = generate_hmac_test( load_hash_vectors, "HMAC", [ "rfc-2202-sha1.txt", ], hashes.SHA1(), ) @pytest.mark.supported( only_if=lambda backend: backend.hmac_supported(hashes.SHA224()), skip_message="Does not support SHA224", ) @pytest.mark.hmac class TestHMAC_SHA224(object): test_hmac_sha224 = generate_hmac_test( load_hash_vectors, "HMAC", [ "rfc-4231-sha224.txt", ], hashes.SHA224(), ) @pytest.mark.supported( only_if=lambda backend: backend.hmac_supported(hashes.SHA256()), skip_message="Does not support SHA256", ) @pytest.mark.hmac class TestHMAC_SHA256(object): test_hmac_sha256 = generate_hmac_test( load_hash_vectors, "HMAC", [ "rfc-4231-sha256.txt", ], hashes.SHA256(), ) @pytest.mark.supported( only_if=lambda backend: backend.hmac_supported(hashes.SHA384()), skip_message="Does not support SHA384", ) @pytest.mark.hmac class TestHMAC_SHA384(object): test_hmac_sha384 = generate_hmac_test( load_hash_vectors, "HMAC", [ "rfc-4231-sha384.txt", ], hashes.SHA384(), ) @pytest.mark.supported( only_if=lambda backend: backend.hmac_supported(hashes.SHA512()), skip_message="Does not support SHA512", ) @pytest.mark.hmac class TestHMAC_SHA512(object): test_hmac_sha512 = generate_hmac_test( load_hash_vectors, "HMAC", [ "rfc-4231-sha512.txt", ], hashes.SHA512(), ) @pytest.mark.supported( only_if=lambda backend: backend.hmac_supported(hashes.RIPEMD160()), skip_message="Does not support RIPEMD160", ) @pytest.mark.hmac class TestHMAC_RIPEMD160(object): test_hmac_ripemd160 = generate_hmac_test( load_hash_vectors, "HMAC", [ "rfc-2286-ripemd160.txt", ], hashes.RIPEMD160(), )
0
1,266
154
5d3764986b1ff63d323b5ce58971f1b5003bfe7d
265
py
Python
ShowFolder.py
loamhoof/sublime-plugins-dump
57518b19a96e090670e2592438688c600a5b875a
[ "MIT" ]
null
null
null
ShowFolder.py
loamhoof/sublime-plugins-dump
57518b19a96e090670e2592438688c600a5b875a
[ "MIT" ]
null
null
null
ShowFolder.py
loamhoof/sublime-plugins-dump
57518b19a96e090670e2592438688c600a5b875a
[ "MIT" ]
null
null
null
import os.path import sublime_plugin
26.5
98
0.716981
import os.path import sublime_plugin class ShowFolder(sublime_plugin.TextCommand): def run(self, _): self.view.window().show_input_panel("Folder path", os.path.dirname(self.view.file_name()), on_done=None, on_change=None, on_cancel=None)
153
24
49
91a5b67f7631d2696b6c734e1c1dee852f1f85c2
338
py
Python
src/apps/about/models/post_kateg.py
rko619619/Skidon
fe09d0d87edb973c0cb1f20478e398bc69899d1b
[ "Apache-2.0" ]
null
null
null
src/apps/about/models/post_kateg.py
rko619619/Skidon
fe09d0d87edb973c0cb1f20478e398bc69899d1b
[ "Apache-2.0" ]
1
2020-04-11T18:55:09.000Z
2020-04-11T18:55:21.000Z
src/apps/about/models/post_kateg.py
rko619619/Skidon
fe09d0d87edb973c0cb1f20478e398bc69899d1b
[ "Apache-2.0" ]
null
null
null
from django.db import models as m
21.125
69
0.60355
from django.db import models as m class Post_kateg(m.Model): name = m.TextField() class Meta: verbose_name_plural = "Post_kateg" ordering = ["name"] def __repr__(self): return f"{self.__class__.__name__} # '{self.pk}:{self.name}'" def __str__(self): return f"{self.name}: '{self.pk}'"
108
172
23
bf04c9460b8d03db1ed049ee58129c4bd712daa5
1,723
py
Python
Best_time_to_sale_stocks.py
minami2k/Leetcode-Hard-Problems_Hacktoberfest2021
a2e07bb2c8ab665e74186085eeff95fe845ae102
[ "MIT" ]
null
null
null
Best_time_to_sale_stocks.py
minami2k/Leetcode-Hard-Problems_Hacktoberfest2021
a2e07bb2c8ab665e74186085eeff95fe845ae102
[ "MIT" ]
9
2021-10-01T14:53:32.000Z
2021-10-19T16:24:58.000Z
Best_time_to_sale_stocks.py
minami2k/Leetcode-Hard-Problems_Hacktoberfest2021
a2e07bb2c8ab665e74186085eeff95fe845ae102
[ "MIT" ]
3
2021-10-01T14:41:21.000Z
2021-10-21T04:32:11.000Z
# https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/ # 123. Best Time to Buy and Sell Stock III(Hard) Solution # 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 at most two transactions. # Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). # Driver code # test = [3, 3, 5, 0, 0, 3, 1, 4] # p = Solution() # result = p.maxProfit(test) # print(result)
42.02439
156
0.59083
# https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/ # 123. Best Time to Buy and Sell Stock III(Hard) Solution # 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 at most two transactions. # Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ l = len(prices) # helper function that finds maxrise and the locations of maxrise in prices[b:e:step] def helper(b, e, step): max_rise, tmp_lo, lo, hi = 0, b, 0, 0 for i in range(b, e, step): rise = prices[i] - prices[tmp_lo] if rise <= 0: tmp_lo = i elif rise > max_rise: max_rise, lo, hi = rise, tmp_lo, i return max_rise, lo, hi # For the first pass, we identify the indices for "at most 1 transaction" problem, so that we find lo, hi max_rise, lo, hi = helper(0, l, 1) # Then there are three possibilities: 1, use (lo, hi) and another rise before lo; 2, (lo, hi) and another rise after hi; 3, use (lo, x) and (y, hi). # In the third case, it is equivalent to finding the max_rise in the sequence prices[hi:lo:-1] m1, m2, m3 = helper(0, lo, 1)[0], helper( hi+1, l, 1)[0], helper(hi-1, lo, -1)[0] return max_rise + max(m1, m2, m3) # Driver code # test = [3, 3, 5, 0, 0, 3, 1, 4] # p = Solution() # result = p.maxProfit(test) # print(result)
332
822
23
a7a936b4a95c632e4145978a6ba86b5ca3ef790e
2,372
py
Python
unittests/pep8_tester.py
RoyVorster/pygccxml
f487b1e26e88d521d623e6a587510b322f7d3dc7
[ "BSL-1.0" ]
null
null
null
unittests/pep8_tester.py
RoyVorster/pygccxml
f487b1e26e88d521d623e6a587510b322f7d3dc7
[ "BSL-1.0" ]
null
null
null
unittests/pep8_tester.py
RoyVorster/pygccxml
f487b1e26e88d521d623e6a587510b322f7d3dc7
[ "BSL-1.0" ]
null
null
null
# Copyright 2014-2017 Insight Software Consortium. # Copyright 2004-2009 Roman Yakovenko. # Distributed under the Boost Software License, Version 1.0. # See http://www.boost.org/LICENSE_1_0.txt import os import pycodestyle import unittest import fnmatch if __name__ == "__main__": run_suite()
24.968421
67
0.618887
# Copyright 2014-2017 Insight Software Consortium. # Copyright 2004-2009 Roman Yakovenko. # Distributed under the Boost Software License, Version 1.0. # See http://www.boost.org/LICENSE_1_0.txt import os import pycodestyle import unittest import fnmatch class Test(unittest.TestCase): def test_pep8_conformance_unitests(self): """ Pep8 conformance test (unitests) Runs on the unittest directory. """ # Get the path to current directory path = os.path.dirname(os.path.realpath(__file__)) self.run_check(path) def test_pep8_conformance_pygccxml(self): """ Pep8 conformance test (pygccxml) Runs on the pygccxml directory. """ # Get the path to current directory path = os.path.dirname(os.path.realpath(__file__)) path += "/../pygccxml/" self.run_check(path) def test_pep8_conformance_example(self): """ Pep8 conformance test (examples) Runs on the example file in the docs. """ # Get the path to current directory path = os.path.dirname(os.path.realpath(__file__)) path += "/../docs/examples/" # Find all the examples files file_paths = [] for root, dirnames, filenames in os.walk(path): for file_path in fnmatch.filter(filenames, '*.py'): file_paths.append(os.path.join(root, file_path)) for path in file_paths: self.run_check(path) def test_pep8_conformance_setup(self): """ Pep8 conformance test (setup) Runs on the setup.py file """ # Get the path to current directory path = os.path.dirname(os.path.realpath(__file__)) path += "/../setup.py" self.run_check(path) def run_check(self, path): """Common method to run the pep8 test.""" result = pycodestyle.StyleGuide().check_files(paths=[path]) if result.total_errors != 0: self.assertEqual( result.total_errors, 0, "Found code style errors (and warnings).") def create_suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(Test)) return suite def run_suite(): unittest.TextTestRunner(verbosity=2).run(create_suite()) if __name__ == "__main__": run_suite()
148
1,852
69
9f5bd35d209281a93fb7f14a5c6f9d3ca1e40ff6
8,650
py
Python
pybind/dnszone.py
RhubarbSin/PyBIND
f7a79891c867296b988fa48f10eeab853bf76ea5
[ "MIT" ]
1
2017-10-19T21:14:47.000Z
2017-10-19T21:14:47.000Z
pybind/dnszone.py
RhubarbSin/PyBIND
f7a79891c867296b988fa48f10eeab853bf76ea5
[ "MIT" ]
null
null
null
pybind/dnszone.py
RhubarbSin/PyBIND
f7a79891c867296b988fa48f10eeab853bf76ea5
[ "MIT" ]
null
null
null
"""Classes for creating DNS zones and writing corresponding zone files. No validation is done here (e.g. requiring a SOA record) because this module may be used to create fragments of zone files to be used via an $INCLUDE directive. Users of this module are encouraged to employ an external validation process like named-checkzone(8) on zone files. Host names are passed to dnsrecord.ResourceRecord methods unmodified; i.e. they must be terminated with a dot ('.') to be interpreted as fully qualified domain names (FQDNs)--otherwise they will be interpreted relative to $ORIGIN, so be diligent in minding your dots. IP addresses may be specified in any format accepted by ipaddr.IPAddress(). Time values may be specified either as an integer (seconds) or a string in one of BIND's time formats. Note that the 'name' keyword argument defaults to '@', so adding an MX record, for example, adds an MX record for the whole domain unless otherwise specified. The 'ttl' keyword argument defaults to None, so records will use the zone's default time-to-live (TTL) unless otherwise specified. """ import time import ipaddr import dnsrecord class _Zone(object): """Base DNS zone object.""" # default values for keyword args; values chosen from RFC recommendations TTL = '1h' REFRESH = '3h' RETRY = '1h' EXPIRY = '2d' NXDOMAIN = '1h' def __init__(self, origin, epochserial=False, ttl=TTL): """Return a _Zone object. Args: origin: (str) zone's root; '.' will be appended if necessary 'example.com' epochserial: (boolean) whether to use number of seconds since epoch as default serial number in SOA record ttl: (str or int) default time-to-live for resource records """ self.origin = origin if not self.origin.endswith('.'): # make sure it looks like FQDN (although it still might be wrong) self.origin += '.' self.epochserial = epochserial self.records = [] # list of dnsrecord objects self.ttl = ttl def write_file(self, filename): """Write zone file. Args: filename: (str) name of file to be written 'zonefile.hosts' """ with open(filename, 'w') as fh: fh.write('$ORIGIN %s\n' % self.origin) fh.write('$TTL %s\n' % self.ttl) for record in self.records: fh.write('%s\n' % record) fh.close() def add_record(self, record): """Add record to zone. This is abstracted from the add_*() methods in case later implementations store the records in a different data structure. (YagNi?) Args: record: (dnsrecord.ResourceRecord) record to be added """ self.records.append(record) def add_soa(self, mname, rname, serial=None, refresh=REFRESH, retry=RETRY, expiry=EXPIRY, nxdomain=NXDOMAIN, name='@', ttl=None): """Add Start of Authority record to zone. Args: mname: (str) host name of name server authoritative for zone 'ns1.example.com.' rname: (str) e-mail address of person responsible for zone 'hostmaster@example.com' serial: (int) serial number '1969123100' refresh: (str or int) slave's refresh interval retry: (str or int) slave's retry interval expiry: (str or int) slave's expiry interval nxdomain: (str or int) negative caching time (TTL) name: (str) name of node to which this record belongs 'example.com.' """ if serial is None: # set default serial number if self.epochserial: serial = int(time.time()) # number of seconds since epoch else: serial = int(time.strftime('%Y%m%d00')) # YYYYMMDD00 soa = dnsrecord.SOA(name, mname, rname, serial, refresh, retry, expiry, nxdomain, ttl) self.add_record(soa) def add_ns(self, name_server, name='@', ttl=None): """Add Name Server record to zone. Args: name_server: (str) host name of name server 'ns1.example.com.' name: (str) name of node to which this record belongs 'example.com.' ttl: (str or int) time-to-live """ ns = dnsrecord.NS(name, name_server, ttl) self.add_record(ns) class ForwardZone(_Zone): """Forward DNS zone.""" def add_a(self, address, name='@', ttl=None): """Add IPv4 Address record to zone. Args: address: (str) IPv4 address '192.168.1.1' name: (str) name of node to which this record belongs 'host.example.com.' ttl: (str or int) time-to-live """ a = dnsrecord.A(name, address, ttl) self.add_record(a) def add_aaaa(self, address, name='@', ttl=None): """Add IPv6 Address record to zone. Args: address: (str) IPv6 address '2001:db8::1' name: (str) name of node to which this record belongs 'host.example.com.' ttl: (str or int) time-to-live """ aaaa = dnsrecord.AAAA(name, address, ttl) self.add_record(aaaa) def add_cname(self, canonical_name, name='@', ttl=None): """Add Canonical Name record to zone. Args: canonical: (str) canonical host name of host 'mail.example.com.' name: (str) name of node to which this record belongs 'mailserver.example.com.' ttl: (str or int) time-to-live """ cname = dnsrecord.CNAME(name, canonical_name, ttl) self.add_record(cname) def add_mx(self, mail_exchanger, preference=10, name='@', ttl=None): """Add Mail Exchanger record to zone. Args: mail_exchanger: (str) host name of mail exchanger 'mail.example.com.' preference: (int) preference value of mail exchanger name: (str) name of node to which this record belongs 'example.com.' ttl: (str or int) time-to-live """ mx = dnsrecord.MX(name, preference, mail_exchanger, ttl) self.add_record(mx) def add_txt(self, text, name='@', ttl=None): """Add Text record to zone. Args: text: (str) textual contents of record 'This is a text record' name: (str) name of node to which this record belongs 'example.com.' ttl: (str or int) time-to-live """ txt = dnsrecord.TXT(name, text, ttl) self.add_record(txt) class ReverseZone(_Zone): """Reverse DNS zone.""" def add_ptr(self, address, name='@', ttl=None): """Add Pointer record to zone. Args: address: (str) IPv4 or IPv6 address '192.168.1.1' name: (str) name of node to which this record belongs 'ns1.example.com.' ttl: (str or int) time-to-live """ ptr = dnsrecord.PTR(address, name, ttl) self.add_record(ptr) def run_tests(): """Run rudimentary tests of module. These are really intended for development and debugging purposes rather than a substitute for unit tests. """ # create forward zone and write to file z = ForwardZone('example.com') z.add_soa('ns1', 'hostmaster') z.add_ns('ns1') z.add_ns('ns2') z.add_mx('mail1') z.add_mx('mail2', 20, ttl=600) z.add_a('192.168.1.1', 'ns1') z.add_aaaa('2001:db8::1', 'ns1') z.add_txt('v=spf1 mx ~all') z.add_cname('mailserver', 'mail') filename = 'fwdzone' z.write_file(filename) print 'Wrote %s.' % filename # create IPv4 reverse zone and write to file z = ReverseZone('1.168.192.in-addr.arpa') z.add_soa('ns1.example.com.', 'hostmaster@example.com.') z.add_ns('ns1.example.com.') z.add_ptr('192.168.1.1', 'ns1.example.com.') filename = 'revzone4' z.write_file(filename) print 'Wrote %s.' % filename # create IPv6 reverse zone and write to file z = ReverseZone('0.0.0.0.0.0.c.f.ip6.arpa', epochserial=True) z.add_soa('ns1.example.com.', 'hostmaster@example.com.') z.add_ns('ns1.example.com.') z.add_ptr('2001:db8::1', 'ns1.example.com.') filename = 'revzone6' z.write_file(filename) print 'Wrote %s.' % filename if __name__ == '__main__': run_tests()
32.156134
78
0.591908
"""Classes for creating DNS zones and writing corresponding zone files. No validation is done here (e.g. requiring a SOA record) because this module may be used to create fragments of zone files to be used via an $INCLUDE directive. Users of this module are encouraged to employ an external validation process like named-checkzone(8) on zone files. Host names are passed to dnsrecord.ResourceRecord methods unmodified; i.e. they must be terminated with a dot ('.') to be interpreted as fully qualified domain names (FQDNs)--otherwise they will be interpreted relative to $ORIGIN, so be diligent in minding your dots. IP addresses may be specified in any format accepted by ipaddr.IPAddress(). Time values may be specified either as an integer (seconds) or a string in one of BIND's time formats. Note that the 'name' keyword argument defaults to '@', so adding an MX record, for example, adds an MX record for the whole domain unless otherwise specified. The 'ttl' keyword argument defaults to None, so records will use the zone's default time-to-live (TTL) unless otherwise specified. """ import time import ipaddr import dnsrecord class _Zone(object): """Base DNS zone object.""" # default values for keyword args; values chosen from RFC recommendations TTL = '1h' REFRESH = '3h' RETRY = '1h' EXPIRY = '2d' NXDOMAIN = '1h' def __init__(self, origin, epochserial=False, ttl=TTL): """Return a _Zone object. Args: origin: (str) zone's root; '.' will be appended if necessary 'example.com' epochserial: (boolean) whether to use number of seconds since epoch as default serial number in SOA record ttl: (str or int) default time-to-live for resource records """ self.origin = origin if not self.origin.endswith('.'): # make sure it looks like FQDN (although it still might be wrong) self.origin += '.' self.epochserial = epochserial self.records = [] # list of dnsrecord objects self.ttl = ttl def write_file(self, filename): """Write zone file. Args: filename: (str) name of file to be written 'zonefile.hosts' """ with open(filename, 'w') as fh: fh.write('$ORIGIN %s\n' % self.origin) fh.write('$TTL %s\n' % self.ttl) for record in self.records: fh.write('%s\n' % record) fh.close() def add_record(self, record): """Add record to zone. This is abstracted from the add_*() methods in case later implementations store the records in a different data structure. (YagNi?) Args: record: (dnsrecord.ResourceRecord) record to be added """ self.records.append(record) def add_soa(self, mname, rname, serial=None, refresh=REFRESH, retry=RETRY, expiry=EXPIRY, nxdomain=NXDOMAIN, name='@', ttl=None): """Add Start of Authority record to zone. Args: mname: (str) host name of name server authoritative for zone 'ns1.example.com.' rname: (str) e-mail address of person responsible for zone 'hostmaster@example.com' serial: (int) serial number '1969123100' refresh: (str or int) slave's refresh interval retry: (str or int) slave's retry interval expiry: (str or int) slave's expiry interval nxdomain: (str or int) negative caching time (TTL) name: (str) name of node to which this record belongs 'example.com.' """ if serial is None: # set default serial number if self.epochserial: serial = int(time.time()) # number of seconds since epoch else: serial = int(time.strftime('%Y%m%d00')) # YYYYMMDD00 soa = dnsrecord.SOA(name, mname, rname, serial, refresh, retry, expiry, nxdomain, ttl) self.add_record(soa) def add_ns(self, name_server, name='@', ttl=None): """Add Name Server record to zone. Args: name_server: (str) host name of name server 'ns1.example.com.' name: (str) name of node to which this record belongs 'example.com.' ttl: (str or int) time-to-live """ ns = dnsrecord.NS(name, name_server, ttl) self.add_record(ns) class ForwardZone(_Zone): """Forward DNS zone.""" def add_a(self, address, name='@', ttl=None): """Add IPv4 Address record to zone. Args: address: (str) IPv4 address '192.168.1.1' name: (str) name of node to which this record belongs 'host.example.com.' ttl: (str or int) time-to-live """ a = dnsrecord.A(name, address, ttl) self.add_record(a) def add_aaaa(self, address, name='@', ttl=None): """Add IPv6 Address record to zone. Args: address: (str) IPv6 address '2001:db8::1' name: (str) name of node to which this record belongs 'host.example.com.' ttl: (str or int) time-to-live """ aaaa = dnsrecord.AAAA(name, address, ttl) self.add_record(aaaa) def add_cname(self, canonical_name, name='@', ttl=None): """Add Canonical Name record to zone. Args: canonical: (str) canonical host name of host 'mail.example.com.' name: (str) name of node to which this record belongs 'mailserver.example.com.' ttl: (str or int) time-to-live """ cname = dnsrecord.CNAME(name, canonical_name, ttl) self.add_record(cname) def add_mx(self, mail_exchanger, preference=10, name='@', ttl=None): """Add Mail Exchanger record to zone. Args: mail_exchanger: (str) host name of mail exchanger 'mail.example.com.' preference: (int) preference value of mail exchanger name: (str) name of node to which this record belongs 'example.com.' ttl: (str or int) time-to-live """ mx = dnsrecord.MX(name, preference, mail_exchanger, ttl) self.add_record(mx) def add_txt(self, text, name='@', ttl=None): """Add Text record to zone. Args: text: (str) textual contents of record 'This is a text record' name: (str) name of node to which this record belongs 'example.com.' ttl: (str or int) time-to-live """ txt = dnsrecord.TXT(name, text, ttl) self.add_record(txt) class ReverseZone(_Zone): """Reverse DNS zone.""" def add_ptr(self, address, name='@', ttl=None): """Add Pointer record to zone. Args: address: (str) IPv4 or IPv6 address '192.168.1.1' name: (str) name of node to which this record belongs 'ns1.example.com.' ttl: (str or int) time-to-live """ ptr = dnsrecord.PTR(address, name, ttl) self.add_record(ptr) def run_tests(): """Run rudimentary tests of module. These are really intended for development and debugging purposes rather than a substitute for unit tests. """ # create forward zone and write to file z = ForwardZone('example.com') z.add_soa('ns1', 'hostmaster') z.add_ns('ns1') z.add_ns('ns2') z.add_mx('mail1') z.add_mx('mail2', 20, ttl=600) z.add_a('192.168.1.1', 'ns1') z.add_aaaa('2001:db8::1', 'ns1') z.add_txt('v=spf1 mx ~all') z.add_cname('mailserver', 'mail') filename = 'fwdzone' z.write_file(filename) print 'Wrote %s.' % filename # create IPv4 reverse zone and write to file z = ReverseZone('1.168.192.in-addr.arpa') z.add_soa('ns1.example.com.', 'hostmaster@example.com.') z.add_ns('ns1.example.com.') z.add_ptr('192.168.1.1', 'ns1.example.com.') filename = 'revzone4' z.write_file(filename) print 'Wrote %s.' % filename # create IPv6 reverse zone and write to file z = ReverseZone('0.0.0.0.0.0.c.f.ip6.arpa', epochserial=True) z.add_soa('ns1.example.com.', 'hostmaster@example.com.') z.add_ns('ns1.example.com.') z.add_ptr('2001:db8::1', 'ns1.example.com.') filename = 'revzone6' z.write_file(filename) print 'Wrote %s.' % filename if __name__ == '__main__': run_tests()
0
0
0
cecf44fdd12e84203872fbc2f54875dcae0381cb
4,237
py
Python
neutron/tests/post_mortem_debug.py
gampel/neutron
51a6260266dc59c066072ca890ad9c40b1aad6cf
[ "Apache-2.0" ]
1,080
2015-01-04T08:35:00.000Z
2022-03-27T09:15:52.000Z
neutron/tests/post_mortem_debug.py
gampel/neutron
51a6260266dc59c066072ca890ad9c40b1aad6cf
[ "Apache-2.0" ]
24
2015-02-21T01:48:28.000Z
2021-11-26T02:38:56.000Z
neutron/tests/post_mortem_debug.py
gampel/neutron
51a6260266dc59c066072ca890ad9c40b1aad6cf
[ "Apache-2.0" ]
1,241
2015-01-02T10:47:10.000Z
2022-03-27T09:42:23.000Z
# Copyright 2013 Red Hat, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. 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 functools import traceback def _exception_handler(debugger, exc_info): """Exception handler enabling post-mortem debugging. A class extending testtools.TestCase can add this handler in setUp(): self.addOnException(post_mortem_debug.exception_handler) When an exception occurs, the user will be dropped into a debugger session in the execution environment of the failure. Frames associated with the testing framework are excluded so that the post-mortem session for an assertion failure will start at the assertion call (e.g. self.assertTrue) rather than the framework code that raises the failure exception (e.g. the assertTrue method). """ tb = exc_info[2] ignored_traceback = get_ignored_traceback(tb) if ignored_traceback: tb = FilteredTraceback(tb, ignored_traceback) traceback.print_exception(exc_info[0], exc_info[1], tb) debugger.post_mortem(tb) def get_ignored_traceback(tb): """Retrieve the first traceback of an ignored trailing chain. Given an initial traceback, find the first traceback of a trailing chain of tracebacks that should be ignored. The criteria for whether a traceback should be ignored is whether its frame's globals include the __unittest marker variable. This criteria is culled from: unittest.TestResult._is_relevant_tb_level For example: tb.tb_next => tb0.tb_next => tb1.tb_next - If no tracebacks were to be ignored, None would be returned. - If only tb1 was to be ignored, tb1 would be returned. - If tb0 and tb1 were to be ignored, tb0 would be returned. - If either of only tb or only tb0 was to be ignored, None would be returned because neither tb or tb0 would be part of a trailing chain of ignored tracebacks. """ # Turn the traceback chain into a list tb_list = [] while tb: tb_list.append(tb) tb = tb.tb_next # Find all members of an ignored trailing chain ignored_tracebacks = [] for tb in reversed(tb_list): if '__unittest' in tb.tb_frame.f_globals: ignored_tracebacks.append(tb) else: break # Return the first member of the ignored trailing chain if ignored_tracebacks: return ignored_tracebacks[-1] class FilteredTraceback(object): """Wraps a traceback to filter unwanted frames.""" def __init__(self, tb, filtered_traceback): """Constructor. :param tb: The start of the traceback chain to filter. :param filtered_traceback: The first traceback of a trailing chain that is to be filtered. """ self._tb = tb self.tb_lasti = self._tb.tb_lasti self.tb_lineno = self._tb.tb_lineno self.tb_frame = self._tb.tb_frame self._filtered_traceback = filtered_traceback @property
34.447154
77
0.700024
# Copyright 2013 Red Hat, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. 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 functools import traceback def get_exception_handler(debugger_name): debugger = _get_debugger(debugger_name) return functools.partial(_exception_handler, debugger) def _get_debugger(debugger_name): try: debugger = __import__(debugger_name) except ImportError: raise ValueError("can't import %s module as a post mortem debugger" % debugger_name) if 'post_mortem' in dir(debugger): return debugger else: raise ValueError("%s is not a supported post mortem debugger" % debugger_name) def _exception_handler(debugger, exc_info): """Exception handler enabling post-mortem debugging. A class extending testtools.TestCase can add this handler in setUp(): self.addOnException(post_mortem_debug.exception_handler) When an exception occurs, the user will be dropped into a debugger session in the execution environment of the failure. Frames associated with the testing framework are excluded so that the post-mortem session for an assertion failure will start at the assertion call (e.g. self.assertTrue) rather than the framework code that raises the failure exception (e.g. the assertTrue method). """ tb = exc_info[2] ignored_traceback = get_ignored_traceback(tb) if ignored_traceback: tb = FilteredTraceback(tb, ignored_traceback) traceback.print_exception(exc_info[0], exc_info[1], tb) debugger.post_mortem(tb) def get_ignored_traceback(tb): """Retrieve the first traceback of an ignored trailing chain. Given an initial traceback, find the first traceback of a trailing chain of tracebacks that should be ignored. The criteria for whether a traceback should be ignored is whether its frame's globals include the __unittest marker variable. This criteria is culled from: unittest.TestResult._is_relevant_tb_level For example: tb.tb_next => tb0.tb_next => tb1.tb_next - If no tracebacks were to be ignored, None would be returned. - If only tb1 was to be ignored, tb1 would be returned. - If tb0 and tb1 were to be ignored, tb0 would be returned. - If either of only tb or only tb0 was to be ignored, None would be returned because neither tb or tb0 would be part of a trailing chain of ignored tracebacks. """ # Turn the traceback chain into a list tb_list = [] while tb: tb_list.append(tb) tb = tb.tb_next # Find all members of an ignored trailing chain ignored_tracebacks = [] for tb in reversed(tb_list): if '__unittest' in tb.tb_frame.f_globals: ignored_tracebacks.append(tb) else: break # Return the first member of the ignored trailing chain if ignored_tracebacks: return ignored_tracebacks[-1] class FilteredTraceback(object): """Wraps a traceback to filter unwanted frames.""" def __init__(self, tb, filtered_traceback): """Constructor. :param tb: The start of the traceback chain to filter. :param filtered_traceback: The first traceback of a trailing chain that is to be filtered. """ self._tb = tb self.tb_lasti = self._tb.tb_lasti self.tb_lineno = self._tb.tb_lineno self.tb_frame = self._tb.tb_frame self._filtered_traceback = filtered_traceback @property def tb_next(self): tb_next = self._tb.tb_next if tb_next and tb_next != self._filtered_traceback: return FilteredTraceback(tb_next, self._filtered_traceback)
680
0
72
b4ba41b6af9e6568e2480af0e806191cf77a6ce4
8,931
py
Python
Gan/model_train.py
caiyueliang/CarClassification
a8d8051085c4e66ed3ed67e56360a515c9762cd5
[ "Apache-2.0" ]
null
null
null
Gan/model_train.py
caiyueliang/CarClassification
a8d8051085c4e66ed3ed67e56360a515c9762cd5
[ "Apache-2.0" ]
null
null
null
Gan/model_train.py
caiyueliang/CarClassification
a8d8051085c4e66ed3ed67e56360a515c9762cd5
[ "Apache-2.0" ]
null
null
null
# encoding:utf-8 import os import torch import torch.nn.functional as F import torch.optim as optim import torchvision from torchvision import transforms as T from torchvision.datasets import ImageFolder from torch.autograd import Variable from torch.utils.data import DataLoader from models.discriminator import Discriminator from models.generator import Generator import time import visdom
39.517699
118
0.543836
# encoding:utf-8 import os import torch import torch.nn.functional as F import torch.optim as optim import torchvision from torchvision import transforms as T from torchvision.datasets import ImageFolder from torch.autograd import Variable from torch.utils.data import DataLoader from models.discriminator import Discriminator from models.generator import Generator import time import visdom class ModuleTrain: def __init__(self, opt, best_loss=0.2): self.opt = opt self.best_loss = best_loss # 正确率这个值,才会保存模型 self.netd = Discriminator(self.opt) self.netg = Generator(self.opt) self.use_gpu = False # 加载模型 if os.path.exists(self.opt.netd_path): self.load_netd(self.opt.netd_path) else: print('[Load model] error: %s not exist !!!' % self.opt.netd_path) if os.path.exists(self.opt.netg_path): self.load_netg(self.opt.netg_path) else: print('[Load model] error: %s not exist !!!' % self.opt.netg_path) # DataLoader初始化 self.transform_train = T.Compose([ T.Resize((self.opt.img_size, self.opt.img_size)), T.ToTensor(), T.Normalize(mean=[.5, .5, .5], std=[.5, .5, .5]), ]) train_dataset = ImageFolder(root=self.opt.data_path, transform=self.transform_train) self.train_loader = DataLoader(dataset=train_dataset, batch_size=self.opt.batch_size, shuffle=True, num_workers=self.opt.num_workers, drop_last=True) # 优化器和损失函数 # self.optimizer = optim.SGD(self.model.parameters(), lr=self.lr, momentum=0.5) self.optimizer_g = optim.Adam(self.netg.parameters(), lr=self.opt.lr1, betas=(self.opt.beta1, 0.999)) self.optimizer_d = optim.Adam(self.netd.parameters(), lr=self.opt.lr2, betas=(self.opt.beta1, 0.999)) self.criterion = torch.nn.BCELoss() self.true_labels = Variable(torch.ones(self.opt.batch_size)) self.fake_labels = Variable(torch.zeros(self.opt.batch_size)) self.fix_noises = Variable(torch.randn(self.opt.batch_size, self.opt.nz, 1, 1)) self.noises = Variable(torch.randn(self.opt.batch_size, self.opt.nz, 1, 1)) # gpu or cpu if self.opt.use_gpu and torch.cuda.is_available(): self.use_gpu = True else: self.use_gpu = False if self.use_gpu: print('[use gpu] ...') self.netd.cuda() self.netg.cuda() self.criterion.cuda() self.true_labels = self.true_labels.cuda() self.fake_labels = self.fake_labels.cuda() self.fix_noises = self.fix_noises.cuda() self.noises = self.noises.cuda() else: print('[use cpu] ...') pass def train(self, save_best=True): print('[train] epoch: %d' % self.opt.max_epoch) for epoch_i in range(self.opt.max_epoch): loss_netd = 0.0 loss_netg = 0.0 correct = 0 print('================================================') for ii, (img, target) in enumerate(self.train_loader): # 训练 real_img = Variable(img) if self.opt.use_gpu: real_img = real_img.cuda() # 训练判别器 if (ii + 1) % self.opt.d_every == 0: self.optimizer_d.zero_grad() # 尽可能把真图片判别为1 output = self.netd(real_img) error_d_real = self.criterion(output, self.true_labels) error_d_real.backward() # 尽可能把假图片判别为0 self.noises.data.copy_(torch.randn(self.opt.batch_size, self.opt.nz, 1, 1)) fake_img = self.netg(self.noises).detach() # 根据噪声生成假图 fake_output = self.netd(fake_img) error_d_fake = self.criterion(fake_output, self.fake_labels) error_d_fake.backward() self.optimizer_d.step() loss_netd += (error_d_real.item() + error_d_fake.item()) # 训练生成器 if (ii + 1) % self.opt.g_every == 0: self.optimizer_g.zero_grad() self.noises.data.copy_(torch.randn(self.opt.batch_size, self.opt.nz, 1, 1)) fake_img = self.netg(self.noises) fake_output = self.netd(fake_img) # 尽可能让判别器把假图片也判别为1 error_g = self.criterion(fake_output, self.true_labels) error_g.backward() self.optimizer_g.step() loss_netg += error_g loss_netd /= (len(self.train_loader) * 2) loss_netg /= len(self.train_loader) print('[Train] Epoch: {} \tNetD Loss: {:.6f} \tNetG Loss: {:.6f}'.format(epoch_i, loss_netd, loss_netg)) if save_best is True: if (loss_netg + loss_netd) / 2 < self.best_loss: self.best_loss = (loss_netg + loss_netd) / 2 self.save(self.netd, self.opt.best_netd_path) # 保存最好的模型 self.save(self.netg, self.opt.best_netg_path) # 保存最好的模型 print('[save best] ...') # self.vis() if (epoch_i + 1) % 5 == 0: self.image_gan() self.save(self.netd, self.opt.netd_path) # 保存最好的模型 self.save(self.netg, self.opt.netg_path) # 保存最好的模型 def vis(self): fix_fake_imgs = self.netg(self.opt.fix_noises) visdom.images(fix_fake_imgs.data.cpu().numpy()[:64] * 0.5 + 0.5, win='fixfake') def image_gan(self): noises = torch.randn(self.opt.gen_search_num, self.opt.nz, 1, 1).normal_(self.opt.gen_mean, self.opt.gen_std) with torch.no_grad(): noises = Variable(noises) if self.use_gpu: noises = noises.cuda() fake_img = self.netg(noises) scores = self.netd(fake_img).data indexs = scores.topk(self.opt.gen_num)[1] result = list() for ii in indexs: result.append(fake_img.data[ii]) torchvision.utils.save_image(torch.stack(result), self.opt.gen_img, normalize=True, range=(-1, 1)) # # print(correct) # # print(len(self.train_loader.dataset)) # train_loss /= len(self.train_loader) # acc = float(correct) / float(len(self.train_loader.dataset)) # print('[Train] Epoch: {} \tLoss: {:.6f}\tAcc: {:.6f}\tlr: {}'.format(epoch_i, train_loss, acc, self.lr)) # # test_acc = self.test() # if save_best is True: # if test_acc > self.best_acc: # self.best_acc = test_acc # str_list = self.model_file.split('.') # best_model_file = "" # for str_index in range(len(str_list)): # best_model_file = best_model_file + str_list[str_index] # if str_index == (len(str_list) - 2): # best_model_file += '_best' # if str_index != (len(str_list) - 1): # best_model_file += '.' # self.save(best_model_file) # 保存最好的模型 # # self.save(self.model_file) def test(self): test_loss = 0.0 correct = 0 time_start = time.time() # 测试集 for data, target in self.test_loader: data, target = Variable(data), Variable(target) if self.use_gpu: data = data.cuda() target = target.cuda() output = self.model(data) # sum up batch loss if self.use_gpu: loss = self.loss(output, target) else: loss = self.loss(output, target) test_loss += loss.item() predict = torch.argmax(output, 1) correct += (predict == target).sum().data time_end = time.time() time_avg = float(time_end - time_start) / float(len(self.test_loader.dataset)) test_loss /= len(self.test_loader) acc = float(correct) / float(len(self.test_loader.dataset)) print('[Test] set: Test loss: {:.6f}\t Acc: {:.6f}\t time: {:.6f} \n'.format(test_loss, acc, time_avg)) return acc def load_netd(self, name): print('[Load model netd] %s ...' % name) self.netd.load_state_dict(torch.load(name)) def load_netg(self, name): print('[Load model netg] %s ...' % name) self.netg.load_state_dict(torch.load(name)) def save(self, model, name): print('[Save model] %s ...' % name) torch.save(model.state_dict(), name) # self.model.save(name)
8,544
-3
238
d57c78c5712e626d8da772be2f1481071b3a0059
1,572
py
Python
Demo-PyQt5/LoginPage.py
siddarth-patil/Demo-PyQt5
dafebb4ce7f58cf0d2d22452f829d633b4256649
[ "Apache-2.0" ]
null
null
null
Demo-PyQt5/LoginPage.py
siddarth-patil/Demo-PyQt5
dafebb4ce7f58cf0d2d22452f829d633b4256649
[ "Apache-2.0" ]
null
null
null
Demo-PyQt5/LoginPage.py
siddarth-patil/Demo-PyQt5
dafebb4ce7f58cf0d2d22452f829d633b4256649
[ "Apache-2.0" ]
null
null
null
import sys from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QLabel, QLineEdit, QGridLayout, QMessageBox) if __name__ == '__main__': app = QApplication(sys.argv) form = LoginForm() form.show() sys.exit(app.exec_())
30.823529
109
0.638041
import sys from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QLabel, QLineEdit, QGridLayout, QMessageBox) class LoginForm(QWidget): def __init__(self): super().__init__() self.setWindowTitle('LoginForm') self.resize(800, 600) layout = QGridLayout() label_name = QLabel('<font size="4"> Username: </font>') self.lineEdit_username = QLineEdit() self.lineEdit_username.setPlaceholderText('Please enter your username') layout.addWidget(label_name, 0, 0) layout.addWidget(self.lineEdit_username, 0, 1) label_password = QLabel('<font size="4"> Password: </font>') self.lineEdit_password = QLineEdit() self.lineEdit_password.setPlaceholderText('Please enter your password') layout.addWidget(label_password, 1, 0) layout.addWidget(self.lineEdit_password, 1, 1) button_login = QPushButton('Login') button_login.clicked.connect(self.check_password) layout.addWidget(button_login, 2, 0, 1, 2) layout.setRowMinimumHeight(2, 75) self.setLayout(layout) def check_password(self): msg = QMessageBox() if self.lineEdit_username.text() == 'siddarth' and self.lineEdit_password.text() == '000': msg.setText('Success') msg.exec_() app.quit() else: msg.setText('Incorrect Password') msg.exec_() if __name__ == '__main__': app = QApplication(sys.argv) form = LoginForm() form.show() sys.exit(app.exec_())
1,241
4
76
f9692728e6609a0c475bcb9dbdfe6023b5335b83
1,077
py
Python
src/tests/tests_util.py
KernelA/nsga3
fc8c862fb41657108d5499f4343beb408e526c19
[ "MIT" ]
7
2020-06-12T21:52:18.000Z
2022-03-24T14:28:01.000Z
src/tests/tests_util.py
KernelA/nsga3
fc8c862fb41657108d5499f4343beb408e526c19
[ "MIT" ]
null
null
null
src/tests/tests_util.py
KernelA/nsga3
fc8c862fb41657108d5499f4343beb408e526c19
[ "MIT" ]
3
2018-01-01T09:46:18.000Z
2021-06-16T07:09:26.000Z
import unittest import random import math from pynsga3 import utils if __name__ == '__main__': unittest.main()
24.477273
84
0.553389
import unittest import random import math from pynsga3 import utils def _binomial(n, k): if k > n: return 0 prod = 1 for i in range(k + 1, n + 1): prod *= i return prod // math.factorial(n - k) class TestStools(unittest.TestCase): def test_random_clip(self): value = 0.5 low_b = -1 upp_b = 1 self.assertEqual(value, utils.tools.clip_random(value, low_b, upp_b)) def test_gen_convex_hull(self): dim = tuple(range(1,6)) count = tuple(range(2, 6)) for d in dim: for c in count: coefficients = utils.tools.convhull.generate_coeff_convex_hull(d, c) self.assertEqual(_binomial(d + c - 2, c - 1), len(coefficients)) for vec in coefficients: self.assertAlmostEqual(1.0, sum(vec), places=10) for coeff in vec: self.assertGreaterEqual(coeff, 0) self.assertLessEqual(coeff, 1) if __name__ == '__main__': unittest.main()
833
15
100
e9c4fb58a56f125b55d2485c0870f6d4d812e1ba
331
py
Python
IQDMPDF/_version.py
IQDM/IQDM-PDF
8f4f04bfa93a76bca8d54706db24f2ab5c516f3e
[ "MIT" ]
5
2020-11-23T18:53:01.000Z
2022-03-29T11:09:25.000Z
IQDMPDF/_version.py
IQDM/IQDM-PDF
8f4f04bfa93a76bca8d54706db24f2ab5c516f3e
[ "MIT" ]
22
2020-11-23T18:47:57.000Z
2021-03-15T02:51:32.000Z
IQDMPDF/_version.py
IQDM/IQDM-PDF
8f4f04bfa93a76bca8d54706db24f2ab5c516f3e
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- # _version.py """Package initialization for IQDM-PDF.""" # Copyright (c) 2021 Dan Cutright # This file is part of IQDM-PDF, released under a MIT license. # See the file LICENSE included with this distribution __author__ = "Dan Cutright" __version__ = "0.3.0" __release__ = "0.3.0"
27.583333
62
0.700906
#!/usr/bin/env python # -*- coding: utf-8 -*- # _version.py """Package initialization for IQDM-PDF.""" # Copyright (c) 2021 Dan Cutright # This file is part of IQDM-PDF, released under a MIT license. # See the file LICENSE included with this distribution __author__ = "Dan Cutright" __version__ = "0.3.0" __release__ = "0.3.0"
0
0
0
e248c9ff1113bd0055fa732947d0d07c8f4c8fbe
1,297
py
Python
test_grad/test2_01_FullyConnectedLayer_grad.py
miemie2013/ppgan
48008d85ec6c5fa2e1469acf8507b2614fa550cc
[ "Apache-2.0" ]
null
null
null
test_grad/test2_01_FullyConnectedLayer_grad.py
miemie2013/ppgan
48008d85ec6c5fa2e1469acf8507b2614fa550cc
[ "Apache-2.0" ]
null
null
null
test_grad/test2_01_FullyConnectedLayer_grad.py
miemie2013/ppgan
48008d85ec6c5fa2e1469acf8507b2614fa550cc
[ "Apache-2.0" ]
1
2022-01-19T03:01:13.000Z
2022-01-19T03:01:13.000Z
import torch import numpy as np from training.networks import FullyConnectedLayer batch_size = 2 in_channels = 512 w_dim = 512 lr = 0.1 # activation = 'linear' # activation = 'lrelu' # activation = 'relu' # activation = 'tanh' activation = 'sigmoid' # activation = 'elu' # activation = 'selu' # activation = 'softplus' # activation = 'swish' model = FullyConnectedLayer(w_dim, in_channels, activation=activation, bias_init=1) model.train() optimizer = torch.optim.SGD(model.parameters(), lr=lr, momentum=0.9) torch.save(model.state_dict(), "pytorch_fullyConnectedLayer.pth") dic = {} for batch_idx in range(20): optimizer.zero_grad(set_to_none=True) ws = torch.randn([batch_size, 512]) ws.requires_grad_(True) styles = model(ws) styles2 = torch.sigmoid(styles) dstyles2_dws = torch.autograd.grad(outputs=[styles2.sum()], inputs=[ws], create_graph=True, only_inputs=True)[0] dic['batch_%.3d.dstyles2_dws'%batch_idx] = dstyles2_dws.cpu().detach().numpy() dic['batch_%.3d.output'%batch_idx] = styles.cpu().detach().numpy() dic['batch_%.3d.input'%batch_idx] = ws.cpu().detach().numpy() loss = dstyles2_dws.sum() + styles2.sum() # loss = styles2.sum() loss.backward() optimizer.step() np.savez('01_fullyConnectedLayer_grad', **dic) print()
27.020833
116
0.701619
import torch import numpy as np from training.networks import FullyConnectedLayer batch_size = 2 in_channels = 512 w_dim = 512 lr = 0.1 # activation = 'linear' # activation = 'lrelu' # activation = 'relu' # activation = 'tanh' activation = 'sigmoid' # activation = 'elu' # activation = 'selu' # activation = 'softplus' # activation = 'swish' model = FullyConnectedLayer(w_dim, in_channels, activation=activation, bias_init=1) model.train() optimizer = torch.optim.SGD(model.parameters(), lr=lr, momentum=0.9) torch.save(model.state_dict(), "pytorch_fullyConnectedLayer.pth") dic = {} for batch_idx in range(20): optimizer.zero_grad(set_to_none=True) ws = torch.randn([batch_size, 512]) ws.requires_grad_(True) styles = model(ws) styles2 = torch.sigmoid(styles) dstyles2_dws = torch.autograd.grad(outputs=[styles2.sum()], inputs=[ws], create_graph=True, only_inputs=True)[0] dic['batch_%.3d.dstyles2_dws'%batch_idx] = dstyles2_dws.cpu().detach().numpy() dic['batch_%.3d.output'%batch_idx] = styles.cpu().detach().numpy() dic['batch_%.3d.input'%batch_idx] = ws.cpu().detach().numpy() loss = dstyles2_dws.sum() + styles2.sum() # loss = styles2.sum() loss.backward() optimizer.step() np.savez('01_fullyConnectedLayer_grad', **dic) print()
0
0
0
52b29f44b7e7da2fd2487ff5347c8cb6b6b83c43
1,668
py
Python
ui/home.py
Slavkata/Edge-Computing-Interpretation
aeb8d19c7a2337b92973dd4097c30d07606a3f4f
[ "MIT" ]
1
2019-04-11T12:48:43.000Z
2019-04-11T12:48:43.000Z
ui/home.py
Slavkata/Edge-Computing-Interpretation
aeb8d19c7a2337b92973dd4097c30d07606a3f4f
[ "MIT" ]
null
null
null
ui/home.py
Slavkata/Edge-Computing-Interpretation
aeb8d19c7a2337b92973dd4097c30d07606a3f4f
[ "MIT" ]
null
null
null
from appJar import gui import paho.mqtt.client as mqtt import sys # sys.path.insert(0, '/home/nikolatz/Edge-Computing-Interpretation/mainNode') # from main_node import runMain app = gui() app.setBg("DarkKhaki") app.startPagedWindow("Welcome to projecto") app.startPage() app.addLabel("w1", "You have to choose two files") app.stopPage() app.startPage() app.addLabel("l1", "upload a file") app.setLabelBg("l1", "green") app.setLabelSticky("l1", "both") app.addFileEntry("f1") app.setEntrySticky("f1", "both") app.stopPage() app.startPage() app.addLabel("l2", "upload a script") app.setLabelBg("l2", "green") app.setLabelSticky("l2", "both") app.addFileEntry("f2") app.setEntrySticky("f2", "both") app.stopPage() app.startPage() app.addButton("Send the work", press) app.setButtonAlign("Send the work", "center") app.setButtonSticky("Send the work", "both") app.stopPage() app.stopPagedWindow() client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("192.168.0.109", 1883, 60) client.loop_start() # start the GUI app.go()
25.661538
77
0.688249
from appJar import gui import paho.mqtt.client as mqtt import sys # sys.path.insert(0, '/home/nikolatz/Edge-Computing-Interpretation/mainNode') # from main_node import runMain def press(button) : if button=="Send the work": # result = 1 runMain(app.getEntry("f1"), app.getEntry("f2")) client.publish("DataFile", app.getEntry("f1")) client.publish("ScriptFile", app.getEntry("f2")) client.publish("StartWork") def on_connect(client, userdata, flags, rc): client.subscribe("Result") def on_message(client, userdata, msg): if msg.topic == "Result": file = open("result.txt", "w") file.write(msg.payload.decode("utf-8")) file.close() app.openPage("Welcome to projecto", 1) app.stopPage() app = gui() app.setBg("DarkKhaki") app.startPagedWindow("Welcome to projecto") app.startPage() app.addLabel("w1", "You have to choose two files") app.stopPage() app.startPage() app.addLabel("l1", "upload a file") app.setLabelBg("l1", "green") app.setLabelSticky("l1", "both") app.addFileEntry("f1") app.setEntrySticky("f1", "both") app.stopPage() app.startPage() app.addLabel("l2", "upload a script") app.setLabelBg("l2", "green") app.setLabelSticky("l2", "both") app.addFileEntry("f2") app.setEntrySticky("f2", "both") app.stopPage() app.startPage() app.addButton("Send the work", press) app.setButtonAlign("Send the work", "center") app.setButtonSticky("Send the work", "both") app.stopPage() app.stopPagedWindow() client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("192.168.0.109", 1883, 60) client.loop_start() # start the GUI app.go()
526
0
68
e55669a6e325a0accc5ed6899f58c0c901c3f7f1
439
py
Python
open/core/migrations/0017_supplement_is_taken_with_food.py
lawrendran/open
d136f694bafab647722c78be6f39ec79d589f774
[ "MIT" ]
105
2019-06-01T08:34:47.000Z
2022-03-15T11:48:36.000Z
open/core/migrations/0017_supplement_is_taken_with_food.py
lawrendran/open
d136f694bafab647722c78be6f39ec79d589f774
[ "MIT" ]
111
2019-06-04T15:34:14.000Z
2022-03-12T21:03:20.000Z
open/core/migrations/0017_supplement_is_taken_with_food.py
lawrendran/open
d136f694bafab647722c78be6f39ec79d589f774
[ "MIT" ]
26
2019-09-04T06:06:12.000Z
2022-01-03T03:40:11.000Z
# Generated by Django 2.2.13 on 2020-08-02 01:23 from django.db import migrations, models
23.105263
75
0.633257
# Generated by Django 2.2.13 on 2020-08-02 01:23 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("core", "0016_null_duration_minutes_activity_log"), ] operations = [ migrations.AddField( model_name="supplement", name="is_taken_with_food", field=models.BooleanField(blank=True, default=None, null=True), ), ]
0
324
23
ae39fac9b810ad342923a39a7caff32041209efb
1,004
py
Python
classifier.py
riccardocadei/GraphML-Contest-2019-Oracle-PoliMI
d7d4ce1d91298e7e7f71138bc82836687c80c5b4
[ "MIT" ]
1
2019-04-06T00:27:55.000Z
2019-04-06T00:27:55.000Z
classifier.py
RiccardoCadei/oracle-ml-contest
d7d4ce1d91298e7e7f71138bc82836687c80c5b4
[ "MIT" ]
null
null
null
classifier.py
RiccardoCadei/oracle-ml-contest
d7d4ce1d91298e7e7f71138bc82836687c80c5b4
[ "MIT" ]
2
2021-04-30T06:08:06.000Z
2022-01-13T07:29:22.000Z
import utils import numpy as np from sklearn.multiclass import OneVsRestClassifier from sklearn.model_selection import KFold, cross_val_score from sklearn.linear_model import SGDClassifier,LogisticRegression # CROSS-VALIDATION ACCURACY # TRAINING ACCURACY AND PREDICTION
33.466667
99
0.747012
import utils import numpy as np from sklearn.multiclass import OneVsRestClassifier from sklearn.model_selection import KFold, cross_val_score from sklearn.linear_model import SGDClassifier,LogisticRegression # CROSS-VALIDATION ACCURACY def validation_accuracy(X, labels): kfolds = KFold(n_splits=10) sgd = SGDClassifier(loss="log",penalty='l1', max_iter=300, tol=1e-3,class_weight="balanced") model = OneVsRestClassifier(sgd, n_jobs=1) scores = cross_val_score(model, X, labels, cv=kfolds, n_jobs=32, verbose=2, scoring="f1_micro") print(f"Mean crossvalidation Micro-F1: {np.mean(scores):.3f}") # TRAINING ACCURACY AND PREDICTION def fit_model(X, labels): sgd = SGDClassifier(loss="log", max_iter=300,tol=1e-3,class_weight="balanced") model = OneVsRestClassifier(sgd, n_jobs=1) model.fit(X, labels) train_pred = model.predict_proba(X) train_pred = train_pred > 0.4 #train_pred = model.predict(X) utils.get_score(train_pred, labels) return model
682
0
46
3bcb8659237db7aeeaf1370f6822ee2753e63421
19
py
Python
Local/__init__.py
FurmanCenter/ACSDownloader
918afc0c7baa8814da98c2e3ee11352af68c027e
[ "Apache-2.0" ]
1
2020-04-15T15:40:18.000Z
2020-04-15T15:40:18.000Z
Local/__init__.py
FurmanCenter/ACSDownloader
918afc0c7baa8814da98c2e3ee11352af68c027e
[ "Apache-2.0" ]
null
null
null
Local/__init__.py
FurmanCenter/ACSDownloader
918afc0c7baa8814da98c2e3ee11352af68c027e
[ "Apache-2.0" ]
null
null
null
from Local import *
19
19
0.789474
from Local import *
0
0
0
4b2bce22af7f8c8d0e4fd9fbfb24415f1ed6d8d0
3,304
py
Python
qtui.py
Daan4/vision-well-position-controller
3926b7a684aee80d159046d7683257f8c23229e8
[ "MIT" ]
null
null
null
qtui.py
Daan4/vision-well-position-controller
3926b7a684aee80d159046d7683257f8c23229e8
[ "MIT" ]
2
2021-09-08T00:43:55.000Z
2022-03-11T23:38:43.000Z
qtui.py
Daan4/vision-well-position-controller
3926b7a684aee80d159046d7683257f8c23229e8
[ "MIT" ]
null
null
null
from PyQt5.QtWidgets import QWidget, QLabel, QGridLayout from PyQt5.QtCore import Qt, pyqtSlot import numpy as np from PyQt5.QtGui import QPixmap, QImage import os
35.526882
83
0.66586
from PyQt5.QtWidgets import QWidget, QLabel, QGridLayout from PyQt5.QtCore import Qt, pyqtSlot import numpy as np from PyQt5.QtGui import QPixmap, QImage import os class MainWindow(QWidget): def __init__(self): super().__init__() self.setWindowTitle(os.path.basename(__file__)) self.move(100, 100) # Labels / Image containers self.label_img_blur = QLabel() self.label_img_blur.setText("Blur") self.img_blur = QLabel() self.label_img_gamma = QLabel() self.label_img_gamma.setText("Gamma") self.img_gamma = QLabel() self.label_img_threshold = QLabel() self.label_img_threshold.setText("Threshold") self.img_threshold = QLabel() self.label_img_scores = QLabel() self.label_img_scores.setText("Scores") self.img_scores = QLabel() self.label_img_result = QLabel() self.label_img_result.setText("Result") self.img_result = QLabel() # Grid layout widget_layout = QGridLayout() widget_layout.addWidget(self.label_img_blur, 0, 0, Qt.AlignLeft) widget_layout.addWidget(self.img_blur, 1, 0, Qt.AlignLeft) widget_layout.addWidget(self.label_img_gamma, 0, 1, Qt.AlignLeft) widget_layout.addWidget(self.img_gamma, 1, 1, Qt.AlignLeft) widget_layout.addWidget(self.label_img_threshold, 0, 2, Qt.AlignLeft) widget_layout.addWidget(self.img_threshold, 1, 2, Qt.AlignLeft) widget_layout.addWidget(self.label_img_scores, 0, 3, Qt.AlignLeft) widget_layout.addWidget(self.img_scores, 1, 3, Qt.AlignLeft) widget_layout.addWidget(self.label_img_result, 0, 4, Qt.AlignLeft) widget_layout.addWidget(self.img_result, 1, 4, Qt.AlignLeft) self.setLayout(widget_layout) @pyqtSlot(np.ndarray) def update_blur(self, image=None): image = image.copy() height, width = image.shape qImage = QImage(image.data, width, height, width, QImage.Format_Indexed8) self.img_blur.setPixmap(QPixmap(qImage)) self.img_blur.show() @pyqtSlot(np.ndarray) def update_gamma(self, image=None): image = image.copy() height, width = image.shape qImage = QImage(image.data, width, height, width, QImage.Format_Indexed8) self.img_gamma.setPixmap(QPixmap(qImage)) self.img_gamma.show() @pyqtSlot(np.ndarray) def update_threshold(self, image=None): image = image.copy() height, width = image.shape qImage = QImage(image.data, width, height, width, QImage.Format_Indexed8) self.img_threshold.setPixmap(QPixmap(qImage)) self.img_threshold.show() @pyqtSlot(np.ndarray) def update_scores(self, image=None): image = image.copy() height, width = image.shape[:2] qImage = QImage(image.data, width, height, width * 3, QImage.Format_RGB888) self.img_scores.setPixmap(QPixmap(qImage)) self.img_scores.show() @pyqtSlot(np.ndarray) def update_result(self, image=None): image = image.copy() height, width = image.shape qImage = QImage(image.data, width, height, width, QImage.Format_Indexed8) self.img_result.setPixmap(QPixmap(qImage)) self.img_result.show()
2,819
296
23
a18d3b5237f1f6ef7fa2d45a57a8c89674ebd272
525
py
Python
Bit_Manipulation/83.Single Number II/Solution.py
Zhenye-Na/LxxxCode
afd79d790d0a7495d75e6650f80adaa99bd0ff07
[ "MIT" ]
12
2019-05-04T04:21:27.000Z
2022-03-02T07:06:57.000Z
Bit_Manipulation/83.Single Number II/Solution.py
Zhenye-Na/LxxxCode
afd79d790d0a7495d75e6650f80adaa99bd0ff07
[ "MIT" ]
1
2019-07-24T18:43:53.000Z
2019-07-24T18:43:53.000Z
Bit_Manipulation/83.Single Number II/Solution.py
Zhenye-Na/LxxxCode
afd79d790d0a7495d75e6650f80adaa99bd0ff07
[ "MIT" ]
10
2019-07-01T04:03:04.000Z
2022-03-09T03:57:37.000Z
class Solution: """ @param A: An integer array @return: An integer """
22.826087
38
0.386667
class Solution: """ @param A: An integer array @return: An integer """ def singleNumberII(self, A): # write your code here if not A or len(A) % 3 != 1: return -1 bits = [0 for _ in range(32)] for a in A: for j in range(32): if ((1 << j) & a) > 0: bits[j] += 1 ans = 0 for i in range(32): t = bits[i] % 3 if t == 1: ans = ans + (1 << i) return ans
413
0
26
e1d1bd72a4aeaa39f3e1afbd64fac6a335a37791
4,108
py
Python
NVIDIAFastPhotoStyle/photo_smooth.py
sleebapaul/AuriaKathi
d1705fc7e0919fd0a9e9f87a2593a9f7319886cf
[ "MIT" ]
9
2019-12-31T15:53:33.000Z
2021-05-06T06:36:22.000Z
NVIDIAFastPhotoStyle/photo_smooth.py
sleebapaul/AuriaKathi
d1705fc7e0919fd0a9e9f87a2593a9f7319886cf
[ "MIT" ]
null
null
null
NVIDIAFastPhotoStyle/photo_smooth.py
sleebapaul/AuriaKathi
d1705fc7e0919fd0a9e9f87a2593a9f7319886cf
[ "MIT" ]
2
2020-01-01T05:03:24.000Z
2020-01-03T13:07:26.000Z
""" Copyright (C) 2018 NVIDIA Corporation. All rights reserved. Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode). """ from __future__ import division import torch.nn as nn import scipy.misc import numpy as np import scipy.sparse import scipy.sparse.linalg from numpy.lib.stride_tricks import as_strided from PIL import Image # Returns sparse matting laplacian # The implementation of the function is heavily borrowed from # https://github.com/MarcoForte/closed-form-matting/blob/master/closed_form_matting.py # We thank Marco Forte for sharing his code.
41.494949
126
0.564752
""" Copyright (C) 2018 NVIDIA Corporation. All rights reserved. Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode). """ from __future__ import division import torch.nn as nn import scipy.misc import numpy as np import scipy.sparse import scipy.sparse.linalg from numpy.lib.stride_tricks import as_strided from PIL import Image class Propagator(nn.Module): def __init__(self, beta=0.9999): super(Propagator, self).__init__() self.beta = beta def process(self, initImg, contentImg): if type(contentImg) == str: content = scipy.misc.imread(contentImg, mode='RGB') else: content = contentImg.copy() # content = scipy.misc.imread(contentImg, mode='RGB') if type(initImg) == str: B = scipy.misc.imread(initImg, mode='RGB').astype(np.float64) / 255 else: B = scipy.asarray(initImg).astype(np.float64) / 255 # B = self. # B = scipy.misc.imread(initImg, mode='RGB').astype(np.float64)/255 h1,w1,k = B.shape h = h1 - 4 w = w1 - 4 B = B[int((h1-h)/2):int((h1-h)/2+h),int((w1-w)/2):int((w1-w)/2+w),:] content = scipy.misc.imresize(content,(h,w)) B = self.__replication_padding(B,2) content = self.__replication_padding(content,2) content = content.astype(np.float64)/255 B = np.reshape(B,(h1*w1,k)) W = self.__compute_laplacian(content) W = W.tocsc() dd = W.sum(0) dd = np.sqrt(np.power(dd,-1)) dd = dd.A.squeeze() D = scipy.sparse.csc_matrix((dd, (np.arange(0,w1*h1), np.arange(0,w1*h1)))) # 0.026 S = D.dot(W).dot(D) A = scipy.sparse.identity(w1*h1) - self.beta*S A = A.tocsc() solver = scipy.sparse.linalg.factorized(A) V = np.zeros((h1*w1,k)) V[:,0] = solver(B[:,0]) V[:,1] = solver(B[:,1]) V[:,2] = solver(B[:,2]) V = V*(1-self.beta) V = V.reshape(h1,w1,k) V = V[2:2+h,2:2+w,:] img = Image.fromarray(np.uint8(np.clip(V * 255., 0, 255.))) return img # Returns sparse matting laplacian # The implementation of the function is heavily borrowed from # https://github.com/MarcoForte/closed-form-matting/blob/master/closed_form_matting.py # We thank Marco Forte for sharing his code. def __compute_laplacian(self, img, eps=10**(-7), win_rad=1): win_size = (win_rad*2+1)**2 h, w, d = img.shape c_h, c_w = h - 2*win_rad, w - 2*win_rad win_diam = win_rad*2+1 indsM = np.arange(h*w).reshape((h, w)) ravelImg = img.reshape(h*w, d) win_inds = self.__rolling_block(indsM, block=(win_diam, win_diam)) win_inds = win_inds.reshape(c_h, c_w, win_size) winI = ravelImg[win_inds] win_mu = np.mean(winI, axis=2, keepdims=True) win_var = np.einsum('...ji,...jk ->...ik', winI, winI)/win_size - np.einsum('...ji,...jk ->...ik', win_mu, win_mu) inv = np.linalg.inv(win_var + (eps/win_size)*np.eye(3)) X = np.einsum('...ij,...jk->...ik', winI - win_mu, inv) vals = (1/win_size)*(1 + np.einsum('...ij,...kj->...ik', X, winI - win_mu)) nz_indsCol = np.tile(win_inds, win_size).ravel() nz_indsRow = np.repeat(win_inds, win_size).ravel() nz_indsVal = vals.ravel() L = scipy.sparse.coo_matrix((nz_indsVal, (nz_indsRow, nz_indsCol)), shape=(h*w, h*w)) return L def __replication_padding(self, arr,pad): h,w,c = arr.shape ans = np.zeros((h+pad*2,w+pad*2,c)) for i in range(c): ans[:,:,i] = np.pad(arr[:,:,i],pad_width=(pad,pad),mode='edge') return ans def __rolling_block(self, A, block=(3, 3)): shape = (A.shape[0] - block[0] + 1, A.shape[1] - block[1] + 1) + block strides = (A.strides[0], A.strides[1]) + A.strides return as_strided(A, shape=shape, strides=strides)
3,315
7
156
b237ed64150fda9b67619d608e0a1309dd379ff8
347
py
Python
tests/unit/testHelpers.py
jacksonal/mafia-slack
6426db25c584861395e5d056a013825ba02f836d
[ "MIT" ]
null
null
null
tests/unit/testHelpers.py
jacksonal/mafia-slack
6426db25c584861395e5d056a013825ba02f836d
[ "MIT" ]
4
2020-09-25T13:45:14.000Z
2020-11-18T01:58:14.000Z
tests/unit/testHelpers.py
jacksonal/mafia-slack
6426db25c584861395e5d056a013825ba02f836d
[ "MIT" ]
2
2020-10-19T16:52:13.000Z
2020-11-11T15:49:09.000Z
from models.player import Player, Roles, States as PlayerStates
20.411765
63
0.711816
from models.player import Player, Roles, States as PlayerStates def createVillager(id=None): player = Player(id) player.state = PlayerStates.ALIVE player.role = Roles.VILLAGER return player def createMafia(id=None): player = Player(id) player.state = PlayerStates.ALIVE player.role = Roles.MAFIA return player
234
0
46
1d58ad51679c5a42cb413e0300ea892304b4c1c0
7,912
py
Python
drforest/dimension_reduction/save.py
joshloyal/drforest
ab1e3f01cab36f15f1c37b82f71421cd025c901e
[ "MIT" ]
2
2021-09-22T12:15:43.000Z
2022-01-04T12:59:50.000Z
drforest/dimension_reduction/save.py
joshloyal/drforest
ab1e3f01cab36f15f1c37b82f71421cd025c901e
[ "MIT" ]
null
null
null
drforest/dimension_reduction/save.py
joshloyal/drforest
ab1e3f01cab36f15f1c37b82f71421cd025c901e
[ "MIT" ]
null
null
null
import warnings import numpy as np import scipy.linalg as linalg from scipy import sparse from sklearn.base import BaseEstimator, TransformerMixin from sklearn.preprocessing import normalize from sklearn.utils import check_array, check_X_y from sklearn.utils.validation import check_is_fitted from .slices import slice_y, is_multioutput __all__ = ['SlicedAverageVarianceEstimation'] class SlicedAverageVarianceEstimation(BaseEstimator, TransformerMixin): """Sliced Average Variance Estimation (SAVE) [1] Linear dimensionality reduction using the conditional covariance, Cov(X|y), to identify the directions defining the central subspace of the data. The algorithm performs a weighted principal component analysis on a transformation of slices of the covariance matrix of the whitened data, which has been sorted with respect to the target, y. Since SAVE looks at second moment information, it may miss first-moment information. In particular, it may miss linear trends. See :class:`sliced.sir.SlicedInverseRegression`, which is able to detect linear trends but may fail in other situations. If possible, both SIR and SAVE should be used when analyzing a dataset. Parameters ---------- n_directions : int, str or None (default='auto') Number of directions to keep. Corresponds to the dimension of the central subpace. If n_directions=='auto', the number of directions is chosen by finding the maximum gap in the ordered eigenvalues of the var(X|y) matrix and choosing the directions before this gap. If n_directions==None, the number of directions equals the number of features. n_slices : int (default=10) The number of slices used when calculating the inverse regression curve. Truncated to at most the number of unique values of ``y``. copy : bool (default=True) If False, data passed to fit are overwritten and running fit(X).transform(X) will not yield the expected results, use fit_transform(X) instead. Attributes ---------- directions_ : array, shape (n_directions, n_features) The directions in feature space, representing the central subspace which is sufficient to describe the conditional distribution y|X. The directions are sorted by ``eigenvalues_``. eigenvalues_ : array, shape (n_directions,) The eigenvalues corresponding to each of the selected directions. These are the eigenvalues of the covariance matrix of the inverse regression curve. Larger eigenvalues indicate more prevelant directions. Examples -------- >>> import numpy as np >>> from sliced import SlicedAverageVarianceEstimation >>> from sliced.datasets import make_quadratic >>> X, y = make_quadratic(random_state=123) >>> save = SlicedAverageVarianceEstimation(n_directions=2) >>> save.fit(X, y) SlicedAverageVarianceEstimation(copy=True, n_directions=2, n_slices=10) >>> X_save = save.transform(X) References ---------- [1] Shao, Y, Cook, RD and Weisberg, S (2007). "Marginal Tests with Sliced Average Variance Estimation", Biometrika, 94, 285-296. """ def fit(self, X, y): """Fit the model with X and y. Parameters ---------- X : array-like, shape (n_samples, n_features) Training data, where n_samples is the number of samples and n_features is the number of features. y : array-like, shape (n_samples,) The target values (class labels in classification, real numbers in regression). Returns ------- self : object Returns the instance itself. """ if sparse.issparse(X): raise TypeError("SlicedInverseRegression does not support " "sparse input.") X, y = check_X_y(X, y, dtype=[np.float64, np.float32], y_numeric=True, copy=self.copy) # handle n_directions == None if self.n_directions is None: n_directions = X.shape[1] elif (not isinstance(self.n_directions, str) and self.n_directions < 1): raise ValueError('The number of directions `n_directions` ' 'must be >= 1. Got `n_directions`={}'.format( self.n_directions)) else: n_directions = self.n_directions # validate y if is_multioutput(y): raise TypeError("The target `y` cannot be multi-output.") n_samples, n_features = X.shape # Center and Whiten feature matrix using a QR decomposition # (this is the approach used in the dr package) if self.copy: X = X - np.mean(X, axis=0) else: X -= np.mean(X, axis=0) Q, R = linalg.qr(X, mode='economic') Z = np.sqrt(n_samples) * Q # sort rows of Z with respect to the target y Z = Z[np.argsort(y), :] # determine slices and counts slices, counts = slice_y(y, self.n_slices) self.n_slices_ = counts.shape[0] # construct slice covariance matrices M = np.zeros((n_features, n_features)) for slice_idx in range(self.n_slices_): n_slice = counts[slice_idx] # center the entries in this slice Z_slice = Z[slices == slice_idx, :] Z_slice -= np.mean(Z_slice, axis=0) # slice covariance matrix V_slice = np.dot(Z_slice.T, Z_slice) / n_slice M_slice = np.eye(n_features) - V_slice M += (n_slice / n_samples) * np.dot(M_slice, M_slice) # eigen-decomposition of slice matrix evals, evecs = linalg.eigh(M) evecs = evecs[:, ::-1] evals = evals[::-1] try: # TODO: internally handle zero variance features. This would not # be a problem if we used svd, but does not match DR. directions = linalg.solve_triangular(np.sqrt(n_samples) * R, evecs) except (linalg.LinAlgError, TypeError): # NOTE: The TypeError is because of a bug in the reporting of scipy raise linalg.LinAlgError( "Unable to back-solve R for the dimension " "reducing directions. This is usually caused by the presents " "of zero variance features. Try removing these features with " "`sklearn.feature_selection.VarianceThreshold(threshold=0.)` " "and refitting.") # the number of directions is chosen by finding the maximum gap among # the ordered eigenvalues. if self.n_directions == 'auto': n_directions = np.argmax(np.abs(np.diff(evals))) + 1 self.n_directions_ = n_directions # normalize directions directions = normalize( directions[:, :self.n_directions_], norm='l2', axis=0) self.directions_ = directions.T self.eigenvalues_ = evals[:self.n_directions_] return self def transform(self, X): """Apply dimension reduction on X. X is projected onto the EDR-directions previously extracted from a training set. Parameters ---------- X : array-like, shape (n_samples, n_features) New data, where n_samples in the number of samples and n_features is the number of features. Returns ------- X_new : array-like, shape (n_samples, n_directions) """ check_is_fitted(self) X = check_array(X) return np.dot(X, self.directions_.T)
36.62963
79
0.630056
import warnings import numpy as np import scipy.linalg as linalg from scipy import sparse from sklearn.base import BaseEstimator, TransformerMixin from sklearn.preprocessing import normalize from sklearn.utils import check_array, check_X_y from sklearn.utils.validation import check_is_fitted from .slices import slice_y, is_multioutput __all__ = ['SlicedAverageVarianceEstimation'] class SlicedAverageVarianceEstimation(BaseEstimator, TransformerMixin): """Sliced Average Variance Estimation (SAVE) [1] Linear dimensionality reduction using the conditional covariance, Cov(X|y), to identify the directions defining the central subspace of the data. The algorithm performs a weighted principal component analysis on a transformation of slices of the covariance matrix of the whitened data, which has been sorted with respect to the target, y. Since SAVE looks at second moment information, it may miss first-moment information. In particular, it may miss linear trends. See :class:`sliced.sir.SlicedInverseRegression`, which is able to detect linear trends but may fail in other situations. If possible, both SIR and SAVE should be used when analyzing a dataset. Parameters ---------- n_directions : int, str or None (default='auto') Number of directions to keep. Corresponds to the dimension of the central subpace. If n_directions=='auto', the number of directions is chosen by finding the maximum gap in the ordered eigenvalues of the var(X|y) matrix and choosing the directions before this gap. If n_directions==None, the number of directions equals the number of features. n_slices : int (default=10) The number of slices used when calculating the inverse regression curve. Truncated to at most the number of unique values of ``y``. copy : bool (default=True) If False, data passed to fit are overwritten and running fit(X).transform(X) will not yield the expected results, use fit_transform(X) instead. Attributes ---------- directions_ : array, shape (n_directions, n_features) The directions in feature space, representing the central subspace which is sufficient to describe the conditional distribution y|X. The directions are sorted by ``eigenvalues_``. eigenvalues_ : array, shape (n_directions,) The eigenvalues corresponding to each of the selected directions. These are the eigenvalues of the covariance matrix of the inverse regression curve. Larger eigenvalues indicate more prevelant directions. Examples -------- >>> import numpy as np >>> from sliced import SlicedAverageVarianceEstimation >>> from sliced.datasets import make_quadratic >>> X, y = make_quadratic(random_state=123) >>> save = SlicedAverageVarianceEstimation(n_directions=2) >>> save.fit(X, y) SlicedAverageVarianceEstimation(copy=True, n_directions=2, n_slices=10) >>> X_save = save.transform(X) References ---------- [1] Shao, Y, Cook, RD and Weisberg, S (2007). "Marginal Tests with Sliced Average Variance Estimation", Biometrika, 94, 285-296. """ def __init__(self, n_directions='auto', n_slices=10, copy=True): self.n_directions = n_directions self.n_slices = n_slices self.copy = copy def fit(self, X, y): """Fit the model with X and y. Parameters ---------- X : array-like, shape (n_samples, n_features) Training data, where n_samples is the number of samples and n_features is the number of features. y : array-like, shape (n_samples,) The target values (class labels in classification, real numbers in regression). Returns ------- self : object Returns the instance itself. """ if sparse.issparse(X): raise TypeError("SlicedInverseRegression does not support " "sparse input.") X, y = check_X_y(X, y, dtype=[np.float64, np.float32], y_numeric=True, copy=self.copy) # handle n_directions == None if self.n_directions is None: n_directions = X.shape[1] elif (not isinstance(self.n_directions, str) and self.n_directions < 1): raise ValueError('The number of directions `n_directions` ' 'must be >= 1. Got `n_directions`={}'.format( self.n_directions)) else: n_directions = self.n_directions # validate y if is_multioutput(y): raise TypeError("The target `y` cannot be multi-output.") n_samples, n_features = X.shape # Center and Whiten feature matrix using a QR decomposition # (this is the approach used in the dr package) if self.copy: X = X - np.mean(X, axis=0) else: X -= np.mean(X, axis=0) Q, R = linalg.qr(X, mode='economic') Z = np.sqrt(n_samples) * Q # sort rows of Z with respect to the target y Z = Z[np.argsort(y), :] # determine slices and counts slices, counts = slice_y(y, self.n_slices) self.n_slices_ = counts.shape[0] # construct slice covariance matrices M = np.zeros((n_features, n_features)) for slice_idx in range(self.n_slices_): n_slice = counts[slice_idx] # center the entries in this slice Z_slice = Z[slices == slice_idx, :] Z_slice -= np.mean(Z_slice, axis=0) # slice covariance matrix V_slice = np.dot(Z_slice.T, Z_slice) / n_slice M_slice = np.eye(n_features) - V_slice M += (n_slice / n_samples) * np.dot(M_slice, M_slice) # eigen-decomposition of slice matrix evals, evecs = linalg.eigh(M) evecs = evecs[:, ::-1] evals = evals[::-1] try: # TODO: internally handle zero variance features. This would not # be a problem if we used svd, but does not match DR. directions = linalg.solve_triangular(np.sqrt(n_samples) * R, evecs) except (linalg.LinAlgError, TypeError): # NOTE: The TypeError is because of a bug in the reporting of scipy raise linalg.LinAlgError( "Unable to back-solve R for the dimension " "reducing directions. This is usually caused by the presents " "of zero variance features. Try removing these features with " "`sklearn.feature_selection.VarianceThreshold(threshold=0.)` " "and refitting.") # the number of directions is chosen by finding the maximum gap among # the ordered eigenvalues. if self.n_directions == 'auto': n_directions = np.argmax(np.abs(np.diff(evals))) + 1 self.n_directions_ = n_directions # normalize directions directions = normalize( directions[:, :self.n_directions_], norm='l2', axis=0) self.directions_ = directions.T self.eigenvalues_ = evals[:self.n_directions_] return self def transform(self, X): """Apply dimension reduction on X. X is projected onto the EDR-directions previously extracted from a training set. Parameters ---------- X : array-like, shape (n_samples, n_features) New data, where n_samples in the number of samples and n_features is the number of features. Returns ------- X_new : array-like, shape (n_samples, n_directions) """ check_is_fitted(self) X = check_array(X) return np.dot(X, self.directions_.T)
142
0
26
61fd127eb16632bfe4be2372eb543f29cdbd30ec
1,811
py
Python
main.py
nullpos/nicolive-reserve-calendar
266bc9d4c05b9b6a140cdca84bf4418944736341
[ "MIT" ]
null
null
null
main.py
nullpos/nicolive-reserve-calendar
266bc9d4c05b9b6a140cdca84bf4418944736341
[ "MIT" ]
1
2016-02-28T11:48:48.000Z
2016-02-28T11:48:48.000Z
main.py
nullpos/nicolive-reserve-calendar
266bc9d4c05b9b6a140cdca84bf4418944736341
[ "MIT" ]
null
null
null
# coding: utf-8 import os import re import sys import ConfigParser from util.live import Live from util.google import Google CONFIG_PATH = os.path.dirname(os.path.abspath(__file__)) + '/config' CONFIG_SAMPLE_FILE = CONFIG_PATH + '.sample' LIVE_BASE_URL = 'http://live.nicovideo.jp/watch/' if __name__ == '__main__': if len(sys.argv) != 3: print "invalid arguments" method = sys.argv[1] if re.match('lv', sys.argv[2]): url = LIVE_BASE_URL + sys.argv[2] else: url = sys.argv[2] main = Main() main.run(url, method)
25.871429
68
0.579238
# coding: utf-8 import os import re import sys import ConfigParser from util.live import Live from util.google import Google CONFIG_PATH = os.path.dirname(os.path.abspath(__file__)) + '/config' CONFIG_SAMPLE_FILE = CONFIG_PATH + '.sample' LIVE_BASE_URL = 'http://live.nicovideo.jp/watch/' class Main(object): def __init__(self): config_path = CONFIG_PATH if not os.path.exists(config_path): config_path = CONFIG_SAMPLE_FILE self.config = self.get_config(config_path) def get_config(self, config_path): config = ConfigParser.ConfigParser() config.read(config_path) nico = 'niconico' google = 'google' nicomail = config.get(nico, 'mail') password = config.get(nico, 'password') calendar_id = config.get(google, 'calendar_id') dictionary = { nico: { 'mail': nicomail, 'password': password }, google: { 'calendar_id': calendar_id } } return dictionary def run(self, url, method): live = Live(main.config.get('niconico')) live_info = live.get(url) google = Google(main.config.get('google')) if method == 'insert': google.insert(live_info) elif method == 'update': google.update(live_info, url) elif method == 'delete': google.delete(live_info, url) elif method == 'search': google.search(live_info, url) if __name__ == '__main__': if len(sys.argv) != 3: print "invalid arguments" method = sys.argv[1] if re.match('lv', sys.argv[2]): url = LIVE_BASE_URL + sys.argv[2] else: url = sys.argv[2] main = Main() main.run(url, method)
1,144
-2
103
f41df9a00e5a99665adcdba0bfca5c34c704048d
2,004
py
Python
app/input/file.py
pedrolp85/pycli
469d22442de2a854aebc3354cdbf9b8fe342ee16
[ "Apache-2.0" ]
null
null
null
app/input/file.py
pedrolp85/pycli
469d22442de2a854aebc3354cdbf9b8fe342ee16
[ "Apache-2.0" ]
null
null
null
app/input/file.py
pedrolp85/pycli
469d22442de2a854aebc3354cdbf9b8fe342ee16
[ "Apache-2.0" ]
null
null
null
from io import StringIO, SEEK_END from pathlib import Path from typing import Iterator, TextIO from .input import Input
34.551724
70
0.518463
from io import StringIO, SEEK_END from pathlib import Path from typing import Iterator, TextIO from .input import Input class FileInput(Input): def __init__(self, file_path: str) -> None: self._file_path = file_path def get_lines(self) -> Iterator[str]: with open(self._file_path, "r") as file: line = "start" while line: line = file.readline() if line: yield line.rstrip("\n") class ReverseFileInput(Input): def __init__(self, file_path: str) -> None: self._file_path = file_path def get_lines(self) -> Iterator[str]: buffer = 100 with open(self._file_path, "r") as file: file_end_pos = file.seek(0, SEEK_END) revlinebuf = StringIO() chunk_buf = StringIO() last_chunk_start = file_end_pos + 1 while last_chunk_start > 0: if buffer > last_chunk_start: buffer = last_chunk_start chunk_start = last_chunk_start - buffer file.seek(chunk_start) chunk_buf.write(file.read(buffer)) chunk = chunk_buf.getvalue() while chunk: lhs, separator_match, rhs = chunk.rpartition("\n") if separator_match: if rhs: revlinebuf.write(rhs[::-1]) completed_line = revlinebuf.getvalue()[::-1] revlinebuf.seek(0) revlinebuf.truncate() yield completed_line else: revlinebuf.write(chunk_buf.getvalue()[::-1]) chunk_buf.seek(len(lhs)) chunk_buf.truncate() chunk = chunk_buf.getvalue() last_chunk_start = chunk_start completed_line = revlinebuf.getvalue()[::-1] yield completed_line
1,716
11
154
3ad7e3174f8fb75f0e120b935beca591ccc8a40b
114
py
Python
etc/mayan/settings.py
KingJ/mayan-edms
cd7f530c8d17e3f11da51692b28b68f585d082b1
[ "MIT" ]
null
null
null
etc/mayan/settings.py
KingJ/mayan-edms
cd7f530c8d17e3f11da51692b28b68f585d082b1
[ "MIT" ]
null
null
null
etc/mayan/settings.py
KingJ/mayan-edms
cd7f530c8d17e3f11da51692b28b68f585d082b1
[ "MIT" ]
null
null
null
ALLOWED_HOSTS = ['*'] BROKER_URL = 'redis://127.0.0.1:6379/0' CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/0'
22.8
50
0.666667
ALLOWED_HOSTS = ['*'] BROKER_URL = 'redis://127.0.0.1:6379/0' CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/0'
0
0
0
47ee50419bc9c62aca74391e6a9a17a4c69b33dc
407
py
Python
outros/speed_test.py
caiocampos/Python-Random-Stuff
5e9005e7dec776e9af0c407d063624d041d3c84c
[ "MIT" ]
null
null
null
outros/speed_test.py
caiocampos/Python-Random-Stuff
5e9005e7dec776e9af0c407d063624d041d3c84c
[ "MIT" ]
null
null
null
outros/speed_test.py
caiocampos/Python-Random-Stuff
5e9005e7dec776e9af0c407d063624d041d3c84c
[ "MIT" ]
null
null
null
from time import time from functools import reduce from operator import add
23.941176
45
0.515971
from time import time from functools import reduce from operator import add def speed_test(): tt = time() res, v , n = [], 0, 100 for i in range(n): t = time() for j in range(n ** 2): v += n * i * j res += [time() - t] print('menor:', min(res)) print('maior:', max(res)) print('média:', reduce(add,res)/len(res)) print('total:', time() - tt)
309
0
23
9178a63c7969278a4d756bab503a3bcb18c7f766
10,924
py
Python
imgurtofolder/imgur_downloader.py
santosderek/Imgur-To-Folder
5716cc81a9b003d1c0499388fc7561053f717aef
[ "Apache-2.0" ]
77
2017-04-24T08:08:53.000Z
2021-10-07T04:04:26.000Z
imgurtofolder/imgur_downloader.py
santosderek/Imgur-To-Folder
5716cc81a9b003d1c0499388fc7561053f717aef
[ "Apache-2.0" ]
12
2017-11-09T17:16:03.000Z
2021-04-23T04:50:52.000Z
imgurtofolder/imgur_downloader.py
santosderek/Imgur-To-Folder
5716cc81a9b003d1c0499388fc7561053f717aef
[ "Apache-2.0" ]
12
2017-09-03T10:41:27.000Z
2021-04-21T11:28:02.000Z
# Derek Santos from imgur import Imgur from pprint import pformat from time import sleep import json import logs import os import re import requests import shutil log = logs.Log('downloader')
41.067669
112
0.569114
# Derek Santos from imgur import Imgur from pprint import pformat from time import sleep import json import logs import os import re import requests import shutil log = logs.Log('downloader') class Imgur_Downloader(Imgur): def __init__(self, configuration, max_favorites): super().__init__(configuration) self._max_favorites = max_favorites def replace_characters(self, word): # NOTE: '\\/:*?"<>|.' are invalid folder characters in a file system invalid_characters = ['\\', "'", '/', ':', '*', '?', '"', '<', '>', '|', '.', '\n'] for character in invalid_characters: word = word.replace(character, '') word = word.strip() return word def parse_id(self, url, page=0, max_items=30, sort='time', window='day'): imgur_base_extensions = { 'album' : [r'(/a/)(\w+)'], 'gallery' : [r'(/g/)(\w+)', r'(/gallery/)(\w+)'], 'subreddit' : [r'(/r/)(\w+)\/(\w+)', r'(/r/)(\w+)$'], 'tag' : [r'(/t/)(\w+)'] } if any(re.search(item, url) for item in imgur_base_extensions['album']): for item in imgur_base_extensions['album']: result = re.search(item, url).group(2) if re.search(item, url) else None if result: self.download_album(result) elif any(re.search(item, url) for item in imgur_base_extensions['gallery']): for item in imgur_base_extensions['gallery']: result = re.search(item, url).group(2) if re.search(item, url) else None if result: self.download_gallery(result) elif any(re.search(item, url) for item in imgur_base_extensions['subreddit']): for item in imgur_base_extensions['subreddit']: if re.search(item, url) is None: continue subreddit = re.search(item, url).group(2) id = re.search(item, url).group(3) if re.compile(item).groups > 2 else None if id is None and subreddit is not None: self.download_subreddit(subreddit, sort=sort, window=window, page=page, max_items=max_items) elif subreddit is not None and id is not None: self.download_subreddit_gallery(subreddit, id) elif any(re.search(item, url) for item in imgur_base_extensions['tag']): for item in imgur_base_extensions['tag']: result = re.search(item, url).group(2) if re.search(item, url) else None if result: self.download_tag(result, page=page, max_items=max_items) else: log.info('Downloading image: %s' % url[url.rfind('/') + 1:]) self.download(url[url.rfind('/') + 1:], url, self.get_download_path()) def get_image_link(self, image): if 'mp4' in image: image_link = image['mp4'] filetype = '.mp4' elif 'gifv' in image: image_link = image['gifv'] filetype = '.gif' else: image_link = image['link'] filetype = image_link[image_link.rfind('.'):] return image_link, filetype def mkdir(self, path): log.debug("Checking if folder exists") if not os.path.exists(path): log.debug("Creating folder: %s" % path) os.makedirs(path) def download_tag(self, id, page=0, max_items=30): log.debug('Getting tag details') items = self.get_tag(id, page=page, max_items=max_items) # For each item in tag. Items are "albums" for item in items: if 'images' in item: tag_root_title = item['title'] if item['title'] else item['id'] tag_root_title = self.replace_characters(tag_root_title) tag_root_path = os.path.join(self.get_download_path(), tag_root_title) self.mkdir(tag_root_path) for position, sub_image in enumerate(item['images'], start=1): title = sub_image['title'] if sub_image['title'] else sub_image['id'] title = self.replace_characters(title) path = os.path.join(tag_root_path, title) self.mkdir(path) log.info('Downloading tag: %s' % title) image_link, filetype = self.get_image_link(sub_image) image_filename = "{} - {}{}".format(sub_image['id'], position, filetype) self.download(image_filename, image_link, path) else: title = item['title'] if item['title'] else item['id'] title = self.replace_characters(title) path = os.path.join(self.get_download_path(), title) self.mkdir(path) log.info('Downloading tag: %s' % title) image_link, filetype = self.get_image_link(sub_image) image_filename = "{} - {}{}".format(sub_image['id'], position, filetype) self.download(image_filename, image_link, path) def download_album(self, id): log.debug('Getting album details') album = self.get_album(id)['data'] title = album['title'] if album['title'] else album['id'] title = self.replace_characters(title) path = os.path.join(self.get_download_path(), title) log.debug("Checking if folder exists") if not os.path.exists(path): log.debug("Creating folder: %s" % path) os.makedirs(path) log.info('Downloading album: %s' % title) for position, image in enumerate(album['images'], start=1): image_link, filetype = self.get_image_link(image) image_filename = "{} - {}{}".format(album['id'], position, filetype) self.download(image_filename, image_link, path) def download_gallery(self, id): log.debug('Getting Gallery details') album = self.get_gallery_album(id)['data'] title = album['title'] if album['title'] else album['id'] title = self.replace_characters(title) path = os.path.join(self.get_download_path(), title) log.debug("Checking if folder exists") if not os.path.exists(path): log.debug("Creating folder: %s" % path) os.makedirs(path) if 'images' in album: log.info('Downloading gallery %s' % album['id']) for position, image in enumerate(album['images'], start=1): image_link, filetype = self.get_image_link(image) filename = album['id'] + ' - ' + str(position) + filetype self.download(filename, image_link, path) else: image_link, filetype = self.get_image_link(album) filename = image_link[image_link.rfind('/') + 1:] log.info('Downloading gallery image: %s' % filename) self.download(filename, image_link, path) def download_subreddit(self, subreddit, sort='time', window='day', page=0, max_items=30): log.debug("Getting subreddit details") subreddit_data = [] response = self.get_subreddit_gallery(subreddit, sort=sort, window=window, page=page)['data'] while len(subreddit_data) < max_items and len(response) != 0: subreddit_data += response page += 1 response = self.get_subreddit_gallery(subreddit, sort, window, page)['data'] log.debug("Sending subreddit items to parse_id") for position, item in enumerate(subreddit_data): if position + 1 <= max_items: self.parse_id(item["link"], page, max_items) def download_subreddit_gallery(self, subreddit, id): log.debug('Getting subreddit gallery details') subreddit_album = self.get_subreddit_image(subreddit, id)['data'] title = subreddit_album['title'] if subreddit_album['title'] else subreddit_album['id'] title = self.replace_characters(title) path = self.get_download_path() log.debug("Checking if folder exists") if not os.path.exists(path): log.debug("Creating folder: %s" % path) os.makedirs(path) log.info('Downloading subreddit gallery image: %s' % title) image_link, filetype = self.get_image_link(subreddit_album) filename = image_link[image_link.rfind('/') + 1:] self.download(filename, image_link, self.get_download_path()) def download_favorites(self, username, latest=True, page=0, max_items=None): log.info("Getting account favorites") favorites = self.get_account_favorites(username = username, sort = 'oldest' if not latest else 'newest', page=page, max_items=max_items) log.debug('Number of favorites: %d' % len(favorites)) for favorite in favorites: self.parse_id(favorite['link']) def list_favorites(self, username, latest=True, page=0, max_items=-1): favorites = self.get_account_favorites(username = username, sort = 'oldest' if not latest else 'newest', page=page, max_items=max_items) log.info(pformat(favorites)) def download_account_images(self, username, page=0, max_items=None): account_images = self.get_account_images(username, page=page) if max_items: account_images = account_images[:max_items] for image in account_images: self.parse_id(image['link']) def download(self, filename, url, path): log.debug('Checking that folder path exists') if not os.path.exists(path): log.debug('Creating folder path') os.makedirs(path) log.debug('Checking to overwrite') if not self.get_overwrite() and os.path.exists(os.path.join(path, filename)): log.info('\tSkipping %s' % filename) return req = requests.get(url, stream=True) if req.status_code == 200: file_size = int(req.headers.get('content-length', 0)) / float(1 << 20) log.info('\t%s, File Size: %.2f MB' % (filename, file_size)) with open(os.path.join(path, filename), 'wb') as image_file: req.raw.decode_content = True shutil.copyfileobj(req.raw, image_file) else: log.info('\tERROR! Can not download: ' + os.path.join(path, filename)) log.info('\tStatus code: ' + str(req.status_code)) # Delaying so no timeout sleep(.1)
10,319
9
400
e27b17ff88d64bd474bb9a68dcd187a5f5e4661b
383
py
Python
essentials/pandas/pandas_5.py
iomegak12/intel-training-usecase-1
0d1ab6f6076f46f7fbb290ceb41d6b851da1af3a
[ "MIT" ]
null
null
null
essentials/pandas/pandas_5.py
iomegak12/intel-training-usecase-1
0d1ab6f6076f46f7fbb290ceb41d6b851da1af3a
[ "MIT" ]
null
null
null
essentials/pandas/pandas_5.py
iomegak12/intel-training-usecase-1
0d1ab6f6076f46f7fbb290ceb41d6b851da1af3a
[ "MIT" ]
null
null
null
import pandas as pd import numpy as np data = { 'Id': [1, 2, 3, 4, 5], 'Name': ['Syed', 'Shah', 'Sunil', 'Sherif', 'Sugata'], 'Score': [100, 200, 250, 350, 275] } df = pd.DataFrame( data, index=['Rank 1', 'Rank 2', 'Rank 3', 'Rank 4', 'Rank 5']) df["Locations"] = np.array( ['Bangalore', 'New York', 'Houston', 'Boston', 'Sydney']) print(df["Name"]) print(df)
22.529412
67
0.545692
import pandas as pd import numpy as np data = { 'Id': [1, 2, 3, 4, 5], 'Name': ['Syed', 'Shah', 'Sunil', 'Sherif', 'Sugata'], 'Score': [100, 200, 250, 350, 275] } df = pd.DataFrame( data, index=['Rank 1', 'Rank 2', 'Rank 3', 'Rank 4', 'Rank 5']) df["Locations"] = np.array( ['Bangalore', 'New York', 'Houston', 'Boston', 'Sydney']) print(df["Name"]) print(df)
0
0
0
9e9e9506c5db455cd9dc6e5c949669444b62df7b
6,949
py
Python
tests/testing_values.py
Gsvend20/P4-Grise_Projekt
28e558139dd0368db2e29de3c8aa3842bad9edef
[ "MIT" ]
2
2022-03-23T08:55:42.000Z
2022-03-23T09:06:04.000Z
tests/testing_values.py
Gsvend20/P4-Grise_Projekt
28e558139dd0368db2e29de3c8aa3842bad9edef
[ "MIT" ]
null
null
null
tests/testing_values.py
Gsvend20/P4-Grise_Projekt
28e558139dd0368db2e29de3c8aa3842bad9edef
[ "MIT" ]
1
2022-03-23T08:55:19.000Z
2022-03-23T08:55:19.000Z
import cv2 import numpy as np from Functions.Featurespace import find_annodir from Functions import imgproc_func as imf import glob # TODO: FIX FS thresholding, GR detection """ SÆT DIN PATH TIL DIT ONE DRIVE HER -> DOWNLOAD ANNOTATIONS MAPPEN FØRST """ # Path to folder containing the different classes path = r'C:\Users\Muku\OneDrive - Aalborg Universitet\P4 - GrisProjekt\Training data\annotations' # Find what classes have been found class_name, anotations = find_annodir(path) # Define trackers = ['hue_upper', 'hue_lower', 'light_upper', 'light_lower', 'saturation_upper', 'saturation_lower'] hls_values = [255, 70, 255, 37, 255, 30] blue_values = [124, 84, 119, 37, 148, 61] scratches_values = [129, 70, 103, 21, 59, 32] roots_values = [200, 105, 121, 101, 152, 114] for i, tracks in enumerate(trackers): imf.define_trackbar(tracks, 'Base', (hls_values[i], 255)) imf.define_trackbar(tracks, 'Cloth', (blue_values[i], 255)) imf.define_trackbar(tracks, 'Scratches', (scratches_values[i], 255)) imf.define_trackbar(tracks, 'ROE', (roots_values[i], 255)) imf.define_trackbar('gaussian blur', 'processing', (0,1)) # imf.define_trackbar('kernel', 'processing', (3,21)) # imf.define_trackbar('low edge', 'processing', (3,100)) # imf.define_trackbar('high edge', 'processing', (3,100)) # imf.define_trackbar('edge color space', 'processing', (0,3)) for category in class_name: # D used to skip categories D = 0 depth_paths = glob.glob(path.replace('\\', '/') + '/' + category + '/**/*aligned*.png', recursive=True) for i in range(10,20): if D: break depth_path = depth_paths[i] bgr_path = depth_path.replace('aligned', 'bgr') depth2_path = depth_path.replace('aligned', 'depth') depth2_img = imf.convert_to_16(cv2.imread(depth2_path)) depth_img = imf.convert_to_16(cv2.imread(depth_path)) bgr_img = cv2.imread(bgr_path) while (True): kernel = imf.retrieve_trackbar('kernel', 'blurs', True) if imf.retrieve_trackbar('gaussian blur', 'blurs'): blur = cv2.GaussianBlur(bgr_img, (kernel,kernel), cv2.BORDER_DEFAULT) else: blur = cv2.medianBlur(bgr_img, kernel) frame_hsi = cv2.cvtColor(blur, cv2.COLOR_BGR2HLS) frame_hsv = cv2.cvtColor(blur, cv2.COLOR_BGR2YCrCb) hls_up = [] hls_low = [] blue_up = [] blue_low = [] scr_up = [] scr_low = [] roe_up = [] roe_low = [] for i in range(0,len(trackers),2): hls_up.append(imf.retrieve_trackbar(trackers[i], 'Base')) hls_low.append(imf.retrieve_trackbar(trackers[i+1], 'Base')) blue_up.append(imf.retrieve_trackbar(trackers[i], 'Cloth')) blue_low.append(imf.retrieve_trackbar(trackers[i+1], 'Cloth')) scr_up.append(imf.retrieve_trackbar(trackers[i], 'Scratches')) scr_low.append(imf.retrieve_trackbar(trackers[i+1], 'Scratches')) roe_up.append(imf.retrieve_trackbar(trackers[i], 'ROE')) roe_low.append(imf.retrieve_trackbar(trackers[i + 1], 'ROE')) # Generate area of interest from pipe depth data aoi_end = cv2.inRange(depth_img, int(np.max(depth_img) - 100), int(np.max(depth_img))) aoi_pipe = cv2.inRange(depth_img, 600, int(np.max(depth_img) - 100)) cnt, hir = cv2.findContours(aoi_pipe, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) pipe_mask = np.zeros_like(depth_img).astype('uint8') pipe_mask = cv2.fillPoly(pipe_mask, cnt, 255) bg_mask = cv2.subtract(pipe_mask, aoi_end) bg_mask = imf.open_img(bg_mask, 21, 21) bg_mask = cv2.dilate(bg_mask, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (21, 21))) hsi_aoi = cv2.bitwise_and(frame_hsi, frame_hsi, mask=bg_mask) # Edge detection # edge_space = imf.retrieve_trackbar('edge color space', 'processing') # if edge_space == 0: # canny = cv2.Canny(frame_hsi[:, :, 0], imf.retrieve_trackbar('low edge', 'processing'), imf.retrieve_trackbar('high edge', 'processing')) # canny = cv2.dilate(canny, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))) # elif edge_space == 1: # canny = cv2.Canny(frame_hsi[:, :, 1], imf.retrieve_trackbar('low edge', 'processing'), # imf.retrieve_trackbar('high edge', 'processing')) # canny = cv2.dilate(canny, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))) # elif edge_space == 2: # canny = cv2.Canny(frame_hsi[:, :, 2], imf.retrieve_trackbar('low edge', 'processing'), # imf.retrieve_trackbar('high edge', 'processing')) # canny = cv2.dilate(canny, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))) # elif edge_space == 3: # canny = cv2.Canny(imf.depth_to_display(depth_img), imf.retrieve_trackbar('low edge', 'processing'), # imf.retrieve_trackbar('high edge', 'processing')) # canny = cv2.dilate(canny, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (6, 6))) """ HER ER MASKS mask1 = base mask2 = cloth mask3 = scratches Hvis du vil have dem individuelt kan du ændre til "bin = open_img((din mask), 7,7)" ellers kan du udkommentere subtract delene indtil det du gerne vil have """ mask1 = cv2.inRange(frame_hsi, np.asarray(hls_low), np.asarray(hls_up)) # Threshold around highlights mask2 = cv2.inRange(frame_hsi, np.asarray(blue_low), np.asarray(blue_up)) # Remove blue, due to the piece of cloth mask3 = cv2.inRange(frame_hsi, np.asarray(scr_low), np.asarray(scr_up)) # Remove blue, due to scratches mask4 = cv2.inRange(frame_hsv, np.asarray(roe_low), np.asarray(roe_up)) # Find roots and pipe edges hsi_thresh = cv2.add(mask1, mask4) hsi_thresh = cv2.subtract(hsi_thresh,mask2) hsi_thresh = cv2.subtract(hsi_thresh, mask3) # hsi_thresh = cv2.add(hsi_thresh, canny) bin = imf.open_img(hsi_thresh, 7, 7) imf.resize_image(bgr_img, 'original', 0.4) imf.resize_image(bin.copy(), 'binary', 0.4) imf.resize_image(mask4, 'blur', 0.4) imf.resize_image(imf.depth_to_display(depth_img), 'depth', 0.4) # imf.resize_image(imf.depth_to_display(canny), 'canny', 0.4) cv2.imwrite('result.png', bin) key = cv2.waitKey(1) if key == ord('q'): break if key == ord('d'): D = 1 break
46.019868
154
0.603972
import cv2 import numpy as np from Functions.Featurespace import find_annodir from Functions import imgproc_func as imf import glob # TODO: FIX FS thresholding, GR detection """ SÆT DIN PATH TIL DIT ONE DRIVE HER -> DOWNLOAD ANNOTATIONS MAPPEN FØRST """ # Path to folder containing the different classes path = r'C:\Users\Muku\OneDrive - Aalborg Universitet\P4 - GrisProjekt\Training data\annotations' # Find what classes have been found class_name, anotations = find_annodir(path) # Define trackers = ['hue_upper', 'hue_lower', 'light_upper', 'light_lower', 'saturation_upper', 'saturation_lower'] hls_values = [255, 70, 255, 37, 255, 30] blue_values = [124, 84, 119, 37, 148, 61] scratches_values = [129, 70, 103, 21, 59, 32] roots_values = [200, 105, 121, 101, 152, 114] for i, tracks in enumerate(trackers): imf.define_trackbar(tracks, 'Base', (hls_values[i], 255)) imf.define_trackbar(tracks, 'Cloth', (blue_values[i], 255)) imf.define_trackbar(tracks, 'Scratches', (scratches_values[i], 255)) imf.define_trackbar(tracks, 'ROE', (roots_values[i], 255)) imf.define_trackbar('gaussian blur', 'processing', (0,1)) # imf.define_trackbar('kernel', 'processing', (3,21)) # imf.define_trackbar('low edge', 'processing', (3,100)) # imf.define_trackbar('high edge', 'processing', (3,100)) # imf.define_trackbar('edge color space', 'processing', (0,3)) for category in class_name: # D used to skip categories D = 0 depth_paths = glob.glob(path.replace('\\', '/') + '/' + category + '/**/*aligned*.png', recursive=True) for i in range(10,20): if D: break depth_path = depth_paths[i] bgr_path = depth_path.replace('aligned', 'bgr') depth2_path = depth_path.replace('aligned', 'depth') depth2_img = imf.convert_to_16(cv2.imread(depth2_path)) depth_img = imf.convert_to_16(cv2.imread(depth_path)) bgr_img = cv2.imread(bgr_path) while (True): kernel = imf.retrieve_trackbar('kernel', 'blurs', True) if imf.retrieve_trackbar('gaussian blur', 'blurs'): blur = cv2.GaussianBlur(bgr_img, (kernel,kernel), cv2.BORDER_DEFAULT) else: blur = cv2.medianBlur(bgr_img, kernel) frame_hsi = cv2.cvtColor(blur, cv2.COLOR_BGR2HLS) frame_hsv = cv2.cvtColor(blur, cv2.COLOR_BGR2YCrCb) hls_up = [] hls_low = [] blue_up = [] blue_low = [] scr_up = [] scr_low = [] roe_up = [] roe_low = [] for i in range(0,len(trackers),2): hls_up.append(imf.retrieve_trackbar(trackers[i], 'Base')) hls_low.append(imf.retrieve_trackbar(trackers[i+1], 'Base')) blue_up.append(imf.retrieve_trackbar(trackers[i], 'Cloth')) blue_low.append(imf.retrieve_trackbar(trackers[i+1], 'Cloth')) scr_up.append(imf.retrieve_trackbar(trackers[i], 'Scratches')) scr_low.append(imf.retrieve_trackbar(trackers[i+1], 'Scratches')) roe_up.append(imf.retrieve_trackbar(trackers[i], 'ROE')) roe_low.append(imf.retrieve_trackbar(trackers[i + 1], 'ROE')) # Generate area of interest from pipe depth data aoi_end = cv2.inRange(depth_img, int(np.max(depth_img) - 100), int(np.max(depth_img))) aoi_pipe = cv2.inRange(depth_img, 600, int(np.max(depth_img) - 100)) cnt, hir = cv2.findContours(aoi_pipe, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) pipe_mask = np.zeros_like(depth_img).astype('uint8') pipe_mask = cv2.fillPoly(pipe_mask, cnt, 255) bg_mask = cv2.subtract(pipe_mask, aoi_end) bg_mask = imf.open_img(bg_mask, 21, 21) bg_mask = cv2.dilate(bg_mask, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (21, 21))) hsi_aoi = cv2.bitwise_and(frame_hsi, frame_hsi, mask=bg_mask) # Edge detection # edge_space = imf.retrieve_trackbar('edge color space', 'processing') # if edge_space == 0: # canny = cv2.Canny(frame_hsi[:, :, 0], imf.retrieve_trackbar('low edge', 'processing'), imf.retrieve_trackbar('high edge', 'processing')) # canny = cv2.dilate(canny, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))) # elif edge_space == 1: # canny = cv2.Canny(frame_hsi[:, :, 1], imf.retrieve_trackbar('low edge', 'processing'), # imf.retrieve_trackbar('high edge', 'processing')) # canny = cv2.dilate(canny, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))) # elif edge_space == 2: # canny = cv2.Canny(frame_hsi[:, :, 2], imf.retrieve_trackbar('low edge', 'processing'), # imf.retrieve_trackbar('high edge', 'processing')) # canny = cv2.dilate(canny, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))) # elif edge_space == 3: # canny = cv2.Canny(imf.depth_to_display(depth_img), imf.retrieve_trackbar('low edge', 'processing'), # imf.retrieve_trackbar('high edge', 'processing')) # canny = cv2.dilate(canny, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (6, 6))) """ HER ER MASKS mask1 = base mask2 = cloth mask3 = scratches Hvis du vil have dem individuelt kan du ændre til "bin = open_img((din mask), 7,7)" ellers kan du udkommentere subtract delene indtil det du gerne vil have """ mask1 = cv2.inRange(frame_hsi, np.asarray(hls_low), np.asarray(hls_up)) # Threshold around highlights mask2 = cv2.inRange(frame_hsi, np.asarray(blue_low), np.asarray(blue_up)) # Remove blue, due to the piece of cloth mask3 = cv2.inRange(frame_hsi, np.asarray(scr_low), np.asarray(scr_up)) # Remove blue, due to scratches mask4 = cv2.inRange(frame_hsv, np.asarray(roe_low), np.asarray(roe_up)) # Find roots and pipe edges hsi_thresh = cv2.add(mask1, mask4) hsi_thresh = cv2.subtract(hsi_thresh,mask2) hsi_thresh = cv2.subtract(hsi_thresh, mask3) # hsi_thresh = cv2.add(hsi_thresh, canny) bin = imf.open_img(hsi_thresh, 7, 7) imf.resize_image(bgr_img, 'original', 0.4) imf.resize_image(bin.copy(), 'binary', 0.4) imf.resize_image(mask4, 'blur', 0.4) imf.resize_image(imf.depth_to_display(depth_img), 'depth', 0.4) # imf.resize_image(imf.depth_to_display(canny), 'canny', 0.4) cv2.imwrite('result.png', bin) key = cv2.waitKey(1) if key == ord('q'): break if key == ord('d'): D = 1 break
0
0
0
3feb4ca7030fb3e2f124726a01e7b2e2e0dc3064
5,568
py
Python
survos2/frontend/plugins/plugins_components.py
DiamondLightSource/SuRVoS2
42bacfb6a5cc267f38ca1337e51a443eae1a9d2b
[ "MIT" ]
4
2017-10-10T14:47:16.000Z
2022-01-14T05:57:50.000Z
survos2/frontend/plugins/plugins_components.py
DiamondLightSource/SuRVoS2
42bacfb6a5cc267f38ca1337e51a443eae1a9d2b
[ "MIT" ]
1
2022-01-11T21:11:12.000Z
2022-01-12T08:22:34.000Z
survos2/frontend/plugins/plugins_components.py
DiamondLightSource/SuRVoS2
42bacfb6a5cc267f38ca1337e51a443eae1a9d2b
[ "MIT" ]
2
2018-03-06T06:31:29.000Z
2019-03-04T03:33:18.000Z
import numpy as np from loguru import logger from scipy import ndimage from skimage import img_as_ubyte, img_as_float from skimage import io from qtpy.QtWidgets import QRadioButton, QPushButton from qtpy import QtWidgets, QtCore, QtGui from survos2.frontend.components.base import * from survos2.frontend.control import Launcher _FeatureNotifier = PluginNotifier()
28.121212
86
0.616559
import numpy as np from loguru import logger from scipy import ndimage from skimage import img_as_ubyte, img_as_float from skimage import io from qtpy.QtWidgets import QRadioButton, QPushButton from qtpy import QtWidgets, QtCore, QtGui from survos2.frontend.components.base import * from survos2.frontend.control import Launcher def _fill_features(combo, full=False, filter=True, ignore=None): params = dict(workspace=True, full=full, filter=filter) result = Launcher.g.run("features", "existing", **params) if result: for fid in result: if fid != ignore: combo.addItem(fid, result[fid]["name"]) else: result = dict() params.setdefault("id", 7) params.setdefault("name", "feat0") params.setdefault("kind", "unknown") result[0] = params _FeatureNotifier = PluginNotifier() class SourceComboBox(LazyComboBox): def __init__(self, ignore_source=None, parent=None): self.ignore_source = ignore_source super().__init__(header=("__data__", "Raw Data"), parent=parent) _FeatureNotifier.listen(self.update) def fill(self): _fill_features(self, ignore=self.ignore_source) class MultiSourceComboBox(LazyMultiComboBox): def __init__(self, parent=None): super().__init__( header=("__data__", "Raw Data"), text="Select Source", parent=parent ) _FeatureNotifier.listen(self.update) def fill(self): _fill_features(self, full=True) class Slider(QCSWidget): valueChanged = QtCore.Signal(int) def __init__( self, value=None, vmax=100, vmin=0, step=1, tracking=True, label=True, auto_accept=True, center=False, parent=None, ): super().__init__(parent=parent) if value is None: value = vmin self.setMinimumWidth(200) self.slider = QtWidgets.QSlider(QtCore.Qt.Horizontal) self.slider.setMinimum(vmin) self.slider.setMaximum(vmax) self.slider.setValue(value) self.slider.setTickInterval(step) self.slider.setSingleStep(step) self.slider.setTracking(tracking) self.step = step hbox = HBox(self, spacing=5) if label: self.label = Label(str(value)) self.label.setMinimumWidth(50) if center: hbox.addSpacing(50) hbox.addWidget(self.slider, 1) hbox.addWidget(self.label) self.valueChanged.connect(self.update_label) else: hbox.addWidget(self.slider, 1) self.slider.valueChanged.connect(self.value_changed) self.slider.wheelEvent = self.wheelEvent self.auto_accept = auto_accept self.locked_idx = None self.pending = None self.blockSignals = self.slider.blockSignals def value_changed(self, idx): if self.auto_accept: self.valueChanged.emit(idx) elif self.locked_idx is None: self.locked_idx = idx self.valueChanged.emit(idx) else: self.slider.blockSignals(True) self.slider.setValue(self.locked_idx) self.slider.blockSignals(False) self.pending = idx def accept(self): if self.pending is not None: val = self.pending self.pending = None self.slider.blockSignals(True) self.slider.setValue(val) self.slider.blockSignals(False) self.valueChanged.emit(val) self.locked_idx = None def update_label(self, idx): self.label.setText(str(idx)) def wheelEvent(self, e): if e.angleDelta().y() > 0 and self.value() < self.maximum(): self.setValue(self.value() + self.step) elif e.angleDelta().y() < 0 and self.value() > self.minimum(): self.setValue(self.value() - self.step) def value(self): return self.pending or self.slider.value() def setValue(self, value): return self.slider.setValue(value) def __getattr__(self, key): return self.slider.__getattribute__(key) class RealSlider(Slider): def __init__(self, value=0, vmax=100, vmin=0, n=1000, **kwargs): super().__init__(value=0, vmin=0, vmax=n, **kwargs) self._n = n self._vmin = vmin self._vmax = vmax self._update_linspace() self.blockSignals(True) self.setValue(value) self.update_label(self._mapvalue(value)) self.blockSignals(False) def _mapvalue(self, val): return (np.abs(self._values - val)).argmin() def value(self): return self._values[self.slider.value()] def update_label(self, idx): idx = "{0:.3f}".format(self._values[idx]) super().update_label(idx) def _update_linspace(self): self._values = np.linspace(self._vmin, self._vmax, self._n + 1, endpoint=True) def setValue(self, val): idx = self._mapvalue(val) super().setValue(idx) def setMaximum(self, vmax): self._vmax = vmax self._update_linspace() def setMinimum(self, vmin): self._vmin = vmin self._update_linspace() def maximum(self): return self._vmax def minimum(self): return self._vmin class Label(QtWidgets.QLabel): def __init__(self, *args): super().__init__(*args) self.setAlignment(QtCore.Qt.AlignCenter) def value(self): return self.text()
4,317
309
566
2308ebf34faedaeeb14af9f1f59d6581114c19a0
10,756
py
Python
CryoMEM/run.py
SNU-HPCS/CryoModel
07a3fbe3f3d44c7960b5aed562a90e204014eea0
[ "MIT" ]
2
2021-05-26T12:32:46.000Z
2021-12-15T13:10:37.000Z
CryoMEM/run.py
SNU-HPCS/CryoModel
07a3fbe3f3d44c7960b5aed562a90e204014eea0
[ "MIT" ]
1
2022-03-02T01:49:20.000Z
2022-03-18T10:37:59.000Z
CryoMEM/run.py
SNU-HPCS/CryoModel
07a3fbe3f3d44c7960b5aed562a90e204014eea0
[ "MIT" ]
null
null
null
#!/usr/bin/env python3.8 from argparse import ArgumentParser import os, pgen from cacti import cacti from cacti.cacti_interface_pb2 import CactiInput if __name__ == '__main__': main()
72.187919
239
0.783098
#!/usr/bin/env python3.8 from argparse import ArgumentParser import os, pgen from cacti import cacti from cacti.cacti_interface_pb2 import CactiInput def model_cache(cacti_config_file, capacity, pgen_output): cacti_input = CactiInput () cacti_input.config_file = os.path.abspath(cacti_config_file) cacti_input.tech_param.cache_sz = capacity # change sram_cell transistor values. cacti_input.tech_param.sram_cell.R_nch_on = 1.45*pgen_output.user_input.Vdd / pgen_output.output_parameter.nmos.Ion cacti_input.tech_param.sram_cell.R_pch_on = 1.45*pgen_output.user_input.Vdd / pgen_output.output_parameter.pmos.Ion cacti_input.tech_param.sram_cell.Vdd = pgen_output.user_input.Vdd cacti_input.tech_param.sram_cell.Vth = pgen_output.output_parameter.nmos.Vth_on cacti_input.tech_param.sram_cell.I_on_n = pgen_output.output_parameter.nmos.Ion cacti_input.tech_param.sram_cell.I_on_p = pgen_output.output_parameter.pmos.Ion cacti_input.tech_param.sram_cell.I_off_n = pgen_output.output_parameter.nmos.Isub cacti_input.tech_param.sram_cell.I_off_p = pgen_output.output_parameter.pmos.Isub cacti_input.tech_param.sram_cell.I_g_on_n = pgen_output.output_parameter.nmos.Igate cacti_input.tech_param.sram_cell.I_g_on_p = pgen_output.output_parameter.pmos.Igate cacti_input.tech_param.sram_cell.n_to_p_eff_curr_drv_ratio = pgen_output.output_parameter.nmos.Ion / pgen_output.output_parameter.pmos.Ion # change peri_global transistor values (repeater/decoder/SA...). cacti_input.tech_param.peri_global.R_nch_on = 1.45*pgen_output.user_input.Vdd / pgen_output.output_parameter.nmos.Ion cacti_input.tech_param.peri_global.R_pch_on = 1.45*pgen_output.user_input.Vdd / pgen_output.output_parameter.pmos.Ion cacti_input.tech_param.peri_global.Vdd = pgen_output.user_input.Vdd cacti_input.tech_param.peri_global.Vth = pgen_output.output_parameter.nmos.Vth_on cacti_input.tech_param.peri_global.I_on_n = pgen_output.output_parameter.nmos.Ion cacti_input.tech_param.peri_global.I_on_p = pgen_output.output_parameter.pmos.Ion cacti_input.tech_param.peri_global.I_off_n = pgen_output.output_parameter.nmos.Isub cacti_input.tech_param.peri_global.I_off_p = pgen_output.output_parameter.pmos.Isub cacti_input.tech_param.peri_global.I_g_on_n = pgen_output.output_parameter.nmos.Igate cacti_input.tech_param.peri_global.I_g_on_p = pgen_output.output_parameter.pmos.Igate cacti_input.tech_param.peri_global.n_to_p_eff_curr_drv_ratio = pgen_output.output_parameter.nmos.Ion / pgen_output.output_parameter.pmos.Ion # change wire values. cacti_input.tech_param.wire_local.R_per_um_mult = (pgen_output.output_parameter.wire.Resistivity / pgen_output.output_parameter.wire_ref.Resistivity) cacti_input.tech_param.wire_inside_mat.R_per_um_mult = (pgen_output.output_parameter.wire.Resistivity / pgen_output.output_parameter.wire_ref.Resistivity) cacti_input.tech_param.wire_outside_mat.R_per_um_mult = (pgen_output.output_parameter.wire.Resistivity / pgen_output.output_parameter.wire_ref.Resistivity) cacti_input.tech_param.vpp = pgen_output.user_input.Vdd + pgen_output.user_input.Vth0 cacti_input.tech_param.dram_cell_Vdd = pgen_output.user_input.Vdd cacti_input.const_param.CU_RESISTIVITY = pgen_output.output_parameter.wire.Resistivity*1e-2*(0.022/0.018) cacti_input.const_param.BULK_CU_RESISTIVITY = pgen_output.output_parameter.wire.Resistivity*1e-2 cacti_print_stderr = True # cacti exec cacti_output_ = cacti (proto=cacti_input, print_stderr=cacti_print_stderr) print(cacti_output_) def model_dram(cacti_config_file, pgen_output, mode=0): cacti_input = CactiInput () cacti_input.config_file = os.path.abspath(cacti_config_file) cacti_input.tech_param.dram_acc.R_nch_on = 1.69*(pgen_output["wl"].user_input.Vdd + pgen_output["wl"].output_parameter.nmos.Vth0+0.5) / pgen_output["wl"].output_parameter.nmos.Ion cacti_input.tech_param.dram_acc.R_pch_on = 1.69*(pgen_output["wl"].user_input.Vdd + pgen_output["wl"].output_parameter.nmos.Vth0+0.5) / pgen_output["wl"].output_parameter.pmos.Ion cacti_input.tech_param.dram_acc.Vdd = pgen_output["wl"].user_input.Vdd cacti_input.tech_param.dram_acc.Vth = pgen_output["wl"].output_parameter.nmos.Vth0 cacti_input.tech_param.dram_acc.I_on_n = pgen_output["wl"].output_parameter.nmos.Ion cacti_input.tech_param.dram_acc.I_on_p = pgen_output["wl"].output_parameter.pmos.Ion cacti_input.tech_param.dram_acc.I_off_n = pgen_output["wl"].output_parameter.nmos.Isub cacti_input.tech_param.dram_acc.I_off_p = pgen_output["wl"].output_parameter.pmos.Isub cacti_input.tech_param.dram_acc.I_g_on_n = pgen_output["wl"].output_parameter.nmos.Igate cacti_input.tech_param.dram_acc.I_g_on_p = pgen_output["wl"].output_parameter.pmos.Igate cacti_input.tech_param.dram_acc.n_to_p_eff_curr_drv_ratio = pgen_output["wl"].output_parameter.nmos.Ion / pgen_output["wl"].output_parameter.pmos.Ion cacti_input.tech_param.dram_wl.R_nch_on = 1.69*(pgen_output["wl"].user_input.Vdd + pgen_output["wl"].output_parameter.nmos.Vth0 +0.5) / pgen_output["wl"].output_parameter.nmos.Ion cacti_input.tech_param.dram_wl.R_pch_on = 1.69*(pgen_output["wl"].user_input.Vdd + pgen_output["wl"].output_parameter.nmos.Vth0 +0.5) / pgen_output["wl"].output_parameter.pmos.Ion cacti_input.tech_param.dram_wl.Vdd = pgen_output["wl"].user_input.Vdd cacti_input.tech_param.dram_wl.Vth = pgen_output["wl"].output_parameter.nmos.Vth0 cacti_input.tech_param.dram_wl.I_on_n = pgen_output["wl"].output_parameter.nmos.Ion cacti_input.tech_param.dram_wl.I_on_p = pgen_output["wl"].output_parameter.pmos.Ion cacti_input.tech_param.dram_wl.I_off_n = pgen_output["wl"].output_parameter.nmos.Isub cacti_input.tech_param.dram_wl.I_off_p = pgen_output["wl"].output_parameter.pmos.Isub cacti_input.tech_param.dram_wl.I_g_on_n = pgen_output["wl"].output_parameter.nmos.Igate cacti_input.tech_param.dram_wl.I_g_on_p = pgen_output["wl"].output_parameter.pmos.Igate cacti_input.tech_param.dram_wl.n_to_p_eff_curr_drv_ratio = pgen_output["wl"].output_parameter.nmos.Ion / pgen_output["wl"].output_parameter.pmos.Ion cacti_input.tech_param.peri_global.R_nch_on = 1.49*pgen_output["hp"].user_input.Vdd / pgen_output["hp"].output_parameter.nmos.Ion cacti_input.tech_param.peri_global.R_pch_on = 1.49*pgen_output["hp"].user_input.Vdd / pgen_output["hp"].output_parameter.pmos.Ion cacti_input.tech_param.peri_global.Vdd = pgen_output["hp"].user_input.Vdd cacti_input.tech_param.peri_global.Vth = pgen_output["hp"].output_parameter.nmos.Vth_on cacti_input.tech_param.peri_global.I_on_n = pgen_output["hp"].output_parameter.nmos.Ion cacti_input.tech_param.peri_global.I_on_p = pgen_output["hp"].output_parameter.pmos.Ion cacti_input.tech_param.peri_global.I_off_n = pgen_output["hp"].output_parameter.nmos.Isub cacti_input.tech_param.peri_global.I_off_p = pgen_output["hp"].output_parameter.pmos.Isub cacti_input.tech_param.peri_global.I_g_on_n = pgen_output["hp"].output_parameter.nmos.Igate cacti_input.tech_param.peri_global.I_g_on_p = pgen_output["hp"].output_parameter.pmos.Igate cacti_input.tech_param.peri_global.n_to_p_eff_curr_drv_ratio = pgen_output["hp"].output_parameter.nmos.Ion / pgen_output["hp"].output_parameter.pmos.Ion cacti_input.tech_param.wire_local.R_per_um_mult = (pgen_output["hp"].output_parameter.wire.Resistivity / pgen_output["hp"].output_parameter.wire_ref.Resistivity) cacti_input.tech_param.wire_inside_mat.R_per_um_mult = (pgen_output["hp"].output_parameter.wire.Resistivity / pgen_output["hp"].output_parameter.wire_ref.Resistivity) cacti_input.tech_param.wire_outside_mat.R_per_um_mult = (pgen_output["hp"].output_parameter.wire.Resistivity / pgen_output["hp"].output_parameter.wire_ref.Resistivity) cacti_input.tech_param.vpp = pgen_output["wl"].user_input.Vdd + pgen_output["wl"].user_input.Vth0 cacti_input.tech_param.dram_cell_Vdd = pgen_output["wl"].user_input.Vdd cacti_input.const_param.CU_RESISTIVITY = pgen_output["hp"].output_parameter.wire.Resistivity*1e-2*(0.022/0.018) cacti_input.const_param.BULK_CU_RESISTIVITY = pgen_output["hp"].output_parameter.wire.Resistivity*1e-2 if mode == 1 or mode == 2: cacti_input.dyn_param_prefix = current_path () + ("/circuit_configs/%.2f%.2f%.2f%.2f" % (pgen_output["hp"].user_input.Vdd, pgen_output["hp"].user_input.Vth0, pgen_output["wl"].user_input.Vdd, pgen_output["wl"].user_input.Vth0)) cacti_input.wire_config = current_path () + ("/circuit_configs/%.2f%.2f%.2f%.2f_wire.txt" % (pgen_output["hp"].user_input.Vdd, pgen_output["hp"].user_input.Vth0, pgen_output["wl"].user_input.Vdd, pgen_output["wl"].user_input.Vth0)) # cacti exec if mode == 0 or mode == 1: cacti_output = cacti (proto=cacti_input, print_stderr=True) elif mode == 2: cacti_output = cacti (proto=cacti_input, print_stderr=True, reproduce=True) print(cacti_output) def parse_arguments(): parser = ArgumentParser() parser.add_argument('cacti_config_file', help='Config file for cacti') parser.add_argument('--pgen', help='Path for pgen', default='../CryoMOSFET/pgen.py') parser.add_argument('temperature', help='Target operating temperature (77-300 [K])', type=int) parser.add_argument('node', help='Technology node size [nm]', type=int) parser.add_argument('vdd', help='Supply voltage [V]', type=float) parser.add_argument('vth', help='Threshold voltage at 300K (i.e., Vth_300k) [V]', type=float) parser.add_argument('capacity', help='Size of the cache/memory [Bytes]', type=int) subparsers = parser.add_subparsers(help='Cell types') parser_dram = subparsers.add_parser('dram', help='DRAM memory') parser_dram.set_defaults(cell_type='dram') parser_dram.add_argument('acc_vdd', help='Supply voltage for access transistors [V]', type=float) parser_dram.add_argument('acc_vth', help='Threshold voltage for access transistors at 300K [V]', type=float) parser_sram = subparsers.add_parser('cache', help='cache') parser_sram.set_defaults(cell_type='cache') return parser.parse_args() def main(): args = parse_arguments() hp_results = pgen.run(args.pgen, pgen.mosfet_mode.HP, args.temperature, args.node, args.vdd, args.vth) if args.cell_type == 'dram': acc_results = pgen.run(args.pgen, pgen.mosfet_mode.ACC, args.temperature, args.node, args.acc_vdd, args.acc_vth) model_dram(args.cacti_config_file, {'hp': hp_results, 'wl': acc_results}) else: model_cache(args.cacti_config_file, args.capacity, hp_results) if __name__ == '__main__': main()
10,474
0
92
ef0e72237c1885c96dcd7cbcfb8813e6f24399d7
219
py
Python
algo/fizzbuzz.py
gsathya/dsalgo
61c89ec597ced3e69bfbb438fd856c8fc5f20aba
[ "MIT" ]
2
2017-02-25T04:05:29.000Z
2018-05-10T16:54:31.000Z
algo/fizzbuzz.py
gsathya/dsalgo
61c89ec597ced3e69bfbb438fd856c8fc5f20aba
[ "MIT" ]
null
null
null
algo/fizzbuzz.py
gsathya/dsalgo
61c89ec597ced3e69bfbb438fd856c8fc5f20aba
[ "MIT" ]
null
null
null
fizzbuzz()
16.846154
27
0.30137
def fizzbuzz(): for i in range(1, 101): s = "" if i % 3 == 0: s += "Fizz" if i % 5 == 0: s += "Buzz" if s == "": s = i print s fizzbuzz()
185
0
22
1e2311a60faaf10a98f1e9908e10657e12fcf455
2,261
py
Python
main/run.py
EverLookNeverSee/MFEWGANs
56e480432370bbb4fdc7723ee7c2306d4239c7fc
[ "MIT" ]
null
null
null
main/run.py
EverLookNeverSee/MFEWGANs
56e480432370bbb4fdc7723ee7c2306d4239c7fc
[ "MIT" ]
null
null
null
main/run.py
EverLookNeverSee/MFEWGANs
56e480432370bbb4fdc7723ee7c2306d4239c7fc
[ "MIT" ]
null
null
null
import torch from torch import nn, optim, ones, randn, zeros, cat from generator import Generator from discriminator import Discriminator from prep import train_loader, batch_size import matplotlib.pyplot as plt # Setting learning rate, number of epochs and loss function lr = 0.001 n_epochs = 300 loss_function = nn.BCELoss() # Instantiating generator = Generator() discriminator = Discriminator() # Setting optimization algorithm optimizer_discriminator = optim.Adam(discriminator.parameters(), lr=lr) optimizer_generator = optim.Adam(generator.parameters(), lr=lr) # Training process for epoch in range(n_epochs): for n, (real_samples, _) in enumerate(train_loader): # Data for training the discriminator real_samples_labels = ones((batch_size, 1)) latent_space_samples = randn((batch_size, 2)) generated_samples = generator(latent_space_samples) generated_samples_labels = zeros((batch_size, 1)) all_samples = cat((real_samples, generated_samples)) all_samples_labels = cat((real_samples_labels, generated_samples_labels)) # Training the discriminator discriminator.zero_grad() output_discriminator = discriminator(all_samples) loss_discriminator = loss_function( output_discriminator, all_samples_labels ) loss_discriminator.backward() optimizer_discriminator.step() # Data for training the generator latent_space_samples = randn((batch_size, 2)) # Training the generator generator.zero_grad() generated_samples = generator(latent_space_samples) output_discriminator_generated = discriminator(generated_samples) loss_generator = loss_function( output_discriminator_generated, real_samples_labels ) loss_generator.backward() optimizer_generator.step() # Show loss value if epoch % 10 == 0 and n == batch_size - 1: print(f"Epoch: {epoch} , Loss D: {loss_discriminator}") print(f"Epoch: {epoch} , Loss G: {loss_generator}") # Checking the samples generated by GAN generated_samples = generated_samples.detach() plt.plot(generated_samples[:, 0], generated_samples[:, 1], ".") plt.show()
33.746269
81
0.709863
import torch from torch import nn, optim, ones, randn, zeros, cat from generator import Generator from discriminator import Discriminator from prep import train_loader, batch_size import matplotlib.pyplot as plt # Setting learning rate, number of epochs and loss function lr = 0.001 n_epochs = 300 loss_function = nn.BCELoss() # Instantiating generator = Generator() discriminator = Discriminator() # Setting optimization algorithm optimizer_discriminator = optim.Adam(discriminator.parameters(), lr=lr) optimizer_generator = optim.Adam(generator.parameters(), lr=lr) # Training process for epoch in range(n_epochs): for n, (real_samples, _) in enumerate(train_loader): # Data for training the discriminator real_samples_labels = ones((batch_size, 1)) latent_space_samples = randn((batch_size, 2)) generated_samples = generator(latent_space_samples) generated_samples_labels = zeros((batch_size, 1)) all_samples = cat((real_samples, generated_samples)) all_samples_labels = cat((real_samples_labels, generated_samples_labels)) # Training the discriminator discriminator.zero_grad() output_discriminator = discriminator(all_samples) loss_discriminator = loss_function( output_discriminator, all_samples_labels ) loss_discriminator.backward() optimizer_discriminator.step() # Data for training the generator latent_space_samples = randn((batch_size, 2)) # Training the generator generator.zero_grad() generated_samples = generator(latent_space_samples) output_discriminator_generated = discriminator(generated_samples) loss_generator = loss_function( output_discriminator_generated, real_samples_labels ) loss_generator.backward() optimizer_generator.step() # Show loss value if epoch % 10 == 0 and n == batch_size - 1: print(f"Epoch: {epoch} , Loss D: {loss_discriminator}") print(f"Epoch: {epoch} , Loss G: {loss_generator}") # Checking the samples generated by GAN generated_samples = generated_samples.detach() plt.plot(generated_samples[:, 0], generated_samples[:, 1], ".") plt.show()
0
0
0
18ee4dedc3c8017c3845ee9f1b64b07f56693f60
1,871
py
Python
geolocation/entrypoint.py
summa-platform/summa-ui-stack
5c7875efb15b5bf23bc0175da39a8e680cf55c89
[ "MIT" ]
null
null
null
geolocation/entrypoint.py
summa-platform/summa-ui-stack
5c7875efb15b5bf23bc0175da39a8e680cf55c89
[ "MIT" ]
null
null
null
geolocation/entrypoint.py
summa-platform/summa-ui-stack
5c7875efb15b5bf23bc0175da39a8e680cf55c89
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 import os, sys, traceback import signal import asyncio from asyncio.subprocess import create_subprocess_exec, PIPE import aiohttp from service import load_config, run as service server_proc = None server_cmd = os.path.join(os.path.dirname(__file__), 'server.sh') server_name = 'twofishes' service_name = 'Geolocation' if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description='UI Stack %s Service Entrypoint' % service_name, formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--config', '-c', metavar='FILE', type=str, default='config.yaml', help='database configuration file') parser.add_argument('--verbose', '-v', action='store_true', help='verbose mode') args = parser.parse_args() config = load_config(args.config) try: loop = asyncio.get_event_loop() asyncio.ensure_future(run_server(loop=loop)) loop.run_until_complete(service(config, verbose=args.verbose)) except KeyboardInterrupt: print('INTERRUPTED') except: print('EXCEPTION') traceback.print_exc()
28.784615
153
0.719936
#!/usr/bin/env python3 import os, sys, traceback import signal import asyncio from asyncio.subprocess import create_subprocess_exec, PIPE import aiohttp from service import load_config, run as service server_proc = None server_cmd = os.path.join(os.path.dirname(__file__), 'server.sh') server_name = 'twofishes' service_name = 'Geolocation' def log(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) async def run_server(loop=None): global server_proc log('Starting %s server ...' % server_name) # ignore SIGINT in child process to allow to execute safe shutdown # https://stackoverflow.com/a/13737455 def preexec_fn(): # signal.signal(signal.SIGINT, signal.SIG_IGN) pass server_proc = await create_subprocess_exec(server_cmd, loop=loop, preexec_fn=preexec_fn) # server_proc = await create_subprocess_exec(server_cmd, stdin=PIPE, stdout=PIPE, loop=loop) # result, stderr = await asyncio.wait_for(server_proc.communicate(text), timeout=timeout) await server_proc.wait() return server_proc.returncode if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description='UI Stack %s Service Entrypoint' % service_name, formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--config', '-c', metavar='FILE', type=str, default='config.yaml', help='database configuration file') parser.add_argument('--verbose', '-v', action='store_true', help='verbose mode') args = parser.parse_args() config = load_config(args.config) try: loop = asyncio.get_event_loop() asyncio.ensure_future(run_server(loop=loop)) loop.run_until_complete(service(config, verbose=args.verbose)) except KeyboardInterrupt: print('INTERRUPTED') except: print('EXCEPTION') traceback.print_exc()
681
0
46
74d2dbb5550d360a8187475b772c1c7a03264372
270
py
Python
lcd/I2C_LCD1602/test.py
ianhom/mpy-lib
a3a103840e52251b54d31b3e4a1afc85b9976718
[ "MIT" ]
1
2019-03-19T13:40:47.000Z
2019-03-19T13:40:47.000Z
lcd/I2C_LCD1602/test.py
ianhom/mpy-lib
a3a103840e52251b54d31b3e4a1afc85b9976718
[ "MIT" ]
null
null
null
lcd/I2C_LCD1602/test.py
ianhom/mpy-lib
a3a103840e52251b54d31b3e4a1afc85b9976718
[ "MIT" ]
1
2020-07-04T09:01:08.000Z
2020-07-04T09:01:08.000Z
''' I2C LCD1602 demo Author: shaoziyang Date: 2018.2 http://www.micropython.org.cn ''' from machine import I2C import time l = LCD1620(I2C(1)) l.puts("Hello microbit!") n = 0 while 1: l.puts(str(n), 0, 1) n = n + 1 time.sleep_ms(1000)
12.857143
33
0.592593
''' I2C LCD1602 demo Author: shaoziyang Date: 2018.2 http://www.micropython.org.cn ''' from machine import I2C import time l = LCD1620(I2C(1)) l.puts("Hello microbit!") n = 0 while 1: l.puts(str(n), 0, 1) n = n + 1 time.sleep_ms(1000)
0
0
0
7bc905097f5ce9d25b6d011a2b1daedcbaa2eb6c
800
py
Python
src/cli.py
eycjur/python_project_template
a083f7c3eb1b400b92a0d0a63f15d89c5bcacfd5
[ "MIT" ]
null
null
null
src/cli.py
eycjur/python_project_template
a083f7c3eb1b400b92a0d0a63f15d89c5bcacfd5
[ "MIT" ]
1
2022-02-14T17:05:17.000Z
2022-02-18T21:57:23.000Z
src/cli.py
eycjur/python_project_template
a083f7c3eb1b400b92a0d0a63f15d89c5bcacfd5
[ "MIT" ]
null
null
null
"""各種pythonファイルをコマンドラインから利用するためのCLIツール See Also: - `typer`_ .. _typer: https://qiita.com/iisaka51/items/18bde4dada0827fbe81e Example: ヘルプ >>> `python cli.py --help` サブコマンドのヘルプ >>> `python cli.py [command] --help` Attention: _は-で実行する """ from typing import Optional import typer from src.add.add import add from src.config import settings # noqa app = typer.Typer() @app.command() def hello() -> None: """hello""" typer.echo("hello") @app.command() def sample( text: Optional[str] = typer.Option(None, "-t", "--text", help="出力する文字列") ) -> None: """メインコマンド""" print("text:", text) print(settings.cfg.is_debug_mode) print(add(3, 5)) typer_click_object = typer.main.get_command(app)
15.384615
76
0.64125
"""各種pythonファイルをコマンドラインから利用するためのCLIツール See Also: - `typer`_ .. _typer: https://qiita.com/iisaka51/items/18bde4dada0827fbe81e Example: ヘルプ >>> `python cli.py --help` サブコマンドのヘルプ >>> `python cli.py [command] --help` Attention: _は-で実行する """ from typing import Optional import typer from src.add.add import add from src.config import settings # noqa app = typer.Typer() @app.command() def hello() -> None: """hello""" typer.echo("hello") @app.command() def sample( text: Optional[str] = typer.Option(None, "-t", "--text", help="出力する文字列") ) -> None: """メインコマンド""" print("text:", text) print(settings.cfg.is_debug_mode) print(add(3, 5)) typer_click_object = typer.main.get_command(app) def main() -> None: typer_click_object()
23
0
23
7f4aa1aba6fb6250fd280920aef36bc8c844c35b
881
py
Python
src/steps/get_pig_data.py
allanwright/media-classifier
a0da0799cc0bd6ef7360012c362f9fab273286c6
[ "MIT" ]
2
2019-08-16T00:49:27.000Z
2021-08-15T16:37:45.000Z
src/steps/get_pig_data.py
allanwright/media-classifier
a0da0799cc0bd6ef7360012c362f9fab273286c6
[ "MIT" ]
1
2020-02-19T10:17:56.000Z
2020-07-26T09:42:49.000Z
src/steps/get_pig_data.py
allanwright/media-classifier
a0da0799cc0bd6ef7360012c362f9fab273286c6
[ "MIT" ]
1
2019-06-27T10:57:07.000Z
2019-06-27T10:57:07.000Z
'''Defines a pipeline step which aquires data from the pig data source. ''' import os from src import datasets from src.step import Step class GetPigData(Step): '''Defines a pipeline step which aquires data from the pig data source. ''' def __init__(self): '''Initializes a new instance of the GetPigData object. ''' super(GetPigData, self).__init__() self.input = { 'path': os.getenv('PIG_PATH'), } self.output = { 'Movies': 'data/raw/movies/pig.txt', 'Music': 'data/raw/music/pig.txt', 'TV Shows': 'data/raw/tv/pig.txt', } def run(self): '''Runs the pipeline step. ''' for (key, value) in self.output.items(): datasets.write_list_to_file( datasets.get_local_files(self.input['path'] % key), value)
24.472222
75
0.570942
'''Defines a pipeline step which aquires data from the pig data source. ''' import os from src import datasets from src.step import Step class GetPigData(Step): '''Defines a pipeline step which aquires data from the pig data source. ''' def __init__(self): '''Initializes a new instance of the GetPigData object. ''' super(GetPigData, self).__init__() self.input = { 'path': os.getenv('PIG_PATH'), } self.output = { 'Movies': 'data/raw/movies/pig.txt', 'Music': 'data/raw/music/pig.txt', 'TV Shows': 'data/raw/tv/pig.txt', } def run(self): '''Runs the pipeline step. ''' for (key, value) in self.output.items(): datasets.write_list_to_file( datasets.get_local_files(self.input['path'] % key), value)
0
0
0
61b59bd6953b5882224ae4180a0662ab506b4493
8,338
py
Python
app/rqalpha/views.py
sddthree/HHHH
5d6b876ead92db09e91b262a7b9b3c8cf947b7a8
[ "MIT" ]
1
2020-06-29T04:52:30.000Z
2020-06-29T04:52:30.000Z
app/rqalpha/views.py
sddthree/HHHH
5d6b876ead92db09e91b262a7b9b3c8cf947b7a8
[ "MIT" ]
null
null
null
app/rqalpha/views.py
sddthree/HHHH
5d6b876ead92db09e91b262a7b9b3c8cf947b7a8
[ "MIT" ]
1
2020-06-29T04:52:31.000Z
2020-06-29T04:52:31.000Z
from flask import render_template, session, redirect, url_for, Flask, request, flash, jsonify from numpy.core.multiarray import ndarray from . import rqalpha import os from multiprocessing import Process import sys sys.path.insert(0, "Z:\Hello\Work\Data\QT") from rqalpha import run_code from .. import db from ..models import Role, User, Strategy from flask_login import login_required, current_user import pickle as pk import numpy as np import time import datetime import json name = None @rqalpha.route('/result/<strategyname>', methods=['GET']) @login_required @rqalpha.route('/result', methods=['GET']) @login_required # noinspection PyGlobalUndefined @rqalpha.route("/result/weather", methods=["GET", "POST"]) @rqalpha.route("/hot", methods=["GET", "POST"])
39.330189
166
0.595107
from flask import render_template, session, redirect, url_for, Flask, request, flash, jsonify from numpy.core.multiarray import ndarray from . import rqalpha import os from multiprocessing import Process import sys sys.path.insert(0, "Z:\Hello\Work\Data\QT") from rqalpha import run_code from .. import db from ..models import Role, User, Strategy from flask_login import login_required, current_user import pickle as pk import numpy as np import time import datetime import json name = None @rqalpha.route('/result/<strategyname>', methods=['GET']) @login_required def result(strategyname): strategy = Strategy.query.filter_by( strategyname=strategyname, author=current_user._get_current_object()).first_or_404() start_date = strategy.startdate end_date = strategy.enddate stock = strategy.stock source_code = strategy.code return render_template('rqalpha/result.html', strategyname=strategyname, start_date=start_date, end_date=end_date, stock=stock, source_code=source_code) @rqalpha.route('/result', methods=['GET']) @login_required def new_result(): strategyname = "Demo" start_date = "2016-01-04" end_date = "2016-10-04" stock = "1000000" source_code = """ # 可以自己import我们平台支持的第三方python模块,比如pandas、numpy等。 # 在这个方法中编写任何的初始化逻辑。context对象将会在你的算法策略的任何方法之间做传递。 def init(context): context.s1 = "000001.XSHE" # 实时打印日志 logger.info("Interested at stock: " + str(context.s1)) # before_trading此函数会在每天交易开始前被调用,当天只会被调用一次 def before_trading(context, bar_dict): pass # 你选择的证券的数据更新将会触发此段逻辑,例如日或分钟历史数据切片或者是实时数据切片更新 def handle_bar(context, bar_dict): # 开始编写你的主要的算法逻辑javascript:void(0) # bar_dict[order_book_id] 可以拿到某个证券的bar信息 # context.portfolio 可以拿到现在的投资组合状态信息 # 使用order_shares(id_or_ins, amount)方法进行落单 # TODO: 开始编写你的算法吧! order_shares(context.s1, 1000) """ return render_template('rqalpha/result.html', strategyname=strategyname, start_date=start_date, end_date=end_date, stock=stock, source_code=source_code) def k_strategy(code, filename, start_date, end_date, account_stock, benchmark="000300.XSHG"): config = {"base": {"start_date": start_date, "end_date": end_date, "benchmark": benchmark, "accounts": {"stock": account_stock}}, "extra": {"log_level": "verbose", }, "mod": {"sys_analyser": {"enabled": True, "output_file": "Z:/Hello/Work/Data/QT/Rqalpha_test/HHH/app/static/test-result/" + filename}}} #"plot_save_file": "Z:/Hello/Work/Data/QT/Rqalpha_test/HHH/app/static/test-result/" + filename , run_code(code, config) def query_db(p, testNum=3): if testNum != 0: try: with open('Z:/Hello/Work/Data/QT/Rqalpha_test/HHH/app/static/test-result/' + name + str(p), 'rb') as f: m = pk.load(f) return m except FileNotFoundError: testNum -= 1 time.sleep(0.25) return query_db(p, testNum) else: return # noinspection PyGlobalUndefined @rqalpha.route("/result/weather", methods=["GET", "POST"]) def weather(): if name != None: if request.method == "POST": p = int(request.form['nm']) print(p) m = query_db(p) if m: i = (int(request.form['id'])) print("i", i) summary = m['summary'] total_returns = summary['total_returns'] annualized_returns = summary['annualized_returns'] benchmark_total_returns = summary['benchmark_total_returns'] benchmark_annualized_returns = summary[ 'benchmark_annualized_returns'] sharpe = summary['sharpe'] portfolio_1 = m['portfolio'][i:i + 300] benchmark_portfolio = m['benchmark_portfolio'][i:i + 300] date = [i for i in portfolio_1.unit_net_value.index] v1 = [i for i in portfolio_1.unit_net_value.values - 1] v2 = [i for i in benchmark_portfolio.unit_net_value.values - 1] portfolio = m['portfolio'][:i + 300] index = portfolio.index portfolio_value = portfolio.unit_net_value * portfolio.units xs = portfolio_value.values rt = portfolio.unit_net_value.values xs_max_accum = np.maximum.accumulate(xs) max_dd_end = np.argmax(xs_max_accum / xs) if max_dd_end == 0: max_dd_end = len(xs) - 1 tmp = (xs - xs_max_accum)[max_dd_end:] max_dd_start = np.argmax( xs[:max_dd_end]) if max_dd_end > 0 else 0 max_ddd_start_day = max_dd_start max_ddd_end_day = len( xs) - 1 if tmp.max() < 0 else np.argmax(tmp) + max_dd_end max_dd_info = "MaxDD {}~{}, {} days".format(str(index[max_dd_start]), str(index[max_dd_end]), (index[max_dd_end] - index[max_dd_start]).days) max_ddd_info = "MaxDDD {}~{}, {} days".format(str(index[max_ddd_start_day]), str(index[max_ddd_end_day]), (index[max_ddd_end_day] - index[max_ddd_start_day]).days) my_file = 'Z:/Hello/Work/Data/QT/Rqalpha_test/HHH/app/static/test-result/' + \ name + str(p) if os.path.exists(my_file): os.remove(my_file) else: date = [] v1 = [] v2 = [] total_returns = "" annualized_returns = "" benchmark_total_returns = "" benchmark_annualized_returns = "" sharpe = "" max_dd_info = "" max_ddd_info = "" else: date = [] v1 = [] v2 = [] total_returns = "" annualized_returns = "" benchmark_total_returns = "" benchmark_annualized_returns = "" sharpe = "" max_dd_info = "" max_ddd_info = "" return jsonify(month=date, evaporation=v1, precipitation=v2, total_returns=total_returns, annualized_returns=annualized_returns, benchmark_total_returns=benchmark_total_returns, benchmark_annualized_returns=benchmark_annualized_returns, sharpe=sharpe, maxDD=max_dd_info, maxDDD=max_ddd_info) # 返回json格式 @rqalpha.route("/hot", methods=["GET", "POST"]) def hot(): global name name = request.form.get('strategy_name') start_date = request.form.get('start_date') end_date = request.form.get('end_date') stock = request.form.get('stock_value') code = request.form.get('code') save_or_not = request.form.get('saveornot') if save_or_not == "true": strategy = Strategy.query.filter_by( strategyname=name, author=current_user._get_current_object()).first() if strategy is not None: db.session.delete(strategy) db.session.commit() db.session.add(Strategy(strategyname=name, startdate=datetime.datetime.strptime(start_date, "%Y-%m-%d"), enddate=datetime.datetime.strptime(end_date, "%Y-%m-%d"), stock=int(stock), code=code, author=current_user._get_current_object())) db.session.commit() else: strategy = Strategy(strategyname=name, startdate=datetime.datetime.strptime(start_date, "%Y-%m-%d"), enddate=datetime.datetime.strptime( end_date, "%Y-%m-%d"), stock=int(stock), code=code, author=current_user._get_current_object()) db.session.add(strategy) db.session.commit() flash('Your strategy has been saved successfully.') for i in range(20): my_file = 'Z:/Hello/Work/Data/QT/Rqalpha_test/HHH/app/static/test-result/' + \ name + str(i - 1) if os.path.exists(my_file): os.remove(my_file) p = Process(target=k_strategy, args=( code, name, start_date, end_date, int(stock))) p.start() return 'ok'
7,820
0
134
6b11159fe08c9faa679e52125037dd3d213c4984
4,169
py
Python
src/sprint_webserver/views/live.py
langrenn-sprint/sprint-webserver
065a96d102a6658e5422ea6a0be5abde4b6558e1
[ "Apache-2.0" ]
null
null
null
src/sprint_webserver/views/live.py
langrenn-sprint/sprint-webserver
065a96d102a6658e5422ea6a0be5abde4b6558e1
[ "Apache-2.0" ]
15
2021-01-11T19:42:39.000Z
2021-04-19T21:09:58.000Z
src/sprint_webserver/views/live.py
langrenn-sprint/sprint-webserver
065a96d102a6658e5422ea6a0be5abde4b6558e1
[ "Apache-2.0" ]
null
null
null
"""Resource module for live view.""" import logging from aiohttp import web import aiohttp_jinja2 from sprint_webserver.services import ( DeltakereService, InnstillingerService, KjoreplanService, KlasserService, ResultatHeatService, StartListeService, ) class Live(web.View): """Class representing the live view.""" # TODO: reduser kompleksistet i denne funksjonen async def get(self) -> web.Response: # noqa: C901 """Get route function that return the live result page.""" _lopsinfo = await InnstillingerService().get_header_footer_info( self.request.app["db"], ) logging.debug(_lopsinfo) try: valgt_klasse = self.request.rel_url.query["klasse"] logging.debug(valgt_klasse) except Exception: valgt_klasse = "" try: valgt_startnr = self.request.rel_url.query["startnr"] except Exception: valgt_startnr = "" klasser = await KlasserService().get_all_klasser(self.request.app["db"]) deltakere = await DeltakereService().get_deltakere_by_lopsklasse( self.request.app["db"], valgt_klasse ) logging.debug(deltakere) kjoreplan = [] startliste = [] resultatliste = [] colseparators = [] colclass = "w3-third" if valgt_startnr == "": kjoreplan = await KjoreplanService().get_heat_for_live_scroll( self.request.app["db"], valgt_klasse ) # responsive design - determine column-arrangement colseparators = ["KA1", "KA5", "SC1", "SA1", "F1", "F5", "A1", "A5"] icolcount = 0 for heat in kjoreplan: if heat["Heat"] in colseparators: icolcount += 1 if (heat["Heat"] == "SC1") and heat["resultat_registrert"]: colseparators.remove("SC1") elif heat["Heat"] in {"FA", "FB", "FC"}: icolcount += 1 colseparators.append(heat["Heat"]) break if icolcount == 4: colclass = "w3-quart" colseparators.remove("KA1") colseparators.remove("F1") startliste = await StartListeService().get_startliste_by_lopsklasse( self.request.app["db"], valgt_klasse ) logging.debug(startliste) resultatliste = await ResultatHeatService().get_resultatheat_by_klasse( self.request.app["db"], valgt_klasse ) else: # only selected racer logging.debug(valgt_startnr) startliste = await StartListeService().get_startliste_by_nr( self.request.app["db"], valgt_startnr, ) logging.debug(startliste) for start in startliste: _heat = await KjoreplanService().get_heat_by_index( self.request.app["db"], start["Heat"], ) kjoreplan.append(_heat) if valgt_klasse == "": valgt_klasse = start["Løpsklasse"] logging.info(valgt_klasse) # check for resultat resultatliste = await ResultatHeatService().get_resultatheat_by_nr( self.request.app["db"], valgt_startnr, ) valgt_startnr = "Startnr: " + valgt_startnr + ", " """Get route function.""" return await aiohttp_jinja2.render_template_async( "live.html", self.request, { "lopsinfo": _lopsinfo, "valgt_klasse": valgt_klasse, "valgt_startnr": valgt_startnr, "colseparators": colseparators, "colclass": colclass, "klasser": klasser, "deltakere": deltakere, "kjoreplan": kjoreplan, "resultatliste": resultatliste, "startliste": startliste, }, )
32.570313
83
0.53562
"""Resource module for live view.""" import logging from aiohttp import web import aiohttp_jinja2 from sprint_webserver.services import ( DeltakereService, InnstillingerService, KjoreplanService, KlasserService, ResultatHeatService, StartListeService, ) class Live(web.View): """Class representing the live view.""" # TODO: reduser kompleksistet i denne funksjonen async def get(self) -> web.Response: # noqa: C901 """Get route function that return the live result page.""" _lopsinfo = await InnstillingerService().get_header_footer_info( self.request.app["db"], ) logging.debug(_lopsinfo) try: valgt_klasse = self.request.rel_url.query["klasse"] logging.debug(valgt_klasse) except Exception: valgt_klasse = "" try: valgt_startnr = self.request.rel_url.query["startnr"] except Exception: valgt_startnr = "" klasser = await KlasserService().get_all_klasser(self.request.app["db"]) deltakere = await DeltakereService().get_deltakere_by_lopsklasse( self.request.app["db"], valgt_klasse ) logging.debug(deltakere) kjoreplan = [] startliste = [] resultatliste = [] colseparators = [] colclass = "w3-third" if valgt_startnr == "": kjoreplan = await KjoreplanService().get_heat_for_live_scroll( self.request.app["db"], valgt_klasse ) # responsive design - determine column-arrangement colseparators = ["KA1", "KA5", "SC1", "SA1", "F1", "F5", "A1", "A5"] icolcount = 0 for heat in kjoreplan: if heat["Heat"] in colseparators: icolcount += 1 if (heat["Heat"] == "SC1") and heat["resultat_registrert"]: colseparators.remove("SC1") elif heat["Heat"] in {"FA", "FB", "FC"}: icolcount += 1 colseparators.append(heat["Heat"]) break if icolcount == 4: colclass = "w3-quart" colseparators.remove("KA1") colseparators.remove("F1") startliste = await StartListeService().get_startliste_by_lopsklasse( self.request.app["db"], valgt_klasse ) logging.debug(startliste) resultatliste = await ResultatHeatService().get_resultatheat_by_klasse( self.request.app["db"], valgt_klasse ) else: # only selected racer logging.debug(valgt_startnr) startliste = await StartListeService().get_startliste_by_nr( self.request.app["db"], valgt_startnr, ) logging.debug(startliste) for start in startliste: _heat = await KjoreplanService().get_heat_by_index( self.request.app["db"], start["Heat"], ) kjoreplan.append(_heat) if valgt_klasse == "": valgt_klasse = start["Løpsklasse"] logging.info(valgt_klasse) # check for resultat resultatliste = await ResultatHeatService().get_resultatheat_by_nr( self.request.app["db"], valgt_startnr, ) valgt_startnr = "Startnr: " + valgt_startnr + ", " """Get route function.""" return await aiohttp_jinja2.render_template_async( "live.html", self.request, { "lopsinfo": _lopsinfo, "valgt_klasse": valgt_klasse, "valgt_startnr": valgt_startnr, "colseparators": colseparators, "colclass": colclass, "klasser": klasser, "deltakere": deltakere, "kjoreplan": kjoreplan, "resultatliste": resultatliste, "startliste": startliste, }, )
0
0
0
8835673acaaceac0726d62a70686959775168460
5,216
py
Python
scripts/search/DropNAS.py
zhengxiawu/XNAS
ea8f8ab31f67155482f5b9a9ad2a0b54c45f45d1
[ "MIT" ]
22
2020-07-01T02:12:01.000Z
2020-09-24T05:32:08.000Z
scripts/search/DropNAS.py
zhengxiawu/XNAS
ea8f8ab31f67155482f5b9a9ad2a0b54c45f45d1
[ "MIT" ]
null
null
null
scripts/search/DropNAS.py
zhengxiawu/XNAS
ea8f8ab31f67155482f5b9a9ad2a0b54c45f45d1
[ "MIT" ]
5
2020-07-09T06:53:18.000Z
2020-08-15T13:15:14.000Z
"""DropNAS searching""" from torch import device import torch.nn as nn import xnas.core.config as config import xnas.logger.logging as logging import xnas.logger.meter as meter from xnas.core.config import cfg from xnas.core.builder import * # DropNAS from xnas.algorithms.DropNAS import * from xnas.runner.trainer import DartsTrainer from xnas.runner.optimizer import darts_alpha_optimizer # Load config and check config.load_configs() logger = logging.get_logger(__name__) class DropNAS_Trainer(DartsTrainer): """Trainer for DropNAS. Rewrite the train_epoch with DropNAS's double-losses policy. """ if __name__ == "__main__": main()
38.637037
124
0.653758
"""DropNAS searching""" from torch import device import torch.nn as nn import xnas.core.config as config import xnas.logger.logging as logging import xnas.logger.meter as meter from xnas.core.config import cfg from xnas.core.builder import * # DropNAS from xnas.algorithms.DropNAS import * from xnas.runner.trainer import DartsTrainer from xnas.runner.optimizer import darts_alpha_optimizer # Load config and check config.load_configs() logger = logging.get_logger(__name__) def main(): device = setup_env() search_space = space_builder() criterion = criterion_builder().to(device) evaluator = evaluator_builder() [train_loader, valid_loader] = construct_loader() # init models darts_controller = DropNAS_CNNController(search_space, criterion).to(device) # init optimizers w_optim = optimizer_builder("SGD", darts_controller.weights()) a_optim = darts_alpha_optimizer("Adam", darts_controller.alphas()) lr_scheduler = lr_scheduler_builder(w_optim) # init recorders dropnas_trainer = DropNAS_Trainer( darts_controller=darts_controller, architect=None, criterion=criterion, lr_scheduler=lr_scheduler, w_optim=w_optim, a_optim=a_optim, train_loader=train_loader, valid_loader=valid_loader, ) # load checkpoint or initial weights start_epoch = dropnas_trainer.darts_loading() if cfg.SEARCH.AUTO_RESUME else 0 # start training dropnas_trainer.start() for cur_epoch in range(start_epoch, cfg.OPTIM.MAX_EPOCH): # train epoch drop_rate = 0. if cur_epoch < cfg.OPTIM.WARMUP_EPOCH else cfg.DROPNAS.DROP_RATE logger.info("Current drop rate: {:.6f}".format(drop_rate)) dropnas_trainer.train_epoch(cur_epoch, drop_rate) # test epoch if (cur_epoch+1) % cfg.EVAL_PERIOD == 0 or (cur_epoch+1) == cfg.OPTIM.MAX_EPOCH: # NOTE: the source code of DropNAS does not use test codes. # recording genotype and alpha to logger logger.info("=== Optimal genotype at epoch: {} ===".format(cur_epoch)) logger.info(dropnas_trainer.model.genotype()) logger.info("=== alphas at epoch: {} ===".format(cur_epoch)) dropnas_trainer.model.print_alphas(logger) if evaluator: evaluator(dropnas_trainer.model.genotype()) dropnas_trainer.finish() class DropNAS_Trainer(DartsTrainer): """Trainer for DropNAS. Rewrite the train_epoch with DropNAS's double-losses policy. """ def __init__(self, darts_controller, architect, criterion, w_optim, a_optim, lr_scheduler, train_loader, valid_loader): super().__init__(darts_controller, architect, criterion, w_optim, a_optim, lr_scheduler, train_loader, valid_loader) def train_epoch(self, cur_epoch, drop_rate): self.model.train() lr = self.lr_scheduler.get_last_lr()[0] cur_step = cur_epoch * len(self.train_loader) self.writer.add_scalar('train/lr', lr, cur_step) self.train_meter.iter_tic() for cur_iter, (trn_X, trn_y) in enumerate(self.train_loader): trn_X, trn_y = trn_X.to(self.device), trn_y.to(self.device, non_blocking=True) # forward pass loss self.a_optimizer.zero_grad() self.optimizer.zero_grad() preds = self.model(trn_X, drop_rate=drop_rate) loss1 = self.criterion(preds, trn_y) loss1.backward() nn.utils.clip_grad_norm_(self.model.weights(), cfg.OPTIM.GRAD_CLIP) self.optimizer.step() if cur_epoch >= cfg.OPTIM.WARMUP_EPOCH: self.a_optimizer.step() # weight decay loss self.a_optimizer.zero_grad() self.optimizer.zero_grad() loss2 = self.model.weight_decay_loss(cfg.OPTIM.WEIGHT_DECAY) \ + self.model.alpha_decay_loss(cfg.DARTS.ALPHA_WEIGHT_DECAY) loss2.backward() nn.utils.clip_grad_norm_(self.model.weights(), cfg.OPTIM.GRAD_CLIP) self.optimizer.step() self.a_optimizer.step() self.model.adjust_alphas() loss = loss1 + loss2 # Compute the errors top1_err, top5_err = meter.topk_errors(preds, trn_y, [1, 5]) loss, top1_err, top5_err = loss.item(), top1_err.item(), top5_err.item() self.train_meter.iter_toc() # Update and log stats self.train_meter.update_stats(top1_err, top5_err, loss, lr, trn_X.size(0)) self.train_meter.log_iter_stats(cur_epoch, cur_iter) self.train_meter.iter_tic() self.writer.add_scalar('train/loss', loss, cur_step) self.writer.add_scalar('train/top1_error', top1_err, cur_step) self.writer.add_scalar('train/top5_error', top5_err, cur_step) cur_step += 1 # Log epoch stats self.train_meter.log_epoch_stats(cur_epoch) self.train_meter.reset() # saving model if (cur_epoch + 1) % cfg.SAVE_PERIOD == 0: self.saving(cur_epoch) if __name__ == "__main__": main()
4,480
0
76
8aa680d96036fbe70c9149414c6bb52189390211
3,334
py
Python
vendor/ansible-module-openshift/library/openshift_policy.py
appuio/ansible-role-openshift-haproxy
f1f0752cbbc67b33a0e533328d3f0cd4ece4b03b
[ "Apache-2.0" ]
null
null
null
vendor/ansible-module-openshift/library/openshift_policy.py
appuio/ansible-role-openshift-haproxy
f1f0752cbbc67b33a0e533328d3f0cd4ece4b03b
[ "Apache-2.0" ]
null
null
null
vendor/ansible-module-openshift/library/openshift_policy.py
appuio/ansible-role-openshift-haproxy
f1f0752cbbc67b33a0e533328d3f0cd4ece4b03b
[ "Apache-2.0" ]
1
2018-09-01T16:26:23.000Z
2018-09-01T16:26:23.000Z
#!/usr/bin/python import json from ansible.module_utils.basic import * if __name__ == "__main__": main()
31.752381
151
0.637672
#!/usr/bin/python import json class PolicyModule: def __init__(self, module): self.module = module self.changed = False self.msg = [] for key in module.params: setattr(self, key, module.params[key]) def update(self): if self.cluster_roles: (rc, stdout, stderr) = self.module.run_command('oc export clusterrolebinding -o json', check_rc=True) roleBindings = json.loads(stdout) for cluster_role in self.cluster_roles: if self.groups: self.update_role_binding(roleBindings, cluster_role, 'group', self.groups) if self.users: self.update_role_binding(roleBindings, cluster_role, 'user', self.users) if self.sccs: (rc, stdout, stderr) = self.module.run_command('oc export scc -o json', check_rc=True) securityContextConstraints = json.loads(stdout) for scc in self.sccs: if self.groups: self.update_scc(securityContextConstraints, scc, 'group', self.groups) if self.users: self.update_scc(securityContextConstraints, scc, 'user',self.users) def update_role_binding(self, roleBindings, cluster_role, principal_type, principals): cmd = 'oc adm policy ' if self.state == 'present': cmd += 'add-cluster-role-to-' + principal_type else: cmd += 'remove-cluster-role-from-' + principal_type changedPrincipals = [] for principal in principals: roleBinding = [rb for rb in roleBindings['items'] if rb['roleRef']['name'] == cluster_role and principal in (rb[principal_type + 'Names'] or [])] if bool(roleBinding) != (self.state == 'present'): changedPrincipals.append(principal) if changedPrincipals: self.changed = True args = cmd + " " + cluster_role + " " + " ".join(changedPrincipals) self.msg.append(args + "; ") if not self.module.check_mode: (rc, stdout, stderr) = self.module.run_command(args, check_rc=True) def update_scc(self, securityContextConstraints, scc, principal_type, principals): cmd = 'oc adm policy ' if self.state == 'present': cmd += 'add-scc-to-' + principal_type else: cmd += 'remove-scc-from-' + principal_type changedPrincipals = [] for principal in principals: inScc = [s for s in securityContextConstraints['items'] if s['metadata']['name'] == scc and principal in (s[principal_type + 's'] or [])] if bool(inScc) != (self.state == 'present'): changedPrincipals.append(principal) if changedPrincipals: self.changed = True args = cmd + " " + scc + " " + " ".join(changedPrincipals) self.msg.append(args + "; ") if not self.module.check_mode: (rc, stdout, stderr) = self.module.run_command(args, check_rc=True) def main(): module = AnsibleModule( argument_spec=dict( state = dict(default='present', choices=['present', 'absent']), cluster_roles = dict(type='list'), sccs = dict(type='list'), groups = dict(type='list'), users = dict(type='list'), ), supports_check_mode=True ) policy = PolicyModule(module) policy.update() module.exit_json(changed=policy.changed, msg=" ".join(policy.msg)) from ansible.module_utils.basic import * if __name__ == "__main__": main()
3,074
-2
146
e91cfd35f65fbc83a61bfdd147a857bae1e095df
960
py
Python
LeetCode/weekly-contest-153-2019.10.18/makeArrayIncreasing_1187.py
Max-PJB/python-learning2
e8b05bef1574ee9abf8c90497e94ef20a7f4e3bd
[ "MIT" ]
null
null
null
LeetCode/weekly-contest-153-2019.10.18/makeArrayIncreasing_1187.py
Max-PJB/python-learning2
e8b05bef1574ee9abf8c90497e94ef20a7f4e3bd
[ "MIT" ]
null
null
null
LeetCode/weekly-contest-153-2019.10.18/makeArrayIncreasing_1187.py
Max-PJB/python-learning2
e8b05bef1574ee9abf8c90497e94ef20a7f4e3bd
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """ ------------------------------------------------- @ Author : pengj @ date : 2019/10/22 11:00 @ IDE : PyCharm @ GitHub : https://github.com/JackyPJB @ Contact : pengjianbiao@hotmail.com ------------------------------------------------- Description : ------------------------------------------------- """ import time from typing import List __author__ = 'Max_Pengjb' start_time = time.time() # 下面写上代码块 # 上面中间写上代码块 end_time = time.time() print('Running time: %s Seconds' % (end_time - start_time)) aa = [1, 2, 3, 4]
24.615385
134
0.486458
#!/usr/bin/env python # -*- coding: utf-8 -*- """ ------------------------------------------------- @ Author : pengj @ date : 2019/10/22 11:00 @ IDE : PyCharm @ GitHub : https://github.com/JackyPJB @ Contact : pengjianbiao@hotmail.com ------------------------------------------------- Description : ------------------------------------------------- """ import time from typing import List __author__ = 'Max_Pengjb' start_time = time.time() # 下面写上代码块 class Solution: def makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int: arr2.sort() j = 0 # TODO dp问题 没太看懂 # # https://leetcode-cn.com/problems/make-array-strictly-increasing/solution/dp-zhi-kao-lu-dang-qian-he-dang-qian-de-shang-yi-g/ pass # 上面中间写上代码块 end_time = time.time() print('Running time: %s Seconds' % (end_time - start_time)) aa = [1, 2, 3, 4]
280
-6
48
ab7cb840d2ccde935078d73cd40c92201d21147f
4,267
py
Python
Python/DLL.py
AlexandroM1234/DataStructures-Algorithms
1a8dd1be69928266da3f50d1c86ad7be5980e205
[ "MIT" ]
null
null
null
Python/DLL.py
AlexandroM1234/DataStructures-Algorithms
1a8dd1be69928266da3f50d1c86ad7be5980e205
[ "MIT" ]
null
null
null
Python/DLL.py
AlexandroM1234/DataStructures-Algorithms
1a8dd1be69928266da3f50d1c86ad7be5980e205
[ "MIT" ]
null
null
null
class DoublyLinkedList: """ Time Complexity: Insertion = O(1) Removal = O(1) Searching = O(N) Access = O(N) Most of the logic is the same as the SLL except dealing with the extra prev point """ def push(self,val): """ Adds a new Node at the end of the DLL """ newNode = Node(val) if not self.head: self.head = newNode self.tail = self.head else: curTail = self.tail curTail.next = newNode newNode.prev = curTail self.tail = newNode self.length += 1 return self def pop(self): """ remove a node from the tail """ if not self.head: return None prevTail = self.tail if self.length == 1: self.head = None self.tail = None else: self.tail = prevTail.prev prevTail.prev = None self.tail.next = None self.length -= 1 return prevTail def shift(self): """ remove a node from the beginning of the Dll """ if not self.head: return None prevHead = self.head if self.length == 1: self.head = None self.tail = None else: self.head = prevHead.next prevHead.next = None prevHead.prev = None self.length -= 1 return prevHead def unshift(self,val): """ add a node at the beginning of the DLL """ newHead = Node(val) if not self.head: self.head = newHead self.tail = self.head else: self.head.prev = newHead newHead.next = self.head self.head = newHead self.length += 1 return self def get(self,index): """ get a node from a given index """ if index < 0 or index >= self.length: return None current = None half = self.length / 2 if index < half: counter = 0 current = self.head while counter != index: current = current.next counter += 1 else: counter = self.length - 1 current = self.tail while counter != index: current = current.prev counter -= 1 return current def setNode(self,index,val): """ set a node's value given its index and a new value """ node = self.get(index) if not node: return None node.val = val return node def insert(self,index,val): """ insert a new node at a given index """ if index < 0 or index > self.length: return False if index == 0: self.unshift(val) return True elif index == self.length: self.push(val) return True else: newNode = Node(val) prev = self.get(index-1) after = prev.next prev.next = newNode newNode.prev = prev newNode.next = after after.prev = newNode self.length += 1 return True def remove(self,index): """ remove a node from a given index """ if index < 0 or index >= self.length: return None if index == 0: return self.shift() elif index == self.length - 1: return self.pop() else: before = self.get(index-1) remove = before.next after = remove.next before.next = after after.prev = before remove.prev = None remove.next = None self.length -= 1 return remove DLL = DoublyLinkedList() DLL.push("val") DLL.push("val2") DLL.push("val3") print(DLL.setNode(1,"newval")) while DLL.head: print(DLL.head.val) DLL.head = DLL.head.next
24.66474
85
0.483947
class Node: def __init__(self,val): self.val = val self.next = None class DoublyLinkedList: """ Time Complexity: Insertion = O(1) Removal = O(1) Searching = O(N) Access = O(N) Most of the logic is the same as the SLL except dealing with the extra prev point """ def __init__(self): self.head = None self.tail = None self.length = 0 def push(self,val): """ Adds a new Node at the end of the DLL """ newNode = Node(val) if not self.head: self.head = newNode self.tail = self.head else: curTail = self.tail curTail.next = newNode newNode.prev = curTail self.tail = newNode self.length += 1 return self def pop(self): """ remove a node from the tail """ if not self.head: return None prevTail = self.tail if self.length == 1: self.head = None self.tail = None else: self.tail = prevTail.prev prevTail.prev = None self.tail.next = None self.length -= 1 return prevTail def shift(self): """ remove a node from the beginning of the Dll """ if not self.head: return None prevHead = self.head if self.length == 1: self.head = None self.tail = None else: self.head = prevHead.next prevHead.next = None prevHead.prev = None self.length -= 1 return prevHead def unshift(self,val): """ add a node at the beginning of the DLL """ newHead = Node(val) if not self.head: self.head = newHead self.tail = self.head else: self.head.prev = newHead newHead.next = self.head self.head = newHead self.length += 1 return self def get(self,index): """ get a node from a given index """ if index < 0 or index >= self.length: return None current = None half = self.length / 2 if index < half: counter = 0 current = self.head while counter != index: current = current.next counter += 1 else: counter = self.length - 1 current = self.tail while counter != index: current = current.prev counter -= 1 return current def setNode(self,index,val): """ set a node's value given its index and a new value """ node = self.get(index) if not node: return None node.val = val return node def insert(self,index,val): """ insert a new node at a given index """ if index < 0 or index > self.length: return False if index == 0: self.unshift(val) return True elif index == self.length: self.push(val) return True else: newNode = Node(val) prev = self.get(index-1) after = prev.next prev.next = newNode newNode.prev = prev newNode.next = after after.prev = newNode self.length += 1 return True def remove(self,index): """ remove a node from a given index """ if index < 0 or index >= self.length: return None if index == 0: return self.shift() elif index == self.length - 1: return self.pop() else: before = self.get(index-1) remove = before.next after = remove.next before.next = after after.prev = before remove.prev = None remove.next = None self.length -= 1 return remove DLL = DoublyLinkedList() DLL.push("val") DLL.push("val2") DLL.push("val3") print(DLL.setNode(1,"newval")) while DLL.head: print(DLL.head.val) DLL.head = DLL.head.next
122
-10
74
814c8136025e552852402cb37f5ee2ee78e8dbae
385
py
Python
tests/test_tushare_api.py
xuan-wang/funcat
c4b184942564ab8a4092acb4907ab069fc44683c
[ "Apache-2.0" ]
18
2019-05-30T01:00:38.000Z
2022-01-03T15:46:25.000Z
tests/test_tushare_api.py
xuan-wang/funcat
c4b184942564ab8a4092acb4907ab069fc44683c
[ "Apache-2.0" ]
5
2019-05-28T15:01:18.000Z
2021-11-24T14:08:39.000Z
tests/test_tushare_api.py
xuan-wang/funcat
c4b184942564ab8a4092acb4907ab069fc44683c
[ "Apache-2.0" ]
8
2020-10-30T10:03:02.000Z
2021-12-04T07:20:36.000Z
import tushare as ts import time start = time.time() df = ts.pro_bar(ts_code='300851.SZ', adj='qfq', start_date='20200714', end_date='20200716') t0 = time.time() - start print(t0) print(df) arr = df.to_records() start = time.time() df = ts.get_k_data("603488", start='2020-07-14', end='2020-07-16', index=False, ktype='D', autype='qfq') t0 = time.time() - start print(t0) print(df)
22.647059
104
0.677922
import tushare as ts import time start = time.time() df = ts.pro_bar(ts_code='300851.SZ', adj='qfq', start_date='20200714', end_date='20200716') t0 = time.time() - start print(t0) print(df) arr = df.to_records() start = time.time() df = ts.get_k_data("603488", start='2020-07-14', end='2020-07-16', index=False, ktype='D', autype='qfq') t0 = time.time() - start print(t0) print(df)
0
0
0