def generate_closeness_matrices(self): ''' Generates p2p_dicts [] :return: ''' for count, tim in enumerate(self.tim_dict): # if len(self.tim_dict[tim]['players'].keys()) < 22: # continue for c, team in enumerate(self.p2p_dicts): range_type = True if int( self.tim_dict[tim]['hasball_team_id'] ) == self.analyzer.teams[c].id else False for player in team: for friend in team[player]: if player == friend: continue if self.range_calculator(range_type, tim, player, friend): team[player][friend] += 1 self.analyzer.closeness_matrices = [ Commons.dict_to_matrix(self.p2p_dicts[0], self.analyzer.teams[0].get_player_names(), True), Commons.dict_to_matrix(self.p2p_dicts[1], self.analyzer.teams[1].get_player_names(), True) ]
def plot(self): print '#' * 49 print '#' * 49 pprint.pprint('PLOTTING') print '#' * 49 print '#' * 49 names = self.shorten_names() grid = gridspec.GridSpec(1, 1) fig = plt.figure() ax1 = fig.add_subplot(grid[0, 0]) plt.xticks(size=15) plt.yticks(size=15) matrix = Commons.dict_to_matrix(self.closeness_matrix, self.keys) self.matrix = matrix im = ax1.imshow(matrix, cmap='Greens') plt.colorbar(im) ax1.set_title("Closeness Matrix", size=15) ax1.set_xticks(np.arange(0, 11, 1)) ax1.set_yticks(np.arange(0, 11, 1)) ax1.set_xticklabels(names) ax1.set_yticklabels(names) for tick in ax1.get_xticklabels(): tick.set_rotation(-90) plt.savefig("close1.pdf", bbox_inches='tight') grid = gridspec.GridSpec(1, 1) fig = plt.figure() ax2 = fig.add_subplot(grid[0, 0]) matrix = Commons.dict_to_matrix(self.pass_matrix, self.keys) im = ax2.imshow(matrix, cmap='Greens') plt.colorbar(im) ax2.set_title("Pass Counts Matrix", size=15) ax2.set_xticks(np.arange(0, 11, 1)) ax2.set_yticks(np.arange(0, 11, 1)) ax2.set_xticklabels(names) ax2.set_yticklabels(names) for tick in ax2.get_xticklabels(): tick.set_rotation(-90) plt.savefig("pass1.pdf", bbox_inches='tight') grid = gridspec.GridSpec(1, 1) fig = plt.figure() ax2 = fig.add_subplot(grid[0, 0]) matrix = Commons.dict_to_matrix(self.marking_matrix, self.keys) im = ax2.imshow(matrix, cmap='Greens') plt.colorbar(im) ax2.set_title("Marking Matrix", size=15) ax2.set_xticks(np.arange(0, 11, 1)) ax2.set_yticks(np.arange(0, 11, 1)) ax2.set_xticklabels(names) ax2.set_yticklabels(names) for tick in ax2.get_xticklabels(): tick.set_rotation(-90) plt.savefig("mark1.pdf", bbox_inches='tight')
def __init__(self, update=False, id=None, timeval=None, taskval=None): super(CalendarWindow, self).__init__() self.setGeometry(300, 300, 400, 400) if update: self.setWindowTitle("Edit Task") else: self.setWindowTitle("Add Task") self.reminder_data = {} self.commons = Commons() self._id = id self._timeval = timeval self._taskval = taskval self.init_ui() self.update = update
def range_calculator(self, range_type, tim, player1, player2): if self.tim_dict[tim]['players'].get(player1) is None or \ self.tim_dict[tim]['players'].get(player2) is None: return False point1 = self.tim_dict[tim]['players'][player1] point2 = self.tim_dict[tim]['players'][player2] if not sum(point1) or not sum(point2): return False if range_type: return Commons.is_in_range(point1, point2) return Commons.is_in_range_def(point1, point2)
def __init__(self, get_type='Single', game=None): home_name = Commons.get_team_abb(game['home']['name']) away_name = Commons.get_team_abb(game['away']['name']) team_abbs = (home_name, away_name) team_names = (game['home']['name'], game['away']['name']) self.db_data = [] self.match_id = game['id'] self.ball_data = [] self.conn = MySqlConnection() self.pkl_loader = None self.get_type = get_type self.team_names = team_names self.team_abbs = team_abbs
def generate_pass_matrices(self): for c, team in enumerate(self.p2p_dicts): for cnt, row in enumerate(self.analyzer.ball_data[:-1]): if self.check_conditions(row, self.analyzer.ball_data[cnt + 1]): self.add_to_matrix(self.analyzer.teams[c], team, row, self.analyzer.ball_data[cnt + 1]) self.analyzer.pass_matrices = [ Commons.dict_to_matrix(self.p2p_dicts[0], self.analyzer.teams[0].get_player_names(), True), Commons.dict_to_matrix(self.p2p_dicts[1], self.analyzer.teams[1].get_player_names(), True) ]
def send_unsent_batch(): global __db_con global __db_cur try: __db_con.row_factory = lite.Row __db_cur = __db_con.cursor() rows = __db_cur.execute( "SELECT timestamp, temp AS temperature FROM temperatures WHERE sent = 0" ).fetchall() json_history = json.dumps([dict(ix) for ix in rows]) req = requests.post( "<YOUR_FIREBASE_FUNCTIONS_ENDPOINT>/batchTemperatureUpdate", headers={ 'content-type': 'application/json', 'x-serial': '%s' } % Commons.getserial(), data=json_history) if req.status_code == requests.codes.ok: __db_cur.execute("UPDATE temperatures SET sent = 1 WHERE sent = 0") __db_con.commit() else: print("Erro ao enviar batch") except lite.Error, e: print "Error %s:" % e.args[0]
def find_beginning_of_attacking_transaction(self, event_time): sec_keys = sorted(self.secs_secs.keys()) init_hasball_team = 0 time_list = [] time = event_time gap = 0 while True: # 3 saniyelik bir boşluk var burada keseceğiz. if gap == 4: # print 'returns at %d because gap of 4' % time return list(reversed(time_list)) # Veri bozulduysa return if time not in sec_keys: # print 'Found a gap at %d' % time, gap += 1 time = Commons.decrease_time(time) continue else: gap = 0 hasball_team = self.find_who_has_ball(time) # Olay anında topun kimde olduğunu bulalım. if not init_hasball_team and hasball_team: init_hasball_team = hasball_team elif not init_hasball_team and not hasball_team: gap += 1 # Topa sahip takım değiştiyse return if hasball_team != init_hasball_team: # print 'returns at %d because hasball changed' % time return list(reversed(time_list)) time_list.append(time) # 1 saniye geri gidelim. time = Commons.decrease_time(time) # Devrenin başına geldiysek return if time < 0: # print 'returns at %d because we are at beginning of half' % time return list(reversed(time_list))
class Inference: def __init__(self): self.class_to_name = {0: 'Non Corona', 1: 'Corona'} self.utils = Commons() self.model = self.utils.prepare_model() def get_prediction(self, image_bytes): try: proc_img = self.utils.preprocess(image_bytes) output = self.model.forward(proc_img) except Exception: return 0, 'error in getting prediction!' conf_scores = softmax(output, dim=1) _, prediction = output.max(1) pred_class = prediction.item() pred_cls_name = self.class_to_name[pred_class] conf_scr = conf_scores.data.numpy()[0, pred_class] return pred_class, pred_cls_name, conf_scr
def prepare_dist_flow(self, time_list, is_home): player_names = self.analyzer.teams[ 0 if is_home else 1].get_player_names() dist_flow = [ Commons.dict_to_matrix(self.secs_secs[x]['dist_matrix'], player_names, is_normalize=False) for x in time_list ] # return self.interpolate_dist_flow(time_list, dist_flow) return dist_flow
def interpolate_event_flow(self, time_list, event_flow): new_event_flow = [] for c, time in enumerate(time_list[:-1]): new_event_flow.append(event_flow[c]) if time != Commons.decrease_time(time_list[c + 1]): gap = 0 inter_time = Commons.increase_time(time) while inter_time != time_list[c + 1]: gap += 1 inter_time = Commons.increase_time(inter_time) wfrob_diff = event_flow[c + 1] - event_flow[c] for i in range(1, gap + 1): new_event_flow.append(event_flow[c] + (wfrob_diff / (gap + 1)) * i) new_event_flow.append(event_flow[-1]) return new_event_flow
def __init__(self, game_info, game_events_by_type): # Analyzers self.closeness_analyzer = None self.marking_analyzer = None self.pass_analyzer = None # Analyzed matrices self.closeness_matrices = [] self.pass_matrices = [] self.marking_matrices = [] # Data collectors self.game_data_collector = None self.ball_data_collector = None # Home and away team data holders self.teams = None self.team_ids = [] self.events = [] # Position data holder self.game_data = None self.ball_data = None self.pass_matrices = [] # All games events list self.events_by_type = game_events_by_type # Helper fields self.pickled = False self.matrix_plotter = MatrixPlotter() self.sec_splitter_index = 0 self.weight_matrices = {} self.printed = False self.team_names = [] self.pickle_loader = PickleLoader( "matrix_%s_%s" % (Commons.get_team_abb(game_info['home']['name']), Commons.get_team_abb(game_info['away']['name'])))
def send_fermentation_settings(): config = ConfigParser.RawConfigParser() try: config.read('fermentation.properties') except ConfigParser.Error: print("Error opening fermentation.properties. Missing?") settings_data = json.dumps( {Commons.getserial(): dict(config.items('Settings'))}) req = requests.post("<YOUR_FIREBASE_FUNCTIONS_ENDPOINT>/fermentationData", headers={'content-type': 'application/json'}, data=settings_data) if req.status_code == requests.codes.ok: print "Fermentation settings sent!" else: print("Error sending fermentation data :(")
def prepare_bot(exchange: str, user: str): settings = load_settings(user) commons = Commons(user, settings['ema_spans_minutes']) all_coins = set(flatten([s.split('/') for s in commons.cc.markets])) settings['coins'] = [c for c in settings['coins'] if c in all_coins] all_margin_pairs = [ f"{e['base']}/{e['quote']}" for e in commons.cc.sapi_get_margin_allpairs() ] settings['symbols'] = [ s for c in settings['coins'] if (s := f"{c}/{settings['quot']}") in all_margin_pairs ] commons.init(settings['symbols']) receiver_funcs = [commons.update_ema] vwap = Vwap(commons, settings) vwap.init() receiver_funcs.append(vwap.on_update) commons.start_call_limiter() streamer = Streamer(settings, receiver_funcs) return commons, vwap, streamer
from commons import Commons from command_builder import CommandBuilder import subprocess import json import sys commons = Commons() command_builder = CommandBuilder() cmd = command_builder.build_get_voter_table(5, 'b1') json = commons.get_correct_json_from_cmd(cmd, 'rows') print(json) cmd = command_builder.build_get_account('b1') ret = commons.get_correct_account_response_from_cmd(cmd, 'total') if ret is None: print("Problem with getting account balance") else: print("Account balance is: %s" % ret) cmd = command_builder.build_get_account('patreosxxxxx') ret = commons.get_correct_account_response_from_cmd(cmd, 'total') if ret is None: print("Problem with cmd: `%s`" % (' '.join(cmd)), file=sys.stderr) else: print("Account balance is: %s" % ret) tokens = commons.safe_split("patreosxxxxx,20", ',', 2) print(tokens[0]) cmd = command_builder.build_get_voter_table(1)
from google.cloud import pubsub from commons import Commons import time from threading import Thread import command_processor CMD_TOPIC = "command-" + Commons.getserial() SUBS_NAME = "command_rcv" pubsub_client = None def topic_exist(): global pubsub_client for topic in pubsub_client.list_topics(): if topic.name == CMD_TOPIC: return True return False def create_topic(topic_name): """Create a new Pub/Sub topic.""" global pubsub_client topic = pubsub_client.topic(topic_name) topic.create() print('Topic {} created.'.format(topic.name))
import json import subprocess import time from pprint import pprint import datetime from commons import Commons from command_builder import CommandBuilder today = datetime.datetime.now().strftime("%Y-%m-%d") #today = '2018-08-30' step_size = 100 debug = True commons = Commons() command_builder = CommandBuilder() cmd = command_builder.build_get_stake_table(1) first_record = commons.get_correct_json_from_cmd(cmd, 'rows', False) user = first_record['rows'][0]['scope'] old_user = '' f = open('./data/staker_accounts_%s.txt' % today, 'w') pprint("Starting with staker: %s" % user) f.write('%s\n' % user) while user != old_user: cmd = command_builder.build_get_stake_table(step_size, user) json_result = commons.get_correct_json_from_cmd(cmd, 'rows') if json_result is None: raise ValueError('Could not get valid json response for user: %s!' % user)
class CalendarWindow(QMainWindow): def __init__(self, update=False, id=None, timeval=None, taskval=None): super(CalendarWindow, self).__init__() self.setGeometry(300, 300, 400, 400) if update: self.setWindowTitle("Edit Task") else: self.setWindowTitle("Add Task") self.reminder_data = {} self.commons = Commons() self._id = id self._timeval = timeval self._taskval = taskval self.init_ui() self.update = update def init_ui(self): self.init_calendar() self.init_lineedit() self.init_pushbuttons() self.init_timedit() self.show() def init_calendar(self): try: self.date = QDate() self.calendar = QCalendarWidget(self) self.calendar.adjustSize() self.calendar.setMinimumDate(self.date.currentDate()) except Exception as err: print(err) def init_lineedit(self): self.text = QLineEdit(self) self.text.setMaxLength(250) self.text.setGeometry(5, 310, 40, 40) self.text.setFixedWidth(350) if not self.update: self._taskval = "Enter Task Description" self.text.setPlaceholderText(self._taskval) else: self.text.setText(self._taskval) def init_pushbuttons(self): self.OK = QtWidgets.QPushButton(self) self.OK.setText("OK") self.OK.move(195, 360) self.OK.clicked.connect(self.show_main) self.Cancel = QtWidgets.QPushButton(self) self.Cancel.setText("Cancel") self.Cancel.move(295, 360) self.Cancel.clicked.connect(self.close) def init_timedit(self): self.time = QTime() self.tedit = QTimeEdit(self) if not self.update: self._timeval = self.time.currentTime() else: self._timeval = QtCore.QTime.fromString(self._timeval, 'HH:mm:ss') self.tedit.setTime(self._timeval) self.tedit.move(5, 260) def show_main(self): try: selected_date = self.calendar.selectedDate() print(self.calendar.selectedDate()) selected_time = self.tedit.time() print(selected_time.toString()) print(self.text.text()) self.reminder_data['Selected_Date'] = selected_date.toString() self.reminder_data['Selected_Time'] = selected_time.toString() self.reminder_data['Task_Description'] = self.text.text() print("From Calendar: ", self.reminder_data) if self.update: self.commons.prepare_json(self.reminder_data, self._id) else: self.commons.prepare_json(self.reminder_data) self.close() except Exception as err: print(err)
from commons import Commons import sqlite3 as lite from network_status import NetworkStatus import NetworkManager import json import requests from threading import Thread import ConfigParser __devices = {} __d_args = ('sender', 'destination', 'interface', 'member', 'path') __d_args = dict([(x + '_keyword', 'd_' + x) for x in __d_args]) TEMP_TOPIC = "smarthomebrew/sensor/temperatura" SERIAL_NUMBER = Commons.getserial() __network_status = NetworkStatus() __db_con = None __db_cur = None __topic = None def on_connect(client, data, rc): client.subscribe([(TEMP_TOPIC, 0)]) def on_message(client, userdata, msg): if __network_status.is_connected(): publish_temp_cloud(msg.payload) else: save_temperature(msg.payload, False)
def animate_strength(self, i): self.cs_im.set_array( Commons.dict_to_matrix(self.p2p_data[i / 10], self.names, is_normalize=False))
#!/usr/bin/python from commons import Commons from log import Log from network import Network from report import Report appliation = Commons() appliation.bootstrapApplication()
import subprocess import time import re import datetime import sys from commons import Commons from command_builder import CommandBuilder commons = Commons() command_builder = CommandBuilder() today = datetime.datetime.now().strftime("%Y-%m-%d") #today = '2018-09-19' input_snapshot_file = './data/20180924_account_snapshot.csv' output_results_file = './data/voter_balances_%s.txt' % today p = open(output_results_file, 'a') output_balance_errors_file = './data/voter_balance_errors_%s.txt' % today e = open(output_balance_errors_file, 'a') input_accounts_file = './data/voter_accounts_%s.txt' % today #input_accounts_file = './data/missing_users_2018-08-13.txt' with open(input_accounts_file, 'r') as f: for line in f: line = line.rstrip() tokens = commons.safe_split(line, ',', 2) user = tokens[0] producers = tokens[1] if commons.is_blank(user):
def __init__(self): self.class_to_name = {0: 'Non Corona', 1: 'Corona'} self.utils = Commons() self.model = self.utils.prepare_model()
def check_conditions(self, *args): return Commons.check_same_team(*args) and \ Commons.check_different_player(*args) and \ Commons.check_few_sec_pass(*args)
import subprocess import time import re import datetime import sys import json from decimal import * from commons import Commons from command_builder import CommandBuilder commons = Commons() command_builder = CommandBuilder() today = datetime.datetime.now().strftime("%Y-%m-%d") #today = '2018-09-19' input_accounts_file = './data/staker_accounts_%s.txt' % today data = [] with open(input_accounts_file, 'r') as f: for line in f: line = line.rstrip() user = line if commons.is_blank(user): print("No user found when splitting: `%s`" % line, file=sys.stderr) continue cmd = [ '/Users/okayplanet/dev/eos/eos/build/programs/cleos/cleos',
import subprocess import time import re import datetime from decimal import Decimal from colors import Colors from commons import Commons import math commons = Commons() color = Colors() fg = color.fg() today = datetime.datetime.now().strftime("%Y-%m-%d") today = '2018-09-19' # user,producer_num,balance output_results_file = './data/airdrop_results_%s.txt' % today def cyan(stmt): return fg.lightcyan + str(stmt) + color.reset def purple(stmt): return fg.purple + str(stmt) + color.reset def yellow(stmt): return fg.yellow + str(stmt) + color.reset total_supply = Decimal(2000000000) airdrop_supply = Decimal(1200000000) max_drop_ratio = Decimal(20) user_base_cap_eos = 10000
import subprocess import time import re import datetime import sys from commons import Commons from command_builder import CommandBuilder commons = Commons() command_builder = CommandBuilder() today = datetime.datetime.now().strftime("%Y-%m-%d") today = '2018-10-01' # time,account,balance input_snapshot_file = './data/%s_account_snapshot.csv' % today # user,producer_num,balance output_results_file = './data/voter_balances_%s.txt' % today p = open(output_results_file, 'a') # user,producer_num output_balance_errors_file = './data/voter_balance_errors_%s.txt' % today e = open(output_balance_errors_file, 'a') # account,staked,producers input_accounts_file = './data/voters%s.csv' % today #input_accounts_file = './data/missing_users_2018-08-13.txt' with open(input_accounts_file, 'r') as f: for line in f: line = line.rstrip()
import subprocess import time import re import datetime import sys from commons import Commons from decimal import Decimal commons = Commons() today = datetime.datetime.now().strftime("%Y-%m-%d") today = '2018-10-01' # user,producer_num,balance output_results_file = './data/airdrop_results_%s.txt' % today total = Decimal(0) with open(output_results_file, 'r') as f: for line in f: line = line.rstrip() tokens = commons.safe_split_limit(line, ',', 2) balance = tokens[1] total = total + Decimal(balance) print('%s' % total)