content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
import torch import torch.optim as optim from torch.optim.lr_scheduler import LambdaLR from allenact.algorithms.onpolicy_sync.losses import PPO from allenact.algorithms.onpolicy_sync.losses.imitation import Imitation from allenact.algorithms.onpolicy_sync.losses.ppo import PPOConfig from allenact.utils.experiment_utils import ( Builder, PipelineStage, TrainingPipeline, LinearDecay, ) from projects.tutorials.object_nav_ithor_ppo_one_object import ( ObjectNavThorPPOExperimentConfig, )
[ 11748, 28034, 198, 11748, 28034, 13, 40085, 355, 6436, 198, 6738, 28034, 13, 40085, 13, 14050, 62, 1416, 704, 18173, 1330, 21114, 6814, 35972, 198, 198, 6738, 477, 268, 529, 13, 282, 7727, 907, 13, 261, 30586, 62, 27261, 13, 22462, 27...
2.914286
175
from numpy import array from pickle import load from pandas import read_csv import os from BioCAT.src.Combinatorics import multi_thread_shuffling, multi_thread_calculating_scores, make_combine, get_score, get_max_aminochain, skipper # Importing random forest model modelpath = os.path.dirname(os.path.abspath(__file__)) + '/RFC.dump' Rf = load(open(modelpath, 'rb')) # The function generate list of shuflled matrix def make_shuffle_matrix(matrix, cpu, iterat): """ The functuion generate massive of shuffled matrix. Parameters ---------- matrix : pandas DataFrame PSSM profile. cpu : int Number of tred used. iterat : int Number of iterations of shuffling. Returns ------- module_shuffling_matrix : list List of matrix, shuffled by module. substrate_shuffling_matrix : list List of matrix, shuffled by substrate. """ module_shuffling_matrix = multi_thread_shuffling(matrix, ShufflingType='module', iterations=iterat, threads=cpu) substrate_shuffling_matrix = multi_thread_shuffling(matrix, ShufflingType='substrate', iterations=iterat, threads=cpu) return module_shuffling_matrix, substrate_shuffling_matrix # The fujnction finds suquence with maximum possible value, results from alignment def get_MaxSeq(matrix, variant_seq): """ The functuion parallel calculation of scores for shuffled matrix. Parameters ---------- matrix : pandas DataFrame PSSM profile. variant_seq : list Variant of core peptide chain. Returns ------- shuffled_scores : list List of scores for shuffled matrix. """ MaxSeq = [] subs = matrix.keys()[1: ] # Find sequence, wich have maximum alignment score for idx in matrix.index: MAX_value = max(list(matrix.iloc[idx][1:])) for key in subs: if matrix[key][idx] == MAX_value: MaxSeq.append(key) # If two smonomer have same value break # Making two variants of MaxSeq MaxSeq_full = MaxSeq.copy() MaxSeq_nan = MaxSeq.copy() for max_sub_idx in range(len(MaxSeq)): if variant_seq[max_sub_idx] == 'nan': MaxSeq_nan[max_sub_idx] = 'nan' # Adding nan to MaxSeq return MaxSeq_full, MaxSeq_nan # The function gives an information about clusters def get_cluster_info(table, BGC_ID, target_file): """ The functuion return information about cluster. Parameters ---------- table : pandas DataFrame Table with meta inforamtion about NRPS clusters. BGC_ID : str PSSM cluster ID. target_file : pandas DataFrame PSSM profile. Returns ------- Name : str Cluster ID. Coord_cluster : str Coordinate of cluster. strand : str Strand of cluster. """ for ind in table[table['ID'].str.contains(BGC_ID)].index: Name = table[table['ID'].str.contains(target_file.split('.')[0].split('_A_')[1])]['Name'][ind] Coord_cluster = table['Coordinates of cluster'][ind] strand = table['Gen strand'][ind] break return Name, Coord_cluster, strand # Calculate scores def calculate_scores(variant_seq, matrix, substrate_shuffling_matrix, module_shuffling_matrix, cpu, iterat): """ Calculating scores. Parameters ---------- variant_seq : list Variant of core peptide chain. matrix : pandas DataFrame PSSM profile. substrate_shuffling_matrix : list List of matrix, shuffled by substrate. module_shuffling_matrix : list List of matrix, shuffled by module. cpu : int Number of threads used. iterat : int Number of iterations of shuffling. Returns ------- Sln_score : float Mln_score : float Slt_score : float Mlt_score : float Sdn_score : float Mdn_score : float Sdt_score : float Mdt_score : float Scores, which calculated with shuffling matrix by different variants. M - module shuffling S - substrate shuffling l - logarithmic transformation of score d - raw score n - MaxSeq with nan replacement t - MaxSeq without nan replacement Relative_score : float Relative score (Probability of target class) Binary : float Binary score of cluster matching. """ # Finding suquence with maximum possible value, results from alignment MaxSeq_full, MaxSeq_nan = get_MaxSeq(matrix, variant_seq) # Calculating shuffled scores Sln_shuffled_score = array(multi_thread_calculating_scores(MaxSeq_nan, substrate_shuffling_matrix, type_value='log', iterations=iterat, threads=cpu)) Mln_shuffled_score = array(multi_thread_calculating_scores(MaxSeq_nan, module_shuffling_matrix, type_value='log', iterations=iterat, threads=cpu)) Slt_shuffled_score = array(multi_thread_calculating_scores(MaxSeq_full, substrate_shuffling_matrix, type_value='log', iterations=iterat, threads=cpu)) Mlt_shuffled_score = array(multi_thread_calculating_scores(MaxSeq_full, module_shuffling_matrix, type_value='log', iterations=iterat, threads=cpu)) Sdn_shuffled_score = array(multi_thread_calculating_scores(MaxSeq_nan, substrate_shuffling_matrix, type_value=None, iterations=iterat, threads=cpu)) Mdn_shuffled_score = array(multi_thread_calculating_scores(MaxSeq_nan, module_shuffling_matrix, type_value=None, iterations=iterat, threads=cpu)) Sdt_shuffled_score = array(multi_thread_calculating_scores(MaxSeq_full, substrate_shuffling_matrix, type_value=None, iterations=iterat, threads=cpu)) Mdt_shuffled_score = array(multi_thread_calculating_scores(MaxSeq_full, module_shuffling_matrix, type_value=None, iterations=iterat, threads=cpu)) # Calculating scores for target sequence log_target_score = get_score(variant_seq, matrix, type_value='log') non_log_target_score = get_score(variant_seq, matrix, type_value=None) # Calculating features scores Sln_score = len(Sln_shuffled_score[Sln_shuffled_score < log_target_score])/len(Sln_shuffled_score) Mln_score = len(Mln_shuffled_score[Mln_shuffled_score < log_target_score])/len(Mln_shuffled_score) Slt_score = len(Slt_shuffled_score[Slt_shuffled_score < log_target_score])/len(Slt_shuffled_score) Mlt_score = len(Mlt_shuffled_score[Mlt_shuffled_score < log_target_score])/len(Mlt_shuffled_score) Sdn_score = len(Sdn_shuffled_score[Sdn_shuffled_score < non_log_target_score])/len(Sdn_shuffled_score) Mdn_score = len(Mdn_shuffled_score[Mdn_shuffled_score < non_log_target_score])/len(Mdn_shuffled_score) Sdt_score = len(Sdt_shuffled_score[Sdt_shuffled_score < non_log_target_score])/len(Sdt_shuffled_score) Mdt_score = len(Mdt_shuffled_score[Mdt_shuffled_score < non_log_target_score])/len(Mdt_shuffled_score) # Calculating Relative score Relative_score = round(Rf.predict_proba([[Sln_score, Mln_score, Sdn_score, Mdn_score, Sdt_score, Mdt_score, Slt_score, Mlt_score ]])[0][1], 3) Binary = Rf.predict([[Sln_score, Mln_score, Sdn_score, Mdn_score, Sdt_score, Mdt_score, Slt_score, Mlt_score ]])[0] return Sln_score, Mln_score, Slt_score, Mlt_score, Sdn_score, Mdn_score, Sdt_score, Mdt_score, Relative_score, Binary def give_results(tsv_out, folder, files, table, ID, PeptideSeq, skip, cpu, iterat): """ The functuion return information about cluster. Parameters ---------- tsv_out : dict Empty dictionary for adding results. folder : str Path to PSSMs. files : list List of PSSMs. table : pandas DataFrame Table with meta inforamtion about NRPS clusters. ID : str Name of substance. PeptideSeq : dict Core peptide chains for different biosynthesis types (e.g. A, B, or C). kip : int Number of presumptive skip. cpu : int Number of threads used. iterat : int Number of iterations of shuffling. Returns ------- tsv_out : dict Full dictionary for adding results. """ for target_file in files: try: BGC_ID = target_file.split('.')[0].split('_A_')[1] except: continue if '_A_' not in target_file: continue Name, Coord_cluster, strand = get_cluster_info(table, BGC_ID, target_file) # Getting information about cluster BGC = read_csv(folder + target_file, sep='\t') # Skipping mode if skip == 0: BGC = [BGC] else: BGC == skipper(BGC, skip) for matrix in BGC: # Check quality of matrix if len(matrix) == 1: continue check = 0 values = matrix.drop(matrix.columns[0], axis=1).values for i in values: if all(i) == 0: check += 1 if check == len(values): # If thes condition is True, the matrix of unrecognized monomers continue # Generating shuffling matrix module_shuffling_matrix, substrate_shuffling_matrix = make_shuffle_matrix(matrix, cpu, iterat) for BS_type in PeptideSeq:# For every biosynthesis profile pathways if PeptideSeq[BS_type] == None: # If in sequence only nan monomers continue if len(PeptideSeq[BS_type]) == 0: # If have not the variant continue # Check correctness of PeptideSeq length_max= get_max_aminochain(PeptideSeq[BS_type]) EPs = make_combine(PeptideSeq[BS_type], length_max, matrix, delta=3) if EPs is None: # If length sequnce can't be scaled to cluster size continue for variant_seq in EPs: Sln_score, Mln_score, Slt_score, Mlt_score, Sdn_score, Mdn_score, Sdt_score, Mdt_score, Relative_score, Binary = calculate_scores(variant_seq, matrix, substrate_shuffling_matrix, module_shuffling_matrix, cpu, iterat) #Recordind dictionary tsv_out['Chromosome ID'].append(Name) tsv_out['Coordinates of cluster'].append(Coord_cluster) tsv_out['Strand'].append(strand) tsv_out['Substance'].append(ID) tsv_out['BGC ID'].append(BGC_ID) tsv_out['Putative linearized NRP sequence'].append('--'.join(variant_seq)) tsv_out['Biosynthesis profile'].append('Type {}'.format(BS_type)) tsv_out['Sln score'].append(Sln_score) #shaffling substrates in matrix with log score and nan in maximally possible sequence tsv_out['Mln score'].append(Mln_score) #shaffling modules matrix with log score and nan in maximally possible sequence tsv_out['Sdn score'].append(Sdn_score) #shaffling substrates matrix without log score and nan in maximally possible sequence tsv_out['Mdn score'].append(Mdn_score) #shaffling modules matrix without log score and nan in maximally possible sequence tsv_out['Sdt score'].append(Sdt_score) #shaffling substrates matrix without log score in maximally possible sequence tsv_out['Mdt score'].append(Mdt_score) #shaffling modules matrix without log score in maximally possible sequence tsv_out['Slt score'].append(Slt_score) #shaffling substrates matrix with log score in maximally possible sequence tsv_out['Mlt score'].append(Mlt_score) #shaffling modules matrix with log score in maximally possible sequence tsv_out['Relative score'].append(Relative_score) #Final score tsv_out['Binary'].append(Binary) #Binary value return tsv_out
[ 6738, 299, 32152, 1330, 7177, 198, 6738, 2298, 293, 1330, 3440, 198, 6738, 19798, 292, 1330, 1100, 62, 40664, 198, 11748, 28686, 198, 6738, 16024, 34, 1404, 13, 10677, 13, 20575, 20900, 873, 1330, 5021, 62, 16663, 62, 1477, 1648, 1359, ...
2.253336
5,471
# built-in from typing import Optional # app from .common import TOKENS, Extractor, Token, traverse from .value import UNKNOWN, get_value get_returns = Extractor() inner_extractor = Extractor()
[ 2, 3170, 12, 259, 198, 6738, 19720, 1330, 32233, 198, 198, 2, 598, 198, 6738, 764, 11321, 1330, 5390, 42, 16938, 11, 29677, 273, 11, 29130, 11, 38138, 198, 6738, 764, 8367, 1330, 4725, 44706, 11, 651, 62, 8367, 628, 198, 1136, 62, ...
3.333333
60
# retired ibmqx2_c_to_tars =\ { 0: [1, 2], 1: [2], 2: [], 3: [2, 4], 4: [2] } # 6 edges # retired ibmqx4_c_to_tars =\ { 0: [], 1: [0], 2: [0, 1, 4], 3: [2, 4], 4: [] } # 6 edges # retired ibmq16Rus_c_to_tars = \ { 0: [], 1: [0, 2], 2: [3], 3: [4, 14], 4: [], 5: [4], 6: [5, 7, 11], 7: [10], 8: [7], 9: [8, 10], 10: [], 11: [10], 12: [5, 11, 13], 13: [4, 14], 14: [], 15: [0, 2, 14] } # 22 edges ibm20AustinTokyo_c_to_tars = \ { 0: [1, 5], 1: [0, 2, 6, 7], 2: [1, 3, 6, 7], 3: [2, 4, 8, 9], 4: [3, 8, 9], 5: [0, 6, 10, 11], 6: [1, 2, 5, 7, 10, 11], 7: [1, 2, 6, 8, 12, 13], 8: [3, 4, 7, 9, 12, 13], 9: [3, 4, 8, 14], 10: [5, 6, 11, 15], 11: [5, 6, 10, 12, 16, 17], 12: [7, 8, 11, 13, 16, 17], 13: [7, 8, 12, 14, 18, 19], 14: [9, 13, 18, 19], 15: [10, 16], 16: [11, 12, 15, 17], 17: [11, 12, 16, 18], 18: [13, 14, 17, 19], 19: [13, 14, 18] } # 86 edges ibmq5YorktownTenerife_c_to_tars = \ { 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 4], 3: [2, 4], 4: [2, 3] } # 12 edges ibmq14Melb_c_to_tars = \ { 0: [1], 1: [0, 2, 13], 2: [1, 3, 12], 3: [2, 4, 11], 4: [3, 5, 10], 5: [4, 6, 9], 6: [5, 8], 7: [8], 8: [6, 7, 9], 9: [5, 8, 10], 10: [4, 9, 11], 11: [3, 10, 12], 12: [2, 11, 13], 13: [1, 12] } # 36 edges
[ 198, 2, 9880, 198, 571, 76, 80, 87, 17, 62, 66, 62, 1462, 62, 83, 945, 796, 59, 198, 90, 198, 220, 220, 220, 657, 25, 685, 16, 11, 362, 4357, 198, 220, 220, 220, 352, 25, 685, 17, 4357, 198, 220, 220, 220, 362, 25, 685, 43...
1.533473
956
import signal import requests import time from math import floor shutdown = False MAIN_TAKER = 0.0065 MAIN_MAKER = 0.002 ALT_TAKER = 0.005 ALT_MAKER = 0.0035 TAKER = (MAIN_TAKER + ALT_TAKER)*2 MAKER = MAIN_MAKER + ALT_MAKER TAKEMAIN = MAIN_TAKER - ALT_MAKER TAKEALT = ALT_TAKER - MAIN_MAKER BUFFER = 0.01 NaN = float('nan') def main(): # price does change in every tick # check position # plain arbitradge # index arbitrage # shock handling # wave riding # pairTickers = [('WMT-M', 'WMT-A'), ('CAT-M', 'CAT-A'), ('MMM-M', 'MMM-A')] with Session('http://localhost:9998', 'VHK3DEDE') as session: while session.get_tick(): try: shock_runner(session) exchange_arbitrage(session, "WMT-M", "WMT-A") exchange_arbitrage(session, "CAT-M", "CAT-A") exchange_arbitrage(session, "MMM-M", "MMM-A") index_arbitrage(session, ['WMT', 'MMM', 'CAT']) except Exception as ex: print("error", str(ex)) # trader = session.getTrader() # print(trader['nlv']) # TODO: position cleaner: try to reduce gross position loss-free # TODO: implement range runner for the last x ticks TAKER4 = MAIN_TAKER * 5 # TODO: send limit orders and use market to cover unfilled ones after if __name__ == '__main__': signal.signal(signal.SIGINT, sigint) main()
[ 11748, 6737, 201, 198, 11748, 7007, 201, 198, 11748, 640, 201, 198, 6738, 10688, 1330, 4314, 201, 198, 201, 198, 49625, 2902, 796, 10352, 201, 198, 201, 198, 5673, 1268, 62, 5603, 42839, 796, 657, 13, 405, 2996, 201, 198, 5673, 1268, ...
2.065007
723
""" ========================================== Genrating feedthrough from single instance ========================================== This example demostrates how to generate a feedthrough wire connection for a given scalar or vector wires. **Initial Design** .. hdl-diagram:: ../../../examples/basic/_initial_design.v :type: netlistsvg :align: center :module: top **Output1** ``wire0`` feedthough from ``inst_2_1`` .. hdl-diagram:: ../../../examples/basic/_output_wire.v :type: netlistsvg :align: center :module: top **Output2** ``bus_in`` feedthrough from ``inst_1_0`` .. hdl-diagram:: ../../../examples/basic/_output_bus.v :type: netlistsvg :align: center :module: top """ from os import path import spydrnet as sdn import spydrnet_physical as sdnphy netlist = sdnphy.load_netlist_by_name('basic_hierarchy') top = netlist.top_instance.reference cable0 = next(top.get_cables("wire0")) inst2 = next(top.get_instances("inst_2_0")) sdn.compose(netlist, '_initial_design.v', skip_constraints=True) top.create_feedthrough(inst2, cable0) top.create_unconn_wires() sdn.compose(netlist, '_output_wire.v', skip_constraints=True) netlist = sdnphy.load_netlist_by_name('basic_hierarchy') top = netlist.top_instance.reference bus_in = next(top.get_cables("bus_in")) inst1 = next(top.get_instances("inst_1_0")) cables = top.create_feedthrough(inst1, bus_in) top.create_unconn_wires() sdn.compose(netlist, '_output_bus.v', skip_constraints=True)
[ 37811, 198, 10052, 2559, 855, 198, 13746, 8821, 3745, 9579, 422, 2060, 4554, 198, 10052, 2559, 855, 198, 198, 1212, 1672, 1357, 455, 9700, 703, 284, 7716, 257, 3745, 9579, 6503, 4637, 329, 198, 64, 1813, 16578, 283, 393, 15879, 19474, ...
2.749071
538
from __future__ import annotations from typing import Optional, Union from tools import tools from exceptions import workflow_exceptions
[ 6738, 11593, 37443, 834, 1330, 37647, 198, 6738, 19720, 1330, 32233, 11, 4479, 198, 198, 6738, 4899, 1330, 4899, 198, 6738, 13269, 1330, 30798, 62, 1069, 11755, 628 ]
4.964286
28
from django.apps import apps from django.test import override_settings from wagtail_live.signals import live_page_update
[ 6738, 42625, 14208, 13, 18211, 1330, 6725, 198, 6738, 42625, 14208, 13, 9288, 1330, 20957, 62, 33692, 198, 198, 6738, 266, 363, 13199, 62, 12583, 13, 12683, 874, 1330, 2107, 62, 7700, 62, 19119, 628, 198 ]
3.444444
36
# -*- coding: utf-8 -*- """ Script Name: Author: Do Trinh/Jimmy - 3D artist. Description: """ # ------------------------------------------------------------------------------------------------------------- """ Import """ import os from PySide2.QtWidgets import (QFrame, QStyle, QAbstractItemView, QSizePolicy, QLineEdit, QPlainTextEdit, QGraphicsItem, QGraphicsView, QGraphicsScene, QRubberBand, QCalendarWidget, ) from PySide2.QtCore import QEvent, QSettings, QSize, Qt, QDateTime from PySide2.QtGui import QColor, QPainter, QFont, QTextCursor SingleSelection = QCalendarWidget.SingleSelection NoSelection = QCalendarWidget.NoSelection SingleLetterDay = QCalendarWidget.SingleLetterDayNames ShortDay = QCalendarWidget.ShortDayNames LongDay = QCalendarWidget.LongDayNames NoHoriHeader = QCalendarWidget.NoHorizontalHeader NoVertHeader = QCalendarWidget.NoVerticalHeader IsoWeekNum = QCalendarWidget.ISOWeekNumbers SelectMode = QCalendarWidget.SelectionMode HoriHeaderFm = QCalendarWidget.HorizontalHeaderFormat VertHeaderFm = QCalendarWidget.VerticalHeaderFormat DayOfWeek = Qt.DayOfWeek Sunday = Qt.Sunday Monday = Qt.Monday Tuesday = Qt.Tuesday Wednesday = Qt.Wednesday Thursday = Qt.Thursday Friday = Qt.Friday Saturday = Qt.Saturday ICONSIZE = 32 ICONBUFFER = -1 BTNTAGSIZE = QSize(87, 20) TAGBTNSIZE = QSize(87-1, 20-1) BTNICONSIZE = QSize(ICONSIZE, ICONSIZE) ICONBTNSIZE = QSize(ICONSIZE+ICONBUFFER, ICONSIZE+ICONBUFFER) DAMG_LOGO_COLOR = QColor(0, 114, 188, 255) # Basic color GlobalColor = Qt.GlobalColor WHITE = QColor(Qt.white) LIGHTGRAY = QColor(Qt.lightGray) GRAY = QColor(Qt.gray) DARKGRAY = QColor(Qt.darkGray) BLACK = QColor(Qt.black) RED = QColor(Qt.red) GREEN = QColor(Qt.green) BLUE = QColor(Qt.blue) DARKRED = QColor(Qt.darkRed) DARKGREEN = QColor(Qt.darkGreen) DARKBLUE = QColor(Qt.darkBlue) CYAN = QColor(Qt.cyan) MAGENTA = QColor(Qt.magenta) YELLOW = QColor(Qt.yellow) DARKCYAN = QColor(Qt.darkCyan) DARKMAGENTA = QColor(Qt.darkMagenta) DARKYELLOW = QColor(Qt.darkYellow) # Dark Palette color Color_BACKGROUND_LIGHT = QColor('#505F69') COLOR_BACKGROUND_NORMAL = QColor('#32414B') COLOR_BACKGROUND_DARK = QColor('#19232D') COLOR_FOREGROUND_LIGHT = QColor('#F0F0F0') COLOR_FOREGROUND_NORMAL = QColor('#AAAAAA') COLOR_FOREGROUND_DARK = QColor('#787878') COLOR_SELECTION_LIGHT = QColor('#148CD2') COLOR_SELECTION_NORMAL = QColor('#1464A0') COLOR_SELECTION_DARK = QColor('#14506E') # Nice color blush = QColor(246, 202, 203, 255) petal = QColor(247, 170, 189, 255) petunia = QColor(231, 62, 151, 255) deep_pink = QColor(229, 2, 120, 255) melon = QColor(241, 118, 110, 255) pomegranate = QColor(178, 27, 32, 255) poppy_red = QColor(236, 51, 39, 255) orange_red = QColor(240, 101, 53, 255) olive = QColor(174, 188, 43, 255) spring = QColor(227, 229, 121, 255) yellow = QColor(255, 240, 29, 255) mango = QColor(254, 209, 26, 255) cantaloupe = QColor(250, 176, 98, 255) tangelo = QColor(247, 151, 47, 255) burnt_orange = QColor(236, 137, 36, 255) bright_orange = QColor(242, 124, 53, 255) moss = QColor(176, 186, 39, 255) sage = QColor(212, 219, 145, 255) apple = QColor(178, 215, 140, 255) grass = QColor(111, 178, 68, 255) forest = QColor(69, 149, 62, 255) peacock = QColor(21, 140, 167, 255) teal = QColor(24, 157, 193, 255) aqua = QColor(153, 214, 218, 255) violet = QColor(55, 52, 144, 255) deep_blue = QColor(15, 86, 163, 255) hydrangea = QColor(150, 191, 229, 255) sky = QColor(139, 210, 244, 255) dusk = QColor(16, 102, 162, 255) midnight = QColor(14, 90, 131, 255) seaside = QColor(87, 154, 188, 255) poolside = QColor(137, 203, 225, 255) eggplant = QColor(86, 5, 79, 255) lilac = QColor(222, 192, 219, 255) chocolate = QColor(87, 43, 3, 255) blackout = QColor(19, 17, 15, 255) stone = QColor(125, 127, 130, 255) gravel = QColor(181, 182, 185, 255) pebble = QColor(217, 212, 206, 255) sand = QColor(185, 172, 151, 255) ignoreARM = Qt.IgnoreAspectRatio scrollAsNeed = Qt.ScrollBarAsNeeded scrollOff = Qt.ScrollBarAlwaysOff scrollOn = Qt.ScrollBarAlwaysOn SiPoMin = QSizePolicy.Minimum # Size policy SiPoMax = QSizePolicy.Maximum SiPoExp = QSizePolicy.Expanding SiPoPre = QSizePolicy.Preferred SiPoIgn = QSizePolicy.Ignored frameStyle = QFrame.Sunken | QFrame.Panel center = Qt.AlignCenter # Alignment right = Qt.AlignRight left = Qt.AlignLeft top = Qt.AlignTop bottom = Qt.AlignBottom hori = Qt.Horizontal vert = Qt.Vertical dockL = Qt.LeftDockWidgetArea # Docking area dockR = Qt.RightDockWidgetArea dockT = Qt.TopDockWidgetArea dockB = Qt.BottomDockWidgetArea dockAll = Qt.AllDockWidgetAreas datetTimeStamp = QDateTime.currentDateTime().toString("hh:mm - dd MMMM yy") # datestamp PRS = dict(password = QLineEdit.Password, center = center , left = left , right = right, spmax = SiPoMax , sppre = SiPoPre, spexp = SiPoExp, spign = SiPoIgn, expanding = QSizePolicy.Expanding, spmin = SiPoMin,) # ------------------------------------------------------------------------------------------------------------- """ Event """ NO_WRAP = QPlainTextEdit.NoWrap NO_FRAME = QPlainTextEdit.NoFrame ELIDE_RIGHT = Qt.ElideRight ELIDE_NONE = Qt.ElideNone # ------------------------------------------------------------------------------------------------------------- """ Window state """ StateNormal = Qt.WindowNoState StateMax = Qt.WindowMaximized StateMin = Qt.WindowMinimized State_Selected = QStyle.State_Selected # ------------------------------------------------------------------------------------------------------------- """ Nodegraph setting variables """ ASPEC_RATIO = Qt.KeepAspectRatio SMOOTH_TRANS = Qt.SmoothTransformation SCROLLBAROFF = Qt.ScrollBarAlwaysOff # Scrollbar SCROLLBARON = Qt.ScrollBarAlwaysOn SCROLLBARNEED = Qt.ScrollBarAsNeeded WORD_WRAP = Qt.TextWordWrap INTERSECT_ITEM_SHAPE = Qt.IntersectsItemShape CONTAIN_ITEM_SHAPE = Qt.ContainsItemShape MATCH_EXACTLY = Qt.MatchExactly DRAG_ONLY = QAbstractItemView.DragOnly # ------------------------------------------------------------------------------------------------------------- """ UI flags """ ITEMENABLE = Qt.ItemIsEnabled ITEMMOVEABLE = QGraphicsItem.ItemIsMovable ITEMSENDGEOCHANGE = QGraphicsItem.ItemSendsGeometryChanges ITEMSCALECHANGE = QGraphicsItem.ItemScaleChange ITEMPOSCHANGE = QGraphicsItem.ItemPositionChange DEVICECACHE = QGraphicsItem.DeviceCoordinateCache SELECTABLE = QGraphicsItem.ItemIsSelectable MOVEABLE = QGraphicsItem.ItemIsMovable FOCUSABLE = QGraphicsItem.ItemIsFocusable PANEL = QGraphicsItem.ItemIsPanel NOINDEX = QGraphicsScene.NoIndex # Scene RUBBER_DRAG = QGraphicsView.RubberBandDrag # Viewer RUBBER_REC = QRubberBand.Rectangle POS_CHANGE = QGraphicsItem.ItemPositionChange NODRAG = QGraphicsView.NoDrag NOFRAME = QGraphicsView.NoFrame ANCHOR_NO = QGraphicsView.NoAnchor ANCHOR_UNDERMICE = QGraphicsView.AnchorUnderMouse ANCHOR_CENTER = QGraphicsView.AnchorViewCenter CACHE_BG = QGraphicsView.CacheBackground UPDATE_VIEWRECT = QGraphicsView.BoundingRectViewportUpdate UPDATE_FULLVIEW = QGraphicsView.FullViewportUpdate UPDATE_SMARTVIEW = QGraphicsView.SmartViewportUpdate UPDATE_BOUNDINGVIEW = QGraphicsView.BoundingRectViewportUpdate UPDATE_MINIMALVIEW = QGraphicsView.MinimalViewportUpdate STAY_ON_TOP = Qt.WindowStaysOnTopHint STRONG_FOCUS = Qt.StrongFocus SPLASHSCREEN = Qt.SplashScreen FRAMELESS = Qt.FramelessWindowHint CUSTOMIZE = Qt.CustomizeWindowHint CLOSEBTN = Qt.WindowCloseButtonHint MINIMIZEBTN = Qt.WindowMinimizeButtonHint AUTO_COLOR = Qt.AutoColor # ------------------------------------------------------------------------------------------------------------- """ Drawing """ ANTIALIAS = QPainter.Antialiasing # Painter ANTIALIAS_TEXT = QPainter.TextAntialiasing ANTIALIAS_HIGH_QUALITY = QPainter.HighQualityAntialiasing SMOOTH_PIXMAP_TRANSFORM = QPainter.SmoothPixmapTransform NON_COSMETIC_PEN = QPainter.NonCosmeticDefaultPen NO_BRUSH = Qt.NoBrush # Brush NO_PEN = Qt.NoPen # Pen ROUND_CAP = Qt.RoundCap ROUND_JOIN = Qt.RoundJoin PATTERN_SOLID = Qt.SolidPattern # Pattern LINE_SOLID = Qt.SolidLine # Line LINE_DASH = Qt.DashLine LINE_DOT = Qt.DotLine LINE_DASH_DOT = Qt.DashDotDotLine TRANSPARENT = Qt.transparent TRANSPARENT_MODE = Qt.TransparentMode # ------------------------------------------------------------------------------------------------------------- """ Meta Object """ QUEUEDCONNECTION = Qt.QueuedConnection # ------------------------------------------------------------------------------------------------------------- """ Keyboard and cursor """ TEXT_BOLD = QFont.Bold TEXT_NORMAL = QFont.Normal MONO_SPACE = QFont.Monospace TEXT_MENEOMIC = Qt.TextShowMnemonic KEY_PRESS = QEvent.KeyPress KEY_RELEASE = QEvent.KeyRelease KEY_ALT = Qt.Key_Alt KEY_DEL = Qt.Key_Delete KEY_TAB = Qt.Key_Tab KEY_SHIFT = Qt.Key_Shift KEY_CTRL = Qt.Key_Control KEY_BACKSPACE = Qt.Key_Backspace KEY_ENTER = Qt.Key_Enter KEY_RETURN = Qt.Key_Return KEY_F = Qt.Key_F KEY_S = Qt.Key_S ALT_MODIFIER = Qt.AltModifier CTRL_MODIFIER = Qt.ControlModifier SHIFT_MODIFIER = Qt.ShiftModifier NO_MODIFIER = Qt.NoModifier CLOSE_HAND_CUSOR = Qt.ClosedHandCursor SIZEF_CURSOR = Qt.SizeFDiagCursor windows = os.name = 'nt' DMK = Qt.AltModifier if windows else CTRL_MODIFIER MOUSE_LEFT = Qt.LeftButton MOUSE_RIGHT = Qt.RightButton MOUSE_MIDDLE = Qt.MiddleButton NO_BUTTON = Qt.NoButton ARROW_NONE = Qt.NoArrow # Cursor CURSOR_ARROW = Qt.ArrowCursor CURSOR_SIZEALL = Qt.SizeAllCursor MOVE_OPERATION = QTextCursor.MoveOperation MOVE_ANCHOR = QTextCursor.MoveMode.MoveAnchor KEEP_ANCHOR = QTextCursor.MoveMode.KeepAnchor ACTION_MOVE = Qt.MoveAction # Action ignoreARM = Qt.IgnoreAspectRatio # ------------------------------------------------------------------------------------------------------------- """ Set number """ RELATIVE_SIZE = Qt.RelativeSize # Size INI = QSettings.IniFormat NATIVE = QSettings.NativeFormat INVALID = QSettings.InvalidFormat SYS_SCOPE = QSettings.SystemScope USER_SCOPE = QSettings.UserScope # ------------------------------------------------------------------------------------------------------------- # Created by Trinh Do on 5/6/2020 - 3:13 AM # 2017 - 2020 DAMGteam. All rights reserved
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 198, 7391, 6530, 25, 220, 198, 13838, 25, 2141, 33822, 71, 14, 40335, 532, 513, 35, 6802, 13, 198, 198, 11828, 25, 628, 198, 37811, 198, 2, 16529, 3880, ...
1.801993
8,227
from selenium import webdriver from selenium.webdriver.chrome.options import Options import sys import time import urllib.request import os sys.stdin = open('idpwd.txt') site = input() id = input() pwd = input() # selenium chromedriver = 'C:\Webdriver\chromedriver.exe' # selenum webdriver chromedirver . driver = webdriver.Chrome(chromedriver) # driver . driver.get(site) driver.find_element_by_name('userId').send_keys(id) driver.find_element_by_name('userPwd').send_keys(pwd) driver.find_element_by_class_name('form-btn').click() driver.set_window_size(1600, 800) driver.find_element_by_xpath("//a[@href='/edu/lectureroom/openlearning/openLearningList.do']/span").click() # driver.find_element_by_id('searchContNm').send_keys('aps') # # driver.find_element_by_xpath("//button[@onclick='fnSearch();']").click() driver.find_elements_by_xpath("//*[contains(text(), '5_B_Java(1)')]")[0].click() driver.find_element_by_xpath("//span[@class='file-name']").click() driver.switch_to.window(driver.window_handles[1]) print(driver.find_elements_by_xpath("//button[@title=' ']")[0].get_attribute('disabled')) # driver.find_elements_by_xpath("//button[@title=' ']")[0].click() # print(driver.find_elements_by_xpath("//button[@title=' ']")[0].get_attribute('disabled')) # url + find # pre = driver.current_url # find = pre.find('/index.html') # url = pre[:find] # src = driver.find_element_by_class_name("background").get_attribute('src') # print(src) ## # for i in driver.find_elements_by_xpath("//button[@title=' ']"): # print(i) cnt = 1 # url = driver.find_elements_by_class_name("background")[-1].get_attribute('src') # print(url) # urllib.request.urlretrieve(url, '123.jpg') # os.system("curl " + url + " > test.jpg") time.sleep(2) driver.get_screenshot_as_file("hi.png") # for i in driver.find_elements_by_class_name("background"): # time.sleep(2) # print(i.get_attribute('style')) # i.screenshot(str(cnt)+'.png') # cnt += 1 while 1: time.sleep(0.4) driver.save_screenshot('APS/C/'+str(cnt)+'.png') # print(driver.find_element_by_class_name("background").get_attribute('src')) # driver.find_element_by_class_name("background").screenshot(str(cnt)+'.png') driver.find_elements_by_xpath("//button[@title=' ']")[0].click() cnt += 1 if driver.find_elements_by_xpath("//button[@title=' ']")[0].get_attribute('disabled') == 'disabled': break
[ 6738, 384, 11925, 1505, 1330, 3992, 26230, 198, 6738, 384, 11925, 1505, 13, 12384, 26230, 13, 46659, 13, 25811, 1330, 18634, 198, 11748, 25064, 198, 11748, 640, 198, 11748, 2956, 297, 571, 13, 25927, 198, 11748, 28686, 198, 17597, 13, 1...
2.5
968
from io import StringIO # StringIO f = StringIO() f.write('Python-100') str = f.getvalue() # print(':%s' %str) f.write('\n') # f.write('100') f.close() # f1 = StringIO('Python-100' + '\n' + '100') # print(f1.read()) f1.close() # outputData() # dataStr dataStr = outputData() # 1. outputData() dataIO = StringIO(dataStr) # outputData() # dataStr dataStr = outputData() # 1. outputData() dataIO = StringIO(dataStr) # 1.1 StringIO print('1.1:\n%s' %dataIO.getvalue()) # 1.2 print('1.2:') for data in dataIO.readlines(): print(data.strip('\n')) # # 1.2 print('1.2:') for data in dataIO.readlines(): print(data.strip('\n')) # # 1.3 # (32) print(':%d' %dataIO.tell()) # dataIO.seek(0) print('1.3:') for data in dataIO: print(data.strip('\n'))
[ 198, 6738, 33245, 1330, 10903, 9399, 198, 198, 2, 220, 10903, 9399, 220, 198, 69, 796, 10903, 9399, 3419, 198, 198, 69, 13, 13564, 10786, 37906, 12, 3064, 11537, 198, 2536, 796, 277, 13, 1136, 8367, 3419, 1303, 220, 198, 4798, 7, 10...
2.134409
372
import biothings.hub.dataload.uploader as uploader
[ 11748, 3182, 849, 654, 13, 40140, 13, 67, 10254, 1170, 13, 25850, 263, 355, 9516, 263, 198 ]
3
17
"""Contains tests for finpack/core/cli.py """ __copyright__ = "Copyright (C) 2021 Matt Ferreira" import os import unittest from importlib import metadata from docopt import docopt from finpack.core import cli
[ 37811, 4264, 1299, 5254, 329, 957, 8002, 14, 7295, 14, 44506, 13, 9078, 198, 37811, 198, 834, 22163, 4766, 834, 796, 366, 15269, 357, 34, 8, 33448, 4705, 12880, 260, 8704, 1, 198, 198, 11748, 28686, 198, 11748, 555, 715, 395, 198, 6...
3.227273
66
enemy = Yaratik() enemy.move_left() # ejderha also includes all functions from parent class (yaratik) ejderha = Ejderha() ejderha.move_left() ejderha.Ates_puskurtme() # Zombie is called the (child class), inherits from Yaratik (parent class) zombie = Zombie() zombie.move_right() zombie.Isirmak()
[ 628, 198, 198, 46970, 796, 575, 34174, 1134, 3419, 198, 46970, 13, 21084, 62, 9464, 3419, 198, 198, 2, 304, 73, 1082, 3099, 635, 3407, 477, 5499, 422, 2560, 1398, 357, 88, 34174, 1134, 8, 198, 68, 73, 1082, 3099, 796, 412, 73, 108...
2.657895
114
""" Author: Peratham Wiriyathammabhum """ import numpy as np import pandas as pd from sklearn.neighbors import NearestNeighbors def affinity_graph(X): ''' This function returns a numpy array. ''' ni, nd = X.shape A = np.zeros((ni, ni)) for i in range(ni): for j in range(i+1, ni): dist = ((X[i] - X[j])**2).sum() # compute L2 distance A[i][j] = dist A[j][i] = dist # by symmetry return A def knn_graph(X, knn=4): ''' This function returns a numpy array. ''' ni, nd = X.shape nbrs = NearestNeighbors(n_neighbors=(knn+1), algorithm='ball_tree').fit(X) distances, indices = nbrs.kneighbors(X) A = np.zeros((ni, ni)) for dist, ind in zip(distances, indices): i0 = ind[0] for i in range(1,knn+1): d = dist[i] A[i0, i] = d A[i, i0] = d # by symmetry return A def sparse_affinity_graph(X): ''' TODO: This function returns a numpy sparse matrix. ''' ni, nd = X.shape A = np.zeros((ni, ni)) for i in range(ni): for j in range(i+1, ni): dist = ((X[i] - X[j])**2).sum() # compute L2 distance A[i][j] = dist A[j][i] = dist # by symmetry return A def laplacian_graph(X, mode='affinity', knn=3, eta=0.01, sigma=2.5): ''' The unnormalized graph Laplacian, L = D W. ''' if mode == 'affinity': W = affinity_graph(X) W[abs(W) > eta] = 0 elif mode == 'nearestneighbor': W = knn_graph(X, knn=knn) elif mode == 'gaussian': W = affinity_graph(X) bandwidth = 2.0*(sigma**2) W = np.exp(W) / bandwidth else: pass D = np.diag(W.sum(axis=1)) L = D - W return L
[ 37811, 198, 13838, 25, 2448, 37520, 370, 343, 7745, 776, 6475, 397, 17047, 628, 198, 37811, 198, 11748, 299, 32152, 355, 45941, 220, 198, 11748, 19798, 292, 355, 279, 67, 220, 198, 6738, 1341, 35720, 13, 710, 394, 32289, 1330, 3169, 1...
2.131285
716
# Copyright 2019 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. """This package houses all subcommands for the recipe engine. See implementation_details.md for the expectations of the modules in this directory. """ import argparse import errno import logging import os import pkgutil import sys if sys.version_info >= (3, 5): # we're running python > 3.5 OS_WALK = os.walk else: # From vpython from scandir import walk as OS_WALK # pylint: disable=wrong-import-position from .. import simple_cfg from ..recipe_deps import RecipeDeps from ..recipe_module_importer import RecipeModuleImporter LOG = logging.getLogger(__name__) # This incantation finds all loadable submodules of ourself. The # `prefix=__name__` bit is so that these modules get loaded with the correct # import names, i.e. # # recipe_engine.internal.commands.<submodule> # # If omitted, then these submodules can get double loaded as both: # # <submodule> AND # recipe_engine.internal.commands.<submodule> # # Which can both interfere with the global python module namespace, and lead to # strange errors when doing type assertions (since all data in these modules # will be loaded under two different names; classes will fail isinstance checks # even though they are "the same"). _COMMANDS = [ loader.find_module(module_name).load_module(module_name) for (loader, module_name, _) in pkgutil.walk_packages( __path__, prefix=__name__+'.') if '.' not in module_name[len(__name__)+1:] ] # Order all commands by an optional __cmd_priority__ field, and then by module # name. _COMMANDS.sort( key=lambda mod: ( not hasattr(mod, '__cmd_priority__'), # modules defining priority first getattr(mod, '__cmd_priority__', None), # actual priority mod.__name__ # name )) # Now actually set these commands on ourself so that 'mock' works correctly. # # This is needed to allow some tests (though it may be worth adjusting these # tests later to not need this. Just delete this function and see which tests # fail to find the dependencies on this behavior). _patch_our_attrs() def _check_recipes_cfg_consistency(recipe_deps): """Checks all recipe.cfg files for the loaded recipe_deps and logs inconsistent dependencies. Args: recipe_deps (RecipeDeps) - The loaded+fetched recipe deps for the current run. """ actual = recipe_deps.main_repo.simple_cfg.deps # For every repo we loaded for repo_name in actual: required_deps = recipe_deps.repos[repo_name].simple_cfg.deps for req_repo_name, req_spec in required_deps.iteritems(): # If this depends on something we didn't load, log an error. if req_repo_name not in actual: LOG.error( '%r depends on %r, but your recipes.cfg is missing an ' 'entry for this.', repo_name, req_repo_name) continue actual_spec = actual[req_repo_name] if req_spec.revision == actual_spec.revision: # They match, it's all good. continue LOG.warn( 'recipes.cfg depends on %r @ %s, but %r depends on version %s.', req_repo_name, actual_spec.revision, repo_name, req_spec.revision) def _cleanup_pyc(recipe_deps): """Removes any .pyc files from the recipes/recipe_module directories. Args: * recipe_deps (RecipeDeps) - The loaded recipe dependencies. """ for repo in recipe_deps.repos.itervalues(): for to_walk in (repo.recipes_dir, repo.modules_dir): for root, _dirs, files in OS_WALK(to_walk): for fname in files: if not fname.endswith('.pyc'): continue try: to_clean = os.path.join(root, fname) LOG.info('cleaning %r', to_clean) os.unlink(to_clean) except OSError as ex: # If multiple things are cleaning pyc's at the same time this can # race. Fortunately we only care that SOMETHING deleted the pyc :) if ex.errno != errno.ENOENT: raise def parse_and_run(): """Parses the command line and runs the chosen subcommand. Returns the command's return value (either int or None, suitable as input to `os._exit`). """ parser = argparse.ArgumentParser( description='Interact with the recipe system.') _add_common_args(parser) subp = parser.add_subparsers(dest='command') for module in _COMMANDS: description = module.__doc__ helplines = [] for line in description.splitlines(): line = line.strip() if not line: break helplines.append(line) module.add_arguments(subp.add_parser( module.__name__.split('.')[-1], # use module's short name formatter_class=argparse.RawDescriptionHelpFormatter, help=' '.join(helplines), description=description, )) args = parser.parse_args() _common_post_process(args) args.postprocess_func(parser.error, args) return args.func(args)
[ 2, 15069, 13130, 383, 406, 9598, 40, 46665, 13, 1439, 2489, 10395, 13, 198, 2, 5765, 286, 428, 2723, 2438, 318, 21825, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 198, 2, 326, 460, 307, 1043, 287, 262, 38559, 24290, 2393, 13, ...
2.739414
1,842
# Copyright (C) 2020-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 """STCPipelinemodule.""" import numpy as np import gzip as gz from .pipeline import TransformationPipeline, Transformer
[ 2, 15069, 357, 34, 8, 12131, 12, 1238, 2481, 8180, 10501, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 198, 198, 37811, 2257, 8697, 40634, 7749, 375, 2261, 526, 15931, 198, 198, 11748, 299, 32152, 355, ...
3.028986
69
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # ------------------------------------------------------------ # File: __init__.py.py # Created Date: 2020/6/24 # Created Time: 0:12 # Author: Hypdncy # Author Mail: hypdncy@outlook.com # Copyright (c) 2020 Hypdncy # ------------------------------------------------------------ # .::::. # .::::::::. # ::::::::::: # ..:::::::::::' # '::::::::::::' # .:::::::::: # '::::::::::::::.. # ..::::::::::::. # ``:::::::::::::::: # ::::``:::::::::' .:::. # ::::' ':::::' .::::::::. # .::::' :::: .:::::::'::::. # .:::' ::::: .:::::::::' ':::::. # .::' :::::.:::::::::' ':::::. # .::' ::::::::::::::' ``::::. # ...::: ::::::::::::' ``::. # ````':. ':::::::::' ::::.. # '.:::::' ':'````.. # ------------------------------------------------------------
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 2, 20368, 1783, 10541, 198, 2, 9220, 25, 11593, 15003, 834, 13, 9078, 13, 9078, 198, 2, 15622, 7536, 25, 12131, 14, ...
1.851852
621
import numpy as np import pytest from pytest import approx from pymt.component.grid import GridMixIn
[ 11748, 299, 32152, 355, 45941, 198, 11748, 12972, 9288, 198, 6738, 12972, 9288, 1330, 5561, 198, 198, 6738, 279, 4948, 83, 13, 42895, 13, 25928, 1330, 24846, 35608, 818, 628, 628, 628, 628, 628, 628, 198 ]
3.166667
36
import sys if __name__ == "__main__": mylog = sys.argv[1] correctlog = sys.argv[2] mylog_sp = load_log_sp(mylog) correctlog_sp = load_log_sp(correctlog) for (i, ((nb1, sp1), (nb2, sp2))) in enumerate(zip(mylog_sp, correctlog_sp)): print('{} {} - {} vs {}'.format( nb1, nb2, sp1, sp2)) if sp1.lower() != sp2.lower() or int(nb1.lower(),16) != int(nb2.lower(), 16): break
[ 11748, 25064, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 616, 6404, 796, 25064, 13, 853, 85, 58, 16, 60, 198, 220, 220, 220, 3376, 6404, 796, 25064, 13, 853, 85, 58, 17, 60, 198, 220, ...
1.981567
217
"""Exercise 1 Usage: $ CUDA_VISIBLE_DEVICES=2 python practico_1_train_petfinder.py --dataset_dir ../ --epochs 30 --dropout 0.1 0.1 --hidden_layer_sizes 200 100 To know which GPU to use, you can check it with the command $ nvidia-smi """ import argparse import os import mlflow import pickle import numpy as np import pandas as pd import tensorflow as tf from sklearn.model_selection import train_test_split from tensorflow.keras import layers, models import warnings warnings.filterwarnings("ignore") from auxiliary import process_features, load_dataset, build_columns, log_dir_name TARGET_COL = 'AdoptionSpeed' ########################################################################################################### print('All operations completed') if __name__ == '__main__': main()
[ 37811, 3109, 23697, 352, 198, 198, 28350, 25, 198, 198, 3, 29369, 5631, 62, 29817, 34563, 62, 39345, 34444, 28, 17, 21015, 1970, 3713, 62, 16, 62, 27432, 62, 6449, 22805, 13, 9078, 1377, 19608, 292, 316, 62, 15908, 11485, 14, 1377, ...
3.32377
244
# -*- coding: utf-8 -*- from __future__ import absolute_import from pkg_resources import parse_version from warnings import warn from copy import deepcopy import networkx as nx from networkx.readwrite import json_graph from catpy.applications.base import CatmaidClientApplication NX_VERSION_INFO = parse_version(nx.__version__)._key[1] err_msg = ( "Tried to treat the edge's source/target fields as indices into the list of nodes, but failed. " "See issue #26 [1]. " "Has CATMAID upgraded to networkx 2.x? [2]\n\n" "[1]: https://github.com/catmaid/catpy/issues/26\n" "[2]: https://github.com/catmaid/CATMAID/blob/master/django/requirements.txt" ) def convert_nodelink_data(jso): """NetworkX serialises graphs differently in v1.x and v2.x. This converts v1-style data (as emitted by CATMAID) to v2-style data. See issue #26 https://github.com/catmaid/catpy/issues/26 Parameters ---------- jso : dict Returns ------- dict """ if NX_VERSION_INFO < (2, 0): warn( "You are converting networkx v1-style JSON (emitted by CATMAID) to v2-style JSON," " but you are using networkx v1" ) out = deepcopy(jso) for edge in out["links"]: for label in ["source", "target"]: try: edge[label] = out["nodes"][edge[label]]["id"] except (KeyError, IndexError): raise RuntimeError(err_msg) return out
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 198, 6738, 279, 10025, 62, 37540, 1330, 21136, 62, 9641, 198, 6738, 14601, 1330, 9828, 198, 6738, 4866, 1330, 2769, ...
2.456667
600
from typing import Optional from watchmen_auth import PrincipalService from watchmen_data_kernel.cache import CacheService from watchmen_data_kernel.common import DataKernelException from watchmen_data_kernel.external_writer import find_external_writer_create, register_external_writer_creator from watchmen_meta.common import ask_meta_storage, ask_snowflake_generator from watchmen_meta.system import ExternalWriterService as ExternalWriterStorageService from watchmen_model.common import ExternalWriterId from watchmen_model.system import ExternalWriter
[ 6738, 19720, 1330, 32233, 198, 198, 6738, 2342, 3653, 62, 18439, 1330, 32641, 16177, 198, 6738, 2342, 3653, 62, 7890, 62, 33885, 13, 23870, 1330, 34088, 16177, 198, 6738, 2342, 3653, 62, 7890, 62, 33885, 13, 11321, 1330, 6060, 42, 7948,...
4.140741
135
nota1 = float(input('Digite a nota da primeira nota ')) peso1 = float(input('Digite o peso da primeira nota ')) nota2 = float(input('Digite a nota da seugundo nota ')) peso2 = float(input('Digite o peso da segundo nota ')) media = (nota1/peso1+nota2/peso2)/2 print('A mdia das duas notas :', media)
[ 1662, 64, 16, 796, 12178, 7, 15414, 10786, 19511, 578, 257, 407, 64, 12379, 6994, 8704, 407, 64, 705, 4008, 198, 12272, 78, 16, 796, 12178, 7, 15414, 10786, 19511, 578, 267, 32317, 78, 12379, 6994, 8704, 407, 64, 705, 4008, 198, 166...
2.416
125
from importlib import import_module from typing import Any def import_string(path: str) -> Any: """Imports a dotted path name and returns the class/attribute. Parameters ---------- path: str Dotted module path to retrieve. Returns ------- Class/attribute at the given import path. Raises ------ ImportError If the path does not exist. """ try: module_path, class_name = path.rsplit('.', 1) except ValueError as error: raise ImportError( f"{path} does not look like a module path", ) from error module = import_module(module_path) try: return getattr(module, class_name) except AttributeError as error: raise ImportError( f"Module '{module_path}' does not define a '{class_name}' " "attribute/class", ) from error
[ 6738, 1330, 8019, 1330, 1330, 62, 21412, 198, 6738, 19720, 1330, 4377, 628, 198, 4299, 1330, 62, 8841, 7, 6978, 25, 965, 8, 4613, 4377, 25, 198, 220, 220, 220, 37227, 3546, 3742, 257, 38745, 3108, 1438, 290, 5860, 262, 1398, 14, 423...
2.512821
351
#!/usr/bin/env python import json import os import re from enum import Enum from os.path import join from le_utils.constants import content_kinds from le_utils.constants import exercises from le_utils.constants import file_formats from le_utils.constants import licenses from ricecooker.chefs import SushiChef from ricecooker.classes import files from ricecooker.classes import nodes from ricecooker.classes import questions from ricecooker.classes.licenses import get_license from ricecooker.exceptions import InvalidFormatException from ricecooker.exceptions import raise_for_invalid_channel from ricecooker.exceptions import UnknownContentKindError from ricecooker.exceptions import UnknownFileTypeError from ricecooker.exceptions import UnknownQuestionTypeError # CHANNEL SETTINGS SOURCE_DOMAIN = "<yourdomain.org>" # content provider's domain SOURCE_ID = "<yourid>" # an alphanumeric channel ID CHANNEL_TITLE = "Testing Ricecooker Channel" # a humand-readbale title CHANNEL_LANGUAGE = "en" # language code of channel # LOCAL DIRS EXAMPLES_DIR = os.path.dirname(os.path.realpath(__file__)) DATA_DIR = os.path.join(EXAMPLES_DIR, "data") CONTENT_DIR = os.path.join(EXAMPLES_DIR, "content") # # A utility function to manage absolute paths that allows us to refer to files # in the CONTENT_DIR (subdirectory `content/' in current directory) using content:// def get_abspath(path, content_dir=CONTENT_DIR): """ Replaces `content://` with absolute path of `content_dir`. By default looks for content in subdirectory `content` in current directory. """ if path: file = re.search("content://(.+)", path) if file: return os.path.join(content_dir, file.group(1)) return path FILE_TYPE_MAPPING = { content_kinds.AUDIO: { file_formats.MP3: FileTypes.AUDIO_FILE, file_formats.PNG: FileTypes.THUMBNAIL, file_formats.JPG: FileTypes.THUMBNAIL, file_formats.JPEG: FileTypes.THUMBNAIL, }, content_kinds.DOCUMENT: { file_formats.PDF: FileTypes.DOCUMENT_FILE, file_formats.PNG: FileTypes.THUMBNAIL, file_formats.JPG: FileTypes.THUMBNAIL, file_formats.JPEG: FileTypes.THUMBNAIL, }, content_kinds.HTML5: { file_formats.HTML5: FileTypes.HTML_ZIP_FILE, file_formats.PNG: FileTypes.THUMBNAIL, file_formats.JPG: FileTypes.THUMBNAIL, file_formats.JPEG: FileTypes.THUMBNAIL, }, content_kinds.H5P: { file_formats.H5P: FileTypes.H5P_FILE, file_formats.PNG: FileTypes.THUMBNAIL, file_formats.JPG: FileTypes.THUMBNAIL, file_formats.JPEG: FileTypes.THUMBNAIL, }, content_kinds.VIDEO: { file_formats.MP4: FileTypes.VIDEO_FILE, file_formats.VTT: FileTypes.SUBTITLE_FILE, file_formats.PNG: FileTypes.THUMBNAIL, file_formats.JPG: FileTypes.THUMBNAIL, file_formats.JPEG: FileTypes.THUMBNAIL, }, content_kinds.EXERCISE: { file_formats.PNG: FileTypes.THUMBNAIL, file_formats.JPG: FileTypes.THUMBNAIL, file_formats.JPEG: FileTypes.THUMBNAIL, }, } def guess_file_type(kind, filepath=None, youtube_id=None, web_url=None, encoding=None): """guess_file_class: determines what file the content is Args: filepath (str): filepath of file to check Returns: string indicating file's class """ if youtube_id: return FileTypes.YOUTUBE_VIDEO_FILE elif web_url: return FileTypes.WEB_VIDEO_FILE elif encoding: return FileTypes.BASE64_FILE else: ext = os.path.splitext(filepath)[1][1:].lower() if kind in FILE_TYPE_MAPPING and ext in FILE_TYPE_MAPPING[kind]: return FILE_TYPE_MAPPING[kind][ext] return None def guess_content_kind(path=None, web_video_data=None, questions=None): """guess_content_kind: determines what kind the content is Args: files (str or list): files associated with content Returns: string indicating node's kind """ # If there are any questions, return exercise if questions and len(questions) > 0: return content_kinds.EXERCISE # See if any files match a content kind if path: ext = os.path.splitext(path)[1][1:].lower() if ext in content_kinds.MAPPING: return content_kinds.MAPPING[ext] raise InvalidFormatException( "Invalid file type: Allowed formats are {0}".format( [key for key, value in content_kinds.MAPPING.items()] ) ) elif web_video_data: return content_kinds.VIDEO else: return content_kinds.TOPIC # LOAD sample_tree.json (as dict) with open(join(DATA_DIR, "sample_tree.json"), "r") as json_file: SAMPLE_TREE = json.load(json_file) # LOAD JSON DATA (as string) FOR PERSEUS QUESTIONS SAMPLE_PERSEUS_1_JSON = open(join(DATA_DIR, "sample_perseus01.json"), "r").read() # SAMPLE_PERSEUS_2_JSON = open(join(DATA_DIR,'sample_perseus02.json'),'r').read() # ADD EXERCISES EXERCISES_NODES = [ { "title": "Rice Cookers", "id": "d98752", "description": "Start cooking rice today!", "children": [ { "title": "Rice Chef", "id": "6cafe2", "author": "Revision 3", "description": "Become a master rice cooker", "file": "https://ia600209.us.archive.org/27/items/RiceChef/Rice Chef.mp4", "license": licenses.CC_BY_NC_SA, "copyright_holder": "Learning Equality", "files": [ { "path": "https://ia600209.us.archive.org/27/items/RiceChef/Rice Chef.mp4" }, { "encoding": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAmFQTFRF////wN/2I0FiNFFuAAAAxdvsN1RxV3KMnrPFFi9PAB1CVG+KXHaQI0NjttLrEjVchIF4AyNGZXB5V087UUw/EzBMpqWeb2thbmpgpqOceXVsERgfTWeADg8QCAEApKGZBAYIop+XCQkIhZ+2T2mEg5mtnK/AobPDkKO2YXqTAAAAJkBetMraZH2VprjIz9zm4enw7/T47fP3wc7ae5GnAAAAN1BsSmSApLfI1ODq2OHp5Orv8PL09vb38fb5wM/bbISbrL/PfZSpxNPgzdnj2+Pr5evw6+/z6e3w3ePp2OPsma2/ABM5Q197ABk4jKG1yNfjytfh1uDo3eXs4unv1t/nztrjqbzMTmmEXneRES1Ji6CzxtXixdPfztrk1N/n1+Dp1d/oz9vlxdPeq73NVG+KYnyUAAAddIuhwtPhvMzaxtTgytfiy9jjwtHewtHenbDCHT1fS2eCRV52qr7PvM3cucrYv87cv8/cvMzavc3bucvacoyl////ByE8WnKKscXWv9Hguszbu8zbvc7dtcnaiJqrcHZ4f4SHEh0nEitFTWZ+hJqumrDDm7HDj6W5dI2lYGJfmZeQl5SNAAAADRciAAATHjdSOVNsPlhyLklmKCYjW1lUlpOLlZKLFSAqWXSOBQAADA0NAAAAHh0bWlhSk5CIk5CIBAYJDRQbERcdDBAUBgkMAAAEDg4NAAAAHBsZWFZQkY6GAAAAAAAABQUEHBsZAAAAGxoYVlROko+GBAQDZ2RdAAAAGhkYcW9oAgICAAAAExMSDQwLjouDjYuDioiAiIV9hoN7VlRO////Z2DcYwAAAMR0Uk5TAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACRKrJyrZlBQECaNXCsKaqypMGAUDcu7Gpn5mf03gDo8+4saiipKq3xRMBH83Eu7OsqbG61DkDMdbFvrizsbK3wNs9Ax/VysS/vLq/zNwfArDhxMfExMXE3pMCMe7byMjIzd33ZgYGQtnz6+zooeJXBQMFD1yHejZ1+l8FBgEELlOR+GgFCQ0SGxoBGFKg+m0BBwEMR6v+hAEDM6nRASWURVuYQQ4AAAABYktHRACIBR1IAAAACXBIWXMAAAjLAAAIywGEuOmJAAABCklEQVQY02NgUGZUUVVT19DUYtBmYmZhYdBh1dXTNzA0MjYxZTFjAwqwm1tYWlnb2NrZO3A4cgIFGJycXVzd3D08vbx9uHyBAn7+AYFBwSEhoWHhEdyRQIGo6JjYuPiExKTklFSeNKBAekZmVnZObk5efkEhbxFQgK+4pLSsvKKyqrqGoZZfgIVBsK6+obGpuaW1rV2oQ1hEgKFTtKu7p7evf8LEI5PEJotLMEyZyjJt+oyZsxhmzzk6V3KeFIO01vwFMrJyCxctXrL02DL55QwsClorVq5avWbtuvUbNh7fpMjAwsKyWWvLFJatStu279h5YhdIAAJ2s+zZu+/kfoQAy4HNLAcPHQYA5YtSi+k2/WkAAAAldEVYdGRhdGU6Y3JlYXRlADIwMTMtMTAtMDRUMTk6Mzk6MjEtMDQ6MDAwU1uYAAAAJXRFWHRkYXRlOm1vZGlmeQAyMDEzLTEwLTA0VDE5OjM5OjIxLTA0OjAwQQ7jJAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAAASUVORK5CYII=" }, ], }, { "title": "Rice Exercise", "id": "6cafe3", "description": "Test how well you know your rice", "license": licenses.CC_BY_NC_SA, "copyright_holder": "Learning Equality", "mastery_model": exercises.DO_ALL, "files": [ { "path": "http://www.publicdomainpictures.net/pictures/110000/nahled/bowl-of-rice.jpg" } ], "questions": [ { "id": "eeeee", "question": "Which rice is your favorite? \\_\\_\\_ ![](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAmFQTFRF////wN/2I0FiNFFuAAAAxdvsN1RxV3KMnrPFFi9PAB1CVG+KXHaQI0NjttLrEjVchIF4AyNGZXB5V087UUw/EzBMpqWeb2thbmpgpqOceXVsERgfTWeADg8QCAEApKGZBAYIop+XCQkIhZ+2T2mEg5mtnK/AobPDkKO2YXqTAAAAJkBetMraZH2VprjIz9zm4enw7/T47fP3wc7ae5GnAAAAN1BsSmSApLfI1ODq2OHp5Orv8PL09vb38fb5wM/bbISbrL/PfZSpxNPgzdnj2+Pr5evw6+/z6e3w3ePp2OPsma2/ABM5Q197ABk4jKG1yNfjytfh1uDo3eXs4unv1t/nztrjqbzMTmmEXneRES1Ji6CzxtXixdPfztrk1N/n1+Dp1d/oz9vlxdPeq73NVG+KYnyUAAAddIuhwtPhvMzaxtTgytfiy9jjwtHewtHenbDCHT1fS2eCRV52qr7PvM3cucrYv87cv8/cvMzavc3bucvacoyl////ByE8WnKKscXWv9Hguszbu8zbvc7dtcnaiJqrcHZ4f4SHEh0nEitFTWZ+hJqumrDDm7HDj6W5dI2lYGJfmZeQl5SNAAAADRciAAATHjdSOVNsPlhyLklmKCYjW1lUlpOLlZKLFSAqWXSOBQAADA0NAAAAHh0bWlhSk5CIk5CIBAYJDRQbERcdDBAUBgkMAAAEDg4NAAAAHBsZWFZQkY6GAAAAAAAABQUEHBsZAAAAGxoYVlROko+GBAQDZ2RdAAAAGhkYcW9oAgICAAAAExMSDQwLjouDjYuDioiAiIV9hoN7VlRO////Z2DcYwAAAMR0Uk5TAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACRKrJyrZlBQECaNXCsKaqypMGAUDcu7Gpn5mf03gDo8+4saiipKq3xRMBH83Eu7OsqbG61DkDMdbFvrizsbK3wNs9Ax/VysS/vLq/zNwfArDhxMfExMXE3pMCMe7byMjIzd33ZgYGQtnz6+zooeJXBQMFD1yHejZ1+l8FBgEELlOR+GgFCQ0SGxoBGFKg+m0BBwEMR6v+hAEDM6nRASWURVuYQQ4AAAABYktHRACIBR1IAAAACXBIWXMAAAjLAAAIywGEuOmJAAABCklEQVQY02NgUGZUUVVT19DUYtBmYmZhYdBh1dXTNzA0MjYxZTFjAwqwm1tYWlnb2NrZO3A4cgIFGJycXVzd3D08vbx9uHyBAn7+AYFBwSEhoWHhEdyRQIGo6JjYuPiExKTklFSeNKBAekZmVnZObk5efkEhbxFQgK+4pLSsvKKyqrqGoZZfgIVBsK6+obGpuaW1rV2oQ1hEgKFTtKu7p7evf8LEI5PEJotLMEyZyjJt+oyZsxhmzzk6V3KeFIO01vwFMrJyCxctXrL02DL55QwsClorVq5avWbtuvUbNh7fpMjAwsKyWWvLFJatStu279h5YhdIAAJ2s+zZu+/kfoQAy4HNLAcPHQYA5YtSi+k2/WkAAAAldEVYdGRhdGU6Y3JlYXRlADIwMTMtMTAtMDRUMTk6Mzk6MjEtMDQ6MDAwU1uYAAAAJXRFWHRkYXRlOm1vZGlmeQAyMDEzLTEwLTA0VDE5OjM5OjIxLTA0OjAwQQ7jJAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAAASUVORK5CYII=)", "type": exercises.MULTIPLE_SELECTION, "correct_answers": [ "White rice", "Brown rice", "Sushi rice <p>abc</p>", ], "all_answers": ["White rice", "Quinoa", "Brown rice", "<"], }, { "id": "bbbbb", "question": "Which rice is the crunchiest?", "type": exercises.SINGLE_SELECTION, "correct_answer": "Rice Krispies \n![](https://upload.wikimedia.org/wikipedia/commons/c/cd/RKTsquares.jpg)", "all_answers": [ "White rice", "Brown rice \n![](https://c2.staticflickr.com/4/3159/2889140143_b99fd8dd4c_z.jpg?zz=1)", "Rice Krispies \n![](https://upload.wikimedia.org/wikipedia/commons/c/cd/RKTsquares.jpg)", ], "hints": "It's delicious", }, { "id": "aaaaa", "question": "How many minutes does it take to cook rice? <img src='https://upload.wikimedia.org/wikipedia/commons/5/5e/Jeera-rice.JPG'>", "type": exercises.INPUT_QUESTION, "answers": ["20", "25", "15"], "hints": [ "Takes roughly same amount of time to install kolibri on Windows machine", "Does this help?\n![](http://www.aroma-housewares.com/images/rice101/delay_timer_1.jpg)", ], }, { "id": "ddddd", "type": exercises.PERSEUS_QUESTION, "item_data": SAMPLE_PERSEUS_1_JSON, }, ], }, { "title": "Rice Exercise 2", "id": "6cafe4", "description": "Test how well you know your rice", "license": licenses.CC_BY_NC_SA, "copyright_holder": "Learning Equality", "mastery_model": exercises.M_OF_N, "files": [ { "path": "https://c1.staticflickr.com/5/4021/4302326650_b11f0f0aaf_b.jpg" } ], "questions": [ { "id": "11111", "question": "<h3 id=\"rainbow\" style=\"font-weight:bold\">RICE COOKING!!!</h3><script type='text/javascript'><!-- setInterval(function() {$('#rainbow').css('color', '#'+((1<<24)*Math.random()|0).toString(16));}, 300); --></script>", "type": exercises.SINGLE_SELECTION, "all_answers": ["Answer"], "correct_answer": "Answer", }, { "id": "121212", "question": "<math> <mrow> <msup><mi> a </mi><mn>2</mn></msup> <mo> + </mo> <msup><mi> b </mi><mn>2</mn></msup> <mo> = </mo> <msup><mi> c </mi><mn>2</mn></msup> </mrow> </math>", "type": exercises.SINGLE_SELECTION, "all_answers": ["Answer"], "correct_answer": "Answer", }, ], }, { "title": "HTML Sample", "id": "abcdef", "description": "An example of how html can be imported from the ricecooker", "license": licenses.PUBLIC_DOMAIN, "files": [{"path": "content://htmltest.zip"}], }, { "title": "Rice Exercise 3", "id": "6cafe5", "description": "Test how well you know your rice", "license": licenses.CC_BY_NC_SA, "copyright_holder": "Learning Equality", "mastery_model": exercises.M_OF_N, "files": [ { "path": "https://upload.wikimedia.org/wikipedia/commons/b/b7/Rice_p1160004.jpg" } ], "questions": [ { "id": "123456", "question": "Solve: $$(111^{x+1}\\times111^\\frac14)\\div111^\\frac12=111^3$$", "type": exercises.SINGLE_SELECTION, "all_answers": ["Yes", "No", "Rice!"], "correct_answer": "Rice!", } ], }, ], } ] SAMPLE_TREE.extend(EXERCISES_NODES) def _build_tree(node, sourcetree): """ Parse nodes given in `sourcetree` and add as children of `node`. """ for child_source_node in sourcetree: try: main_file = ( child_source_node["files"][0] if "files" in child_source_node else {} ) kind = guess_content_kind( path=main_file.get("path"), web_video_data=main_file.get("youtube_id") or main_file.get("web_url"), questions=child_source_node.get("questions"), ) except UnknownContentKindError: continue if kind == content_kinds.TOPIC: child_node = nodes.TopicNode( source_id=child_source_node["id"], title=child_source_node["title"], author=child_source_node.get("author"), description=child_source_node.get("description"), thumbnail=child_source_node.get("thumbnail"), ) node.add_child(child_node) source_tree_children = child_source_node.get("children", []) _build_tree(child_node, source_tree_children) elif kind == content_kinds.VIDEO: child_node = nodes.VideoNode( source_id=child_source_node["id"], title=child_source_node["title"], license=get_license( child_source_node.get("license"), description="Description of license", copyright_holder=child_source_node.get("copyright_holder"), ), author=child_source_node.get("author"), description=child_source_node.get("description"), derive_thumbnail=True, # video-specific data thumbnail=child_source_node.get("thumbnail"), ) add_files(child_node, child_source_node.get("files") or []) node.add_child(child_node) elif kind == content_kinds.AUDIO: child_node = nodes.AudioNode( source_id=child_source_node["id"], title=child_source_node["title"], license=child_source_node.get("license"), author=child_source_node.get("author"), description=child_source_node.get("description"), thumbnail=child_source_node.get("thumbnail"), copyright_holder=child_source_node.get("copyright_holder"), ) add_files(child_node, child_source_node.get("files") or []) node.add_child(child_node) elif kind == content_kinds.DOCUMENT: child_node = nodes.DocumentNode( source_id=child_source_node["id"], title=child_source_node["title"], license=child_source_node.get("license"), author=child_source_node.get("author"), description=child_source_node.get("description"), thumbnail=child_source_node.get("thumbnail"), copyright_holder=child_source_node.get("copyright_holder"), ) add_files(child_node, child_source_node.get("files") or []) node.add_child(child_node) elif kind == content_kinds.EXERCISE: mastery_model = ( child_source_node.get("mastery_model") and {"mastery_model": child_source_node["mastery_model"]} ) or {} child_node = nodes.ExerciseNode( source_id=child_source_node["id"], title=child_source_node["title"], license=child_source_node.get("license"), author=child_source_node.get("author"), description=child_source_node.get("description"), exercise_data=mastery_model, thumbnail=child_source_node.get("thumbnail"), copyright_holder=child_source_node.get("copyright_holder"), ) add_files(child_node, child_source_node.get("files") or []) for q in child_source_node.get("questions"): question = create_question(q) child_node.add_question(question) node.add_child(child_node) elif kind == content_kinds.HTML5: child_node = nodes.HTML5AppNode( source_id=child_source_node["id"], title=child_source_node["title"], license=child_source_node.get("license"), author=child_source_node.get("author"), description=child_source_node.get("description"), thumbnail=child_source_node.get("thumbnail"), copyright_holder=child_source_node.get("copyright_holder"), ) add_files(child_node, child_source_node.get("files") or []) node.add_child(child_node) elif kind == content_kinds.H5P: child_node = nodes.H5PAppNode( source_id=child_source_node["id"], title=child_source_node["title"], license=child_source_node.get("license"), author=child_source_node.get("author"), description=child_source_node.get("description"), thumbnail=child_source_node.get("thumbnail"), copyright_holder=child_source_node.get("copyright_holder"), ) add_files(child_node, child_source_node.get("files") or []) node.add_child(child_node) else: # unknown content file format continue return node if __name__ == "__main__": """ This code will run when the sushi chef is called from the command line. """ chef = SampleChef() chef.main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 33918, 198, 11748, 28686, 198, 11748, 302, 198, 6738, 33829, 1330, 2039, 388, 198, 6738, 28686, 13, 6978, 1330, 4654, 198, 198, 6738, 443, 62, 26791, 13, 9979, 1187, 1330, 2695, ...
1.808682
11,541
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # <pep8 compliant> import enchant import os import pickle import re
[ 2, 46424, 347, 43312, 38644, 38559, 24290, 9878, 11290, 46424, 198, 2, 198, 2, 220, 770, 1430, 318, 1479, 3788, 26, 345, 460, 17678, 4163, 340, 290, 14, 273, 198, 2, 220, 13096, 340, 739, 262, 2846, 286, 262, 22961, 3611, 5094, 1378...
3.680851
235
import numpy as np import os import json import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data import DataLoader, TensorDataset from naslib.utils.utils import AverageMeterGroup from naslib.predictors.utils.encodings import encode from naslib.predictors import Predictor # NOTE: faster on CPU device = torch.device("cpu") print("device:", device)
[ 11748, 299, 32152, 355, 45941, 198, 11748, 28686, 198, 11748, 33918, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 11748, 28034, 13, 40085, 355, 6436, 198, 6738, 2...
3.393443
122
from pythonforandroid.toolchain import Recipe, shprint, current_directory, ArchARM from os.path import exists, join, realpath from os import uname import glob import sh recipe = LibX264Recipe()
[ 6738, 21015, 1640, 19411, 13, 25981, 7983, 1330, 26694, 11, 427, 4798, 11, 1459, 62, 34945, 11, 5579, 33456, 198, 6738, 28686, 13, 6978, 1330, 7160, 11, 4654, 11, 1103, 6978, 198, 6738, 28686, 1330, 555, 480, 198, 11748, 15095, 198, 1...
3.62963
54
#coding=utf-8 try: if __name__.startswith('qgb.Win'): from .. import py else: import py except Exception as ei: raise ei raise EnvironmentError(__name__) if py.is2(): import _winreg as winreg from _winreg import * else: import winreg from winreg import * def get(skey,name,root=HKEY_CURRENT_USER,returnType=True): ''' from qgb.Win import reg reg.get(r'Software\Microsoft\Windows\CurrentVersion\Internet Settings','ProxyEnable') reg.get(r'HKLM\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters\Size' ) There are seven predefined root keys, traditionally named according to their constant handles defined in the Win32 API skey name FileNotFoundError: [WinError 2] ''' r = OpenKey(root,skey) r = QueryValueEx(r,name) if returnType:return r[0],'{} : {}'.format(REG_TYPE[r[1]],r[1]) else :return r[0] REG_TYPE={ 0 : 'REG_NONE', 1 : 'REG_SZ', 2 : 'REG_EXPAND_SZ', 3 : 'REG_BINARY', 4 : 'REG_DWORD', 5 : 'REG_DWORD_BIG_ENDIAN', 6 : 'REG_LINK', 7 : 'REG_MULTI_SZ', 8 : 'REG_RESOURCE_LIST', 9 : 'REG_FULL_RESOURCE_DESCRIPTOR', 10: 'REG_RESOURCE_REQUIREMENTS_LIST', 11: 'REG_QWORD'}
[ 2, 66, 7656, 28, 40477, 12, 23, 198, 28311, 25, 198, 197, 361, 11593, 3672, 834, 13, 9688, 2032, 342, 10786, 80, 22296, 13, 16643, 6, 2599, 198, 197, 197, 6738, 11485, 1330, 12972, 198, 197, 17772, 25, 198, 197, 197, 11748, 12972, ...
2.265896
519
import unittest import paramiko from tornado.httputil import HTTPServerRequest from tests.utils import read_file, make_tests_data_path from webssh.handler import MixinHandler, IndexHandler, InvalidValueError
[ 11748, 555, 715, 395, 198, 11748, 5772, 12125, 198, 198, 6738, 33718, 13, 2804, 1996, 346, 1330, 38288, 18497, 18453, 198, 6738, 5254, 13, 26791, 1330, 1100, 62, 7753, 11, 787, 62, 41989, 62, 7890, 62, 6978, 198, 6738, 3992, 45824, 13...
3.767857
56
import logging from unittest import mock from unittest.mock import call from django.conf import settings from django.contrib.auth import get_user_model from django.core.signing import Signer from django.urls import reverse from django.http import Http404 from django.test import RequestFactory from braces.views import LoginRequiredMixin from django.test import override_settings from model_mommy import mommy from apps.notifications.models import Log, StatusUpdate, MemberUpdate, ReadLog, \ ActionContextQuerySet from apps.notifications.views import LogListView, LogCountView, ReadLogUpdateView, \ LogQuestionnairesListView, LogInformationUpdateCreateView, \ LogSubscriptionPreferencesView, SignedLogSubscriptionPreferencesView from apps.qcat.tests import TestCase #def test_add_user_aware_data_is_todo(self): # data = self._test_add_user_aware_data() # self.assertTrue(data[1]['is_todo']) def test_get_status_invalid(self): request = RequestFactory().get('{}?statuses=foo'.format(self.url_path)) view = self.setup_view(self.view, request) self.assertEqual(view.get_statuses(), []) class ReadLogUpdateViewTest(TestCase):
[ 11748, 18931, 198, 6738, 555, 715, 395, 1330, 15290, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 869, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 1330, 651, 62, 7220, 62, ...
3.072165
388
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import sys import os sys.path.insert(0, os.path.abspath('..')) from clint import resources resources.init('kennethreitz', 'clint') lorem = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' print('%s created.' % resources.user.path) resources.user.write('lorem.txt', lorem) print('lorem.txt created') assert resources.user.read('lorem.txt') == lorem print('lorem.txt has correct contents') resources.user.delete('lorem.txt') print('lorem.txt deleted') assert resources.user.read('lorem.txt') == None print('lorem.txt deletion confirmed')
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 11748, 25064, 198, 11748, 28686, 198, 198, 17597, 13, 697...
2.874652
359
from django.conf.urls import url from django.conf import settings from django.conf.urls.static import static from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^image/$', views.add_image, name='upload_image'), url(r'^profile/$', views.profile_info, name='profile'), url(r'^update/$', views.profile_update, name='update'), url(r'^comment/(?P<image_id>\d+)', views.comment, name='comment'), url(r'^search/', views.search_results, name = 'search_results'), url(r'^follow/(?P<user_id>\d+)', views.follow, name = 'follow'), url(r'^unfollow/(?P<user_id>\d+)', views.unfollow, name='unfollow'), url(r'^likes/(\d+)/$', views.like_images,name='likes') ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 19016, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 13, 12708, 1330, 220, 9037, 198, 6738, 764, 1330, 5009, 198, 198, 6371, 33279, ...
2.564669
317
import random import math from fractions import Fraction from datetime import datetime from jinja2 import Template # empty class for passing to template engine # returns flour percent using flour type def get_special_flour_percent(flourType: str, breadFlourPercent:int) -> int: if flourType == 'Hard Red Whole Wheat' or flourType == 'Hard White Wheat': percentages = [0,25,30,35,40,45,50] percentages = list(filter(lambda x: 100-breadFlourPercent >= x, percentages)) return random.choice(percentages) elif flourType == 'Rye' and breadFlourPercent >= 75: percentages = [0,10,15,20] percentages = list(filter(lambda x: 100-breadFlourPercent >= x, percentages)) return random.choice(percentages) else: percentages = [0,10,15,20,25.30] percentages = list(filter(lambda x: 100-breadFlourPercent >= x, percentages)) return random.choice(percentages) # returns multiplied spoon units from teaspoon fraction input, 3 tsp = 1 tbsp # returns amount given the type of flavoring(spices) # returns list of spices using number of spices # check if extract is nut # checks if extract1 and extract2 are both allowed based on zest/extract same flavor # return list of extracts using number of extracts # return percentage of enrichment # return liquid percent from liquid tpye # return fruit puree fruit choice(s), omitted fruit chance weighting for now # retrun fruit puree percent from 0-2 fruitPurees using random generation # returns rounded ml conversion from percent, used in template # takes filename and writes an html recipe file
[ 11748, 4738, 198, 11748, 10688, 198, 6738, 49876, 1330, 376, 7861, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 474, 259, 6592, 17, 1330, 37350, 198, 198, 2, 6565, 1398, 329, 6427, 284, 11055, 3113, 220, 198, 198, 2, 5860, 1060...
3.521445
443
import datetime from unittest.mock import patch import dns.resolver import dns.rrset import pytest import pytz from django.utils import timezone from freezegun import freeze_time from rest_framework import status from posthog.models import Organization, OrganizationDomain, OrganizationMembership, Team from posthog.test.base import APIBaseTest, BaseTest def test_cannot_list_or_retrieve_domains_for_other_org(self): self.organization_membership.level = OrganizationMembership.Level.ADMIN self.organization_membership.save() response = self.client.get(f"/api/organizations/@current/domains/{self.another_domain.id}") self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) self.assertEqual(response.json(), self.not_found_response()) response = self.client.get(f"/api/organizations/{self.another_org.id}/domains/{self.another_domain.id}") self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) self.assertEqual(response.json(), self.permission_denied_response()) # Create domains def test_cannot_request_verification_for_verified_domains(self): self.organization_membership.level = OrganizationMembership.Level.ADMIN self.organization_membership.save() self.domain.verified_at = timezone.now() self.domain.save() response = self.client.post(f"/api/organizations/@current/domains/{self.domain.id}/verify") self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEqual( response.json(), { "type": "validation_error", "code": "already_verified", "detail": "This domain has already been verified.", "attr": None, }, ) def test_only_admin_can_create_verified_domains(self): count = OrganizationDomain.objects.count() response = self.client.post("/api/organizations/@current/domains/", {"domain": "evil.posthog.com"}) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) self.assertEqual( response.json(), self.permission_denied_response("Your organization access level is insufficient."), ) self.assertEqual(OrganizationDomain.objects.count(), count) def test_only_admin_can_request_verification(self): response = self.client.post(f"/api/organizations/@current/domains/{self.domain.id}/verify") self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) self.assertEqual( response.json(), self.permission_denied_response("Your organization access level is insufficient."), ) self.domain.refresh_from_db() self.assertEqual(self.domain.verified_at, None) # Update domains # Delete domains
[ 11748, 4818, 8079, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 8529, 198, 198, 11748, 288, 5907, 13, 411, 14375, 198, 11748, 288, 5907, 13, 21062, 2617, 198, 11748, 12972, 9288, 198, 11748, 12972, 22877, 198, 6738, 42625, 14208, 13, ...
2.542525
1,117
import numpy as np import tensorflow as tf from tensorflow import keras import matplotlib.pyplot as plt from os import listdir from tensorflow.keras.callbacks import ModelCheckpoint dataDir = "./data/trainSmallFA/" files = listdir(dataDir) files.sort() totalLength = len(files) inputs = np.empty((len(files), 3, 64, 64)) targets = np.empty((len(files), 3, 64, 64)) for i, file in enumerate(files): npfile = np.load(dataDir + file) d = npfile['a'] inputs[i] = d[0:3] # inx, iny, mask targets[i] = d[3:6] # p, velx, vely # print("inputs shape = ", inputs.shape) print(np.shape(targets[:, 1, :, :].flatten())) maxvel = np.amax(np.sqrt(targets[:, 1, :, :]* targets[:, 1, :, :] + targets[:, 2, :, :]* targets[:, 2, :, :])) print(maxvel) targets[:, 1:3, :, :] /= maxvel targets[:, 0, :, :] /= np.amax(targets[:, 0, :, :]) for input in inputs: plt.figure(num=None, figsize=(20, 10), dpi=80, facecolor='w', edgecolor='k') # predicted data plt.subplot(331) plt.title('x vel') plt.imshow(input[0, :, :], cmap='jet') # vmin=-100,vmax=100, cmap='jet') plt.colorbar() plt.subplot(332) plt.title('y vel') plt.imshow(input[1, :, :], cmap='jet') plt.colorbar() plt.show()
[ 11748, 299, 32152, 355, 45941, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 6738, 11192, 273, 11125, 1330, 41927, 292, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 28686, 1330, 1351, 15908, 198, 6738, 11192,...
2.189474
570
from pepper.framework import * from pepper import logger from pepper.language import Utterance from pepper.language.generation.thoughts_phrasing import phrase_thoughts from pepper.language.generation.reply import reply_to_question from .responder import Responder, ResponderType from pepper.language import UtteranceType from pepper.knowledge import sentences, animations from random import choice import re from typing import Optional, Union, Tuple, Callable
[ 6738, 13385, 13, 30604, 1330, 1635, 198, 6738, 13385, 1330, 49706, 198, 198, 6738, 13385, 13, 16129, 1330, 7273, 353, 590, 198, 6738, 13385, 13, 16129, 13, 20158, 13, 2016, 912, 62, 746, 81, 2313, 1330, 9546, 62, 2016, 912, 198, 6738,...
4.160714
112
# -*- coding: utf-8 -*- import re from unicodedata import normalize from flask import Blueprint, render_template, current_app from flask import redirect, url_for, g, abort from sqlalchemy import desc from fedora_college.core.database import db from fedora_college.modules.content.forms import * # noqa from fedora_college.core.models import * # noqa from fedora_college.fedmsgshim import publish from flask_fas_openid import fas_login_required bundle = Blueprint('content', __name__, template_folder='templates') from fedora_college.modules.content.media import * # noqa _punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+') # Verify if user is authenticated # generate url slug def slugify(text, delim=u'-'): """Generates an slightly worse ASCII-only slug.""" result = [] for word in _punct_re.split(text.lower()): word = normalize('NFKD', word).encode('ascii', 'ignore') if word: result.append(word) return unicode(delim.join(result)) # attach tags to a content entry # delete content # add / edit more content # View Blog post
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 302, 198, 6738, 28000, 9043, 1045, 1330, 3487, 1096, 198, 6738, 42903, 1330, 39932, 11, 8543, 62, 28243, 11, 1459, 62, 1324, 198, 6738, 42903, 1330, 18941, 11, 19...
2.838462
390
"""Test the Airthings config flow.""" from unittest.mock import patch import airthings from homeassistant import config_entries from homeassistant.components.airthings.const import CONF_ID, CONF_SECRET, DOMAIN from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import RESULT_TYPE_CREATE_ENTRY, RESULT_TYPE_FORM from tests.common import MockConfigEntry TEST_DATA = { CONF_ID: "client_id", CONF_SECRET: "secret", }
[ 37811, 14402, 262, 317, 3333, 654, 4566, 5202, 526, 15931, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 8529, 198, 198, 11748, 1633, 27971, 198, 198, 6738, 1363, 562, 10167, 1330, 4566, 62, 298, 1678, 198, 6738, 1363, 562, 10167, 13, ...
3.019737
152
# ------------------------------------------------------------------------------ # Copyright (c) NKU # Licensed under the MIT License. # Written by Xuanyi Li (xuanyili.edu@gmail.com) # ------------------------------------------------------------------------------ import os import torch import torch.nn.functional as F #import cv2 as cv import numpy as np if __name__ == '__main__': pass # import matplotlib.pyplot as plt # image = cv.imread('/media/lxy/sdd1/ActiveStereoNet/StereoNet_pytorch/results/forvideo/iter-122.jpg') #im_gray = cv.imread('/media/lxy/sdd1/ActiveStereoNet/StereoNet_pytorch/results/forvideo/iter-133.jpg', cv.IMREAD_GRAYSCALE) # print(im_gray.shape) #im_color = cv.applyColorMap(im_gray*2, cv.COLORMAP_JET) # cv.imshow('test', im_color) # cv.waitKey(0) #cv.imwrite('test.png',im_color) # print(image.shape) # plt.figure('Image') # sc =plt.imshow(image) # sc.set_cmap('hsv') # plt.colorbar() # plt.axis('off') # plt.show() # print('end') # image[:,:,0].save('/media/lxy/sdd1/ActiveStereoNet/StereoNet_pytorch/results/pretrained_StereoNet_single/it1er-151.jpg')
[ 2, 16529, 26171, 198, 2, 15069, 357, 66, 8, 46465, 52, 198, 2, 49962, 739, 262, 17168, 13789, 13, 198, 2, 22503, 416, 33591, 1092, 72, 7455, 357, 87, 84, 1092, 2403, 13, 15532, 31, 14816, 13, 785, 8, 198, 2, 16529, 26171, 198, 1...
2.54386
456
from aiohttp import web import base64 import io import face_recognition main()
[ 6738, 257, 952, 4023, 1330, 3992, 198, 11748, 2779, 2414, 198, 11748, 33245, 198, 11748, 1986, 62, 26243, 653, 198, 198, 12417, 3419, 198 ]
3.333333
24
# ~~~ # This file is part of the paper: # # " An Online Efficient Two-Scale Reduced Basis Approach # for the Localized Orthogonal Decomposition " # # https://github.com/TiKeil/Two-scale-RBLOD.git # # Copyright 2019-2021 all developers. All rights reserved. # License: Licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) # Authors: # Stephan Rave # Tim Keil # ~~~ from setuptools import setup setup(name='rblod', version='2021.1', description='Pymor support for RBLOD', author='Tim Keil', author_email='tim.keil@wwu.de', license='MIT', packages=['rblod'])
[ 2, 220, 4907, 93, 198, 2, 770, 2393, 318, 636, 286, 262, 3348, 25, 198, 2, 198, 2, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 366, 1052, 7467, 412, 5632, 4930, 12, 29990, 39963, 6455, 271, 38066, 198, 2, 220, 220, 220, ...
2.406593
273
import os import shutil import numpy as np import pandas as pd import seaborn as sns import cosmicfish as cf import matplotlib.pyplot as plt import dill # Instruct pyplot to use seaborn sns.set() # Set project, data, CLASS directories projectdir = os.environ['STORAGE_DIR'] datastore = os.environ['DATASTORE_DIR'] classpath = os.environ['CLASS_DIR'] fidx = int(os.environ['FORECAST_INDEX']) # Generate output paths fp_resultsdir = projectdir cf.makedirectory(fp_resultsdir) # Specify resolution of numerical integrals derivative_step = 0.008 # How much to vary parameter to calculate numerical derivative g_derivative_step = 0.1 mu_integral_step = 0.05 # For calculating numerical integral wrt mu between -1 and 1 # Linda Fiducial Cosmology fp_fid = { "A_s" : 2.2321e-9, "n_s" : 0.967, "omega_b" : 0.02226, "omega_cdm" : 0.1127, "tau_reio" : 0.0598, "h" : 0.701, "T_cmb" : 2.726, # Units [K] "N_ncdm" : 4., "deg_ncdm" : 1.0, "T_ncdm" : (0.79/2.726), # Units [T_cmb]. "m_ncdm" : 0.01, # Units [eV] "b0" : 1.0, "beta0" : 1.7, "beta1" : 1.0, "alphak2" : 1.0, "sigma_fog_0" : 250000, #Units [m s^-2] "N_eff" : 0.0064, #We allow relativistic neutrinos in addition to our DM relic "relic_vary" : "N_ncdm", # Fix T_ncdm or m_ncdm "m_nu" : 0.02 } # EUCLID values z_table = np.array([0.65, 0.75, 0.85, 0.95, 1.05, 1.15, 1.25, 1.35, 1.45, 1.55, 1.65, 1.75, 1.85, 1.95]) dNdz = np.array([2434.280, 4364.812, 4728.559, 4825.798, 4728.797, 4507.625, 4269.851, 3720.657, 3104.309, 2308.975, 1514.831, 1474.707, 893.716, 497.613]) skycover = 0.3636 # Run Fisher Forecast full_masses = np.geomspace(0.01, 10., 21) full_temps = np.array([0.79, 0.91, 0.94, 1.08]) mass_index=(fidx % 21) temp_index=(fidx // 21) masses = np.array([full_masses[mass_index]]) temps = np.array([full_temps[temp_index]]) omegacdm_set = np.array([ fp_fid['omega_cdm'] - ((masses/cf.NEUTRINO_SCALE_FACTOR)* np.power(tval / 1.95, 3.)) for tidx, tval in enumerate(temps)]) fp_fiducialset = [[ dict(fp_fid, **{ 'm_ncdm' : masses[midx], 'omega_cdm' : omegacdm_set[tidx, midx], 'T_ncdm' : temps[tidx]/2.726}) for midx, mval in enumerate(masses)] for tidx, tval in enumerate(temps)] fp_forecastset = [[cf.forecast( classpath, datastore, '2relic', fidval, z_table, "EUCLID", dNdz, fsky=skycover, dstep=derivative_step, gstep=g_derivative_step, RSD=True, FOG=True, AP=True, COV=True) for fididx, fidval in enumerate(fidrowvals)] for fidrowidx, fidrowvals in enumerate(fp_fiducialset)] #dill.load_session('') for frowidx, frowval in enumerate(fp_forecastset): for fidx, fcst in enumerate(frowval): if type(fcst.fisher)==type(None): fcst.gen_pm() fcst.gen_fisher( fisher_order=[ 'omega_b', 'omega_cdm', 'n_s', 'A_s', 'tau_reio', 'h', 'N_ncdm', 'M_ncdm', 'sigma_fog', 'beta0', 'beta1', 'alpha_k2'], mu_step=mu_integral_step, skipgen=False) print("Relic Forecast ", fidx, " complete...") dill.dump_session(os.path.join(fp_resultsdir, 'fp_'+str(temp_index)+'_'+str(mass_index)+'.db')) else: print('Fisher matrix already generated!')
[ 11748, 28686, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220,...
1.25741
6,410
import os if __name__ == "__main__": dims = ["32", "64", "128", "256", "512", "1024", "2048"] for dim in dims: os.system( f"perf stat -e r11 -x, -r 10 ../matmul.out ../data/mat-A-{dim}.txt ../data/mat-B-{dim}.txt ./out/out-{dim}.txt 2>>res_arm.csv" ) print(f"Finished {dim}") print("Finished.")
[ 11748, 28686, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 5391, 82, 796, 14631, 2624, 1600, 366, 2414, 1600, 366, 12762, 1600, 366, 11645, 1600, 366, 25836, 1600, 366, 35500, 1600, 366, 1238, ...
1.965909
176
# coding: utf-8 # Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401 from oci.decorators import init_model_state_from_kwargs
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 2, 15069, 357, 66, 8, 1584, 11, 33448, 11, 18650, 290, 14, 273, 663, 29116, 13, 220, 1439, 2489, 10395, 13, 198, 2, 770, 3788, 318, 10668, 12, 36612, 284, 345, 739, 262, 14499, 2448, 33532, 1...
3.097561
164
# Copyright (c) 2022, salesforce.com, inc. # All rights reserved. # SPDX-License-Identifier: BSD-3-Clause # For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause import os import re import time import random import argparse import torch from transformers import GPT2TokenizerFast from jaxformer.hf.codegen.modeling_codegen import CodeGenForCausalLM ######################################################################## # util ######################################################################## # model ######################################################################## # sample ######################################################################## # main if __name__ == '__main__': test_truncate() main() print('done.')
[ 2, 15069, 357, 66, 8, 33160, 11, 4200, 3174, 13, 785, 11, 753, 13, 198, 2, 1439, 2489, 10395, 13, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 347, 10305, 12, 18, 12, 2601, 682, 198, 2, 1114, 1336, 5964, 2420, 11, 766, 2...
4.024155
207
import unittest from services import RoverRunnerService from tests.test_environment.marses import small_mars_with_one_rover_empty_commands from tests.test_environment import mocks as m from data_objects import Rover
[ 11748, 555, 715, 395, 198, 6738, 2594, 1330, 36718, 49493, 16177, 198, 6738, 5254, 13, 9288, 62, 38986, 13, 76, 945, 274, 1330, 1402, 62, 76, 945, 62, 4480, 62, 505, 62, 305, 332, 62, 28920, 62, 9503, 1746, 198, 6738, 5254, 13, 92...
3.677966
59
import argparse import warnings warnings.simplefilter("ignore", UserWarning) import files from tensorboardX import SummaryWriter import os import numpy as np import time import torch import torch.optim import torch.nn as nn import torch.utils.data import torchvision import torchvision.transforms as tfs from data import DataSet,return_model_loader from util import weight_init, write_conv, setup_runtime, AverageMeter, MovingAverage if __name__ == "__main__": args = get_parser().parse_args() name = "%s" % args.comment.replace('/', '_') try: args.device = [int(item) for item in args.device.split(',')] except AttributeError: args.device = [int(args.device)] setup_runtime(seed=42, cuda_dev_id=args.device) print(args, flush=True) print() print(name,flush=True) writer = SummaryWriter('./runs/%s/%s'%(args.data,name)) writer.add_text('args', " \n".join(['%s %s' % (arg, getattr(args, arg)) for arg in vars(args)])) # Setup model and train_loader print('Commencing!', flush=True) model, train_loader = return_model_loader(args) train_loader = RotationDataLoader(args.imagenet_path, is_validation=False, crop_size=224, batch_size=args.batch_size, num_workers=args.workers, shuffle=True) # add additional head to the network for RotNet loss. if args.arch == 'alexnet': if args.hc == 1: model.__setattr__("top_layer0", nn.Linear(4096, args.ncl)) model.top_layer = None model.headcount = args.hc+1 model.__setattr__("top_layer%s" % args.hc, nn.Linear(4096, 4)) else: if args.hc == 1: model.__setattr__("top_layer0", nn.Linear(2048*int(args.archspec), args.ncl)) model.top_layer = None model.headcount = args.hc+1 model.__setattr__("top_layer%s" % args.hc, nn.Linear(2048*int(args.archspec), 4)) if args.init: for mod in model.modules(): mod.apply(weight_init) # Setup optimizer o = Optimizer() o.writer = writer o.lr = args.lr o.num_epochs = args.epochs o.resume = True o.log_interval = args.log_interval o.checkpoint_dir = os.path.join(args.exp, 'checkpoints') # Optimize o.optimize(model, train_loader)
[ 11748, 1822, 29572, 198, 11748, 14601, 198, 40539, 654, 13, 36439, 24455, 7203, 46430, 1600, 11787, 20361, 8, 198, 11748, 3696, 198, 6738, 11192, 273, 3526, 55, 1330, 21293, 34379, 198, 11748, 28686, 198, 11748, 299, 32152, 355, 45941, 19...
2.311573
1,011
# -*- coding: utf-8 -*- from tests import HangulizeTestCase from hangulize.langs.vie import Vietnamese
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 5254, 1330, 24300, 377, 1096, 14402, 20448, 198, 6738, 8181, 377, 1096, 13, 17204, 82, 13, 85, 494, 1330, 23618, 198 ]
2.861111
36
from mathlibpy.functions import * import unittest if __name__ == "__main__": unittest.main()
[ 6738, 10688, 8019, 9078, 13, 12543, 2733, 1330, 1635, 198, 11748, 555, 715, 395, 628, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 555, 715, 395, 13, 12417, 3419, 198 ]
2.615385
39
if __name__ == '__main__': letters = ["c", "f", "j"] target = "a" print(f"Input: letters = {letters}, target = {target}") print(f"Output: {Solution().nextGreatestLetter(letters, target)}")
[ 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 7475, 796, 14631, 66, 1600, 366, 69, 1600, 366, 73, 8973, 198, 220, 220, 220, 2496, 796, 366, 64, 1, 198, 220, 220, 220, 3601, 7, 69, 1, 205...
2.555556
81
import nonebot from nonebot import on_command from nonebot.rule import to_me from nonebot.typing import T_State from nonebot.adapters import Bot, Event from nonebot.log import logger from .config import global_config from .schedule import anti_cpdaily_check_routine cpdaily = on_command('cpdaily') scheduler = nonebot.require("nonebot_plugin_apscheduler").scheduler
[ 11748, 4844, 13645, 198, 6738, 4844, 13645, 1330, 319, 62, 21812, 198, 6738, 4844, 13645, 13, 25135, 1330, 284, 62, 1326, 198, 6738, 4844, 13645, 13, 774, 13886, 1330, 309, 62, 9012, 198, 6738, 4844, 13645, 13, 324, 12126, 1330, 18579, ...
3.3125
112
""" ============ Dollar Ticks ============ Use a `~.ticker.FormatStrFormatter` to prepend dollar signs on y axis labels. """ import numpy as np import matplotlib.pyplot as plt import matplotlib.ticker as ticker # Fixing random state for reproducibility np.random.seed(19680801) fig, ax = plt.subplots() ax.plot(100*np.random.rand(20)) formatter = ticker.FormatStrFormatter('$%1.2f') ax.yaxis.set_major_formatter(formatter) for tick in ax.yaxis.get_major_ticks(): tick.label1.set_visible(False) tick.label2.set_visible(True) tick.label2.set_color('green') plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.ticker matplotlib.ticker.FormatStrFormatter matplotlib.axis.Axis.set_major_formatter matplotlib.axis.Axis.get_major_ticks matplotlib.axis.Tick
[ 37811, 198, 25609, 198, 35, 13228, 309, 3378, 198, 25609, 198, 198, 11041, 257, 4600, 93, 13, 83, 15799, 13, 26227, 13290, 8479, 1436, 63, 284, 3143, 437, 8872, 5895, 319, 331, 16488, 14722, 13, 198, 37811, 198, 11748, 299, 32152, 355...
2.910714
336
import json import re from flask import request, abort, jsonify from Chibrary import config from Chibrary.config import logger from Chibrary.exceptions import * from functools import wraps from urllib import parse from Chibrary.server import db """ { code: ..., message: ..., data: ..., } """ # headerAuthorization: {token} # headerAuthorization: {token} # request # def url_check(url: str): # url = url.lower() # reg = "^(https|http|ftp|rtsp|mms)\\://?([a-zA-Z0-9\\.\\-]+(\\:[a-zA-Z0-9\\.&%\\$\\-]+)*@)?((25[0-5]|2" \ # "[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]" \ # "{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|" \ # "2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|([a-zA-Z0-9\\-]+\\.)*[a-zA-Z0-9\\-]+\\.[a-zA-Z]" \ # "{2,4})(\\:[0-9]+)?(/[^/][a-zA-Z0-9\\.\\,\\?\\'\\\\/\\+&%\\$\\=~_\\-@]*)*$" # print(re.search(url, reg)) if __name__ == '__main__': print(parse_url_query('http://blog.com/sss/ssss/s?wd=dsfa&a=fdsa&a=1&b=1.1&a=s')) print(format_file_size(20250000)) # print(url_check('http://www.bilibili.com/'))
[ 11748, 33918, 198, 11748, 302, 198, 6738, 42903, 1330, 2581, 11, 15614, 11, 33918, 1958, 198, 6738, 609, 4115, 1330, 4566, 198, 6738, 609, 4115, 13, 11250, 1330, 49706, 198, 6738, 609, 4115, 13, 1069, 11755, 1330, 1635, 198, 6738, 1257,...
1.697931
725
import numpy as np from something import Top i = 0 while i < 10: a = np.ndarray((10,4)) b = np.ones((10, Top)) i += 1 del Top # show_store()
[ 11748, 299, 32152, 355, 45941, 198, 6738, 1223, 1330, 5849, 198, 198, 72, 796, 657, 198, 4514, 1312, 1279, 838, 25, 198, 220, 220, 220, 257, 796, 45941, 13, 358, 18747, 19510, 940, 11, 19, 4008, 198, 220, 220, 220, 275, 796, 45941, ...
2.279412
68
from aiohttp_admin2.mappers import Mapper from aiohttp_admin2.mappers import fields def test_correct_float_type(): """ In this test we check success convert to float type. """ mapper = FloatMapper({"field": 1}) mapper.is_valid() assert mapper.data["field"] == 1.0 mapper = FloatMapper({"field": 2}) mapper.is_valid() assert mapper.data["field"] == 2.0 mapper = FloatMapper({"field": -3}) mapper.is_valid() assert mapper.data["field"] == -3.0 mapper = FloatMapper({"field": 0}) mapper.is_valid() assert mapper.data["field"] == 0.0 def test_wrong_float_type(): """ In this test we check error when we received wrong float type. """ assert FloatMapper({"field": "string"}).is_valid() is False assert FloatMapper({"field": []}).is_valid() is False
[ 6738, 257, 952, 4023, 62, 28482, 17, 13, 76, 46629, 1330, 337, 11463, 198, 6738, 257, 952, 4023, 62, 28482, 17, 13, 76, 46629, 1330, 7032, 628, 198, 198, 4299, 1332, 62, 30283, 62, 22468, 62, 4906, 33529, 198, 220, 220, 220, 37227, ...
2.623824
319
""" Try to load all of the MODFLOW-USG examples in ../examples/data/mfusg_test. These are the examples that are distributed with MODFLOW-USG. """ import os import flopy # make the working directory tpth = os.path.join("temp", "t038") if not os.path.isdir(tpth): os.makedirs(tpth) # build list of name files to try and load usgpth = os.path.join("..", "examples", "data", "mfusg_test") usg_files = [] for path, subdirs, files in os.walk(usgpth): for name in files: if name.endswith(".nam"): usg_files.append(os.path.join(path, name)) # # function to load a MODFLOW-USG model and then write it back out def load_model(namfile, model_ws): m = flopy.modflow.Modflow.load( namfile, model_ws=model_ws, version="mfusg", verbose=True, check=False ) assert m, f"Could not load namefile {namfile}" assert m.load_fail is False m.change_model_ws(tpth) m.write_input() return if __name__ == "__main__": for fusg in usg_files: d, f = os.path.split(fusg) load_model(f, d)
[ 37811, 198, 23433, 284, 3440, 477, 286, 262, 19164, 3697, 3913, 12, 2937, 38, 6096, 287, 11485, 14, 1069, 12629, 14, 7890, 14, 76, 69, 385, 70, 62, 9288, 13, 198, 4711, 389, 262, 6096, 326, 389, 9387, 351, 19164, 3697, 3913, 12, 2...
2.352018
446
#!/usr/bin/env python3 import os from argparse import ArgumentParser, ArgumentTypeError, FileType, Namespace from typing import Any
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 28686, 198, 6738, 1822, 29572, 1330, 45751, 46677, 11, 45751, 6030, 12331, 11, 9220, 6030, 11, 28531, 10223, 198, 6738, 19720, 1330, 4377, 628, 198 ]
3.722222
36
from typing import Optional from asn1crypto import core, x509, cms __all__ = [ 'Target', 'TargetCert', 'Targets', 'SequenceOfTargets', 'AttrSpec', 'AAControls' ] # Blame X.509... def _make_tag_explicit(field_decl): tag_dict = field_decl[2] if 'explicit' in tag_dict: return tag_dict['explicit'] = tag_dict['implicit'] del tag_dict['implicit'] def _make_tag_implicit(field_decl): tag_dict = field_decl[2] if 'implicit' in tag_dict: return tag_dict['implicit'] = tag_dict['explicit'] del tag_dict['explicit'] # Deal with wbond/asn1crypto#218 _make_tag_explicit(cms.RoleSyntax._fields[1]) _make_tag_explicit(cms.SecurityCategory._fields[1]) # Deal with wbond/asn1crypto#220 _make_tag_implicit(cms.AttCertIssuer._alternatives[1]) # patch in attribute certificate extensions # Note: unlike in Certomancer, we don't do this one conditionally, since # we need the actual Python types to agree with what we export ext_map = x509.ExtensionId._map ext_specs = x509.Extension._oid_specs ext_map['2.5.29.55'] = 'target_information' ext_specs['target_information'] = SequenceOfTargets ext_map['2.5.29.56'] = 'no_rev_avail' ext_specs['no_rev_avail'] = core.Null ext_map['1.3.6.1.5.5.7.1.6'] = 'aa_controls' ext_specs['aa_controls'] = AAControls ext_map['1.3.6.1.5.5.7.1.4'] = 'audit_identity' ext_specs['audit_identity'] = core.OctetString
[ 6738, 19720, 1330, 32233, 198, 198, 6738, 355, 77, 16, 29609, 78, 1330, 4755, 11, 2124, 29022, 11, 269, 907, 198, 198, 834, 439, 834, 796, 685, 198, 220, 220, 220, 705, 21745, 3256, 705, 21745, 37608, 3256, 705, 51, 853, 1039, 3256,...
2.408935
582
from model.group import Group import random
[ 6738, 2746, 13, 8094, 1330, 4912, 198, 11748, 4738, 198 ]
4.4
10
''' Autor: Gurkirt Singh Start data: 15th May 2016 purpose: of this file is read frame level predictions and process them to produce a label per video ''' from sklearn.svm import LinearSVC from sklearn.ensemble import RandomForestClassifier import numpy as np import pickle import os import time,json import pylab as plt from eval_detection import ANETdetection import scipy.io as sio #######baseDir = "/mnt/sun-alpha/actnet/"; baseDir = "/data/shared/solar-machines/actnet/"; #baseDir = "/mnt/solar-machines/actnet/"; ########imgDir = "/mnt/sun-alpha/actnet/rgb-images/"; ######## imgDir = "/mnt/DATADISK2/ss-workspace/actnet/rgb-images/"; annotPklFile = "../Evaluation/data/actNet200-V1-3.pkl" if __name__=="__main__": #processOnePredictions() # saveAps() # plotmAPs() evalALL()
[ 7061, 6, 198, 16541, 273, 25, 24797, 74, 2265, 14403, 198, 10434, 1366, 25, 1315, 400, 1737, 1584, 198, 29983, 25, 286, 428, 2393, 318, 1100, 5739, 1241, 16277, 290, 1429, 606, 284, 4439, 257, 6167, 583, 2008, 198, 198, 7061, 6, 198...
2.640523
306
import csv if __name__ == '__main__': data = '''book_title,author,publisher,pub_date,isbn Python 101,Mike Driscoll, Mike Driscoll,2020,123456789 wxPython Recipes,Mike Driscoll,Apress,2018,978-1-4842-3237-8 Python Interviews,Mike Driscoll,Packt Publishing,2018,9781788399081''' records = [] for line in data.splitlines(): records.append(line.strip().split(',')) headers = records.pop(0) list_of_dicts = [] for row in records: my_dict = dict(zip(headers, row)) list_of_dicts.append(my_dict) csv_dict_writer('output_dict.csv', headers, list_of_dicts)
[ 11748, 269, 21370, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1366, 796, 705, 7061, 2070, 62, 7839, 11, 9800, 11, 12984, 8191, 11, 12984, 62, 4475, 11, 271, 9374, 198, 220, 220, 220,...
2.382239
259
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC # SPDX-License-Identifier: Apache-2.0 import pytest from decisionengine.framework.modules import Publisher, Source from decisionengine.framework.modules.Module import verify_products from decisionengine.framework.modules.Source import Parameter
[ 2, 30628, 55, 12, 8979, 15269, 8206, 25, 2177, 376, 7780, 72, 4992, 10302, 11, 11419, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 2551, 18392, 13, 30604, ...
3.949367
79
import torch import torch.nn as nn from torch.nn.functional import max_pool1d from utility.model_parameter import Configuration, ModelParameter
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 6738, 28034, 13, 20471, 13, 45124, 1330, 3509, 62, 7742, 16, 67, 198, 198, 6738, 10361, 13, 19849, 62, 17143, 2357, 1330, 28373, 11, 9104, 36301, 628 ]
3.842105
38
''' <xs:complexType name="backup"> <xs:annotation> <xs:documentation></xs:documentation> </xs:annotation> <xs:sequence> <xs:group ref="duration"/> <xs:group ref="editorial"/> </xs:sequence> </xs:complexType> ''' from musicscore.dtd.dtd import Sequence, GroupReference, Element from musicscore.musicxml.groups.common import Editorial from musicscore.musicxml.elements.note import Duration from musicscore.musicxml.types.complextypes.complextype import ComplexType
[ 7061, 6, 198, 197, 27, 34223, 25, 41887, 6030, 1438, 2625, 1891, 929, 5320, 198, 197, 197, 27, 34223, 25, 1236, 14221, 29, 198, 197, 197, 197, 27, 34223, 25, 22897, 341, 12240, 34223, 25, 22897, 341, 29, 198, 197, 197, 3556, 34223, ...
2.841176
170
import nltk import re import csv import string import collections import numpy as np from nltk.corpus import wordnet from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer from nltk.tokenize import WordPunctTokenizer from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix """"Pre - Processing: tokenization, stopwords removal, remove words(with size 1), lower capitalization & lemmatization""" """"Read Data""" # Open sms corpus. sms_file = open('SMSSpamCollection.txt', encoding="utf8") # Check the structure of this file! sms_data = [] sms_labels = [] # CSV Reader LABEL & DATA are separated by TAB. csv_reader = csv.reader(sms_file,delimiter='\t') # Store labels and data. for line in csv_reader: sms_text = preprocessing(line[1]) if ( sms_text != None): # adding the sms_id sms_labels.append( line[0]) # adding the cleaned text We are calling preprocessing method sms_data.append(sms_text) sms_file.close() """Sampling steps (70:30)""" trainset_size = int(round(len(sms_data)*0.70)) # I chose this threshold for 70:30 train and test split. print('The training set size for this classifier is ' + str(trainset_size) + '\n') x_train = np.array([''.join(el) for el in sms_data[0:trainset_size]]) # train sms_data (70%). y_train = np.array([el for el in sms_labels[0:trainset_size]]) # train sms_labels (70%). x_test = np.array([''.join(el) for el in sms_data[trainset_size+1:len(sms_data)]]) # test sms_data (30%). y_test = np.array([el for el in sms_labels[trainset_size+1:len(sms_labels)]]) # test sms_labels (30%). """We are building a TFIDF vectorizer here""" from sklearn.feature_extraction.text import TfidfVectorizer vectorizer = TfidfVectorizer(min_df=2, ngram_range=(1, 2), stop_words='english', strip_accents='unicode', norm='l2') X_train = vectorizer.fit_transform(x_train) X_test = vectorizer.transform(x_test) """Text Clustering - K Means""" from sklearn.cluster import KMeans, MiniBatchKMeans print('--> Text Clustering - K Means') true_k = 5 km = KMeans(n_clusters=true_k, init='k-means++', max_iter=100, n_init=1) kmini = MiniBatchKMeans(n_clusters=true_k, init='k-means++', n_init=1, init_size=1000, batch_size=1000, verbose=False) #verbose=opts.verbose # we are using the same test,train data in TFIDF form as we did in text classification km_model = km.fit(X_train) print("For K-mean clustering ") clustering = collections.defaultdict(list) for idx, label in enumerate(km_model.labels_): clustering[label].append(idx) print(clustering) kmini_model = kmini.fit(X_train) print("For K-mean Mini batch clustering ") clustering = collections.defaultdict(list) for idx, label in enumerate(kmini_model.labels_): clustering[label].append(idx) print(clustering)
[ 11748, 299, 2528, 74, 201, 198, 11748, 302, 201, 198, 11748, 269, 21370, 201, 198, 11748, 4731, 201, 198, 11748, 17268, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 201, 198, 6738, 299, 2528, 74, 13, 10215, 79, 385, 1330, 1573, ...
2.538124
1,141
import torch import numpy as np import hashlib from torch.autograd import Variable import os
[ 11748, 28034, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 12234, 8019, 198, 6738, 28034, 13, 2306, 519, 6335, 1330, 35748, 198, 11748, 28686, 628, 628, 628, 628, 198, 220, 220, 220, 220, 220, 220, 220, 220, 628, 628, 628, 628, 628...
2.813953
43
from ibm_watson import TextToSpeechV1, SpeechToTextV1, DetailedResponse from os import system from json import loads if __name__ == '__main__': main()
[ 6738, 24283, 76, 62, 86, 13506, 1330, 8255, 2514, 5248, 3055, 53, 16, 11, 24709, 2514, 8206, 53, 16, 11, 4614, 6255, 31077, 198, 198, 6738, 28686, 1330, 1080, 198, 6738, 33918, 1330, 15989, 628, 628, 198, 361, 11593, 3672, 834, 6624, ...
2.962963
54
from subprocess import run
[ 6738, 850, 14681, 1330, 1057, 628 ]
4.666667
6
# Generated by Django 2.1.7 on 2019-02-23 23:45 from django.db import migrations
[ 2, 2980, 515, 416, 37770, 362, 13, 16, 13, 22, 319, 13130, 12, 2999, 12, 1954, 2242, 25, 2231, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 628 ]
2.766667
30
from . import (emoji as emj, keyboards as kb, telegram as tg, phrases as phr, finance as fin, utils, glossary, bots, gcp, sed, db)
[ 6738, 764, 1330, 357, 368, 31370, 355, 795, 73, 11, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 34512, 355, 47823, 11, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 573...
1.448454
194
#!/usr/bin/env python # -*- coding: utf-8 """ :mod:`question.serializers` -- serializers """ from rest_framework import serializers from .models import Question, PossibleAnswer from category.models import Category
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 198, 198, 37811, 198, 25, 4666, 25, 63, 25652, 13, 46911, 11341, 63, 1377, 11389, 11341, 198, 37811, 198, 198, 6738, 1334, 62, 30604, 13...
3.421875
64
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'src/ui_ShowResultDialog.ui' # # Created: Sat May 16 17:05:43 2015 # by: PyQt5 UI code generator 5.4 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets from widgets.ImageLabel import ImageLabel
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 5178, 7822, 7560, 422, 3555, 334, 72, 2393, 705, 10677, 14, 9019, 62, 15307, 23004, 44204, 13, 9019, 6, 198, 2, 198, 2, 15622, 25, 7031, 1737, 1467, 1596, 25...
2.852174
115
""" mixcoatl.admin.api_key ---------------------- Implements access to the DCM ApiKey API """ from mixcoatl.resource import Resource from mixcoatl.decorators.lazy import lazy_property from mixcoatl.decorators.validations import required_attrs from mixcoatl.utils import uncamel, camelize, camel_keys, uncamel_keys import json
[ 37811, 198, 19816, 1073, 25864, 13, 28482, 13, 15042, 62, 2539, 198, 19351, 438, 198, 198, 3546, 1154, 902, 1895, 284, 262, 6257, 44, 5949, 72, 9218, 7824, 198, 37811, 198, 6738, 5022, 1073, 25864, 13, 31092, 1330, 20857, 198, 6738, 5...
3.31
100
my_set = {1, 3, 5} my_dict = {'name': 'Jose', 'age': 90} another_dict = {1: 15, 2: 75, 3: 150} lottery_players = [ { 'name': 'Rolf', 'numbers': (13, 45, 66, 23, 22) }, { 'name': 'John', 'numbers': (14, 56, 80, 23, 22) } ] universities = [ { 'name': 'Oxford', 'location': 'UK' }, { 'name': 'MIT', 'location': 'US' } ]
[ 1820, 62, 2617, 796, 1391, 16, 11, 513, 11, 642, 92, 198, 1820, 62, 11600, 796, 1391, 6, 3672, 10354, 705, 23409, 3256, 705, 496, 10354, 4101, 92, 198, 29214, 62, 11600, 796, 1391, 16, 25, 1315, 11, 362, 25, 5441, 11, 513, 25, 6...
1.746835
237
"""Class :py:class:`QWTable` is a QTableView->QWidget for tree model ====================================================================== Usage :: # Run test: python lcls2/psdaq/psdaq/control_gui/QWTable.py from psdaq.control_gui.QWTable import QWTable w = QWTable() Created on 2019-03-28 by Mikhail Dubrovin Re-designed after copy psana/graphqt/QWTable.py -> psdaq/control_gui/ """ import logging logger = logging.getLogger(__name__) from PyQt5.QtWidgets import QTableView, QVBoxLayout, QAbstractItemView, QSizePolicy from PyQt5.QtGui import QStandardItemModel, QStandardItem from PyQt5.QtCore import Qt, QModelIndex from psdaq.control_gui.QWIcons import icon if __name__ == '__main__': import sys from PyQt5.QtWidgets import QApplication logging.basicConfig(format='%(asctime)s %(name)s %(levelname)s: %(message)s', datefmt='%H:%M:%S', level=logging.DEBUG) app = QApplication(sys.argv) w = QWTable() #w.setGeometry(100, 100, 700, 300) w.setWindowTitle('QWTable') w.move(100,50) w.show() app.exec_() del w del app # EOF
[ 198, 37811, 9487, 1058, 9078, 25, 4871, 25, 63, 48, 54, 10962, 63, 318, 257, 1195, 10962, 7680, 3784, 48, 38300, 329, 5509, 2746, 198, 23926, 50155, 198, 198, 28350, 7904, 628, 220, 220, 220, 1303, 5660, 1332, 25, 21015, 300, 565, 8...
2.569087
427
"""Extension loader for filetype handlers. The extension objects provided by MIMEExtensionLoader objects have four attributes: parse, embed, add_options, and update_options. The first two are used as handlers for supporting the MIME type as primary and embeded resources. The last two are (currently) only used for printing. """ __version__ = '$Revision: 2.4 $' from . import extloader import string
[ 37811, 11627, 3004, 40213, 329, 2393, 4906, 32847, 13, 198, 198, 464, 7552, 5563, 2810, 416, 337, 3955, 6500, 742, 3004, 17401, 5563, 423, 1440, 198, 1078, 7657, 25, 21136, 11, 11525, 11, 751, 62, 25811, 11, 290, 4296, 62, 25811, 13, ...
3.803738
107
# coding: utf-8 # (C) Copyright IBM Corp. 2021. # # 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. # IBM OpenAPI SDK Code Generator Version: 3.25.0-2b3f843a-20210115-164628 """ The administration REST API for IBM Event Streams on Cloud. """ from typing import Dict, List import json from ibm_cloud_sdk_core import BaseService, DetailedResponse from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from ibm_cloud_sdk_core.utils import convert_model from .common import get_sdk_headers ############################################################################## # Service ############################################################################## ############################################################################## # Models ############################################################################## def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() def __str__(self) -> str: """Return a `str` version of this ReplicaAssignmentBrokers object.""" return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ReplicaAssignmentBrokers') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other: 'ReplicaAssignmentBrokers') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ConfigCreate(): """ ConfigCreate. :attr str name: (optional) The name of the config property. :attr str value: (optional) The value for a config property. """ def __init__(self, *, name: str = None, value: str = None) -> None: """ Initialize a ConfigCreate object. :param str name: (optional) The name of the config property. :param str value: (optional) The value for a config property. """ self.name = name self.value = value def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'value') and self.value is not None: _dict['value'] = self.value return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() def __str__(self) -> str: """Return a `str` version of this ConfigCreate object.""" return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ConfigCreate') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other: 'ConfigCreate') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ConfigUpdate(): """ ConfigUpdate. :attr str name: (optional) The name of the config property. :attr str value: (optional) The value for a config property. :attr bool reset_to_default: (optional) When true, the value of the config property is reset to its default value. """ def __init__(self, *, name: str = None, value: str = None, reset_to_default: bool = None) -> None: """ Initialize a ConfigUpdate object. :param str name: (optional) The name of the config property. :param str value: (optional) The value for a config property. :param bool reset_to_default: (optional) When true, the value of the config property is reset to its default value. """ self.name = name self.value = value self.reset_to_default = reset_to_default def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'value') and self.value is not None: _dict['value'] = self.value if hasattr(self, 'reset_to_default') and self.reset_to_default is not None: _dict['reset_to_default'] = self.reset_to_default return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() def __str__(self) -> str: """Return a `str` version of this ConfigUpdate object.""" return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ConfigUpdate') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other: 'ConfigUpdate') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other class MirroringActiveTopics(): """ Topics that are being actively mirrored. :attr List[str] active_topics: (optional) """ def __init__(self, *, active_topics: List[str] = None) -> None: """ Initialize a MirroringActiveTopics object. :param List[str] active_topics: (optional) """ self.active_topics = active_topics def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'active_topics') and self.active_topics is not None: _dict['active_topics'] = self.active_topics return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() def __str__(self) -> str: """Return a `str` version of this MirroringActiveTopics object.""" return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'MirroringActiveTopics') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other: 'MirroringActiveTopics') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other class MirroringTopicSelection(): """ Mirroring topic selection payload. :attr List[str] includes: (optional) """ def __init__(self, *, includes: List[str] = None) -> None: """ Initialize a MirroringTopicSelection object. :param List[str] includes: (optional) """ self.includes = includes def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'includes') and self.includes is not None: _dict['includes'] = self.includes return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() def __str__(self) -> str: """Return a `str` version of this MirroringTopicSelection object.""" return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'MirroringTopicSelection') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other: 'MirroringTopicSelection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ReplicaAssignment(): """ ReplicaAssignment. :attr int id: (optional) The ID of the partition. :attr ReplicaAssignmentBrokers brokers: (optional) """ def __init__(self, *, id: int = None, brokers: 'ReplicaAssignmentBrokers' = None) -> None: """ Initialize a ReplicaAssignment object. :param int id: (optional) The ID of the partition. :param ReplicaAssignmentBrokers brokers: (optional) """ self.id = id self.brokers = brokers def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'id') and self.id is not None: _dict['id'] = self.id if hasattr(self, 'brokers') and self.brokers is not None: _dict['brokers'] = self.brokers.to_dict() return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() def __str__(self) -> str: """Return a `str` version of this ReplicaAssignment object.""" return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ReplicaAssignment') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other: 'ReplicaAssignment') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other class TopicConfigs(): """ TopicConfigs. :attr str cleanup_policy: (optional) The value of config property 'cleanup.policy'. :attr str min_insync_replicas: (optional) The value of config property 'min.insync.replicas'. :attr str retention_bytes: (optional) The value of config property 'retention.bytes'. :attr str retention_ms: (optional) The value of config property 'retention.ms'. :attr str segment_bytes: (optional) The value of config property 'segment.bytes'. :attr str segment_index_bytes: (optional) The value of config property 'segment.index.bytes'. :attr str segment_ms: (optional) The value of config property 'segment.ms'. """ def __init__(self, *, cleanup_policy: str = None, min_insync_replicas: str = None, retention_bytes: str = None, retention_ms: str = None, segment_bytes: str = None, segment_index_bytes: str = None, segment_ms: str = None) -> None: """ Initialize a TopicConfigs object. :param str cleanup_policy: (optional) The value of config property 'cleanup.policy'. :param str min_insync_replicas: (optional) The value of config property 'min.insync.replicas'. :param str retention_bytes: (optional) The value of config property 'retention.bytes'. :param str retention_ms: (optional) The value of config property 'retention.ms'. :param str segment_bytes: (optional) The value of config property 'segment.bytes'. :param str segment_index_bytes: (optional) The value of config property 'segment.index.bytes'. :param str segment_ms: (optional) The value of config property 'segment.ms'. """ self.cleanup_policy = cleanup_policy self.min_insync_replicas = min_insync_replicas self.retention_bytes = retention_bytes self.retention_ms = retention_ms self.segment_bytes = segment_bytes self.segment_index_bytes = segment_index_bytes self.segment_ms = segment_ms def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'cleanup_policy') and self.cleanup_policy is not None: _dict['cleanup.policy'] = self.cleanup_policy if hasattr(self, 'min_insync_replicas') and self.min_insync_replicas is not None: _dict['min.insync.replicas'] = self.min_insync_replicas if hasattr(self, 'retention_bytes') and self.retention_bytes is not None: _dict['retention.bytes'] = self.retention_bytes if hasattr(self, 'retention_ms') and self.retention_ms is not None: _dict['retention.ms'] = self.retention_ms if hasattr(self, 'segment_bytes') and self.segment_bytes is not None: _dict['segment.bytes'] = self.segment_bytes if hasattr(self, 'segment_index_bytes') and self.segment_index_bytes is not None: _dict['segment.index.bytes'] = self.segment_index_bytes if hasattr(self, 'segment_ms') and self.segment_ms is not None: _dict['segment.ms'] = self.segment_ms return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() def __str__(self) -> str: """Return a `str` version of this TopicConfigs object.""" return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TopicConfigs') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other: 'TopicConfigs') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other class TopicDetail(): """ TopicDetail. :attr str name: (optional) The name of the topic. :attr int partitions: (optional) The number of partitions. :attr int replication_factor: (optional) The number of replication factor. :attr int retention_ms: (optional) The value of config property 'retention.ms'. :attr str cleanup_policy: (optional) The value of config property 'cleanup.policy'. :attr TopicConfigs configs: (optional) :attr List[ReplicaAssignment] replica_assignments: (optional) The replia assignment of the topic. """ def __init__(self, *, name: str = None, partitions: int = None, replication_factor: int = None, retention_ms: int = None, cleanup_policy: str = None, configs: 'TopicConfigs' = None, replica_assignments: List['ReplicaAssignment'] = None) -> None: """ Initialize a TopicDetail object. :param str name: (optional) The name of the topic. :param int partitions: (optional) The number of partitions. :param int replication_factor: (optional) The number of replication factor. :param int retention_ms: (optional) The value of config property 'retention.ms'. :param str cleanup_policy: (optional) The value of config property 'cleanup.policy'. :param TopicConfigs configs: (optional) :param List[ReplicaAssignment] replica_assignments: (optional) The replia assignment of the topic. """ self.name = name self.partitions = partitions self.replication_factor = replication_factor self.retention_ms = retention_ms self.cleanup_policy = cleanup_policy self.configs = configs self.replica_assignments = replica_assignments def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'partitions') and self.partitions is not None: _dict['partitions'] = self.partitions if hasattr(self, 'replication_factor') and self.replication_factor is not None: _dict['replicationFactor'] = self.replication_factor if hasattr(self, 'retention_ms') and self.retention_ms is not None: _dict['retentionMs'] = self.retention_ms if hasattr(self, 'cleanup_policy') and self.cleanup_policy is not None: _dict['cleanupPolicy'] = self.cleanup_policy if hasattr(self, 'configs') and self.configs is not None: _dict['configs'] = self.configs.to_dict() if hasattr(self, 'replica_assignments') and self.replica_assignments is not None: _dict['replicaAssignments'] = [x.to_dict() for x in self.replica_assignments] return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() def __str__(self) -> str: """Return a `str` version of this TopicDetail object.""" return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TopicDetail') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other: 'TopicDetail') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 2, 357, 34, 8, 15069, 19764, 11421, 13, 33448, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, ...
2.512379
7,149
import functions from pytest import approx from bcca.test import should_print def test_min_insurance(): assert functions.min_insurance(100000) == approx(80000.0) assert functions.min_insurance(123456789) == approx(98765431.2) assert functions.min_insurance(0) == approx(0.0) assert functions.min_insurance(-54317890) == approx(-43454312.0) def test_bmi(): assert functions.bmi(160, 67) == approx(25.05680552) assert functions.bmi(200, 72) == approx(27.12191358) assert functions.bmi(120, 60) == approx(23.43333333) def test_calories(): assert functions.calories(5, 20) == 125 assert functions.calories(1, 1) == 13 def test_earnings(): assert functions.earnings(100, 100, 100) == 3600 assert functions.earnings(50, 75, 100) == 2550 assert functions.earnings(0, 1000, 79) == 12711
[ 11748, 5499, 198, 6738, 12972, 9288, 1330, 5561, 198, 6738, 275, 13227, 13, 9288, 1330, 815, 62, 4798, 628, 628, 628, 628, 628, 198, 4299, 1332, 62, 1084, 62, 1040, 3874, 33529, 198, 220, 220, 220, 6818, 5499, 13, 1084, 62, 1040, 38...
2.686709
316
from django.contrib import admin from .models import Product admin.site.register(Product)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 198, 6738, 764, 27530, 1330, 8721, 198, 28482, 13, 15654, 13, 30238, 7, 15667, 8 ]
3.75
24
# coding=utf-8 from __future__ import unicode_literals from .base import BasePlugin
[ 2, 19617, 28, 40477, 12, 23, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 764, 8692, 1330, 7308, 37233, 628 ]
3.307692
26
#!/usr/bin/env python3 # Project: VUT FIT SUI Project - Dice Wars # Authors: # - Josef Kol <xkolar71@stud.fit.vutbr.cz> # - Dominik Harmim <xharmi00@stud.fit.vutbr.cz> # - Petr Kapoun <xkapou04@stud.fit.vutbr.cz> # - Jindich estk <xsesta05@stud.fit.vutbr.cz> # Year: 2020 # Description: Generates game configurations. import random import sys from argparse import ArgumentParser import time from signal import signal, SIGCHLD from utils import run_ai_only_game, BoardDefinition parser = ArgumentParser(prog='Dice_Wars') parser.add_argument('-p', '--port', help="Server port", type=int, default=5005) parser.add_argument('-a', '--address', help="Server address", default='127.0.0.1') procs = [] def signal_handler(): """ Handler for SIGCHLD signal that terminates server and clients. """ for p in procs: try: p.kill() except ProcessLookupError: pass PLAYING_AIs = [ 'xkolar71_orig', 'xkolar71_2', 'xkolar71_3', 'xkolar71_4', ] if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 2, 4935, 25, 569, 3843, 376, 2043, 311, 10080, 4935, 532, 34381, 6176, 198, 2, 46665, 25, 198, 2, 220, 220, 532, 5264, 69, 25910, 220, 220, 220, 220, 220, 1279, 87, 74, ...
2.402715
442
import functools import sys from contextlib import contextmanager import pytest _orig_trace = None # if _orig_trace and not hasattr(sys, "pypy_version_info"): # Fails with PyPy2 (https://travis-ci.org/antocuni/pdb/jobs/509624590)?!
[ 11748, 1257, 310, 10141, 198, 11748, 25064, 198, 6738, 4732, 8019, 1330, 4732, 37153, 198, 198, 11748, 12972, 9288, 198, 198, 62, 11612, 62, 40546, 796, 6045, 628, 628, 198, 2, 611, 4808, 11612, 62, 40546, 290, 407, 468, 35226, 7, 175...
2.711111
90
""" Various generic env utilties. """ def center_crop_img(img, crop_zoom): """ crop_zoom is amount to "zoom" into the image. E.g. 2.0 would cut out half of the width, half of the height, and only give the center. """ raw_height, raw_width = img.shape[:2] center = raw_height // 2, raw_width // 2 crop_size = raw_height // crop_zoom, raw_width // crop_zoom min_y, max_y = int(center[0] - crop_size[0] // 2), int(center[0] + crop_size[0] // 2) min_x, max_x = int(center[1] - crop_size[1] // 2), int(center[1] + crop_size[1] // 2) img_cropped = img[min_y:max_y, min_x:max_x] return img_cropped def crop_img(img, relative_corners): """ relative_corners are floats between 0 and 1 designating where the corners of a crop box should be ([[top_left_x, top_left_y], [bottom_right_x, bottom_right_y]]). e.g. [[0, 0], [1, 1]] would be the full image, [[0.5, 0.5], [1, 1]] would be bottom right.""" rc = relative_corners raw_height, raw_width = img.shape[:2] top_left_pix = [int(rc[0][0] * raw_width), int(rc[0][1] * raw_height)] bottom_right_pix = [int(rc[1][0] * raw_width), int(rc[1][1] * raw_height)] img_cropped = img[top_left_pix[1]:bottom_right_pix[1], top_left_pix[0]:bottom_right_pix[0]] return img_cropped
[ 37811, 26386, 14276, 17365, 3384, 2326, 444, 13, 37227, 198, 198, 4299, 3641, 62, 31476, 62, 9600, 7, 9600, 11, 13833, 62, 89, 4207, 2599, 198, 220, 220, 220, 37227, 13833, 62, 89, 4207, 318, 2033, 284, 366, 89, 4207, 1, 656, 262, ...
2.377323
538
# -*- coding: utf-8 -*- from __future__ import absolute_import import mock from exam import fixture from sentry import options from sentry.models import Project from sentry.testutils import TestCase from sentry.utils.http import ( is_same_domain, is_valid_origin, get_origins, absolute_uri, is_valid_ip, )
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 198, 11748, 15290, 198, 198, 6738, 2814, 1330, 29220, 198, 198, 6738, 1908, 563, 1330, 3689, 198, 6738, 1908, 5...
3.067308
104
# -*- coding: utf-8 -*- """WebHelpers used in project.""" #from webhelpers import date, feedgenerator, html, number, misc, text from markupsafe import Markup
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 13908, 12621, 19276, 973, 287, 1628, 526, 15931, 198, 198, 2, 6738, 3992, 16794, 364, 1330, 3128, 11, 3745, 8612, 1352, 11, 27711, 11, 1271, 11, 12747, 11, ...
3
53
import sys; from Thesis.load.loadBenchmark import runLoadBenchmarkAsBatch; from Thesis.cluster.RiakCluster import RiakCluster; NORMAL_BINDING = 'riak'; CONSISTENCY_BINDING = 'riak_consistency'; IPS_IN_CLUSTER = ['172.16.33.14', '172.16.33.15', '172.16.33.16', '172.16.33.17', '172.16.33.18']; cluster = RiakCluster(NORMAL_BINDING, CONSISTENCY_BINDING, IPS_IN_CLUSTER); runLoadBenchmarkAsBatch(cluster, ['172.16.33.10'], '/root/YCSB/workloads/workload_load', 3, '/root/YCSB/loads/riak', ['1000000000'], ['1'], ['1']); # main();
[ 11748, 25064, 26, 198, 198, 6738, 383, 13429, 13, 2220, 13, 2220, 44199, 4102, 1330, 1057, 8912, 44199, 4102, 1722, 33, 963, 26, 198, 6738, 383, 13429, 13, 565, 5819, 13, 49, 32994, 2601, 5819, 1330, 30385, 461, 2601, 5819, 26, 198, ...
2.071429
280
# coding: utf-8 # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. import unittest from mock import patch from auto_nag.people import People from auto_nag.round_robin import BadFallback, RoundRobin
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 2, 770, 8090, 6127, 5178, 318, 2426, 284, 262, 2846, 286, 262, 29258, 5094, 198, 2, 13789, 11, 410, 13, 362, 13, 15, 13, 1002, 257, 4866, 286, 262, 4904, 43, 373, 407, 9387, 351, 428, ...
3.211009
109
# should re-write compiled functions to take a local and global dict # as input. from __future__ import absolute_import, print_function import sys import os from . import ext_tools from . import catalog from . import common_info from numpy.core.multiarray import _get_ndarray_c_version ndarray_api_version = '/* NDARRAY API VERSION %x */' % (_get_ndarray_c_version(),) # not an easy way for the user_path_list to come in here. # the PYTHONCOMPILED environment variable offers the most hope. function_catalog = catalog.catalog() function_cache = {} def inline(code,arg_names=[],local_dict=None, global_dict=None, force=0, compiler='', verbose=0, support_code=None, headers=[], customize=None, type_converters=None, auto_downcast=1, newarr_converter=0, **kw): """ Inline C/C++ code within Python scripts. ``inline()`` compiles and executes C/C++ code on the fly. Variables in the local and global Python scope are also available in the C/C++ code. Values are passed to the C/C++ code by assignment much like variables passed are passed into a standard Python function. Values are returned from the C/C++ code through a special argument called return_val. Also, the contents of mutable objects can be changed within the C/C++ code and the changes remain after the C code exits and returns to Python. inline has quite a few options as listed below. Also, the keyword arguments for distutils extension modules are accepted to specify extra information needed for compiling. Parameters ---------- code : string A string of valid C++ code. It should not specify a return statement. Instead it should assign results that need to be returned to Python in the `return_val`. arg_names : [str], optional A list of Python variable names that should be transferred from Python into the C/C++ code. It defaults to an empty string. local_dict : dict, optional If specified, it is a dictionary of values that should be used as the local scope for the C/C++ code. If local_dict is not specified the local dictionary of the calling function is used. global_dict : dict, optional If specified, it is a dictionary of values that should be used as the global scope for the C/C++ code. If `global_dict` is not specified, the global dictionary of the calling function is used. force : {0, 1}, optional If 1, the C++ code is compiled every time inline is called. This is really only useful for debugging, and probably only useful if your editing `support_code` a lot. compiler : str, optional The name of compiler to use when compiling. On windows, it understands 'msvc' and 'gcc' as well as all the compiler names understood by distutils. On Unix, it'll only understand the values understood by distutils. (I should add 'gcc' though to this). On windows, the compiler defaults to the Microsoft C++ compiler. If this isn't available, it looks for mingw32 (the gcc compiler). On Unix, it'll probably use the same compiler that was used when compiling Python. Cygwin's behavior should be similar. verbose : {0,1,2}, optional Specifies how much information is printed during the compile phase of inlining code. 0 is silent (except on windows with msvc where it still prints some garbage). 1 informs you when compiling starts, finishes, and how long it took. 2 prints out the command lines for the compilation process and can be useful if your having problems getting code to work. Its handy for finding the name of the .cpp file if you need to examine it. verbose has no effect if the compilation isn't necessary. support_code : str, optional A string of valid C++ code declaring extra code that might be needed by your compiled function. This could be declarations of functions, classes, or structures. headers : [str], optional A list of strings specifying header files to use when compiling the code. The list might look like ``["<vector>","'my_header'"]``. Note that the header strings need to be in a form than can be pasted at the end of a ``#include`` statement in the C++ code. customize : base_info.custom_info, optional An alternative way to specify `support_code`, `headers`, etc. needed by the function. See :mod:`scipy.weave.base_info` for more details. (not sure this'll be used much). type_converters : [type converters], optional These guys are what convert Python data types to C/C++ data types. If you'd like to use a different set of type conversions than the default, specify them here. Look in the type conversions section of the main documentation for examples. auto_downcast : {1,0}, optional This only affects functions that have numpy arrays as input variables. Setting this to 1 will cause all floating point values to be cast as float instead of double if all the Numeric arrays are of type float. If even one of the arrays has type double or double complex, all variables maintain their standard types. newarr_converter : int, optional Unused. Other Parameters ---------------- Relevant :mod:`distutils` keywords. These are duplicated from Greg Ward's :class:`distutils.extension.Extension` class for convenience: sources : [string] List of source filenames, relative to the distribution root (where the setup script lives), in Unix form (slash-separated) for portability. Source files may be C, C++, SWIG (.i), platform-specific resource files, or whatever else is recognized by the "build_ext" command as source for a Python extension. .. note:: The `module_path` file is always appended to the front of this list include_dirs : [string] List of directories to search for C/C++ header files (in Unix form for portability). define_macros : [(name : string, value : string|None)] List of macros to define; each macro is defined using a 2-tuple, where 'value' is either the string to define it to or None to define it without a particular value (equivalent of "#define FOO" in source or -DFOO on Unix C compiler command line). undef_macros : [string] List of macros to undefine explicitly. library_dirs : [string] List of directories to search for C/C++ libraries at link time. libraries : [string] List of library names (not filenames or paths) to link against. runtime_library_dirs : [string] List of directories to search for C/C++ libraries at run time (for shared extensions, this is when the extension is loaded). extra_objects : [string] List of extra files to link with (e.g. object files not implied by 'sources', static libraries that must be explicitly specified, binary resource files, etc.) extra_compile_args : [string] Any extra platform- and compiler-specific information to use when compiling the source files in 'sources'. For platforms and compilers where "command line" makes sense, this is typically a list of command-line arguments, but for other platforms it could be anything. extra_link_args : [string] Any extra platform- and compiler-specific information to use when linking object files together to create the extension (or to create a new static Python interpreter). Similar interpretation as for 'extra_compile_args'. export_symbols : [string] List of symbols to be exported from a shared extension. Not used on all platforms, and not generally necessary for Python extensions, which typically export exactly one symbol: "init" + extension_name. swig_opts : [string] Any extra options to pass to SWIG if a source file has the .i extension. depends : [string] List of files that the extension depends on. language : string Extension language (i.e. "c", "c++", "objc"). Will be detected from the source extensions if not provided. See Also -------- distutils.extension.Extension : Describes additional parameters. """ # this grabs the local variables from the *previous* call # frame -- that is the locals from the function that called # inline. global function_catalog call_frame = sys._getframe().f_back if local_dict is None: local_dict = call_frame.f_locals if global_dict is None: global_dict = call_frame.f_globals if force: module_dir = global_dict.get('__file__',None) func = compile_function(code,arg_names,local_dict, global_dict,module_dir, compiler=compiler, verbose=verbose, support_code=support_code, headers=headers, customize=customize, type_converters=type_converters, auto_downcast=auto_downcast, **kw) function_catalog.add_function(code,func,module_dir) results = attempt_function_call(code,local_dict,global_dict) else: # 1. try local cache try: results = apply(function_cache[code],(local_dict,global_dict)) return results except TypeError as msg: msg = str(msg).strip() if msg[:16] == "Conversion Error": pass else: raise TypeError(msg) except NameError as msg: msg = str(msg).strip() if msg[:16] == "Conversion Error": pass else: raise NameError(msg) except KeyError: pass # 2. try function catalog try: results = attempt_function_call(code,local_dict,global_dict) # 3. build the function except ValueError: # compile the library module_dir = global_dict.get('__file__',None) func = compile_function(code,arg_names,local_dict, global_dict,module_dir, compiler=compiler, verbose=verbose, support_code=support_code, headers=headers, customize=customize, type_converters=type_converters, auto_downcast=auto_downcast, **kw) function_catalog.add_function(code,func,module_dir) results = attempt_function_call(code,local_dict,global_dict) return results
[ 2, 815, 302, 12, 13564, 14102, 5499, 284, 1011, 257, 1957, 290, 3298, 8633, 198, 2, 355, 5128, 13, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 3601, 62, 8818, 198, 198, 11748, 25064, 198, 11748, 28686, 198, 6738, 764, 1...
2.577616
4,387
# Copyright 2015 Tesora 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 abc import os import re import six from trove.guestagent.common import guestagent_utils from trove.guestagent.common import operating_system from trove.guestagent.common.operating_system import FileMode
[ 2, 15069, 1853, 10696, 5799, 3457, 13, 198, 2, 1439, 6923, 33876, 13, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 220, 220, 220, 407, 779, ...
3.436735
245
import pathlib import yaml documentations = {"Our Platform": "QuantConnect-Platform-2.0.0.yaml", "Alpha Streams": "QuantConnect-Alpha-0.8.yaml"} for section, source in documentations.items(): yaml_file = open(source) doc = yaml.load(yaml_file, Loader=yaml.Loader) paths = doc["paths"] for api_call, result in paths.items(): j = 1 content = result["post"] if "post" in result else result["get"] # Create path if not exist destination_folder = pathlib.Path("/".join(content["tags"])) destination_folder.mkdir(parents=True, exist_ok=True) # Create Introduction part with open(destination_folder / f'{j:02} Introduction.html', "w") as html_file: html_file.write("<p>\n") html_file.write(f"{content['summary']}\n") html_file.write("</p>\n") j += 1 # Create Description part if having one if "description" in content: with open(destination_folder / f'{j:02} Description.html', "w") as html_file: html_file.write('<p>\n') html_file.write(f'{content["description"]}\n') html_file.write('</p>\n') j += 1 # Create Request part with open(destination_folder / f'{j:02} Request.html', "w") as html_file: description_ = "" if "parameters" in content: writeUp = RequestTable(api_call, content["parameters"]) elif "requestBody" in content: if "description" in content["requestBody"]: description_ = str(content["requestBody"]["description"]) if description_[-1] != ".": description_ += "." description_ += " " writeUp = ResponseTable(content["requestBody"]) else: writeUp = '<table class="table qc-table">\n<thead>\n<tr>\n' writeUp += f'<th colspan="1"><code>{api_call}</code> Method</th>\n</tr>\n</thead>\n' writeUp += f'</tr>\n<td><code>{api_call}</code> method takes no parameters.</td>\n</tr>\n</table>' description_ += f'The <code>{api_call}</code> API accepts requests in the following format:\n' html_file.write("<p>\n" + description_ + "</p>\n") html_file.write(writeUp) j += 1 # Create Response part with open(destination_folder / f'{j:02} Responses.html', "w") as html_file: html_file.write('<p>\n') html_file.write(f'The <code>{api_call}</code> API provides a response in the following format:\n') html_file.write('</p>\n') request_body = content["responses"] for code, properties in request_body.items(): if code == "200": html_file.write('<h4>200 Success</h4>\n') elif code == "401": html_file.write('<h4>401 Authentication Error</h4>\n<table class="table qc-table">\n<thead>\n<tr>\n') html_file.write('<th colspan="2"><code>UnauthorizedError</code> Model - Unauthorized response from the API. Key is missing, invalid, or timestamp is too old for hash.</th>\n') html_file.write('</tr>\n</thead>\n<tr>\n<td width="20%">www_authenticate</td> <td> <code>string</code> <br/> Header</td>\n</tr>\n</table>\n') continue elif code == "404": html_file.write('<h4>404 Not Found Error</h4>\n') html_file.write('<p>The requested item, index, page was not found.</p>\n') continue elif code == "default": html_file.write('<h4>Default Generic Error</h4>\n') writeUp = ResponseTable(properties) html_file.write(writeUp) print(f"Documentation of {section} is generated and inplace!")
[ 11748, 3108, 8019, 198, 11748, 331, 43695, 198, 198, 22897, 602, 796, 19779, 5122, 19193, 1298, 366, 24915, 13313, 12, 37148, 12, 17, 13, 15, 13, 15, 13, 88, 43695, 1600, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, ...
1.896811
2,258
from .utils import get_request, authorized
[ 6738, 764, 26791, 1330, 651, 62, 25927, 11, 10435, 198 ]
4.3
10
from django.conf.urls import url # from .views import BaseIndexView urlpatterns = [ # url(r'^$', BaseIndexView.as_view(), name="index"), ]
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 19016, 198, 2, 422, 764, 33571, 1330, 7308, 15732, 7680, 628, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 1303, 19016, 7, 81, 6, 61, 3, 3256, 7308, 15732, 7680, 13, 292, 6...
2.769231
52
# Copyright (c) 2018, Palo Alto Networks # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # Author: Scott Shoaf <sshoaf@paloaltonetworks.com> ''' Palo Alto Networks create_loadable_configs.py Provides rendering of configuration templates with user defined values Output is a set of loadable full configurations and set commands for Panos and Panorama Edit the config_variables.yaml values and then run the script This software is provided without support, warranty, or guarantee. Use at your own risk. ''' import datetime import os import shutil import sys import time import getpass import oyaml from jinja2 import Environment, FileSystemLoader from passlib.hash import des_crypt from passlib.hash import md5_crypt from passlib.hash import sha256_crypt from passlib.hash import sha512_crypt defined_filters = ['md5_hash', 'des_hash', 'sha512_hash'] def myconfig_newdir(myconfigdir_name, foldertime): ''' create a new main loadable_configs folder if required then new subdirectories for configs :param myconfigdir_name: prefix folder name from the my_variables.py file :param foldertime: datetime when script run; to be used as suffix of folder name :return: the myconfigdir full path name ''' # get the full path to the config directory we want (panos / panorama) myconfigpath = os.path.abspath(os.path.join('..', 'loadable_configs')) if os.path.isdir(myconfigpath) is False: os.mkdir(myconfigpath, mode=0o755) print('created new loadable config directory') # check that configs folder exists and if not create a new one # then create snippets and full sub-directories myconfigdir = '{0}/{1}-{2}'.format(myconfigpath, myconfigdir_name, foldertime) if os.path.isdir(myconfigdir) is False: os.mkdir(myconfigdir, mode=0o755) print('\ncreated new archive folder {0}-{1}'.format(myconfigdir_name, foldertime)) if os.path.isdir('{0}/{1}'.format(myconfigdir, config_type)) is False: os.mkdir('{0}/{1}'.format(myconfigdir, config_type)) print('created new subdirectories for {0}'.format(config_type)) return myconfigdir def template_render(filename, template_path, render_type, context): ''' render the jinja template using the context value from config_variables.yaml :param filename: name of the template file :param template_path: path for the template file :param render_type: type if full or set commands; aligns with folder name :param context: dict of variables to render :return: return the rendered xml file and set conf file ''' print('..creating template for {0}'.format(filename)) env = Environment(loader=FileSystemLoader('{0}/{1}'.format(template_path, render_type))) # load our custom jinja filters here, see the function defs below for reference env.filters['md5_hash'] = md5_hash env.filters['des_hash'] = des_hash env.filters['sha512_hash'] = sha512_hash template = env.get_template(filename) rendered_template = template.render(context) return rendered_template def template_save(snippet_name, myconfigdir, config_type, element): ''' after rendering the template save to the myconfig directory each run saves with a unique prefix name + datetime :param snippet_name: name of the output file :param myconfigdir: path to the my_config directory :param config_type: based on initial run list; eg. panos or panorama :param element: xml element rendered based on input variables; used as folder name :param render_type: type eg. if full or snippets; aligns with folder name :return: no value returned (future could be success code) ''' print('..saving template for {0}'.format(snippet_name)) filename = snippet_name with open('{0}/{1}/{2}'.format(myconfigdir, config_type, filename), 'w') as configfile: configfile.write(element) # copy the variables file used for the render into the my_template folder var_file = 'loadable_config_vars/config_variables.yaml' if os.path.isfile('{0}/{1}'.format(myconfigdir, var_file)) is False: vfilesrc = var_file vfiledst = '{0}/{1}'.format(myconfigdir, var_file) shutil.copy(vfilesrc, vfiledst) return # define functions for custom jinja filters def md5_hash(txt): ''' Returns the MD5 Hashed secret for use as a password hash in the PanOS configuration :param txt: text to be hashed :return: password hash of the string with salt and configuration information. Suitable to place in the phash field in the configurations ''' return md5_crypt.hash(txt) def des_hash(txt): ''' Returns the DES Hashed secret for use as a password hash in the PanOS configuration :param txt: text to be hashed :return: password hash of the string with salt and configuration information. Suitable to place in the phash field in the configurations ''' return des_crypt.hash(txt) def sha256_hash(txt): ''' Returns the SHA256 Hashed secret for use as a password hash in the PanOS configuration :param txt: text to be hashed :return: password hash of the string with salt and configuration information. Suitable to place in the phash field in the configurations ''' return sha256_crypt.hash(txt) def sha512_hash(txt): ''' Returns the SHA512 Hashed secret for use as a password hash in the PanOS configuration :param txt: text to be hashed :return: password hash of the string with salt and configuration information. Suitable to place in the phash field in the configurations ''' return sha512_crypt.hash(txt) def replace_variables(config_type, render_type, input_var): ''' get the input variables and render the output configs with jinja2 inputs are read from the template directory and output to my_config :param config_type: panos or panorama to read/write to the respective directories :param archivetime: datetimestamp used for the output my_config folder naming ''' config_variables = 'config_variables.yaml' # create dict of values for the jinja template render context = create_context(config_variables) # update context dict with variables from user input for snippet_var in input_var: context[snippet_var] = input_var[snippet_var] # get the full path to the output directory we want (panos / panorama) template_path = os.path.abspath(os.path.join('..', 'templates', config_type)) # append to the sys path for module lookup sys.path.append(template_path) # output subdir located in loadable_configs dir myconfig_path = myconfig_newdir(input_var['output_dir'], input_var['archive_time']) # render full and set conf files print('\nworking with {0} config template'.format(render_type)) if render_type == 'full': filename = 'iron_skillet_{0}_full.xml'.format(config_type) if render_type == 'set_commands': filename = 'iron_skillet_{0}_full.conf'.format(config_type) element = template_render(filename, template_path, render_type, context) template_save(filename, myconfig_path, config_type, element) print('\nconfigs have been created and can be found in {0}'.format(myconfig_path)) print('along with the metadata values used to render the configs\n') return if __name__ == '__main__': # Use the timestamp to create a unique folder name print('=' * 80) print(' ') print('Welcome to Iron-Skillet'.center(80)) print(' ') print('=' * 80) input_var = {} # archive_time used as part of the my_config directory name input_var['archive_time'] = datetime.datetime.fromtimestamp(time.time()).strftime('%Y%m%d_%H%M%S') print('\ndatetime used for folder creation: {0}\n'.format(input_var['archive_time'])) # this prompts for the prefix name of the output directory input_var['output_dir'] = input('Enter the name of the output directory: ') # this prompts for the superuser username to be added into the configuration; no default admin/admin used input_var['ADMINISTRATOR_USERNAME'] = input('Enter the superuser administrator account username: ') print('\na phash will be created for superuser {0} and added to the config file\n'.format( input_var['ADMINISTRATOR_USERNAME'])) passwordmatch = False # prompt for the superuser password to create a phash and store in the my_config files; no default admin/admin while passwordmatch is False: password1 = getpass.getpass("Enter the superuser administrator account password: ") password2 = getpass.getpass("Enter password again to verify: ") if password1 == password2: input_var['ADMINISTRATOR_PASSWORD'] = password1 passwordmatch = True else: print('\nPasswords do not match. Please try again.\n') # loop through all config types that have their respective template folders for config_type in ['panos', 'panorama']: for render_type in ['full', 'set_commands']: replace_variables(config_type, render_type, input_var)
[ 2, 15069, 357, 66, 8, 2864, 11, 44878, 34317, 27862, 198, 2, 198, 2, 2448, 3411, 284, 779, 11, 4866, 11, 13096, 11, 290, 14, 273, 14983, 428, 3788, 329, 597, 198, 2, 4007, 351, 393, 1231, 6838, 318, 29376, 7520, 11, 2810, 326, 2...
3.003967
3,277
import glob import logging import os import warnings import pytest from _pytest.outcomes import Failed from _pytest.reports import TestReport from .broker_pact import BrokerPact, BrokerPacts, PactBrokerConfig from .result import PytestResult, log # Future options to be implemented. Listing them here so naming consistency can be a thing. # group.addoption("--pact-publish-pacts", action="store_true", default=False, # help="publish pacts to pact broker") # group.addoption("--pact-consumer-version", default=None, # help="consumer version to use when publishing pacts to the broker") # group.addoption("--pact-consumer-version-source", default=None, # help="generate consumer version from source 'git-tag' or 'git-hash'") # group.addoption("--pact-consumer-version-tag", metavar='TAG', action="append", # help="tag(s) that should be applied to the consumer version when pacts " # "are uploaded to the broker; multiple tags may be supplied") # add the pact broker URL to the pytest output if running verbose def test_id(identifier): interaction, _ = identifier return str(interaction) def pytest_generate_tests(metafunc): if "pact_verifier" in metafunc.fixturenames: broker_url = get_broker_url(metafunc.config) if not broker_url: pact_files_location = metafunc.config.getoption("pact_files") if not pact_files_location: raise ValueError("need a --pact-broker-url or --pact-files option") pact_files = load_pact_files(pact_files_location) metafunc.parametrize( "pact_verifier", flatten_pacts(pact_files), ids=test_id, indirect=True ) else: provider_name = get_provider_name(metafunc.config) if not provider_name: raise ValueError("--pact-broker-url requires the --pact-provider-name option") broker = PactBrokerConfig( broker_url, metafunc.config.getoption("pact_broker_token"), metafunc.config.getoption("pact_verify_consumer_tag", []), ) broker_pacts = BrokerPacts( provider_name, pact_broker=broker, result_factory=PytestResult ) pacts = broker_pacts.consumers() filter_consumer_name = metafunc.config.getoption("pact_verify_consumer") if not filter_consumer_name: filter_consumer_name = metafunc.config.getoption("pact_consumer_name") if filter_consumer_name: warnings.warn( "The --pact-consumer-name command-line option is deprecated " "and will be removed in the 3.0.0 release.", DeprecationWarning, ) if filter_consumer_name: pacts = [pact for pact in pacts if pact.consumer == filter_consumer_name] metafunc.parametrize("pact_verifier", flatten_pacts(pacts), ids=test_id, indirect=True)
[ 11748, 15095, 198, 11748, 18931, 198, 11748, 28686, 198, 11748, 14601, 198, 198, 11748, 12972, 9288, 198, 6738, 4808, 9078, 9288, 13, 448, 8988, 1330, 22738, 198, 6738, 4808, 9078, 9288, 13, 48922, 1330, 6208, 19100, 198, 198, 6738, 764, ...
2.245513
1,393
# -*- coding: utf-8 -*- def docstring_property(class_doc): """Property attribute for docstrings. Took from: https://gist.github.com/bfroehle/4041015 >>> class A(object): ... '''Main docstring''' ... def __init__(self, x): ... self.x = x ... @docstring_property(__doc__) ... def __doc__(self): ... return "My value of x is %s." % self.x >>> A.__doc__ 'Main docstring' >>> a = A(10) >>> a.__doc__ 'My value of x is 10.' """ return wrapper
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 628, 198, 4299, 2205, 8841, 62, 26745, 7, 4871, 62, 15390, 2599, 198, 220, 220, 220, 37227, 21746, 11688, 329, 2205, 37336, 13, 198, 220, 220, 220, 309, 566, 422, 25, 3740,...
2.164659
249
import warnings try: import cudasift as cs except: cs = None import numpy as np import pandas as pd def match(edge, aidx=None, bidx=None, **kwargs): """ Apply a composite CUDA matcher and ratio check. If this method is used, no additional ratio check is necessary and no symmetry check is required. The ratio check is embedded on the cuda side and returned as an ambiguity value. In testing symmetry is not required as it is expensive without significant gain in accuracy when using this implementation. """ source_kps = edge.source.get_keypoints(index=aidx) source_des = edge.source.descriptors[aidx] source_map = {k:v for k, v in enumerate(source_kps.index)} destin_kps = edge.destination.get_keypoints(index=bidx) destin_des = edge.destination.descriptors[bidx] destin_map = {k:v for k, v in enumerate(destin_kps.index)} s_siftdata = cs.PySiftData.from_data_frame(source_kps, source_des) d_siftdata = cs.PySiftData.from_data_frame(destin_kps, destin_des) cs.PyMatchSiftData(s_siftdata, d_siftdata) matches, _ = s_siftdata.to_data_frame() # Matches are reindexed 0-n, but need to be remapped to the source_kps, # destin_kps indices. This is the mismatch) source = np.empty(len(matches)) source[:] = edge.source['node_id'] destination = np.empty(len(matches)) destination[:] = edge.destination['node_id'] df = pd.concat([pd.Series(source), pd.Series(matches.index), pd.Series(destination), matches.match, matches.score, matches.ambiguity], axis=1) df.columns = ['source_image', 'source_idx', 'destination_image', 'destination_idx', 'score', 'ambiguity'] df.source_idx = df.source_idx.map(source_map) df.destination_idx = df.destination_idx.map(destin_map) # Set the matches and set the 'ratio' (ambiguity) mask edge.matches = df
[ 11748, 14601, 198, 198, 28311, 25, 198, 220, 220, 220, 1330, 269, 463, 292, 2135, 355, 50115, 198, 16341, 25, 198, 220, 220, 220, 50115, 796, 6045, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, ...
2.5722
741
from flask_restx import Api from app.apis.hello import api as hello api = Api( title='api', version='1.0', description='', prefix='/api', doc='/api' ) api.add_namespace(hello)
[ 6738, 42903, 62, 2118, 87, 1330, 5949, 72, 198, 198, 6738, 598, 13, 499, 271, 13, 31373, 1330, 40391, 355, 23748, 198, 198, 15042, 796, 5949, 72, 7, 198, 220, 220, 220, 3670, 11639, 15042, 3256, 198, 220, 220, 220, 2196, 11639, 16, ...
2.341176
85
# coding: utf-8 import unittest from test.support import captured_stdout from brainfuck import BrainFuck if __name__ == "__main__": unittest.main()
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 11748, 555, 715, 395, 198, 6738, 1332, 13, 11284, 1330, 7907, 62, 19282, 448, 198, 198, 6738, 3632, 31699, 1330, 14842, 34094, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 83...
2.854545
55