content
stringlengths
7
1.05M
STREAM_ERROR_SOURCE_USER = "stream_error_source_user" STREAM_ERROR_SOURCE_STREAM_PUMP = "stream_error_source_stream_pump" STREAM_ERROR_SOURCE_SUBSCRIPTION_GAZE_DATA = "stream_error_source_subscription_gaze_data" STREAM_ERROR_SOURCE_SUBSCRIPTION_USER_POSITION_GUIDE = "stream_error_source_subscription_user_position_guide" STREAM_ERROR_SOURCE_SUBSCRIPTION_EXTERNAL_SIGNAL = "stream_error_source_subscription_external_signal" STREAM_ERROR_SOURCE_SUBSCRIPTION_TIME_SYNCHRONIZATION_DATA = \ "stream_error_source_subscription_time_synchronization_data" STREAM_ERROR_SOURCE_SUBSCRIPTION_EYE_IMAGE = "stream_error_source_subscription_eye_image" STREAM_ERROR_SOURCE_SUBSCRIPTION_NOTIFICATION = "stream_error_source_subscription_notification" STREAM_ERROR_CONNECTION_LOST = "stream_error_connection_lost" STREAM_ERROR_INSUFFICIENT_LICENSE = "stream_error_insufficient_license" STREAM_ERROR_NOT_SUPPORTED = "stream_error_not_supported" STREAM_ERROR_TOO_MANY_SUBSCRIBERS = "stream_error_too_many_subscribers" STREAM_ERROR_INTERNAL_ERROR = "stream_error_internal_error" STREAM_ERROR_USER_ERROR = "stream_error_user_error" class StreamErrorData(object): '''Provides information about a stream error. ''' def __init__(self, data): if not isinstance(data, dict): raise ValueError("You shouldn't create StreamErrorData objects yourself.") self._system_time_stamp = data["system_time_stamp"] self._error = data["error"] self._source = data["source"] self._message = data["message"] @property def system_time_stamp(self): return self._system_time_stamp @property def source(self): return self._source @property def error(self): return self._error @property def message(self): return self._message
"""Filter Package -------------- This package is the root module for spectral filtering utilities. """
def digit_sum(num: str): res = 0 for c in num: res += int(c) return res def digit_prod(num: str): res = 1 for c in num: res *= int(c) return res def main(): memo = {} T = int(input()) for t in range(1, T + 1): A, B = [int(x) for x in input().split(" ")] res = 0 for num in range(A, B + 1): num_str = "".join(sorted(str(num))) if num_str not in memo: memo[num_str] = digit_prod(num_str) % digit_sum(num_str) == 0 if memo[num_str]: res += 1 print(f"Case #{t}: {res}") if __name__ == "__main__": main()
"""Organizations package. Modules: organizations shortname_orgs """
BOT_TOKEN = "1910688339:AAG0t3dMaraOL9u31bkjMEbFcMPy-Pl6rA8" RESULTS_COUNT = 4 # NOTE Number of results to show, 4 is better SUDO_CHATS_ID = [1731097588, -1005456463651] DRIVE_NAME = [ "Root", # folder 1 name "Cartoon", # folder 2 name "Course", # folder 3 name "Movies", # .... "Series", # ...... "Others" # and soo onnnn folder n names ] DRIVE_ID = [ "0AHQOFQWVW-LiUk9PVA", # folder 1 id "0AKqQHy-eIErTUk9PVA", # folder 2 id "0AITVP56KLmIIUk9PVA", # and so onn... folder n id "10_hTMK8HE8k144wOTth_3x1hC2kZL-LR", "1-oTctBpyFcydDNiptLL09Enwte0dClCq", "1B9A3QqQqF31IuW2om3Qhr-wkiVLloxw8" ] INDEX_URL = [ "https://vc.vc007.workers.dev/0:", # folder 1 index link "https://vc.vc007.workers.dev/1:/Animated", # folder 2 index link "https://vc.vc007.workers.dev/2:", # and soo on folder n link "https://vc.vc007.workers.dev/1:/Movies", "https://vc.vc007.workers.dev/1:/Series", "https://dl.null.tech/0:/Roms" ]
if __name__ == '__main__': n = int(input()) i = 0 while n > 0: print(i ** 2) i = i + 1 n = n - 1
""" # LARGEST NUMBER Given a list of non-negative integers nums, arrange them such that they form the largest number. Note: The result may be very large, so you need to return a string instead of an integer. Example 1: Input: nums = [10,2] Output: "210" Example 2: Input: nums = [3,30,34,5,9] Output: "9534330" Example 3: Input: nums = [1] Output: "1" Example 4: Input: nums = [10] Output: "10" Constraints: 1 <= nums.length <= 100 0 <= nums[i] <= 109 """ class LargerNumKey(str): """def __lt__(x, y): return x+y > y+x""" class Solution: def largestNumber(self, nums): largest_num = ''.join(sorted(map(str, nums), key=LargerNumKey)) return '0' if largest_num[0] == '0' else largest_num
#11. Find GCD of two given Numbers. m = int(input("Enter the First Number: ")) n = int(input("Enter the Second Number: ")) r = m while(m!=n): if(m>n): m=m-n else: n=n-m print("G.C.D is ",m)
############ ## Solution ############ def e_step(Y, psi, A, L, dt): """ Args: Y (numpy 3d array): tensor of recordings, has shape (n_trials, T, C) psi (numpy vector): initial probabilities for each state A (numpy matrix): transition matrix, A[i,j] represents the prob to switch from i to j. Has shape (K,K) L (numpy matrix): Poisson rate parameter for different cells. Has shape (C,K) dt (float): duration of a time bin Returns: ll (float): data log likelihood gamma (numpy 3d array): singleton marginal distribution. Has shape (n_trials, T, K) xi (numpy 4d array): pairwise marginal distribution for adjacent nodes . Has shape (n_trials, T-1, K, K) """ n_trials = Y.shape[0] T = Y.shape[1] K = psi.size log_a = np.zeros((n_trials, T, K)) log_b = np.zeros((n_trials, T, K)) log_A = np.log(A) log_obs = ss.poisson(L * dt).logpmf(Y[..., None]).sum(-2) # n_trials, T, K # forward pass log_a[:, 0] = log_obs[:, 0] + np.log(psi) for t in range(1, T): tmp = log_A + log_a[:, t - 1, :,None] # (n_trials, K,K) maxtmp = tmp.max(-2) # (n_trials,K) log_a[:, t] = log_obs[:, t] + maxtmp + np.log(np.exp(tmp - maxtmp[:, None]).sum(-2)) # backward pass for t in range(T - 2, -1, -1): # tmp = log_A + log_b[:, t + 1, None] + log_obs[:, t + 1, :, None] tmp = log_A + log_b[:, t + 1, None] + log_obs[:, t + 1, None] maxtmp = tmp.max(-1) log_b[:, t] = maxtmp + np.log(np.exp(tmp - maxtmp[..., None]).sum(-1)) # data log likelihood maxtmp = log_a[:, -1].max(-1) ll = np.log(np.exp(log_a[:, -1] - maxtmp[:, None]).sum(-1)) + maxtmp # singleton and pairwise marginal distributions gamma = np.exp(log_a + log_b - ll[:, None, None]) xi = np.exp(log_a[:, :-1, :, None] + (log_obs + log_b)[:, 1:, None] + log_A - ll[:, None, None, None]) return ll.mean() / T / dt, gamma, xi
#Shipping Accounts App #Define list of users users = ['eramom', 'footea', 'davisv', 'papinukt', 'allenj', 'eliasro'] print("Welcome to the Shipping Accounts Program.") #Get user input username = input("\nHello, what is your username: ").lower().strip() #User is in list.... if username in users: #print a price summary print("\nHello " + username + ". Welcome back to your account.") print("Current shipping prices are as follows:") print("\nShipping orders 0 to 100: \t\t$5.10 each") print("Shipping orders 100 to 500: \t\t$5.00 each") print("Shipping orders 500 to 1000 \t\t$4.95 each") print("Shipping orders over 1000: \t\t$4.80 each") #Determine price based on how many items are shipped quantity = int(input("\nHow many items would you like to ship: ")) if quantity < 100: cost = 5.10 elif quantity < 500: cost = 5.00 elif quantity < 1000: cost = 4.95 else: cost = 4.80 #Display final cost bill = quantity*cost bill = round(bill, 2) print("To ship " + str(quantity) + " items it will cost you $" +str(bill) + " at $" + str(cost) + " per item.") #Place order choice = input("\nWould you like to place this order (y/n): ").lower() if choice.startswith('y'): print("OKAY. Shipping your " + str(quantity) + " items.") else: print("OKAY, no order is being placed at this time.") #The user is not in the list else: print("Sorry, you do not have an account with us. Goodbye...")
""" @author: lyh @time: 2020-08-15 @file:students @version:1.0 """ def func(): print("使用pycharm提交代码") func()
# A class to represent the adjacency list of the node class AdjNode: def __init__(self, data): self.vertex = data self.next = None class Graph: def __init__(self, vertices): self.V = vertices self.graph = [None] * self.V self.verticeslist = [] def add_edge(self, src, dest): self.verticeslist.append(src) self.verticeslist.append(dest) node = AdjNode(dest) node.next = self.graph[src] self.graph[src] = node # Adding the source node to the destination as # it is the undirected graph node = AdjNode(src) node.next = self.graph[dest] self.graph[dest] = node def adjacency_list(self): for i in range(self.V): print("Adjacency list of vertex {}\n head".format(i), end="") temp = self.graph[i] while temp: print(" -> {}".format(temp.vertex), end="") temp = temp.next print(" \n") # Saves space O(|V|+|E|) . In the worst case, there can be C(V, 2) number of edges in a graph thus consuming O(V^2) space. Adding a vertex is easier. def adjacency_matrix(self): self.verticeslist = set(self.verticeslist) print(self.verticeslist) print("ADJACENCY MATRIX for ") for i in self.verticeslist: d = [] print("I", i) temp = self.graph[i] while temp: d.append(temp.vertex) temp = temp.next print(d) if __name__ == "__main__": V = 5 graph = Graph(V) graph.add_edge(0, 1) graph.add_edge(0, 4) graph.add_edge(1, 2) graph.add_edge(1, 3) graph.add_edge(1, 4) graph.add_edge(2, 3) graph.add_edge(3, 4) # graph.adjacency_list() graph.adjacency_matrix()
""" Contains configurations options so secret, that they may not even be commited to git! """ ADMIN_PASSWORD = "secret" SECRET_KEY = "secret key"
description = 'Vaccum sensors and temperature control' devices = dict( vacuum=device( 'nicos_ess.estia.devices.pfeiffer.PfeifferTPG261', description='Pfeiffer TPG 261 vacuum gauge controller', hostport='192.168.1.254:4002', fmtstr='%.2E', ), )
#!/usr/bin/env python3 """ The copyrights of this software are owned by Duke University. Please refer to the LICENSE.txt and README.txt files for licensing instructions. The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent """ """ Welcome message for ASCENT software """ def welcome(): print(""" Funding for development of this software provided by NIH SPARC OT2 OD025340\n -+*+- -+++=: -: ====: .-==: -@= +@: *@::*@. :**. @#-=%# .@*-=@= :%# -. *@ =@: =**- @* *@ -@- +- =%#: *@==%% *+*+ @#==%* -@- -+ =@- *@--: :*:=*. @#-#% -@- =: :@* *@: *@ ++ .*- @* :@+ :@*:-@+ ---. :- .*- ++ +- -+ .=++- .......:::::::::::=* :*: ::::::::::........ -* + .*+ . """) print(""" The copyrights of this software are owned by Duke University. Please refer to the LICENSE.txt and README.txt files for licensing instructions.\n The source code can be found at the following GitHub repository: \nhttps://github.com/wmglab-duke/ascent --- """)
SECRET_KEY = "123" INSTALLED_APPS = [ 'sr' ] SR = { 'test1': 'Test1', 'test2': { 'test3': 'Test3', }, 'test4': { 'test4': 'Test4 {0} {1}', }, 'test5': { 'test5': "<b>foo</b>", } }
# coding=utf-8 """ tests.functional.module ~~~~~~~~~~~~~~ Functional tests """
# -*- coding: utf-8 -*- numero_empleado = int(input()) numero_hrs_mes = int(input()) pago_por_hora = float('%.2f' % ( float(input()) )) pago_por_mes = pago_por_hora*numero_hrs_mes pago_por_mes = '%.2f'%(float(pago_por_mes)) print ("NUMBER = " + str(numero_empleado)) print ("SALARY = U$ " + str(pago_por_mes))
""" 変数(定数)置き場です 変数(定数) ---- zero_bpm : float -> 0BPMのタイミングポイントです、正確には0ではありませんがほぼ0です inf_bpm : float -> ∞BPM(10億BPM以上?)のタイミングポイントです max_offset : int -> 最大offset値です、空ノーツを生成するときにしか使い所がありません min_offset : str -> 最小offset値です、使い所がありません key_asset : List[List[int]] -> キーとポジションのリストです。1つ目がキーの値です、0, 11, 13, 15, 17, 19以上は非対応です。2つ目がポジションです、左を0として順番に並んでいます """ zero_bpm: float = 1E+100 inf_bpm: float = 1E-100 max_offset: int = 2147483647 min_offset: int = -2147483648 key_asset: list = [ [], [256], [128, 384], [85, 256, 426], [64, 192, 320, 448], [51, 153, 256, 358, 460], [42, 128, 213, 298, 384, 469], [42, 128, 213, 256, 329, 402, 475], [32, 96, 160, 224, 288, 352, 416, 480], [28, 85, 142, 199, 256, 312, 369, 426, 483], [25, 76, 128, 179, 230, 281, 332, 384, 435, 486], [], [21, 64, 106, 149, 192, 234, 277, 320, 362, 405, 448, 490], [], [18, 54, 91, 128, 164, 201, 237, 274, 310, 347, 384, 420, 457, 493], [], [16, 48, 80, 112, 144, 176, 208, 240, 272, 304, 336, 368, 400, 432, 464, 496], [], [14, 42, 71, 99, 128, 156, 184, 213, 241, 270, 298, 327, 384, 355, 412, 440, 469, 497] ]
print('Descubra a média de 2 notas: \nObs: Utilize ponto para separas as casas decimais.') a1 = float(input('Digite a nota da primeira avaliação: ')) a2 = float(input('Digite a nota da segunda avaliação: ')) m = (a1 + a2) / 2 print('A média das notas é igual a {:.1f}'.format(m))
{ "targets": [ { "target_name": "wiringpi", "sources": [ "wiringpi.cc" ], "include_dirs": [ "/usr/local/include" ], "ldflags": [ "-lwiringPi" ] } ] }
#!/usr/bin/env python # coding: utf-8 # # [Program pertama: "Hello World"](https://academy.dqlab.id/main/livecode/157/283/1247) # In[1]: print("Hello World!") # # [Program Pertamaku](https://academy.dqlab.id/main/livecode/157/283/1248) # In[2]: print("Halo Dunia") print("Riset Bahasa Python") # # [Struktur Program Python - Part 1](https://academy.dqlab.id/main/livecode/157/283/1249) # In[3]: # Statement print("Belajar Python menyenangkan") print("Halo Dunia") print("Hello World!") # Variables & Literals bilangan1 = 5 bilangan2 = 10 kalimat1 = "Belajar Bahasa Python" # Operators print(bilangan1 + bilangan2) # # [Tugas Praktek](https://academy.dqlab.id/main/livecode/157/283/1250) # In[4]: bilangan1 = 20 bilangan2 = 10 print(bilangan1 - bilangan2) # # [Tugas Praktek](https://academy.dqlab.id/main/livecode/157/283/1251) # In[5]: harga_asli = 20000 potongan = 2000 harga_setelah_potongan = harga_asli - potongan harga_final = harga_setelah_potongan * 1.1 print(harga_final) # # [Sequence Type – Part 1](https://academy.dqlab.id/main/livecode/157/284/1262) # In[6]: contoh_list = [1, 'dua', 3, 4.0, 5] print(contoh_list[0]) print(contoh_list[3]) contoh_list = [1, 'dua', 3, 4.0, 5] contoh_list[3] = 'empat' print(contoh_list[3]) # # [Sequence Type – Part 2](https://academy.dqlab.id/main/livecode/157/284/1263) # In[7]: contoh_tuple = ('Januari','Februari','Maret','April') print(contoh_tuple[0]) contoh_tuple = ('Januari','Februari','Maret','April') contoh_tuple[0] = 'Desember' # # [Set Type](https://academy.dqlab.id/main/livecode/157/284/1264) # In[8]: contoh_list = ['Dewi','Budi','Cici','Linda','Cici'] print(contoh_list) contoh_set = {'Dewi','Budi','Cici','Linda','Cici'} print(contoh_set) contoh_frozen_set = ({'Dewi','Budi','Cici','Linda','Cici'}) print(contoh_frozen_set) # # [Mapping Type](https://academy.dqlab.id/main/livecode/157/284/1265) # In[9]: person = {'nama': 'John Doe', 'pekerjaan': 'Programmer'} print(person['nama']) print(person['pekerjaan']) # # [Tugas Praktek](https://academy.dqlab.id/main/livecode/157/284/1266) # In[10]: sepatu = {"nama barang": "Sepatu Niko", "harga": 150000, "diskon": 30000 } baju = {"nama barang": "Baju Unikloh", "harga": 80000, "diskon": 8000 } celana = {"nama barang": "Celana Lepis", "harga": 200000, "diskon": 60000 } # # [Tugas Praktek](https://academy.dqlab.id/main/livecode/157/284/1267) # In[11]: sepatu = {"nama": "Sepatu Niko", "harga": 150000, "diskon": 30000} baju = {"nama": "Baju Unikloh", "harga": 80000, "diskon": 8000} celana = {"nama": "Celana Lepis", "harga": 200000, "diskon": 60000} daftar_belanja = [sepatu, baju, celana] # # [Tugas Praktek](https://academy.dqlab.id/main/livecode/157/284/1268) # In[12]: # Data yang dinyatakan ke dalam dictionary sepatu = {"nama": "Sepatu Niko", "harga": 150000, "diskon": 30000} baju = {"nama": "Baju Unikloh", "harga": 80000, "diskon": 8000} celana = {"nama": "Celana Lepis", "harga": 200000, "diskon": 60000} # Hitunglah harga masing-masing data setelah dikurangi diskon harga_sepatu = sepatu["harga"] - sepatu["diskon"] harga_baju = baju["harga"] - baju["diskon"] harga_celana = celana["harga"] - celana["diskon"] # Hitung harga total total_harga = harga_sepatu + harga_baju + harga_celana # Hitung harga kena pajak total_pajak = total_harga * 0.1 # Cetak total_harga + total_pajak print(total_harga + total_pajak) # # [Nilai Prioritas Operator dalam Python – Part 1](https://academy.dqlab.id/main/livecode/157/293/1295) # In[13]: # Kode awal total_harga = 150000 potongan_harga = 0.3 pajak = 0.1 # pajak dalam persen ~ 10% harga_bayar = 1 - 0.3 # baris pertama harga_bayar *= total_harga # baris kedua pajak_bayar = pajak * harga_bayar # baris ketiga harga_bayar += pajak_bayar # baris ke-4 print("Kode awal - harga_bayar=", harga_bayar) # Penyederhanaan baris kode dengan menerapkan prioritas operator total_harga = 150000 potongan_harga = 0.3 pajak = 0.1 # pajak dalam persen ~ 10% harga_bayar = (1 - 0.3) * total_harga #baris pertama harga_bayar += harga_bayar * pajak # baris kedua print("Penyederhanaan kode - harga_bayar=", harga_bayar) # # [Tugas Praktek](https://academy.dqlab.id/main/livecode/157/293/1298) # In[14]: sepatu = { "nama" : "Sepatu Niko", "harga": 150000, "diskon": 30000 } baju = { "nama" : "Baju Unikloh", "harga": 80000, "diskon": 8000 } celana = { "nama" : "Celana Lepis", "harga": 200000, "diskon": 60000 } harga_sepatu = sepatu["harga"] - sepatu["diskon"] harga_baju = baju["harga"] - baju["diskon"] harga_celana = celana["harga"] - celana["diskon"] total_harga = (harga_sepatu + harga_baju + harga_celana) * 1.1 print(total_harga) # # [Python Conditioning for Decision – Part 2](https://academy.dqlab.id/main/livecode/157/294/1300) # In[15]: # Statement if x = 4 if x % 2 == 0: # jika sisa bagi x dengan 2 sama dengan 0 print("x habis dibagi dua") # statemen aksi lebih menjorok ke dalam # Statement if ... elif ... else x = 7 if x % 2 == 0: # jika sisa bagi x dengan 2 sama dengan 0 print("x habis dibagi dua") elif x % 3 == 0: # jika sisa bagi x dengan 3 sama dengan 0 print("x habis dibagi tiga") elif x % 5 == 0: # jika sisa bagi x dengan 5 sama dengan 0 print("x habis dibagi lima") else: print("x tidak habis dibagi dua, tiga ataupun lima") # # [Python Conditioning for Decision – Part 3](https://academy.dqlab.id/main/livecode/157/294/1301) # In[16]: jam = 13 if jam >= 5 and jam < 12: # selama jam di antara 5 s.d. 12 print("Selamat pagi!") elif jam >= 12 and jam < 17: # selama jam di antara 12 s.d. 17 print("Selamat siang!") elif jam >= 17 and jam < 19: # selama jam di antara 17 s.d. 19 print("Selamat sore!") else: # selain kondisi di atas print("Selamat malam!") # # [Tugas Praktek](https://academy.dqlab.id/main/livecode/157/294/1302) # In[17]: tagihan_ke = 'Mr. Yoyo' warehousing = { 'harga_harian': 1000000, 'total_hari':15 } cleansing = { 'harga_harian': 1500000, 'total_hari':10 } integration = { 'harga_harian':2000000, 'total_hari':15 } transform = { 'harga_harian':2500000, 'total_hari':10 } sub_warehousing = warehousing['harga_harian'] * warehousing['total_hari'] sub_cleansing = cleansing['harga_harian'] * cleansing['total_hari'] sub_integration = integration['harga_harian'] * integration['total_hari'] sub_transform = transform['harga_harian'] * transform['total_hari'] total_harga = sub_warehousing + sub_cleansing + sub_integration + sub_transform print("Tagihan kepada:") print(tagihan_ke) print("Selamat pagi, anda harus membayar tagihan sebesar:") print(total_harga) # # [Tugas Praktek](https://academy.dqlab.id/main/livecode/157/294/1303) # In[18]: jam = 17 tagihan_ke = 'Mr. Yoyo' warehousing = { 'harga_harian': 1000000, 'total_hari':15 } cleansing = { 'harga_harian': 1500000, 'total_hari':10 } integration = { 'harga_harian':2000000, 'total_hari':15 } transform = { 'harga_harian':2500000, 'total_hari':10 } sub_warehousing = warehousing['harga_harian']*warehousing['total_hari'] sub_cleansing = cleansing['harga_harian']*cleansing['total_hari'] sub_integration = integration['harga_harian']*integration['total_hari'] sub_transform = transform['harga_harian']*transform['total_hari'] total_harga = sub_warehousing+sub_cleansing+sub_integration+sub_transform print("Tagihan kepada:") print(tagihan_ke) if jam > 19: print("Selamat malam, anda harus membayar tagihan sebesar:") elif jam > 17 : print("Selamat sore, anda harus membayar tagihan sebesar:") elif jam > 12: print("Selamat siang, anda harus membayar tagihan sebesar:") else: print("Selamat pagi, anda harus membayar tagihan sebesar:") print(total_harga) # # [Python while loops – Part 1](https://academy.dqlab.id/main/livecode/157/294/1305) # In[19]: # Tagihan tagihan = [50000, 75000, 125000, 300000, 200000] # Tanpa menggunakan while loop total_tagihan = tagihan[0] + tagihan[1] + tagihan[2] + tagihan[3] + tagihan[4] print(total_tagihan) # Dengan menggunakan while loop i = 0 # sebuah variabel untuk mengakses setiap elemen tagihan satu per satu jumlah_tagihan = len(tagihan) # panjang (jumlah elemen dalam) list tagihan total_tagihan = 0 # mula-mula, set total_tagihan ke 0 while i < jumlah_tagihan: # selama nilai i kurang dari jumlah_tagihan total_tagihan += tagihan[i] # tambahkan tagihan[i] ke total_tagihan i += 1 # tambahkan nilai i dengan 1 untuk memproses tagihan selanjutnya. print(total_tagihan) # # [Python while loops – Part 2](https://academy.dqlab.id/main/livecode/157/294/1306) # In[20]: tagihan = [50000, 75000, -150000, 125000, 300000, -50000, 200000] i = 0 jumlah_tagihan = len(tagihan) total_tagihan = 0 while i < jumlah_tagihan: # jika terdapat tagihan ke-i yang bernilai minus (di bawah nol), # pengulangan akan dihentikan if tagihan[i] < 0: total_tagihan = -1 print("terdapat angka minus dalam tagihan, perhitungan dihentikan!") break total_tagihan += tagihan[i] i += 1 print(total_tagihan) # # [Python while loops – Part 3](https://academy.dqlab.id/main/livecode/157/294/1307) # In[21]: tagihan = [50000, 75000, -150000, 125000, 300000, -50000, 200000] i = 0 jumlah_tagihan = len(tagihan) total_tagihan = 0 while i < jumlah_tagihan: # jika terdapat tagihan ke-i yang bernilai minus (di bawah nol), # abaikan tagihan ke-i dan lanjutkan ke tagihan berikutnya if tagihan[i] < 0: i += 1 continue total_tagihan += tagihan[i] i += 1 print(total_tagihan) # # [Python for loops – Part 1](https://academy.dqlab.id/main/livecode/157/294/1308) # In[22]: list_tagihan = [50000, 75000, -150000, 125000, 300000, -50000, 200000] total_tagihan = 0 for tagihan in list_tagihan: # untuk setiap tagihan dalam list_tagihan total_tagihan += tagihan # tambahkan tagihan ke total_tagihan print(total_tagihan) # # [Python for loops – Part 2](https://academy.dqlab.id/main/livecode/157/294/1309) # In[23]: list_tagihan = [50000, 75000, -150000, 125000, 300000, -50000, 200000] total_tagihan = 0 for tagihan in list_tagihan: if tagihan < 0: print("terdapat angka minus dalam tagihan, perhitungan dihentikan!") break total_tagihan += tagihan print(total_tagihan) # # [Python for loops – Part 3](https://academy.dqlab.id/main/livecode/157/294/1310) # In[24]: list_daerah = ['Malang', 'Palembang', 'Medan'] list_buah = ['Apel', 'Duku', 'Jeruk'] for nama_daerah in list_daerah: for nama_buah in list_buah: print(nama_buah+" "+nama_daerah) # # [Tugas Praktek](https://academy.dqlab.id/main/livecode/157/294/1311) # In[25]: list_cash_flow = [2500000, 5000000, -1000000, -2500000, 5000000, 10000000, -5000000, 7500000, 10000000, -1500000, 25000000, -2500000] total_pengeluaran, total_pemasukan = 0, 0 for dana in list_cash_flow : if dana > 0: total_pemasukan += dana else: total_pengeluaran += dana total_pengeluaran *= -1 print(total_pengeluaran) print(total_pemasukan) # # [Ekspedisi Pamanku](https://academy.dqlab.id/main/livecode/157/295/1313) # In[26]: # Data uang_jalan = 1500000 jumlah_hari = 31 list_plat_nomor = [8993, 2198, 2501, 2735, 3772, 4837, 9152] # Pengecekan kendaraan dengan nomor pelat ganjil atau genap # Deklarasikan kendaraan_genap dan kendaraan_ganjil = 0 kendaraan_genap = 0 kendaraan_ganjil = 0 for plat_nomor in list_plat_nomor: if plat_nomor % 2 == 0: kendaraan_genap += 1 else: kendaraan_ganjil += 1 # Total pengeluaran untuk kendaraan dengan nomor pelat ganjil # dan genap dalam 1 bulan i = 1 total_pengeluaran = 0 while i <= jumlah_hari: if i % 2 == 0: total_pengeluaran += (kendaraan_genap * uang_jalan) else: total_pengeluaran += (kendaraan_ganjil * uang_jalan) i += 1 # Cetak total pengeluaran print(total_pengeluaran)
"""Core exceptions.""" class Unauthenticated(Exception): """Thrown when user is not authenticated.""" pass class MalformedRequestData(Exception): """Thrown when request data is malformed.""" pass class InputError(Exception): """Thrown on input error.""" pass class FileTypeError(Exception): """Thrown on file type error.""" pass
bot_name = 'your_bot_username' bot_token = 'your_bot_token' redis_server = 'localhost' redis_port = 6379 bot_master = 'your_userid_here'
class NavigationHelper: def __init__(self, app): self.app = app def open_home_page(self): wd = self.app.wd wd.get(self.app.base_url) def return_to_home_page(self): wd = self.app.wd wd.find_element_by_link_text("home").click()
_base_ = [ './retina.py' ] model= dict( type='CustomRetinaNet', #pretrained=None, #backbone=dict( # Replacding R50 by OTE MV2 # _delete_=True, # type='mobilenetv2_w1', # out_indices=(2, 3, 4, 5), # frozen_stages=-1, # norm_eval=True, # False in OTE setting # pretrained=True, #), #neck=dict( # in_channels=[24, 32, 96, 320], # out_channels=64, #), #bbox_head=dict( # type='CustomRetinaHead', # in_channels=64, # feat_channels=64, #), )
class BaseComponent(object): def __init__(self): self.version = self.__version__ def forward(self, tweet: str): raise NotImplementedError @property def __version__(self): raise NotImplementedError
# -*- coding: utf-8 -*- GENDERS = { 1: (1, u'男'), 2: (2, u'女'), 3: (3, u'保密') }
def create_spam_worker_name(user_id): return f'user_{user_id}_spam_worker' def create_email_worker_name(user_id): return f'user_{user_id}_email_worker' def create_worker_celery_name(worker_name): return f"celery@{worker_name}" def create_spam_worker_celery_name(user_id): return create_worker_celery_name(create_spam_worker_name(user_id)) def create_email_worker_celery_name(user_id): return create_worker_celery_name(create_email_worker_name(user_id)) def create_user_spam_queue_name(user_id): return f'user_{user_id}_spam_queue' def create_user_email_queue_name(user_id): return f'user_{user_id}_email_queue'
def aditya(): return "aditya" def shantanu(num): if num>10: return "shantanu" else: return "patankar"
def personalData(): """ Asks the user for their name and age. Uses a try except block to cast their age to an int prints out their name ad age. :return: """ user_name = input("Enter your name: ") user_age = input("Enter your age") #use a try except block when casting to an int. try: age = int(user_age) print("Hello", user_name, "you are", age, "years old.") except ValueError: #error returned if the variable cannot be cast as it is not a number print("The age you have entered is not a number") personalData()
# Define a Multiplication Function def mul(num1, num2): return num1 * num2
''' Write a Python program to accept a filename from the user and print the extension of that. ''' ext = input("Enter a file name: ") files = ext.split('.') print(files[1])
def kth_largest1(arr,k): if k > len(arr): return None for i in range(k-1): arr.remove(max(arr)) return max(arr) def kth_largest2(arr,k): if k > len(arr): return None n = len(arr) arr.sort() return(arr[n - k]) print(kth_largest2([4,2,8,9,5,6,7],2))
# the way currently the code is written it is possible to change the value accidently or it can be changed accidently class Customer: def __init__(self, cust_id, name, age, wallet_balance): self.cust_id = cust_id self.name = name self.age = age self.wallet_balance = wallet_balance def update_balance(self, amount): if amount < 1000 and amount > 0: self.wallet_balance += amount def show_balance(self): print("The balance is ", self.wallet_balance) c1 = Customer(100, "Gopal", 24, 1000) c1.wallet_balance = 10000000 c1.show_balance() # this example shows how the code & data is vulnarable and its being changed by invoking the object by the method
#!/usr/bin/env python3.7 # -*- coding: utf-8 -*- # https://leetcode.com/problems/reverse-integer/ inputs = [123, -123, 120, 1534236469] def reverse(x): """ Given a 32-bit signed integer, reverse digits of an integer. Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. """ '''# By converting to string. if x < 0: s = str(x).strip('-') return int('-' + s[::-1]) else: return int(str(x)[::-1])''' # O(n). num = 0 # Convert to absolute value. a = abs(x) while a != 0: temp = a % 10 num = num * 10 + temp a = a // 10 if x > 0 and num < 2147483647: return num elif x < 0 and num <= 2147483647: return -num else: return 0 for i in inputs: print(reverse(i))
def match(output_file, input_file): block = [] blocks = [] for line in open(input_file, encoding='utf8').readlines(): if line.startswith('#'): block.append(line) else: if block: blocks.append(block) block = [] block1 = [] blocks1 = [] for line in open(output_file, encoding='utf8').readlines(): if not line.startswith('#'): block1.append(line) else: if block1: blocks1.append(block1) block1 = [] if block1: blocks1.append(block1) assert len(blocks) == len(blocks1), (len(blocks), len(blocks1)) with open(output_file+'.pred', 'w', encoding='utf8') as fo: for block, block1 in zip(blocks, blocks1): for line in block: fo.write(line) for line in block1: fo.write(line)
class MysqlDumpParser: def __init__(self, table: str): """ :param: str table The name of the table to parse, in case there are multiple tables in the same file """ self.table = table self.columns = [] @staticmethod def is_create_statement(line): return line.upper().startswith('CREATE TABLE') @staticmethod def is_field_definition(line): return line.strip().startswith('`') @staticmethod def is_insert_statement(line): return line.upper().startswith('INSERT INTO') @staticmethod def get_mysql_name_value(line): value = None result = re.search(r'\`([^\`]*)\`', line) if result: value = result.groups()[0] return value @staticmethod def get_value_tuples(line): values = line.partition(' VALUES ')[-1].strip().replace('NULL', 'None') if values[-1] == ';': values = values[:-1] return ast.literal_eval(values) def to_dict(self, filename: str): """ Given a gzipped mysql dump file, yield a dict for each record. My use case for this is when performing ETLs where this step needs to yield a line separated JSON file, particularly useful when targeting Google BigQuery as the target storage technology. :param: str filename Path to gz file containing the MySQL dump file """ current_table = None with gzip.open(filename, 'rb') as reader: for line in reader: line = line.decode() if MysqlDumpParser.is_create_statement(line): current_table = MysqlDumpParser.get_mysql_name_value(line) if current_table != self.table: continue elif current_table == self.table and MysqlDumpParser.is_field_definition(line): col = MysqlDumpParser.get_mysql_name_value(line) self.columns.append(col) elif MysqlDumpParser.is_insert_statement(line): current_table = MysqlDumpParser.get_mysql_name_value(line) if current_table != self.table: continue values = MysqlDumpParser.get_value_tuples(line) schema = self.columns for row in values: yield dict(zip(schema, row))
# quicksort def partition(arr,low,high): i = ( low-1 ) # index of smaller element pivot = arr[high] # pivot for j in range(low , high): # If current element is smaller than or # equal to pivot if arr[j] <= pivot: # increment index of smaller element i = i+1 arr[i],arr[j] = arr[j],arr[i] arr[i+1], arr[high] = arr[high], arr[i+1] return ( i+1 ) def quickSort(arr,low,high): if low < high: # pi is partitioning index, arr[p] is now # at right place pi = partition(arr,low,high) # Separately sort elements before # partition and after partition quickSort(arr, low, pi-1) quickSort(arr, pi+1, high) else: print("Error encountered") def printList(arr): for i in range(len(arr)): print(arr[i],end=" ") print() # Driver code to test above def main(): user_arr = list(input("Give me some numbers seperated by a space\n")) print("Given Array: ", end="\n") n = len(user_arr) quickSort(user_arr,0,n-1) print ("Sorted array is: ", end="\n") printList(user_arr) # for i in range(n): # sort_list = list([(quickSort(arr,0,n-1))]) # print ("%d" %arr[i]) main()
class Solution: def threeSumClosest(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ nums.sort() rls = nums[0] + nums[1] + nums[2] for i in range(len(nums)-2): j, k = i+1, len(nums)-1 while j < k: s = nums[i] + nums[j] + nums[k] if s == target: return s rls = s if abs(s-target) < abs(rls-target) else rls if s < target: j += 1 else: k -= 1 return rls
# A mapping between model field internal datatypes and sensible # client-friendly datatypes. In virtually all cases, client programs # only need to differentiate between high-level types like number, string, # and boolean. More granular separation be may desired to alter the # allowed operators or may infer a different client-side representation SIMPLE_TYPES = { 'auto': 'key', 'foreignkey': 'key', 'biginteger': 'number', 'decimal': 'number', 'float': 'number', 'integer': 'number', 'positiveinteger': 'number', 'positivesmallinteger': 'number', 'smallinteger': 'number', 'nullboolean': 'boolean', 'char': 'string', 'email': 'string', 'file': 'string', 'filepath': 'string', 'image': 'string', 'ipaddress': 'string', 'slug': 'string', 'text': 'string', 'url': 'string', } # A mapping between the client-friendly datatypes and sensible operators # that will be used to validate a query condition. In many cases, these types # support more operators than what are defined, but are not include because # they are not commonly used. OPERATORS = { 'key': ('exact', '-exact', 'in', '-in'), 'boolean': ('exact', '-exact', 'in', '-in'), 'date': ('exact', '-exact', 'in', '-in', 'lt', 'lte', 'gt', 'gte', 'range', '-range'), 'number': ('exact', '-exact', 'in', '-in', 'lt', 'lte', 'gt', 'gte', 'range', '-range'), 'string': ('exact', '-exact', 'iexact', '-iexact', 'in', '-in', 'icontains', '-icontains', 'iregex', '-iregex'), 'datetime': ('exact', '-exact', 'in', '-in', 'lt', 'lte', 'gt', 'gte', 'range', '-range'), 'time': ('exact', '-exact', 'in', '-in', 'lt', 'lte', 'gt', 'gte', 'range', '-range'), } # A general mapping of formfield overrides for all subclasses. the mapping is # similar to the SIMPLE_TYPE_MAP, but the values reference internal # formfield classes, that is integer -> IntegerField. in many cases, the # validation performed may need to be a bit less restrictive than what the # is actually necessary INTERNAL_DATATYPE_FORMFIELDS = { 'integer': 'FloatField', 'positiveinteger': 'FloatField', 'positivesmallinteger': 'FloatField', 'smallinteger': 'FloatField', 'biginteger': 'FloatField', } # The minimum number of distinct values required when determining to set the # `searchable` flag on `DataField` instances during the `init` process. This # will only be applied to fields with a Avocado datatype of 'string' ENUMERABLE_MAXIMUM = 30 # Flag for enabling the history API HISTORY_ENABLED = True # The maximum size of a user's history. If the value is an integer, this # is the maximum number of allowed items in the user's history. Set to # `None` (or 0) to enable unlimited history. Note, in order to enforce this # limit, the `avocado history --prune` command must be executed to remove # the oldest history from each user based on this value. HISTORY_MAX_SIZE = None # App that the metadata migrations will be created for. This is typically the # project itself. METADATA_MIGRATION_APP = None # Directory for the migration backup fixtures. If None, this will default to # the fixtures dir in the app defined by `METADATA_MIGRATION_APP` METADATA_FIXTURE_DIR = None METADATA_FIXTURE_SUFFIX = 'avocado_metadata' METADATA_MIGRATION_SUFFIX = 'avocado_metadata_migration' # Query processors QUERY_PROCESSORS = { 'default': 'avocado.query.pipeline.QueryProcessor', } # Custom validation error and warnings messages VALIDATION_ERRORS = {} VALIDATION_WARNINGS = {} # Toggle whether DataField instances should cache the underlying data # for their most common data access methods. DATA_CACHE_ENABLED = True # These settings affect how queries can be shared between users. # A user is able to enter either a username or an email of another user # they wish to share the query with. To limit to only one type of sharing # set the appropriate setting to True and all others to false. SHARE_BY_USERNAME = True SHARE_BY_EMAIL = True SHARE_BY_USERNAME_CASE_SENSITIVE = True # Toggle whether the permissions system should be enabled. # If django-guardian is installed and this value is None or True, permissions # will be applied. If the value is True and django-guardian is not installed # it is an error. If set to False the permissions will not be applied. PERMISSIONS_ENABLED = None # Caches are used to improve performance across various APIs. The two primary # ones are data and query. Data cache is used for individual data field # caching such as counts, values, and aggregations. Query cache is used for # the ad-hoc queries built from a context and view. DATA_CACHE = 'default' QUERY_CACHE = 'default' # Name of the queue to use for scheduling and working on async jobs. ASYNC_QUEUE = 'avocado'
constants = { # --- ASSETS FILE NAMES AND DELAY BETWEEN FOOTAGE "CALIBRATION_CAMERA_STATIC_PATH": "assets/cam1 - static/calibration.mov", "CALIBRATION_CAMERA_MOVING_PATH": "assets/cam2 - moving light/calibration.mp4", "COIN_1_VIDEO_CAMERA_STATIC_PATH": "assets/cam1 - static/coin1.mov", "COIN_1_VIDEO_CAMERA_MOVING_PATH": "assets/cam2 - moving light/coin1.mp4", "COIN_2_VIDEO_CAMERA_STATIC_PATH": "assets/cam1 - static/coin2.mov", "COIN_2_VIDEO_CAMERA_MOVING_PATH": "assets/cam2 - moving light/coin2.mp4", "COIN_3_VIDEO_CAMERA_STATIC_PATH": "assets/cam1 - static/coin3.mov", "COIN_3_VIDEO_CAMERA_MOVING_PATH": "assets/cam2 - moving light/coin3.mp4", "COIN_4_VIDEO_CAMERA_STATIC_PATH": "assets/cam1 - static/coin4.mov", "COIN_4_VIDEO_CAMERA_MOVING_PATH": "assets/cam2 - moving light/coin4.mp4", "FILE_1_MOVING_CAMERA_DELAY": 2.724, # [seconds] (static) 3.609 - 0.885 (moving) "FILE_2_MOVING_CAMERA_DELAY": 2.024, # [seconds] (static) 2.995 - 0.971 (moving) "FILE_3_MOVING_CAMERA_DELAY": 2.275, # [seconds] (static) 3.355 - 1.08 (moving) "FILE_4_MOVING_CAMERA_DELAY": 2.015, # [seconds] (static) 2.960 - 0.945 (moving) # --- CAMERA CALIBRATION CONSTANTS "CHESSBOARD_SIZE": (6, 9), "CALIBRATION_FRAME_SKIP_INTERVAL": 40, # We just need some, not all # --- ANALYSIS CONSTANTS "SQAURE_GRID_DIMENSION": 200, # It will be a 400x400 square grid inside the marker "ALIGNED_VIDEO_FPS": 30, "ANALYSIS_FRAME_SKIP": 5, # It will skip this frames each iteration during analysis # --- DEBUG CONSTANTS "STATIC_CAMERA_FEED_WINDOW_TITLE": "Static camera feed", "MOVING_CAMERA_FEED_WINDOW_TITLE": "Moving camera feed", "WARPED_FRAME_WINDOW_TITLE": "Warped moving frame", "LIGHT_DIRECTION_WINDOW_TITLE": "Light direction", "LIGHT_DIRECTION_WINDOW_SIZE": 200, # --- INTERACTIVE RELIGHTING CONSTANTS "INTERPOLATED_WINDOW_TITLE": "Interpolated Data", "INPUT_LIGHT_DIRECTION_WINDOW_TITLE": "Light direction input", # --- DATA FILE NAMES CONSTANTS "CALIBRATION_INTRINSICS_CAMERA_STATIC_PATH": "data/static_intrinsics.xml", "CALIBRATION_INTRINSICS_CAMERA_MOVING_PATH": "data/moving_intrinsics.xml", "COIN_1_ALIGNED_VIDEO_STATIC_PATH": "data/1_static_aligned_video.mov", "COIN_1_ALIGNED_VIDEO_MOVING_PATH": "data/1_moving_aligned_video.mp4", "COIN_2_ALIGNED_VIDEO_STATIC_PATH": "data/2_static_aligned_video.mov", "COIN_2_ALIGNED_VIDEO_MOVING_PATH": "data/2_moving_aligned_video.mp4", "COIN_3_ALIGNED_VIDEO_STATIC_PATH": "data/3_static_aligned_video.mov", "COIN_3_ALIGNED_VIDEO_MOVING_PATH": "data/3_moving_aligned_video.mp4", "COIN_4_ALIGNED_VIDEO_STATIC_PATH": "data/4_static_aligned_video.mov", "COIN_4_ALIGNED_VIDEO_MOVING_PATH": "data/4_moving_aligned_video.mp4", "COIN_1_EXTRACTED_DATA_FILE_PATH": "data/1_extracted_data.npz", "COIN_2_EXTRACTED_DATA_FILE_PATH": "data/2_extracted_data.npz", "COIN_3_EXTRACTED_DATA_FILE_PATH": "data/3_extracted_data.npz", "COIN_4_EXTRACTED_DATA_FILE_PATH": "data/4_extracted_data.npz", "COIN_1_INTERPOLATED_DATA_RBF_FILE_PATH": "data/1_rbf_interpolated_data.npz", "COIN_2_INTERPOLATED_DATA_RBF_FILE_PATH": "data/2_rbf_interpolated_data.npz", "COIN_3_INTERPOLATED_DATA_RBF_FILE_PATH": "data/3_rbf_interpolated_data.npz", "COIN_4_INTERPOLATED_DATA_RBF_FILE_PATH": "data/4_rbf_interpolated_data.npz", "COIN_1_INTERPOLATED_DATA_PTM_FILE_PATH": "data/1_ptm_interpolated_data.npz", "COIN_2_INTERPOLATED_DATA_PTM_FILE_PATH": "data/2_ptm_interpolated_data.npz", "COIN_3_INTERPOLATED_DATA_PTM_FILE_PATH": "data/3_ptm_interpolated_data.npz", "COIN_4_INTERPOLATED_DATA_PTM_FILE_PATH": "data/4_ptm_interpolated_data.npz", }
def timeConversion(s): if "P" in s: s = s.split(":") if s[0] == '12': s = s.split(":") s[2] = s[2][:2] print(":".join(s)) else: s[0] = str(int(s[0])+12) s[2] = s[2][:2] print(":".join(s)) else: s = s.split(":") if s[0] == "12": s[0] == "00" print(s) s[2] = s[2][:2] print(":".join(s),'AM') else: s[2] = s[2][:2] print(":".join(s)) s = input() timeConversion(s)
def for_loop4(str, x): result = 0 for i in str: if i == x: result += 1 return result def main(): print(for_loop4('athenian', 'e')) print(for_loop4('apples', 'a')) print(for_loop4('hello', 'a')) print(for_loop4('alphabet', 'h')) print(for_loop4('aaaaa', 'b')) if __name__ == '__main__': main()
""" Tuples - iterable - immutable - strings are also immutable """ car = ('honda', 'city', 'white', 'DL09671', '78878GFG', 2016) print(car) print(type(car)) print(len(car)) for item in car: print(item) print(car[0])
# Author : Nekyz # Date : 30/06/2015 # Project Euler Challenge 3 # Largest palindrome of 2 three digit number def is_palindrome (n): # Reversing n to see if it's the same ! Extended slice are fun if str(n) == (str(n))[::-1]: return True return False max = 0 for i in range(999,100,-1): for j in range (999,100,-1): product = i * j if is_palindrome(product): if (product > max): max = product print(i," * ",j," = ", product) print("Max palindrome is : ", max)
# -*- coding: utf-8 -*- def remove_duplicate_elements(check_list): func = lambda x,y:x if y in x else x + [y] return reduce(func, [[], ] + check_list)
class LightingSource(Enum, IComparable, IFormattable, IConvertible): """ Indicates the lighting scheme type in rendering settings. enum LightingSource,values: ExteriorArtificial (23),ExteriorSun (21),ExteriorSunAndArtificial (22),InteriorArtificial (26),InteriorSun (24),InteriorSunAndArtificial (25) """ def __eq__(self, *args): """ x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """ pass def __format__(self, *args): """ __format__(formattable: IFormattable,format: str) -> str """ pass def __ge__(self, *args): pass def __gt__(self, *args): pass def __init__(self, *args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass def __le__(self, *args): pass def __lt__(self, *args): pass def __ne__(self, *args): pass def __reduce_ex__(self, *args): pass def __str__(self, *args): pass ExteriorArtificial = None ExteriorSun = None ExteriorSunAndArtificial = None InteriorArtificial = None InteriorSun = None InteriorSunAndArtificial = None value__ = None
# coding: utf-8 mail_conf = { "host": "", "sender": "boom_run raise error", "username": "", "passwd": "", "mail_postfix": "", "recipients": [ "", ] } redis_conf = { "host": "127.0.0.1", "port": 6379, }
# # PySNMP MIB module BEGEMOT-PF-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BEGEMOT-PF-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:37:07 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ConstraintsIntersection") begemot, = mibBuilder.importSymbols("BEGEMOT-MIB", "begemot") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Gauge32, iso, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, Bits, ObjectIdentity, Integer32, TimeTicks, Unsigned32, NotificationType, IpAddress, MibIdentifier, Counter32, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "iso", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "Bits", "ObjectIdentity", "Integer32", "TimeTicks", "Unsigned32", "NotificationType", "IpAddress", "MibIdentifier", "Counter32", "Counter64") TextualConvention, DisplayString, TruthValue = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString", "TruthValue") begemotPf = ModuleIdentity((1, 3, 6, 1, 4, 1, 12325, 1, 200)) if mibBuilder.loadTexts: begemotPf.setLastUpdated('200501240000Z') if mibBuilder.loadTexts: begemotPf.setOrganization('NixSys BVBA') if mibBuilder.loadTexts: begemotPf.setContactInfo(' Philip Paeps Postal: NixSys BVBA Louizastraat 14 BE-2800 Mechelen Belgium E-Mail: philip@FreeBSD.org') if mibBuilder.loadTexts: begemotPf.setDescription('The Begemot MIB for the pf packet filter.') begemotPfObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1)) pfStatus = MibIdentifier((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 1)) pfCounter = MibIdentifier((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 2)) pfStateTable = MibIdentifier((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 3)) pfSrcNodes = MibIdentifier((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 4)) pfLimits = MibIdentifier((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 5)) pfTimeouts = MibIdentifier((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 6)) pfLogInterface = MibIdentifier((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 7)) pfInterfaces = MibIdentifier((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 8)) pfTables = MibIdentifier((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9)) pfAltq = MibIdentifier((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 10)) pfStatusRunning = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 1, 1), TruthValue()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfStatusRunning.setStatus('current') if mibBuilder.loadTexts: pfStatusRunning.setDescription('True if pf is currently enabled.') pfStatusRuntime = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 1, 2), TimeTicks()).setUnits('1/100th of a Second').setMaxAccess("readonly") if mibBuilder.loadTexts: pfStatusRuntime.setStatus('current') if mibBuilder.loadTexts: pfStatusRuntime.setDescription('Indicates how long pf has been enabled. If pf is not currently enabled, indicates how long it has been disabled. If pf has not been enabled or disabled since the system was started, the value will be 0.') pfStatusDebug = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("none", 0), ("urgent", 1), ("misc", 2), ("loud", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: pfStatusDebug.setStatus('current') if mibBuilder.loadTexts: pfStatusDebug.setDescription('Indicates the debug level at which pf is running.') pfStatusHostId = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 1, 4), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfStatusHostId.setStatus('current') if mibBuilder.loadTexts: pfStatusHostId.setDescription('The (unique) host identifier of the machine running pf.') pfCounterMatch = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 2, 1), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfCounterMatch.setStatus('current') if mibBuilder.loadTexts: pfCounterMatch.setDescription('Number of packets that matched a filter rule.') pfCounterBadOffset = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 2, 2), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfCounterBadOffset.setStatus('current') if mibBuilder.loadTexts: pfCounterBadOffset.setDescription('Number of packets with bad offset.') pfCounterFragment = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 2, 3), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfCounterFragment.setStatus('current') if mibBuilder.loadTexts: pfCounterFragment.setDescription('Number of fragmented packets.') pfCounterShort = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 2, 4), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfCounterShort.setStatus('current') if mibBuilder.loadTexts: pfCounterShort.setDescription('Number of short packets.') pfCounterNormalize = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 2, 5), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfCounterNormalize.setStatus('current') if mibBuilder.loadTexts: pfCounterNormalize.setDescription('Number of normalized packets.') pfCounterMemDrop = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 2, 6), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfCounterMemDrop.setStatus('current') if mibBuilder.loadTexts: pfCounterMemDrop.setDescription('Number of packets dropped due to memory limitations.') pfStateTableCount = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 3, 1), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfStateTableCount.setStatus('current') if mibBuilder.loadTexts: pfStateTableCount.setDescription('Number of entries in the state table.') pfStateTableSearches = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 3, 2), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfStateTableSearches.setStatus('current') if mibBuilder.loadTexts: pfStateTableSearches.setDescription('Number of searches against the state table.') pfStateTableInserts = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 3, 3), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfStateTableInserts.setStatus('current') if mibBuilder.loadTexts: pfStateTableInserts.setDescription('Number of entries inserted into the state table.') pfStateTableRemovals = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 3, 4), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfStateTableRemovals.setStatus('current') if mibBuilder.loadTexts: pfStateTableRemovals.setDescription('Number of entries removed from the state table.') pfSrcNodesCount = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 4, 1), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfSrcNodesCount.setStatus('current') if mibBuilder.loadTexts: pfSrcNodesCount.setDescription('Number of entries in the source tracking table.') pfSrcNodesSearches = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 4, 2), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfSrcNodesSearches.setStatus('current') if mibBuilder.loadTexts: pfSrcNodesSearches.setDescription('Number of searches against the source tracking table.') pfSrcNodesInserts = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 4, 3), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfSrcNodesInserts.setStatus('current') if mibBuilder.loadTexts: pfSrcNodesInserts.setDescription('Number of entries inserted into the source tracking table.') pfSrcNodesRemovals = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 4, 4), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfSrcNodesRemovals.setStatus('current') if mibBuilder.loadTexts: pfSrcNodesRemovals.setDescription('Number of entries removed from the source tracking table.') pfLimitsStates = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 5, 1), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfLimitsStates.setStatus('current') if mibBuilder.loadTexts: pfLimitsStates.setDescription("Maximum number of 'keep state' rules in the ruleset.") pfLimitsSrcNodes = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 5, 2), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfLimitsSrcNodes.setStatus('current') if mibBuilder.loadTexts: pfLimitsSrcNodes.setDescription("Maximum number of 'sticky-address' or 'source-track' rules in the ruleset.") pfLimitsFrags = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 5, 3), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfLimitsFrags.setStatus('current') if mibBuilder.loadTexts: pfLimitsFrags.setDescription("Maximum number of 'scrub' rules in the ruleset.") pfTimeoutsTcpFirst = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 6, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTimeoutsTcpFirst.setStatus('current') if mibBuilder.loadTexts: pfTimeoutsTcpFirst.setDescription('State after the first packet in a connection.') pfTimeoutsTcpOpening = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 6, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTimeoutsTcpOpening.setStatus('current') if mibBuilder.loadTexts: pfTimeoutsTcpOpening.setDescription('State before the destination host ever sends a packet.') pfTimeoutsTcpEstablished = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 6, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTimeoutsTcpEstablished.setStatus('current') if mibBuilder.loadTexts: pfTimeoutsTcpEstablished.setDescription('The fully established state.') pfTimeoutsTcpClosing = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 6, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTimeoutsTcpClosing.setStatus('current') if mibBuilder.loadTexts: pfTimeoutsTcpClosing.setDescription('State after the first FIN has been sent.') pfTimeoutsTcpFinWait = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 6, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTimeoutsTcpFinWait.setStatus('current') if mibBuilder.loadTexts: pfTimeoutsTcpFinWait.setDescription('State after both FINs have been exchanged and the connection is closed.') pfTimeoutsTcpClosed = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 6, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTimeoutsTcpClosed.setStatus('current') if mibBuilder.loadTexts: pfTimeoutsTcpClosed.setDescription('State after one endpoint sends an RST.') pfTimeoutsUdpFirst = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 6, 7), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTimeoutsUdpFirst.setStatus('current') if mibBuilder.loadTexts: pfTimeoutsUdpFirst.setDescription('State after the first packet.') pfTimeoutsUdpSingle = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 6, 8), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTimeoutsUdpSingle.setStatus('current') if mibBuilder.loadTexts: pfTimeoutsUdpSingle.setDescription('State if the source host sends more than one packet but the destination host has never sent one back.') pfTimeoutsUdpMultiple = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 6, 9), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTimeoutsUdpMultiple.setStatus('current') if mibBuilder.loadTexts: pfTimeoutsUdpMultiple.setDescription('State if both hosts have sent packets.') pfTimeoutsIcmpFirst = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 6, 10), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTimeoutsIcmpFirst.setStatus('current') if mibBuilder.loadTexts: pfTimeoutsIcmpFirst.setDescription('State after the first packet.') pfTimeoutsIcmpError = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 6, 11), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTimeoutsIcmpError.setStatus('current') if mibBuilder.loadTexts: pfTimeoutsIcmpError.setDescription('State after an ICMP error came back in response to an ICMP packet.') pfTimeoutsOtherFirst = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 6, 12), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTimeoutsOtherFirst.setStatus('current') if mibBuilder.loadTexts: pfTimeoutsOtherFirst.setDescription('State after the first packet.') pfTimeoutsOtherSingle = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 6, 13), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTimeoutsOtherSingle.setStatus('current') if mibBuilder.loadTexts: pfTimeoutsOtherSingle.setDescription('State if the source host sends more than one packet but the destination host has never sent one back.') pfTimeoutsOtherMultiple = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 6, 14), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTimeoutsOtherMultiple.setStatus('current') if mibBuilder.loadTexts: pfTimeoutsOtherMultiple.setDescription('State if both hosts have sent packets.') pfTimeoutsFragment = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 6, 15), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTimeoutsFragment.setStatus('current') if mibBuilder.loadTexts: pfTimeoutsFragment.setDescription('Seconds before an unassembled fragment is expired.') pfTimeoutsInterval = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 6, 16), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTimeoutsInterval.setStatus('current') if mibBuilder.loadTexts: pfTimeoutsInterval.setDescription('Interval between purging expired states and fragments.') pfTimeoutsAdaptiveStart = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 6, 17), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTimeoutsAdaptiveStart.setStatus('current') if mibBuilder.loadTexts: pfTimeoutsAdaptiveStart.setDescription('When the number of state entries exceeds this value, adaptive scaling begins.') pfTimeoutsAdaptiveEnd = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 6, 18), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTimeoutsAdaptiveEnd.setStatus('current') if mibBuilder.loadTexts: pfTimeoutsAdaptiveEnd.setDescription('When reaching this number of state entries, all timeout values become zero, effectively purging all state entries immediately.') pfTimeoutsSrcNode = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 6, 19), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTimeoutsSrcNode.setStatus('current') if mibBuilder.loadTexts: pfTimeoutsSrcNode.setDescription('Length of time to retain a source tracking entry after the last state expires.') pfLogInterfaceName = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 7, 1), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfLogInterfaceName.setStatus('current') if mibBuilder.loadTexts: pfLogInterfaceName.setDescription("The name of the interface configured with 'set loginterface'. If no interface has been configured, the object will be empty.") pfLogInterfaceIp4BytesIn = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 7, 2), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfLogInterfaceIp4BytesIn.setStatus('current') if mibBuilder.loadTexts: pfLogInterfaceIp4BytesIn.setDescription('Number of IPv4 bytes passed in on the loginterface.') pfLogInterfaceIp4BytesOut = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 7, 3), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfLogInterfaceIp4BytesOut.setStatus('current') if mibBuilder.loadTexts: pfLogInterfaceIp4BytesOut.setDescription('Number of IPv4 bytes passed out on the loginterface.') pfLogInterfaceIp4PktsInPass = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 7, 4), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfLogInterfaceIp4PktsInPass.setStatus('current') if mibBuilder.loadTexts: pfLogInterfaceIp4PktsInPass.setDescription('Number of IPv4 packets passed in on the loginterface.') pfLogInterfaceIp4PktsInDrop = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 7, 5), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfLogInterfaceIp4PktsInDrop.setStatus('current') if mibBuilder.loadTexts: pfLogInterfaceIp4PktsInDrop.setDescription('Number of IPv4 packets dropped coming in on the loginterface.') pfLogInterfaceIp4PktsOutPass = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 7, 6), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfLogInterfaceIp4PktsOutPass.setStatus('current') if mibBuilder.loadTexts: pfLogInterfaceIp4PktsOutPass.setDescription('Number of IPv4 packets passed out on the loginterface.') pfLogInterfaceIp4PktsOutDrop = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 7, 7), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfLogInterfaceIp4PktsOutDrop.setStatus('current') if mibBuilder.loadTexts: pfLogInterfaceIp4PktsOutDrop.setDescription('Number of IPv4 packets dropped going out on the loginterface.') pfLogInterfaceIp6BytesIn = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 7, 8), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfLogInterfaceIp6BytesIn.setStatus('current') if mibBuilder.loadTexts: pfLogInterfaceIp6BytesIn.setDescription('Number of IPv6 bytes passed in on the loginterface.') pfLogInterfaceIp6BytesOut = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 7, 9), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfLogInterfaceIp6BytesOut.setStatus('current') if mibBuilder.loadTexts: pfLogInterfaceIp6BytesOut.setDescription('Number of IPv6 bytes passed out on the loginterface.') pfLogInterfaceIp6PktsInPass = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 7, 10), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfLogInterfaceIp6PktsInPass.setStatus('current') if mibBuilder.loadTexts: pfLogInterfaceIp6PktsInPass.setDescription('Number of IPv6 packets passed in on the loginterface.') pfLogInterfaceIp6PktsInDrop = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 7, 11), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfLogInterfaceIp6PktsInDrop.setStatus('current') if mibBuilder.loadTexts: pfLogInterfaceIp6PktsInDrop.setDescription('Number of IPv6 packets dropped coming in on the loginterface.') pfLogInterfaceIp6PktsOutPass = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 7, 12), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfLogInterfaceIp6PktsOutPass.setStatus('current') if mibBuilder.loadTexts: pfLogInterfaceIp6PktsOutPass.setDescription('Number of IPv6 packets passed out on the loginterface.') pfLogInterfaceIp6PktsOutDrop = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 7, 13), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfLogInterfaceIp6PktsOutDrop.setStatus('current') if mibBuilder.loadTexts: pfLogInterfaceIp6PktsOutDrop.setDescription('Number of IPv6 packets dropped going out on the loginterface.') pfInterfacesIfNumber = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 8, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfInterfacesIfNumber.setStatus('current') if mibBuilder.loadTexts: pfInterfacesIfNumber.setDescription('The number of network interfaces on this system.') pfInterfacesIfTable = MibTable((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 8, 2), ) if mibBuilder.loadTexts: pfInterfacesIfTable.setStatus('current') if mibBuilder.loadTexts: pfInterfacesIfTable.setDescription('Table of network interfaces, indexed on pfInterfacesIfNumber.') pfInterfacesIfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 8, 2, 1), ).setIndexNames((0, "BEGEMOT-PF-MIB", "pfInterfacesIfIndex")) if mibBuilder.loadTexts: pfInterfacesIfEntry.setStatus('current') if mibBuilder.loadTexts: pfInterfacesIfEntry.setDescription('An entry in the pfInterfacesIfTable containing information about a particular network interface in the machine.') pfInterfacesIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 8, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))) if mibBuilder.loadTexts: pfInterfacesIfIndex.setStatus('current') if mibBuilder.loadTexts: pfInterfacesIfIndex.setDescription('A unique value, greater than zero, for each interface.') pfInterfacesIfDescr = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 8, 2, 1, 2), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfInterfacesIfDescr.setStatus('current') if mibBuilder.loadTexts: pfInterfacesIfDescr.setDescription('The name of the interface.') pfInterfacesIfType = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 8, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("group", 0), ("instance", 1), ("detached", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: pfInterfacesIfType.setStatus('current') if mibBuilder.loadTexts: pfInterfacesIfType.setDescription('Indicates whether the interface is a group inteface, an interface instance, or whether it has been removed or destroyed.') pfInterfacesIfTZero = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 8, 2, 1, 4), TimeTicks()).setUnits('1/100th of a Second').setMaxAccess("readonly") if mibBuilder.loadTexts: pfInterfacesIfTZero.setStatus('current') if mibBuilder.loadTexts: pfInterfacesIfTZero.setDescription('Time since statistics were last reset or since the interface was loaded.') pfInterfacesIfRefsState = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 8, 2, 1, 5), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfInterfacesIfRefsState.setStatus('current') if mibBuilder.loadTexts: pfInterfacesIfRefsState.setDescription('The number of state and/or source track entries referencing this interface.') pfInterfacesIfRefsRule = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 8, 2, 1, 6), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfInterfacesIfRefsRule.setStatus('current') if mibBuilder.loadTexts: pfInterfacesIfRefsRule.setDescription('The number of rules referencing this interface.') pfInterfacesIf4BytesInPass = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 8, 2, 1, 7), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfInterfacesIf4BytesInPass.setStatus('current') if mibBuilder.loadTexts: pfInterfacesIf4BytesInPass.setDescription('The number of IPv4 bytes passed coming in on this interface.') pfInterfacesIf4BytesInBlock = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 8, 2, 1, 8), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfInterfacesIf4BytesInBlock.setStatus('current') if mibBuilder.loadTexts: pfInterfacesIf4BytesInBlock.setDescription('The number of IPv4 bytes blocked coming in on this interface.') pfInterfacesIf4BytesOutPass = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 8, 2, 1, 9), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfInterfacesIf4BytesOutPass.setStatus('current') if mibBuilder.loadTexts: pfInterfacesIf4BytesOutPass.setDescription('The number of IPv4 bytes passed going out on this interface.') pfInterfacesIf4BytesOutBlock = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 8, 2, 1, 10), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfInterfacesIf4BytesOutBlock.setStatus('current') if mibBuilder.loadTexts: pfInterfacesIf4BytesOutBlock.setDescription('The number of IPv4 bytes blocked going out on this interface.') pfInterfacesIf4PktsInPass = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 8, 2, 1, 11), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfInterfacesIf4PktsInPass.setStatus('current') if mibBuilder.loadTexts: pfInterfacesIf4PktsInPass.setDescription('The number of IPv4 packets passed coming in on this interface.') pfInterfacesIf4PktsInBlock = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 8, 2, 1, 12), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfInterfacesIf4PktsInBlock.setStatus('current') if mibBuilder.loadTexts: pfInterfacesIf4PktsInBlock.setDescription('The number of IPv4 packets blocked coming in on this interface.') pfInterfacesIf4PktsOutPass = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 8, 2, 1, 13), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfInterfacesIf4PktsOutPass.setStatus('current') if mibBuilder.loadTexts: pfInterfacesIf4PktsOutPass.setDescription('The number of IPv4 packets passed going out on this interface.') pfInterfacesIf4PktsOutBlock = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 8, 2, 1, 14), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfInterfacesIf4PktsOutBlock.setStatus('current') if mibBuilder.loadTexts: pfInterfacesIf4PktsOutBlock.setDescription('The number of IPv4 packets blocked going out on this interface.') pfInterfacesIf6BytesInPass = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 8, 2, 1, 15), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfInterfacesIf6BytesInPass.setStatus('current') if mibBuilder.loadTexts: pfInterfacesIf6BytesInPass.setDescription('The number of IPv6 bytes passed coming in on this interface.') pfInterfacesIf6BytesInBlock = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 8, 2, 1, 16), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfInterfacesIf6BytesInBlock.setStatus('current') if mibBuilder.loadTexts: pfInterfacesIf6BytesInBlock.setDescription('The number of IPv6 bytes blocked coming in on this interface.') pfInterfacesIf6BytesOutPass = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 8, 2, 1, 17), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfInterfacesIf6BytesOutPass.setStatus('current') if mibBuilder.loadTexts: pfInterfacesIf6BytesOutPass.setDescription('The number of IPv6 bytes passed going out on this interface.') pfInterfacesIf6BytesOutBlock = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 8, 2, 1, 18), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfInterfacesIf6BytesOutBlock.setStatus('current') if mibBuilder.loadTexts: pfInterfacesIf6BytesOutBlock.setDescription('The number of IPv6 bytes blocked going out on this interface.') pfInterfacesIf6PktsInPass = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 8, 2, 1, 19), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfInterfacesIf6PktsInPass.setStatus('current') if mibBuilder.loadTexts: pfInterfacesIf6PktsInPass.setDescription('The number of IPv6 packets passed coming in on this interface.') pfInterfacesIf6PktsInBlock = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 8, 2, 1, 20), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfInterfacesIf6PktsInBlock.setStatus('current') if mibBuilder.loadTexts: pfInterfacesIf6PktsInBlock.setDescription('The number of IPv6 packets blocked coming in on this interface.') pfInterfacesIf6PktsOutPass = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 8, 2, 1, 21), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfInterfacesIf6PktsOutPass.setStatus('current') if mibBuilder.loadTexts: pfInterfacesIf6PktsOutPass.setDescription('The number of IPv6 packets passed going out on this interface.') pfInterfacesIf6PktsOutBlock = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 8, 2, 1, 22), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfInterfacesIf6PktsOutBlock.setStatus('current') if mibBuilder.loadTexts: pfInterfacesIf6PktsOutBlock.setDescription('The number of IPv6 packets blocked going out on this interface.') pfTablesTblNumber = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTablesTblNumber.setStatus('current') if mibBuilder.loadTexts: pfTablesTblNumber.setDescription('The number of tables on this system.') pfTablesTblTable = MibTable((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 2), ) if mibBuilder.loadTexts: pfTablesTblTable.setStatus('current') if mibBuilder.loadTexts: pfTablesTblTable.setDescription('Table of tables, index on pfTablesTblIndex.') pfTablesTblEntry = MibTableRow((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 2, 1), ).setIndexNames((0, "BEGEMOT-PF-MIB", "pfTablesTblIndex")) if mibBuilder.loadTexts: pfTablesTblEntry.setStatus('current') if mibBuilder.loadTexts: pfTablesTblEntry.setDescription('Any entry in the pfTablesTblTable containing information about a particular table on the system.') pfTablesTblIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))) if mibBuilder.loadTexts: pfTablesTblIndex.setStatus('current') if mibBuilder.loadTexts: pfTablesTblIndex.setDescription('A unique value, greater than zero, for each table.') pfTablesTblDescr = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 2, 1, 2), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTablesTblDescr.setStatus('current') if mibBuilder.loadTexts: pfTablesTblDescr.setDescription('The name of the table.') pfTablesTblCount = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 2, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTablesTblCount.setStatus('current') if mibBuilder.loadTexts: pfTablesTblCount.setDescription('The number of addresses in the table.') pfTablesTblTZero = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 2, 1, 4), TimeTicks()).setUnits('1/100th of a Second').setMaxAccess("readonly") if mibBuilder.loadTexts: pfTablesTblTZero.setStatus('current') if mibBuilder.loadTexts: pfTablesTblTZero.setDescription('The time passed since the statistics of this table were last cleared or the time since this table was loaded, whichever is sooner.') pfTablesTblRefsAnchor = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 2, 1, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTablesTblRefsAnchor.setStatus('current') if mibBuilder.loadTexts: pfTablesTblRefsAnchor.setDescription('The number of anchors referencing this table.') pfTablesTblRefsRule = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 2, 1, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTablesTblRefsRule.setStatus('current') if mibBuilder.loadTexts: pfTablesTblRefsRule.setDescription('The number of rules referencing this table.') pfTablesTblEvalMatch = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 2, 1, 7), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTablesTblEvalMatch.setStatus('current') if mibBuilder.loadTexts: pfTablesTblEvalMatch.setDescription('The number of evaluations returning a match.') pfTablesTblEvalNoMatch = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 2, 1, 8), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTablesTblEvalNoMatch.setStatus('current') if mibBuilder.loadTexts: pfTablesTblEvalNoMatch.setDescription('The number of evaluations not returning a match.') pfTablesTblBytesInPass = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 2, 1, 9), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTablesTblBytesInPass.setStatus('current') if mibBuilder.loadTexts: pfTablesTblBytesInPass.setDescription('The number of bytes passed in matching the table.') pfTablesTblBytesInBlock = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 2, 1, 10), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTablesTblBytesInBlock.setStatus('current') if mibBuilder.loadTexts: pfTablesTblBytesInBlock.setDescription('The number of bytes blocked coming in matching the table.') pfTablesTblBytesInXPass = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 2, 1, 11), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTablesTblBytesInXPass.setStatus('current') if mibBuilder.loadTexts: pfTablesTblBytesInXPass.setDescription('The number of bytes statefully passed in where the state entry refers to the table, but the table no longer contains the address in question.') pfTablesTblBytesOutPass = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 2, 1, 12), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTablesTblBytesOutPass.setStatus('current') if mibBuilder.loadTexts: pfTablesTblBytesOutPass.setDescription('The number of bytes passed out matching the table.') pfTablesTblBytesOutBlock = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 2, 1, 13), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTablesTblBytesOutBlock.setStatus('current') if mibBuilder.loadTexts: pfTablesTblBytesOutBlock.setDescription('The number of bytes blocked going out matching the table.') pfTablesTblBytesOutXPass = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 2, 1, 14), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTablesTblBytesOutXPass.setStatus('current') if mibBuilder.loadTexts: pfTablesTblBytesOutXPass.setDescription('The number of bytes statefully passed out where the state entry refers to the table, but the table no longer contains the address in question.') pfTablesTblPktsInPass = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 2, 1, 15), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTablesTblPktsInPass.setStatus('current') if mibBuilder.loadTexts: pfTablesTblPktsInPass.setDescription('The number of packets passed in matching the table.') pfTablesTblPktsInBlock = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 2, 1, 16), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTablesTblPktsInBlock.setStatus('current') if mibBuilder.loadTexts: pfTablesTblPktsInBlock.setDescription('The number of packets blocked coming in matching the table.') pfTablesTblPktsInXPass = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 2, 1, 17), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTablesTblPktsInXPass.setStatus('current') if mibBuilder.loadTexts: pfTablesTblPktsInXPass.setDescription('The number of packets statefully passed in where the state entry refers to the table, but the table no longer contains the address in question.') pfTablesTblPktsOutPass = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 2, 1, 18), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTablesTblPktsOutPass.setStatus('current') if mibBuilder.loadTexts: pfTablesTblPktsOutPass.setDescription('The number of packets passed out matching the table.') pfTablesTblPktsOutBlock = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 2, 1, 19), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTablesTblPktsOutBlock.setStatus('current') if mibBuilder.loadTexts: pfTablesTblPktsOutBlock.setDescription('The number of packets blocked going out matching the table.') pfTablesTblPktsOutXPass = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 2, 1, 20), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTablesTblPktsOutXPass.setStatus('current') if mibBuilder.loadTexts: pfTablesTblPktsOutXPass.setDescription('The number of packets statefully passed out where the state entry refers to the table, but the table no longer contains the address in question.') pfTablesAddrTable = MibTable((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 3), ) if mibBuilder.loadTexts: pfTablesAddrTable.setStatus('current') if mibBuilder.loadTexts: pfTablesAddrTable.setDescription('Table of addresses from every table on the system.') pfTablesAddrEntry = MibTableRow((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 3, 1), ).setIndexNames((0, "BEGEMOT-PF-MIB", "pfTablesAddrIndex")) if mibBuilder.loadTexts: pfTablesAddrEntry.setStatus('current') if mibBuilder.loadTexts: pfTablesAddrEntry.setDescription('An entry in the pfTablesAddrTable containing information about a particular entry in a table.') pfTablesAddrIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))) if mibBuilder.loadTexts: pfTablesAddrIndex.setStatus('current') if mibBuilder.loadTexts: pfTablesAddrIndex.setDescription('A unique value, greater than zero, for each address.') pfTablesAddrNet = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 3, 1, 2), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTablesAddrNet.setStatus('current') if mibBuilder.loadTexts: pfTablesAddrNet.setDescription('The IP address of this particular table entry.') pfTablesAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 3, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 32))).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTablesAddrMask.setStatus('current') if mibBuilder.loadTexts: pfTablesAddrMask.setDescription('The CIDR netmask of this particular table entry.') pfTablesAddrTZero = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 3, 1, 4), TimeTicks()).setUnits('1/100th of a Second').setMaxAccess("readonly") if mibBuilder.loadTexts: pfTablesAddrTZero.setStatus('current') if mibBuilder.loadTexts: pfTablesAddrTZero.setDescription("The time passed since this entry's statistics were last cleared, or the time passed since this entry was loaded into the table, whichever is sooner.") pfTablesAddrBytesInPass = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 3, 1, 5), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTablesAddrBytesInPass.setStatus('current') if mibBuilder.loadTexts: pfTablesAddrBytesInPass.setDescription('The number of inbound bytes passed as a result of this entry.') pfTablesAddrBytesInBlock = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 3, 1, 6), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTablesAddrBytesInBlock.setStatus('current') if mibBuilder.loadTexts: pfTablesAddrBytesInBlock.setDescription('The number of inbound bytes blocked as a result of this entry.') pfTablesAddrBytesOutPass = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 3, 1, 7), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTablesAddrBytesOutPass.setStatus('current') if mibBuilder.loadTexts: pfTablesAddrBytesOutPass.setDescription('The number of outbound bytes passed as a result of this entry.') pfTablesAddrBytesOutBlock = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 3, 1, 8), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTablesAddrBytesOutBlock.setStatus('current') if mibBuilder.loadTexts: pfTablesAddrBytesOutBlock.setDescription('The number of outbound bytes blocked as a result of this entry.') pfTablesAddrPktsInPass = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 3, 1, 9), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTablesAddrPktsInPass.setStatus('current') if mibBuilder.loadTexts: pfTablesAddrPktsInPass.setDescription('The number of inbound packets passed as a result of this entry.') pfTablesAddrPktsInBlock = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 3, 1, 10), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTablesAddrPktsInBlock.setStatus('current') if mibBuilder.loadTexts: pfTablesAddrPktsInBlock.setDescription('The number of inbound packets blocked as a result of this entry.') pfTablesAddrPktsOutPass = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 3, 1, 11), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTablesAddrPktsOutPass.setStatus('current') if mibBuilder.loadTexts: pfTablesAddrPktsOutPass.setDescription('The number of outbound packets passed as a result of this entry.') pfTablesAddrPktsOutBlock = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 9, 3, 1, 12), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfTablesAddrPktsOutBlock.setStatus('current') if mibBuilder.loadTexts: pfTablesAddrPktsOutBlock.setDescription('The number of outbound packets blocked as a result of this entry.') pfAltqQueueNumber = MibScalar((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 10, 1), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfAltqQueueNumber.setStatus('current') if mibBuilder.loadTexts: pfAltqQueueNumber.setDescription('The number of queues in the active set.') pfAltqQueueTable = MibTable((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 10, 2), ) if mibBuilder.loadTexts: pfAltqQueueTable.setStatus('current') if mibBuilder.loadTexts: pfAltqQueueTable.setDescription('Table containing the rules that are active on this system.') pfAltqQueueEntry = MibTableRow((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 10, 2, 1), ).setIndexNames((0, "BEGEMOT-PF-MIB", "pfAltqQueueIndex")) if mibBuilder.loadTexts: pfAltqQueueEntry.setStatus('current') if mibBuilder.loadTexts: pfAltqQueueEntry.setDescription('An entry in the pfAltqQueueTable table.') pfAltqQueueIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 10, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))) if mibBuilder.loadTexts: pfAltqQueueIndex.setStatus('current') if mibBuilder.loadTexts: pfAltqQueueIndex.setDescription('A unique value, greater than zero, for each queue.') pfAltqQueueDescr = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 10, 2, 1, 2), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfAltqQueueDescr.setStatus('current') if mibBuilder.loadTexts: pfAltqQueueDescr.setDescription('The name of the queue.') pfAltqQueueParent = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 10, 2, 1, 3), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfAltqQueueParent.setStatus('current') if mibBuilder.loadTexts: pfAltqQueueParent.setDescription("Name of the queue's parent if it has one.") pfAltqQueueScheduler = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 10, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 8, 11))).clone(namedValues=NamedValues(("cbq", 1), ("hfsc", 8), ("priq", 11)))).setMaxAccess("readonly") if mibBuilder.loadTexts: pfAltqQueueScheduler.setStatus('current') if mibBuilder.loadTexts: pfAltqQueueScheduler.setDescription('Scheduler algorithm implemented by this queue.') pfAltqQueueBandwidth = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 10, 2, 1, 5), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfAltqQueueBandwidth.setStatus('current') if mibBuilder.loadTexts: pfAltqQueueBandwidth.setDescription('Bandwitch assigned to this queue.') pfAltqQueuePriority = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 10, 2, 1, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfAltqQueuePriority.setStatus('current') if mibBuilder.loadTexts: pfAltqQueuePriority.setDescription('Priority level of the queue.') pfAltqQueueLimit = MibTableColumn((1, 3, 6, 1, 4, 1, 12325, 1, 200, 1, 10, 2, 1, 7), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pfAltqQueueLimit.setStatus('current') if mibBuilder.loadTexts: pfAltqQueueLimit.setDescription('Maximum number of packets in the queue.') mibBuilder.exportSymbols("BEGEMOT-PF-MIB", pfTablesTblIndex=pfTablesTblIndex, pfLogInterfaceIp4PktsOutPass=pfLogInterfaceIp4PktsOutPass, pfTimeoutsTcpOpening=pfTimeoutsTcpOpening, pfStatusRunning=pfStatusRunning, pfStateTableCount=pfStateTableCount, pfSrcNodesSearches=pfSrcNodesSearches, pfCounterBadOffset=pfCounterBadOffset, pfStateTableSearches=pfStateTableSearches, pfTablesTblTable=pfTablesTblTable, pfInterfacesIf6PktsInPass=pfInterfacesIf6PktsInPass, pfInterfacesIf6BytesOutBlock=pfInterfacesIf6BytesOutBlock, pfTablesTblPktsOutPass=pfTablesTblPktsOutPass, pfLogInterfaceIp6BytesOut=pfLogInterfaceIp6BytesOut, pfStatusRuntime=pfStatusRuntime, pfLogInterfaceIp4PktsInDrop=pfLogInterfaceIp4PktsInDrop, pfInterfacesIf4PktsInBlock=pfInterfacesIf4PktsInBlock, pfAltqQueueParent=pfAltqQueueParent, pfInterfacesIfEntry=pfInterfacesIfEntry, pfTablesTblEvalNoMatch=pfTablesTblEvalNoMatch, pfTablesTblBytesOutPass=pfTablesTblBytesOutPass, PYSNMP_MODULE_ID=begemotPf, pfStatusHostId=pfStatusHostId, pfLogInterfaceIp4BytesOut=pfLogInterfaceIp4BytesOut, pfTablesAddrEntry=pfTablesAddrEntry, pfTablesTblPktsInXPass=pfTablesTblPktsInXPass, pfTimeoutsTcpClosing=pfTimeoutsTcpClosing, pfLogInterfaceIp6PktsOutDrop=pfLogInterfaceIp6PktsOutDrop, pfTablesTblBytesInPass=pfTablesTblBytesInPass, pfAltqQueueDescr=pfAltqQueueDescr, pfTimeoutsOtherFirst=pfTimeoutsOtherFirst, pfTablesTblBytesOutBlock=pfTablesTblBytesOutBlock, pfAltqQueueLimit=pfAltqQueueLimit, pfTablesTblPktsInBlock=pfTablesTblPktsInBlock, pfAltqQueueBandwidth=pfAltqQueueBandwidth, pfCounterMemDrop=pfCounterMemDrop, pfInterfacesIf6BytesInBlock=pfInterfacesIf6BytesInBlock, pfInterfaces=pfInterfaces, pfTimeoutsUdpFirst=pfTimeoutsUdpFirst, pfStateTable=pfStateTable, pfInterfacesIf4PktsOutBlock=pfInterfacesIf4PktsOutBlock, pfTimeoutsAdaptiveEnd=pfTimeoutsAdaptiveEnd, pfTablesTblEvalMatch=pfTablesTblEvalMatch, pfInterfacesIfNumber=pfInterfacesIfNumber, pfTablesTblRefsRule=pfTablesTblRefsRule, pfTimeoutsOtherMultiple=pfTimeoutsOtherMultiple, pfTimeoutsTcpFinWait=pfTimeoutsTcpFinWait, pfLogInterfaceIp6BytesIn=pfLogInterfaceIp6BytesIn, pfTablesTblPktsOutXPass=pfTablesTblPktsOutXPass, pfLimits=pfLimits, pfLogInterface=pfLogInterface, pfTimeoutsTcpEstablished=pfTimeoutsTcpEstablished, pfLogInterfaceIp6PktsInPass=pfLogInterfaceIp6PktsInPass, pfAltq=pfAltq, pfTablesTblBytesInXPass=pfTablesTblBytesInXPass, pfTablesTblTZero=pfTablesTblTZero, pfTablesTblRefsAnchor=pfTablesTblRefsAnchor, pfTablesAddrBytesInBlock=pfTablesAddrBytesInBlock, pfInterfacesIf4PktsOutPass=pfInterfacesIf4PktsOutPass, pfTimeoutsTcpClosed=pfTimeoutsTcpClosed, pfInterfacesIf6PktsOutPass=pfInterfacesIf6PktsOutPass, pfTablesAddrPktsInBlock=pfTablesAddrPktsInBlock, begemotPfObjects=begemotPfObjects, pfStateTableRemovals=pfStateTableRemovals, pfTablesAddrBytesInPass=pfTablesAddrBytesInPass, pfTablesTblPktsOutBlock=pfTablesTblPktsOutBlock, pfCounterFragment=pfCounterFragment, pfTimeoutsIcmpFirst=pfTimeoutsIcmpFirst, pfInterfacesIf4BytesOutPass=pfInterfacesIf4BytesOutPass, pfTablesAddrTable=pfTablesAddrTable, pfInterfacesIf4PktsInPass=pfInterfacesIf4PktsInPass, pfLogInterfaceIp6PktsInDrop=pfLogInterfaceIp6PktsInDrop, pfStatusDebug=pfStatusDebug, pfTimeouts=pfTimeouts, pfInterfacesIf4BytesOutBlock=pfInterfacesIf4BytesOutBlock, pfTablesAddrMask=pfTablesAddrMask, pfLogInterfaceIp4BytesIn=pfLogInterfaceIp4BytesIn, pfInterfacesIfTZero=pfInterfacesIfTZero, pfInterfacesIf6PktsOutBlock=pfInterfacesIf6PktsOutBlock, pfCounter=pfCounter, pfTablesAddrBytesOutPass=pfTablesAddrBytesOutPass, pfInterfacesIf6BytesInPass=pfInterfacesIf6BytesInPass, pfTimeoutsUdpSingle=pfTimeoutsUdpSingle, pfInterfacesIfRefsState=pfInterfacesIfRefsState, pfTables=pfTables, pfSrcNodesCount=pfSrcNodesCount, pfTimeoutsFragment=pfTimeoutsFragment, pfInterfacesIfDescr=pfInterfacesIfDescr, pfInterfacesIf6PktsInBlock=pfInterfacesIf6PktsInBlock, pfLogInterfaceIp4PktsOutDrop=pfLogInterfaceIp4PktsOutDrop, pfTablesTblEntry=pfTablesTblEntry, pfInterfacesIf4BytesInBlock=pfInterfacesIf4BytesInBlock, pfTablesAddrTZero=pfTablesAddrTZero, pfTimeoutsOtherSingle=pfTimeoutsOtherSingle, pfLogInterfaceIp4PktsInPass=pfLogInterfaceIp4PktsInPass, pfAltqQueuePriority=pfAltqQueuePriority, pfLogInterfaceIp6PktsOutPass=pfLogInterfaceIp6PktsOutPass, pfTimeoutsAdaptiveStart=pfTimeoutsAdaptiveStart, pfTimeoutsIcmpError=pfTimeoutsIcmpError, begemotPf=begemotPf, pfInterfacesIfIndex=pfInterfacesIfIndex, pfLimitsSrcNodes=pfLimitsSrcNodes, pfCounterMatch=pfCounterMatch, pfInterfacesIfType=pfInterfacesIfType, pfLimitsFrags=pfLimitsFrags, pfCounterNormalize=pfCounterNormalize, pfStateTableInserts=pfStateTableInserts, pfTimeoutsSrcNode=pfTimeoutsSrcNode, pfSrcNodes=pfSrcNodes, pfTimeoutsUdpMultiple=pfTimeoutsUdpMultiple, pfAltqQueueTable=pfAltqQueueTable, pfTablesTblPktsInPass=pfTablesTblPktsInPass, pfAltqQueueNumber=pfAltqQueueNumber, pfStatus=pfStatus, pfTablesTblNumber=pfTablesTblNumber, pfTablesAddrBytesOutBlock=pfTablesAddrBytesOutBlock, pfTablesAddrPktsOutBlock=pfTablesAddrPktsOutBlock, pfAltqQueueIndex=pfAltqQueueIndex, pfSrcNodesInserts=pfSrcNodesInserts, pfInterfacesIf4BytesInPass=pfInterfacesIf4BytesInPass, pfTablesTblDescr=pfTablesTblDescr, pfSrcNodesRemovals=pfSrcNodesRemovals, pfTablesTblCount=pfTablesTblCount, pfTablesAddrPktsInPass=pfTablesAddrPktsInPass, pfInterfacesIf6BytesOutPass=pfInterfacesIf6BytesOutPass, pfTablesTblBytesInBlock=pfTablesTblBytesInBlock, pfLimitsStates=pfLimitsStates, pfTablesAddrIndex=pfTablesAddrIndex, pfTimeoutsTcpFirst=pfTimeoutsTcpFirst, pfAltqQueueEntry=pfAltqQueueEntry, pfTablesAddrNet=pfTablesAddrNet, pfCounterShort=pfCounterShort, pfTimeoutsInterval=pfTimeoutsInterval, pfAltqQueueScheduler=pfAltqQueueScheduler, pfTablesTblBytesOutXPass=pfTablesTblBytesOutXPass, pfTablesAddrPktsOutPass=pfTablesAddrPktsOutPass, pfInterfacesIfTable=pfInterfacesIfTable, pfLogInterfaceName=pfLogInterfaceName, pfInterfacesIfRefsRule=pfInterfacesIfRefsRule)
# -*- coding:utf-8 -*- p = raw_input("Escribe una frase: ") for letras in p: print(p.upper())
# -*- coding: utf-8 -*- # A idéia para este problema é criar uma lista com os estados da região norte no formato de string, depois disso # é checado se o estado inserido está contido na lista e é exibido o resultado. # Lista de estados da ragião norte rn = ["acre", "amapa", "amazonas", "para", "rondonia", "roraima", "tocantins"] # Input do estado e = input() # Caso o estado esteja na região norte if e in rn: # Exibe o resultado print("Regiao Norte") else: # Caso contrário exibe o outro resultado print("Outra regiao")
def find_words_in_phone_number(): phone_number = "3662277" words = ["foo", "bar", "baz", "foobar", "emo", "cap", "car", "cat"] lst = [] cmap = dict(a=2, b=2, c=2, d=3, e=3, f=3, g=4, h=4, i=4, j=5, k=5, l=5, m=6, n=6, o=6, p=7, q=7, r=7, s=7, t=8, u=8, v=8, w=9, x=9, y=9, z=9) for word in words: num = "".join(str(cmap.get(x.lower(), "0")) for x in word) found = num in phone_number print(found, word, num, phone_number) found and lst.append(word) print(lst) def countdown(count: int): for num in range(count, 0, -1): print(num) if __name__ == '__main__': find_words_in_phone_number()
CMarketRspInfoField = { "ErrorID": "int", "ErrorMsg": "string", } CMarketReqUserLoginField = { "UserId": "string", "UserPwd": "string", "UserType": "string", "MacAddress": "string", "ComputerName": "string", "SoftwareName": "string", "SoftwareVersion": "string", "AuthorCode": "string", "ErrorDescription": "string", } CMarketRspUserLoginField = { "UserName": "string", "UserPwd": "string", "UserType": "string", } CMarketReqUserLogoutField = { "BrokerID": "string", "UserId": "string", "ErrorDescription": "string", } CMarketReqMarketDataField = { "MarketType": "char", "SubscMode": "char", "MarketCount": "int", "MarketTrcode[MAX_SUB_COUNT]": "string", "ErrorDescription": "string", } CMarketRspMarketDataField = { "ExchangeCode": "string", "TreatyCode": "string", "BuyPrice": "string", "BuyNumber": "string", "SalePrice": "string", "SaleNumber": "string", "CurrPrice": "string", "CurrNumber": "string", "High": "string", "Low": "string", "Open": "string", "IntradaySettlePrice": "string", "Close": "string", "Time": "string", "FilledNum": "string", "HoldNum": "string", "BuyPrice2": "string", "BuyPrice3": "string", "BuyPrice4": "string", "BuyPrice5": "string", "BuyNumber2": "string", "BuyNumber3": "string", "BuyNumber4": "string", "BuyNumber5": "string", "SalePrice2": "string", "SalePrice3": "string", "SalePrice4": "string", "SalePrice5": "string", "SaleNumber2": "string", "SaleNumber3": "string", "SaleNumber4": "string", "SaleNumber5": "string", "HideBuyPrice": "string", "HideBuyNumber": "string", "HideSalePrice": "string", "HideSaleNumber": "string", "LimitDownPrice": "string", "LimitUpPrice": "string", "TradeDay": "string", "BuyPrice6": "string", "BuyPrice7": "string", "BuyPrice8": "string", "BuyPrice9": "string", "BuyPrice10": "string", "BuyNumber6": "string", "BuyNumber7": "string", "BuyNumber8": "string", "BuyNumber9": "string", "BuyNumber10": "string", "SalePrice6": "string", "SalePrice7": "string", "SalePrice8": "string", "SalePrice9": "string", "SalePrice10": "string", "SaleNumber6": "string", "SaleNumber7": "string", "SaleNumber8": "string", "SaleNumber9": "string", "SaleNumber10": "string", "TradeFlag": "string", "DataTimestamp": "string", "DataSourceId": "string", "CanSellVol": "string", "QuoteType": "string", "AggressorSide": "string", "PreSettlementPrice": "string", } CMarketReqBrokerDataField = { "ContCode": "string", "ErrorDescription": "string", } CMarketRspBrokerDataField = { "BrokerData": "string", } CMarketRspTradeDateField = { "TradeDate": "string", "TradeProduct": "string", }
# cook your dish here print("137=2(2(2)+2+2(0))+2(2+2(0))+2(0)") print("1315=2(2(2+2(0))+2)+2(2(2+2(0)))+2(2(2)+2(0))+2+2(0)") print("73=2(2(2)+2)+2(2+2(0))+2(0)") print("136=2(2(2)+2+2(0))+2(2+2(0))") print("255=2(2(2)+2+2(0))+2(2(2)+2)+2(2(2)+2(0))+2(2(2))+2(2+2(0))+2(2)+2+2(0)") print("1384=2(2(2+2(0))+2)+2(2(2+2(0)))+2(2(2)+2)+2(2(2)+2(0))+2(2+2(0))") print("16385=2(2(2+2(0))+2(2)+2)+2(0)")
#!/usr/bin/env python # -*- coding: utf-8 -*- """ __project__ = 'leetcode' __file__ = '__init__.py' __author__ = 'king' __time__ = '2020/1/10 22:37' _ooOoo_ o8888888o 88" . "88 (| -_- |) O\ = /O ____/`---'\____ .' \\| |// `. / \\||| : |||// \ / _||||| -:- |||||- \ | | \\\ - /// | | | \_| ''\---/'' | | \ .-\__ `-` ___/-. / ___`. .' /--.--\ `. . __ ."" '< `.___\_<|>_/___.' >'"". | | : `- \`.;`\ _ /`;.`/ - ` : | | \ \ `-. \_ __\ /__ _/ .-` / / ======`-.____`-.___\_____/___.-`____.-'====== `=---=' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 佛祖保佑 永无BUG """ """ 难度:简单 给定一个只包含小写字母的有序数组letters和一个目标字母target, 寻找有序数组里面比目标字母大的最小字母。 数组里字母的顺序是循环的。举个例子,如果目标字母target = 'z' 并且有序数组为letters = ['a', 'b'],则答案返回'a'。 输入: letters = ["c", "f", "j"] target = "a" 输出: "c" 输入: letters = ["c", "f", "j"] target = "c" 输出: "f" 输入: letters = ["c", "f", "j"] target = "d" 输出: "f" 输入: letters = ["c", "f", "j"] target = "g" 输出: "j" 输入: letters = ["c", "f", "j"] target = "j" 输出: "c" 输入: letters = ["c", "f", "j"] target = "k" 输出: "c" """ class Solution(object): def nextGreatestLetter(self, letters, target): """ :type letters: List[str] :type target: str :rtype: str """ left = 0 right = len(letters) - 1 while left <= right: mid = (left + right) // 2 if target < letters[mid]: right = mid - 1 else: left = mid + 1 return letters[left % len(letters)] print(Solution().nextGreatestLetter(["c", "f", "j"], "a"))
def área(largura, altura): print(f'\nA área de um terreno {largura}m x {altura}m é de {largura * altura}m².\n') print(f'\n{"Controle de Terrenos":^25}', '-' * 25, sep='\n') área(float(input("LARGURA (m): ")), float(input("ALTURA (m): ")))
#!/usr/bin/env python """ Copyright 2012 GroupDocs. 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. """ class UserInfo: """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.""" def __init__(self): self.swaggerTypes = { 'nickname': 'str', 'firstname': 'str', 'lastname': 'str', 'pkey': 'str', 'pswd_salt': 'str', 'claimed_id': 'str', 'token': 'str', 'storage': 'int', 'photo': 'list[int]', 'active': 'bool', 'trial': 'bool', 'news_eanbled': 'bool', 'alerts_eanbled': 'bool', 'support_eanbled': 'bool', 'support_email': 'str', 'annotation_branded': 'bool', 'viewer_branded': 'bool', 'is_real_time_broadcast_enabled': 'bool', 'is_scroll_broadcast_enabled': 'bool', 'is_zoom_broadcast_enabled': 'bool', 'annotation_logo': 'list[int]', 'pointer_tool_cursor': 'list[int]', 'annotation_header_options': 'int', 'is_annotation_navigation_widget_enabled': 'bool', 'is_annotation_zoom_widget_enabled': 'bool', 'is_annotation_download_widget_enabled': 'bool', 'is_annotation_print_widget_enabled': 'bool', 'is_annotation_help_widget_enabled': 'bool', 'is_right_panel_enabled': 'bool', 'is_thumbnails_panel_enabled': 'bool', 'is_standard_header_always_shown': 'bool', 'is_toolbar_enabled': 'bool', 'is_text_annotation_button_enabled': 'bool', 'is_rectangle_annotation_button_enabled': 'bool', 'is_point_annotation_button_enabled': 'bool', 'is_strikeout_annotation_button_enabled': 'bool', 'is_polyline_annotation_button_enabled': 'bool', 'is_typewriter_annotation_button_enabled': 'bool', 'is_watermark_annotation_button_enabled': 'bool', 'is_annotation_document_name_shown': 'bool', 'annotation_navigation_icons': 'list[int]', 'annotation_tool_icons': 'list[int]', 'annotation_background_color': 'int', 'viewer_logo': 'list[int]', 'viewer_options': 'int', 'is_viewer_navigation_widget_enabled': 'bool', 'is_viewer_zoom_widget_enabled': 'bool', 'is_viewer_download_widget_enabled': 'bool', 'is_viewer_print_widget_enabled': 'bool', 'is_viewer_help_widget_enabled': 'bool', 'is_viewer_document_name_shown': 'bool', 'isviewer_right_mouse_button_menu_enabled': 'bool', 'signedupOn': 'long', 'signedinOn': 'long', 'signin_count': 'int', 'roles': 'list[RoleInfo]', 'signature_watermark_enabled': 'bool', 'signature_desktop_notifications': 'bool', 'webhook_notification_retries': 'int', 'webhook_notification_failed_recipients': 'str', 'signature_color': 'str', 'id': 'float', 'guid': 'str', 'primary_email': 'str' } self.nickname = None # str self.firstname = None # str self.lastname = None # str self.pkey = None # str self.pswd_salt = None # str self.claimed_id = None # str self.token = None # str self.storage = None # int self.photo = None # list[int] self.active = None # bool self.trial = None # bool self.news_eanbled = None # bool self.alerts_eanbled = None # bool self.support_eanbled = None # bool self.support_email = None # str self.annotation_branded = None # bool self.viewer_branded = None # bool self.is_real_time_broadcast_enabled = None # bool self.is_scroll_broadcast_enabled = None # bool self.is_zoom_broadcast_enabled = None # bool self.annotation_logo = None # list[int] self.pointer_tool_cursor = None # list[int] self.annotation_header_options = None # int self.is_annotation_navigation_widget_enabled = None # bool self.is_annotation_zoom_widget_enabled = None # bool self.is_annotation_download_widget_enabled = None # bool self.is_annotation_print_widget_enabled = None # bool self.is_annotation_help_widget_enabled = None # bool self.is_right_panel_enabled = None # bool self.is_thumbnails_panel_enabled = None # bool self.is_standard_header_always_shown = None # bool self.is_toolbar_enabled = None # bool self.is_text_annotation_button_enabled = None # bool self.is_rectangle_annotation_button_enabled = None # bool self.is_point_annotation_button_enabled = None # bool self.is_strikeout_annotation_button_enabled = None # bool self.is_polyline_annotation_button_enabled = None # bool self.is_typewriter_annotation_button_enabled = None # bool self.is_watermark_annotation_button_enabled = None # bool self.is_annotation_document_name_shown = None # bool self.annotation_navigation_icons = None # list[int] self.annotation_tool_icons = None # list[int] self.annotation_background_color = None # int self.viewer_logo = None # list[int] self.viewer_options = None # int self.is_viewer_navigation_widget_enabled = None # bool self.is_viewer_zoom_widget_enabled = None # bool self.is_viewer_download_widget_enabled = None # bool self.is_viewer_print_widget_enabled = None # bool self.is_viewer_help_widget_enabled = None # bool self.is_viewer_document_name_shown = None # bool self.isviewer_right_mouse_button_menu_enabled = None # bool self.signedupOn = None # long self.signedinOn = None # long self.signin_count = None # int self.roles = None # list[RoleInfo] self.signature_watermark_enabled = None # bool self.signature_desktop_notifications = None # bool self.webhook_notification_retries = None # int self.webhook_notification_failed_recipients = None # str self.signature_color = None # str self.id = None # float self.guid = None # str self.primary_email = None # str
def get_current_players(current_room): host_user = current_room['host_user'] users = current_room['game']['users'] players = [player for player in users] players.append(host_user) return players
mi_dicc = { "Alemania": "Berlin", "Francia": "París", "Reino Unido": "Londres", "España": "Madrid" } print(mi_dicc["Francia"]) # París print(mi_dicc["España"]) # Madrid print(mi_dicc) # {'Alemania': 'Berlin', # 'Francia': 'París', # 'Reino Unido': 'Londres', # 'España': 'Madrid'} mi_dicc["Italia"] = "Lisboa" print(mi_dicc) # {'Alemania': 'Berlin', # 'Francia': 'París', # 'Reino Unido': 'Londres', # 'España': 'Madrid', # 'Italia': 'Lisboa'} mi_dicc["Italia"] = "Roma" print(mi_dicc) # {'Alemania': 'Berlin', # 'Francia': 'París', # 'Reino Unido': 'Londres', # 'España': 'Madrid', # 'Italia': 'Roma'} del mi_dicc["Reino Unido"] print(mi_dicc) # {'Alemania': 'Berlin', # 'Francia': 'París', # 'España': 'Madrid', # 'Italia': 'Roma'} mi_dicc = {"Alemania": "Berlín", 23: "Jordan", "Mosqueteros": 3} print(mi_dicc) # {'Alemania': 'Berlín', 23: 'Jordan', 'Mosqueteros': 3} mi_tupla = ("España", "Francia", "Reino Unido", "Alemania") mi_dicc = { mi_tupla[0]: "Madrid", mi_tupla[1]: "París", mi_tupla[2]: "Londres", mi_tupla[3]: "Berlín" } print(mi_dicc) # {'España': 'Madrid', # 'Francia': 'París', # 'Reino Unido': 'Londres', # 'Alemania': 'Berlín'} print(mi_dicc["España"]) # Madrid print(mi_dicc[mi_tupla[0]]) # Madrid mi_dicc = { 23: "Jordan", "Nombre": "Michael", "Equipo": "Chicago", "Anillos": (1991, 1992, 1993, 1996, 1997, 1998) } print(mi_dicc) # {23: 'Jordan', # 'Nombre': 'Michael', # 'Equipo': 'Chicago', # 'Anillos': (1991, 1992, 1993, 1996, 1997, 1998)} print(mi_dicc["Equipo"]) # Chicago print(mi_dicc["Anillos"]) # (1991, 1992, 1993, 1996, 1997, 1998) mi_dicc = { 23: "Jordan", "Nombre": "Michael", "Equipo": "Chicago", "Anillos": { "Temporadas": (1991, 1992, 1993, 1996, 1997, 1998) } } print(mi_dicc) # {23: 'Jordan', # 'Nombre': 'Michael', # 'Equipo': 'Chicago', # 'Anillos': {'Temporadas': (1991, 1992, 1993, 1996, 1997, 1998)}} print( mi_dicc["Anillos"]) # {'Temporadas': (1991, 1992, 1993, 1996, 1997, 1998)} print(mi_dicc.keys()) # dict_keys([23, 'Nombre', 'Equipo', 'Anillos']) print(mi_dicc.values()) # dict_values(['Jordan', 'Michael', 'Chicago', # {'Temporadas': (1991, 1992, 1993, 1996, 1997, 1998)}]) print(len(mi_dicc)) # 4
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Helpdesk', 'category': 'Customer Relationship Management', 'version': '1.0', 'description': """ Helpdesk Management. ==================== Like records and processing of claims, Helpdesk and Support are good tools to trace your interventions. This menu is more adapted to oral communication, which is not necessarily related to a claim. Select a customer, add notes and categorize your interventions with a channel and a priority level. """, 'author': 'OpenERP SA', 'website': 'http://www.openerp.com', 'depends': ['crm'], 'data': [ 'crm_helpdesk_view.xml', 'crm_helpdesk_menu.xml', 'security/ir.model.access.csv', 'report/crm_helpdesk_report_view.xml', 'crm_helpdesk_data.xml', ], 'demo': ['crm_helpdesk_demo.xml'], 'test': ['test/process/help-desk.yml'], 'installable': True, 'auto_install': False, 'images': ['images/helpdesk_analysis.jpeg','images/helpdesk_categories.jpeg','images/helpdesk_requests.jpeg'], } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
class DuckyScriptParser: ''' This class is a parser for the DuckyScript language. It allows to generate a sequence of frame to inject keystrokes according to the provided script. ''' def __init__(self,content="",filename=""): if content != "": self.content = content else: self.content = open(filename,"r").read() self.specialKeys ={ "ENTER":["ENTER"], "super":["GUI","WINDOWS"], "ctrl":["CTRL","CONTROL"], "alt":["ALT"], "shift":["SHIFT"], "DOWNARROW":["DOWNARROW","DOWN"], "UPARROW":["UPARROW","UP"], "LEFTARROW":["LEFTARROW","LEFT"], "RIGHTARROW":["RIGHTARROW","RIGHT"], "F1":["F1"], "F2":["F2"], "F3":["F3"], "F4":["F4"], "F5":["F5"], "F6":["F6"], "F7":["F7"], "F8":["F8"], "F9":["F9"], "F10":["F10"], "F11":["F11"], "F12":["F12"], "ESC":["ESC","ESCAPE"], "PAUSE":["PAUSE"], "SPACE":["SPACE"], "TAB":["TAB"], "END":["END"], "DELETE":["DELETE"], "PAUSE":["BREAK","PAUSE"], "PRINTSCREEN":["PRINTSCREEN"], "CAPSLOCK":["CAPSLOCK"], "SCROLLLOCK":["SCROLLLOCK"], "INSERT":["INSERT"], "HOME":["HOME"], "PAGEUP":["PAGEUP"], "PAGEDOWN":["PAGEDOWN"] } def _isSpecialKey(self,string): for k,v in self.specialKeys.items(): if string in v: return True return False def _getSpecialKey(self,string): for k,v in self.specialKeys.items(): if string in v: return k return string def _parseInstruction(self,instruction=[]): first = instruction[0] if first == "REM": return None elif first == "STRING": return {"type":"text", "param":" ".join(instruction[1:])} elif first == "DELAY": return {"type":"sleep", "param":int(instruction[1])} elif first == "REPEAT": return {"type":"repeat", "param":int(instruction[1])} elif first == "DEFAULTDELAY" or first == "DEFAULT_DELAY": return {"type":"defaultdelay", "param":int(instruction[1])} elif first == "APP" or first == "MENU": return {"type":"keys","param":["shift","F10"]} elif self._isSpecialKey(first): keys = [] for k in instruction: keys.append(self._getSpecialKey(k)) if len(keys)==1: if keys[0] in ("ctrl","alt","shift"): key = key.upper() elif keys[0] == "super": key = "GUI" else: key = keys[0] return {"type":"key", "param":key} else: return {"type":"keys", "param":keys} def _parse(self): self.instructions = [] instructions = self.content.split("\n") for instruction in instructions: tokens = instruction.split(" ") generated = self._parseInstruction(tokens) if generated is not None: self.instructions.append(generated) def _generatePacketsFromInstruction(self, currentDelay=0, previousInstruction={}, currentInstruction={}, textFunction=None, keyFunction=None, sleepFunction=None ): defaultDelay,packets = currentDelay, [] if currentInstruction["type"] == "defaultdelay": defaultDelay = currentInstruction["param"] elif currentInstruction["type"] == "sleep": packets += sleepFunction(duration=currentInstruction["param"]) elif currentInstruction["type"] == "repeat" and previousInstruction != {}: for _ in range(currentInstruction["param"]): defaultDelay,nextPackets = self._generatePacketsFromInstruction( currentDelay=currentDelay, previousInstruction={}, currentInstruction=previousInstruction, textFunction=textFunction, keyFunction=keyFunction, sleepFunction=sleepFunction ) packets += nextPackets elif currentInstruction["type"] == "text": packets += textFunction(string=currentInstruction["param"]) elif currentInstruction["type"] == "key": packets += keyFunction(key=currentInstruction["param"]) elif currentInstruction["type"] == "keys": ctrl = "ctrl" in currentInstruction["param"] alt = "alt" in currentInstruction["param"] gui = "super" in currentInstruction["param"] shift = "shift" in currentInstruction["param"] key = "" for i in currentInstruction["param"]: if i not in ("ctrl","alt","super","shift"): key = i packets += keyFunction(key=key,shift=shift,gui=gui,ctrl=ctrl,alt=alt) return defaultDelay,packets def generatePackets(self,textFunction=None, keyFunction=None, sleepFunction=None, initFunction=None): ''' This function allows to generate the sequence of packets corresponding to the provided script. You have to provide different functions that returns the sequence of packets for a given action. :param textFunction: function corresponding to a text injection :type textFunction: func :param keyFunction: function corresponding to a single keystroke injection :type keyFunction: func :param sleepFunction: function corresponding to a sleep interval :type sleepFunction: func :param initFunction: function corresponding to the initialization of the process :type initFunction: func :return: sequence of packets :rtype: list of ``mirage.libs.wireless_utils.packets.Packet`` ''' self._parse() defaultDelay = 0 previousInstruction = {} currentInstruction = {} packets = initFunction() for currentInstruction in self.instructions: newDelay,nextPackets = self._generatePacketsFromInstruction( currentDelay=defaultDelay, previousInstruction=previousInstruction, currentInstruction=currentInstruction, textFunction=textFunction, keyFunction=keyFunction, sleepFunction=sleepFunction ) packets += nextPackets defaultDelay = newDelay if defaultDelay > 0: packets += sleepFunction(duration=defaultDelay) previousInstruction = currentInstruction return packets
def Awana_Academy(name, age): ## say to python that all the code that come after that line is going to be in d function print("Hello " + name + "you are " + age + "years old ") Awana_Academy("Alex " , "45") Awana_Academy("Donald ", "12")
# https://www.codewars.com/kata/55d2aee99f30dbbf8b000001/ ''' Details : A new school year is approaching, which also means students will be taking tests. The tests in this kata are to be graded in different ways. A certain number of points will be given for each correct answer and a certain number of points will be deducted for each incorrect answer. For ommitted answers, points will either be awarded, deducted, or no points will be given at all. Return the number of points someone has scored on varying tests of different lengths. The given parameters will be: An array containing a series of 0s, 1s, and 2s, where 0 is a correct answer, 1 is an omitted answer, and 2 is an incorrect answer. The points awarded for correct answers The points awarded for omitted answers (note that this may be negative) The points deducted for incorrect answers (hint: this value has to be subtracted) Note: The input will always be valid (an array and three numbers) Examples #1: [0, 0, 0, 0, 2, 1, 0], 2, 0, 1 --> 9 because: 5 correct answers: 5*2 = 10 1 omitted answer: 1*0 = 0 1 wrong answer: 1*1 = 1 which is: 10 + 0 - 1 = 9 #2: [0, 1, 0, 0, 2, 1, 0, 2, 2, 1], 3, -1, 2) --> 3 because: 4*3 + 3*-1 - 3*2 = 3 ''' def score_test(tests, right, omit, wrong): return tests.count(0) * right + tests.count(1) * omit - tests.count(2) * wrong
# https://open.kattis.com/problems/babybites n = int(input()) inp = input().split() for i in range(0, n): if inp[i].isdigit(): if int(inp[i]) != i + 1: print('something is fishy') break else: print('makes sense')
#Let's use tuples to store information about a file: its name, #its type and its size in bytes. #Fill in the gaps in this code to return the size in kilobytes (a kilobyte is 1024 bytes) up to 2 decimal places. #Code: def file_size(file_info): name, type, size= file_info return("{:.2f}".format(size / 1024)) print(file_size(('Class Assignment', 'docx', 17875))) # Should print 17.46 print(file_size(('Notes', 'txt', 496))) # Should print 0.48 print(file_size(('Program', 'py', 1239))) # Should print 1.21
class DictToObj(object): """ transform a dict to a object """ def __init__(self, d): for a, b in d.items(): if type(a) is bytes: attr = a.decode() else: attr = a if isinstance(b, (list, tuple)): setattr(self, attr, [DictToObj(x) if isinstance(x, dict) else x for x in b]) else: setattr(self, attr, DictToObj(b) if isinstance(b, dict) else b) class DictToObjJson(object): """ transform a dict to a object """ def __init__(self, d): for a, b in d.items(): if type(a) is bytes: attr = a.decode() else: attr = a if type(b) is bytes: b = b.decode() if isinstance(b, (list, tuple)): setattr(self, attr, [DictToObj(x) if isinstance(x, dict) else x for x in b]) else: setattr(self, attr, DictToObj(b) if isinstance(b, dict) else b)
class Solution(object): def merge_sort(self,mylist): if len(mylist)<=1: return mylist n=len(mylist)//2#分為左右臨近的兩塊 left=mylist[:n] right=mylist[n:] return self.merge(self.merge_sort(left),self.merge_sort(right))#分別再對左右兩塊進行各自的左右分塊 def merge(self,left,right): r,l=0,0 result=[] while l<len(left) and r<len(right):#left中的數分別與right中的數進行比較、插入 if left[l]<=right[r]:#由於list內部已是比過大小的,所以若left第一個值小於right第一個值,則必定小於right中其他值,則無需再比較 result.append(left[l]) l+=1 else: result.append(right[r]) r+=1 result.extend(left[l:]) result.extend(right[r:])#將剩餘的數加回結果list後,防止值的丟失 return result
""" Given an array nums of 0s and 1s and an integer k, return True if all 1's are at least k places away from each other, otherwise return False. Input: nums = [1,0,0,0,1,0,0,1], k = 2 Output: true Explanation: Each of the 1s are at least 2 places away from each other. Input: nums = [1,1,1,1,1], k = 0 Output: true """ class Solution: def kLengthApart(self, nums: List[int], k: int) -> bool: count_zero = 0 for i, n in enumerate(nums): if n == 1: if i != 0 and count_zero < k: return False count_zero = 0 elif n == 0: count_zero += 1 if i == len(nums) - 1: return True
"""Clean Code in Python - Chapter 7: Using Generators > The Interface for Iteration * Distinguish between iterable objects and iterators * Create iterators """ class SequenceIterator: """ >>> si = SequenceIterator(1, 2) >>> next(si) 1 >>> next(si) 3 >>> next(si) 5 """ def __init__(self, start=0, step=1): self.current = start self.step = step def __next__(self): value = self.current self.current += self.step return value
def safe_repr(obj): """Returns a repr of an object and falls back to a minimal representation of type and ID if the call to repr raised an error. :param obj: object to safe repr :returns: repr string or '(type<id> repr error)' string :rtype: str """ try: obj_repr = repr(obj) except: obj_repr = "({0}<{1}> repr error)".format(type(obj), id(obj)) return obj_repr
# -*- coding: utf-8 -*- # 1'den 1000'e kadar olan sayılardan mükemmel sayı olanları ekrana yazdırın. Bunun için bir sayının mükemmel olup olmadığını dönen bir tane fonksiyon yazın. # Bir sayının bölenlerinin toplamı kendine eşitse bu sayı mükemmel bir sayıdır. Örnek olarak 6 mükemmel bir sayıdır (1 + 2 + 3 = 6). def mukemmel(sayı): toplam = 0 for i in range(1,sayı): if (sayı % i == 0): toplam += i return toplam == sayı for i in range(1,1001): if (mukemmel(i)): print("Mükemmel Sayı:",i)
print('\033[31m=\033[m'*12, '\033[33mReajuste Salarial\033[m', '\033[31m=\033[m'*12) sal = float(input('\033[35mQual é o salario do Funcionário? R$' )) p = sal * 15/100 print('\033[4;32mUm funcionário que ganhava R$\033[34m{},\033[4;32m com 15% de aumento, passa a receber R$\033[34m{:.2f}.'.format(sal,(sal+p)))
"""These SESSION commands are used to enter and exit the various processors in the program. """ class ProcessorEntry: def aux2(self, **kwargs): """Enters the binary file dumping processor. APDL Command: /AUX2 Notes ----- Enters the binary file dumping processor (ANSYS auxiliary processor AUX2). This processor is used to dump the contents of certain ANSYS binary files for visual examination. This command is valid only at the Begin Level. """ command = "/AUX2," return self.run(command, **kwargs) def aux3(self, **kwargs): """Enters the results file editing processor. APDL Command: /AUX3 Notes ----- Enters the results file editing processor (ANSYS auxiliary processor AUX3). This processor is used to edit ANSYS results files. This command is valid only at the Begin Level. """ command = "/AUX3," return self.run(command, **kwargs) def aux12(self, **kwargs): """Enters the radiation processor. APDL Command: /AUX12 Notes ----- Enters the radiation processor (ANSYS auxiliary processor AUX12). This processor supports the Radiation Matrix and the Radiosity Solver methods. This command is valid only at the Begin Level. """ command = "/AUX12," return self.run(command, **kwargs) def aux15(self, **kwargs): """Enters the IGES file transfer processor. APDL Command: /AUX15 Notes ----- Enters the IGES file transfer processor (ANSYS auxiliary processor AUX15), used to read an IGES data file into the ANSYS program. This command is valid only at the Begin Level. """ command = "/AUX15," return self.run(command, **kwargs) def finish(self, **kwargs): """Exits normally from a processor. APDL Command: FINISH Notes ----- Exits any of the ANSYS processors or the DISPLAY program. For the ANSYS processors, data will remain intact in the database but the database is not automatically written to a file (use the SAVE command to write the database to a file). See also the /QUIT command for an alternate processor exit command. If exiting POST1, POST26, or OPT, see additional notes below. POST1: Data in the database will remain intact, including the POST1 element table data, the path table data, the fatigue table data, and the load case pointers. POST26: Data in the database will remain intact, except that POST26 variables are erased and specification commands (such as FILE, PRTIME, NPRINT, etc.) are reset. Use the /QUIT command to exit the processor and bypass these exceptions. This command is valid in any processor. This command is not valid at the Begin level. """ command = "FINISH," return self.run(command, **kwargs) def map(self, kdim="", kout="", limit="", **kwargs): """Maps pressures from source points to target surface elements. APDL Command: MAP Parameters ---------- kdim Interpolation key: 0 or 2 - Interpolation is done on a surface (default). 3 - Interpolation is done within a volume. This option is useful if the supplied source data is volumetric field data rather than surface data. kout Key to control how pressure is applied when a target node is outside of the source region: 0 - Use the pressure(s) of the nearest source point for target nodes outside of the region (default). 1 - Set pressures outside of the region to zero. limit Number of nearby points considered for interpolation. The minimum is 5; the default is 20. Lower values reduce processing time. However, some distorted or irregular meshes will require a higher LIMIT value to find the points encompassing the target node in order to define the region for interpolation. Notes ----- Maps pressures from source points to target surface elements. """ return self.run(f"MAP,,{kdim},,{kout},{limit}", **kwargs) def post1(self, **kwargs): """Enters the database results postprocessor. APDL Command: /POST1 Notes ----- Enters the general database results postprocessor (POST1). All load symbols (/PBC, /PSF, or /PBF) are automatically turned off with this command. This command is valid only at the Begin Level. """ command = "/POST1," return self.run(command, **kwargs) def post26(self, **kwargs): """Enters the time-history results postprocessor. APDL Command: /POST26 Notes ----- Enters the time-history results postprocessor (POST26). This command is valid only at the Begin Level. """ command = "/POST26," return self.run(command, **kwargs) def prep7(self, **kwargs): """Enters the model creation preprocessor. APDL Command: /PREP7 Notes ----- Enters the general input data preprocessor (PREP7). This command is valid only at the Begin Level. """ command = "/PREP7," return self.run(command, **kwargs) def quit(self, **kwargs): """Exits a processor. APDL Command: /QUIT Notes ----- This is an alternative to the FINISH command. If any cleanup or file writing is normally done by the FINISH command, it is bypassed if the /QUIT command is used instead. A new processor may be entered after this command. See the /EXIT command to terminate the run. This command is valid in any processor. This command is not valid at the Begin level. """ command = "/QUIT," return self.run(command, **kwargs) def slashsolu(self, **kwargs): """Enters the solution processor. APDL Command: /SOLU Notes ----- This command is valid only at the Begin Level. """ command = "/SOLU," return self.run(command, **kwargs)
# 141, Суптеля Владислав # 【Дата】:「09.03.20」 # 6. Написати рекурсивну процедуру перекладу натурального числа з десяткової системи числення в N-річної. # Значення N в основній програмі вводиться з клавіатури (2 ≤ N ≤ 16). n = int(input("「Введите число」: ")) a = int(input("「Введите основание системы счисления」: ")) def rashinban(n, a): if not 2 <= a <= 16: quit(print(" 0_o \n wwww ")) elif a == 2: print(bin(n)) elif a == 8: print(oct(n)) elif a == 10: print('Смысл? . . \n' + str(n)) elif a == 16: print(hex(n)) else: #потому что я не мазохист print("Поддерживаются только позиционные системы исчисления в составе двоичной, восьмеричной, десятичной и шестнадцатеричной!") rashinban(n, a) # >o_o> #def boon(n, a): # print(int(str(n), a)) #boon(n, a) # http://pro-chislo.ru/perevod-sistem-schislenija
""" .. module:: data_series :synopsis: Defines the DataSeries class. .. moduleauthor:: Scott W. Fleming <fleming@stsci.edu> """ #-------------------- class DataSeries(object): """ Defines a Data Series object, which contains the data (plot series) and plot labels for those series. """ def __init__(self, mission, obsid, plot_series, plot_labels, xunits, yunits, errcode, is_ancillary=None): """ Create a DataSeries object. :param mission: The mission this DataSeries comes from. :type mission: str :param obsid: The observation ID this DataSeries comes from. :type obsid: str :param plot_series: A 1-D list containing one or more 1-D lists that contain the (x,y) pairs for the given series of data. :type plot_series: list :param plot_labels: A 1-D list containing the strings to use as plot labels for each of the series of data. :type plot_series: list :param xunits: A 1-D list containing the strings to use as x-axis unit labels for each of the series of data. :type xunits: list :param yunits: A 1-D list containing the strings to use as y-axis unit labels for each of the series of data. :type yunits: list :param errcode: An integer used to signal if there was a problem reading in the data. :type errcode: int :param is_ancillary: A 1-D list of ints that, if set, indicates the returned data should NOT be plotted by default. If set to 0, then DO plot by default. :type is_ancillary: list """ self.mission = mission self.obsid = obsid self.plot_series = plot_series self.plot_labels = plot_labels self.xunits = xunits self.yunits = yunits self.errcode = errcode if is_ancillary is not None: self.is_ancillary = is_ancillary #--------------------
# -*- coding: utf-8 -*- # @File : observer.py # @Project : src # @Time : 2018/12/21 0:09 # @Site : https://github.com/MaiXiaochai # @Author : maixiaochai """ 1)观察者(observer)模式: 背后的思想是降低发布者与订阅者之间的耦合度,从而易于在运行时添加/删除订阅者。 2)拍卖会类似于观察者模式, 每个拍卖出价人都有一些拍牌,在他们想出价时就可以举起来。不论出价人在何时举起一块牌, 拍卖师都会像主持者那样更新报价,并将新的价格广播给所有出价人(订阅者)。 3)RabbitMQ可用于为应用添加异步消息支持,支持多种消息协议(比如,HTTP和AMQP), 可以在python 应用中用于实现发布-订阅模式,也就是观察者设计模式 4)事件驱动系统是另一个可以使用(通常也会使用)观察者模式的例子。监听者被用于监听特定事件(如键盘键入某个键)。 事件扮演发布者的角色,监听者则扮演观察者的角色。 5)当我们希望在一个对象(主持者/发布者/可观察者)发生变化时通知/更新另一个或多个对象的时候,通常会使用观察者模式。 """ # 实现一个数据格式化程序。默认格式化程序是以十进制格式展示一个数值,我们可以添加/注册十六进制和二进制格式化程序, # 当然,我们可以添加/注册更多的格式化程序。每次更新默认格式化程序的值时,已注册的格式化程序就会收到通知,并采取行动。 # 在这里,行动就是以相关的格式展示新的值。 # 在一些模式中,继承能体现自身价值,观察者模式是这些模式中的一个。我们实现一个基类Publisher, # 包括添加、删除及通知观察者这些公用功能。 class Publisher: def __init__(self): self.observers = [] def add(self, observer): if observer not in self.observers: self.observers.append(observer) else: print('Falied to add: {}'.format(observer)) def remove(self, observer): try: self.observers.remove(observer) except ValueError: print('Failed to remove: {}'.format(observer)) def notify(self): """ 在变化发生时通知所有观察者 """ # o.notify(self)这里其实是在调用订阅者本身的notify()方法 [o.notify(self) for o in self.observers] class DefaultFormatter(Publisher): def __init__(self, name): """ 调用基类的__init__()方法,因为这在Python中没法自动完成。 _data,我们使用了名称改变来声明不能直接访问该变量,虽然Python中直接访问一个变量始终是可能的, 资深开发人员不会去访问_data变量,因为代码中已经声明不应该这样做。 """ Publisher.__init__(self) self.name = name self._data = 0 def __str__(self): """ type(self).__name__是一种获取类名的方便技巧,避免了硬编码类名。 这降低了代码的可读性,却提高了代码的可维护性。 """ return "{}: '{}' has data = {}".format(type(self).__name__, self.name, self._data) @property def data(self): """ @property修饰器,提供变量_data的读访问方式,使用object.data代替object.data() """ return self._data @data.setter def data(self, new_value): """ 使用了@setter修饰器,该修饰器会在每次使用赋值操作(=)为_data变量赋新值时被调用。 就方法本身而言,它尝试吧新值强制类型转换为一个整数,并在类型转换失败时处理异常。 :param new_value: :return: """ try: self._data = int(new_value) except ValueError as e: print("Error: {}".format(e)) else: # 如果try里边的语句正常执行,然后就执行else里的语句 self.notify() class HexFormatter: """ 十六进制观察者 """ def notify(self, publisher): print("{}: '{}' has now hex data = {}".format(type(self).__name__, publisher.name, hex(publisher.data))) class BinaryFormatter: """ 二进制观察者 """ def notify(self, publisher): print("{}: '{}' has now bin data = {}".format(type(self).__name__, publisher.name, bin(publisher.data))) def main(): df = DefaultFormatter('test1') print(df, '\n') hf = HexFormatter() df.add(hf) df.data = 3 print(df, '\n') bf = BinaryFormatter() df.add(bf) df.data = 21 print(df, '\n') df.remove(hf) df.data = 40 print(df, '\n') df.remove(hf) df.add(bf) df.data = 'hello' print(df, '\n') df.data = 15.8 print(df) if __name__ == "__main__": main() """ out: DefaultFormatter: 'test1' has data = 0 HexFormatter: 'test1' has now hex data = 0x3 DefaultFormatter: 'test1' has data = 3 HexFormatter: 'test1' has now hex data = 0x15 BinaryFormatter: 'test1' has now bin data = 0b10101 DefaultFormatter: 'test1' has data = 21 BinaryFormatter: 'test1' has now bin data = 0b101000 DefaultFormatter: 'test1' has data = 40 Failed to remove: <__main__.HexFormatter object at 0x00000236CF4151D0> Falied to add: <__main__.BinaryFormatter object at 0x00000236CF4155F8> Error: invalid literal for int() with base 10: 'hello' DefaultFormatter: 'test1' has data = 40 BinaryFormatter: 'test1' has now bin data = 0b1111 DefaultFormatter: 'test1' has data = 15 """
class AdaptiveComponentInstanceUtils(object): """ An interface for Adaptive Component Instances. """ @staticmethod def CreateAdaptiveComponentInstance(doc, famSymb): """ CreateAdaptiveComponentInstance(doc: Document,famSymb: FamilySymbol) -> FamilyInstance Creates a FamilyInstance of Adaptive Component Family. doc: The Document famSymb: The FamilySymbol Returns: The Family Instance """ pass @staticmethod def GetInstancePlacementPointElementRefIds(famInst): """ GetInstancePlacementPointElementRefIds(famInst: FamilyInstance) -> IList[ElementId] Gets Placement Adaptive Point Element Ref ids to which the instance geometry adapts. famInst: The FamilyInstance. Returns: The Placement Adaptive Point Element Ref ids to which the instance geometry adapts. """ pass @staticmethod def GetInstancePointElementRefIds(famInst): """ GetInstancePointElementRefIds(famInst: FamilyInstance) -> IList[ElementId] Gets Adaptive Point Element Ref ids to which the instance geometry adapts. famInst: The FamilyInstance. Returns: The Adaptive Point Element Ref ids to which the instance geometry adapts. """ pass @staticmethod def GetInstanceShapeHandlePointElementRefIds(famInst): """ GetInstanceShapeHandlePointElementRefIds(famInst: FamilyInstance) -> IList[ElementId] Gets Shape Handle Adaptive Point Element Ref ids to which the instance geometry adapts. famInst: The FamilyInstance Returns: The Shape Handle Adaptive Point Element Ref ids to which the instance geometry adapts. """ pass @staticmethod def HasAdaptiveFamilySymbol(famInst): """ HasAdaptiveFamilySymbol(famInst: FamilyInstance) -> bool Verifies if a FamilyInstance has an Adaptive Family Symbol. famInst: The FamilyInstance Returns: True if the FamilyInstance has an Adaptive Family Symbol. """ pass @staticmethod def IsAdaptiveComponentInstance(famInst): """ IsAdaptiveComponentInstance(famInst: FamilyInstance) -> bool Verifies if a FamilyInstance is an Adaptive Component Instance. famInst: The FamilyInstance Returns: True if the FamilyInstance has an Adaptive Component Instances. """ pass @staticmethod def IsAdaptiveFamilySymbol(famSymb): """ IsAdaptiveFamilySymbol(famSymb: FamilySymbol) -> bool Verifies if a FamilySymbol is a valid Adaptive Family Symbol. famSymb: The FamilySymbol Returns: True if the FamilySymbol is a valid Adaptive Family Symbol. """ pass @staticmethod def IsInstanceFlipped(famInst): """ IsInstanceFlipped(famInst: FamilyInstance) -> bool Gets the value of the flip parameter on the adaptive instance. famInst: The FamilyInstance Returns: True if the instance is flipped. """ pass @staticmethod def MoveAdaptiveComponentInstance(famInst, trf, unHost): """ MoveAdaptiveComponentInstance(famInst: FamilyInstance,trf: Transform,unHost: bool) Moves Adaptive Component Instance by the specified transformation. famInst: The FamilyInstance trf: The Transformation unHost: True if the move should disassociate the Point Element Refs from their hosts. False if the Point Element Refs remain hosted. """ pass @staticmethod def SetInstanceFlipped(famInst, flip): """ SetInstanceFlipped(famInst: FamilyInstance,flip: bool) Sets the value of the flip parameter on the adaptive instance. famInst: The FamilyInstance flip: The flip flag """ pass __all__ = [ "CreateAdaptiveComponentInstance", "GetInstancePlacementPointElementRefIds", "GetInstancePointElementRefIds", "GetInstanceShapeHandlePointElementRefIds", "HasAdaptiveFamilySymbol", "IsAdaptiveComponentInstance", "IsAdaptiveFamilySymbol", "IsInstanceFlipped", "MoveAdaptiveComponentInstance", "SetInstanceFlipped", ]
# -*- coding: utf-8 -*- def submatrixSum(M): """ Strnjena podmatrika z največjo vsoto komponent. Časovna zahtevnost: O(m^2 n), kjer je m × n dimenzija vhodne matrike. """ m = len(M) assert m > 0 n = len(M[0]) assert n > 0 and all(len(l) == n for l in M) s = {(-1, h): 0 for h in range(n)} V = {} for j in range(m): for h in range(n): s[j, h] = s[j-1, h] + M[j][h] for i in range(j+1): V[i, j, 0] = (s[j, 0] - s[i-1, 0], 0) for h in range(1, n): v, k = V[i, j, h-1] x = s[j, h] - s[i-1, h] if v < 0: v = x k = h else: v += x V[i, j, h] = (v, k) (v, k), (i, j, h) = max((y, x) for x, y in V.items()) return (v, (i, k), [r[k:h+1] for r in M[i:j+1]])
def gmaps_url_to_coords(url): gmaps_coords = url.split('=') coords = (0.0, 0.0) # defaults to 0,0 if len(gmaps_coords) == 2: gmaps_coords = gmaps_coords[1] coords = tuple(map(lambda c: float(c), gmaps_coords.split(','))) return coords
# Copyright 2014 Google Inc. All rights reserved. # # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE filters or at # https://developers.google.com/open-source/licenses/bsd { 'includes': [ '../../common.gypi', ], 'targets': [ { 'target_name': 'filters', 'type': '<(component)', 'sources': [ 'avc_decoder_configuration.cc', 'avc_decoder_configuration.h', 'decoder_configuration.cc', 'decoder_configuration.h', 'ec3_audio_util.cc', 'ec3_audio_util.h', 'h264_byte_to_unit_stream_converter.cc', 'h264_byte_to_unit_stream_converter.h', 'h264_parser.cc', 'h264_parser.h', 'h265_byte_to_unit_stream_converter.cc', 'h265_byte_to_unit_stream_converter.h', 'h265_parser.cc', 'h265_parser.h', 'h26x_bit_reader.cc', 'h26x_bit_reader.h', 'h26x_byte_to_unit_stream_converter.cc', 'h26x_byte_to_unit_stream_converter.h', 'hevc_decoder_configuration.cc', 'hevc_decoder_configuration.h', 'nal_unit_to_byte_stream_converter.cc', 'nal_unit_to_byte_stream_converter.h', 'nalu_reader.cc', 'nalu_reader.h', 'vp_codec_configuration.cc', 'vp_codec_configuration.h', 'vp8_parser.cc', 'vp8_parser.h', 'vp9_parser.cc', 'vp9_parser.h', 'vpx_parser.h', ], 'dependencies': [ '../../base/base.gyp:base', ], }, { 'target_name': 'filters_unittest', 'type': '<(gtest_target_type)', 'sources': [ 'avc_decoder_configuration_unittest.cc', 'ec3_audio_util_unittest.cc', 'h264_byte_to_unit_stream_converter_unittest.cc', 'h264_parser_unittest.cc', 'h265_byte_to_unit_stream_converter_unittest.cc', 'h265_parser_unittest.cc', 'h26x_bit_reader_unittest.cc', 'hevc_decoder_configuration_unittest.cc', 'nal_unit_to_byte_stream_converter_unittest.cc', 'nalu_reader_unittest.cc', 'vp_codec_configuration_unittest.cc', 'vp8_parser_unittest.cc', 'vp9_parser_unittest.cc', ], 'dependencies': [ '../../media/base/media_base.gyp:media_base', '../../testing/gmock.gyp:gmock', '../../testing/gtest.gyp:gtest', '../test/media_test.gyp:media_test_support', 'filters', ], }, ], }
def no_teen_sum(a, b, c): retSum = 0 for i in [a, b, c]: if i <= 19 and i >= 13 and i != 15 and i != 16: continue retSum += i return retSum
"""Python implementation for doubly-linked list data structure.""" class DoublyLinkedList(object): """Sets properties and methods of a doubly-linked list.""" def __init__(self): """Create new instance of DoublyLinkedList.""" self.tail = None self.head = None self._length = 0 def push(self, val=None): """Instantiate and push new node.""" if val is None: raise ValueError('You must give a value.') new_node = Node(val, self.head) if self.head is None: self.head = new_node self.tail = new_node new_node.next_node = None self._length += 1 return self.head.prev_node = new_node self.head = new_node self._length += 1 def append(self, val=None): """Instantiate and append new node.""" if val is None: raise ValueError('You must give a value.') new_node = Node(val, None, self.tail) if self.head is None: self.head = new_node self.tail = new_node new_node.prev_node = None self._length += 1 return self.tail.next_node = new_node self.tail = new_node self._length += 1 def pop(self): """Remove and return node from head of doubly linked list.""" current_node = self.head if current_node is None: raise IndexError('The doubly linked list is empty.') if current_node.next_node is not None: self.head = current_node.next_node self.head.prev_node = None else: self.head = None self.tail = None self._length -= 1 return current_node.val def shift(self): """Remove and return node from tail of doubly linked list.""" current_node = self.tail if current_node is None: raise IndexError('The doubly linked list is empty.') if current_node.prev_node is not None: self.tail = current_node.prev_node self.tail.next_node = None else: self.head = None self.tail = None self._length -= 1 return current_node.val def remove(self, val): """Find and remove the first Node with a given value.""" current_item = self.head if current_item is None: raise ValueError('Node not in doubly linked list, it is empty.') while current_item.val != val: current_item = current_item.next_node if current_item is None: raise ValueError('Node not in doubly linked list.') if self.head == self.tail: self.head = None self.tail = None elif current_item.prev_node is None: self.head = current_item.next_node self.head.prev_node = None elif current_item.next_node is None: self.tail = current_item.prev_node self.tail.next_node = None else: current_item.prev_node.next_node = current_item.next_node current_item.next_node.prev_node = current_item.prev_node self._length -= 1 def __len__(self): """Return the size of a doubly linked list, overwriting len method.""" return self._length class Node(object): """Set properties and methods of Node class.""" def __init__(self, val, next_node=None, prev_node=None): """Create new Node.""" self.val = val self.next_node = next_node self.prev_node = prev_node
def read_input(filename): with open(filename, 'r') as file: N, k = file.readline().strip().split() N, k = int(N), int(k) X = [] clusters = [] for _ in range(N): buffers = file.readline().strip().split() X.append([float(v) for v in buffers]) for _ in range(k): buffers = file.readline().strip().split() clusters.append([float(v) for v in buffers]) return X, clusters def add_2d_matrix(A, B): a1, b1, c1, d1 = A[0][0], A[0][1], A[1][0], A[1][1] a2, b2, c2, d2 = B[0][0], B[0][1], B[1][0], B[1][1] return [[a1+a2, b1+b2], [c1+c2, d1+d2]] def det_2d_matrix(A): """Determinant of a 2d matrix A = [[a, b], [c, d]] det(A) = ad - bc """ a, b, c, d = A[0][0], A[0][1], A[1][0], A[1][1] return a * d - b * c def invert_2d_matrix(A): """Inverse of a 2d matrix A = [[a, b], [c, d]] invert(A) = 1 / det(A) * [[d, -b], [-c, a]] """ a, b, c, d = A[0][0], A[0][1], A[1][0], A[1][1] scalar = 1 / det_2d_matrix(A) return [[scalar*d, scalar*-b], [scalar*-c, scalar*a]] def mul_vector_2d_matrix(vector, A): a, b, c, d = A[0][0], A[0][1], A[1][0], A[1][1] return [vector[0]*a + vector[1]*c, vector[0]*b + vector[1]*d] def mul_scalar_2d_matrix(scalar, A): a, b, c, d = A[0][0], A[0][1], A[1][0], A[1][1] return [[scalar*a, scalar*b], [scalar*c, scalar*d]] def div_scalar_2d_matrix(scalar, A): a, b, c, d = A[0][0], A[0][1], A[1][0], A[1][1] return [[a/scalar, b/scalar], [c/scalar, d/scalar]] def add_vector(vector1, vector2): return [v1 + v2 for v1, v2 in zip(vector1, vector2)] def sub_vector(vector1, vector2): return [v1 - v2 for v1, v2 in zip(vector1, vector2)] def dot_vector(vector1, vector2): return sum([v1 * v2 for v1, v2 in zip(vector1, vector2)]) def mul_vector(vector1, vector2): mul = [[0. for j in range(len(vector1))] for i in range(len(vector1))] for i in range(len(vector1)): for j in range(len(vector2)): mul[i][j] = vector1[i] * vector2[j] return mul
def func(): yield 1 yield 2 yield 3 def main(): for item in func(): print(item) # print(func()) #<generator object func at 0x7f227f3ae3b8> obj1 = (1,2,3,) obj = (i for i in range(10)) print (obj) # print(obj[1]) # 'generator' object is not subscriptable obj2 = [i for i in range(10)] print(obj2) print(obj2[1]) # Works absolutely fine mygenerator = (x*x for x in range(3)) print(mygenerator) print('-------') print('Iterate A Generator') print('-------') for item in obj: print(item) print('-------') print('Again!!!') print('-------') for item in obj: print(item) # Prints nothing if __name__ == '__main__': main()
def is_palindrome(str, length): is_pali = True length -= 1 for i in range (0, length//2): if (str[i] != str[length - i]): is_pali = False break return is_pali str = input('please enter a string\n') message = "Palindrome!" if is_palindrome(str, len(str)) else "not pali" print (message)
# TODO -- co.api.InvalidResponse is used in (client) public code. This should # move to private. class ClientError(Exception): def __init__(self, status_code, message): Exception.__init__(self) self.status_code = status_code self.message = message def to_dict(self): return {"message": self.message}
# Desafio 2 - Aula 5 : Primeiro 'input' e lista simplês com cores. nome = input('Me diga seu nome: ') cor = {'azul' : '\033[34m', 'limpa' : '\033[m'} print(f'Seu nome é,\033[34m{nome}{cor["limpa"]}!') print(f'Seu nome é \033[34m{nome}\033[m!')
groups_dict = { -1001384861110: "expresses" } log_file = "logs.log" database_file = "Couples.sqlite" couples_delta = 60 * 60 * 4
def sample_service(name=None): """ This is a sample service. Give it your name and prepare to be greeted! :param name: Your name :type name: basestring :return: A greeting or an error """ if name: return { 'hello': name} else: return {"error": "what's your name?"}
class Solution: def reverseStr(self, s: str, k: int) -> str: if not s or not k or k < 0: return "" s = list(s) for i in range(0, len(s), 2 * k): s[i: i+k] = reversed(s[i:i+k]) return ''.join(s)
d1, d2 = map(int, input().split()) s = d1 + d2 dic = {} for i in range(2, s + 1): dic[i] = 0 for i in range(1, d1 + 1): for j in range(1, d2 + 1): dic[i + j] += 1 top = 0 out = [] for key in dic: if dic[key] == top: out.append(key) elif dic[key] > top: top = dic[key] out = [] out.append(key) else: continue for i in out: print(i)
''' PARTIAL DEARRANGEMENTS A partial dearrangement is a dearrangement where some points are fixed. That is, given a number n and a number k, we need to find count of all such dearrangements of n numbers, where k numbers are fixed in their position. ''' mod = 1000000007 def nCr(n, r, mod): if n < r: return -1 # We create a pascal triangle. Pascal = [] Pascal.append(1) for i in range(0, r): Pascal.append(0) # We use the known formula nCr = (n-1)C(r) + (n-1)C(r-1) # for computing the values. for i in range(0, n + 1): k = ((i) if (i < r) else (r)) # We know, nCr = nC(n-r). Thus, at any point we only need min # of the two, so as to improve our computation time. for j in range(k, 0, -1): Pascal[j] = (Pascal[j] + Pascal[j - 1]) % mod return Pascal[r] def count(n, k): if k == 0: if n == 0: return 1 if n == 1: return 0 return (n - 1) * (count(n - 1, 0) + count(n - 2, 0)) return nCr(n, k, mod) * count(n - k, 0) number = int(input()) k = int(input()) dearrangements = count(number, k) print("The number of partial dearrangements is", dearrangements) ''' INPUT : n = 6 k = 3 OUTPUT: The number of partial dearrangements is 40 '''
#!/usr/bin/env python3 class Color(): black = "\u001b[30m" red = "\u001b[31m" green = "\u001b[32m" yellow = "\u001b[33m" blue = "\u001b[34m" magenta = "\u001b[35m" cyan = "\u001b[36m" white = "\u001b[37m" reset = "\u001b[0m"
# Classic crab rave text filter def apply_filter(input_stream, overlay_text, font_file, font_color, font_size): text_lines = overlay_text.split("\n") text_shadow = int(font_size / 16) # ffmpeg does not support multiline text with vertical align if len(text_lines) >= 2: video_stream = input_stream.video.drawtext( x="(w-text_w)/2", y="(h-text_h)/2-text_h", text=text_lines[0], fontfile=font_file, fontcolor=font_color, fontsize=font_size, shadowcolor="black@0.6", shadowx=str(text_shadow), shadowy=str(text_shadow) ).drawtext( x="(w-text_w)/2", y="(h-text_h)/2+text_h", text=text_lines[1], fontfile=font_file, fontcolor=font_color, fontsize=font_size, shadowcolor="black@0.6", shadowx=str(text_shadow), shadowy=str(text_shadow) ) else: video_stream = input_stream.video.drawtext( x="(w-text_w)/2", y="(h-text_h)/2", text=overlay_text, fontfile=font_file, fontcolor=font_color, fontsize=font_size, shadowcolor="black@0.6", shadowx=str(text_shadow), shadowy=str(text_shadow) ) return video_stream
class ElementableError(Exception): pass class InvalidElementError(KeyError, ElementableError): def __init__(self, msg): msg = f"Element {msg} is not supported" super().__init__(msg)
""" 7 - Faça um programa que receba dois números e mostre o maior. Se por acaso, os dois números forem iguais, imprima a mensagem Números Iguais. """ numero1 = int(input("Digite o primeiro número: ")) numero2 = int(input("Digite o segundo número: ")) if numero1 > numero2: print(f'Entre os números {numero1} e {numero2} o número {numero1} é maior.') elif numero1 < numero2: print(f'Entre os números {numero1} e {numero2} o número {numero2} é maior.') else: print('Números iguais') """ #else: numero1 == numero2 print(f'Os números {numero1} e {numero2} são iguais.') numero1 == numero2 Dado que você verifica na linha 9 se 'numero1' é maior que 'numero2' e verifica na linha 11 se 'numero1' é menor que 'numero2', se não for nem uma coisa nem outra então os números só podem ser iguais. """
NTIPAliasFlag = {} NTIPAliasFlag["identified"]="0x10" NTIPAliasFlag["eth"]="0x400000" NTIPAliasFlag["ethereal"]="0x400000" NTIPAliasFlag["runeword"]="0x4000000"
for _ in range(int(input())): word = input() if len(word) > 10: print(word[0]+str(len(word)-2)+word[-1]) else: print(word)
xmin, ymin, xmax, ymax = 100, 100, 1000, 800 # Bit code (0001, 0010, 0100, 1000 and 0000) LEFT, RIGHT, BOT, TOP = 1, 2, 4, 8 INSIDE = 0 print(f"Xmin: {xmin}\nYmin: {ymin}\nXmax: {xmax}\nYmax: {ymax}") x1 = float(input("Enter x: ")) y1 = float(input("Enter y: ")) x2 = float(input("Enter x2: ")) y2 = float(input("Enter y2: ")) # Compute code, doing OR operation according # the position of x,y def computeCode(x, y): code = INSIDE if x < xmin: code |= LEFT elif x > xmax: code |= RIGHT if y < ymin: code |= BOT elif y > ymax: code |= TOP return code # Clipping line process def cohenSuthClip(x1, y1, x2, y2): # Compute region code code1 = computeCode(x1, y1) code2 = computeCode(x2, y2) accept = False while True: # If both endpoints lie within clip bounds if code1 == 0 and code2 == 0: accept = True break # If both endpoints are outside clip bounds elif (code1 & code2) != 0: break # Some inside and some outside else: # Clip process needed # At least one point is outside clip x = 1. y = 1. code_out = code1 if code1 != 0 else code2 # Find intersection point # F(y) => y = y1 + slope * (x - x1), # F(x) => x = x1 + (1 / slope) * (y - y1) if code_out & TOP: # point is above xmax x = x1 + (x2 - x1) * (ymax - y1) / (y2 - y1) y = ymax elif code_out & BOT: # point is below clip x = x1 + (x2 - x1) * (ymin - y1) / (x2 - x1) y = ymin elif code_out & LEFT: # point is to the left of the clip y = y1 + (y2 - y1) * (xmin - x1) / (x2 - x1) x = xmin elif code_out & RIGHT: # point is to the right of the clip y = y1 + (y2 - y1) * (xmax - x1) / (x2 - x1) x = xmax # intersection point x,y is set now # replace point outside clipping bounds # by recently found intersection point if code_out == code1: x1 = x y1 = y code1 = computeCode(x1, y1) else: x2 = x y2 = y code2 = computeCode(x2, y2) if accept: print(f"Line accepted from {x1}, {y1}, {x2}, {y2}") else: print("Line rejected") cohenSuthClip(x1, y1, x2, y2)