text
stringlengths
8
6.05M
""" PRACTICE Test 2, practice_problem 4. Authors: David Mutchler, Valerie Galluzzi, Mark Hays, Amanda Stouder, their colleagues and Muqing Zheng. October 2015. """ # TODO: 1. PUT YOUR NAME IN THE ABOVE LINE. import simple_testing as st import math def main(): """ Calls the TEST functions in this module. """ test_practice_problem4a() test_practice_problem4b() test_practice_problem4c() test_practice_problem4d() # ---------------------------------------------------------------------- # Students: Some of the testing code below uses SimpleTestCase objects, # from the imported simple_testing (st) module. # ---------------------------------------------------------------------- # ---------------------------------------------------------------------- # Students: Use this is_prime function in some of the problems below. # It is ALREADY DONE - no need to modify or add to it. # ---------------------------------------------------------------------- def is_prime(n): """ INPUT: An integer. OUTPUT: True if the given integer is prime, else False. SIDE EFFECTS: None. DESCRIPTION: This function returns True or False, depending on whether the given integer is prime or not. Since the smallest prime is 2, this function returns False on all integers < 2. NOTE: The algorithm used here is simple and clear but slow. Preconditions: :type n: int """ if n < 2: return False for k in range(2, int(math.sqrt(n) + 0.1) + 1): if n % k == 0: return False return True def test_practice_problem4a(): """ Tests the practice_problem4a function. """ # ------------------------------------------------------------------ # TODO: 2. Implement this TEST function. # It TESTS the practice_problem4a function defined below. # Include at least ** 2 ** ADDITIONAL tests (we wrote 5 for you). # # Try to choose tests that might expose errors in your code! # # Use the same 4-step process as for previous TEST functions. # ------------------------------------------------------------------ expected = 119 actual = practice_problem4a((12, 33, 118, 9, 13, 3, 9, 1, 19, 20)) print('Actual is ', actual, 'expected is ', expected) expected = 112 actual = practice_problem4a((112, 0, 18, 9, 13, 3, 9, 20, 19, 20)) print('Actual is ', actual, 'expected is ', expected) # ------------------------------------------------------------------ # 5 tests. # They use the imported simple_testing (st) module. # Each test is a SimpleTestCase with 3 arguments: # -- the function to test, # -- a list containing the argument(s) to send to the function, # -- the correct returned value. # For example, the first test below will call # practice_problem4a((12, 33, 18, 9, 13, 3, 9, 20, 19, 20)) # and compare the returned value against 22 (the correct answer). # ------------------------------------------------------------------ tests = [st.SimpleTestCase(practice_problem4a, [(12, 33, 18, 9, 13, 3, 9, 20, 19, 20)], 19 + 3), st.SimpleTestCase(practice_problem4a, [(3, 12, 10, 8, 8, 9, 8, 11)], 10 + 8), st.SimpleTestCase(practice_problem4a, [(-9999999999, 8888888888)], - 9999999999 + 8888888888), st.SimpleTestCase(practice_problem4a, [(8888888888, -9999999999)], 8888888888 + -9999999999), st.SimpleTestCase(practice_problem4a, [(-77, 20000, -33, 40000, -55, 60000, -11)], - 11 + 20000), ] # ------------------------------------------------------------------ # Run the 5 tests in the tests list constructed above. # ------------------------------------------------------------------ st.SimpleTestCase.run_tests('practice_problem4a', tests) # ------------------------------------------------------------------ # TODO 2 continued: More tests: # YOU add at least ** 2 ** additional tests here. # # You can use the SimpleTestCase class as above, or use # the ordinary expected/actual way, your choice. # # SUGGESTION: Ask an assistant to CHECK your tests to confirm # that they are adequate tests! # ------------------------------------------------------------------ expected = 191 actual = practice_problem4a((12, 33, 118, 9, 173, 3, 9, 1, 190, 20)) print('Actual is ', actual, 'expected is ', expected) expected = 112 actual = practice_problem4a((112, 0, -5, 9, 13, 3, 9, 120, 19, 20)) print('Actual is ', actual, 'expected is ', expected) def practice_problem4a(sequence): """ INPUT: A sequence of numbers. OUTPUT: A number that is the sum of two other numbers (see DESCRIPTION). SIDE EFFECTS: None. DESCRIPTION: For the given sequence of numbers, returns the sum: -- the largest of the numbers at EVEN INDICES, plus -- the smallest of the numbers at ODD INDICES. EXAMPLE: For example, if the sequence is: (12, 33, 18, 9, 13, 3, 9, 20, 19, 20) then the largest of the numbers at EVEN indices is the largest of 12 18 13 9 19 which is 19, and the smallest of the numbers at ODD integers is the smallest of 33 9 3 20 20 which is 3, so the answer in this example would be 19 + 3 = 22. Preconditions: :type sequence: (list, tuple) of numbers with len(sequence) >= 2. """ # ------------------------------------------------------------------ # TODO: 3. Implement and test this function. # Some tests are already written for you (above), # but you are required to write ADDITIONAL tests (above). # ------------------------------------------------------------------ lar = sequence[0] sma = sequence[1] for k in range(0, len(sequence)): if k % 2 == 0: if lar < sequence[k]: lar = sequence[k] if k % 2 == 1: if sma > sequence[k]: sma = sequence[k] return lar + sma def test_practice_problem4b(): """ Tests the practice_problem4b function. """ # ------------------------------------------------------------------ # TODO: 4. Implement this TEST function. # It TESTS the practice_problem4b function defined below. # Include at least ** 2 ** ADDITIONAL tests (we wrote 13 for you). # # Try to choose tests that might expose errors in your code! # # Use the same 4-step process as for previous TEST functions. # ------------------------------------------------------------------ expected = False actual = practice_problem4b((12, 33, 118, 9, 173, 3, 9, 1, 190, 20)) print('Actual is ', actual, 'expected is ', expected) expected = True actual = practice_problem4b((112, 20, -5, 9, 13, 3, 9, 120, 19, 20)) print('Actual is ', actual, 'expected is ', expected) # 13 tests. They use the imported simple_testing (st) module. tests = [st.SimpleTestCase(practice_problem4b, [[12, 33, 18, 'hello', 9, 13, 3, 9]], True), st.SimpleTestCase(practice_problem4b, [[12, 12, 33, 'hello', 5, 33, 5, 9]], False), st.SimpleTestCase(practice_problem4b, [(77, 112, 33, 'hello', 0, 43, 5, 77)], True), st.SimpleTestCase(practice_problem4b, [[1, 1, 1, 1, 1, 1, 2]], False), st.SimpleTestCase(practice_problem4b, [['aa', 'a']], False), st.SimpleTestCase(practice_problem4b, ['aaa'], True), st.SimpleTestCase(practice_problem4b, [['aa', 'a', 'b', 'a', 'b', 'a']], True), st.SimpleTestCase(practice_problem4b, [[9]], False), st.SimpleTestCase(practice_problem4b, [(12, 33, 8, 'hello', 99, 'hello')], True), st.SimpleTestCase(practice_problem4b, [['hello there', 'he', 'lo', 'hello']], False), st.SimpleTestCase(practice_problem4b, [((8,), '8', (4 + 4, 4 + 4), [8, 8], 7, 8)], False), st.SimpleTestCase(practice_problem4b, [[(8,), '8', [4 + 4, 4 + 4], (8, 8), 7, [8, 8]]], True), st.SimpleTestCase(practice_problem4b, [[(8,), '8', [4 + 4, 4 + 4], [8, 8], 7, (8, 8)]], False), ] # Run the 13 tests in the tests list constructed above. st.SimpleTestCase.run_tests('practice_problem4b', tests) # ------------------------------------------------------------------ # TODO 4 continued: More tests: # YOU add at least ** 2 ** additional tests here. # # You can use the SimpleTestCase class as above, or use # the ordinary expected/actual way, your choice. # # SUGGESTION: Ask an assistant to CHECK your tests to confirm # that they are adequate tests! # ------------------------------------------------------------------ expected = True actual = practice_problem4b((12, 33, 118, 11, 173, 3, 9, 1, 190, 11)) print('Actual is ', actual, 'expected is ', expected) expected = True actual = practice_problem4b((112, 11, -5, 9, 13, 3, 9, 120, 19, 11)) print('Actual is ', actual, 'expected is ', expected) def practice_problem4b(sequence): """ INPUT: A non-empty sequence. OUTPUT: True or False (see DESCRIPTION). SIDE EFFECTS: None. DESCRIPTION: Returns True if the last element of the sequence appears again somewhere else in the sequence. Otherwise returns False. EXAMPLES: For example, given: sequence = [12, 33, 18, 'hello', 9, 13, 3, 9] - returns True sequence = [12, 12, 33, 'hello', 5, 33, 5, 9] - returns False sequence = [77, 112, 33, 'hello', 0, 43, 5, 77] - returns True sequence = [9] - returns False sequence = [12, 33, 8, 'hello', 99, 'hello'] - returns True sequence = ['hello there', 'he', 'lo', 'hello'] - returns False Precondition: :type: sequence: (list, tuple, str) that is non-empty. """ # ------------------------------------------------------------------ # TODO: 5. Implement and test this function. # Some tests are already written for you (above), # but you are required to write ADDITIONAL tests (above). # # IMPLEMENTATION REQUIREMENT: You are NOT allowed to use the # 'count' or 'index' methods for sequences in this problem # (because here we want you to demonstrate your ability # to use explicit looping here). # ------------------------------------------------------------------ if len(sequence) > 1: for k in range(len(sequence) - 1): if sequence[k] == sequence[len(sequence) - 1]: return True return False elif len(sequence) == 1: return False def test_practice_problem4c(): """ Tests the practice_problem4c function. """ # ------------------------------------------------------------------ # TODO: 6. Implement this TEST function. # It TESTS the practice_problem4c function defined below. # Include at least ** 2 ** ADDITIONAL tests (we wrote 4 for you). # # Try to choose tests that might expose errors in your code! # # Use the same 4-step process as for previous TEST functions. # ------------------------------------------------------------------ expected = [1, 5] actual = practice_problem4c((12, 33, 33, 'a', 173, 3, 3, 1, 190, 'a')) print('Actual is ', actual, 'expected is ', expected) expected = [] actual = practice_problem4c((112, [2, 0], -5, 9, 13, 3, 9, 120, 19, [2, 0])) print('Actual is ', actual, 'expected is ', expected) # 4 tests. They use the imported simple_testing (st) module. tests = [st.SimpleTestCase(practice_problem4c, [(9, 33, 8, 8, 0, 4, 4, 8)], [2, 5]), st.SimpleTestCase(practice_problem4c, [(9, 9, 9, 9, 0, 9, 9, 9)], [0, 1, 2, 5, 6]), st.SimpleTestCase(practice_problem4c, [(4, 5, 4, 5, 4, 5, 4)], []), st.SimpleTestCase(practice_problem4c, ['abbabbb'], [1, 4, 5]), ] # Run the 4 tests in the tests list constructed above. st.SimpleTestCase.run_tests('practice_problem4c', tests) # ------------------------------------------------------------------ # TODO 6 continued: More tests: # YOU add at least ** 2 ** additional tests here. # # You can use the SimpleTestCase class as above, or use # the ordinary expected/actual way, your choice. # # SUGGESTION: Ask an assistant to CHECK your tests to confirm # that they are adequate tests! # ------------------------------------------------------------------ expected = [] actual = practice_problem4c((12, 33, 118, 9, 8, 9, 0, 1, 190, 20)) print('Actual is ', actual, 'expected is ', expected) expected = [0] actual = practice_problem4c((0, 0, -5, 9, 13, 3, 9, 120, 19, 20)) print('Actual is ', actual, 'expected is ', expected) def practice_problem4c(sequence): """ INPUT: A non-empty sequence. OUTPUT: A list of integers (see DESCRIPTION). SIDE EFFECTS: None. DESCRIPTION: Returns a list containing all the places (indices) where an item in the given sequence appears twice in a row. EXAMPLES: Given sequence (9, 33, 8, 8, 0, 4, 4, 8) -- this function returns [2, 5] since 8 appears twice in a row starting at index 2 and 4 appears twice in a row starting at index 5 Given sequence (9, 9, 9, 9, 0, 9, 9, 9) -- this function returns [0, 1, 2, 5, 6] Given sequence (4, 5, 4, 5, 4, 5, 4) -- this function returns [] Given sequence 'abbabbb' -- this function returns [1, 4, 5] Precondition: :type: sequence: (list, tuple, str) that is non-empty. """ # ------------------------------------------------------------------ # TODO: 7. Implement and test this function. # Some tests are already written for you (above), # but you are required to write ADDITIONAL tests (above). # ------------------------------------------------------------------ list = [] for k in range(len(sequence) - 1): if sequence[k] == sequence[k + 1]: list += [k] return list def test_practice_problem4d(): """ Tests the practice_problem4d function. """ # ------------------------------------------------------------------ # TODO: 8. Implement this TEST function. # It TESTS the practice_problem4d function defined below. # Include at least ** 2 ** ADDITIONAL tests (we wrote 5 for you). # # Try to choose tests that might expose errors in your code! # # Use the same 4-step process as for previous TEST functions. # ------------------------------------------------------------------ expected = 23 actual = practice_problem4d((0, 0, 7, 7, 13, 3, 7, 120, 19, 20)) print('Actual is ', actual, 'expected is ', expected) expected = 13 actual = practice_problem4d((0, 0, -5, 9, 13, 3, 9, 120, 19, 20)) print('Actual is ', actual, 'expected is ', expected) # 3 tests. They use the imported simple_testing (st) module. tests = [st.SimpleTestCase(practice_problem4d, [(6, 80, 17, 13, 40, 3, 3, 7, 13, 7, 12, 5)], 17 + 3 + 7 + 13), st.SimpleTestCase(practice_problem4d, [(7, 7, 7, 7, 7, 4, 4, 8, 5, 5, 6)], 0), st.SimpleTestCase(practice_problem4d, [(2, 3, 5, 7, 5, 3, 2)], 2 + 3 + 5 + 7 + 5 + 3), st.SimpleTestCase(practice_problem4d, [(11, 3, 17, 13, 40, 3, 3, 7, 13, 7, 12, 5)], 11 + 3 + 17 + 3 + 7 + 13), st.SimpleTestCase(practice_problem4d, [(6, 80, 17, 13, 40, 3, 3, 7, 13, 7, 11, 5)], 17 + 3 + 7 + 13 + 7 + 11), ] # Run the 5 tests in the tests list constructed above. st.SimpleTestCase.run_tests('practice_problem4d', tests) # ------------------------------------------------------------------ # TODO 8 continued: More tests: # YOU add at least ** 2 ** additional tests here. # # You can use the SimpleTestCase class as above, or use # the ordinary expected/actual way, your choice. # # SUGGESTION: Ask an assistant to CHECK your tests to confirm # that they are adequate tests! # ------------------------------------------------------------------ expected = 10 actual = practice_problem4d((0, 0, 7, 7, 7, 3, 7, 120, 19, 20)) print('Actual is ', actual, 'expected is ', expected) expected = 16 actual = practice_problem4d((1, 3, 5, 9, 13, 3, 9, 120, 19, 20)) print('Actual is ', actual, 'expected is ', expected) def practice_problem4d(sequence): """ INPUT: A non-empty sequence of integers. OUTPUT: An integer that is the sum of certain prime numbers (see DESCRIPTION). SIDE EFFECTS: None. DESCRIPTION: Returns the sum of all the items in the given sequence such that the item is a prime number and its immediate successor is a DIFFERENT prime number. EXAMPLES: Given sequence (6, 80, 17, 13, 40, 3, 3, 7, 13, 7, 12, 5) -- this function returns 17 + 3 + 7 + 13, which is 40 Given sequence (7, 7, 7, 7, 7, 4, 4, 8, 5, 5, 6) -- this function returns 0 Given sequence (2, 3, 5, 7, 5, 3, 2) -- this function returns 2 + 3 + 5 + 7 + 5 + 3, which is 25 Preconditions: :type: sequence: (list, tuple) of integers with len(sequence) >= 2. """ # ------------------------------------------------------------------ # TODO: 9. Implement and test this function. # Some tests are already written for you (above), # but you are required to write ADDITIONAL tests (above). # # IMPLEMENTATION REQUIREMENT: # Use (call) the is_prime function define above, # as appropriate. # ------------------------------------------------------------------ sum = 0 for k in range(len(sequence) - 1): if is_prime(sequence[k]) == True and is_prime(sequence[k + 1]) == True and sequence[k] != sequence[k + 1] : sum += sequence[k] return sum # ---------------------------------------------------------------------- # Calls main to start the ball rolling. # ---------------------------------------------------------------------- main()
#!/usr/bin/env /proj/sot/ska/bin/python ############################################################################################# # # # ccd_comb_plot.py: read data and create SIB plots # # monthly, quorterly, one year, and last year # # EDIT THE END OF THE SCRIPT TO PLOT MONTHLY DATA: OUTPUT WILL BE IN # # /data/mta_www/mta_sib/Plot # # # # author: t. isobe (tisobe@cfa.harvard.edu) # # # # Last Update: Oct 24, 2016 # # # ############################################################################################# import os import sys import re import string import random import operator import pyfits import numpy import matplotlib as mpl if __name__ == '__main__': mpl.use('Agg') # #--- reading directory list # comp_test = 'live' if comp_test == 'test' or comp_test == 'test2': path = '/data/mta/Script/ACIS/SIB/house_keeping/dir_list_py_test' else: path = '/data/mta/Script/ACIS/SIB/house_keeping/dir_list_py' f = open(path, 'r') data = [line.strip() for line in f.readlines()] f.close() for ent in data: atemp = re.split(':', ent) var = atemp[1].strip() line = atemp[0].strip() exec "%s = %s" %(var, line) # #--- check whether this is run for lev2 # level = 1 if len(sys.argv) == 2: if sys.argv[1] == 'lev2': data_dir = data_dir2 web_dir = web_dir + 'Lev2/' level = 2 # #--- append a path to a private folder to python directory # sys.path.append(bin_dir) sys.path.append(mta_dir) # #--- converTimeFormat contains MTA time conversion routines # import convertTimeFormat as tcnv import mta_common_functions as mcf import robust_linear as robust # #--- temp writing file name # rtail = int(10000 * random.random()) zspace = '/tmp/zspace' + str(rtail) # #--- set a list of the name of the data # nameList = ['Super Soft Photons', 'Soft Photons', 'Moderate Energy Photons', 'Hard Photons', 'Very Hard Photons', 'Beyond 10 keV'] #--------------------------------------------------------------------------------------------------- #-- ccd_comb_plot: a control script to create plots --- #--------------------------------------------------------------------------------------------------- def ccd_comb_plot(choice, syear = 2000, smonth = 1, eyear = 2000, emonth = 1, header = 'plot_ccd'): """ a control script to create plots Input: choice --- if normal, monthly updates of plots are created. if check, plots for a given period are created syear --- starting year of the period, choice must be 'check' smonth --- starting month of the period, choice must be 'check' eyear --- ending year of the period, choice must be 'check' emonth --- ending month of the period, choice must be 'check' header --- a header of the plot file choice must be 'check' Output: png formated plotting files """ # #--- find today's date, and set a few thing needed to set output directory and file name # if choice == 'check': dlist = collect_data_file_names('check', syear, smonth, eyear, emonth) plot_out = web_dir + '/Plot/' #check_and_create_dir(plot_out) plot_data(dlist, plot_out, header, yr=syear, mo=smonth) #--------------------------------------------------------------------------------------------------- #-- check_and_create_dir: check whether a directory exist, if not, create one --- #--------------------------------------------------------------------------------------------------- def check_and_create_dir(dir): """ check whether a directory exist, if not, create one Input: dir --- directory name Output: directory created if it was not there. """ chk = mcf.chkFile(dir) if chk == 0: cmd = 'mkdir ' + dir os.system(cmd) #--------------------------------------------------------------------------------------------------- #-- define_x_range: set time plotting range --- #--------------------------------------------------------------------------------------------------- def define_x_range(dlist, xunit=''): """ set time plotting range Input: dlist --- list of data files (e.g., Data_2012_09) Output: start --- starting time in either DOM or fractional year end --- ending time in either DOM or fractional year """ num = len(dlist) if num == 1: atemp = re.split('Data_', dlist[0]) btemp = re.split('_', atemp[1]) year = int(btemp[0]) month = int(btemp[1]) nyear = year nmonth = month + 1 if nmonth > 12: nmonth = 1 nyear += 1 else: slist = sorted(dlist) atemp = re.split('Data_', slist[0]) btemp = re.split('_', atemp[1]) year = int(btemp[0]) month = int(btemp[1]) atemp = re.split('Data_', slist[len(slist)-1]) btemp = re.split('_', atemp[1]) tyear = int(btemp[0]) tmonth = int(btemp[1]) nyear = tyear nmonth = tmonth + 1 if nmonth > 12: nmonth = 1 nyear += 1 start = tcnv.findDOM(year, month, 1, 0, 0, 0) end = tcnv.findDOM(nyear, nmonth, 1, 0, 0, 0) # #--- if it is a long term, unit is in year # if xunit == 'year': [syear, sydate] = tcnv.DOMtoYdate(start) chk = 4.0 * int(0.25 * syear) if chk == syear: base = 366 else: base = 365 start = syear + sydate/base [eyear, eydate] = tcnv.DOMtoYdate(end) chk = 4.0 * int(0.25 * eyear) if chk == eyear: base = 366 else: base = 365 end = eyear + eydate/base return [start, end] #--------------------------------------------------------------------------------------------------- #-- plot_data: for a given data directory list, prepare data sets and create plots --- #--------------------------------------------------------------------------------------------------- def plot_data(dlist, plot_out, header, yr='', mo='', xunit='', psize=1): """ for a given data directory list, prepare data sets and create plots Input: dlist --- a list of input data directories plot_out -- a directory name where the plots are deposited header --- a head part of the plotting file yr --- a year in string form optional mo --- a month in letter form optional xunit --- if "year", the plotting is made with fractional year, otherwise in dom psize --- a size of plotting point. Output: a png formated file """ # #--- set lists for accumulated data sets # time_full = [] count_full = [] time_ccd5 = [] count_ccd5 = [] time_ccd6 = [] count_ccd6 = [] time_ccd7 = [] count_ccd7 = [] # #--- set plotting range for x # [xmin, xmax] = define_x_range(dlist, xunit=xunit) # #--- go though all ccds # for ccd in range(0, 10): outname = plot_out + header + str(ccd) + '.png' filename = 'lres_ccd' + str(ccd) + '_merged.fits' # #--- extract data from data files in the list and combine them # [atime, assoft, asoft, amed, ahard, aharder, ahardest] = accumulate_data(dlist, filename) if len(atime) > 0: # #--- if the plot is a long term, use the unit of year. otherwise, dom # if xunit == 'year': xtime = convert_time(atime, format=1) else: xtime = convert_time(atime) # #--- create the full range and ccd 5, 6, and 7 data sets # xdata = [] ydata = [] for i in range(0, len(xtime)): time_full.append(xtime[i]) xdata.append(xtime[i]) sum = assoft[i] + asoft[i] + amed[i] + ahard[i] + aharder[i] + ahardest[i] count_full.append(sum) ydata.append(sum) if ccd == 5: time_ccd5 = xtime for i in range(0, len(xtime)): sum = assoft[i] + asoft[i] + amed[i] + ahard[i] + aharder[i] + ahardest[i] count_ccd5.append(sum) if ccd == 6: time_ccd6 = xtime for i in range(0, len(xtime)): sum = assoft[i] + asoft[i] + amed[i] + ahard[i] + aharder[i] + ahardest[i] count_ccd6.append(sum) if ccd == 7: time_ccd7 = xtime for i in range(0, len(xtime)): sum = assoft[i] + asoft[i] + amed[i] + ahard[i] + aharder[i] + ahardest[i] count_ccd7.append(sum) # #--- prepare for the indivisual plot # xsets = [] for i in range(0, 6): xsets.append(xtime) data_list = (assoft, asoft, amed, ahard, aharder, ahardest) # #--- plottting data # entLabels = nameList plot_data_sub(xsets, data_list, entLabels, xmin, xmax, outname, xunit=xunit) # #--- combined data for the ccd # xset_comb = [xdata] data_comb = [ydata] name = 'CCD' + str(ccd) + ' combined' entLabels = [name] outname2 = change_outname_comb(header, plot_out, ccd) plot_data_sub(xset_comb, data_comb, entLabels, xmin, xmax, outname2, xunit=xunit) else: cmd = 'cp ' + house_keeping + 'no_data.png ' + outname os.system(cmd) outname2 = change_outname_comb(header, plot_out, ccd) cmd = 'cp ' + house_keeping + 'no_data.png ' + outname2 os.system(cmd) # #--- combined data plot # xsets = [time_full] data_list = [count_full] entLabels = ['Total SIB'] outname = plot_out + header + '_combined.png' plot_data_sub(xsets, data_list, entLabels, xmin, xmax, outname, xunit=xunit) # #--- ccd5, ccd6, and ccd7 # xsets = [time_ccd5, time_ccd6, time_ccd7] data_list = [count_ccd5, count_ccd6, count_ccd7] entLabels = ['CCD5', 'CCD6', 'CCD7'] outname = plot_out + header + '_ccd567.png' plot_data_sub(xsets, data_list, entLabels, xmin, xmax, outname, xunit=xunit) # #--- add html page # #--------------------------------------------------------------------------------------------------- #-- add_html_page: update/add html page to Plot directory --- #--------------------------------------------------------------------------------------------------- def add_html_page(ptype, plot_out, yr, mo): """ update/add html page to Plot directory Input: ptype --- indiecator of which html page to be updated plot_out --- a directory where the html page is updated/created yr --- a year of the file mo --- a month of the file Output: either month.html or year.hmtl in an appropriate directory """ current = tcnv.currentTime(format='Display') lmon = '' if ptype == 'month': ofile = plot_out + 'month.html' lmon = tcnv.changeMonthFormat(int(mo)) if level == 2: file = house_keeping + 'month2.html' else: file = house_keeping + 'month.html' elif ptype == 'year': ofile = plot_out + 'year.html' if level == 2: file = house_keeping + 'year2.html' else: file = house_keeping + 'year.html' text = open(file, 'r').read() text = text.replace('#YEAR#', yr) text = text.replace('#MONTH#', lmon) text = text.replace('#DATE#', current) f = open(ofile, 'w') f.write(text) f.close() #--------------------------------------------------------------------------------------------------- #-- change_outname_comb: change file name to "comb" form --- #--------------------------------------------------------------------------------------------------- def change_outname_comb(header, plot_out, ccd): """ change file name to "comb" form Input: header --- original header form plot_out --- output directory name ccd --- ccd # Output: outname --- <plot_out>_<modified header>_ccd<ccd#>.png """ for nchk in ('month'): n1 = re.search(nchk, header) if n1 is not None: rword = nchk ptype = nchk nword = 'combined_' + nchk break header = header.replace(rword, nword) outname = plot_out + header + str(ccd) + '.png' return outname #--------------------------------------------------------------------------------------------------- #-- plot_data_sub: plotting data --- #--------------------------------------------------------------------------------------------------- def plot_data_sub(xSets, data_list, entLabels, xmin, xmax, outname, xunit=0, psize=1.0): """ plotting data Input: XSets --- a list of lists of x values data_list --- a list of lists of y values entLabels --- a list of names of the data xmin --- starting of x range xmax --- ending of x range outname --- output file name xunit --- if "year" x is plotted in year format, otherwise dom psize --- size of the plotting point Output: outname --- a png formated plot """ try: if xunit == 'year': xmin = int(xmin) xmax = int(xmax) + 2 else: xdiff = xmax - xmin xmin -= 0.05 * xdiff xmax += 0.05 * xdiff # #--- now set y related quantities # ySets = [] yMinSets = [] yMaxSets = [] for data in data_list: yMinSets.append(0) ySets.append(data) if len(data) > 0: ymax = set_Ymax(data) yMaxSets.append(ymax) else: yMaxSets.append(1) if xunit == 'year': xname = 'Time (Year)' else: xname = 'Time (DOM)' yname = 'cnts/s' # #--- actual plotting is done here # plotPanel(xmin, xmax, yMinSets, yMaxSets, xSets, ySets, xname, yname, entLabels, outname, psize=psize) except: cmd = 'cp ' + house_keeping + 'no_data.png ' + outname os.system(cmd) #--------------------------------------------------------------------------------------------------- #-- set_Ymax: find a plotting range --- #--------------------------------------------------------------------------------------------------- def set_Ymax(data): """ find a plotting range Input: data --- data Output: ymax --- max rnage set in 4.0 sigma from the mean """ avg = numpy.mean(data) sig = numpy.std(data) ymax = avg + 4.0 * sig if ymax > 20: ymax = 20 return ymax #--------------------------------------------------------------------------------------------------- #-- collect_data_file_names: or a given period, create a list of directory names --- #--------------------------------------------------------------------------------------------------- def collect_data_file_names(period, syear=2000, smonth=1, eyear=2000, emonth=12): """ for a given period, create a list of directory names Input: period --- indicator of which peirod, "month", "quarter", "year", "lyear", "full", and "check'" if period == 'check', then you need to give a period in year and month syear --- year of the starting date smonth --- month of the starting date eyear --- year of the ending date emonth --- month of the ending date Output data_lst --- a list of the directory names """ # #--- find today's date # [year, mon, day, hours, min, sec, weekday, yday, dst] = tcnv.currentTime() data_list = [] # #--- find the last month # if period == 'month': mon -= 1 if mon < 1: mon = 12 year -= 1 if mon < 10: cmon = '0' + str(mon) else: cmon = str(mon) dfile = data_dir + 'Data_' + str(year) + '_' + cmon data_list.append(dfile) # #--- find the last three months # if period == 'quarter': for i in range(1, 4): lyear = year month = mon -i if month < 1: month = 12 + month lyear = year -1 if month < 10: cmon = '0' + str(month) else: cmon = str(month) dfile = data_dir + 'Data_' + str(lyear) + '_' + cmon data_list.append(dfile) # #--- find data for the last one year (ending the last month) # elif period == 'year': cnt = 0 if mon > 1: for i in range(1, mon): if i < 10: cmon = '0' + str(i) else: cmon = str(i) dfile = data_dir + 'Data_' + str(year) + '_' + cmon data_list.append(dfile) cnt += 1 if cnt < 11: year -= 1 for i in range(mon, 13): if i < 10: cmon = '0' + str(i) else: cmon = str(i) dfile = data_dir + 'Data_' + str(year) + '_' + cmon data_list.append(dfile) # #--- fill the list with the past year's data # elif period == 'lyear': year -= 1 for i in range(1, 13): if i < 10: cmon = '0' + str(i) else: cmon = str(i) dfile = data_dir + 'Data_' + str(year) + '_' + cmon data_list.append(dfile) # #--- fill the list with the entire data # elif period == 'full': for iyear in range(2000, year+1): for i in range (1, 13): if i < 10: cmon = '0' + str(i) else: cmon = str(i) dfile = data_dir + 'Data_' + str(iyear) + '_' + cmon data_list.append(dfile) # #--- if the period is given, use them # elif period == 'check': syear = int(syear) eyear = int(eyear) smonth = int(smonth) emonth = int(emonth) if syear == eyear: for i in range(smonth, emonth+1): if i < 10: cmon = '0' + str(i) else: cmon = str(i) dfile = data_dir + 'Data_' + str(syear) + '_' + cmon data_list.append(dfile) elif syear < eyear: for iyear in range(syear, eyear+1): if iyear == syear: for month in range(smonth, 13): if i < 10: cmon = '0' + str(i) else: cmon = str(i) dfile = data_dir + 'Data_' + str(iyear) + '_' + cmon data_list.append(dfile) elif iyear == eyear: for month in range(1, emonth+1): if i < 10: cmon = '0' + str(i) else: cmon = str(i) dfile = data_dir + 'Data_' + str(iyear) + '_' + cmon data_list.append(dfile) else: for month in range(1, 13): if i < 10: cmon = '0' + str(i) else: cmon = str(i) dfile = data_dir + 'Data_' + str(iyear) + '_' + cmon data_list.append(dfile) return data_list #--------------------------------------------------------------------------------------------------- #-- read_data_file: read out needed data from a given file --- #--------------------------------------------------------------------------------------------------- def read_data_file(file): """ read out needed data from a given file Input: file --- input file name Output: a list of lists of data: [time, ssoft, soft, med, hard, harder, hardest] """ try: hdulist = pyfits.open(file) tbdata = hdulist[1].data # #--- extracted data are 5 minutes accumulation; convert it into cnt/sec # time = tbdata.field('time').tolist() ssoft = (tbdata.field('SSoft') / 600.0).tolist() soft = (tbdata.field('Soft') / 600.0).tolist() med = (tbdata.field('Med') / 600.0).tolist() hard = (tbdata.field('Hard') / 600.0).tolist() harder = (tbdata.field('Harder') / 600.0).tolist() hardest = (tbdata.field('Hardest') / 600.0).tolist() hdulist.close() return [time, ssoft, soft, med, hard, harder, hardest] except: return [[], [], [], [], [], [], []] #--------------------------------------------------------------------------------------------------- #-- accumulate_data: combine the data in the given period --- #--------------------------------------------------------------------------------------------------- def accumulate_data(inlist, file): """ combine the data in the given period Input: inlist: a list of data directories to extract data file: a file name of the data Output: a list of combined data lst: [atime, assoft, asoft, amed, ahard, aharder, ahardest] """ atime = [] assoft = [] asoft = [] amed = [] ahard = [] aharder = [] ahardest = [] for dname in inlist: infile = dname + '/' + file chk = mcf.chkFile(infile) if chk == 0: infile = infile + '.gz' try: [time, ssoft, soft, med, hard, harder, hardest] = read_data_file(infile) atime = atime + time assoft = assoft + ssoft asoft = asoft + soft amed = amed + med ahard = ahard + hard aharder = aharder + harder ahardest = ahardest + hardest except: pass return [atime, assoft, asoft, amed, ahard, aharder, ahardest] #--------------------------------------------------------------------------------------------------- #-- convert_time: convert time format from seconds from 1998.1.1 to dom or fractional year --- #--------------------------------------------------------------------------------------------------- def convert_time(time, format = 0): """ convert time format from seconds from 1998.1.1 to dom or fractional year Input: time --- a list of time in seconds format --- if 0, convert into dom, otherwise, fractional year Output: timeconverted --- a list of conveted time """ timeconverted = [] for ent in time: stime = tcnv.convertCtimeToYdate(ent) atime = tcnv.dateFormatConAll(stime) if format == 0: timeconverted.append(float(atime[7])) else: year = float(atime[0]) ydate = float(atime[6]) chk = 4.0 * int(0.25 * year) if chk == year: base = 366 else: base = 365 year += ydate /base timeconverted.append(year) return timeconverted #--------------------------------------------------------------------------------------------------- #--- plotPanel: plots multiple data in separate panels --- #--------------------------------------------------------------------------------------------------- def plotPanel(xmin, xmax, yMinSets, yMaxSets, xSets, ySets, xname, yname, entLabels, outname, psize=1.0): """ This function plots multiple data in separate panels Input: xmin, xmax, ymin, ymax: plotting area xSets: a list of lists containing x-axis data ySets: a list of lists containing y-axis data yMinSets: a list of ymin yMaxSets: a list of ymax entLabels: a list of the names of each data Output: a png plot: out.png """ # #--- set line color list # colorList = ('blue', 'green', 'red', 'aqua', 'lime', 'fuchsia', 'maroon', 'black', 'yellow', 'olive') # #--- clean up the plotting device # plt.close('all') # #---- set a few parameters # mpl.rcParams['font.size'] = 9 props = font_manager.FontProperties(size=9) plt.subplots_adjust(hspace=0.08) tot = len(entLabels) # #--- start plotting each data # for i in range(0, len(entLabels)): axNam = 'ax' + str(i) # #--- setting the panel position # j = i + 1 if i == 0: line = str(tot) + '1' + str(j) else: line = str(tot) + '1' + str(j) + ', sharex=ax0' line = str(tot) + '1' + str(j) exec "%s = plt.subplot(%s)" % (axNam, line) exec "%s.set_autoscale_on(False)" % (axNam) #---- these three may not be needed for the new pylab, but exec "%s.set_xbound(xmin,xmax)" % (axNam) #---- they are necessary for the older version to set exec "%s.set_xlim(xmin=xmin, xmax=xmax, auto=False)" % (axNam) exec "%s.set_ylim(ymin=yMinSets[i], ymax=yMaxSets[i], auto=False)" % (axNam) xdata = xSets[i] ydata = ySets[i] # #---- actual data plotting # p, = plt.plot(xdata, ydata, color=colorList[i], marker='.', markersize=psize, lw =0) # #---- compute fitting line # (intc, slope, berr) = robust.robust_fit(xdata, ydata) cslope = str('%.4f' % round(slope, 4)) ystart = intc + slope * xmin yend = intc + slope * xmax plt.plot([xmin, xmax], [ystart, yend], color=(colorList[i+2]), lw=1) # #--- add legend # tline = entLabels[i] + ' Slope: ' + cslope leg = legend([p], [tline], prop=props, loc=2) leg.get_frame().set_alpha(0.5) exec "%s.set_ylabel(yname, size=8)" % (axNam) # #--- add x ticks label only on the last panel # for i in range(0, tot): ax = 'ax' + str(i) if i != tot-1: exec "line = %s.get_xticklabels()" % (ax) for label in line: label.set_visible(False) else: pass xlabel(xname) # #--- set the size of the plotting area in inch (width: 10.0in, height 2.08in x number of panels) # fig = matplotlib.pyplot.gcf() height = (2.00 + 0.08) * tot fig.set_size_inches(10.0, height) # #--- save the plot in png format # plt.savefig(outname, format='png', dpi=100) #-------------------------------------------------------------------- # #--- pylab plotting routine related modules # from pylab import * import matplotlib.pyplot as plt import matplotlib.font_manager as font_manager import matplotlib.lines as lines if __name__ == '__main__': # ccd_comb_plot('normal') # ccd_comb_plot('other') ccd_comb_plot('check', syear=2017, smonth=12, eyear=2017, emonth=12, header='month_plot_ccd')
import io import os.path import string import sys from textwrap import dedent from hypothesis import given, example, note, assume from hypothesis.strategies import text from py2_compat import unittest, mock from django_develop import utils TEST_ROOT = os.path.dirname(__file__) class TestVirtualEnvDetection(unittest.TestCase): def test_is_inside_virtual_env(self): """ Check `utils.is_inside_virtual_env()` against various sets of sys prefix paths. """ system = mock.sentinel.system virtual = mock.sentinel.virtual # These are the sets of sys module attributes that should be present or absent # with various versions of Python and virtualenv / venv. test_cases = { 'py2_base': dict(prefix=system), # Python 3 (as of 3.3 / PEP 405) adds a sys.base_prefix attribute 'py3_base': dict(base_prefix=system, prefix=system), 'py3_venv': dict(base_prefix=system, prefix=virtual), # virtualenv saves sys.real_prefix, and changes the others 'py2_virtualenv': dict(real_prefix=system, prefix=virtual), 'py3_virtualenv': dict(real_prefix=system, prefix=virtual, base_prefix=virtual), } for (label, sys_attrs) in test_cases.items(): with self.subTest(label=label): # Note: The spec=[] is important so that absent sys_attrs raise AttributeError # instead of returning mocks. with mock.patch('django_develop.utils.sys', spec=[], **sys_attrs): expected = sys_attrs['prefix'] is virtual self.assertEqual(utils.is_inside_virtual_env(), expected) class TestIsCandidateName(unittest.TestCase): """ `utils.is_candidate_name()` """ # Hacky strategy for module names modnames = text(string.printable).map(str) @given(modnames.filter(lambda s: 'settings' not in s)) @example('not_a_setting') def test_non_candidates(self, modname): """ Random names aren't candidates. """ self.assertFalse(utils.is_candidate_name(modname)) @given(modnames, modnames) @example('foo_', '_bar') @example('app.', '.mod') def test_candidates(self, pre, post): """ Names containing "settings" are candidates. """ modname = pre + 'settings' + post note('modname={!r}'.format(modname)) self.assertTrue(utils.is_candidate_name(modname)) # Special-cased names specials = [ 'django.conf.global_settings', 'django.core.management.commands.diffsettings', 'django_develop.dev_settings', ] def test_exceptions(self): """ The special-cased names are not candidates. """ for modname in self.specials: with self.subTest(modname=modname): self.assertFalse(utils.is_candidate_name(modname)) @given(modnames, modnames) @example('foo_', '_bar') @example('app.', '.mod') def test_modified_exceptions(self, pre, post): """ Prefixed and suffixed versions of the special-cased names are not excepted. """ assume(pre or post) # Require at least some prefix or suffix for special in self.specials: modname = pre + special + post note('modname={!r}'.format(modname)) self.assertTrue(utils.is_candidate_name(modname)) class TestDiscoverCandidateSettings(unittest.TestCase): """ `utils.discover_candidate_settings()` """ def test_dummy_path(self): """ Discover no candidates from an empty / dummy `sys.path`. """ paths = [ [], ['dummy'], ['foo', 'bar'], ] for path in paths: with self.subTest(path=path): with mock.patch('sys.path', path): self.assertEqual( list(utils.discover_candidate_settings()), []) def test_examples(self): """ Discover the example settings modules. """ # Limit the search to the test root to avoid having to mask out third-party modules, # such as hypothesis._settings. with mock.patch('sys.path', [TEST_ROOT]): self.assertEqual( list(utils.discover_candidate_settings()), [(TEST_ROOT, [ 'test_examples.error_settings', 'test_examples.likely_settings', 'test_examples.no_likely_settings', 'test_examples.no_settings', ])]) class TestFindPotentialProblems(unittest.TestCase): """ `utils.find_potential_problems()` """ def test_import_failures(self): """ Flag import failures. """ # Python 3.6 introduced ModuleNotFoundError. # https://docs.python.org/3/whatsnew/3.6.html#other-language-changes _ModuleNotFoundError = 'ImportError' if sys.version_info < (3, 6) else 'ModuleNotFoundError' cases = { '': {'import raised ValueError'}, '.': {'import raised TypeError'}, '..': {'import raised TypeError'}, '.foo': {'import raised TypeError'}, ' ': {'import raised {}'.format(_ModuleNotFoundError)}, 'nonexistent': {'import raised {}'.format(_ModuleNotFoundError)}, 'not.existent': {'import raised {}'.format(_ModuleNotFoundError)}, 'test_examples.error_settings': {'import raised NameError'}, } for (modname, problems) in cases.items(): with self.subTest(modname=modname): self.assertEqual(utils.find_potential_problems(modname), problems) def test_problems(self): """ Flag importable modules with with problems. """ cases = { 'test_examples.no_settings': {'no uppercase names'}, 'test_examples.no_likely_settings': {'no likely setting names'}, } for (modname, problems) in cases.items(): with self.subTest(modname=modname): self.assertEqual(utils.find_potential_problems(modname), problems) def test_likely_settings(self): """ Pass modules with likely setting names. """ self.assertEqual( utils.find_potential_problems('test_examples.likely_settings'), set()) def test_individual_likely_settings(self): """ The presence of any one of these settings makes a module count as likely. """ likely_names = [ 'DATABASES', 'EMAIL_BACKEND', 'INSTALLED_APPS', 'MEDIA_ROOT', 'MEDIA_URL', 'MIDDLEWARE_CLASSES', 'ROOT_URLCONF', 'SECRET_KEY', 'SITE_ID', 'STATIC_ROOT', 'STATIC_URL', ] for name in likely_names: with self.subTest(name=name): with mock.patch.multiple('test_examples.no_likely_settings', create=True, **{name: 'dummy'}): self.assertEqual( utils.find_potential_problems('test_examples.no_likely_settings'), set()) class TestPrintCandidateSettings(unittest.TestCase): """ `utils.print_candidate_settings()` """ def _patch_stdout(self): # Python 2 compatibility: Intercept sys.stdout with BytesIO instead of StringIO. return mock.patch('sys.stdout', new_callable=( io.BytesIO if sys.version_info < (3,) else io.StringIO)) def test_no_candidates(self): """ Printing out no candidates. """ with mock.patch('sys.path', []): with self._patch_stdout() as stdout: utils.print_candidate_settings() self.assertEqual(stdout.getvalue(), dedent("""\ Looking for usable Django settings modules in Python path... None found. """)) def test_likely_candidates(self): """ Printing a likely candidate. """ with self._patch_stdout() as stdout: utils.print_candidate_settings() self.assertEqual(stdout.getvalue(), dedent("""\ Looking for usable Django settings modules in Python path... Found: In {}: test_examples.likely_settings """.format(TEST_ROOT))) def test_all_candidates(self): """ Printing and reporting problematic candidates too. """ with mock.patch('sys.path', [TEST_ROOT]): with self._patch_stdout() as stdout: utils.print_candidate_settings(include_problems=True) self.assertEqual(stdout.getvalue(), dedent("""\ Looking for usable Django settings modules in Python path... Found: In {}: test_examples.error_settings (import raised NameError) test_examples.likely_settings test_examples.no_likely_settings (no likely setting names) test_examples.no_settings (no uppercase names) """.format(TEST_ROOT)))
from matplotlib import pyplot as plt from skimage import data from skimage.feature import blob_dog, blob_log, blob_doh from math import sqrt from skimage.color import rgb2gray ''' Laplacian of Gaussian (LoG): 这是速度最慢,可是最准确的一种算法。简单来说,就是对一幅图先进行一系列不同尺度的高斯滤波,然后对滤波后的图像做Laplacian运算。将全部的图像进行叠加。局部最大值就是所要检測的blob,这个算法对于大的blob检測会非常慢,还有就是该算法适合于检測暗背景下的亮blob。 Difference of Gaussian (DoG): 这是LoG算法的一种高速近似,对图像进行高斯滤波之后,不做Laplacian运算,直接做减法。相减后的图做叠加。找到局部最大值,这个算法的缺陷与LoG相似。 Determinant of Hessian (DoH): 这是最快的一种算法,不须要做多尺度的高斯滤波,运算速度自然提升非常多,这个算法对暗背景上的亮blob或者亮背景上的暗blob都能检測。 ''' # 生成斑点图片 image = data.hubble_deep_field()[0:500, 0:500] # 转成灰度图 image_gray = rgb2gray(image) # 显示图片 plt.imshow(image) # LoG算法获得斑点信息 blobs_log = blob_log(image_gray, max_sigma=30, num_sigma=10, threshold=.1) print(blobs_log) # 得到斑点坐标和高斯核的标准差 ''' [[499. 435. 1. ] [499. 386. 4.22222222] [499. 342. 1. ] ... [ 3. 196. 1. ] [ 3. 152. 1. ] [ 0. 305. 1. ]] ''' # 计算第三列半径 blobs_log[:, 2] = blobs_log[:, 2] * sqrt(2) print(blobs_log) ''' [[499. 435. 1.41421356] [499. 386. 5.97112393] [499. 342. 1.41421356] ... [ 3. 196. 1.41421356] [ 3. 152. 1.41421356] [ 0. 305. 1.41421356]] ''' # DoG算法获得斑点信息 blobs_dog = blob_dog(image_gray, max_sigma=30, threshold=.1) # print(blobs_dog) # 计算第三列半径 blobs_dog[:, 2] = blobs_dog[:, 2] * sqrt(2) # print(blobs_dog) # DoH算法获取斑点信息 blobs_doh = blob_doh(image_gray, max_sigma=30, threshold=.01) # print(blobs_doh) # 将斑点信息存入列表 blobs_list = [blobs_log, blobs_dog, blobs_doh] # 分别对应黄色绿色红色 colors = ['yellow', 'lime', 'red'] # 分别对应三个标题 titles = ['LoG', 'DoG', 'DoH'] # 将结果信息组合 sequence = zip(blobs_list, colors, titles) # 绘图 fig, axes = plt.subplots(1, 3, sharex=True, sharey=True, subplot_kw={'adjustable': 'box-forced'}) axes = axes.ravel() for blobs, color, title in sequence: ax = axes[0] axes = axes[1:] ax.set_title(title) ax.imshow(image, interpolation='nearest') for blob in blobs: y, x, r = blob c = plt.Circle((x, y), r, color=color, linewidth=2, fill=False) ax.add_patch(c) plt.show()
STATIC_VERSION = "cad1f4d9"
import errno import numpy as np import pandas as pd import json import os import time from itertools import product from openpyxl import load_workbook def create_sections(number_of_sections: int, bound: tuple): """ Generate lat lon coordinates for the boundaries of sections :param number_of_sections: integer :param bound: tuple of lat_min, lat_max, lon_min, lon_max :return: tuple(dataframe with lat lon as columns containing the boundaries of the sections, list of coordinates defining all zones generated) """ lat_min, lat_max, lon_min, lon_max = bound lon_length = lon_max - lon_min lat_length = lat_max - lat_min section_limits = pd.DataFrame() epsilon = 0.000001 # Just a small number section_limits["lon"] = np.arange( lon_min, lon_max + epsilon, lon_length / number_of_sections ) section_limits["lat"] = np.arange( lat_min, lat_max + epsilon, lat_length / number_of_sections ) section_coordinates = [] for j in range(1, number_of_sections + 1): for i in range(1, number_of_sections + 1): section_coordinates.append( ( section_limits["lat"][j - 1], section_limits["lat"][j], section_limits["lon"][i - 1], section_limits["lon"][i], ) ) return section_limits, section_coordinates def load_test_parameters_from_json(run_test=False): """ Loads parameters for computational_study from json file and makes all combinations of these. :return list - all combinations of parameters from json file """ if run_test: with open("project_test.json") as json_file: data = json.load(json_file) else: with open("instance/test_instances.json") as json_file: data = json.load(json_file) ranges = [] param = data["ranges"] param.update(data["model"]["alternative_tuners"]) for key in param: if type(param[key]) is list: parameter_min, parameter_max, parameter_increment = param[key] if ( type(parameter_min) is float or type(parameter_max) is float or type(parameter_increment) is float ): ranges.append( np.arange( parameter_min, (parameter_max + 0.0001), parameter_increment, ) ) else: ranges.append( range(parameter_min, parameter_max + 1, parameter_increment) ) elif type(param[key]) is float: parameter = param[key] ranges.append([parameter]) else: parameter = param[key] ranges.append(range(parameter, parameter + 1)) constraints = data["constraints"] constraint_list = [] for constraint_name in constraints: constraint = constraints[constraint_name] constraint_list.append(constraint) models = data["model"]["model_type"] if type(models) is not list: input_list = list(product(*ranges, (models,), *constraint_list)) else: input_list = list(product(*ranges, models, *constraint_list)) instance_list = [] for ( zones_per_axis, nodes_per_zone, number_of_vehicles, T_max, time_limit, theta, beta, model_type, valid_inequality, symmetry, ) in input_list: seed = data["model"]["seed"] subsets = data["model"]["subsets"] instance_list.append( { "number_of_sections": zones_per_axis, "number_of_scooters_per_section": nodes_per_zone, "number_of_vehicles": number_of_vehicles, "T_max": T_max, "time_limit": time_limit, "theta": theta, "beta": beta, "model_type": model_type, "valid_inequalities": valid_inequality if type(valid_inequality) is list else [valid_inequality], "symmetry": symmetry if type(symmetry) is list else [symmetry], "T_max_is_percentage": data["model"]["T_max_is_percentage"], "seed": np.random.randint(0, 1000) if seed == "random" else seed, "subsets": subsets if len(subsets) > 0 else None, } ) return instance_list def save_models_to_excel(timestamp=time.strftime("%d-%m %H.%M")): """ Iterates through all saved_models and store the information in an excel sheet. Saved information: zones, nodes per zone, # vehicles, T_max, solution time, GAP """ try: os.makedirs("computational_study") except OSError as e: if e.errno != errno.EEXIST: raise if not os.path.isfile("computational_study/comp_study_summary.xlsx"): pd.DataFrame().to_excel("computational_study/comp_study_summary.xlsx") book = load_workbook("computational_study/comp_study_summary.xlsx") writer = pd.ExcelWriter( "computational_study/comp_study_summary.xlsx", engine="openpyxl" ) writer.book = book writer.sheets = dict((ws.title, ws) for ws in book.worksheets) sheets = [ws.title for ws in book.worksheets] ( zones, nodes_per_zone, number_of_vehicles, T_max, percent_t_max, solution_time, gap, visit_list, objective_value, model_type, theta, beta, deviation_before, deviation_after, deviation_after_squared, valid_inequalities_cons, symmetry_cons, seed, ) = ([], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []) for root, dirs, files in os.walk("saved_models/", topdown=True): if len(dirs) == 0: if root.split("/")[-1] not in sheets: for file in files: with open(f"{root}/{file}") as file_path: model = json.load(file_path) model_param = file.split("_") zones.append(int(model_param[1])) nodes_per_zone.append(int(model_param[2])) number_of_vehicles.append(int(model_param[3])) T_max.append(int(model_param[4])) visit_list.append(model["Visit Percentage"]) deviation_before.append(model["Deviation Before"]) deviation_after.append(model["Deviation After"]) deviation_after_squared.append(model["Deviation After Squared"]) solution_time.append(float(model["SolutionInfo"]["Runtime"])) gap.append(float(model["SolutionInfo"]["MIPGap"])) objective_value.append(float(model["SolutionInfo"]["ObjVal"])) model_type.append(model["Instance"]["model_class"]) theta.append(model["Instance"]["theta"]) beta.append(model["Instance"]["beta"]) valid_inequalities_cons.append( str(model["Valid Inequalities"]).strip("[],") ) symmetry_cons.append(str(model["Symmetry constraint"]).strip("[],")) seed.append(model["Seed"]) is_percent_T_max, percent = model["Instance"]["is_percent_T_max"] if is_percent_T_max: percent_t_max.append(percent) else: percent_t_max.append(0) df = pd.DataFrame( list( zip( zones, nodes_per_zone, number_of_vehicles, T_max, percent_t_max, solution_time, gap, visit_list, deviation_before, deviation_after, deviation_after_squared, objective_value, model_type, theta, beta, valid_inequalities_cons, symmetry_cons, seed, ) ), columns=[ "Zones", "Nodes per zone", "Number of vehicles", "T_max", "Percent T_max", "Solution time", "Gap", "Visit percent", "Deviation before", "Deviation after", "Deviation after squared", "Obj value", "Model type", "Theta", "Beta", "Valid Inequalities", "Symmetry constraint", "Seed", ], ) df.to_excel( writer, float_format="%.5f", sheet_name=str(timestamp), ) writer.save() def get_center_of_bound(bound): lat_min, lat_max, lon_min, lon_max = bound return lat_min + (lat_max - lat_min) / 2, lon_min + (lon_max - lon_min) / 2
# -*- coding: utf-8 -*- """ Created on Thu Jun 6 11:17:51 2019 @author: Administrator """ import numpy as np from scipy import signal import matplotlib.pyplot as plt sig_freq = 470 noise_freq = 360 target_freq = 470 sample_freq= 4000 N = 4000 k = (N*target_freq)/sample_freq def windows(name='Hanning', N=20): # Rect/Hanning/Hamming if name == 'Hamming': window = np.array([0.54 - 0.46 * np.cos(2 * np.pi * n / (N - 1)) for n in range(N)]) elif name == 'Hanning': window = np.array([0.5 - 0.5 * np.cos(2 * np.pi * n / (N - 1)) for n in range(N)]) elif name == 'Rect': window = np.ones(N) return window def goertzel(din,k,N): win = windows('Hanning',N) w = 2*np.pi*k/N coef = 2*np.cos(w) print("w:%f,coef:%f\n"%(w,coef)) q1=0 q2=0 for i in range(N): x = din[i]*win[i] q0 = coef*q1 - q2 + x q2 = q1 q1 = q0 return np.sqrt(q1**2 + q2**2 - q1*q2*coef)*2/N m = np.cos(2*np.pi*sig_freq*np.arange(N*2)/sample_freq) cn = np.cos(2*np.pi*noise_freq*np.arange(N*2)/sample_freq) wn = np.random.randn(2*N) cs = m*1+cn+wn*0 x = np.arange(m.shape[0])/sample_freq #fig = plt.figure() #ax = fig.add_subplot(211) #ax.plot(x[:N],m[:N]) print("k:%d,N:%d"%(k,N)) print(goertzel(cs[:N],k,N))
# -*- coding: utf-8 -*- from ctypes import * class ADSB_Data_Struct(Structure): _pack_ = 1 _fields_ = [("ICAO", c_char*16), ("Flight_ID", c_char*16), ("Flight_24bit_addr",c_int32), ("Aircraft_Category", c_uint8), ("Altitude", c_int16), ("Radio_Altitude", c_int16), ("North_South_Velocity", c_float), ("East_West_Velocity", c_float), ("Vertical_Speed", c_float), ("Latitude", c_float), ("Longitude", c_float), ("Heading_Track_Angle", c_float), ("Air_Ground_Sta", c_uint8), ("Ground_Speed", c_uint16), ("Seconds", c_uint8), ("Mintes", c_uint8), ("Hours", c_uint8), ("sec",c_float), ("p_Seconds", c_uint8), ("p_Mintes", c_uint8), ("p_Hours", c_uint8), ("p_sec",c_float), ("v_Seconds", c_uint8), ("v_Mintes", c_uint8), ("v_Hours", c_uint8), ("v_sec",c_float), ("s_Seconds", c_uint8), ("s_Mintes", c_uint8), ("s_Hours", c_uint8), ("s_sec",c_float), ("NACV", c_uint8), ("NACp", c_uint8), ("NIC", c_uint8), ("SIL", c_uint8), ("SDA", c_uint8), ("emergency_priority_sta", c_uint8), ("data_link_version", c_uint8)] class TCAS_Data_Struct(Structure): _pack_ = 1 _fields_ = [("Track_ID", c_char*8), ("Flight_24bit_address", c_uint32), ("Altitude", c_int16), ("Vertical_Speed", c_int16), ("Bearing", c_float), ("Range", c_float), ("Warning_Status", c_uint8), ("Seconds", c_uint8), ("Mintes", c_uint8), ("Hours", c_uint8), ("sec", c_float)] class Ownship_Data_Struct(Structure): _pack_ = 1 _fields_ = [("ICAO", c_char*16), ("Flight_ID", c_char*16), ("Flight_24bit_addr", c_int32), ("Altitude", c_int16), ("Radio_Altitude", c_int16), ("North_South_Velocity", c_float), ("East_West_Velocity", c_float), ("Vertical_Speed", c_float), ("Latitude", c_float), ("Longitude", c_float), ("Heading_Track_Angle", c_float), ("Air_Ground_Sta",c_uint8), ("Ground_Speed", c_uint16), ("Flight_Length", c_uint16), ("Flight_Width", c_uint16), ("Seconds", c_uint8), ("Mintes", c_uint8), ("Hours", c_uint8), ("sec", c_float), ("NACV", c_uint8), ("NACp", c_uint8), ("NIC", c_uint8), ("SIL", c_uint8) ] print(sizeof(Ownship_Data_Struct)) print(sizeof(ADSB_Data_Struct)) print(sizeof(TCAS_Data_Struct))
"""Support for bunq account balance."""
from helper import helper import random as rm ''' Strict Donkey Hillclimber algorithm ''' def simulatedAnnealing(mel, mir, failValue, scoreFunction): ''' A probabilistic algorithm for approximating the global optimum of a given function, the global optimum being the final mutation (swap) that changes the genome sequence of the Drosophila Melanogaster into the Drosophila Miranda. The algorithm starts with the genome-sequence of the Drosophila Melanogaster and then generates a random mutation on the genome-sequence. If the score of the genome sequence is higher than the score of the current mutation (Or when starting: the Melanogaster sequence), the generated mutation is the new current mutation. This repeats until the Melanogaster is transformed into the Miranda. Arguments: ---------------------------------------------------------- mel: The genome sequence of the Drosophila Melanogaster, with which the algorithm starts it's mutation sequence. ---------------------------------------------------------- mir: The genome sequence of the Drosophila Miranda, which is the intended target of the mutations on the Melanogaster. The algorithm stops once it has mutated the Melanogaster into the genome sequence of the Miranda. ---------------------------------------------------------- failValue: The value of the interval of failed mutations (Mutations with a lesser or equal score than the latest mutation) by which the algorithm allows lesser mutations to pass into the mutation sequence, in order to avoid getting stuck on a plateau. ---------------------------------------------------------- scoreFunction: The function which the algorithm uses to score each individual mutation. ---------------------------------------------------------- Returns: ---------------------------------------------------------- scoreHistory: A list of the all the (accepted) generated mutations, including the score of each individual mutation. Each mutation & score is saved in the list as a tuple. ---------------------------------------------------------- ''' curScore = 0 swaps = 0 failCount = 0 curMel = mel swapHistory = [mel] scoreHistory = [0] print("---------------------------------------") print("SIMULATED ANNEALING: LIVE VISUALIZATION") print("---------------------------------------") # Repeat the algorithm until mel has been transformed into mir while curMel != mir: mutatedMel = helper.mutateSingle(curMel) mutatedScore = scoreFunction(mutatedMel) # If the newly generated score is higher than the current, # the mutated mel is the new current mel if mutatedScore > curScore: print("Found better mutation!") curMel = mutatedMel curScore = mutatedScore print(curMel) swapHistory.append(curMel) scoreHistory.append(curScore) swaps += 1 # To avoid getting stuck on a plateau, the algorithm allows a mutation # with an equal or a mutation with score 1 lower than the latest # mutation to pass approximately once every 1000 failed swaps if mutatedScore == curScore or mutatedScore == (curScore - 1): failCount += 1 marge = int(failValue * 0.001) if failCount % failValue in range(0, marge): print((4 * " ")+"Trying different route.") curMel = mutatedMel curScore = mutatedScore print(curMel) swapHistory.append(curMel) scoreHistory.append(curScore) swaps += 1 # If the generated mutation is less than the current score, # add 1 to failCount if mutatedScore < curScore: failCount += 1 print("--------------------------------") print("SIMULATED ANNEALING: SWAPHISTORY") print("--------------------------------") # Create a list with the history of every accepted mutation and it's score history = helper.makeTuple([], scoreHistory, swapHistory) # Print full mutation history and the corresponding score for each mutation for i in range(len(scoreHistory)): print("Mutation: ", swapHistory[i], "Score: ", scoreHistory[i], "Swaps: ", i) return history, len(scoreHistory) # print("Mutation: ", swapHistory[i], "Score: ", scoreHistory[i], "Swaps: ", i) # return history
import random print(random.randint(5, 20)) # line 1 print(random.randrange(3, 10, 2)) # line 2 print(random.uniform(2.5, 5.5)) # line 3 # line one 5 was the smallest i got and 20 was the largest # line two 3 was the smallest and 9 was the largest # line three was 3.6711 and largest was 4.952 print() print(random.randint(0, 100)) # i got 70
valor = int(input('Digite o valor a ser sacado: ')) cinquenta = vinte = dez = um = 0 ced = 50 '''código do professor: total = 0 while True: if valor >= ced: valor -= ced total += 1 else: if total > 0: print(f'Total de {total} cédulas de {ced}') if ced == 50: ced == 20 elif ced == 20: ced = 10 elif ced == 10: ced = 1 total = 0 if total == 0: break''' while valor >= 50: cinquenta += 1 valor -= 50 while valor >= 20: vinte += 1 valor -= 20 while valor >= 10: dez += 1 valor -= 10 while valor >= 1: um += 1 valor -= 1 print(f'''Quantidade de notas de cinquenta: {cinquenta} Quantidade de notas de vinte: {vinte} Quantidade de notas de dez: {dez} Quantidade de notas de um: {um} ''')
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('administration', '0004_auto_20191019_0158'), ] operations = [ migrations.AlterField( model_name='clients', name='id_country', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='administration.country'), ), ]
import pandas as pd friend_list = [ ["John", 25, "student"], ["Nate", 30, "teacher"], ["Jenny", 30, None] ] column_name = ["name", "age", "job"] df = pd.DataFrame(friend_list,columns=column_name) #조건에 맞는 행 보여주기 print(df[1:3]) #슬라이싱 가능 print() print(df.loc[[0,2]]) #0행과 2행 보여줌 print() print(df.iloc[[0,2]]) #0, 2번 인덱스 보여줌 print() print(df[(df.age>25)&(df.name=="Jenny")]) #조건에 맞는 행만 출력 print() print(df.query("age>25 & name==\"Nate\"")) #조건에 맞는 행만 출력 print() #조건에 맞는 열 보여주기 print(df.iloc[:,0:2]) #0~1번열의 모든 행 표시 print() print(df[["name","job"]]) #이름과 직업만 표시 print() print(df.filter(items=["name","job"])) #이름과 직업만 표시 print() print(df.filter(like="a", axis=1)) #이름에 a가 들어간 컬럼표시 print() print(df.filter(regex="b$", axis=1)) #이름이 b로 끝나는 컬럼표시 print()
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import datetime class Migration(migrations.Migration): dependencies = [ ('FBData', '0004_auto_20150614_1552'), ] operations = [ migrations.AlterField( model_name='fbdata', name='created', field=models.DateTimeField(auto_now_add=True, default=datetime.datetime(2015, 6, 14, 16, 1, 0, 409317)), preserve_default=True, ), ]
#!/proj/sot/ska3/flight/bin/python ##################################################################################### # # # update_sim_flex.py: update sim_flex difference data sets # # # # author: t. isobe (tisobe@cfa.harvard.edu) # # # # last update: Feb 02, 2021 # # # ##################################################################################### import os import sys import re import string import time import numpy import astropy.io.fits as pyfits import Ska.engarchive.fetch as fetch import Chandra.Time import datetime import random import getpass # #--- reading directory list # path = '/data/mta/Script/MTA_limit_trends/Scripts/house_keeping/dir_list' with open(path, 'r') as f: data = [line.strip() for line in f.readlines()] for ent in data: atemp = re.split(':', ent) var = atemp[1].strip() line = atemp[0].strip() exec("%s = %s" %(var, line)) # #--- append path to a private folder # sys.path.append(bin_dir) sys.path.append(mta_dir) # #--- import several functions # import mta_common_functions as mcf #---- contains other functions commonly used in MTA scripts import glimmon_sql_read as gsr import envelope_common_function as ecf # #--- set a temporary file name # rtail = int(time.time() * random.random()) zspace = '/tmp/zspace' + str(rtail) #------------------------------------------------------------------------------------------- #-- update_sim_offset: update sim offset data --- #------------------------------------------------------------------------------------------- def update_sim_offset(): """ update sim offset data input: none output: <out_dir>/Comp_save/Compsimoffset/<msid>_full_data_<year>.fits """ t_file = 'flexadif_full_data_*.fits*' out_dir = deposit_dir + 'Comp_save/Compsimoffset/' [tstart, tstop, year] = ecf.find_data_collecting_period(out_dir, t_file) # #--- update the data # get_data(tstart, tstop, year, out_dir) # #--- zip the fits file from the last year at the beginning of the year # ecf.check_zip_possible(out_dir) #------------------------------------------------------------------------------------------- #-- get_data: update sim flex offset data for the given data period -- #------------------------------------------------------------------------------------------- def get_data(start, stop, year, out_dir): """ update sim flex offset data for the given data period input: start --- start time in seconds from 1998.1.1 stop --- stop time in seconds from 1998.1.1 year --- data extracted year out_dir --- output_directory output: <out_dir>/Comp_save/Compsimoffset/<msid>_full_data_<year>.fits """ print(f"Period: {start} <--> {stop} in Year: {year}") for msid in ['flexadif', 'flexbdif', 'flexcdif']: if msid == 'flexadif': msid_t = '3faflaat' msid_s = '3sflxast' elif msid == 'flexbdif': msid_t = '3faflbat' msid_s = '3sflxbst' else: msid_t = '3faflcat' msid_s = '3sflxcst' out = fetch.MSID(msid_t, start, stop) tdat1 = out.vals ttime = out.times out = fetch.MSID(msid_s, start, stop) tdat2 = out.vals tlen1 = len(tdat1) tlen2 = len(tdat2) if tlen1 == 0 or tlen2 == 0: continue if tlen1 > tlen2: diff = tlen1 - tlen2 for k in range(0, diff): tdat2 = numpy.append(tdat2, tadt2[-1]) elif tlen1 < tlen2: diff = tlen2 - tlen1 for k in range(0, diff): tdat1 = numpy.append(tdat1, tadt1[-1]) ocols = ['time', msid] cdata = [ttime, tdat1 - tdat2] ofits = out_dir + msid + '_full_data_' + str(year) +'.fits' if os.path.isfile(ofits): ecf.update_fits_file(ofits, ocols, cdata) else: ecf.create_fits_file(ofits, ocols, cdata) #------------------------------------------------------------------------------------------- if __name__ == "__main__": # #--- Create a lock file and exit strategy in case of race conditions # name = os.path.basename(__file__).split(".")[0] user = getpass.getuser() if os.path.isfile(f"/tmp/{user}/{name}.lock"): sys.exit(f"Lock file exists as /tmp/{user}/{name}.lock. Process already running/errored out. Check calling scripts/cronjob/cronlog.") else: os.system(f"mkdir -p /tmp/{user}; touch /tmp/{user}/{name}.lock") update_sim_offset() # #--- Remove lock file once process is completed # os.system(f"rm /tmp/{user}/{name}.lock")
#!/usr/bin/env python # Copyright 2009-2014 Eucalyptus Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from config_manager.baseconfig import BaseConfig, EucalyptusProperty import copy class Eucalyptus(BaseConfig): def __init__(self): super(Eucalyptus, self).__init__(name=None, description=None, write_file_path=None, read_file_path=None, version=None) self.log_level = self.create_property(json_name='log-level') self.set_bind_addr = self.create_property('set_bind_addr', value=True) self.eucalyptus_repo = self.create_property('eucalyptus-repo') self.euca2ools_repo = self.create_property('euca2ools-repo') self.enterprise_repo = self.create_property('enterprise-repo') self.enterprise = self.create_property('enterprise') self.nc = self.create_property('nc') self.topology = self.create_property('topology') self.network = self.create_property('network') self.system_properties = self.create_property('system_properties') self.install_load_balancer = self.create_property( 'install-load-balancer', value=True) self.install_imaging_worker = self.create_property('install-imaging-worker', value=True) self.use_dns_delegation = self._set_eucalyptus_property( name='bootstrap.webservices.use_dns_delegation', value=True) def _process_json_output(self, json_dict, show_all=False, **kwargs): tempdict = copy.copy(json_dict) eucaprops = {} aggdict = self._aggregate_eucalyptus_properties() for key in aggdict: value = aggdict[key] # handle value of 'False' as valid if value or value is False: eucaprops[key] = aggdict[key] elif not value and show_all: eucaprops["!" + str(key)] = aggdict[key] if eucaprops: if 'eucalyptus_properties' not in tempdict: tempdict['eucalyptus_properties'] = eucaprops else: tempdict['eucalyptus_properties'].update(eucaprops) return super(Eucalyptus, self)._process_json_output(json_dict=tempdict, show_all=show_all, **kwargs) def add_topology(self, topology): self.topology.value = topology def set_log_level(self, log_level): self.log_level.value = log_level
import os import json def extract_route(req): return req.split()[1][1:] def read_file(path): nome1,nome2 = os.path.splitext(path) lista_arq = [".txt", ".html", ".css",".js"] if nome2 in lista_arq: f = open(path, "rt") return f.read().encode(encoding="utf-8") else: f = open(path,"rb") return f.read() def load_data(path): with open("data/" + path) as arq_json: return json.load(arq_json) def load_template(path): path = "templates/" + path return read_file(path).decode(encoding="utf-8") def build_response(body='', code=200, reason='OK', headers=''): resposta = f"HTTP/1.1 {code} {reason}\n\n{body}" if headers != "": resposta = f"HTTP/1.1 {code} {reason}\n{headers}\n\n{body}" return resposta.encode()
from neo4j.v1 import GraphDatabase uri = "bolt://localhost:7687" driver = GraphDatabase.driver(uri, auth=("neo4j", "Password")) def get_skills_by_attribute(attr): with driver.session() as session: with session.begin_transaction() as tx: Skills = tx.run("Match (:Attribute{Name:$name})-[:UNLOCKS]->(s:Skill)" "Return distinct s", name = attr) #print(Skills[0]) i = 0 for skill in Skills: print(skill[0].properties) def get_skills_by_attribute_amount(attr, amount): with driver.session() as session: with session.begin_transaction() as tx: Skill = tx.run("Match (:Attribute{Name:$name})-[:UNLOCKS]->(s:Skill {Skill_Req:$amount})" "Return distinct s", name = attr, amount = str(amount)) for obj in Skill: print(obj[0].properties) get_skills_by_attribute("Heat Res") get_skills_by_attribute_amount("Heat Res", 10)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ ПОРЯДОК ИСПОЛЬЗОВАНИЯ: apache_log_parser_split.py some_log_file Анализирует содержимое лог-файла и генерирует отчет, содержащий перечень удаленных хостов, кол-во переданных байт и код состояния """ import sys def dictify_logline(line): """ Parse logline and get: hosts, bytes, status code :param line: :return: hosts, bytes, status code """ splite_line = line.split() return {'remote_host': splite_line[0], 'status_code': splite_line[8], 'bytes_sent': splite_line[9]} def generate_log_report(logfile): """ Read lines and gets bytes sent for each remote hosts :param logfile: :return: dict {'remote_host':[bytes_sent, ...]} """ report_dict = {} for line in logfile: line_dict = dictify_logline(line) print(line_dict) try: bytes_sent = int(line_dict['bytes_sent']) except ValueError: continue report_dict.setdefault(line_dict['remote_host'], []).append(bytes_sent) return report_dict if __name__ == '__main__': if not len(sys.argv) > 1: print(__doc__) sys.exit(1) infile_name = sys.argv[1] try: infile = open(infile_name, 'r') except IOError: print("You must specity a valid file to parse") print(__doc__) sys.exit(1) log_report = generate_log_report(infile) print(log_report) infile.close()
import subprocess import torch subprocess.call( "pip install git+https://github.com/facebookresearch/fvcore.git", shell=True ) net = torch.hub.load("zhanghang1989/ResNeSt", "resnest50", pretrained=True)
import boto3 region = 'us-east-1' # db_instance = 'db-instance-identifier' rds = boto3.client('rds', region_name=region) dbs = rds.describe_db_instances() for output in dbs['DBInstances']: print('Master Username: ' + output['MasterUsername'] + '\nBackup Window: ' + output['PreferredBackupWindow']) # print ([rds['MasterUsername'] for rds in dbs['DBInstances']])
#!/usr/bin/env python # -*- coding: utf-8 -*- from player import * from smart_contract import * from blockchain import * accounts = [] new_game_flag=1 while new_game_flag: print() blockchain = BlockChain() players = [] """ 三人游戏,创建游戏账户 """ while len(players) < 3: str_1 = input('You want to create a new account? (Y/N):') if str_1 == 'Y': name_1 = input('Please input your account name:') flag = 1 for account in accounts: if account.name == name_1: print('this name has already existed') print() flag = 0 break if flag: accounts.append(Account(name_1)) players.append(Account(name_1)) print() elif str_1 == 'N': name_1 = input('You already have an account? Please input its name: ') flag = 1 for account in accounts: if account.name == name_1: flag = 0 print("Yes. This name has already existed") players.append(account) print() if flag == 1: print("Sorry. This name doesn't exist") print() else: print('Please input Y or N') """ 指定broker bet_max:最大押注金额 bet_min:最少押注金额 同时为参加游戏必须缴纳的金额 """ game_state = Game_state() while True: flag = 0 for i in range(0, 3): str_n = players[i].name str_1 = input(str_n+', do you want to be broker? Y/N:') if str_1 == 'Y': str_2 = input('Please input the max bet:') str_3 = input('Please input the min bet:') try: bet_max = int(str_2) bet_min = int(str_3) if bet_max<bet_min: print('The max bet should be bigger than the min bet') h=6/0 if players[i].balance < (bet_max * 4 + bet_min * 2): print("You don't have enough money") h=6/0 flag = 1 break except: print('Please input the suitable number') print('And you lose the chance to become broker') if flag: break """ 初始化游戏,加入玩家 """ init_game(players[i], bet_max, bet_min, game_state) str_1 = [] for i in range(0, 3): if not players[i].name == game_state.broker.name: str_1.append(players[i].name) join_game(players[i], game_state) #上传玩家加入游戏后的信息和缴纳的金额 blockchain.new_transaction(game_state.sender[0], game_state.send_content[0], game_state.send_flag[0]) blockchain.new_transaction(game_state.sender[1], game_state.send_content[1], game_state.send_flag[1]) proof = blockchain.proof_of_work() prev_hash = blockchain.hash(blockchain.chain[-1]) blockchain.minetoblock_c(proof, prev_hash) print() print('========================Game starts========================') print() #上传第一个签名 print("Now you all should input the first signature. And you shouldn't tell others") print("The program will calculate the hash of the signature") print("And then put the hash at the billboard") print() print(game_state.broker.name+", please input your first signature") str_1 = input("Your signature_1:") print(game_state.players[0].name+", please input your first signature") str_2 = input("Your signature_1:") print(game_state.players[1].name+", please input your first signature") str_3 = input("You signature_1:") upload_sig_hash(game_state.broker, str_1, game_state) upload_sig_hash(game_state.players[0], str_2, game_state) upload_sig_hash(game_state.players[1], str_3, game_state) blockchain.new_transaction(game_state.sender[2], game_state.send_content[2], game_state.send_flag[2]) blockchain.new_transaction(game_state.sender[3], game_state.send_content[3], game_state.send_flag[3]) blockchain.new_transaction(game_state.sender[4], game_state.send_content[4], game_state.send_flag[4]) proof = blockchain.proof_of_work() prev_hash = blockchain.hash(blockchain.chain[-1]) blockchain.minetoblock_c(proof, prev_hash) print() #上传第二个签名 print("Now you all should input the second signature.And you shouldn't tell others") print("The program will calculate the hash of the signature") print("And then put the hash at the billboard") print() print(game_state.broker.name+", please input your second signature") str_1 = input("Your signature_2:") print(game_state.players[0].name+", please input your second signature") str_2 = input("Your signature_2:") print(game_state.players[1].name+", please input your second signature") str_3 = input("You signature_2:") upload_sig_hash(game_state.broker, str_1, game_state) upload_sig_hash(game_state.players[0], str_2, game_state) upload_sig_hash(game_state.players[1], str_3, game_state) blockchain.new_transaction(game_state.sender[5], game_state.send_content[5], game_state.send_flag[5]) blockchain.new_transaction(game_state.sender[6], game_state.send_content[6], game_state.send_flag[6]) blockchain.new_transaction(game_state.sender[7], game_state.send_content[7], game_state.send_flag[7]) proof = blockchain.proof_of_work() prev_hash = blockchain.hash(blockchain.chain[-1]) blockchain.minetoblock_c(proof, prev_hash) #再次上传第一个签名,验证后发送给其他人 print() print("Now you all should input the first signature.And we will show it to other people") print("Please ensure that you input the correct signature. And you will have 2 chances") print("If all wrong, the game will be over. ") print("And your guarantee fee will be sent to the other two people") print() print(game_state.broker.name+", please input your first signature again") str_1 = input("Your signature_1:") print(game_state.players[0].name+", please input your first signature again") str_2 = input("Your signature_1:") print(game_state.players[1].name+", please input your first signature again") str_3 = input("You signature_1:") upload_sig_1(game_state.broker.name, str_1, game_state, blockchain) try: if not len(game_state.sender) == 9: h=6/0 except: print(game_state.broker.name+", Please input the right signature") str_1 = input("Your signature_1:") upload_sig_1(game_state.broker.name, str_1, game_state, blockchain) try: if not len(game_state.sender) == 9: h=6/0 except: print(game_state.broker.name+", you cheated others. Game over.") print("And you will lose", game_state.bet_min*2,"dollar") send_money(game_state.broker, game_state.players[0], game_state, game_state.bet_min) send_money(game_state.broker, game_state.players[1], game_state, game_state.bet_min) blockchain.new_transaction(game_state.sender[8], game_state.send_content[8], game_state.send_flag[8]) blockchain.new_transaction(game_state.sender[9], game_state.send_content[9], game_state.send_flag[9]) proof = blockchain.proof_of_work() prev_hash = blockchain.hash(blockchain.chain[-1]) blockchain.minetoblock_c(proof, prev_hash) print() print("broker(", game_state.broker.name, ")'s balance:", game_state.broker.balance) print("player_1(", game_state.players[0].name, ")'s balance:", game_state.players[0].balance) print("player_2(", game_state.players[1].name, ")'s balance", game_state.players[1].balance) exit() upload_sig_1(game_state.players[0].name, str_2, game_state, blockchain) try: if not len(game_state.sender) == 10: h=6/0 except: print(game_state.players[0].name+", Please input the right signature") str_2 = input("Your signature_1:") upload_sig_1(game_state.players[0].name, str_2, game_state, blockchain) try: if not len(game_state.sender) == 10: h=6/0 except: print(ame_state.players[0].name+", you cheated others. Game over.") print("And you will lose ", game_state.bet_min," dollar") send_money(game_state.players[0], game_state.broker, game_state, game_state.bet_min/2) send_money(game_state.players[0], game_state.players[1], game_state, game_state.bet_min/2) send_money(game_state.broker, game_state.players[1], game_state, game_state.bet_min) blockchain.new_transaction(game_state.sender[9], game_state.send_content[9], game_state.send_flag[9]) blockchain.new_transaction(game_state.sender[10], game_state.send_content[10], game_state.send_flag[10]) blockchain.new_transaction(game_state.sender[11], game_state.send_content[11], game_state.send_flag[11]) proof = blockchain.proof_of_work() prev_hash = blockchain.hash(blockchain.chain[-1]) blockchain.minetoblock_c(proof, prev_hash) print() print("broker(", game_state.broker.name, ")'s balance:", game_state.broker.balance) print("player_1(", game_state.players[0].name, ")'s balance:", game_state.players[0].balance) print("player_2(", game_state.players[1].name, ")'s balance", game_state.players[1].balance) exit() upload_sig_1(game_state.players[1].name, str_3, game_state, blockchain) try: if not len(game_state.sender)==11: h=6/0 except: print(game_state.players[1].name+", Please input the right signature") str_3=input("Your signature_1:") upload_sig_1(game_state.players[1].name, str_3, game_state, blockchain) try: if not len(game_state.sender) == 11: h=6/0 except: print(game_state.players[1].name+", you cheated others. Game over.") print("And you will lose ", game_state.bet_min," dollar") send_money(game_state.players[1], game_state.players[0], game_state, game_state.bet_min/2) send_money(game_state.players[1], game_state.broker, game_state, game_state.bet_min/2) send_money(game_state.broker, game_state.players[0], game_state, game_state.bet_min) blockchain.new_transaction(game_state.sender[10], game_state.send_content[10], game_state.send_flag[10]) blockchain.new_transaction(game_state.sender[11], game_state.send_content[11], game_state.send_flag[11]) blockchain.new_transaction(game_state.sender[12], game_state.send_content[12], game_state.send_flag[12]) proof = blockchain.proof_of_work() prev_hash = blockchain.hash(blockchain.chain[-1]) blockchain.minetoblock_c(proof, prev_hash) print() print("broker(", game_state.broker.name, ")'s balance:", game_state.broker.balance) print("player_1(", game_state.players[0].name, ")'s balance:", game_state.players[0].balance) print("player_2(", game_state.players[1].name, ")'s balance", game_state.players[1].balance) exit() blockchain.new_transaction(game_state.sender[8], game_state.send_content[8], game_state.send_flag[8]) blockchain.new_transaction(game_state.sender[9], game_state.send_content[9], game_state.send_flag[9]) blockchain.new_transaction(game_state.sender[10], game_state.send_content[10], game_state.send_flag[10]) proof = blockchain.proof_of_work() prev_hash = blockchain.hash(blockchain.chain[-1]) blockchain.minetoblock_c(proof, prev_hash) #calculate the secret print() calculate_s(game_state.broker, blockchain, game_state) calculate_s(game_state.players[0], blockchain, game_state) calculate_s(game_state.players[1], blockchain, game_state) print("Now everyone has calculated their secret. And they will keep it secret") print("None of them know the others' secrets") print() print("broker(", game_state.broker.name, ")'s secret:", game_state.broker.s) print("player_1(", game_state.players[0].name, ")'s secret:", game_state.players[0].s) print("player_2(", game_state.players[1].name, ")'s secret:", game_state.players[1].s) #players input their bet print() print("Now Players should input their bet") print() str_1 = input(game_state.players[0].name+", do you want to give up betting? Y/N:") if str_1 == 'Y': bet_flag_0 = 0 amount = 0 else: bet_flag_0 = 1 while True: str_2 = input("Please input your bet:") amount = int(str_2) if amount <= game_state.bet_max and amount >= game_state.bet_min: break print("The max bet is ", game_state.bet_max, ", and the min bet is ", game_state.bet_min) print("Ensure that your bet is between the max bet and min bet") player_bet(game_state.players[0], bet_flag_0, game_state, amount) str_1 = input(game_state.players[1].name+", do you want to give up betting? Y/N:") if str_1 == 'Y': bet_flag_1 = 0 amount = 0 else: bet_flag_1 = 1 while True: str_2 = input("Please input your bet:") amount = int(str_2) if amount <= game_state.bet_max and amount >= game_state.bet_min: break print("The max bet is ", game_state.bet_max, ", and the min bet is ", game_state.bet_min) print("Ensure that your bet is between the max bet and min bet") player_bet(game_state.players[1], bet_flag_1, game_state, amount) blockchain.new_transaction(game_state.sender[11], game_state.send_content[11], game_state.send_flag[11]) blockchain.new_transaction(game_state.sender[12], game_state.send_content[12], game_state.send_flag[12]) proof = blockchain.proof_of_work() prev_hash = blockchain.hash(blockchain.chain[-1]) blockchain.minetoblock_c(proof, prev_hash) # Broker input his bet print() beg_flag = [] if game_state.bet_one: print(game_state.players[0].name+"'s bet is ", game_state.bet_one) str_1 = input("Broker, do you want to give up betting with him? Y/N:") if str_1 == 'Y': print(game_state.players[0].name+", broker gives up betting for you") beg_flag.append(0) else: beg_flag.append(1) else: beg_flag.append(1) print("Broker, "+game_state.players[0].name+" gives up betting for you") print() if game_state.bet_two: print(game_state.players[1].name+"'s bet is ", game_state.bet_two) str_1 = input("Broker, do you want to give up betting with him? Y/N:") if str_1 == 'Y': print(game_state.players[1].name+", broker gives up betting for you") print() beg_flag.append(0) else: beg_flag.append(1) else: beg_flag.append(1) print("Broker, "+game_state.players[1].name+" gives up betting for you") print() broker_bet(beg_flag, game_state) #compare s and upload signature_2 compare_s(game_state.broker.s, game_state.players[0].s, game_state.players[1].s, game_state) print() print("Now you all should input the second signature.And we will show it to other people") print("Please ensure that you input the correct signature. And you will have 2 chances") print("If all wrong, the game will be over. ") print("And your guarantee fee will be sent to other people") print() print(game_state.broker.name+", please input your second signature again") str_1 = input("Your signature_2:") print(game_state.players[0].name+", please input your second signature again") str_2 = input("Your signature_2:") print(game_state.players[1].name+", please input your second signature again") str_3 = input("You signature_2:") upload_sig_2(game_state.broker.name, str_1, game_state, blockchain) try: if not len(game_state.sender)==14: h=6/0 except: print(game_state.broker.name+", please input the right signature") str_1=input("Your signature_2:") upload_sig_2(game_state.broker.name, str_1, game_state, blockchain) try: if not len(game_state.sender)==14: h=6/0 except: print(game_state.broker.name+", you cheated others. We have defaulted you lose the game.") send_data(game_state.broker.name, game_state, 00000) if game_state.bet_one: game_state.win['one']='00' else: game_state.win['one']='01' if game_state.bet_two: game_state.win['two']='00' else: game_state.win['two']='01' upload_sig_2(game_state.players[0].name, str_2, game_state, blockchain) try: if not len(game_state.sender)==15: h=6/0 except: print(game_state.players[0].name+", please input the right signature") str_2=input("Your signature_2:") upload_sig_2(game_state.players[0].name, str_2, game_state, blockchain) try: if not len(game_state.sender)==15: h=6/0 except: print(game_state.players[0].name+", you cheated others. We have defaulted you lose the game.") send_data(game_state.players[0].name, game_state, 00000) if game_state.bet_one: game_state.win['one']='10' else: game_state.win['one']='11' upload_sig_2(game_state.players[1].name, str_3, game_state, blockchain) try: if not len(game_state.sender)==16: h=6/0 except: print(game_state.players[1].name+", please input the right signature") str_3=input("Your signature_2:") upload_sig_2(game_state.players[1].name, str_3, game_state, blockchain) try: if not len(game_state.sender)==16: h=6/0 except: print(game_state.players[1].name+", you cheated others. We have defaulted you lose the game.") send_data(game_state.players[1].name, game_state, 00000) if game_state.bet_two: game_state.win['two']='10' else: game_state.win['two']='11' blockchain.new_transaction(game_state.sender[13], game_state.send_content[13], game_state.send_flag[13]) blockchain.new_transaction(game_state.sender[14], game_state.send_content[14], game_state.send_flag[14]) blockchain.new_transaction(game_state.sender[15], game_state.send_content[15], game_state.send_flag[15]) proof = blockchain.proof_of_work() prev_hash = blockchain.hash(blockchain.chain[-1]) blockchain.minetoblock_c(proof, prev_hash) #payoff payoff(game_state) print("broker(", game_state.broker.name, ")'s secret:", game_state.broker.s) print("player_1(", game_state.players[0].name, ")'s secret:", game_state.players[0].s) print("player_2(", game_state.players[1].name, ")'s secret:", game_state.players[1].s) print() print("broker(", game_state.broker.name, ")'s balance:", game_state.broker.balance) print("player_1(", game_state.players[0].name, ")'s balance:", game_state.players[0].balance) print("player_2(", game_state.players[1].name, ")'s balance", game_state.players[1].balance) print() str_1 = input(game_state.broker.name+", continue to play? Y/N:") str_2 = input(game_state.players[0].name+", continue to play? Y/N:") str_3 = input(game_state.players[1].name+", continue to play? Y/N:") if not str_1+str_2+str_3=='YYY': new_game_flag=0 print("Game over")
# -*- coding: utf-8 -*- import requests class neteasemusic(): def __init__(self, cookie): self.s = requests.Session() self.url = 'http://music.163.com/api/point/dailyTask?type=1&csrf_token=123' self.header = { 'Pragma':'no-cache', 'DNT':'1', 'Accept-Encoding':'gzip, deflate, sdch', 'Accept-Language':'en,zh-CN;q=0.8,zh;q=0.6', 'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.30 Safari/537.36', 'Content-Type':'application/x-www-form-urlencoded', 'Accept':'*/*', 'Cache-Control':'no-cache', 'Referer':'http://music.163.com/discover', 'Cookie':cookie, 'Connection':'keep-alive', } def sign(self): return self.s.get(self.url, headers=self.header)
t = int(input()) mod = 10**9 + 7 while (t): t -= 1 num, k = [int(x) for x in input().split()] ans = k-1 l = k-num a = l%(num-1) d = num-1 n = (l-a)//d + 1 ans += (n*(a+l))//2 if (n >= k): ans = k-1 print(ans%mod)
import json from allauth import utils from core.forms import ProfileForm, TeamForm, InviteUserForm from core.models import Event, Team, TeamMember from django.contrib import messages from django.contrib.auth import get_user_model from django.contrib.auth.decorators import login_required from django.core.exceptions import PermissionDenied from django.core.mail import send_mail from django.shortcuts import get_object_or_404, render, redirect from django.http import JsonResponse, HttpResponse, HttpResponseForbidden from django.views.decorators.http import require_http_methods from django.utils.crypto import get_random_string from haystack.query import SearchQuerySet def home(request): events = Event.objects.filter(is_published=True) return render(request, 'core/home.html', {'events': events}) def view_event(request, event_id): event = get_object_or_404(Event, pk=event_id) return render(request, 'core/view_event.html', {'event': event}) @login_required def profile(request, profile_id=None): if not profile_id: profile_id = request.user.id edit = True if request.user.id == int(profile_id) else False user = get_object_or_404(get_user_model(), pk=profile_id) team_form = TeamForm() teams = TeamMember.objects.filter(user=user) if request.method == 'POST': form = ProfileForm(request.POST, instance=user) if form.is_valid(): form.save() update_photo = request.FILES.get('photo', None) messages.success(request, 'Профиль обновлен') if update_photo: user.photo = update_photo user.save() else: form = ProfileForm(instance=user) return render(request, 'core/profile.html', {'form': form, 'team_form': team_form, 'teams': teams, 'edit': edit, 'user': user}) @login_required def create_team(request): if request.method == 'POST': form = TeamForm(request.POST, request.FILES) if form.is_valid(): team = form.save(commit=False) team.creator = request.user team.save() team_member = TeamMember(team=team, user=request.user, is_admin=True) team_member.save() messages.success(request, 'Команда создана') return redirect('profile') @login_required def show_team(request, team_id): team = get_object_or_404(Team, pk=team_id) form = TeamForm(instance=team) invite_user_form = InviteUserForm() members = TeamMember.objects.filter(team=team) return render(request, 'core/team.html', {'team': team, 'form': form, 'invite_user_form': invite_user_form, 'members': members}) @login_required def update_team(request, team_id): team = get_object_or_404(Team, pk=team_id) if request.method == 'POST': form = TeamForm(request.POST, instance=team) if form.is_valid(): form.save() update_photo = request.FILES.get('photo', None) if update_photo: team.photo = update_photo team.save() messages.success(request, 'Данные команды изменены') return redirect('show_team', team.id) @login_required @require_http_methods(["POST"]) def invite_user(request, team_id): form = InviteUserForm(request.POST) inviter = request.user team = get_object_or_404(Team, pk=team_id) if form.is_valid(): first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] birth_date = form.cleaned_data['birth_date'] email = form.cleaned_data['email'] sex = form.cleaned_data['sex'] username = utils.generate_unique_username([first_name, last_name, email]) password = get_random_string(length=8) User = get_user_model() invited_user = User.objects.create_user(username=username, email=email, password=password) invited_user.birth_date = birth_date invited_user.sex = sex invited_user.is_active = True invited_user.first_name = first_name invited_user.last_name = last_name invited_user.save() send_mail('Приглашение на сайт ARF.BY', 'Вас пригласил {}. Ваш логин: {}. Ваш пароль: {}, пожалуйста, ' 'смените его после первого входа на сайт'.format(inviter.get_full_name(), email, password), 'admin@arf.by', [email], fail_silently=True) messages.success(request, 'Приглашение отправлено') team_member = TeamMember(team=team, user=invited_user, is_admin=False) team_member.save() else: messages.error(request, 'Участник с данным адресом электронной почты уже зарегистрирован!') return redirect('show_team', team_id) @login_required def team_add_member(request, team_id, user_id): team = get_object_or_404(Team, pk=team_id) target_user = get_user_model().objects.get(pk=user_id) if request.user.is_team_admin(team_id): tm = TeamMember.objects.create(user=target_user, team=team, is_admin=False) tm.save() return redirect('show_team', team_id) @login_required def remove_team_member(request, team_id, member_id): team = get_object_or_404(Team, pk=team_id) user = request.user target_user = get_user_model().objects.get(pk=member_id) if user.is_team_admin(team_id): tm = TeamMember.objects.get(user=target_user, team=team) if tm.user.is_played_for_team(team): messages.error(request, 'Невозможно удалить участника, потому как он принимал участие в гонках за команду') elif tm.is_admin: messages.error(request, 'Невозможно удалить участника, наделенного правами администратора') elif tm.user.is_in_future_team_entries(): messages.error(request, 'Невозможно удалить участника, ' 'зарегистрированного на будущее мероприятие в составе текущей команды') else: tm.delete() messages.success(request, 'Участник удален из состава команды.') else: raise PermissionDenied return redirect('show_team', team_id) @login_required def grant_team_admin(request, team_id, member_id): target_user = get_user_model().objects.get(pk=member_id) if request.user.is_team_admin(team_id): tm = TeamMember.objects.get(user=target_user, team=team_id) tm.is_admin = True tm.save() messages.success(request, 'Права обновлены.') else: raise PermissionDenied return redirect('show_team', team_id) def autocomplete(request): sqs = SearchQuerySet().autocomplete(text=request.GET.get('query','')) result = [] for r in sqs: if int(r.id) != request.user.id: #add and not in team result.append({'data': r.id, 'value': '{} {}'.format(r.first_name, r.last_name)}) the_data = json.dumps({ 'suggestions': result }) return HttpResponse(the_data, content_type='application/json')
# #!/bin/python3 # # import math # import os # import random # import re # import sys # # # # Complete the arrayManipulation function below. # def arrayManipulation(n, queries): # lista_final = [0 for _ in range(n)] # for i in range(len(queries)): # for j in range(queries[i][0], queries[i][1]+1): # lista_final[j-1] += queries[i][2] # return max(lista_final) # # if __name__ == '__main__': # # nm = input().split() # # n = int(nm[0]) # # m = int(nm[1]) # # queries = [] # # for _ in range(m): # queries.append(list(map(int, input().rstrip().split()))) # # result = arrayManipulation(n, queries) # print(result) n, inputs = [int(n) for n in input().split(" ")] list = [0]*(n+1) for _ in range(inputs): x, y, incr = [int(n) for n in input().split(" ")] list[x-1] += incr if((y)<=len(list)): list[y] -= incr; print(list) max = x = 0 for i in list: x=x+i; if(max<x): max=x; print(max)
#------------------------------------------------------------------------------- # Name: NLTK-Entity-Extraction # Author: Pratap Vardhan # Created: 17-10-2013 #------------------------------------------------------------------------------- import nltk # Read the file f = open('file.txt') # Each sentence stored in line data = f.readlines() for line in data: # Tokenize each line tokens = nltk.word_tokenize(line) # Apply POS Tagger on tokens tagged = nltk.pos_tag(tokens) # NE chunking on tags entities = nltk.chunk.ne_chunk(tagged) print entities f.close()
#!python # encoding: utf-8 # Created by djg-m at 07.01.2021 from handling_db import SqlHandling class ManageDB: """ Creates a database and relations for messenger application. """ def __init__(self, db): self.database = db self.db = None def create_db(self): """ Creates a database. :return: None :rtype: None """ self.db = SqlHandling() self.db.do_database(self.database) def create_users_table(self): """ Creates user relation. :return: None :rtype: None """ sql = ("CREATE TABLE users (" "id serial PRIMARY KEY," "username VARCHAR(255)," "hashed_password BYTEA" ")") self.db.do_query(sql) def create_messages_table(self): """ Creates messages relation. :return: None :rtype: None """ sql = ("CREATE TABLE messages (" "id serial PRIMARY KEY," "from_id INT REFERENCES users(id)," "to_id INT REFERENCES users(id)," "message TEXT," "creation_date TIMESTAMP DEFAULT current_timestamp" ")") self.db.do_query(sql) if __name__ == "__main__": db = ManageDB('msg_t01') db.create_db() db.create_users_table() db.create_messages_table()
import pygame class Screen: screen = None background = None # Constructor for the screen object that uses the above screen size declarations # background should be an SDL_rect def __init__(self, w, h): # Screen settings self.screen = pygame.display.set_mode((w, h)) # background should be an SDL_Rect def set_background(self, background): self.background = background def draw(self): if self.background is not None: self.screen.blit(self.background, (0, 0)) pygame.display.flip()
# -*- coding: utf-8 -*- # Copyright 2017 IBM RESEARCH. 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. # ============================================================================= """ A collection of useful quantum information functions. Currently this file is very sparse. More functions will be added over time. """ import math import numpy as np import scipy.linalg as la from qiskit.tools.qi.pauli import pauli_group ############################################################### # circuit manipulation. ############################################################### # Define methods for making QFT circuits def qft(circ, q, n): """n-qubit QFT on q in circ.""" for j in range(n): for k in range(j): circ.cu1(math.pi/float(2**(j-k)), q[j], q[k]) circ.h(q[j]) ############################################################### # State manipulation. ############################################################### def partial_trace(state, sys, dims=None, reverse=True): """ Partial trace over subsystems of multi-partite matrix. Note that subsystems are ordered as rho012 = rho0(x)rho1(x)rho2. Args: state (NxN matrix_like): a matrix sys (list(int): a list of subsystems (starting from 0) to trace over dims (list(int), optional): a list of the dimensions of the subsystems. If this is not set it will assume all subsystems are qubits. reverse (bool, optional): ordering of systems in operator. If True system-0 is the right most system in tensor product. If False system-0 is the left most system in tensor product. Returns: A matrix with the appropriate subsytems traced over. """ # convert op to density matrix rho = np.array(state) if rho.ndim == 1: rho = outer(rho) # convert state vector to density mat # compute dims if not specified if dims is None: n = int(np.log2(len(rho))) dims = [2 for i in range(n)] if len(rho) != 2 ** n: raise Exception("Input is not a multi-qubit state, \ specifify input state dims") else: dims = list(dims) # reverse sort trace sys if isinstance(sys, int): sys = [sys] else: sys = sorted(sys, reverse=True) # trace out subsystems for j in sys: # get trace dims if reverse: dpre = dims[j + 1:] dpost = dims[:j] else: dpre = dims[:j] dpost = dims[j + 1:] dim1 = int(np.prod(dpre)) dim2 = int(dims[j]) dim3 = int(np.prod(dpost)) # dims with sys-j removed dims = dpre + dpost # do the trace over j rho = __trace_middle(rho, dim1, dim2, dim3) return rho def __trace_middle_dims(sys, dims, reverse=True): """ Get system dimensions for __trace_middle. Args: j (int): system to trace over. dims(list[int]): dimensions of all subsystems. reverse (bool): if true system-0 is right-most system tensor product. Returns: Tuple (dim1, dims2, dims3) """ dpre = dims[:sys] dpost = dims[sys + 1:] if reverse: dpre, dpost = (dpost, dpre) dim1 = int(np.prod(dpre)) dim2 = int(dims[sys]) dim3 = int(np.prod(dpost)) return (dim1, dim2, dim3) def __trace_middle(op, dim1=1, dim2=1, dim3=1): """ Partial trace over middle system of tripartite state. Args: op (NxN matrix_like): a tri-partite matrix dim1: dimension of the first subsystem dim2: dimension of the second (traced over) subsystem dim3: dimension of the third subsystem Returns: A (D,D) matrix where D = dim1 * dim3 """ op = op.reshape(dim1, dim2, dim3, dim1, dim2, dim3) d = dim1 * dim3 return op.trace(axis1=1, axis2=4).reshape(d, d) def vectorize(rho, method='col'): """Flatten an operator to a vector in a specified basis. Args: rho (ndarray): a density matrix. method (str): the method of vectorization. Allowed values are - 'col' (default) flattens to column-major vector. - 'row' flattens to row-major vector. - 'pauli'flattens in the n-qubit Pauli basis. - 'pauli-weights': flattens in the n-qubit Pauli basis ordered by weight. Returns: ndarray: the resulting vector. """ rho = np.array(rho) if method == 'col': return rho.flatten(order='F') elif method == 'row': return rho.flatten(order='C') elif method in ['pauli', 'pauli_weights']: num = int(np.log2(len(rho))) # number of qubits if len(rho) != 2**num: raise Exception('Input state must be n-qubit state') if method is 'pauli_weights': pgroup = pauli_group(num, case=0) else: pgroup = pauli_group(num, case=1) vals = [np.trace(np.dot(p.to_matrix(), rho)) for p in pgroup] return np.array(vals) def devectorize(vec, method='col'): """Devectorize a vectorized square matrix. Args: vec (ndarray): a vectorized density matrix. basis (str): the method of devectorizaation. Allowed values are - 'col' (default): flattens to column-major vector. - 'row': flattens to row-major vector. - 'pauli': flattens in the n-qubit Pauli basis. - 'pauli-weights': flattens in the n-qubit Pauli basis ordered by weight. Returns: ndarray: the resulting matrix. """ vec = np.array(vec) d = int(np.sqrt(vec.size)) # the dimension of the matrix if len(vec) != d*d: raise Exception('Input is not a vectorized square matrix') if method == 'col': return vec.reshape(d, d, order='F') elif method == 'row': return vec.reshape(d, d, order='C') elif method in ['pauli', 'pauli_weights']: num = int(np.log2(d)) # number of qubits if d != 2 ** num: raise Exception('Input state must be n-qubit state') if method is 'pauli_weights': pgroup = pauli_group(num, case=0) else: pgroup = pauli_group(num, case=1) pbasis = np.array([p.to_matrix() for p in pgroup]) / 2 ** num return np.tensordot(vec, pbasis, axes=1) def choi_to_rauli(choi, order=1): """ Convert a Choi-matrix to a Pauli-basis superoperator. Note that this function assumes that the Choi-matrix is defined in the standard column-stacking converntion and is normalized to have trace 1. For a channel E this is defined as: choi = (I \otimes E)(bell_state). The resulting 'rauli' R acts on input states as |rho_out>_p = R.|rho_in>_p where |rho> = vectorize(rho, method='pauli') for order=1 and |rho> = vectorize(rho, method='pauli_weights') for order=0. Args: Choi (matrix): the input Choi-matrix. order (int, optional): ordering of the Pauli group vector. order=1 (default) is standard lexicographic ordering. Eg: [II, IX, IY, IZ, XI, XX, XY,...] order=0 is ordered by weights. Eg. [II, IX, IY, IZ, XI, XY, XZ, XX, XY,...] Returns: A superoperator in the Pauli basis. """ # get number of qubits' n = int(np.log2(np.sqrt(len(choi)))) pgp = pauli_group(n, case=order) rauli = [] for i in pgp: for j in pgp: pauliop = np.kron(j.to_matrix().T, i.to_matrix()) rauli += [np.trace(np.dot(choi, pauliop))] return np.array(rauli).reshape(4 ** n, 4 ** n) def chop(op, epsilon=1e-10): """ Truncate small values of a complex array. Args: op (array_like): array to truncte small values. epsilon (float): threshold. Returns: A new operator with small values set to zero. """ op.real[abs(op.real) < epsilon] = 0.0 op.imag[abs(op.imag) < epsilon] = 0.0 return op def outer(v1, v2=None): """ Construct the outer product of two vectors. The second vector argument is optional, if absent the projector of the first vector will be returned. Args: v1 (ndarray): the first vector. v2 (ndarray): the (optional) second vector. Returns: The matrix |v1><v2|. """ if v2 is None: u = np.array(v1).conj() else: u = np.array(v2).conj() return np.outer(v1, u) ############################################################### # Measures. ############################################################### def funm_svd(a, func): """Apply real scalar function to singular values of a matrix. Args: a : (N, N) array_like Matrix at which to evaluate the function. func : callable Callable object that evaluates a scalar function f. Returns: funm : (N, N) ndarray Value of the matrix function specified by func evaluated at `A`. """ U, s, Vh = la.svd(a, lapack_driver='gesvd') S = np.diag(func(s)) return U.dot(S).dot(Vh) def state_fidelity(state1, state2): """Return the state fidelity between two quantum states. Either input may be a state vector, or a density matrix. Args: state1: a quantum state vector or density matrix. state2: a quantum state vector or density matrix. Returns: The state fidelity F(state1, state2). """ # convert input to numpy arrays s1 = np.array(state1) s2 = np.array(state2) # fidelity of two state vectors if s1.ndim == 1 and s2.ndim == 1: return np.abs(s2.conj().dot(s1)) # fidelity of vector and density matrix elif s1.ndim == 1: # psi = s1, rho = s2 return np.sqrt(np.abs(s1.conj().dot(s2).dot(s1))) elif s2.ndim == 1: # psi = s2, rho = s1 return np.sqrt(np.abs(s2.conj().dot(s1).dot(s2))) # fidelity of two density matrices else: s1sq = funm_svd(s1, np.sqrt) s2sq = funm_svd(s2, np.sqrt) return np.linalg.norm(s1sq.dot(s2sq), ord='nuc') def purity(state): """Calculate the purity of a quantum state. Args: state (np.array): a quantum state Returns: purity. """ rho = np.array(state) if rho.ndim == 1: rho = outer(rho) return np.real(np.trace(rho.dot(rho))) def concurrence(state): """Calculate the concurrence. Args: state (np.array): a quantum state Returns: concurrence. """ rho = np.array(state) if rho.ndim == 1: rho = outer(state) if len(state) != 4: raise Exception("Concurence is not defined for more than two qubits") YY = np.fliplr(np.diag([-1, 1, 1, -1])) A = rho.dot(YY).dot(rho.conj()).dot(YY) w = la.eigh(A, eigvals_only=True) w = np.sqrt(np.maximum(w, 0)) return max(0.0, w[-1]-np.sum(w[0:-1])) ############################################################### # Other. ############################################################### def is_pos_def(x): return np.all(np.linalg.eigvals(x) > 0)
import sys from node import * #input params, where we make two lists, and make them intersect input_list_1 = list([1, 9, 3, 6, 5, 11, 3, 2]); input_list_2 = list([11, -1, 2, 4, 3, 7, 8, 9]); intersect_index = 3; linked_list_1 = node(); linked_list_1.make_list(input_list_1); linked_list_2 = node(); linked_list_2.make_list(input_list_2); iterator_1 = linked_list_1; for index in range(intersect_index): iterator_1 = iterator_1.next; iterator_2 = linked_list_2; for index in range(len(input_list_2)-1): iterator_2 = iterator_2.next; iterator_2.next = iterator_1; #we now inspect the two linked lists to see if they intersect... #...by trying to see where two iterators (one for each list) itersect print("FIRST LIST: "); linked_list_1.print_list(); print("SECOND LIST: "); linked_list_2.print_list(); iterator_1 = linked_list_1; list_1_len = 0; while(iterator_1): list_1_len += 1; iterator_1 = iterator_1.next; iterator_2 = linked_list_2; list_2_len = 0; while(iterator_2): list_2_len += 1; iterator_2 = iterator_2.next; #make sure that the first list is the larger one if (list_1_len < list_2_len): list_1_len, list_2_len = list_2_len, list_1_len; linked_list_1, linked_list_2 = linked_list_2, linked_list_1; #advance the iterator of first list so that iterator_1, iterator_2 have to cover the same total distance advance_iterator_1 = list_1_len-list_2_len; iterator_1, iterator_2 = linked_list_1, linked_list_2; for index in range(advance_iterator_1): iterator_1 = iterator_1.next; #we assume that the lists don't intersect, then we try to disprove it does_intersect = False; for index in range(list_2_len): if (id(iterator_1) == id(iterator_2)): does_intersect = True; break; iterator_1 = iterator_1.next; iterator_2 = iterator_2.next; #print output if (does_intersect): print("INTERSECTION HAPPENS!"); else: print("NO INTERSECTION HAPPENS!");
import socket import threading import tkinter import tkinter.messagebox # 服务器 Ip = '127.0.0.1' Port = 50007 ServerAddr = (Ip, Port) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(ServerAddr) Channel = '0' # 表示不在任何一个聊天室 UserId = '0' # 表示还未进入聊天室,没有username UserName = 'server' Rooms = [] # 聊天室 [[room_name,[UserName, UserId, Addr],...] # [room_name,users,users,...] # 用于存放在线用户的信息 [username, userid, addr] # 聊天窗口 # 创建图形界面 Root = tkinter.Tk() Root.title('server') # 窗口命名为用户名 Root['height'] = 380 Root['width'] = 600 # 创建多行文本框 ListBox = tkinter.Listbox(Root) ListBox.place(x=130, y=0, width=300, height=300) # 创建输入文本框和关联变量 msg = tkinter.StringVar() msg.set('') entry = tkinter.Entry(Root, width=120, textvariable=msg) entry.place(x=130, y=310, width=230, height=50) # 滚动条 scrollbar = tkinter.Scrollbar(ListBox, command=ListBox.yview) scrollbar.pack(side=tkinter.RIGHT, fill=tkinter.Y) ListBox.config(yscrollcommand=scrollbar.set) # new channel输入框 new_channel = tkinter.StringVar() new_channel.set('') new_channel_entry = tkinter.Entry(Root, textvariable=new_channel) new_channel_entry.place(x=50, y=310, width=75, height=20) # online users online_user_list = tkinter.Listbox(Root) online_user_list.place(x=430, y=0, width=170, height=300) # init online user def init_online_user(): online_user_list.delete(0, tkinter.END) online_user_list.insert(tkinter.END, "----------Online Users--------") online_user_list.itemconfig(tkinter.END, fg='blue') init_online_user() # 更新自己的users列表 def update_users(u): init_online_user() para = u.split(' ') for item in para: online_user_list.insert(tkinter.END, item) # 更新用户的user列表 # i表示channel index def client_update_online_users(i): # 把更新后的用户列表发给channel里每一个人 m = "server 0:20:0:" for j in range(1, len(Rooms[i])): m = m + Rooms[i][j][1] + " " for j in range(1, len(Rooms[i])): s.sendto(m.encode(), Rooms[i][j][2]) # channel list channel_list = tkinter.Listbox(Root) channel_list.place(x=0, y=0, width=130, height=300) # 初始化channel list def init_channel_list(): channel_list.delete(0, tkinter.END) channel_list.insert(tkinter.END, "-------Channels-------") channel_list.itemconfig(tkinter.END, fg='blue') init_channel_list() # server 离开房间初始化 def init(): global Channel, UserId Channel = '0' UserId = '0' # 清空用户列表 init_online_user() # 清空文本框 ListBox.delete(0, tkinter.END) # 标题 Root.title('server') # enter channel # 处理自己 # 给其他用户发送消息 # 必须先离开当前channel,才能进入下一个channel def enter(event): global UserId, Channel me = channel_list.get(channel_list.curselection()) if Channel == '0': Channel = me # title改成channel名称 Root.title(channel_list.get(channel_list.curselection())) for i in range(len(Rooms)): if Rooms[i][0] == me: user_id = UserName + '-' + str(len(Rooms[i])) UserId = user_id Rooms[i].append(['server', user_id, ServerAddr]) tkinter.messagebox.showinfo(title="Reminder", message="You now in "+me) # enter之后把用户列表发给每一个人 client_update_online_users(i) break else: tkinter.messagebox.showerror(title="ERROR", message="You have to leave this room first!") channel_list.bind('<Double-Button>', enter) # 提醒用户,有人离开了房间 # 22 # i index of channel u userid def client_sb_leave(i, u): data = "server 0:22:0:" + u for j in range(1, len(Rooms[i])): s.sendto(data.encode(), Rooms[i][j][2]) # kick out userid # 21 def kickout(event): dstId = online_user_list.get(online_user_list.curselection()) if dstId == UserId: tkinter.messagebox.showinfo(title="Reminder", message="You cannot kick out yourself") else: for i in range(len(Rooms)): if Rooms[i][0] == Channel: for j in range(1, len(Rooms[i])): if Rooms[i][j][1] == dstId: data = "server 0:21:0:" s.sendto(data.encode(), Rooms[i][j][2]) del (Rooms[i][j]) tkinter.messagebox.showinfo(title="Reminder", message="You kick out " + dstId) break # 更新用户列表 # 20 client_update_online_users(i) # 发送给每个其他的用户,该用户已经离开, # 22 client_sb_leave(i, dstId) break online_user_list.bind('<Double-Button>', kickout) # 更新channel list,给每个用户发送channel # 只有在开通channel和关闭channel时需要update def update_channels(): init_channel_list() m = "server 0:19:0:" for i in range(len(Rooms)): m = m + Rooms[i][0] + ' ' # 计算要发送的channel channel_list.insert(tkinter.END, Rooms[i][0]) # 更新自己列表 for i in range(len(Rooms)): for j in range(1, len(Rooms[i])): s.sendto(m.encode(), Rooms[i][j][2]) # 给每个用户更新channel信息 # button open channel # 检查是否有重名的channel def open_channel(): channelname = new_channel_entry.get() new_channel.set('') # 清空 if channelname == "": tkinter.messagebox.showinfo(title="Reminder", message="Please input channel name") else: flag = 0 for i in range(len(Rooms)): if Rooms[i][0] == channelname: tkinter.messagebox.showerror(title="ERROR", message="This room already exists!") flag = 1 break if flag == 0: room = [channelname] Rooms.append(room) update_channels() # open channel open_channel_butt = tkinter.Button(Root, text='New', command=open_channel) open_channel_butt.place(x=5, y=310, width=40, height=20) # leave channel def leave(): global Channel, UserId if Channel == '0': tkinter.messagebox.showinfo(title="Reminder", message="You are not in any channel") else: for i in range(len(Rooms)): if Rooms[i][0] == Channel: # 自己退出 for j in range(1, len(Rooms[i])): if Rooms[i][j][2] == ServerAddr: del (Rooms[i][j]) tkinter.messagebox.showinfo(title="Reminder", message="You leave " + Channel) break client_sb_leave(i, UserId) client_update_online_users(i) break init() leave_channel_butt = tkinter.Button(Root, text='Leave', command=leave) leave_channel_butt.place(x=65, y=340, width=50, height=20) # close channel # 一定要选中 def close(): dstCh = channel_list.get(channel_list.curselection()) if dstCh == Channel: tkinter.messagebox.showerror(title="error", message="You should leave first!") else: for i in range(len(Rooms)): if Rooms[i][0] == dstCh: m = "server 0:23:0:" for j in range(1, len(Rooms[i])): s.sendto(m.encode(), Rooms[i][j][2]) del (Rooms[i]) break # server反应 tkinter.messagebox.showinfo(title="Reminder", message="You closed " + dstCh) update_channels() close_channal_butt = tkinter.Button(Root, text='Close', command=close) close_channal_butt.place(x=5, y=340, width=50, height=20) # server 处理转发message def transmit_message(user, channel, sender_data): user_info = user.split(' ', 1) user_id = user_info[1] user_name = user_info[0] m = user_name + ' ' + user_id + ':15:' + channel + ':' + sender_data for i in range(len(Rooms)): if Rooms[i][0] == channel: for j in range(1, len(Rooms[i])): s.sendto(m.encode(), Rooms[i][j][2]) # 表示要显示在屏幕上的 def message(user, recv_data): user_info = user.split(' ', 1) user_id = user_info[1] m = 'From ' + user_id + ' :' + recv_data ListBox.insert(tkinter.END, m) # 发送当前channel def client_channels(recv_data): if len(Rooms) == 0: m = "server 0:19:0:" else: m = "server 0:19:0:" for i in range(len(Rooms)): m = m + Rooms[i][0] + ' ' s.sendto(m.encode(), recv_data) def client_join(addr, parameters): user_info = parameters.split(' ', 1) user_name = user_info[1] channel_name = user_info[0] for i in range(len(Rooms)): if Rooms[i][0] == channel_name: # 请求对象更新状态,回复userid user_id = user_name+'-'+str(len(Rooms[i])) Rooms[i].append([user_name, user_id, addr]) m = "server 0:17:0:"+user_name+' '+user_id+' '+channel_name s.sendto(m.encode(), addr) # join 之后把用户列表发给所有用户 # channel更新 # 更新用户的channel 列表 # 这里是防止用户在请求channel之后还未加入channel # server又新开了几个channel # 加入之后可以马上更新 client_update_online_users(i) update_channels() break # 处理转发private msg def client_msg(sender_info, channel_name, parameters): para = parameters.split(' ', 1) recv_id = para[0] recv_addr = [] m = para[1] for i in range(len(Rooms)): if Rooms[i][0] == channel_name: for j in range(1, len(Rooms[i])): if Rooms[i][j][1] == recv_id: recv_addr = Rooms[i][j][2] break break m = sender_info + ':18:' + channel_name + ":(private) " + m s.sendto(m.encode(), recv_addr) # 同意user离开的回复 def client_leave(addr, user, channel_name): client = user.split(' ', 1) user_id = client[1] for i in range(len(Rooms)): if Rooms[i][0] == channel_name: for j in range(1, len(Rooms[i])): if Rooms[i][j][1] == user_id: del (Rooms[i][j]) m = 'server 0:16:0:' s.sendto(m.encode(), addr) break # 发送给每个其他的用户,该用户已经离开,并且要更新用户列表 client_sb_leave(i, user_id) client_update_online_users(i) break def sb_leave(u): tkinter.messagebox.showinfo(title="Attention", message=u + " has left!") # 接收 def rec(): # 解析协议 while True: data, r_addr = s.recvfrom(512) data = data.decode() recv_mes = data.split(':', 3) if recv_mes[1] == '08': # [addr, username user_id, channel, parameters] transmit_message(recv_mes[0], recv_mes[2], recv_mes[3]) elif recv_mes[1] == '09': client_channels(r_addr) elif recv_mes[1] == '10': # [addr, parameters] client_join(r_addr, recv_mes[3]) elif recv_mes[1] == '12': client_msg(recv_mes[0], recv_mes[2], recv_mes[3]) elif recv_mes[1] == '13': client_leave(r_addr, recv_mes[0],recv_mes[2]) elif recv_mes[1] == '15': message(recv_mes[0], recv_mes[3]) elif recv_mes[1] == '20': update_users(recv_mes[3]) elif recv_mes[1] == '22': sb_leave(recv_mes[3]) t = threading.Thread(target=rec) t.start() # 发送 # 当前不在任何一个聊天室内 def send(event=0): # 应用层协议格式 # parameter_number # command type # sender_channel # parameters # msg(if any) if Channel == '0': tkinter.messagebox.showinfo(title="Reminder", message="Please join in any channel first") else: m = entry.get() m = 'server' + ' ' + UserId + ':08:' + Channel + ':' + m s.sendto(m.encode(), ServerAddr) msg.set('') # 发送后清空文本框 # 创建发送按钮 button = tkinter.Button(Root, text='发送', command=send) button.place(x=370, y=310, width=60, height=50) Root.bind('<Return>', send) # 绑定回车发送信息 Root.mainloop() # 结束,切断 s.close()
# -*- coding: utf-8 -*- """ Created on Sat Jun 24 10:03:22 2017 @author: Jonathan Morgan """ from subprocess import call import sys import re from PyQt5 import QtWidgets, QtCore, QtGui from PyQt5.QtWidgets import QWidget, QStackedWidget, QApplication,\ QLineEdit, QCheckBox, QLabel, QAction, QMainWindow, QFileDialog, QGridLayout, QVBoxLayout,\ QGroupBox, QFormLayout, QSpinBox, QPushButton from PyQt5.QtCore import QProcess import numpy as np from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar import matplotlib.pyplot as plt class Window(QMainWindow): def __init__(self): super(Window, self).__init__() self.initUI() def initUI(self): # defining the exitting, saving and opening of files exitAction = QAction('&Exit', self) exitAction.setShortcut('Ctrl+Q') exitAction.setStatusTip('Exit/Terminate application') exitAction.triggered.connect(self.close) openAction = QAction('&Open Input File', self) openAction.setShortcut('Ctrl+O') openAction.setStatusTip('Open Input File') openAction.triggered.connect(self.openFileNameDialog) saveAction = QAction('&Save Input File', self) saveAction.setShortcut('Ctrl+S') saveAction.setStatusTip('Save Input File') saveAction.triggered.connect(self.saveFileDialog) losAction = QAction('&Generate Input File', self) losAction.setStatusTip('Generate LOS File') losAction.triggered.connect(self.genLOSFile) helpAction = QAction('&Help', self) helpAction.setShortcut('Ctrl+H') helpAction.setStatusTip('Help') helpAction.triggered.connect(self.helpFileDialog) self.statusBar() menubar = self.menuBar() menubar.setToolTip('This is a <b>QWidget</b> for MenuBar') fileMenu = menubar.addMenu('&File') fileMenu.addAction(exitAction) fileMenu.addAction(openAction) fileMenu.addAction(saveAction) fileMenu.addAction(losAction) fileMenu.addAction(helpAction) toolbar = self.addToolBar('Exit') toolbar.addAction(exitAction) toolbar.addAction(openAction) toolbar.addAction(saveAction) toolbar.addAction(losAction) toolbar.addAction(helpAction) self.content = Widgettown(self) self.setCentralWidget(self.content) self.show() def openFileNameDialog(self): # MASTER READ CAPABILITY(AND POPULATE WIDGETS) name, _ = QFileDialog.getOpenFileName(self, "Open File", "", "All Files(*);;Input Files(*.inp)") if name: # reading in the file then going to compare to existing dictionary keys print("Opening Input File:", name) line_num = 2 l_input = {} input_text = open(name).read() ba = QtCore.QByteArray(input_text.encode('utf-8')) input_line = QtCore.QTextStream(ba) while input_line.atEnd() is False: line1 = input_line.readLine() if "---" in line1: line1 = input_line.readLine() if "Line" in line1: line1 = input_line.readLine() count = 0 l_input['Line'+str(line_num)] = np.empty(shape=(1, 1), dtype='<U25') while re.match('(.)', line1) is not None: tmp=line1.split() for i in range(len(tmp)): tmp[i] = str(tmp[i]) if count > 0 and len(tmp) != len(l_input['Line'+str(line_num)][count-1]): if len(tmp) > len(l_input['Line'+str(line_num)][count-1]): dif = len(tmp) - len(l_input['Line'+str(line_num)][count-1]) t = np.pad(l_input['Line'+str(line_num)][0:count-1], ((0,0),(0,dif)), 'constant',constant_values=(0,)) l_input['Line'+str(line_num)] = t l_input['Line'+str(line_num)]=np.resize(l_input['Line'+str(line_num)], [count+1, len(tmp)]) for i in range(len(tmp)): l_input['Line'+str(line_num)][count, i]=tmp[i] elif len(tmp) < len(l_input['Line'+str(line_num)][count-1]): w = len(l_input['Line'+str(line_num)][count-1]) l_input['Line'+str(line_num)] = np.resize(l_input['Line'+str(line_num)], [count+1, w]) for i in range(len(tmp)): l_input['Line'+str(line_num)][count, i]=tmp[i] else: l_input['Line'+str(line_num)]=np.resize(l_input['Line'+str(line_num)], [count+1, len(tmp)]) for i in range(len(tmp)): l_input['Line'+str(line_num)][count, i]=tmp[i] line1 = input_line.readLine() count += 1 line_num += 1 tmp = list(l_input['Line2'][-1, 0]) l_input['Line2'] = np.resize(l_input['Line2'], [1, len(tmp)]) for ll in range(len(tmp)): l_input['Line2'][0, ll] = tmp[ll] print(l_input) # SHOULD TRY TO MODULARIZE THIS AND GNERALIZE FOR GETTING THE INPUTS WHERE THEY NEED TO GO # now going to compare the entries in the dictionary to buttons for i in range(2, len(l_input)+2, 1): # starting from line 2 if l_input['Line'+str(i)] is not None: if i > 6: if i == 7: self.content.regionbox.setValue(len(l_input['Line'+str(i)])) for g in range(len(self.content.il['Line'+str(i)])): # for the range of the input line dictionary for h in range(len(self.content.il['Line'+str(i)][g])): if "QCheckBox" in str(self.content.il['Line'+str(i)][g,h]): self.content.il['Line'+str(i)][g,h].setChecked(False) elif "QLineEdit" in str(self.content.il['Line'+str(i)][g, h]): self.content.il['Line'+str(i)][g,h].setText("0.0") elif "QComboBox" in str(self.content.il['Line'+str(i)][g, h]): self.content.il['Line'+str(i)][g,h].setCurrentIndex(0) try: if l_input['Line'+str(i)][g, h] is not None: if "QLineEdit" in str(self.content.il['Line'+str(i)][g, h]) and any(char.isdigit() for char in l_input['Line'+str(i)][g, h]) is True: self.content.il['Line'+str(i)][g, h].setText(l_input['Line'+str(i)][g, h]) print("set",l_input['Line'+str(i)][g, h],"in QLineEdit") elif hasattr(self.content.il['Line'+str(i)][g, h], 'currentIndex') is True: for k in range(self.content.il['Line'+str(i)][g, h].count()): if l_input['Line'+str(i)][g, h] in self.content.il['Line'+str(i)][g, h].itemText(k): self.content.il['Line'+str(i)][g, h].setCurrentIndex(k) print("set",l_input['Line'+str(i)][g, h],"in QComboBox") elif "QCheckBox" in str(self.content.il['Line'+str(i)][g, h]) and l_input['Line'+str(i)][g, h] is not None: self.content.il['Line'+str(i)][g, h].setChecked(True) self.content.il['Line'+str(i)][g, h+1].setText(l_input['Line'+str(i)][g, h+1]) print("set",l_input['Line'+str(i)][g, h],"in QCheckBox") except: print("READ DID NOT FIND ENTRIES AT: OR FIELD DOES NOT EXIST", g, h) if i < 6: for m in range(len(l_input['Line'+str(i)])): # for the range of the input line dictionary for n in range(len(l_input['Line'+str(i)][m])): for g in range(len(self.content.il['Line'+str(i)])): # for the range of the existing dictionary and corresonding lines for h in range(len(self.content.il['Line'+str(i)][g])): #if "QCheckBox" in str(self.content.il['Line'+str(i)][g,h]) and self.content.il['Line'+str(i)][g,h].isChecked() is True: # self.content.il['Line'+str(i)][g,h].setChecked(False) #elif "QLineEdit" in str(self.content.il['Line'+str(i)][g, h]) and self.content.il['Line'+str(i)][g, h].text() != "0.0": # self.content.il['Line'+str(i)][g,h].setText("0.0") #elif "QComboBox" in str(self.content.il['Line'+str(i)][g, h]) and self.content.il['Line'+str(i)][g, h].currentIndex() != 0: # self.content.il['Line'+str(i)][g,h].setCurrentIndex(0) if "QCheckBox" in str(self.content.il['Line'+str(i)][g, h]) and "("+l_input['Line'+str(i)][m, n]+")" in self.content.il['Line'+str(i)][g, h].text(): self.content.il['Line'+str(i)][g, h].setChecked(True) print("CheckBox ",self.content.il['Line'+str(i)][g, h].text(),"Checked") elif i == 3 and self.content.il['Line'+str(i)][1, 0].isChecked() is True: if "QComboBox" in str(self.content.il['Line'+str(i)][g, h]): for k in range(self.content.il['Line'+str(i)][g, h].count()): if "("+l_input['Line'+str(i)][m, n]+")" in self.content.il['Line'+str(i)][g, h].itemText(k): self.content.il['Line'+str(i)][g, h].setCurrentIndex(k) if "QLineEdit" in str(self.content.il['Line'+str(i)][g, h]) and l_input['Line'+str(i)][0, 3] is not None: self.content.il['Line'+str(i)][g, h].setText(str(l_input['Line'+str(i)][0, 3])) def helpFileDialog(self): msgbox = QtWidgets.QDialog() text=open('help.txt').read() msgbox.setWindowTitle("Help File") msg = QtWidgets.QTextEdit(msgbox) msg.resize(700,700) msg.updateGeometry() msg.setText(text) msg.setReadOnly(True) msgbox.resize(700,700) msgbox.updateGeometry() msgbox.setWindowModality(QtCore.Qt.ApplicationModal) msgbox.exec_() def genLOSFile(self): name = QFileDialog.getSaveFileName(self, "Write Out LOS File", "", "All Files(*);;Input Files(*.dat)") print("Writing LOS out to:", name[0]) f = open(name[0], 'w') f.write("#15.0\n#\n\n") f.write("n x ntot Tt") sum_nrho = 0 for i in range(0, self.content.los['SpecNum'].value()): ind = self.content.los['Species'][i, 0].currentIndex() f.write(" "+self.content.los['Species'][i, 0].itemText(ind)) sum_nrho += float(self.content.los['Species'][i, 1].text()) f.write("\n"+str(1)+" "+str(0.0)+" "+str(sum_nrho)+" "+str(float(self.content.los['Temperature'].text()))) for i in range(0, self.content.los['SpecNum'].value()): f.write(" "+self.content.los['Species'][i, 1].text()) def saveFileDialog(self): # MASTER WRITE CAPABILITY name = QFileDialog.getSaveFileName(self, "Save File", "", "All Files(*);;Input Files(*.inp)") print("Writing out to:", name[0]) f = open(name[0], 'w') f.write("15.0\n**********\n**********\n") f.write("Line 0: Header - anything between here and the ---'s writes to stdout\n\ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <- 1st format line\n\ --------------------------\n\ Line 1: Database Path\n\ /share/apps/neqair/v15.0-prerelease/DATABASES\n\ --------------------------\n") f.write("Line 2:\n") for i in range(len(self.content.il['Line2'])): for j in range(2): if "QCheckBox" in str(self.content.il['Line2'][i,j]) and self.content.il['Line2'][i, j].isChecked() is True: data = self.content.il['Line2'][i, j].text() data = data[data.find("(")+1:data.find(")")].split()[0] f.write(" "+data) print("Filetype Written") f.write("\n\n") f.write("-------------------\n") f.write("Line 3:\n") for i in range(len(self.content.il['Line3'])): for j in range(3): if "QCheckBox" in str(self.content.il['Line3'][i,j]) and self.content.il['Line3'][i, j].isChecked() is True: data = self.content.il3info[i] data = data[data.find("(")+1:data.find(")")].split()[0] f.write(data) if "Non" in self.content.il['Line3'][i, j].text() and self.content.il['Line3'][i, j].isChecked() is True: if self.content.il['Line3'][i,1].currentIndex() != 0: ind = self.content.il['Line3'][i, 1].currentIndex() data = self.content.il['Line3'][i, 1].itemText(ind) data = data[data.find("(")+1:data.find(")")].split()[0] f.write(" "+data) ind = self.content.il['Line3'][i, 2].currentIndex() data = self.content.il['Line3'][i, 2].itemText(ind) data = data[data.find("(")+1:data.find(")")].split()[0] f.write(" "+data) if self.content.il['Line3'][i,2].currentIndex() < (self.content.il['Line3'][i,2].count()-2): f.write(" "+self.content.il['Line3'][i, 3].text()+"\n") print("State Pop Method Written") f.write("\n\n") f.write("-------------------\n") f.write("Line 4:\n") for i in range(len(self.content.il['Line4'])): if "QCheckBox" in str(self.content.il['Line4'][i, 0]) and self.content.il['Line4'][i, 0].isChecked() is True: data = self.content.il4info[i] data = data[data.find("(")+1:data.find(")")].split()[0] f.write(data) if "(C)" in self.content.il['Line4'][i, 0].text() and self.content.il['Line4'][i, 0].isChecked() is True: f.write(" "+self.content.il['Line4'][i,1].text()+" "+self.content.il['Line4'][i,2].text()) if "(S)" in self.content.il['Line4'][i, 0].text() and self.content.il['Line4'][i, 0].isChecked() is True: f.write(" "+self.content.il['Line4'][i,1].text()) if "(B)" in self.content.il['Line4'][i, 0].text() and self.content.il['Line4'][i, 0].isChecked() is True: f.write(" "+self.content.il['Line4'][i,1].text()) f.write("\n\n") f.write("-------------------\n") f.write("Line 5:\n") print("Geometry Written") for i in range(len(self.content.il['Line5'])): if "QCheckBox" in str(self.content.il['Line5'][i,0]) and self.content.il['Line5'][i, 0].isChecked() is True: if "(G)" in self.content.il['Line5'][i, 0].text() and self.content.il['Line5'][i, 0].isChecked() is True: f.write("G "+self.content.il['Line5'][i,1].text()+" "+self.content.il['Line5'][i,2].text()) else: data = self.content.il5info[i] data = data[data.find("(")+1:data.find(")")].split()[0] f.write(" "+data+"\n") print("Boundary Written") f.write("\n\n") f.write("-------------------\n") f.write("Line 6:\n") f.write("I\n") for i in range(len(self.content.speclist)): if "Button" in str(self.content.il['Line6'][i]) and self.content.il['Line6'][i].isChecked() is True: print("Writing", self.content.il['Line6'][i].text()) if len(self.content.il['Line6'][i].text()) == 1: for j in range(len(self.content.aband)): if self.content.il['Line6CB'][i, j].isChecked() is True: f.write(self.content.il['Line6'][i].text()+" "+self.content.il['Line6CB'][i, j].text()+"\n") if "NO" in self.content.il['Line6'][i].text(): for j in range(len(self.content.noband)): if self.content.il['Line6CB'][i, j].isChecked() is True: f.write("NO "+self.content.il['Line6CB'][i, j].text()+"\n") if "N2" in self.content.il['Line6'][i].text(): for j in range(len(self.content.n2band)): if self.content.il['Line6CB'][i, j].isChecked() is True: f.write("N2 "+self.content.il['Line6CB'][i, j].text()+"\n") if "O2" in self.content.il['Line6'][i].text(): for j in range(len(self.content.o2band)): if self.content.il['Line6CB'][i, j].isChecked() is True: f.write("O2 "+self.content.il['Line6CB'][i, j].text()+"\n") print("Species Bands Written") f.write("\n") f.write("-------------------\n") f.write("Line 7:\n") for i in range(self.content.regionbox.value()): if self.content.il['Line7'][i,0].text() != "0.0": for j in range(len(self.content.il['Line7'][0, :])-1): if "QLineEdit" in str(self.content.il['Line7'][i,j]): dataw1w2 = self.content.il['Line7'][i, j].text() f.write(" "+dataw1w2) if "QComboBox" in str(self.content.il['Line7'][i,j]): ind = self.content.il['Line7'][i, j].currentIndex() dataam = self.content.il['Line7'][i, j].itemText(ind) f.write(" "+dataam) if "QCheckBox" in str(self.content.il['Line7'][i,j]) and self.content.il['Line7'][i, j].isChecked() is True: f.write(" R "+self.content.il['Line7'][i, j+1].text()) f.write("\n") print("Regions Written") f.write("\n") if self.content.il['Line2'][1,0].isChecked() is True: f.write("-------------------\n") f.write("Line 8:\n") for i in range(self.content.regionbox.value()): if self.content.il['Line8'][i,0].text() != "0.0": for j in range(len(self.content.il['Line8'][0, :])): if "QLineEdit" in str(self.content.il['Line8'][i,j]) and self.content.il['Line8'][i,j].text() != "0.0": dataw1w2 = self.content.il['Line8'][i, j].text() f.write(" "+dataw1w2) if "QComboBox" in str(self.content.il['Line8'][i,j]): ind = self.content.il['Line8'][i, j].currentIndex() dataam = self.content.il['Line8'][i, j].itemText(ind) f.write(" "+dataam) f.write("\n") print("Scan Written") f.write("\n") #if self.content.il['Line4'][2,0].isChecked() is True: f.write("-------------------\n") f.write("Line 9:\n") for i in range(len(self.content.il['Line9'])): for j in range(len(self.content.il['Line9'][i])): if j < 2: if "QComboBox" in str(self.content.il['Line9'][i,j]): ind = self.content.il['Line9'][i, j].currentIndex() dataam = self.content.il['Line9'][i, j].itemText(ind) f.write(" "+dataam) if "QLineEdit" in str(self.content.il['Line9'][i,j]) and self.content.il['Line9'][i, j].text() != "0.0": dataw1w2 = self.content.il['Line9'][i, j].text() f.write(" "+dataw1w2) if j == 2: if "QLineEdit" in str(self.content.il['Line9'][i,j]): dataw1w2 = self.content.il['Line9'][i, j].text() f.write(" "+dataw1w2) f.write("\n") f.close() # write all variables out first and then format one f.write function # this may cut down on the cost of the things. class Widgettown(QWidget): # WHERE ALL OF THE FUNCTIONALITY IS LOCATED def __init__(self, parent): QWidget.__init__(self, parent) self.speclist = None self.fontss = QtGui.QFont() self.fontss.setBold(True) self.fontss.setUnderline(True) self.leftlist = QtWidgets.QComboBox() # self.leftlist.insertItem(0, 'Plots') self.leftlist.addItem('Spectral Fitting') self.leftlist.addItem('NEQAIR Input') self.leftlist.setMaximumWidth(500) self.stack1 = QWidget() self.stack1.setMinimumSize(768,432) self.stack2 = QWidget() self.stack2.setMaximumWidth(500) self.stack3 = QWidget() self.stack3.setMaximumWidth(500) self.stack1UI() self.stack2UI() self.stack3UI() self.Stack = QStackedWidget(self) # self.Stack.addWidget(self.stack1) self.Stack.addWidget(self.stack2) self.Stack.addWidget(self.stack3) gbox = QtWidgets.QGridLayout(self) gbox.addWidget(self.leftlist, 0, 0) gbox.addWidget(self.Stack, 1,0) gbox.addWidget(self.stack1,0,1,2,2) self.setLayout(gbox) self.leftlist.currentIndexChanged.connect(self.display) self.show() def stack1UI(self): # THE PLOTTING CAPABILITY # figure painting from matplot self.figure = plt.figure() self.canvas = FigureCanvas(self.figure) # toolbar addition self.toolbar = NavigationToolbar(self.canvas, self) self.toolbar.show() # some buttons for functionality self.button = QPushButton('ReadPlot') self.button.clicked.connect(self.readplot) self.colchange1 = QtWidgets.QComboBox() self.colchange1.currentIndexChanged.connect(self.newplot) # make new plot function self.colchange2 = QtWidgets.QComboBox() self.colchange2.currentIndexChanged.connect(self.newplot) # make new plot function self.button2 = QPushButton('ClearPlot') self.button2.clicked.connect(self.figure.clear) layout = QtWidgets.QVBoxLayout() glayout = QGridLayout() layout.addWidget(self.toolbar) layout.addWidget(self.canvas) glayout.addWidget(self.button,0,0) glayout.addWidget(self.button2,0,1) glayout.addWidget(self.colchange1,1,0) glayout.addWidget(self.colchange2,1,1) layout.addLayout(glayout) self.stack1.setLayout(layout) def stack2UI(self): # THE LOS DATA CAPABILITY self.los = {} los_tmp = np.empty(shape=(1, 1), dtype=object) self.stack2.masterlayout = QtWidgets.QGridLayout() formGroupBox1 = QGroupBox("Temperatures") layout1 = QtWidgets.QFormLayout() los_tmp[0, 0] = QLineEdit("0.0", self) los_tmp[0, 0].setValidator(QtGui.QDoubleValidator()) layout1.addRow(QLabel("Translational:"), los_tmp[0, 0]) self.los['Temperature'] = los_tmp[0, 0] layout1.addRow(QLabel("Vibrational:"), QLineEdit()) layout1.addRow(QLabel("Two-Temp?:"), QCheckBox()) formGroupBox1.setLayout(layout1) formGroupBox2 = QGroupBox("Spectrum Species") layout2 = QFormLayout() self.losnumbox= QSpinBox(self) self.losnumbox.setValue(2) self.los['SpecNum'] = self.losnumbox self.losnumbox.valueChanged.connect(self.loschange) layout2.addRow(QLabel("Number of Species:"),self.losnumbox) allspec = ["N", "O", "C", "H", "He", "Ar", "Fe", "Al", "Cr", "Cu", "K", "Mg", "Na", "Ni", "S", "Si", "N2", "N2+", "NO", "O2", "CN", "CO", "C2", "H2", "NH", "CH", "CO2", "C3", "MgO", "SiO" ] self.mylinedit = QtWidgets.QLineEdit("0.0") los_tmp = np.empty(shape=(self.losnumbox.value(), 2), dtype=object) for i in range(self.losnumbox.value()): # create default number of tables for j in range(2): if j == 0: los_tmp[i, j] = QtWidgets.QComboBox() los_tmp[i, j].addItems(allspec[:]) layout2.addRow(QLabel("Species "+str(i+1)), los_tmp[i, j]) if j == 1: los_tmp[i, j] = QtWidgets.QLineEdit("0.0", self) los_tmp[i, j].setValidator(QtGui.QDoubleValidator()) layout2.addRow(QLabel("Number Density "+str(i+1)), los_tmp[i, j]) formGroupBox2.setLayout(layout2) self.los['Species'] = los_tmp formGroupBox3 = QtWidgets.QGroupBox("Ranges") layout3 = QFormLayout() los_tmp = np.empty(shape=(3, 1), dtype=object) for i in range(len(los_tmp)): los_tmp[i, 0] = QLineEdit("0.0", self) los_tmp[i, 0].setValidator(QtGui.QDoubleValidator()) self.simplexbutton = QPushButton("Execute Order 66") self.simplexbutton.pressed.connect(self.simplex) layout3.addRow(QLabel("Max Iter: "), los_tmp[0, 0]) layout3.addRow(QLabel("Max FuncEval:"), los_tmp[1, 0]) layout3.addRow(QLabel("Tolerance :"), los_tmp[2, 0]) layout3.addRow(QLabel("Start Optimization"),self.simplexbutton) self.los['Fitting'] = los_tmp formGroupBox3.setLayout(layout3) self.stack2.masterlayout.addWidget(formGroupBox1, 0, 0) self.stack2.masterlayout.addWidget(formGroupBox2, 0, 1) self.stack2.masterlayout.addWidget(formGroupBox3, 1, 0, 1, 2) self.stack2.setLayout(self.stack2.masterlayout) del los_tmp def simplex(self): # self.simplexbutton.setEnabled(0) self.simplexbutton.setText("Please Wait") command = "ls" process=QProcess(self) process.finished.connect(self.reenableSimplex) process.startDetached(command) print("kerzappo!") for i in range(len(self.los['Fitting'])): print(self.los['Fitting'][i, 0].text()) def reenableSimplex(self): self.simplexbutton.setText("Start Optimization") def stack3UI(self): # THE NEQAIR MODEL INPUT CAPABILITY # TABS--------------------------------- self.il2info = ["(I)ntensity.out", "Intensity_(S)canned.out", "(L)OS.out", "(P)opulation", "(A)bsorbance/Emittance", "(C)oupling.out", "(M) stdout"] self.il3info = ["(B) Boltzmann", "(N) Non-Boltzmann", "(Q) Traditional QSS ", "(T) Time derivative limited", "(R) Reaction residual limited ", "(F) Flux limited", "(C) Constant escape factor", "(L) Local Escape factor", "(F) Full local calculation", "(N) Non-local coupling", "(S) Saha", "(F) Input from File", "(A) absorption/emission coefficients from File"] self.il4info = ["(T) Tangent Slab", "(C) Spherical Cap", "(S) Shock Tube", "(L) Line of Sight", "(B) Blackbody", "(P) Calculate Populations", "(X) Perform scan on existing intensity.out"] self.il5info = ["(B) Blackbody", "(I) read Intensity.in", "(N) no initial radiance", "(I) read emissivity.in", "(G) Greybody", "(B) Blackbody"] self.il6info = ["WL1", "WL2", "A", "M", "Delta", "R", "dd"] self.il7info = ["ICCD1", "ICCD2", "Voigt", "Gauss"] # create the dictionaries to place the widgets within for each tab. self.il = {} self.layout3 = QtWidgets.QVBoxLayout(self) self.tabs = QtWidgets.QTabWidget() # create the tabs self.tab1 = QWidget() self.tab2 = QWidget() self.tab3 = QWidget() self.tab4 = QWidget() self.tab5 = QWidget() self.tab6 = QWidget() self.tabs.addTab(self.tab1, "Outputs and Calc-style") # Add tabs self.tabs.addTab(self.tab2, "Species Information") self.tabs.addTab(self.tab3, "Geometry \& Boundary Conditions") self.tabs.addTab(self.tab4, "Regions") self.tabs.addTab(self.tab5, "Scan Style") self.tabs.addTab(self.tab6, "Spatial Scan") self.tabs.setMovable(True) # Create first tab - Generic File information(sim type and such) self.tab1.masterlayout = QGridLayout() self.tab1.layout1 = QGridLayout() self.tab1.group1 = QtWidgets.QGroupBox("File Output(s)") self.tab1.layout2 = QGridLayout() self.tab1.group2 = QtWidgets.QGroupBox("Calculation Method") tmp_arr = np.empty(shape=(len(self.il2info), 2), dtype=object) for i in range(7): # INPUT LINE 2 tmp_arr[i, 0] = QtWidgets.QCheckBox(self.il2info[i], self) self.tab1.layout1.addWidget(tmp_arr[i, 0], i+1, 0) if "(I)" in self.il2info[i] or "(S)" in self.il2info[i]: tmp_arr[i, 1] = QtWidgets.QCheckBox("(2)Column Format?", self) self.tab1.layout1.addWidget(tmp_arr[i, 1], i+1, 2) self.il['Line2'] = tmp_arr # Creates the OutPut type dictionary section self.tab1.group1.setLayout(self.tab1.layout1) print("created FileOutput") tmp_arr = np.empty(shape=(5, 4), dtype=object) for i in range(5): # INPUT LINE 3 if i < 2: tmp_arr[i, 0] = QtWidgets.QCheckBox(self.il3info[i], self) self.tab1.layout2.addWidget(tmp_arr[i, 0], i+1, 0) if "Non-B" in self.il3info[i]: # Filling the combo boxes out and adding to dict tmp_arr[i, 1] = QtWidgets.QComboBox() tmp_arr[i, 1].addItem("--optional--") tmp_arr[i, 1].addItems(self.il3info[2:5]) tmp_arr[i, 2] = QtWidgets.QComboBox() tmp_arr[i, 2].addItems(self.il3info[6:10]) self.tab1.layout2.addWidget(tmp_arr[i, 1], i+1, 2) self.tab1.layout2.addWidget(tmp_arr[i, 2], i+1, 3) tmp_arr[i ,3] = QtWidgets.QLineEdit("0.0",self) tmp_arr[i, 3].setMaximumWidth(50) tmp_arr[i, 3].setValidator(QtGui.QDoubleValidator()) self.tab1.layout2.addWidget(tmp_arr[i, 3], i+1, 4) if i >= 2: tmp_arr[i, 0]= QtWidgets.QCheckBox(self.il3info[i+8], self) self.tab1.layout2.addWidget(tmp_arr[i, 0], i+1, 0) self.tab1.group2.setLayout(self.tab1.layout2) self.tab1.masterlayout.addWidget(self.tab1.group1, 0, 0) self.tab1.masterlayout.addWidget(self.tab1.group2, 1, 0) self.tab1.setLayout(self.tab1.masterlayout) self.il['Line3'] = tmp_arr # creates the State Pop Method Dictionary section print("created State Population") self.il['Line3'][1, 2].setCurrentIndex(2) self.il['Line3'][1, 2].currentIndexChanged.connect(self.combofloat) #self.il['Line2'][1, 0].clicked.connect(self.tabshow) # ---- Create second tab self.tab2.layout3 = QGridLayout() self.losopen = QPushButton("Read LOS") self.losopen.clicked.connect(self.ReadLOS) # define the button's functionality self.tab2.layout3.addWidget(self.losopen, 0, 0) self.tab2.setLayout(self.tab2.layout3) # ---- Create third tab self.tab3.masterlayout = QGridLayout() self.tab3.group1 = QGroupBox("Geometry") self.tab3.layout1mod = QVBoxLayout() self.tab3.layout1 = QGridLayout() tmp_arr = np.empty(shape=(len(self.il4info), 3), dtype=object) for i in range(len(self.il4info)): # INPUT LINE 4 tmp_arr[i, 0] = QtWidgets.QCheckBox(self.il4info[i], self) self.tab3.layout1.addWidget(tmp_arr[i, 0], i, 0, 1, 1) if "(C)" in self.il4info[i]: tmp_arr[i, 1] = QtWidgets.QLineEdit("0.0", self) tmp_arr[i, 2] = QtWidgets.QLineEdit("0.0", self) tmp_arr[i, 1].setMaximumWidth(50) tmp_arr[i, 2].setMaximumWidth(50) self.tab3.layout1.addWidget(tmp_arr[i, 1], i, 1, 1, 1) self.tab3.layout1.addWidget(tmp_arr[i, 2], i, 2, 1, 1) if "(S)" in self.il4info[i]: tmp_arr[i, 1] = QtWidgets.QLineEdit("0.0", self) tmp_arr[i, 1].setMaximumWidth(50) self.tab3.layout1.addWidget(tmp_arr[i, 1], i, 1, 1, 1) if "(B)" in self.il4info[i]: tmp_arr[i, 1] = QtWidgets.QLineEdit("0.0", self) tmp_arr[i, 1].setMaximumWidth(50) self.tab3.layout1.addWidget(tmp_arr[i, 1], i, 1, 1, 1) self.il['Line4'] = tmp_arr # creates the Geometry Section of the dictionary tmp_arr = np.empty(shape=(len(self.il5info), 3), dtype=object) self.tab3.group1.setLayout(self.tab3.layout1) self.tab3.group2 = QGroupBox("Boundary Conditions") self.tab3.group2grid = QGridLayout() self.tab3.group2_1 = QGroupBox("Initial Point") self.tab3.group2_2 = QGroupBox("Final Point") self.tab3.layout2 = QGridLayout() for i in range(len(self.il5info[0:3])): # INPUT LINE 5 tmp_arr[i, 0] = QtWidgets.QCheckBox(self.il5info[i], self) self.tab3.layout2.addWidget(tmp_arr[i, 0], i, 0) self.tab3.group2_1.setLayout(self.tab3.layout2) self.tab3.layout3 = QGridLayout() for i in range(3): # INPUT LINE 5 tmp_arr[i+3, 0] = QtWidgets.QCheckBox(self.il5info[i+3], self) self.tab3.layout3.addWidget(tmp_arr[i+3, 0], i, 0) if "(G)" in self.il5info[i+3]: tmp_arr[i+3, 1] = QtWidgets.QLineEdit("0.0", self) tmp_arr[i+3, 1].setMaximumWidth(50) tmp_arr[i+3, 2] = QtWidgets.QLineEdit("0.0", self) tmp_arr[i+3, 2].setMaximumWidth(50) self.tab3.layout3.addWidget(tmp_arr[i+3, 1], i, 1, 1, 1) self.tab3.layout3.addWidget(tmp_arr[i+3, 2], i, 2, 1, 1) self.tab3.group2_2.setLayout(self.tab3.layout3) self.tab3.group2grid.addWidget(self.tab3.group2_1, 0 , 0) self.tab3.group2grid.addWidget(self.tab3.group2_2, 1 , 0) self.tab3.group2.setLayout(self.tab3.group2grid) self.il['Line5'] = tmp_arr # creates the Boundary Condition section of the dictionary self.tab3.masterlayout.addWidget(self.tab3.group1, 0, 0) self.tab3.masterlayout.addWidget(self.tab3.group2, 0, 1) self.tab3.setLayout(self.tab3.masterlayout) print("created Boundary/Geometry") # ---- Create fourth tab self.tab4.masterlayout = QVBoxLayout() self.tab4.layout1 = QFormLayout() self.regionbox = QSpinBox(self) self.regionbox.setValue(4) self.regionbox.valueChanged.connect(self.regionchange) self.tab4.layout1.addRow(QLabel("Number of Regions"),self.regionbox) self.tab4.layout3 = QGridLayout() self.tab4.legend2 = QLabel("Min Lambda") self.tab4.legend3 = QLabel("Max Lambda") self.tab4.legend4 = QLabel("Grid Spacing") self.tab4.legend5 = QLabel("Delta") self.tab4.legend6 = QLabel("Range?") self.tab4.legend7 = QLabel("Range Value") self.tab4.legend2.setFont(self.fontss) self.tab4.legend3.setFont(self.fontss) self.tab4.legend4.setFont(self.fontss) self.tab4.legend5.setFont(self.fontss) self.tab4.legend6.setFont(self.fontss) self.tab4.legend7.setFont(self.fontss) self.tab4.layout3.addWidget(self.tab4.legend2, 0, 0, QtCore.Qt.AlignCenter) self.tab4.layout3.addWidget(self.tab4.legend3, 0, 1, QtCore.Qt.AlignCenter) self.tab4.layout3.addWidget(self.tab4.legend4, 0, 2, QtCore.Qt.AlignCenter) self.tab4.layout3.addWidget(self.tab4.legend5, 0, 3, QtCore.Qt.AlignCenter) self.tab4.layout3.addWidget(self.tab4.legend6, 0, 4, QtCore.Qt.AlignCenter) self.tab4.layout3.addWidget(self.tab4.legend7, 0, 5, QtCore.Qt.AlignCenter) self.tab4.layout4 = QGridLayout() tmp_arr = np.empty(shape=(self.regionbox.value(), 6), dtype=object) for i in range(self.regionbox.value()): # create default number of tables for j in range(6): if j<2 or j == 3 or j == 5: tmp_arr[i, j] = QtWidgets.QLineEdit("0.0", self) tmp_arr[i, j].setMaximumWidth(100) tmp_arr[i, j].setValidator(QtGui.QDoubleValidator()) self.tab4.layout4.addWidget(tmp_arr[i, j], i+1, j) if j == 2: tmp_arr[i, j] = QtWidgets.QComboBox() tmp_arr[i, j].addItems(self.il6info[2:4]) self.tab4.layout4.addWidget(tmp_arr[i, j], i+1, j) if j == 4: tmp_arr[i, j] = QtWidgets.QCheckBox("R", self) self.tab4.layout4.addWidget(tmp_arr[i, j], i+1, j) self.il['Line7'] = tmp_arr # creates the Regions section of the dictionary self.tab4.masterlayout.addLayout(self.tab4.layout1) self.tab4.masterlayout.addLayout(self.tab4.layout3) self.tab4.masterlayout.addLayout(self.tab4.layout4) self.tab4.setLayout(self.tab4.masterlayout) print("created Regions") # ---- Creates fifth tab self.tab5.masterlayout = QVBoxLayout() self.tab5.layout1 = QGridLayout() self.tab5.legend1 = QLabel("Spacing") self.tab5.legend2 = QLabel("Type") self.tab5.legend3 = QLabel("Param1") self.tab5.legend4 = QLabel("Param2") self.tab5.legend5 = QLabel("Param3") self.tab5.legend1.setFont(self.fontss) self.tab5.legend2.setFont(self.fontss) self.tab5.legend3.setFont(self.fontss) self.tab5.legend4.setFont(self.fontss) self.tab5.legend5.setFont(self.fontss) self.tab5.layout1.addWidget(self.tab5.legend1, 0, 0, QtCore.Qt.AlignCenter) self.tab5.layout1.addWidget(self.tab5.legend2, 0, 1, QtCore.Qt.AlignCenter) self.tab5.layout1.addWidget(self.tab5.legend3, 0, 2, QtCore.Qt.AlignCenter) self.tab5.layout1.addWidget(self.tab5.legend4, 0, 3, QtCore.Qt.AlignCenter) self.tab5.layout1.addWidget(self.tab5.legend5, 0, 4, QtCore.Qt.AlignCenter) self.tab5.layout2 = QGridLayout() tmp_arr1 = np.empty(shape=(self.regionbox.value(), 5), dtype=object) for i in range(self.regionbox.value()): # create default number of tables...too tmp_arr1[i, 0] = QtWidgets.QLineEdit("0.0", self) tmp_arr1[i, 0].setValidator(QtGui.QDoubleValidator()) self.tab5.layout2.addWidget(tmp_arr1[i, 0], i+1, 0) tmp_arr1[i, 1] = QtWidgets.QComboBox() tmp_arr1[i, 1].setMaximumWidth(100) tmp_arr1[i, 1].addItems(self.il7info[:]) self.tab5.layout2.addWidget(tmp_arr1[i, 1], i+1, 1) for j in range(3): tmp_arr1[i, j+2] = QtWidgets.QLineEdit("0.0", self) tmp_arr1[i, j+2].setValidator(QtGui.QDoubleValidator()) self.tab5.layout2.addWidget(tmp_arr1[i, j+2], i+1, j+2) for i in range(self.regionbox.value()): for j in range(5): tmp_arr1[i, j].setMaximumWidth(100) self.il['Line8'] = tmp_arr1 # creates the Scan portion of the dictionary. only required for shock tube self.tab5.masterlayout.addLayout(self.tab5.layout1) self.tab5.masterlayout.addLayout(self.tab5.layout2) self.tab5.layout1.setSpacing(0) self.tab5.setLayout(self.tab5.masterlayout) print("created Scan") # ---- Creates sixth tab self.tab6.masterlayout = QVBoxLayout() self.tab6.layout1 = QGridLayout() self.tab6.legend11 = QLabel("Slit Profile") self.tab6.legend12= QLabel("Base1") self.tab6.legend13 = QLabel("Base2 (Trapezoid)") self.tab6.legend11.setFont(self.fontss) self.tab6.legend12.setFont(self.fontss) self.tab6.legend13.setFont(self.fontss) self.tab6.layout1.addWidget(self.tab6.legend11, 0, 0, QtCore.Qt.AlignCenter) self.tab6.layout1.addWidget(self.tab6.legend12, 0, 1, QtCore.Qt.AlignCenter) self.tab6.layout1.addWidget(self.tab6.legend13, 0, 2, QtCore.Qt.AlignCenter) self.tab6.layout2 = QGridLayout() tmp_arr1 = np.empty(shape=(self.regionbox.value(), 3), dtype=object) tmp_arr1[0, 0] = QtWidgets.QComboBox() tmp_arr1[0, 0].addItem('triangle') tmp_arr1[0, 0].addItem('trapezoid') self.tab6.layout2.addWidget(tmp_arr1[0, 0], 0, 0) tmp_arr1[0, 1] = QtWidgets.QLineEdit("0.0", self) tmp_arr1[0, 1].setValidator(QtGui.QDoubleValidator()) self.tab6.layout2.addWidget(tmp_arr1[0, 1], 0, 1) tmp_arr1[0, 2] = QtWidgets.QLineEdit("0.0", self) tmp_arr1[0, 2].setValidator(QtGui.QDoubleValidator()) self.tab6.layout2.addWidget(tmp_arr1[0, 2], 0, 2) self.tab6.layout3 = QGridLayout() self.tab6.legend31 = QLabel("Line Type") self.tab6.legend32 = QLabel("Param1") self.tab6.legend33 = QLabel("Param2") self.tab6.legend31.setFont(self.fontss) self.tab6.legend32.setFont(self.fontss) self.tab6.legend33.setFont(self.fontss) self.tab6.layout3.addWidget(self.tab6.legend31, 0, 0, QtCore.Qt.AlignCenter) self.tab6.layout3.addWidget(self.tab6.legend32, 0, 1, QtCore.Qt.AlignCenter) self.tab6.layout3.addWidget(self.tab6.legend33, 0, 2, QtCore.Qt.AlignCenter) self.tab6.layout4 = QGridLayout() tmp_arr1[1, 0] = QtWidgets.QComboBox() tmp_arr1[1, 0].addItems(self.il7info[:]) self.tab6.layout4.addWidget(tmp_arr1[1, 0], 1, 0) tmp_arr1[1, 1] = QtWidgets.QLineEdit("0.0", self) tmp_arr1[1, 1].setValidator(QtGui.QDoubleValidator()) self.tab6.layout4.addWidget(tmp_arr1[1, 1], 1, 1) tmp_arr1[1, 2] = QtWidgets.QLineEdit("0.0", self) tmp_arr1[1, 2].setValidator(QtGui.QDoubleValidator()) self.tab6.layout4.addWidget(tmp_arr1[1, 2], 1, 2) self.tab6.layout5 = QGridLayout() self.tab6.legend51 = QLabel("Temporal Width") self.tab6.legend51.setFont(self.fontss) self.tab6.layout5.addWidget(self.tab6.legend51, 0, 0, QtCore.Qt.AlignCenter) self.tab6.layout6 = QGridLayout() tmp_arr1[2, 0] = QtWidgets.QLineEdit("0.0", self) tmp_arr1[2, 0].setValidator(QtGui.QDoubleValidator()) self.tab6.layout6.addWidget(tmp_arr1[2, 0], 2, 0) self.il['Line9'] = tmp_arr1 # creates the Scan portion of the dictionary. only required for shock tube self.tab6.masterlayout.addLayout(self.tab6.layout1) self.tab6.masterlayout.addLayout(self.tab6.layout2) self.tab6.masterlayout.addLayout(self.tab6.layout3) self.tab6.masterlayout.addLayout(self.tab6.layout4) self.tab6.masterlayout.addLayout(self.tab6.layout5) self.tab6.masterlayout.addLayout(self.tab6.layout6) self.tab6.setLayout(self.tab6.masterlayout) print("created Spatial Scan") # Add tabs to widget self.layout3.addWidget(self.tabs) self.stack3.setLayout(self.layout3) del tmp_arr, tmp_arr1 # FUNCTIONS------------------------------------------------- def readplot(self): # OPENING AND READING FIGURE IN self.colchange1.clear() # clear the previous plot datas entires self.colchange2.clear() # clear the previous plot datas entires datafile, __ = QFileDialog.getOpenFileName(self, "Open File", "", "All Files(*)") if datafile: datafile = str(datafile) try: self.plotfile =np.genfromtxt(datafile, comments='#', skip_header=3, names=True, unpack=True, autostrip=True) sax = self.figure.add_subplot(111) # adds figure as a subplot. might be nice to use this to allow user to plot multiple things. sax.plot(self.plotfile[self.plotfile.dtype.names[0]], self.plotfile[self.plotfile.dtype.names[1]], '*-') # need controls for one vs. another self.colchange1.addItems(self.plotfile.dtype.names[:]) self.colchange2.addItems(self.plotfile.dtype.names[:]) self.canvas.draw() except: self.plotfile =np.genfromtxt(datafile, dtype=float, comments="(", skip_header=1, names=True, unpack=True) sax = self.figure.add_subplot(111) # adds figure as a subplot. might be nice to use this to allow user to plot multiple things. sax.plot(self.plotfile[self.plotfile.dtype.names[0]], self.plotfile[self.plotfile.dtype.names[1]], '*-') # need controls for one vs. another self.colchange1.addItems(self.plotfile.dtype.names[:]) self.colchange2.addItems(self.plotfile.dtype.names[:]) self.canvas.draw() def newplot(self): self.figure.clf() sax = self.figure.add_subplot(111) # adds figure as a subplot. might be nice to use this to allow user to plot multiple things. i1 = self.colchange1.currentIndex() i2 = self.colchange2.currentIndex() sax.plot(self.plotfile[self.plotfile.dtype.names[i1]], self.plotfile[self.plotfile.dtype.names[i2]], '*-') self.canvas.draw() def checkSpecies(self): name, __ = QFileDialog.getOpenFileName(self, "Open File", "", "All Files(*)") if name: m_input = {} print("Checking Molecule List:", name) input_text = open(name).readlines() e = len(input_text) j = 0 while j != e: if "***" in input_text[j]: if "U" in input_text[j+1]: mols = input_text[j+2].split()[0:2] m_input.setdefault(mols[0],[]) m_input[mols[0]].append(mols[1]) j+=1 return m_input def ReadLOS(self): # OPENING LOS.DAT FILE TO READ COLUMN HEADERS self.m = self.checkSpecies() for key, value in self.m.items(): print ("have :",key, value) self.aband = ["bb", "bf", "ff"] self.n2band = ["1+", "2+", "BH2", "LBH", "BH1", "WJ", "CY"] self.o2band = ["SR"] self.noband = ["beta", "gam", "del", "eps", "bp", "gp", "IR"] datafile, __ = QFileDialog.getOpenFileName(self, "Open File", "", "All Files(*)") if datafile: print("Opening LOS File:", datafile) datafile = str(datafile) spectrum =np.genfromtxt(datafile, dtype=None, skip_header=21, names=True) self.spec = spectrum.dtype.names[7:-1] # omitting all of the n, n_total stuff self.spec = [w.replace('_1', '+') for w in self.spec] # erasing the nasty characters and replacing with user-identifiables self.spec.sort() # sort the list # This next little piece of code is dumb and inefficient, should replace with something more elegant xcount = 0 for i in range(len(self.spec)): if "+" not in self.spec[i]: xcount += 1 self.speclist = [None]*xcount k = 0 for i in range(len(self.spec)): if "+" not in self.spec[i]: self.speclist[k] = self.spec[i] k += 1 # End bad section self.allcheck = QtWidgets.QCheckBox() self.allcheck.clicked.connect(self.checkemalll) self.tab2.layout3.addWidget(self.allcheck, 0, 1) self.tab2.layout3.addWidget(QLabel("Check All Bands"), 0, 2, 1, 7, QtCore.Qt.AlignLeft) tmp_arrb = [None]*len(self.speclist) tmp_arrcb = np.empty(shape=(xcount, len(self.n2band)), dtype=object) for i in range(len(self.speclist)): tmp_arrb[i] = QPushButton(self.speclist[i], self) tmp_arrb[i].setCheckable(True) self.tab2.layout3.addWidget(tmp_arrb[i], i+1, 0) try: if self.m[str(self.speclist[i])] is not None and "+" not in self.speclist[i]: for j in range(len(self.m[str(self.speclist[i])])): tmp_arrcb[i, j] = QtWidgets.QCheckBox(self.m[str(self.speclist[i])][j]) self.tab2.layout3.addWidget(tmp_arrcb[i, j], i+1, j*2+1) except: if len(self.speclist[i]) == 1: for j in range(3): # making specific bands for atoms(bf, bb, ff) tmp_arrcb[i, j] = QtWidgets.QCheckBox(self.aband[j]) self.tab2.layout3.addWidget(tmp_arrcb[i, j], i+1, j*2+1) self.il['Line6'] = tmp_arrb # The press buttons for each species self.il['Line6CB'] = tmp_arrcb # the check buttons for each species def loschange(self): print("my value chaanged!") def regionchange(self): count = self.regionbox.value() # tables want clayout = int((self.tab4.layout4.count())/6) # tables have(includes spinbox) print("count is: ", count, "clayout is: ", clayout) if count < clayout: for k in range(6): self.il['Line7'][clayout-1, k] = None # the spacing is offset from that array loc by 1 regionToRemove = self.tab4.layout4.itemAtPosition(clayout, k).widget() regionToRemove.setParent(None) self.tab4.layout4.removeWidget(regionToRemove) for kk in range(5): self.il['Line8'][clayout-1, kk] = None lineToRemove = self.tab5.layout2.itemAtPosition(clayout, kk).widget() lineToRemove.setParent(None) self.tab5.layout2.removeWidget(lineToRemove) elif count > clayout: self.il['Line7'] = np.resize(self.il['Line7'], [count, len(self.il6info)-1]) # resize the array to the count size with corresponding list length for j in range(6): if j<2 or j == 3 or j == 5: self.il['Line7'][count-1, j] = QtWidgets.QLineEdit("0.0", self) self.il['Line7'][count-1, j].setMaximumWidth(100) self.il['Line7'][count-1, j].setValidator(QtGui.QDoubleValidator()) self.tab4.layout4.addWidget(self.il['Line7'][count-1, j], count, j) if j == 2: self.il['Line7'][count-1, j] = QtWidgets.QComboBox() self.il['Line7'][count-1, j].setMaximumWidth(100) self.il['Line7'][count-1, j].addItems(self.il6info[2:4]) self.tab4.layout4.addWidget(self.il['Line7'][count-1, j], count, j) if j == 4: self.il['Line7'][count-1, j] = QtWidgets.QCheckBox("R", self) self.tab4.layout4.addWidget(self.il['Line7'][count-1, j], count, j) self.tab4.setLayout(self.tab4.masterlayout) self.il['Line8'] = np.resize(self.il['Line8'], [count, 5]) self.il['Line8'][count-1, 0] = QtWidgets.QLineEdit("0.0", self) self.il['Line8'][count-1, 0].setMaximumWidth(100) self.il['Line8'][count-1, 0].setValidator(QtGui.QDoubleValidator()) self.tab5.layout2.addWidget(self.il['Line8'][count-1, 0], count, 0) self.il['Line8'][count-1, 1] = QtWidgets.QComboBox() self.il['Line8'][count-1, 1].setMaximumWidth(100) self.il['Line8'][count-1, 1].addItems(self.il7info[:]) self.tab5.layout2.addWidget(self.il['Line8'][count-1, 1], count, 1) for j in range(3): self.il['Line8'][count-1, j+2] = QtWidgets.QLineEdit("0.0", self) self.il['Line8'][count-1, j+2].setMaximumWidth(100) self.il['Line8'][count-1, j+2].setValidator(QtGui.QDoubleValidator()) self.tab5.layout2.addWidget(self.il['Line8'][count-1, j+2], count, j+2) self.tab5.setLayout(self.tab5.masterlayout) def checkemalll(self): if self.allcheck.isChecked(): for i in range(len(self.speclist)): self.il['Line6'][i].setChecked(True) for j in range(len(self.n2band)): if hasattr(self.il['Line6CB'][i, j], 'setChecked'): self.il['Line6CB'][i, j].setChecked(True) def clearplot(self): self.figure.close() self.canvas.draw() def display(self, i): self.Stack.setCurrentIndex(i) def combofloat(self): if self.il['Line3'][1, 2].currentIndex() <= (self.il['Line3'][1, 2].count() - 2): self.il['Line3'][1, 3].show() else: self.il['Line3'][1, 3].hide() def main(): app = QApplication(sys.argv) ex = Window() ex.setWindowTitle('NeQtPy v0.1') sys.exit(app.exec_()) if __name__ == '__main__': main()
# Libraries import time import allFunctionFiles # all function required imported # serial setup port = "/dev/ttyUSB1" baud = 9600 ser = serial.Serial(port, baud, timeout=None) # Initializing Variables obstacle_list = [] # List storing locations(node numbers) of obstacles turn_cost_90 = 510 # Turn cost used for a* algorithm, obtained by measuring time it takes for bot to turn turn_cost_180 = 700 cell_to_cell_cost = 200 # Cost for movement from cell to cell, used for a* algorithm init_start_node = 0 init_end_node = 26 init_direction = 'N' final_deposition_node = 0 # Deposition Zones for different fruits given as Node numbers depostion_zone_apple = [37, 38, 44, 45] depostion_zone_bberry = [35, 36, 42, 43] depostion_zone_orange = [40, 41, 47, 48] # Required Fruits Table apple_dict = {'L': 1, 'M': 1, 'S': 1} blue_dict = {'L': 1, 'M': 1, 'S': 1} orange_dict = {'L': 0, 'M': 2, 'S': 0} # Tree locations of the fruits tree_location_1 = 9 tree_location_2 = 29 tree_location_3 = 18 # Shortest Node to DZ, used in a* algorithm shortest_node_to_dep = 0 # nodes on which bot can travel travesable_nodes = [ 42, 43, 44, 45, 46, 47, 48, 35, 36, 37, 38, 39, 40, 41, 28, 29, 30, 31, 32, 33, 34, 21, 22, 23, 24, 25, 26, 27, 14, 15, 16, 17, 18, 19, 20, 07, 8, 9, 10, 11, 12, 13, 00, 01, 02, 03, 04, 05, 06, ] # Stores character values needed to be sent for each command. Same is mapped in bot code. # for example if forward command is required, 'n' is sent to the bot serially and accordingly the bot moves ahead. command_dict = { 'forward': 'n', 'reverse': 's', 'right-forward': 'r', 'left-forward': 'l', 'turn-180': 't', 'angle_right': 'f', 'angle_left': 'g', 'left': 'e', 'right': 'w', 'turn-180-left': 'A', 'turn-180-right': 'D', 'buzzer-on': ',', 'buzzer-off': '.', 'stop': 'e' } # ------------------------------------------------------------------- # initializeArms() # Remove tree locations from traversable nodes travesable_nodes.remove(tree_location_1) travesable_nodes.remove(tree_location_2) travesable_nodes.remove(tree_location_3) # Get fruit positions for each tree fruit_postion_1 = getNeighbouringNodes(tree_location_1) fruit_postion_2 = getNeighbouringNodes(tree_location_2) fruit_postion_3 = getNeighbouringNodes(tree_location_3) print '' # There are total of 12 bot movements since there are 3 trees and max number of fruits on 1 tree can be 4 # hence total bot movements will be 3 * 4 = 12 which includes picking up and dropping fruits # Bot has to travel to all fruit locations fruit_trav_location = fruit_postion_1 + fruit_postion_2 + fruit_postion_3 # bot movements from 1 - 2 # ---------------------------------------------------------------------------------------------------------------------# # Determine shortest node from w.r.t current position temp = 1000 shortest_node = 0 for value in fruit_trav_location: distance = node_distance(init_start_node, value) if distance < temp: temp = distance shortest_node = value fruit_trav_location.remove(shortest_node) # Find Path using a* algorithm print init_start_node, " --> ", shortest_node cost, pickup_node, directions, face = a_star_search(init_start_node, shortest_node, travesable_nodes, init_direction) # Check which tree the bot has arrived if shortest_node in fruit_postion_1: dest = tree_location_1 deposition_node = depostion_zone_apple elif shortest_node in fruit_postion_2: dest = tree_location_2 deposition_node = depostion_zone_bberry else: dest = tree_location_3 deposition_node = depostion_zone_orange # If not facing the tree, make the bot turn tree_facing_turn, tree_facing_dir = turn_4_tree(face, pickup_node, dest) if not tree_facing_turn == 'forward': directions.append(tree_facing_turn) face = tree_facing_dir # Change node to reach one location before destination : This is implemented because it's easier to detect fruits on # trees if the bot arrives at the tree from the facing direction. If it arrives from Left or Right, it has to turn # and might not allign with the tree as expected. Hence if it can arrive from the facing direction compute shortest # path w.r.t that node. shortest_node, changeNode = nodeBeforeShotestNode(shortest_node, face) # If possible then calculate again if changeNode: print init_start_node, " --> ", shortest_node cost, pickup_node, directions, face = a_star_search(init_start_node, shortest_node, travesable_nodes, init_direction) if shortest_node in fruit_postion_1: dest = tree_location_1 deposition_node = depostion_zone_apple elif shortest_node in fruit_postion_2: dest = tree_location_2 deposition_node = depostion_zone_bberry else: dest = tree_location_3 deposition_node = depostion_zone_orange tree_facing_turn, tree_facing_dir = turn_4_tree(face, pickup_node, dest) if not tree_facing_turn == 'forward': directions.append(tree_facing_turn) face = tree_facing_dir print "Track 0 :", directions print 'final facing direction : ', face print '' # update the inital direction for next path findings init_direction = face # Send commands to Bot for detected_value in directions: if detected_value in command_dict.keys(): sendCommand(command_dict[detected_value]) waitForResponse() if changeNode: sendCommand('forward') # Start Fruit detection detected_fruit, det_fruit_size = img_detect_4_pi.image_processing() # Chedk if required Fruit is to be plucked or Not check_to_pluck = Eliminator(detected_fruit, det_fruit_size) pluckOrNot(check_to_pluck) if check_to_pluck: if init_direction == 'N': init_direction = 'S' elif init_direction == 'W': init_direction = 'E' elif init_direction == 'S': init_direction = 'N' else: init_direction = 'W' # ---------------------------------------------------------------------------------------------------------------------# # If fruit Plucked go to DZ or else go to next shortest tree location # Exectue only if the fruit is plucked or else skip this path and compute path to next fruit location if check_to_pluck: temp_dep = 1000 shortest_node_dep = 0 for value in deposition_node: distance = node_distance(shortest_node, value) if distance < temp_dep: temp_dep = distance shortest_node_to_dep = value print shortest_node, " --> ", shortest_node_to_dep cost0, pickup_node0, directions0, face0 = a_star_search(shortest_node, shortest_node_to_dep, travesable_nodes, init_direction) print 'face0 : ', face0 init_direction = face0 print "Track 0 return :", directions0 print 'final facing direction : ', init_direction print '' print '' for detected_value in directions0: if detected_value in command_dict.keys(): sendCommand(command_dict[detected_value]) waitForResponse() openArms() # bot movements from 1 - 12 # repeat the same steps as above # ---------------------------------------------------------------------------------------------------------------------# for i in range(1, 12): if check_to_pluck: next_node = shortest_node_to_dep else: next_node = shortest_node print ' skipping DZ :' temp = 1000 shortest_node = 0 for value in fruit_trav_location: distance = node_distance(next_node, value) if distance < temp: temp = distance shortest_node = value fruit_trav_location.remove(shortest_node) print '' print next_node, " --> ", shortest_node cost1, pickup_node1, directions1, face1 = a_star_search(next_node, shortest_node, travesable_nodes, init_direction) if shortest_node in fruit_postion_1: dest = tree_location_1 deposition_node = depostion_zone_apple elif shortest_node in fruit_postion_2: dest = tree_location_2 deposition_node = depostion_zone_bberry else: dest = tree_location_3 deposition_node = depostion_zone_orange tree_facing_turn1, tree_facing_dir1 = turn_4_tree(face1, pickup_node1, dest) if not tree_facing_turn1 == 'forward': directions1.append(tree_facing_turn1) face1 = tree_facing_dir1 shortest_node, changeNode = nodeBeforeShotestNode(shortest_node, face1) if changeNode: cost, pickup_node1, directions1, face1 = a_star_search(next_node, shortest_node, travesable_nodes, init_direction) if shortest_node in fruit_postion_1: dest = tree_location_1 deposition_node = depostion_zone_apple elif shortest_node in fruit_postion_2: dest = tree_location_2 deposition_node = depostion_zone_bberry else: dest = tree_location_3 deposition_node = depostion_zone_orange tree_facing_turn, tree_facing_dir = turn_4_tree(face1, pickup_node1, dest) if not tree_facing_turn == 'forward': directions1.append(tree_facing_turn) face1 = tree_facing_dir print "Track ", i, directions1 print 'final facing direction : ', face1 print '' print '' init_direction = face1 for detected_value in directions1: if detected_value in command_dict.keys(): sendCommand(command_dict[detected_value]) waitForResponse() if changeNode: sendCommand('forward') detected_fruit, det_fruit_size = img_detect_4_pi.image_processing() check_to_pluck = Eliminator(detected_fruit, det_fruit_size) pluckOrNot(check_to_pluck) if check_to_pluck: if init_direction == 'N': init_direction = 'S' elif init_direction == 'W': init_direction = 'E' elif init_direction == 'S': init_direction = 'N' else: init_direction = 'W' # -----------------------------------------------------------------------------------------------------------------# if check_to_pluck: temp_dep = 1000 shortest_node_dep = 0 for value in deposition_node: distance = node_distance(shortest_node, value) if distance < temp_dep: temp_dep = distance shortest_node_to_dep = value print shortest_node, " --> ", shortest_node_to_dep cost2, pickup_node2, directions2, face2 = a_star_search(shortest_node, shortest_node_to_dep, travesable_nodes, init_direction) init_direction = face2 print "Track return ", i, directions2 print 'final facing direction : ', init_direction print '' print '' for detected_value in directions2: if detected_value in command_dict.keys(): sendCommand(command_dict[detected_value]) waitForResponse() openArms() # -----------------------------------------------------------------------------------------------------------------# # -----------------------------------------------------------------------------------------------------------------# # -----------------------------------------------------------------------------------------------------------------#
import sys,re,os.path def RemoveAtAt(Line): AtAtFinder = re.search('(.*?)(@.*?@)(.*)',Line) if AtAtFinder: OneDown = AtAtFinder.group(1)+AtAtFinder.group(3) return RemoveAtAt(OneDown) else: return Line def FormatSplit(Line): return Line.replace('==','@') def AddNewline(Line): if Line[-1] == '\n': return Line else: return Line + '\n' ThisFilename = sys.argv[1] ThisBasename = os.path.basename(ThisFilename) ThisOutputName = 'psd_clean/' + ThisBasename ThisFile = open(ThisFilename,'r') ThisText = ThisFile.readlines() ThisFile.close() ThisOutput = open(ThisOutputName,'w') for i in range(len(ThisText)): NoAts = RemoveAtAt(ThisText[i]) BetterAts = FormatSplit(NoAts) ThisOutput.write(AddNewline(BetterAts)) ThisOutput.close()
# -*- coding: utf-8 -*- """ Created on Thu Apr 30 12:17:09 2020 @author: anusk """ import numpy as np from scipy.stats import entropy from math import log, e import pandas as pd import copy import cv2 def entropy2(labels): """ Computes entropy of label distribution. """ n_labels = labels.size if n_labels <= 1: return 0 counts = np.bincount(labels) probs = counts / n_labels #n_classes = np.count_nonzero(probs) n_classes = 256 #print('nclases ' + str(n_classes)) if n_classes <= 1: return 0 ent = 0. # Compute standard entropy. for i in probs: if i != 0: ent -= i * log(i, n_classes) return ent def entropyfilter(img): J = copy.deepcopy(img) F = np.zeros(J.shape, dtype=np.float64) J = np.pad(J, ((4, 4), (4, 4)), 'reflect') h, w = J.shape for i in range(4, h-4): for j in range(4, w-4): x = J[i-4:i+5,j-4:j+5] x = np.reshape(x, 81) F[i-4,j-4]= entropy2(x) F = F/F.max() return np.uint8(255*F) if __name__ == "__main__": img = cv2.imread('cormoran_rgb.jpg', True) img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) J = entropyfilter(img) cv2.imshow('stdfilt', J) cv2.waitKey(0) cv2.destroyWindow('stdfilt')
import pde from matplotlib import pyplot as plt import sys import logging logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) f,ap = plt.subplots(3) f,ae = plt.subplots(3) prob = pde.problems.instpoisson1d.quad prob.plot(ap) n=100 solver = pde.solvers.classic.poisson_pwlinear_1d_solver(prob) solver.solve(n=1000000) solver.plot(ap,col='r') solver.ploterr(ae,col='r',logabs=True) solver.errstats() solver = pde.solvers.fullgp.poisson_1d_solver(prob) solver.solve(n=50) solver.plot(ap,col='g') solver.ploterr(ae,col='g',logabs=True) solver.errstats() solver = pde.solvers.structgp.poisson_1d_solver(prob) solver.solve(n=200) solver.plot(ap,col='c') solver.ploterr(ae,col='c',logabs=True) solver.errstats() plt.show()
# Faça um Programa que converta metros para centímetros. # entrada de dados metros = float(input('Digite uma distância em metros: ')) # processamento centimetros = int(metros * 100) mensagem = '{} metros equivalem a {} centímetros'.format(metros, centimetros) # saída de dados print(mensagem)
class ResultadoDFS: def __init__(self, tiempo_visitado, tiempo_finalizado, bosque): self.bosque = bosque self.tiempo_finalizado = tiempo_finalizado self.tiempo_visitado = tiempo_visitado def get_tiempo_visitado(self): return self.tiempo_visitado def get_tiempo_finalizado(self): return self.tiempo_finalizado def get_bosque_DFS(self): return self.bosque
# Generated by Django 2.1.2 on 2019-01-28 07:22 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('products', '0037_auto_20190128_0919'), ] operations = [ migrations.AlterField( model_name='product', name='product_description', field=models.TextField(blank=True, help_text='Опис продукту, який відображатиметься на сайті. Макс.: 512 символів.', max_length=512, null=True, verbose_name='Опис продукту'), ), ]
# Generated by Django 2.1 on 2018-08-12 20:58 from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import uuid class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Campaign', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('uuid', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)), ('name', models.CharField(max_length=100, verbose_name='name')), ('campaign_type', models.PositiveSmallIntegerField(choices=[(1, 'Regular'), (2, 'Automated'), (3, 'A/B Test')], default=1, verbose_name='type')), ('status', models.PositiveSmallIntegerField(choices=[(1, 'Sent'), (2, 'Scheduled'), (3, 'Draft'), (4, 'Queued'), (5, 'Delivering'), (6, 'Paused')], db_index=True, default=3, verbose_name='status')), ('send_date', models.DateTimeField(blank=True, db_index=True, null=True, verbose_name='send date')), ('create_date', models.DateTimeField(auto_now_add=True, verbose_name='create date')), ('update_date', models.DateTimeField(default=django.utils.timezone.now, verbose_name='update date')), ('recipients_count', models.PositiveIntegerField(default=0)), ('track_opens', models.BooleanField(default=True, verbose_name='track opens')), ('track_clicks', models.BooleanField(default=True, verbose_name='track clicks')), ('unique_opens_count', models.PositiveIntegerField(default=0, editable=False, verbose_name='unique opens')), ('total_opens_count', models.PositiveIntegerField(default=0, editable=False, verbose_name='total opens')), ('unique_clicks_count', models.PositiveIntegerField(default=0, editable=False, verbose_name='unique clicks')), ('total_clicks_count', models.PositiveIntegerField(default=0, editable=False, verbose_name='total clicks')), ('open_rate', models.FloatField(default=0.0, editable=False, verbose_name='opens')), ('click_rate', models.FloatField(default=0.0, editable=False, verbose_name='clicks')), ], options={ 'verbose_name': 'campaign', 'verbose_name_plural': 'campaigns', 'db_table': 'colossus_campaigns', }, ), migrations.CreateModel( name='Email', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('uuid', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)), ('template_content', models.TextField(blank=True, verbose_name='email template content')), ('from_email', models.EmailField(max_length=254, verbose_name='email address')), ('from_name', models.CharField(blank=True, max_length=100, verbose_name='name')), ('subject', models.CharField(max_length=150, verbose_name='subject')), ('preview', models.CharField(blank=True, max_length=150, verbose_name='preview')), ('content', models.TextField(blank=True, verbose_name='content')), ('content_html', models.TextField(blank=True, verbose_name='content HTML')), ('content_text', models.TextField(blank=True, verbose_name='content plain text')), ('unique_opens_count', models.PositiveIntegerField(default=0, editable=False, verbose_name='unique opens')), ('total_opens_count', models.PositiveIntegerField(default=0, editable=False, verbose_name='total opens')), ('unique_clicks_count', models.PositiveIntegerField(default=0, editable=False, verbose_name='unique clicks')), ('total_clicks_count', models.PositiveIntegerField(default=0, editable=False, verbose_name='total clicks')), ('campaign', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='emails', to='campaigns.Campaign', verbose_name='campaign')), ], options={ 'verbose_name': 'email', 'verbose_name_plural': 'emails', 'db_table': 'colossus_emails', }, ), migrations.CreateModel( name='Link', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('uuid', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)), ('url', models.URLField(max_length=2048, verbose_name='URL')), ('unique_clicks_count', models.PositiveIntegerField(default=0, editable=False, verbose_name='unique clicks count')), ('total_clicks_count', models.PositiveIntegerField(default=0, editable=False, verbose_name='total clicks count')), ('index', models.PositiveSmallIntegerField(default=0, verbose_name='index')), ('email', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='links', to='campaigns.Email', verbose_name='email')), ], options={ 'verbose_name': 'link', 'verbose_name_plural': 'links', 'db_table': 'colossus_links', }, ), ]
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Jul 28 11:46:46 2017 @author: ian """ import pandas as pd import matplotlib.pyplot as plt from scipy.stats import linregress import datetime as dt import numpy as np import DataIO as io path='/home/ian/OzFlux/Sites/GatumPasture/Data/Processed/All/GatumPasture_L3.nc' df = io.OzFluxQCnc_to_data_structure(path, output_structure='pandas') df['T_rad'] = (df.Flu / (5.67 * 10**-8)) ** (1/4.0) - 273.15 T_list = ['Ts_10cma', 'Ts_10cmb', 'Ta', 'Ta_GF', 'Ts_GF', 'T_rad'] daily_df = (df[T_list].groupby([lambda x: x.year, lambda y: y.dayofyear]).mean()) daily_df.index = [dt.datetime(i[0], 1, 1) + dt.timedelta(i[1]) for i in daily_df.index] diel_df = (df[T_list].groupby([lambda x: x.hour, lambda y: y.minute]).mean()) diel_df.index = np.arange(48) / 2.0 diel_df.dropna(inplace = True) fig, (ax1, ax2) = plt.subplots(1, 2, figsize = (16, 8)) fig.patch.set_facecolor('white') ax1.plot(df.index, df.Ta, label = 'Air') ax1.plot(df.index, df.T_rad, label = 'Surface') ax2.plot(df.T_rad, df.Ta, marker = 'o', color = '0.7', ms = 2, ls = '')
import random, string with open('./9.txt', 'w') as f: for i in range(100): len = random.randint(11, 14) f.write(''.join(random.choices(string.ascii_lowercase + string.ascii_uppercase + string.digits, k = len)) + "\n") f.close()
#!/usr/bin/env python3 import csv class csvToDB: playerlist = [] def csvImporter(self, csv): with open('/home/tyrell/app/files/player_data.csv', newline='') as csvfile: reader = csv.DictReader(csvfile) return reader def csvExportToPostgre(self, reader): for row in reader: name = row['name'] yearStart = row['year_start'] yearEnd = row['year_end'] position = row['position'] height = row['height'] weight = row['weight'] birthDate = row['birth_date'] college = row['college'] # csvImporter()
# coding: utf-8 ''' Created on 2017-05-16 @author:Alex Wang 执行shell命令 ''' import os import subprocess import threading import time def run(cmd, timeout=None, timeit=False): if timeit: start_time = time.time() # print('[+] start({}) {}'.format(timeout, ' '.join(cmd))) d = subprocess.run(cmd, stdout=subprocess.PIPE, timeout=timeout) elapsed_time = time.time() - start_time tid = threading.current_thread().ident pid = os.getpid() print('[+][{}][{}] done({})({}) {}'.format(pid, tid, elapsed_time, timeout, ' '.join(cmd))) return d.returncode, d.stdout d = subprocess.run(cmd, stdout=subprocess.PIPE, timeout=timeout) return d.returncode, d.stdout def run_shell(cmd_str, timeout = 20): d = subprocess.run(cmd_str, stdout=subprocess.PIPE, timeout=timeout, shell = True) pid = os.getpid() return d.returncode, d.stdout def test(): filename ="" timeout = 20 retcode, stdout = run(['ffprobe', '-v', 'quiet', '-show_format', '-show_streams', '-print_format', 'json', filename],timeout=timeout) cmd_str = 'ls -ll | wc -l' run_shell(cmd_str)
# -*- coding: utf-8 -*- """ Created on Wed Jan 17 19:11:07 2018 功能:获取头条新闻、体育资讯等资料 接口:聚合数据api接口,可以根据 type_参数来调整获取的新闻类型 @author: mynumber """ from urllib.request import urlopen from urllib.error import HTTPError,URLError import json class News(object): """浏览信息,可以读取新闻的标题,文本等内容""" def __init__(self): self.url='http://v.juhe.cn/toutiao/index?' self.key='97639d9aaa3e5c400df2dc57cb661d35' def get_news(self,type_='top'): """获取新闻,对获取的数据进行处理,默认情况下直接获取头条 类型如下:top(头条,默认),shehui(社会),guonei(国内), guoji(国际),yule(娱乐),tiyu(体育)junshi(军事),keji(科技), caijing(财经),shishang(时尚) """ url=self.url+'type='+type_+'&key='+self.key print(type_) try: html=urlopen(url).read().decode('utf-8') response=json.loads(html) print('成功获取新闻...') return response['result']['data'] except HTTPError as e: print("HTTPError") print(e.code) except URLError as e: print("URLError") print(e.reason) """ #实例化对象,调用对象的get_news函数即可获取新闻 news=News() #获得新闻是一个含有三十条新闻,可以根据不同的属性进行查看 n=news.get_news(type_='top') print(n[0]['title']) """
{ 'target_defaults': { 'msvs_settings': { 'VCCLCompilerTool': { 'WarningLevel': '4', 'WarnAsError': 'true', }, }, 'msvs_system_include_dirs': [ '$(ProjectName)', # Different for each target 'common', # Same for all targets ], }, 'targets': [ { 'target_name': 'foo', 'type': 'executable', 'sources': [ 'main.cc', ], }, { 'target_name': 'bar', 'type': 'executable', 'sources': [ 'main.cc', ], }, ], }
__author__ = 'VHLAND002' import sys import parse_ula # array that will hold all variables that have been defined definedVars = [] semantic_errors = [] # traverses the tuples to create the AST recursively # @param: tree- this is the tuple list we get # @param: value- this is the indentation value for the tab chars def traverseTree(tree, lineno): # if we have a tuple list with only 2 elements we have 2 leaves or the parent of a 2 leaves if tree[0] is None: return if tree[0] == 'IdentifierExpression': if not checkVariable(tree[1][1]): semantic_errors.append("semantic error on line " + str(lineno)) for k in range(2, len(tree)): if k is not None: traverseTree(tree[k],lineno) return elif tree[0] == 'ID': if checkVariable(tree[1]): semantic_errors.append("semantic error on line " + str(lineno)) else: definedVars.append(tree[1]) return for q in range(1, len(tree)): if q is not None: traverseTree(tree[q],lineno) # checks if the parsed variable is in the defined list def checkVariable(var): if var in definedVars: return True else: return False # write errors out to a file def exportErrors(name): # export all errors here name = name[0:-4] + '.err' outFile = open(name, 'w') # we loop through the tree and write the output to the file outFile.write(semantic_errors[0]) print(semantic_errors[0]) outFile.close() def main(): # we see if we have parser errors errors = parse_ula.buildParser(sys.argv[1], True) if errors: for i in errors: semantic_errors.append(i) lineno = 0 # we check if we have semantic errors for r in parse_ula.mainTree: if r is not None: lineno += 1 traverseTree(r,lineno) # we export all errors exportErrors(sys.argv[1]) if __name__ == "__main__": main()
""" Taylor-Green Vortex """ from phi.flow import * def taylor_green_pressure(x): return math.sum(math.cos(2 * x * VORTEX_COUNT), 'vector') / 4 * math.exp(-4 * VORTEX_COUNT ** 2 * t / RE) def taylor_green_velocity(x): sin = math.sin(VORTEX_COUNT * x) cos = math.cos(VORTEX_COUNT * x) return math.exp(-2 * VORTEX_COUNT ** 2 * t / RE) * stack({ 'x': -cos.vector['x'] * sin.vector['y'], 'y': sin.vector['x'] * cos.vector['y']}, dim=channel('vector')) DOMAIN = dict(x=64, y=64, bounds=Box(x=2*PI, y=2*PI), extrapolation=PERIODIC) VORTEX_COUNT = 1 RE = vis.control(60.) # Reynolds number for analytic function dt = vis.control(0.1) t = 0. analytic_pressure = sim_pressure = CenteredGrid(taylor_green_pressure, **DOMAIN) analytic_velocity = sim_velocity = StaggeredGrid(taylor_green_velocity, **DOMAIN) # also works with CenteredGrid viewer = view(sim_velocity, sim_pressure, namespace=globals()) for _ in viewer.range(): t += dt sim_velocity = advect.semi_lagrangian(sim_velocity, sim_velocity, dt) sim_velocity, sim_pressure = fluid.make_incompressible(sim_velocity) analytic_pressure = CenteredGrid(taylor_green_pressure, **DOMAIN) analytic_velocity = StaggeredGrid(taylor_green_velocity, **DOMAIN)
import torch import torch.nn as nn class DetectNet(nn.Module): def __init__(self, vis_sys, num_classes, vis_sys_n_out, embedding_n_out=512): super(DetectNet, self).__init__() self.vis_sys = vis_sys self.embedding = nn.Sequential(nn.Linear(in_features=num_classes, out_features=embedding_n_out), nn.ReLU(inplace=True), ) self.decoder = nn.Linear(in_features=vis_sys_n_out + embedding_n_out, out_features=1) # always 1, because it indicates target present or absent def forward(self, img, query): vis_out = self.vis_sys(img) query_out = self.embedding(query) out = self.decoder( torch.cat((vis_out, query_out), dim=1) ) return out
# -*- coding: utf-8 -*- """ Created on Fri Aug 23 23:30:14 2019 @author: HP """ #dividing array into two arrays of equal sums #can be done by using DP s1=[] s2=[] def two_sum(arr,i,sum1): if i==0: if (arr[i]==sum1): s1.append(arr[i]) return 1 elif sum1==0: s2.append(arr[i]) return 1 else: return 0 elif sum1<0: return 0 else: if two_sum(arr,i-1,sum1-arr[i]): s1.append(arr[i]) return 1 elif two_sum(arr,i-1,sum1): s2.append(arr[i]) return 1 else: return 0 arr=[3,1,1,2,2,1,6] sum=0 for i in arr: sum+=i sum=int(sum/2) print(two_sum(arr,len(arr)-1,sum)) for i in s1: print(i,end=" ") print() for i in s2: print(i,end=" ")
from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.http import HttpResponse from project import settings # Create your views here. # @login_required def index(request): lang = request.META.get('LANGUAGE', request.META.get('LANG')) if lang is None: lang = "en" elif lang == "zh": pass elif ":" in lang: try: lang = lang.split(":")[1] except: lang = "en" return render( request, "app/index.html", {"DEBUG": settings.DEBUG, "LANG": lang} )
#Write a Python program that accepts a string and calculate the number of digits and letters Sample Data : Python 3.2, Expected Output : Letters 6, Digits 2: data=str(input("Enter your data here: ")) digits=0 letters=0 for i in data: if i=='0' or i=='1' or i=='2' or i=='3' or i=='4' or i=='5' or i=='6' or i=='7' or i=='8' or i=='9': digits=digits+1 else: letters=letters+1 print("Digits:", digits) print("Letters:",letters)
#Qwerty@123 import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import Keys MY_ADDRESS = Keys.getEmailID() PASSWORD = Keys.getEmailPassword() TO_ADDRESS = "kamarajk@tcd.ie" def sendEmail(): s = smtplib.SMTP(host = 'smtp.gmail.com', port = 587) s.starttls() s.login(MY_ADDRESS, PASSWORD) message = "ALERT! This specific area might require your attention. Please check it out." msg = MIMEMultipart() msg['From'] = MY_ADDRESS msg['To'] = TO_ADDRESS msg['Subject'] = "ALERT!!! Potential disaster detected." msg.attach(MIMEText(message, 'plain')) s.send_message(msg) del msg s.quit() print("Email sent successfully!")
def diff(A, B): l = len(A) n = 0 for i in range(l): if A[i] != B[i]: n += 1 return n AB = input() A, B = AB.split()[0], AB.split()[1] d = len(A) for i in range(len(B) - len(A) + 1): d2 = diff(A, B[i:i + len(A)]) if d2 < d: d = d2 print(d) # Done
# -*- coding: utf-8 -*- from flask import request, Blueprint from flask import g import json import hashlib import logging from libs.util import make_response from libs.util import create_access_token from libs.response_meta import ResponseMeta from .authorization import require_application_auth from models.user import User app = Blueprint('user', __name__) def publish_message(rds, channel, msg): rds.publish(channel, msg) def saslprep(string): return string def ha1(username, realm, password): t = ':'.join((username, realm, saslprep(password))) return hashlib.md5(t.encode()).hexdigest() def hmac(username, realm, password): return ha1(username, realm, password) @app.route("/auth/grant", methods=["POST"]) @require_application_auth def grant_auth_token(): rds = g.rds appid = request.appid obj = request.get_json(force=True, silent=True, cache=False) if obj is None: logging.debug("json decode err:%s", e) raise ResponseMeta(400, "json decode error") uid = obj.get('uid') if type(uid) != int: raise ResponseMeta(400, "invalid param") name = obj.get('user_name', "") token = User.get_user_access_token(rds, appid, uid) if not token: token = create_access_token() User.add_user_count(rds, appid, uid) User.save_user_access_token(rds, appid, uid, name, token) u = "%s_%s"%(appid, uid) realm = "com.beetle.face" key = hmac(u, realm, token) User.set_turn_realm_key(rds, realm, u, key) data = {"data":{"token":token}} return make_response(200, data) @app.route("/users/<int:uid>", methods=["POST", "PATCH"]) @require_application_auth def user_setting(uid): rds = g.rds appid = request.appid obj = request.get_json(force=True, silent=True, cache=False) if obj is None: logging.debug("json decode err:%s", e) raise ResponseMeta(400, "json decode error") if 'name' in obj: User.set_user_name(rds, appid, uid, obj['name']) elif 'forbidden' in obj: #聊天室禁言 fb = 1 if obj['forbidden'] else 0 User.set_user_forbidden(rds, appid, uid, fb) content = "%d,%d,%d"%(appid, uid, fb) publish_message(rds, "speak_forbidden", content) elif 'do_not_disturb' in obj: contact_id = obj['do_not_disturb']['peer_uid'] on = obj['do_not_disturb']['on'] User.set_user_do_not_disturb(g.rds, appid, uid, contact_id, on) elif 'mute' in obj: User.set_mute(rds, appid, uid, obj["mute"]) else: raise ResponseMeta(400, "invalid param") return ""
'''Database models News API''' from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class DataTimeMixin: ''' Mixin for initializing relevant sqlalchemy columns datetime columns containing current datetime ''' create_at = db.Column(db.DateTime, default=db.func.now()) class NewsArticle(DataTimeMixin, db.Model): '''News Article stored in the database''' id = db.Column(db.Integer, primary_key=True) headline = db.Column(db.String) text = db.Column(db.String) sentiment_score = db.Column(db.Integer) def __repr__(self): return 'id: {id}\nheadline: {headline}\ntext: {text}'.format( id=self.id, headline=self.headline, text=self.text, sentiment_score = db.Column(db.Integer) )
import time import queue import random import threading from tkinter import * from tkinter.dialog import * from collections import deque class GUI(Tk): def __init__(self, queue): Tk.__init__(self) self.queue = queue self.is_game_over = False self.canvas = Canvas(self, width = 495, height = 305, bg = 'white') self.canvas.pack() self.draw_body() self.food = self.canvas.create_rectangle(0, 0, 0, 0, fill = 'black', outline = 'white') self.points_earned = self.canvas.create_text(455, 15, text = "score:0") self.queue_handler() def queue_handler(self): try: while True: task = self.queue.get(block = False) # task 是一个 dict if task.get('game_over'): self.game_over() if task.get('move'): self.update_body(task['move']) if task.get('food'): self.canvas.coords(self.food, *task['food']) elif task.get('points_earned'): self.canvas.itemconfigure(self.points_earned, text = 'score:{}'.format(task['points_earned'])) self.queue.task_done() except queue.Empty: if not self.is_game_over: self.canvas.after(100, self.queue_handler) def draw_body(self): global body for item in body: self.canvas.create_rectangle(item, fill = 'blue', outline = 'white') self.canvas.create_rectangle(body[0], fill = 'red', outline = 'white') def update_body(self, last): snake = self.canvas.create_rectangle(last, fill = 'white', outline = 'white') self.draw_body() def game_over(self): self.is_game_over = True dialog = Dialog(self, title = "Game Over", text = "Game Over!", bitmap = DIALOG_ICON, default = 0, strings = ('yes', 'no')) quit() class Food(): def __init__(self, queue): self.queue = queue self.generate_food() def generate_food(self): x = random.randrange(5, 480, 10) y = random.randrange(5, 295, 10) self.position = [x - 5, y - 5, x + 5, y + 5] self.queue.put({'food':self.position}) class Snake(threading.Thread): def __init__(self, gui, queue): threading.Thread.__init__(self) self.gui = gui self.queue = queue self.daemon = True self.points_earned = 0 self.snake_head = [30, 0, 40, 10] self.food = Food(queue) self.direction = 'Right' self.start() def run(self): if self.gui.is_game_over: self._delete() while not self.gui.is_game_over: time.sleep(0.5) self.move() def move(self): global body self.calculate_new_coordinates() self.check_game_over() body.appendleft(self.snake_head) self.queue.put({'move':body[-1]}) body.pop() if self.food.position == self.snake_head: self.points_earned += 1 self.queue.put({'points_earned':self.points_earned}) self.calculate_new_coordinates() body.appendleft(self.snake_head) self.food.generate_food() def key_pressed(self, e): self.direction = e.keysym def calculate_new_coordinates(self): global body if self.direction == 'Up': self.snake_head = [body[0][0], body[0][1] - 10, body[0][2], body[0][3] - 10] elif self.direction == 'Down': self.snake_head = [body[0][0], body[0][1] + 10, body[0][2], body[0][3] + 10] elif self.direction == 'Left': self.snake_head = [body[0][0] - 10, body[0][1], body[0][2] - 10, body[0][3]] elif self.direction == 'Right': self.snake_head = [body[0][0] + 10, body[0][1], body[0][2] + 10, body[0][3]] def check_game_over(self): global body x = self.snake_head[0] y = self.snake_head[1] if not -5 < x < 505 or not -5 < y < 315 or self.snake_head in body: self.queue.put({'game_over':True}) def main(): global body body = deque() body.append([30, 0, 40, 10]) body.append([20, 0, 30, 10]) body.append([10, 0, 20, 10]) body.append([0 , 0, 10, 10]) msg_queue = queue.Queue() gui = GUI(msg_queue) gui.title("I'm snake") snake = Snake(gui, msg_queue) gui.bind('<Key-Left>', snake.key_pressed) gui.bind('<Key-Right>', snake.key_pressed) gui.bind('<Key-Down>', snake.key_pressed) gui.bind('<Key-Up>', snake.key_pressed) gui.mainloop() if __name__ == '__main__': main()
from django.shortcuts import render, redirect from .form import ProduitForm,FactureForm from django.contrib.auth.decorators import login_required from django.http import HttpResponse from .models import Produit, Facture # Create your views here. @login_required(login_url='/register/login/') def AjouterProduit(request): form = ProduitForm() if request.method == 'POST': form = ProduitForm(request.POST) print(form) if form.is_valid(): print("formvalid ;;") form.save() return redirect('/library/AfficherProduit') else: print("form not valdi") context = {'ProduitForm': ProduitForm} return render(request, 'produit.html', context) @login_required(login_url='/register/login/') def Update(request,pk): produit= Produit.objects.get(id=pk) print("NIV 1") if request.method=='POST': print("niv 2") form=ProduitForm(request.POST,instance=produit) print(form) if form.is_valid(): print(form) print("niv3") form.save() return redirect('/library/AfficherProduit') print("niv 0") return render(request,'index.html') @login_required(login_url='/register/login/') def ModifierProduit(request,pk): produit = Produit.objects.get(id=pk) return render(request, 'ModifierProduit.html', {'produit':produit}) @login_required(login_url='/register/login/') def AfficherProduit(request): objects = Produit.objects.all().order_by('designation'); context = {'produits': objects} return render(request, 'tables.html', context) @login_required(login_url='/register/login/') def Delete(request,pk): produit=Produit.objects.get(id=pk) produit.delete() return redirect('/library/AfficherProduit') @login_required(login_url='/register/login/') def AjouterFacture(request): form = FactureForm() if request.method == 'POST': form = FactureForm(request.POST) print(form) if form.is_valid(): print("formvalid ;;") form.save() return redirect('/library/AfficherFacture') else: print("form not valdi") return render(request, 'facture.html') @login_required(login_url='/register/login/') def AfficherFacture(request): factures = Facture.objects.all() context = {'factures': factures} return render(request, 'TableFacture.html', context) @login_required(login_url='/register/login/') def editFacture(request,pk): facture = Facture.objects.get(id=pk) return render(request, 'ModifierFacture.html', {'facture': facture}) @login_required(login_url='/register/login/') def UpdateFacture(request,pk): facture = Facture.objects.get(id=pk) print("NIV 1") if request.method == 'POST': print("niv 2") form = FactureForm(request.POST, instance=facture) print(form) if form.is_valid(): print(form) print("niv3") form.save() return redirect('/library/AfficherFacture') print("niv 0") return render(request, 'index.html') @login_required(login_url='/register/login/') def DeleteFac(request,pk): facture=Facture.objects.get(id=pk) facture.delete() return redirect('/library/AfficherProduit') def Facture2(request): return render(request,"Facture2.html")
import numpy as np import torch from tqdm import trange from .inception import InceptionV3 def get_inception_score(images, device, splits=10, batch_size=32, verbose=False): block_idx = InceptionV3.BLOCK_INDEX_BY_DIM['prob'] model = InceptionV3([block_idx]).to(device) model.eval() preds = [] if verbose: iterator = trange(0, len(images), batch_size, dynamic_ncols=True) else: iterator = range(0, len(images), batch_size) for start in iterator: end = start + batch_size batch_images = images[start: end] batch_images = torch.from_numpy(batch_images).type(torch.FloatTensor) batch_images = batch_images.to(device) pred = model(batch_images)[0] preds.append(pred.cpu().numpy()) preds = np.concatenate(preds, 0) scores = [] for i in range(splits): part = preds[ (i * preds.shape[0] // splits): ((i + 1) * preds.shape[0] // splits), :] kl = part * ( np.log(part) - np.log(np.expand_dims(np.mean(part, 0), 0))) kl = np.mean(np.sum(kl, 1)) scores.append(np.exp(kl)) return np.mean(scores), np.std(scores)
# @see https://adventofcode.com/2015/day/17 from itertools import combinations with open('day17_input.txt', 'r') as f: containers = [int(l) for l in f] def calc_num_of_ways(c: list): min_ways, max_ways = 0, 0 l = len(c) # Generate all combinations of containers # Use [combinations of] the index of the list of containers to ensure identical sizes are included # ...and only select those volumes that add up to exactly 150 l for dl in range(1, l+1): ways = [p for p in combinations(range(l), dl) if 150 == sum([c[i] for i in p])] lw = len(ways) if 0 == min_ways and lw > 0: min_ways = lw max_ways += lw return max_ways, min_ways maxw, minw = calc_num_of_ways(containers) print('------------ PART 01 -------------') print('Combinations of containers that can exactly fit all 150 liters of eggnog:', maxw) print('\n------------ PART 02 -------------') print('Num of ways you can fill the min num of containers that can fit 150 liters:', minw)
import wave from scipy import fromstring, int16 import numpy as np from scipy import signal import matplotlib.pyplot as plt #wavfile = 'hirakegoma.wav' wavfile = 'ohayo.wav' wr = wave.open(wavfile, "rb") ch = wr.getnchannels() width = wr.getsampwidth() fr = wr.getframerate() fn = wr.getnframes() nperseg = 256 #4096 #2048 #1024 #256 #128 #32 #64 #512 print('ch', ch) print('frame', fn) fs = fn / fr print('fr',fr) print('sampling fs ', fs, 'sec') print('width', width) origin = wr.readframes(wr.getnframes()) data = origin[:fn] wr.close() amp = max(data) print('amp',amp) print('len of origin', len(origin)) print('len of sampling: ', len(data)) # ステレオ前提 > monoral x = np.frombuffer(data, dtype="int16") #/32768.0 print('max(x)',max(x)) t = np.linspace(0,fs, fn/2, endpoint=False) plt.plot(t, x) plt.show() f, t, Zxx = signal.stft(x, fs=fs*fn/20, nperseg=nperseg) plt.figure() plt.pcolormesh(t, f, np.abs(Zxx), vmin=0, vmax=amp) plt.ylim([f[1], f[-1]]) plt.xlim([0, 3]) plt.title('STFT Magnitude') plt.ylabel('Frequency [Hz]') plt.xlabel('Time [sec]') plt.yscale('log') plt.show() #Zero the components that are 10% or less of the carrier magnitude, then convert back to a time series via inverse STFT #キャリア振幅の10%以下の成分をゼロにしてから、逆STFTを介して時系列に変換し直す maxZxx= max(data) print('maxZxx',maxZxx) Zxx = np.where(np.abs(Zxx) >= maxZxx*2, Zxx, 0) plt.figure() plt.pcolormesh(t, f, np.abs(Zxx), vmin=0, vmax=amp) plt.ylim([f[1], f[-1]]) plt.title('STFT Magnitude') plt.ylabel('Frequency [Hz]') plt.xlabel('Time [sec]') plt.yscale('log') plt.show() _, xrec = signal.istft(Zxx, fs) #Compare the cleaned signal with the original and true carrier signals. #きれいにされた信号を元のそして本当の搬送波信号と比較 t = np.linspace(0,fs, fn/2, endpoint=False) plt.figure() plt.plot(t, x, t, xrec) #, time, carrier) #plt.xlim([20, 75]) plt.xlabel('Time [sec]') plt.ylabel('Signal') #plt.legend(['Carrier + Noise', 'Filtered via STFT', 'True Carrier']) plt.show() plt.figure() plt.plot(t, xrec-x) #, time, carrier) #plt.xlim([0, 0.1]) plt.xlabel('Time [sec]') plt.ylabel('Signal') #plt.legend(['Carrier + Noise', 'Filtered via STFT', 'True Carrier']) plt.show() # 書き出し outf = './output/test.wav' ww = wave.open(outf, 'w') ww.setnchannels(ch) ww.setsampwidth(width) ww.setframerate(fr) outd = x #xrec print(len(x)) ww.writeframes(outd) ww.close() outf = './output/test1.wav' ww = wave.open(outf, 'w') ww.setnchannels(ch) ww.setsampwidth(2*width) ww.setframerate(2*fr) maxrec=max(xrec) outd = xrec/maxrec print(max(outd),min(outd)) ww.writeframes(outd) ww.close()
# Generated by Django 2.0.5 on 2018-06-04 08:07 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('calculation', '0011_map_unit'), ] operations = [ migrations.CreateModel( name='Calculation', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('qty_children', models.PositiveIntegerField()), ('created_at', models.DateTimeField(db_index=True, verbose_name='создано')), ('values', models.TextField(default='gAN9cQAu', verbose_name='')), ('food_intake', models.PositiveIntegerField(db_index=True, verbose_name='приём пищи')), ('dish', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.PROTECT, to='calculation.Dish', verbose_name='блюдо')), ], ), migrations.RemoveField( model_name='stock', name='from_of', ), migrations.RemoveField( model_name='stock', name='invoce', ), migrations.RemoveField( model_name='stock', name='product', ), migrations.AlterField( model_name='menu', name='created_at', field=models.DateField(db_index=True, verbose_name='создано'), ), migrations.AlterField( model_name='registration', name='motion', field=models.SmallIntegerField(choices=[('in', 'interior'), ('out', 'outer')], default=1), ), migrations.DeleteModel( name='Stock', ), ]
"""Utility functions for AUACM package""" import requests from auacm.common import BASE_URL def log(message): """Log a message""" print(message) callbacks = dict() def subcommand(command): """Decorator to register a function as a subcommand""" def wrapped(function): """Add the function to the callbacks""" callbacks[command] = function return function return wrapped def _find_pid_from_name(name): """Look up the pid from the problem name""" response = requests.get(BASE_URL + 'problems') if not response.ok: print('There was an error looking up the problem id') exit(1) pid = -1 for problem in response.json()['data']: if name.lower() in problem['name'].lower(): pid = problem['pid'] break return pid def format_str_len(string, length): """Format a string to break before a specified length""" words, result, current_line = string.split(), '', 0 for word in words: if current_line + len(word) < length: result += ' ' + word current_line += 1 + len(word) else: result += '\n' + word current_line = len(word) return result
from selenium.webdriver.common.by import By from pageObjects.checkOutPage import checkOutPage class HomePage: # define constructor def __init__(self, driver): self.driver = driver shop = (By.LINK_TEXT, "Shop") def shopItems(self): # return self.driver.find_element(*HomePage.shop) self.driver.find_element(*HomePage.shop).click() Checkoutpage = checkOutPage(self.driver) return Checkoutpage # If it is a class variable, we need to call the defined object by classname.object, in this case homePage.shop # if it is a instance variable in the constructor, we need to call the object by self.object # by passing the *, it will identify the Tuple
# -*- coding: utf-8 -*- from django import forms from ckeditor.widgets import CKEditorWidget class PostAdminForm(forms.ModelForm): desc = forms.CharField(widget=forms.Textarea, label='摘要', required=False) content = forms.CharField(widget=CKEditorWidget(), label='正文', required=True)
# imports import pandas as pd from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error import numpy as np # read in the data drinks = pd.read_csv('https://raw.githubusercontent.com/sinanuozdemir/python-data-science-workshop/master/drinks.csv', na_filter=False) # features X = drinks[['beer_servings','spirit_servings']] X.shape # response y = drinks['wine_servings'] y.shape # fit a linear model lm = LinearRegression() lm.fit(X, y) # examine the intercept and coefficients lm.intercept_ lm.coef_ # manually predict wine servings for the first two countries drinks.head() lm.intercept_ + 0*lm.coef_[0] + 0*lm.coef_[1] lm.intercept_ + 89*lm.coef_[0] + 132*lm.coef_[1] # predict for all countries preds = lm.predict(X) preds # compute the MSE and RMSE mean_squared_error(y, preds) np.sqrt(mean_squared_error(y, preds)) # docus on RMSE https://www.kaggle.com/wiki/RootMeanSquaredError # compute the R^2 lm.score(X, y) # Important questions: # Is the relationship actually linear? # Did we include the right variables? # Do we have the right data to answer this question? # Will our model generalize to new data?
#!/usr/bin/env python3 """Filter SNPS from the output of 03_saf_maf_gl_depth_all.sh Usage: <program> angsd_output_folder filtered_folder window_size min_maf max_maf_other_snps max_surrounding_snps Where: window_size is the number of base pairs on each side where surrounding SNPs are searched min_maf is the lowest accepted MAF value for a SNP of interest max_maf_other_snps is the highest accepted MAF value for a surounding SNP max_surrounding_snps is the maximal number of SNPs with max_maf_other_snps accepted in window_size The script will read all needed files in the angsd_output_folder and use the information in all of them to filter the SNPs in one pass. Files found in the angsd_output_folder: *_maf0.01_pctind0.5_maxdepth20.arg *_maf0.01_pctind0.5_maxdepth20.beagle.gz # used *_maf0.01_pctind0.5_maxdepth20.counts.gz # used *_maf0.01_pctind0.5_maxdepth20.depthGlobal *_maf0.01_pctind0.5_maxdepth20.depthSample *_maf0.01_pctind0.5_maxdepth20.mafs # used *_maf0.01_pctind0.5_maxdepth20.pos.gz *_maf0.01_pctind0.5_maxdepth20.saf.gz *_maf0.01_pctind0.5_maxdepth20.saf.idx *_maf0.01_pctind0.5_maxdepth20.saf.pos.gz """ # Modules from collections import defaultdict import gzip import sys import os # Function def myopen(_file, mode="rt"): if _file.endswith(".gz"): return gzip.open(_file, mode=mode) else: return open(_file, mode=mode) # Parse user input try: angsd_output_folder = sys.argv[1] filtered_folder = sys.argv[2] window_size = int(sys.argv[3]) min_maf = float(sys.argv[4]) max_maf_other_snps = float(sys.argv[5]) max_surrounding_snps = int(sys.argv[6]) except: print(__doc__) sys.exit(1) # Open input file handles files = os.listdir(angsd_output_folder) input_files = {} input_files["beagle"] = myopen( os.path.join( angsd_output_folder, [f for f in files if f.endswith("beagle.gz")][0] ) ) input_files["counts"] = myopen( os.path.join( angsd_output_folder, [f for f in files if f.endswith("counts.gz")][0] ) ) input_files["mafs"] = myopen( os.path.join( angsd_output_folder, [f for f in files if f.endswith("mafs")][0] ) ) # Create output folder if not os.path.exists(filtered_folder): os.mkdir(filtered_folder) # Open output file handles files = os.listdir(angsd_output_folder) output_files = {} output_files["beagle"] = myopen( os.path.join( filtered_folder, [f for f in files if f.endswith("beagle.gz")][0] ), "wt" ) output_files["counts"] = myopen( os.path.join( filtered_folder, [f for f in files if f.endswith("counts.gz")][0] ), "wt" ) output_files["mafs"] = myopen( os.path.join( filtered_folder, [f for f in files if f.endswith("mafs")][0] ), "wt" ) # SNP containers left_snps = [] center_snp = None right_snps = [] counter = 0 # Write headers to output files for f in input_files: output_files[f].write(input_files[f].readline()) # Read lines from all 3 files one at a time for mafs_line in input_files["mafs"]: #counter += 1 #if counter >= 2000: # sys.exit() # Position info (scaffold<str>, position<int>) pos = mafs_line.strip().split()[:2] pos = (pos[0], int(pos[1])) # Keep infos about positions in 'queue' in order to keep as little # information as needed to treat a given SNP. For example, we need only the # 30 positions on each side of a SNP to decide if we are keeping it. # Format mafs for later use mafs = mafs_line.strip().split() # Format beagle for later use beagle = input_files["beagle"].readline().strip().split() # Format count for later use counts = input_files["counts"].readline().strip().split() counts = [int(x) for x in counts] info = (pos, mafs, beagle, counts) if not center_snp: center_snp = info elif len(right_snps) < window_size: right_snps.append(info) else: # Add the new SNP right_snps.append(info) # Informations of the SNP being treated p, m, b, c = center_snp # Filters keep_snp = True # MAF maf = float(m[5]) if maf < min_maf: keep_snp = False # Surrounding SNPs surrounding_snps = [ x for x in left_snps + right_snps if x[0][0] == p[0] and ((x[0][1] - window_size) <= p[1] <= (x[0][1] + window_size)) ] if len(surrounding_snps) > max_surrounding_snps: keep_snp = False # If MAF of surrounding SNPs is low enough, keep? else: for s in surrounding_snps: if float(s[1][5]) > max_maf_other_snps: keep_snp = False # Write wanted SNP infos in the output files if keep_snp: output_files["mafs"].write("\t".join([str(x) for x in m]) + "\n") output_files["beagle"].write("\t".join([str(x) for x in b]) + "\n") output_files["counts"].write("\t".join([str(x) for x in c]) + "\n") # - move SNPs from right to left if len(left_snps) >= window_size: left_snps.pop(0) left_snps.append(center_snp) center_snp = right_snps.pop(0) # Close file handles for f in input_files: input_files[f].close() for f in output_files: output_files[f].close()
def int_to_bin(n): return format(n, 'b')
import random as r import time as t import os num1 = r.randint(2, 9) num2 = r.randint(1, 9) start = t.time() calc = int(input("%d * %d = "%(num1,num2))) end = t.time() t.sleep(2) #뜸들이기 if calc == num1 * num2: if end - start < 2: print("천재") else: print("보통") else: print("실망이야...") doll = ["피카츄","라이츄","파이리","꼬북이"] while doll: #0, "", [], (), {} 거짓말이 되죠 input(""" =====인형뽑기===== <Enter 누르면 게임 시작> """) print("**인형목록**") print(doll) crain = int(input("숫자 입력(1 ~ 3) : ")) answer = r.randint(1, 3) if crain == answer: select = r.choice(doll) print("윙~") t.sleep(1) print("윙~") t.sleep(1) print("윙~") t.sleep(1) print("딸캉~") print("%s가 뽑혔습니다."%select) doll.remove(select) else: print("크레인 기계가 이상하게 움직여ㅜ") os.system("pause") os.system("cls") print("☆☆인형을 모두 뽑았습니다.☆☆")
def nested_lists(): allscores = set() allnames = [] for i in range(int(input())): list = [] name = input() score = float(input()) list.append(name) list.append(score) allscores.add(score) allnames.append(list) allnames.sort(key=lambda x: x[1]) list = [] l = sorted(allscores, reverse=True) first = l.pop() second = l.pop() for i in range(len(allnames)): if second == allnames[i][1]: list.append(allnames[i][0]) list.sort() return list for i in nested_lists(): print(i)
from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', one_hot=True) import tensorflow as tf sess = tf.InteractiveSession() x = tf.placeholder(tf.float32, shape=[None, 784], name="x") batch_size = tf.placeholder(tf.int32, None, name="batch_size") def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def deconv2d(x, W, output_shape): return tf.nn.conv2d_transpose(x, W,output_shape, strides=[1, 2, 2, 1], padding='VALID') def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') W_conv1 = weight_variable([5, 5, 1, 32]) b_conv1 = bias_variable([32]) x_flat = tf.reshape(x, [-1]) x_image = tf.reshape(x, [-1,28,28,1]) h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) h_pool1 = max_pool_2x2(h_conv1) W_conv2 = weight_variable([5, 5, 32, 64]) b_conv2 = bias_variable([64]) h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) h_pool2 = max_pool_2x2(h_conv2) #output last convlayer W_fc1 = weight_variable([7 * 7 * 64, 1024]) b_fc1 = bias_variable([1024]) h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) W_fc2 = weight_variable([1024, 10]) b_fc2 = bias_variable([10]) y_conv_ = tf.matmul(h_fc1, W_fc2) y_conv = tf.add(y_conv_, b_fc2) channels = 32 W_fc1_r = weight_variable([10, 7*7*channels]) b_fc1_r = bias_variable([7*7*channels]) h_fc1_r_ = tf.matmul(y_conv, W_fc1_r) h_fc1_r = tf.add(h_fc1_r_, b_fc1_r) h_fc1_r_flat = tf.reshape(h_fc1_r, [-1, 7, 7, channels]) W_conv2_r = weight_variable([2, 2, channels, channels]) b_conv2_r = bias_variable([channels]) output_shape_conv2r = [batch_size, 14, 14, channels] h_conv2_r = tf.nn.relu(deconv2d(h_fc1_r_flat, W_conv2_r, output_shape_conv2r) + b_conv2_r) #deconvolution1 W_conv1_r = weight_variable([2, 2, channels, channels]) b_conv1_r = bias_variable([channels]) output_shape_conv1r = [batch_size, 28, 28, channels] h_conv1_r = deconv2d(h_conv2_r, W_conv1_r, output_shape_conv1r)+ b_conv1_r #deconvolution 2 #output_img = tf.nn.softmax(tf.reshape(tf.reduce_mean(h_conv1_r, axis=3, keep_dims=True), [-1]), name='output_img') output_img = tf.reshape(tf.reduce_mean(h_conv1_r, axis=3, keep_dims=True), [-1], name='output_img') #cross_entropy = tf.reduce_mean(-tf.reduce_sum(x_flat * tf.log(output_img), reduction_indices=[0]))#manual cross-entropy. Numerically instable #cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=x_flat, logits=output_img, dim=0)) #nice entropy function. Doesnt work least_squares = tf.reduce_sum(tf.multiply((x_flat- output_img),(x_flat- output_img))) train_step = tf.train.AdamOptimizer(1e-4).minimize(least_squares) sess.run(tf.global_variables_initializer()) saver = tf.train.Saver() for i in range(20000): batch = mnist.train.next_batch(50) [_, loss_val] = sess.run([train_step, least_squares], feed_dict={x: batch[0], batch_size: 50}) if i%100 == 0: print("step %d, loss %g" %(i, loss_val)) save_path = saver.save(sess, 'model') print("Model saved in file: %s" % save_path)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 识别人脸鉴定是哪个人 # 导入face_recogntion模块,可用命令安装 pip install face_recognition import face_recognition #将jpg文件加载到numpy数组中 liu_image = face_recognition.load_image_file("liu.jpeg") liming_image = face_recognition.load_image_file("liming.jpeg") #要识别的图片 unknown_image = face_recognition.load_image_file("liming.jpeg") #获取每个图像文件中每个面部的面部编码 #由于每个图像中可能有多个面,所以返回一个编码列表。 #但是由于我知道每个图像只有一个脸,我只关心每个图像中的第一个编码,所以我取索引0。 liming_face_encoding = face_recognition.face_encodings(liming_image)[0] liu_face_encoding = face_recognition.face_encodings(liu_image)[0] #print("chen_face_encoding:{}".format(liu_face_encoding)) unknown_face_encoding = face_recognition.face_encodings(unknown_image)[0] #print("unknown_face_encoding :{}".format(unknown_face_encoding)) known_faces = [ liu_face_encoding,liming_face_encoding ] #结果是True/false的数组,未知面孔known_faces阵列中的任何人相匹配的结果 results = face_recognition.compare_faces([liu_face_encoding], unknown_face_encoding) if results: print ("这个人是刘德华") #name = known_faces[first_match_index] print("result :{}".format(results)) #print ("这个人是刘德华") #print("这个未知面孔是 陈都灵 吗? {}".format(results[0])) #print("这个未知面孔是 我们从未见过的新面孔吗? {}".format(not True in results))
import pipes class CEProbeScript(object): """A class used to generate job-scripts for CE probes.""" def __init__(self): self._required_files = [] self._generated_files = [] def require_file(self, fname, size = None, sha1sum = None): self._required_files.append((fname, size, sha1sum)) def generate_file(self, fname, content = None): self._generated_files.append((fname, content)) def write_to(self, fh): fh.write('#! /bin/sh\n' 'echo "Job started `date -Is`."\n' 'status=0\n' 'error() { echo 1>&2 "ERROR: $@"; status=1; }\n') for fname, size, sha1sum in self._required_files: d = dict(fname = pipes.quote(fname), size = size, sha1sum = sha1sum) fh.write('if test ! -e %(fname)s; then\n' ' error "Missing file "%(fname)s\n'%d) if not size is None: fh.write('elif test `stat -c %%s %(fname)s` -ne %(size)d; then\n' ' error "Wrong size for "%(fname)s\n'%d) if not sha1sum is None: fh.write('elif test `sha1sum %(fname)s` -ne %(sha1sum)d; then\n' ' error "Wrong sha1sum for "%(fname)s\n'%d) fh.write('fi\n') for fname, content in self._generated_files: if content is None: fh.write('hostname >%s\n'%pipes.quote(fname)) else: fh.write('echo %s >%s\n' % (pipes.quote(content), pipes.quote(content))) fh.write('echo "Present files before termination:"\n' 'ls -l\n' 'echo "Job finished `date -Is`, status = $status."\n' 'exit $status\n') def save_to(self, path): fh = open(path, 'w') self.write_to(fh) fh.close()
#!/usr/bin/env python import sys from matplotlib import pyplot as plt import parmed as pmd orig_lib, new_lib, resname0, resname1 = sys.argv[1:] res0 = pmd.load_file(orig_lib)[resname0] res1 = pmd.load_file(new_lib)[resname1] c0 = [a.charge for a in res0.atoms] c1 = [a.charge for a in res1.atoms] print(c0, sum(c0)) print(c1, sum(c1))
# Exercício 6.17 - Livro estoque = { 'tomate': [50, 2.30], 'alface': [35, 0.45], 'batata': [60, 1.20], 'feijão': [20, 1.50] } while True: print('=-=' * 10) produto = str(input('Informe o produto desejado: ')).lower() if produto == 'sair': print('FIM') break elif produto not in estoque.keys(): print('Produto não cadastrado!') else: quantidade = int(input('Informe a quantidade a comprar: ')) if estoque[produto][0] < quantidade: print('Não há essa quantidade estocada!') else: estoque[produto][0] -= quantidade preco = estoque[produto][1] total = preco * quantidade print(f'{produto.capitalize()}: R${preco:.2f} x {quantidade} = R${total:.2f}') print('=-=' * 10) print(f"{'PRODUTOS'}{'QUANTIDADES':^15}{'PREÇOS'}") for chave, valor in estoque.items(): qtd = valor[0] preco = valor[1] if qtd == 0: print(f'{chave.capitalize()} {"ACABOU":^16} {preco:>3.2f}') else: print(f'{chave.capitalize()} {qtd:>9} {preco:>11.2f}')
import os import sys import shutil sys.path.insert(0, 'scripts') sys.path.insert(0, 'tools/families') sys.path.insert(0, 'tools/trees') import experiments as exp import fam from ete3 import SeqGroup def get_genes(input_ali): msa = SeqGroup(input_ali) genes = set() for entry in msa.get_entries(): genes.add(entry[0]) return genes def generate(inputdir, outputdir): fam.init_top_directories(outputdir) input_dict_path = os.path.join(inputdir, "names_to_replace_Archaea_taxa_set") ali_dir = os.path.join(inputdir, "ali") input_species_tree = os.path.join(inputdir, "25_perc_best_BayesianArcv5.faa.treefile_renamed.rooted") output_species_tree = fam.get_species_tree(outputdir) shutil.copy(input_species_tree, output_species_tree) genes_to_species = {} for line in open(input_dict_path).readlines(): sp = line.replace("\n", "").split("\t") genes_to_species[sp[0]] = sp[1] for ali in os.listdir(ali_dir): family = ali.split(".")[0] fam.init_family_directories(outputdir, family) input_ali = os.path.join(ali_dir, ali) output_ali = fam.get_alignment(outputdir, family) shutil.copy(input_ali, output_ali) genes = get_genes(input_ali) species_to_genes = {} for gene in genes: species = genes_to_species[gene] assert (not species in species_to_genes) species_to_genes[species] = [gene] mapping_file = fam.get_mappings(outputdir, family) fam.write_phyldog_mapping(species_to_genes, mapping_file) fam.postprocess_datadir(outputdir) if (__name__ == "__main__"): if (len(sys.argv) < 3): print("Syntax: python" + os.path.basename(__file__) + " input_dir output_dir") inputdir = sys.argv[1] outputdir = sys.argv[2] generate(inputdir, outputdir)
""" In training scheme 1, we don't anneal anything. There is an initial round of training without RL, followed by a fragment wherein the exploration is gradually decreased. There are 3 main hyper-parameters: * area_weight during stage 0 * area_weight during remaining stages * nonzero_weight during remaining stages """ import clify import numpy as np from dps.env.advanced import yolo_rl from dps.datasets import EmnistObjectDetectionDataset def prepare_func(): from dps import cfg cfg.curriculum[0]["area_weight"] = cfg.stage0_area_weight distributions = dict( nonzero_weight=[70., 75., 80., 85., 90], area_weight=list(np.linspace(0.1, 0.8, 5)), stage0_area_weight=[.01, .02, .03, .04], ) config = yolo_rl.good_config.copy( prepare_func=prepare_func, patience=10000, render_step=100000, lr_schedule=1e-4, max_overlap=40, hooks=[], n_val=16, eval_step=1000, max_steps=100000, fixed_values=dict(), curriculum=[ dict(fixed_values=dict(obj=1), max_steps=10000), dict(obj_exploration=0.2,), dict(obj_exploration=0.1,), dict(obj_exploration=0.1, lr_schedule=1e-5), dict(obj_exploration=0.1, lr_schedule=1e-6), ], ) # Create the datasets if necessary. with config: train = EmnistObjectDetectionDataset(n_examples=int(config.n_train), shuffle=True, example_range=(0.0, 0.9)) val = EmnistObjectDetectionDataset(n_examples=int(config.n_val), shuffle=True, example_range=(0.9, 1.)) from dps.hyper import build_and_submit clify.wrap_function(build_and_submit)(config=config, distributions=distributions)
import xml_path import uuid from numpy import logical_and import pandas as pd from datetime import timedelta import init_data_struct as ids # all eval_ methods def eval_leg_type_error(leg): leg_type = xml_path.get_leg_type(leg) if leg_type == 'OEV': # previously get_leg_route_category(), shoiuld be identical (todo check!) leg_subtype = xml_path.get_leg_route_category(leg) if leg_subtype in ['bus', 'nfb']: # bus, skip segments but keep leg leg_type_anomaly = 'OEV - BUS ({t})'.format(t=leg_subtype) elif leg_subtype in ['t', 'nft']: # tram, skip segments but keep leg leg_type_anomaly = 'OEV - TRAM ({t})'.format(t=leg_subtype) else: leg_type_anomaly = '' else: leg_type_anomaly = leg_type return leg_type_anomaly def eval_leg_route_name(legs_df): # initialize and ensures str() rather than NaN-float legs_df['route_name'] = legs_df['route_category'] + ' ' # unlike previous version of code, this is a Null value and not a 'None' str mask = legs_df['route_line'].isnull() legs_df.ix[mask, 'route_name'] += legs_df.ix[mask, 'route_number'] legs_df.ix[~mask, 'route_name'] += legs_df.ix[~mask, 'route_line'] return def eval_nat_replace(segments_df): # set start time to end time if missing segments_df.loc[segments_df['time_start'].isnull(), 'time_start'] = \ segments_df.loc[segments_df['time_start'].isnull(), 'time_end'] # set end time to start time if missing segments_df.loc[segments_df['time_end'].isnull(), 'time_end'] = \ segments_df.loc[segments_df['time_end'].isnull(), 'time_start'] return def eval_segment_is_waypoint(segments_df): segments_df['waypoint'] = segments_df['node'].apply(xml_path.get_seg_type) != 'STATION' segments_df.loc[(segments_df['time_start'].isnull() & segments_df['time_end'].isnull()), 'waypoint'] = True return def add_moving_segments(segments_df, legs_df, trip_link_df, CONFIG): """ Segments are only the static stays at the station, and their IDs are all even. Adds odd-numbered movements segments that link station stops. Updates the trip_link_df with the new IDs :param segments_df: :param legs_df: :param trip_link_df: :param CONFIG: :return: """ # TODO test that waypoint inclusion works well leg_subset = legs_df.loc[legs_df['leg_type'] == '', ['leg_number']] seg_subset = segments_df.loc[~segments_df['waypoint'], ['segment_number', 'time_start', 'time_end', 'stop_id_start', 'stop_id_end']] merged = pd.merge(trip_link_df, leg_subset, left_on='leg_id', right_index=True, suffixes=('', '_leg'), sort=False) merged = pd.merge(merged, seg_subset, left_on='segment_id', right_index=True, suffixes=('', '_seg'), sort=False) # values need to be ordered before using .shift() merged.sort_values(['itinerary_id', 'leg_number', 'segment_number'], ascending=True, inplace=True) # Pads with START_TRIP_BUFFER the 1st and last segment to include the wait at station. time_buffer = timedelta(seconds=int(CONFIG.get('params', 'START_TRIP_BUFFER'))) merged_groupby = merged.copy().groupby('itinerary_id') # TODO -- why is COPY needed? first_pts_list = merged_groupby['segment_id'].first() segments_df.loc[first_pts_list.values, 'time_start'] = segments_df.loc[first_pts_list.values, 'time_end']\ - time_buffer last_pts_list = merged_groupby['segment_id'].last() segments_df.loc[last_pts_list.values, 'time_end'] = segments_df.loc[last_pts_list.values, 'time_start'] \ + time_buffer # starts from the end of previous segment and goes to start of next one temp_col_names = {'time_end': 'time_start', 'stop_id_end': 'stop_id_start', 'time_start': 'time_end', 'stop_id_start': 'stop_id_end' } merged.rename(columns=temp_col_names, inplace=True) merged[['time_end', 'stop_id_end']] = merged[['time_end', 'stop_id_end']].shift(-1).values merged['segment_number'] += 1 # Drop segments that link different itineraries merged = merged[merged['itinerary_id'] == merged['itinerary_id'].shift(-1)] # Initialize new uuid for the segments that were created merged['segment_id'] = [str(uuid.uuid4()) for i in range(merged['segment_id'].shape[0])] merged['waypoint'] = False new_seg_view = merged[['segment_id', 'segment_number', 'time_start', 'time_end', 'stop_id_start', 'stop_id_end', 'waypoint']] new_segments = ids.init_segments_df(values=new_seg_view, set_index=True, drop_node=True) segments_df = pd.concat([segments_df, new_segments]) trip_link_df = pd.concat([trip_link_df, merged[trip_link_df.columns]]) # Identify long_pause segments # # (these are weighted more heavily later because 'static' points are deemed more reliable) train_long_stop_threshold = timedelta(seconds=int(CONFIG.get('params', 'TRAIN_LONG_STOP_THRESHOLD'))) segments_df['is_long_stop'] = logical_and( (segments_df['time_end'] - segments_df['time_start']) >= train_long_stop_threshold, (segments_df['segment_number'] % 2) == 0) return segments_df, trip_link_df def eval_n_leg(trip_link_df, itinerary_df, legs_df): """ This currently calculates all legs, including those labeled as 'FUSSWEG' ot other ones to be skipped... :param trip_link_df: :param itinerary_df: :param legs_df: :return: """ # takes only legs that are well conditioned leg_mask = trip_link_df['leg_id'].isin(legs_df[legs_df['leg_type'] == ''].index) # count legs leg_count = trip_link_df.loc[leg_mask, ['itinerary_id', 'leg_id']].groupby('itinerary_id')['leg_id'].nunique() itinerary_df['num_legs'] = leg_count # Itineraries that have 0 legs won't get counted to fill NaN with 0 itinerary_df['num_legs'].fillna(0, inplace=True) return def eval_n_seg(trip_link_df, legs_df, segments_df, seg_count_name): # Takes only segments that are not way points seg_mask = trip_link_df['segment_id'].isin(segments_df[~segments_df['waypoint']].index) # Count segments seg_count = trip_link_df.loc[seg_mask, ['leg_id', 'segment_id']].groupby('leg_id').count() seg_count.rename(columns={'segment_id': 'num_legs'}, inplace=True) legs_df[seg_count_name] = seg_count # Legs that have 0 segments won't get counted to fill NaN with 0 legs_df[seg_count_name].fillna(0, inplace=True) return
import unittest from katas.beta.what_day_is_it import day class DayTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(day('20151208'), 'Tuesday') def test_equals_2(self): self.assertEqual(day('20140728'), 'Monday') def test_equals_3(self): self.assertEqual(day('20160229'), 'Monday') def test_equals_4(self): self.assertEqual(day('20160301'), 'Tuesday') def test_equals_5(self): self.assertEqual(day('19000228'), 'Wednesday') def test_equals_6(self): self.assertEqual(day('19000301'), 'Thursday')
from os import times_result import composite as cp import filter import get_VIs as vi import harmonize import export_as_geotiff as exp import ee def wrapper_prep(params): ''' This function prepares each Landsat collection for merging by filtering for appropriate parameters and harmonizing collection Args: imgCollection (ee.ImageCollection): raw Landsat image collection params (dictionary): parameters to extract image collection of vegetation indices from Landsat image collection Returns: filtered_collection (ee.ImageCollection): filtered and harmonized image collection ''' # extract params IMAGE_COLLECTION = params['IMAGE_COLLECTION'] FILTER_POINT = params['FILTER_POINT'] LANDSAT_SAT = params['LANDSAT_SAT'] CLOUD_COVER_OVER_LAND = params['CLOUD_COVER_OVER_LAND'] IMAGE_QUALITY = params['IMAGE_QUALITY'] GEOMETRIC_RMSE = params['GEOMETRIC_RMSE'] good_landsat_names = ['LS5', 'LS7', 'LS8'] if LANDSAT_SAT not in good_landsat_names: raise ValueError("Inappropriate landsat name!") if LANDSAT_SAT == 'LS5' or LANDSAT_SAT == 'LS7': HARMONIZE_FUNC = harmonize.harmonizeEtm elif LANDSAT_SAT == 'LS8': HARMONIZE_FUNC = harmonize.prepOli # filter and harmonize filtered_harmonized_collection = filter.filter_collection(imgCollection=IMAGE_COLLECTION, filterpoint=FILTER_POINT, landsat_sat= LANDSAT_SAT, harmonizefunc=HARMONIZE_FUNC, # harmonize cloudcover=CLOUD_COVER_OVER_LAND, img_qual=IMAGE_QUALITY, rmse=GEOMETRIC_RMSE) return filtered_harmonized_collection def wrapper_VI(prepped_LS5, prepped_LS7, prepped_LS8): ''' Merges, adds vegetation indices, selects growing season, and creates annual median composites Args: prepped_LS5 (ee.ImageCollection): filtered and harmonization Landsat 5 image collection prepped_LS7 (ee.ImageCollection): filtered and harmonization Landsat 7 image collection prepped_LS8 (ee.ImageCollection): filtered and harmonization Landsat 8 image collection Returns: annual_median_composites (ee.ImageCollection): annual median composites ''' # merges all landsat collection all_LS = prepped_LS5.merge(prepped_LS7).merge(prepped_LS8) # adds vegetation indices as bands to image collection all_LS = all_LS.map(vi.getNDVI).map(vi.getNBR).map(vi.getSAVI) # select only growing season growing_LS = all_LS.filter(ee.Filter.calendarRange(6, 9, 'month')) # create annual median composites annual_median_composites = cp.median_composite(growing_LS) return annual_median_composites # print(growing_LS.size().getInfo()) def test(a, b): print("TESTING: ", a*b)
import sponsorapp.views as sponsorapp from django.urls import path app_name = 'sponsorapp' urlpatterns = [ path('sponsor/', sponsorapp.sponsor, name='sponsor'), ]
import pytube from pytube.cli import on_progress url = input("Input video's url: ") video = pytube.YouTube(url, on_progress_callback=on_progress) stream = video.streams.get_highest_resolution() stream.download('C:\\Users\\Workspace\\Downloads') print('Done!')
import unittest from katas.kyu_6.next_version import next_version class NextVersionTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(next_version('1.2.3'), '1.2.4') def test_equals_2(self): self.assertEqual(next_version('0.9.9'), '1.0.0') def test_equals_3(self): self.assertEqual(next_version('1'), '2') def test_equals_4(self): self.assertEqual(next_version('1.2.3.4.5.6.7.8'), '1.2.3.4.5.6.7.9') def test_equals_5(self): self.assertEqual(next_version('9.9'), '10.0')
def get_diagonal(arr): index = 0 diagonal = [] for row in arr: number = row[index] diagonal.append(number) index += 1 return diagonal def diagonal_difference(arr): first_diagonal = get_diagonal(arr) arr.reverse() second_diagonal = get_diagonal(arr) return abs(sum(first_diagonal) - sum(second_diagonal)) count_rows = int(input()) array = [] for _ in range(count_rows): row = list(map(int, input().split())) array.append(row) print(diagonal_difference(array))
from Geometry import Point, Rectangle def main(): p1 = Point(2,5) p2 = Point(5,6) r1 = Rectangle(p1,p2) print("Area=" + str(r1.getArea())) print("Perimeter=" + str(r1.getPerimeter())) r1.dilate(3) print("\nDilated by 3") print("Area=" + str(r1.getArea())) print("Perimeter=" + str(r1.getPerimeter())) r1.translate(-10,3) print("\nTranslated!") print("Area=" + str(r1.getArea())) print("Perimeter=" + str(r1.getPerimeter())) print(r1) main()
import math import numpy as np def similarity(v1, v2): dot = np.dot(v1, v2) mag1 = np.linalg.norm(v1) mag2 = np.linalg.norm(v2) return dot / (mag1 * mag2) def angle(v1, v2): sim = similarity(v1, v2) return math.degrees(math.acos(sim)) def mbti_similarity(mbti1, mbti2): m1 = np.array(mbti1) m2 = np.array(mbti2) m1 = m1 - 0.5 m2 = m2 - 0.5 return math.fabs(angle(m1, m2)) if __name__ == "__main__": mbti1_str = input("mbti 1의 E. N. T. J의 함량을 입력하세요") mbti2_str = input("mbti 2의 E. N. T. J의 함량을 입력하세요") mbti1 = [float(x) for x in mbti1_str.split()] mbti2 = [float(x) for x in mbti2_str.split()] deg = mbti_similarity(mbti1, mbti2) print("각도(0-180):", deg)
from matplotlib import pyplot as plt def smooth_line(li,size): retract = (size-1)//2 for i in range(retract,len(li)-retract): li[i] = sum(li[i-retract:i+retract])/size return li def draw_loss(losslist,epoch,savepath): plt.rcParams['font.sans-serif'] = ['KaiTi'] plt.rcParams['axes.unicode_minus'] = False temp_color_x = [x+1 for x in range(len(losslist))] losslist = smooth_line(losslist,100) plt.plot(temp_color_x,losslist) plt.xticks(range(0,len(losslist),5*len(losslist)//epoch),range(0,epoch,5)) plt.savefig(savepath) print("已经保存损失变化图像%s"%(savepath)) pass
#!/usr/bin/env python #-*-coding:utf-8-*- # @File:adaboost_model.py # @Author: Michael.liu # @Date:2020/6/18 17:36 # @Desc: this code is .... import numpy as np import pandas as pd import time import json import matplotlib.pyplot as plt from sklearn.ensemble import AdaBoostClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.datasets import make_gaussian_quantiles from sklearn.externals import joblib class AdaBoostModel(object): train_df = None vali_df = None test_df = None model = None def __init__(self,args): self.args = args with open(args.config_path, "r", encoding="utf8") as fr: self.config = json.load(fr) self.train_file = self.config["adt_train_file"] self.vali_file= self.config["adt_vali_file"] self.test_file = self.config["adt_test_file"] def load_train_data(self, names): self.train_df = pd.read_csv(self.train_file, names=names, sep=',') def load_vali_data(self, names): self.vali_df = pd.read_csv(self.vali_file, names=names, sep=',') def load_test_data(self, names): self.test_df = pd.read_csv(self.test_file, names=names, sep=',') def train(self, feature_head, target_head): t_start = time.time() x_train = self.train_df[feature_head] y_train = self.train_df[target_head] x_test = self.test_df[feature_head] y_test = self.test_df[target_head] bdt = AdaBoostClassifier(DecisionTreeClassifier(max_depth=self.config["adt_max_depth"], min_samples_split=self.config["adt_min_samples_split"], min_samples_leaf=self.config["adt_min_samples_leaf"]), algorithm = self.config["adt_algorithm"], n_estimators = self.cofig["adt_n_estimators"], learning_rate = self.config["adt_learning_rate"]) bdt.fit(x_train, y_train) print('Accuracy of Adaboost Classifier:%f' % bdt.score(x_test, y_test)) joblib.dump(bdt, 'gen_bdt.pkl') self.model = bdt print('cost the time %s' % (time.time() - t_start)) def infer(self, feature_head, target_head, model_path=None): t_start = time.time() if model_path != None: self.model = joblib.load(model_path) x_vali = self.vali_df[feature_head] y_vali = self.vali_df[target_head] print('Accuracy of Adaboost Classifier:%f' % self.model.score(x_vali, y_vali))
from django import forms from .models import Feature class featureForm(forms.ModelForm): class Meta: model = Feature fields = ('featureName','description') labels = { 'featureName': 'Title' }
import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from dsn.util.systems import LowRankRNN from dsn.train_dsn import train_dsn import pandas as pd import scipy.stats import sys, os os.chdir("../") nlayers = int(sys.argv[1]) c_init_order = int(sys.argv[2]) sigma_init = float(sys.argv[3]) random_seed = int(sys.argv[4]) # create an instance of the V1_circuit system class fixed_params = {'g':0.8, 'rhom':3.0, 'rhon':1.38, 'betam':0.6, 'betan':1.0} behavior_type = "CDD" means = np.array([0.3, 0.3]) variances = np.array([0.001, 0.001]) behavior = {"type": behavior_type, "means": means, "variances": variances} # set model options model_opts = {"rank": 2, "input_type": "input"} system = LowRankRNN( fixed_params, behavior, model_opts=model_opts, solve_its=25, solve_eps=0.5 ) # set up DSN architecture latent_dynamics = None TIF_flow_type = "PlanarFlow" mult_and_shift = "post" arch_dict = { "D": system.D, "latent_dynamics": latent_dynamics, "mult_and_shift": mult_and_shift, "TIF_flow_type": TIF_flow_type, "repeats": nlayers, } k_max = 40 batch_size = 1000 lr_order = -3 min_iters = 1000 max_iters = 2000 train_dsn( system, batch_size, arch_dict, k_max=k_max, sigma_init=sigma_init, c_init_order=c_init_order, lr_order=lr_order, random_seed=random_seed, min_iters=min_iters, max_iters=max_iters, check_rate=100, dir_str="test", )
import cv2 import numpy as np def hsv_shadow_remove(frame_rgb, background_rgb): #Define variable alpha = 0.4 beta = 0.6 th = 0.1 ts = 0.5 #CHANGE THE INITIALIZATION foreground_without_shadows = [] hsv_frame = cv2.cvtColor(frame_rgb, cv2.COLOR_RGB2HSV) hsv_background = cv2.cvtColor(background_rgb, cv2.COLOR_RGB2HSV) #Conditions to fulfill #Pixel is considered shadow if it fulfills these 3 conditions cond1 = np.divide(hsv_frame[:, :, 2], hsv_background[:, :, 2]) condition1 = (cond1 >= alpha) condition2 = (cond1 <= beta) condition3 = (hsv_frame[:, :, 1]-hsv_background[:, :, 1] <= ts) condition4 = (hsv_frame[:, :, 0]-hsv_background[:, :, 0] <= th) shadow_mask = np.bitwise_and(np.bitwise_and(condition1, condition2), np.bitwise_and(condition3, condition4)) # Return Boolean mask return shadow_mask
import os wpos_x = 100 wpos_y = 100 os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (wpos_x,wpos_y) import pygame from pygame.locals import * import random text_size = 60 bg_col = (0,0,0) text_col = (255,255,255) w_width = 640 w_height = 480 try: pygame.init() w = pygame.display.set_mode((w_width,w_height)) # create font object myfont = pygame.font.Font(None, text_size) # uses default pygame font # create text images text_go = myfont.render('GO!', True, text_col, bg_col) rect_go = text_go.get_rect() # get the rectangle around the text text_end = myfont.render('DONE!', True, text_col, bg_col) rect_end = text_end.get_rect() # get the rectangle around the text # centering rect_go.center =rect_end.center = [w_width/2, w_height/2] w.fill(bg_col) pygame.display.flip() pygame.time.wait(1000+random.randint(0,1000)) w.blit(text_go, rect_go) pygame.display.flip() t0 = pygame.time.get_ticks() while True: e = pygame.event.poll() if e.type == KEYDOWN and e.key == K_SPACE: t = pygame.time.get_ticks() - t0 print "Reaction Time = {} ms".format(t) w.blit(text_end, rect_end) pygame.display.flip() pygame.time.wait(1000) break finally: pygame.quit()
#!/usr/bin/env python # -*- coding: utf-8 -*- # 打印 print "hello wrold!" print "hello Again" print "I like typing this." print "this is fun" print "Yay,printing." print "I'd much rather you 'not'" print 'I "sad " do not touch this' print "this is another line"
# -*- coding: utf-8 -*- class Solution: def arrayNesting(self, nums): result = 0 for num in nums: if num is None: continue current, length = num, 0 while nums[current] is not None: previous = current current = nums[current] nums[previous] = None length += 1 result = max(result, length) return result if __name__ == "__main__": solution = Solution() assert 4 == solution.arrayNesting([5, 4, 0, 3, 1, 6, 2])
print('Faça um programa que leia tres numeros e mostre qual é o maior e qual é o menor') n1 = int(input('Escreva um número: ')) n2 = int(input('Escreva um número: ')) n3 = int(input('Escreva um número: ')) print('O maior número desses é o {}'.format(max(n1, n2, n3))) print('O menor número desses é o {}'.format(min(n1, n2, n3)))
name = input("Enter Name: ") age = input("Enter Age: ") print('Name: ', name) print('Age after 2 years: ', int(age) + 2)
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from typing import List, Optional, Tuple import numpy as np from gym import spaces from gym.core import Env from mtenv.utils import seeding from mtenv.utils.types import ActionType, DoneType, EnvObsType, InfoType, RewardType StepReturnType = Tuple[EnvObsType, RewardType, DoneType, InfoType] class BanditEnv(Env): # type: ignore[misc] # Class cannot subclass 'Env' (has type 'Any') def __init__(self, n_arms: int): self.n_arms = n_arms self.action_space = spaces.Discrete(n_arms) self.observation_space = spaces.Box( low=0.0, high=1.0, shape=(1,), dtype=np.float32 ) self.reward_probability = spaces.Box( low=0.0, high=1.0, shape=(self.n_arms,) ).sample() def seed(self, seed: Optional[int] = None) -> List[int]: self.np_random_env, seed = seeding.np_random(seed) assert isinstance(seed, int) return [seed] def reset(self) -> EnvObsType: return np.asarray([0.0]) def step(self, action: ActionType) -> StepReturnType: sample = self.np_random_env.rand() reward = 0.0 if sample < self.reward_probability[action]: reward = 1.0 return np.asarray([0.0]), reward, False, {} def run() -> None: env = BanditEnv(5) env.seed(seed=5) for episode in range(3): print("=== episode " + str(episode)) print(env.reset()) for _ in range(5): action = env.action_space.sample() print(env.step(action)) if __name__ == "__main__": run()
import turtle import math # class circle class Circle: def __init__(self,snow,radius,x,y): snow.snowmani.up() #set the initial absolute direction of turtle snow.snowmani.sety(y) #set the x and y coordinates of the turtle.These will act as initial points.Could have used goto too here. snow.snowmani.setx(x) arc_length=1*(math.pi/180)*radius#mathematical stuff.This is basically the arc length corresponding to the said radius.Many lines will be drawn.Which will give the illusion of circle. snow.snowmani.down() #ready to draw a circle. snow.snowmani.begin_fill() #We also have to fill white color for i in range(360): #a circle is a 360 degree figure. snow.snowmani.forward(arc_length) #make the line.This will be a small line.Many lines will be joined giving the illusion of circle. snow.snowmani.left(1) #turn the turtle. snow.snowmani.up()#reset the direction snow.snowmani.end_fill() #finish the filling. class Arm: def __init__(self,snow,x,y,length,heading,color="black"): snow.snowmani.up() #Same drill as above snow.snowmani.goto(x,y) # goto the starting point. snow.snowmani.color(color) #set the color of turtle. snow.snowmani.setheading(heading) #set the destination of arm snow.snowmani.down() #set the direction of turtle. snow.snowmani.forward(length) #Go forward. snow.snowmani.setheading(heading+20) snow.snowmani.forward(20) snow.snowmani.up() snow.snowmani.back(20) snow.snowmani.down() snow.snowmani.setheading(heading-20) snow.snowmani.forward(20) snow.snowmani.up() snow.snowmani.home() snow.snowmani.color("black") #reset the color. class Face: def __init__(self,snow,x,y,color="black",flag=False): snow.snowmani.up() snow.snowmani.goto(x+10,y) snow.snowmani.dot() snow.snowmani.goto(x-10,y) snow.snowmani.dot() snow.snowmani.goto(x,y-10) snow.snowmani.dot() snow.snowmani.goto(x-15,y-25) snow.snowmani.down() snow.snowmani.up() self.snowmani1=turtle.Turtle() self.snowmani1.penup() self.snowmani1.goto(x,y) self.snowmani1.pendown() self.snowmani1.color(color) self.snowmani1.fillcolor(color) arc_length=1*(math.pi/180)*10 self.snowmani1.down() self.snowmani1.right(90) for i in range(180): self.snowmani1.forward(arc_length) self.snowmani1.left(1) if flag: #if flag is true ,i.e,this is snowwoman than draw girlish lips. self.snowmani1.begin_fill() i=x+14 j=y-10 Circle(self,5,i,j) self.snowmani1.end_fill() hide(self.snowmani1) class Button: def __init__(self,x,y,radius,color="black"): self.snowmani=turtle.Turtle() self.x=x self.y=y self.snowmani.fillcolor(color) hide(self.snowmani) Circle(self,radius,self.x,self.y) class Rectangle: def __init__(self,x,y,width,height,color="red"): self.snowmani=turtle.Turtle() self.snowmani.fillcolor(color) self.snowmani.color(color) hide(self.snowmani) self.snowmani.begin_fill() self.snowmani.penup() # Pull the pen up self.snowmani.goto(x + width / 2, y + height / 2)#again mathematically when you solve the equation you get these formulas to draw the hat. self.snowmani.pendown() # Pull the pen down self.snowmani.right(90) self.snowmani.forward(height) self.snowmani.right(90) self.snowmani.forward(width) self.snowmani.right(90) self.snowmani.forward(height) self.snowmani.right(90) self.snowmani.forward(width) self.snowmani.end_fill() class Triangle: def __init__(self,x,y,color="yellow"): self.snowmani=turtle.Turtle() self.snowmani.fillcolor(color) self.snowmani.color(color) hide(self.snowmani) steps=100 # random steps choosen. self.snowmani.begin_fill() self.snowmani.penup() self.snowmani.goto(x,y) self.snowmani.forward(steps) self.snowmani.left(120) self.snowmani.forward(steps) self.snowmani.left(120) self.snowmani.forward(steps) self.snowmani.left(200) self.snowmani.end_fill() class Hair: def __init__(self,x,y): self.snowmani=turtle.Turtle() self.snowmani.pensize(2) self.snowmani.fillcolor("red") self.snowmani.color("red") hide(self.snowmani) self.snowmani.penup() self.snowmani.goto(x-30,y-5) self.snowmani.pendown() self.snowmani.right(100) self.snowmani.forward(40) self.snowmani.penup() self.snowmani.goto(x-25,y-5) self.snowmani.pendown() self.snowmani.left(10) self.snowmani.forward(30) self.snowmani.penup() self.snowmani.goto(x+25,y-5) self.snowmani.pendown() # self.snowmani.left(100) self.snowmani.forward(40) self.snowmani.penup() self.snowmani.goto(x+30,y-5) self.snowmani.pendown() self.snowmani.left(10) self.snowmani.forward(30) # class Snowman class Snowperson: def __init__(self,x,y,color="white"): self.start_x=x self.start_y=y self.snowmani=turtle.Turtle() self.snowmani.fillcolor(color) self.snowmani.speed(0) hide(self.snowmani) def draw(self): Circle(self,40,self.start_x,self.start_y) #head Face(self,self.start_x,self.start_y+50) # Hair(self.start_x,self.start_y+80) Circle(self,70,self.start_x,self.start_y-140) #upper torso Circle(self,100,self.start_x,self.start_y-340) #lower torso Arm(self,self.start_x-70,self.start_y-70,50,160) #left arm Arm(self,self.start_x+70,self.start_y-70,50,20) #right arm Button(self.start_x,self.start_y-30,10) #topmost button Button(self.start_x,self.start_y-60,10) #second button Button(self.start_x,self.start_y-170,10) #first button Button(self.start_x,self.start_y-280,10) #second button def __str__(self): return "this is snowperson" class Snowman: def __init__(self,x,y,color="white"): self.start_x=x self.start_y=y self.snowmani=turtle.Turtle() self.snowmani.fillcolor(color) hide(self.snowmani) def draw(self): Circle(self,40,self.start_x,self.start_y) #head Rectangle(self.start_x,self.start_y+80,100,5) #hat below Rectangle(self.start_x,self.start_y+130,60,100) #hat above Circle(self,70,self.start_x,self.start_y-140) #upper torso Circle(self,100,self.start_x,self.start_y-340) #lower torso Arm(self,self.start_x-70,self.start_y-70,50,160,"red") #left arm Arm(self,self.start_x+70,self.start_y-70,50,20,"red") #right arm Face(self,self.start_x,self.start_y+50) #face Button(self.start_x,self.start_y-30,10,"grey") #topmost button Button(self.start_x,self.start_y-60,10,"grey") #second button Button(self.start_x,self.start_y-170,10,"grey") #first button Button(self.start_x,self.start_y-280,10,"grey") #second button def __str__(self): return "this is snowman" class Snowwoman: def __init__(self,x,y,color="white"): self.start_x=x self.start_y=y self.snowmani=turtle.Turtle() self.snowmani.fillcolor(color) hide(self.snowmani) def draw(self): Circle(self,40,self.start_x,self.start_y) #head Circle(self,70,self.start_x,self.start_y-140) #upper torso Circle(self,100,self.start_x,self.start_y-340) #lower torso Arm(self,self.start_x-70,self.start_y-70,50,160,"red") #left arm Arm(self,self.start_x+70,self.start_y-70,50,20,"red") #right arm Face(self,self.start_x,self.start_y+50,"red",True) #face Button(self.start_x,self.start_y-30,10,"yellow") #topmost button Button(self.start_x,self.start_y-60,10,"purple") #second button Button(self.start_x,self.start_y-170,10,"yellow") #first button Button(self.start_x,self.start_y-280,10,"purple") #second button Triangle(self.start_x-50,self.start_y+75) Hair(self.start_x,self.start_y+80) def __str__(self): return "this is snowwomen" class Screen(): """ This is to manipulate the screen object. """ def __init__(self): self.screen=turtle.Screen() def wait(self): self.screen.exitonclick() def putitle(self,string): """ What to write when the drawing part of the program is completed. """ self.screen.title(string) def hide(turtle): turtle.hideturtle() if __name__=="__main__": snowperson=Snowperson(-500,100) snowperson.draw() snowman=Snowman(-100,100) snowman.draw() snowwoman=Snowwoman(300,100) snowwoman.draw() screen=Screen() screen.putitle("Three snowpeople") screen.wait()