content
stringlengths
7
1.05M
#!/usr/bin/env python # -*- coding:utf-8 -*- #--------------------------------------------------------------------------- # # Author: lubo # E-mail: 454331202@qq.com # LastModified: 2014-05-23 11:18:31 # Filename: gl.py # Desc: # #--------------------------------------------------------------------------- headline1 = '' headline2 = '' mysql_headline1 = '' mysql_headline2 = '' ncpu = 0 #Number of processors # Options Flag optflag = 0 #whether input opt timeFlag = 0 # -t : print current time interval = 1 # -i : time(second) interval my_load = 0 # -l : print load info my_cpu = 0 # -c : print cpu info my_swap = 0 # -s : print swap info my_disk = None # -d : print disk info my_net = None # -n : print net info mysql = 0 # -mysql: print mysql status mysql_conn ='' # mysql conn info com = 0; # -com : print mysql status innodb_hit = 0 # -hit : Print Innodb Hit% innodb_rows = 0 # -innodb_rows : Print Innodb Rows Status innodb_pages= 0 # -innodb_pages: Innodb Buffer Pool Pages Status innodb_data = 0 # -innodb_data : Innodb Data Status innodb_log = 0 # -innodb_log : Innodb Log Status innodb_status=0 # -innodb_status: Show Engine Innodb Status threads = 0 # -T : Print Threads Status bytes = 0 # -B : Print Bytes Status my_port = '3306' # default prot 3306 my_socket =None # sockfile my_pwd =None # root user password dbrt = 0 # -rt lock_file='' tcprstat_logfile='' tcprstat_dir='/tmp/' orz_logfile=None old_console='' logfile_by_day=0 # one day one logfile # Variables For : #-----> Get SysInfo (from /proc/stat): CPU sys_cpu1 = (0,0,0,0,0,0,0,0) total_1 = 0 # #<----- Get SysInfo (from /proc/stat): CPU #-----> Get SysInfo (from /proc/vmstat): SWAP swap1 ={'pswpin':0,'pswpout':0} swap_not_first = 0 #<----- Get SysInfo (from /proc/vmstat): SWAP #-----> Get SysInfo (from /proc/net/dev): NET net1 ={'recv':0,'send':0} net_not_first = 0 #<----- Get SysInfo (from /proc/net/dev): NET #-----> Get SysInfo (from /proc/diskstats): IO sys_io1 = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) io_not_first = 0; # no print first value #ncpu = `grep processor /proc/cpuinfo | wc -l`; #/* Number of processors */ # grep "HZ" -R /usr/include/* # /usr/include/asm-x86_64/param.h:#define HZ 100 HZ = 100 #<----- Get SysInfo (from /proc/diskstats): IO #-----> Get Mysql Status mystat1={"Com_select":0, "Com_delete":0 , "Com_update":0, "Com_insert":0, "Innodb_buffer_pool_read_requests":0, "Innodb_rows_inserted":0, "Innodb_rows_updated":0, "Innodb_rows_deleted":0, "Innodb_rows_read":0, "Threads_created":0, "Bytes_received":0, "Bytes_sent":0, "Innodb_buffer_pool_pages_flushed":0, "Innodb_data_read":0, "Innodb_data_reads":0, "Innodb_data_writes":0, "Innodb_data_written":0, "Innodb_os_log_fsyncs":0, "Innodb_os_log_written":0} mysql_no_first = 0 #<----- Get Mysql Status HAS_COLOR=1 count=None #times python_version=''
# @Fábio C NUnes # Crie um programa que leia o nome de uma cidade e diga se ela começa ou não com o nome 'Santo'. cidade = str(input('Escreva o nome da cidade: ')).lower().strip() i = 'santo' in (cidade) y = ' ' in (cidade[5]) z = i and y == True print(z)
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"display": "00_core.ipynb", "Markdown": "00_core.ipynb", "Audio": "00_core.ipynb", "first_run": "00_core.ipynb", "beep": "00_core.ipynb", "h1": "00_core.ipynb", "h2": "00_core.ipynb", "h3": "00_core.ipynb", "h4": "00_core.ipynb", "h5": "00_core.ipynb", "h6": "00_core.ipynb", "from_file": "00_core.ipynb", "good_url": "00_core.ipynb", "user_agent": "00_core.ipynb", "extract_apex": "00_core.ipynb", "extract_meta_link": "00_core.ipynb", "extract_links": "00_core.ipynb", "extract_title": "00_core.ipynb", "extract_meta": "00_core.ipynb", "extract_hx": "00_core.ipynb", "extract_body": "00_core.ipynb", "extract_stemmed": "00_core.ipynb", "extract_url_keywords": "00_core.ipynb", "extract_keywords": "00_core.ipynb", "gsc_guess_site": "00_core.ipynb", "gsc_url2keyword_query": "00_core.ipynb", "gsc_url_query": "00_core.ipynb", "gsc2df": "00_core.ipynb", "df_allout": "00_core.ipynb", "ga_accounts": "00_core.ipynb", "ga_properties": "00_core.ipynb", "ga_properties_g4": "00_core.ipynb", "ga_profiles": "00_core.ipynb", "ga_everything": "00_core.ipynb", "inspect_url": "00_core.ipynb", "drop_table": "00_core.ipynb", "pk_compositor": "00_core.ipynb", "pk_inserter": "00_core.ipynb", "config2dict": "00_core.ipynb", "build_google_search_query": "00_core.ipynb", "extract_serps": "00_core.ipynb", "run_me": "00_core.ipynb", "look": "00_core.ipynb", "show_globals": "00_core.ipynb", "enlighten_me": "00_core.ipynb", "save_me": "00_core.ipynb", "please_explain": "00_core.ipynb", "bs": "00_core.ipynb", "lr": "10_requirements.ipynb", "SPACES": "00_core.ipynb", "LINES": "00_core.ipynb", "pstem": "00_core.ipynb", "stop_words": "00_core.ipynb", "pkl": "00_core.ipynb", "unpkl": "00_core.ipynb", "svc_ga": "00_core.ipynb", "svc_ga4": "00_core.ipynb", "svc_gsc": "00_core.ipynb", "svc_mail": "00_core.ipynb", "svc_oauth": "00_core.ipynb", "svc_sheet": "00_core.ipynb", "svc_photo": "00_core.ipynb", "svc_youtube": "00_core.ipynb", "out": "10_requirements.ipynb", "table": "10_requirements.ipynb", "upgrades": "10_requirements.ipynb", "outputs": "10_requirements.ipynb"} modules = ["core.py", "pip_upgrades.py"] doc_url = "https://miklevin.github.io/mlseo/" git_url = "https://github.com/miklevin/mlseo/tree/main/" def custom_doc_links(name): return None
#17/02/21 #What does this code do? # This code takes an input "n" and counts out until that number is reached. # This works similarly to the previous code, except with numbers. n = int(input('Enter a number: ')) for i in range(n): print(i + 1) #What is happening here? # In line 1, our code is taking an integer input, and assigning it to "n" # After that, it prints i+1, until n is reached.
# Enter your code here. Read input from STDIN. Print output to STDOUT n=int(input()) strarr=[] for x in range(n): strin=input() strarr.append(strin) stradd=set(strarr) print(len(stradd))
''' 580C. Kefa and Park dfs and similar, graphs, trees, 1500 http://codeforces.com/problemset/problem/580/C ''' n, m = map(int, input().split()) cat = 1 empty = 0 status = [-1] + list(map(int, input().split())) tree = {} for _ in range(n-1): s, e = map(int, input().split()) if s not in tree: tree[s] = [e] else: tree[s].append(e) if e not in tree: tree[e] = [s] else: tree[e].append(s) count = 0 # graph: dict type, s: start node code def BFS(graph, s): queue = [] queue.append(s) seen = set() seen.add(s[0]) result = 0 while (len(queue) > 0): vertex, current_c = queue.pop(0) if current_c <= m: nodes = graph[vertex] # if is the restaurant(leaves) if vertex != s[0] and len(nodes) == 1: result += 1 else: # if not leaves, add the children for w in nodes: if w not in seen: # if not exceed max cat met if status[w] == empty: queue.append([w, 0]) elif current_c+status[w] <= m: queue.append([w, current_c+status[w]]) seen.add(w) return result count = BFS(tree, [1, status[1]]) print(count)
""" Practice Binary Search """ def binary_search(array, target): mid = len(array) // 2 high = len(array) - 1 print("high", high) low = 0 while low <= high: mid = int((low+high)) // 2 print("mid", mid) print('mid element', array[mid]) if array[mid] == target: print("Print statement ends") return array[mid] if target < array[mid]: high = mid - 1 else: low = mid + 1 return None # test: array = [2, 3, 14, 18, 19, 42, 46, 90, 1001] target = 42 print(binary_search(array,target))
# https://adventofcode.com/2021/day/14 test = "2021-14_sample.txt" run = "2021-14_input.txt" def part1(fname): template = None inserts = {} for i, line in enumerate(open(fname)): if i == 0: template = line.rstrip() elif line[2:6] == ' -> ': inserts[line[0:2]] = line[6] #print(template) for _ in range(10): reversed = [template[-1]] for i in range(len(template)-2, -1, -1): pair = template[i:i+2] #print(f'{pair}') if pair in inserts: reversed.append(inserts[pair]) reversed.append(template[i]) template = ''.join(reversed[::-1]) #print(template) counts = {} for c in template: counts[c] = counts.get(c, 0) + 1 print(counts) return max(counts.values()) - min(counts.values()) def print_nonzero(inserts): print('---') for k, v in inserts.items(): if v['count'] > 0: print(f' {k} : {v}') print('---') def part2(fname, steps): inserts = {} for i, line in enumerate(open(fname)): if i == 0: template = line.rstrip() elif line[2:6] == ' -> ': inserts[line[0:2]] = {'count':0, 'next':[line[0]+line[6], line[6]+line[1]]} print(template) for i in range(len(template)-1): pair = template[i:i+2] inserts[pair]['count'] += 1 #print_nonzero(inserts) for _ in range(steps): # with 40 steps the string becomes terabytes in size state = {} for k in inserts: state[k] = inserts[k]['count'] inserts[k]['count'] = 0 for k in state: for nk in inserts[k]['next']: inserts[nk]['count'] += state[k] #print_nonzero(inserts) counts = {template[-1]:1} for pair in inserts: c = pair[0] counts[c] = counts.get(c, 0) + inserts[pair]['count'] for i in counts.items(): print(i) return max(counts.values()) - min(counts.values()) assert part1(test) == 1588 print(f'part1: {part1(run)}') assert part2(test, 10) == 1588 assert part2(test, 40) == 2188189693529 print(f'part2: {part2(run, 40)}')
''' Created on 11 Dec 2021 @author: laurentmichel ''' class MappingException(Exception): pass class ParsingException(Exception): pass class NotImplementedException(Exception): pass
_base_ = [ '../_base_/models/dla34up_lane.py', '../_base_/datasets/bdd100k_lane.py', '../_base_/schedules/bdd100k_lane_12e.py', '../_base_/default_runtime.py' ]
class Solution(object): def totalHammingDistance(self, nums): """ :type nums: List[int] :rtype: int """ total, l = 0, len(nums) for i in range(0, 32): bit_count = 0 for num in nums: bit_count += (num >> i) & 1 total += bit_count * (l - bit_count) return total
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2021/1/3 14:32 # @Author : cendeavor # @File : basic_mapper.py # @Software: PyCharm class BasicMapper: @staticmethod def stats_collection(db, cname, key=None): """集合统计函数 返回集合的一些基本统计数据,比如count之类 Args: db: 目标数据库 cname: 目标集合名 key: 用于筛选的键值名(考虑后面改成condition字典形式) Returns: stats: 关于集合的一些统计数据 """ stats = { 'total': db[cname].count(), 'unique': {}, } if key: stats['unique'][key] = len(db[cname].distinct(key)) print(stats) return stats
# -*- coding: utf-8 -*- """This code is a part of Hydra Toolkit .. module:: hydratk.extensions.datagen.translation.cs.help :platform: Unix :synopsis: Czech language translation for Datagen extension help generator .. moduleauthor:: Petr Rašek <bowman@hydratk.org> """ language = { 'name': 'Čeština', 'ISO-639-1': 'cs' } ''' Datagen Commands ''' help_cmd = { 'gen-asn1': 'enkódovat textový soubor, dekódovat binární soubor podle ASN.1 specifikace', 'gen-json': 'generovat vzorový json soubor podle JSON specifikace', 'gen-xml': 'generovat vzorový xml soubor podle WSDL/XSD specifikace', 'gen-selenium': 'převést Selenium skript do Yoda formátu', # standalone with option profile datagen 'asn1': 'enkódovat textový soubor, dekódovat binární soubor podle ASN.1 specifikace', 'json': 'generovat vzorový json soubor podle JSON specifikace', 'xml': 'generovat vzorový xml soubor podle WSDL/XSD specifikace', 'selenium': 'převést Selenium skript do Yoda formátu' } ''' Datagen Options ''' help_opt = { 'gen-spec': {'{h}--gen-spec <cesta>{e}': {'description': 'soubor se specifikací', 'commands': ('gen-asn1', 'gen-json', 'gen-xml')}}, 'gen-input': {'{h}--gen-input <cesta>{e}': {'description': 'vstupní soubor', 'commands': ('gen-asn1')}}, 'gen-output': {'{h}[--gen-output <cesta>]{e}': {'description': 'výstupní soubor, default vstupní soubor s jinou příponou nebo sample.json, sample.xml', 'commands': ('gen-asn1', 'gen-json', 'gen-xml', 'gen-selenium')}}, 'gen-action': {'{h}--gen-action compile|decode|encode|transcode{e}': {'description': 'akce', 'commands': ('gen-asn1')}}, 'gen-element': {'{h}--gen-element <název>{e}': {'description': 'název elementu ze specifikace', 'commands': ('gen-asn1', 'gen-xml')}}, 'gen-iformat': {'{h}[--gen-iformat ber|der|oer|aper|uper|xer|gser]{e}': {'description': 'vstupní formát, default ber pro akci decode, gser pro akci encode', 'commands': ('gen-asn1')}}, 'gen-oformat': {'{h}[--gen-oformat ber|der|oer|aper|uper|xer|gser]{e}': {'description': 'výstupní formát, default ber pro akci encode, gser pro akci decode', 'commands': ('gen-asn1')}}, 'gen-envelope': {'{h}[--gen-envelope]{e}': {'description': 'generovat včetně SOAP obálky', 'commands': ('gen-xml')}}, 'gen-browser': {'{h}[--gen-browser <title>]{e}': {'description': 'použitý prohlížeč, default Firefox', 'commands': ('gen-selenium')}}, 'gen-timeout': {'{h}[--gen-timeout <number>]{e}': {'description': 'timeout pro wait příkazy, default 10', 'commands': ('gen-selenium')}}, # standalone with option profile datagen 'spec': {'{h}--spec <cesta>{e}': {'description': 'soubor se specifikací', 'commands': ('asn1', 'json', 'xml')}}, 'input': {'{h}--input <cesta>{e}': {'description': 'vstupní soubor', 'commands': ('asn1')}}, 'output': {'{h}[--output <cesta>]{e}': {'description': 'výstupní soubor, default vstupní soubor s jinou příponou nebo sample.json, sample.xml', 'commands': ('asn1', 'json', 'xml', 'selenium')}}, 'action': {'{h}--action compile|decode|encode|transcode{e}': {'description': 'akce', 'commands': ('asn1')}}, 'element': {'{h}--element <název>{e}': {'description': 'název elementu ze specifikace', 'commands': ('asn1', 'xml')}}, 'iformat': {'{h}[--iformat ber|der|oer|aper|uper|xer|gser]{e}': {'description': 'vstupní formát, default ber pro akci decode, gser pro akci encode', 'commands': ('asn1')}}, 'oformat': {'{h}[--oformat ber|der|oer|aper|uper|xer|gser]{e}': {'description': 'výstupní formát, default ber pro akci encode, gser pro akci decode', 'commands': ('asn1')}}, 'envelope': {'{h}[--envelope]{e}': {'description': 'generovat včetně SOAP obálky', 'commands': ('xml')}}, 'browser': {'{h}[--browser <title>]{e}': {'description': 'použitý prohlížeč, default Firefox', 'commands': ('selenium')}}, 'timeout': {'{h}[--timeout <number>]{e}': {'description': 'timeout pro wait příkazy, default 10', 'commands': ('selenium')}} }
class ColumnLayer(tf.keras.layers.Layer): def __init__( self, upstream_dim, num_column_instances, position_dim, context_fan_in, context_num_samples, context_initial_sharpness, train_context, noise_rate, bypass_rate, ): super(ColumnLayer, self).__init__() self.upstream_dim = upstream_dim self.num_column_instances = num_column_instances self.position_dim = position_dim self.context_fan_in = context_fan_in self.context_num_samples = context_num_samples self.context_initial_sharpness = context_initial_sharpness self.train_context = train_context self.noise_rate = noise_rate self.bypass_rate = bypass_rate def build(self, input_shape): self.context_aggregator = ContextAggregationLayer( context_fan_in=self.context_fan_in, position_dim=self.position_dim, num_samples=self.context_num_samples, initial_sharpness=self.context_initial_sharpness, train_context=self.train_context, dtype='mixed_float16', ) self.permanence_separator = PermanenceSeparatorLayer( upstream_dim=self.upstream_dim, position_dim=self.position_dim, bypass_rate=self.bypass_rate, noise_rate=self.noise_rate, ) self.column_selector = ColumnSelectorLayer( num_column_instances=self.num_column_instances, ) super(ColumnLayer, self).build(input_shape) def reconstruct(self, upstream_state): reconstruction = self.permanence_separator.reconstruct(upstream_state) reconstruction = self.context_aggregator.reconstruct(reconstruction) return reconstruction def call(self, centered_input, training, is_bootstrapping=False): enriched_input = self.context_aggregator(centered_input) full_upstream_state, full_reconstruction = self.permanence_separator( enriched_input, is_bootstrapping=is_bootstrapping, ) full_reconstruction = self.context_aggregator.reconstruct(full_reconstruction) upstream_state = self.column_selector(full_upstream_state) # Restore unit length for the selected upstream states upstream_state = tf.math.l2_normalize(upstream_state, axis=-1, epsilon=tf.keras.backend.epsilon()) reconstruction = self.permanence_separator.reconstruct(upstream_state, training=training) reconstruction = self.context_aggregator.reconstruct(reconstruction) return [upstream_state, reconstruction, full_reconstruction]
################### # COLOR CONSTANTS ################### HEADER = '\033[95m' OK_BLUE = '\033[94m' OK_GREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' ########################### # ERROR MESSAGES CONSTANTS ########################### BASE_ERROR_MSG = '\n\nAll available commands:\n' \ 'flaskbox --init \tInit the flaskbox.yml file' \ '\nflaskbox --start \tRun your mock Server\n' FILE_EXISTS_MESSAGE = OK_GREEN + 'flaskbox.yml' \ + ENDC + ' already exists' NOT_EXISTS_MESSAGE = 'You need to create the ' + OK_GREEN + \ 'flaskbox.yml' + ENDC + ' file' + BASE_ERROR_MSG
def copyFile(): with open('test.txt') as file: content = file.read() with open('anotherTest.txt', 'w') as file: file.write(content) copyFile()
#!/usr/bin/env python3 # Day 10: Excel Sheet Column Number # # Given a column title as appear in an Excel sheet, return its corresponding # column number. # A = 1 # B = 2 # C = 3 # ... # Z = 26 # AA = 27 # AB = 28 # ... class Solution: def titleToNumber(self, s: str) -> int: # In other words, convert from base 26 to base 10, plus 1 as we # don't start at zero decimal = 0 for digit in s: decimal *= 26 decimal += ord(digit) - ord("A") + 1 return decimal # Tests assert Solution().titleToNumber("A") == 1 assert Solution().titleToNumber("AB") == 28 assert Solution().titleToNumber("ZY") == 701
class MissingValueError(ValueError): pass class ValidationError(ValueError): pass
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 21 20:59:18 2021 @author: anelmusic """ def train_model(model, train_ds, val_ds, epochs, batch_size, num_train_imgs, num_val_imgs, optimizer, metrics, loss): model.compile(loss=loss, optimizer=optimizer, metrics=metrics) steps_per_epoch =num_train_imgs//batch_size val_steps = num_val_imgs//batch_size model_history = model.fit(train_ds, epochs=epochs, steps_per_epoch=val_steps, validation_steps=val_steps, validation_data=val_ds) model.save_weights(config.SAVE_LOAD_WEIGHTS_PATH) def evaluate_model(model, ds, epochs, batch_size, num_train_imgs, num_val_imgs, optimizer, metrics, loss): model.compile(loss=loss, optimizer=optimizer, metrics=metrics) steps_per_epoch =num_train_imgs//batch_size val_steps = num_val_imgs//batch_size model.load_weights(config.SAVE_LOAD_WEIGHTS_PATH) loss, acc = model.evaluate(ds, steps= val_steps) print("Restored model, accuracy: {:5.2f}%".format(100 * acc))
def leiaInt(msg): n = (input(msg)) while n.isalpha() or n == '': print('\033[0;31mERRO! Digite um número inteiro válido.\033[m') n = (input(msg)).lstrip() return n n = leiaInt('Digite um número: ') print(f'Voce acabou de digitar o número {n}.')
class AImodel: def __init__(self): pass def process(self,input): return -1
# 一串字符串(string)是字符(characters)的序列(sqquence)。基本上,字符串就是一串词汇。 # 主要有单引号,双引号和三引号。引号的开始和结束必须是相同类型。 # '' # "" # """ or ''' 主要用来指定多行的字符串 # print ('test') # # print("test") # # abc = ''' # Today is Aug 16 2018. I's a bad day. # # I miss you. # # What are you doing now? # # ''' # # print(abc) # \ 续行符,一般用于句尾 # x = "Python is a very good program language , i want to learn it ," \ # "i need use it to build or develop a good program" # # print(x) # \a 响铃 y = "it's middle night , \a i will go to sleep." print(y)
#Factorial digit sum #Recursive funtion to calculate def factorial(num): #For negative numbers 0 or 1 will return 1 if num <= 1: return 1 else: #If num is greater than 1 multiply num by num-1 recursively until it returns 1(lowest value) return num * factorial(num-1) #Ask user to input a number and asgn value to f f = input("Please, enter a natural number to calculate factorial from: ") #Call function passing in f parsed and print the returning value. print(factorial(int(f)))
class Solution: def minRefuelStops(self, target, startFuel, stations): """ :type target: int :type startFuel: int :type stations: List[List[int]] :rtype: int """ # dp[i] means maximum distance with ith refuel n = len(stations) dp = [startFuel] + [0] * n for i in range(n): # for every station for j in reversed(range(i + 1)): if dp[j] >= stations[i][0]: dp[j + 1] = max(dp[j + 1], dp[j] + stations[i][1]) return next((i for i in range(len(dp)) if dp[i] >= target), -1)
class Solution: def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int: n = len(arr) cnt = 0 for i in range(n): for j in range(i + 1, n): for k in range(j + 1, n): cnt += abs(arr[i] - arr[j]) <= a and abs(arr[j] - arr[k]) <= b and abs(arr[i] - arr[k]) <= c return cnt
""" 3, 6, 7, 11, H=8 4 4. 4. 4 1 2. 2. 3 sum()=8 34567 FTTTT [30,11,23,4,20], H = 5 29,30,31 F. T. T Input: piles = [3,6,7,11], H = 8 3,6,7,11 3 6 1 1 45678 FFTTT 30,11,23,4,20 30 1. 1. 1. 1. 1 5T 29 2. 1. 1 1. 1 6 F """ class Solution: def minEatingSpeed(self, piles: List[int], H: int) -> int: def canEatPile(rate): hoursFull = 0 for p in piles: # Eat until full hoursFull += p // rate if p % rate > 0: hoursFull += 1 return hoursFull <= H left, right = 1, max(piles) while left < right: mid = left + (right - left) // 2 if canEatPile(mid): right = mid else: left = mid + 1 return left
"""***************************************************************************** * Copyright (C) 2019 Microchip Technology Inc. and its subsidiaries. * * Subject to your compliance with these terms, you may use Microchip software * and any derivatives exclusively with Microchip products. It is your * responsibility to comply with third party license terms applicable to your * use of third party software (including open source software) that may * accompany Microchip software. * * THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER * EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED * WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A * PARTICULAR PURPOSE. * * IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, * INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND * WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS * BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE * FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN * ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY, * THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE. *****************************************************************************""" ################################################################################################### ########################### Global variables ################################# ################################################################################################### adcSym_SEQR1_USCH = [] adcCHMenu = [] adcSym_CH_CHER = [] adcSym_CH_NAME = [] adcSym_CH_PositiveInput = [] adcSym_CH_NegativeInput = [] adcSym_CH_IER_EOC = [] ################################################################################################### ########################### Callback Functions ################################# ################################################################################################### def adcClockControl(symbol, event): clockSet = False Database.clearSymbolValue("core", adcInstanceName.getValue() + "_CLOCK_ENABLE") for channelID in range(0, 12): if (adcSym_CH_CHER[channelID].getValue() == True): clockSet = True if(clockSet == True): Database.setSymbolValue("core", adcInstanceName.getValue() + "_CLOCK_ENABLE", True, 2) else: Database.setSymbolValue("core", adcInstanceName.getValue() + "_CLOCK_ENABLE", False, 2) def adcInterruptEnableDisableCallback(symbol, event): global interruptSymbolEnable deviceHandlerLastName = "_InterruptHandler" interruptLastNameHandler = "_INTERRUPT_HANDLER" interruptLastNameHandlerLock = "_INTERRUPT_HANDLER_LOCK" interruptNamespace = "core" interruptSymbolHandler = adcInstanceName.getValue() + interruptLastNameHandler interruptSymbolHandlerLock = adcInstanceName.getValue() + interruptLastNameHandlerLock interruptSet = False Database.clearSymbolValue("core", interruptSymbolHandlerLock) Database.clearSymbolValue("core", interruptSymbolEnable) Database.clearSymbolValue("core", interruptSymbolHandler) for channelID in range(0, 12): if (adcSym_CH_IER_EOC[channelID].getValue() == True): interruptSet = True if (adcSym_IER_COMPE.getValue() == True): interruptSet = True if(interruptSet == True): Database.setSymbolValue( interruptNamespace, interruptSymbolEnable, True, 2) Database.setSymbolValue( interruptNamespace, interruptSymbolHandler, adcInstanceName.getValue() + deviceHandlerLastName, 2) Database.setSymbolValue( interruptNamespace, interruptSymbolHandlerLock, True, 2) else: #Do not try to restore the handler name to the default Database.setSymbolValue( interruptNamespace, interruptSymbolHandlerLock, False, 2) Database.setSymbolValue( interruptNamespace, interruptSymbolEnable, False, 2) def dependencyClockStatus(symbol, event): clockSet = False clock = bool(Database.getSymbolValue("core", adcInstanceName.getValue() + "_CLOCK_ENABLE")) for channelID in range(0, 12): if (adcSym_CH_CHER[channelID].getValue() == True): clockSet = True if(clockSet == True and clock == False): symbol.setVisible(True) else: symbol.setVisible(False) def dependencyIntStatus(symbol, event): global interruptSymbolEnable interruptSet = False interrupt = bool(Database.getSymbolValue("core", interruptSymbolEnable)) for channelID in range(0, 12): if (adcSym_CH_IER_EOC[channelID].getValue() == True): interruptSet = True if (adcSym_IER_COMPE.getValue() == True): interruptSet = True if(interruptSet == True and interrupt == False): symbol.setVisible(True) else: symbol.setVisible(False) def adcGetPeripheralClock(): peripheral_clk_freq = int(Database.getSymbolValue("core", adcInstanceName.getValue() + "_CLOCK_FREQUENCY")) return peripheral_clk_freq def adcPrescalWarning(symbol, event): clock = adcGetPeripheralClock() prescaler = adcSym_MR_PRESCAL.getValue() + 1 adcFreq = clock / (2 * prescaler) if (adcFreq < 200000): symbol.setLabel("ADC Frequency < 200,000 Hz. Decrease prescaler value. ") symbol.setVisible(True) elif (adcFreq > 20000000): symbol.setLabel("ADC Frequency > 20,000,000 Hz. Increase prescaler value. ") symbol.setVisible(True) else: symbol.setVisible(False) def adcFreqCalc(symbol, event): clock = adcGetPeripheralClock() prescaler = adcSym_MR_PRESCAL.getValue() + 1 adcFreq = clock / (2 * prescaler) symbol.clearValue() symbol.setValue(adcFreq, 2) def adcCalcConversionTime(adcSym_CONV_TIME, event): clock = adcGetPeripheralClock() adcClockSourceInvalidSym.setVisible((clock == 0)) if (clock == 0): clock = 1 prescaler = adcSym_MR_PRESCAL.getValue() + 1 over_sampling_rate = adcSym_EMR_OSR_VALUE.getSelectedKey() multiplier = 1 if (over_sampling_rate == "NO_AVERAGE"): multiplier = 1 elif (over_sampling_rate == "OSR4_SIN") or (over_sampling_rate == "OSR4_MUL"): multiplier = 4 elif (over_sampling_rate == "OSR16_SIN") or (over_sampling_rate == "OSR16_MUL"): multiplier = 16 elif (over_sampling_rate == "OSR64_SIN") or (over_sampling_rate == "OSR64_MUL"): multiplier = 64 elif (over_sampling_rate == "OSR256_SIN") or (over_sampling_rate == "OSR256_MUL"): multiplier = 256 conv_time = ((2 * prescaler) * 21.0 * 1000000.0 * multiplier) / clock adcSym_CONV_TIME.setLabel("**** Conversion Time is "+str(conv_time)+" us ****") def adcUserSeqVisible(adcSym_SEQR1_USCHLocal, event): for channelID in range(0, 11): adcSym_SEQR1_USCH[channelID].setVisible(event["value"]) def adcCHNameVisible(symbol, event): id = [] #split as per "_" to get the channel number id = symbol.getID().split("_") channelID = int(id[1]) adcSym_CH_NAME[channelID].setVisible(event["value"]) def adcCHPosInpVisible(symbol, event): id = [] #split as per "_" to get the channel number id = symbol.getID().split("_") channelID = int(id[1]) adcSym_CH_PositiveInput[channelID].setVisible(event["value"]) def adcCHNegInpVisible(symbol, event): id = [] #split as per "_" to get the channel number id = symbol.getID().split("_") channelID = int(id[1]) adcSym_CH_NegativeInput[channelID].setVisible(event["value"]) def adcCHInterruptVisible(symbol, event): id = [] #split as per "_" to get the channel number id = symbol.getID().split("_") channelID = int(id[1]) adcSym_CH_IER_EOC[channelID].setVisible(event["value"]) def adcCHEnable(symbol, event): id = [] #split as per "_" to get the channel number id = symbol.getID().split("_") channelID = int(id[1]) #for diff mode, hide next odd channel if(event["id"].find("_NEG_INP") > 0): if(event["value"] == "AN"+str(channelID)): adcCHMenu[channelID].setVisible(False) else: adcCHMenu[channelID].setVisible(True) def adcTriggerVisible(symbol, event): symObj = event["symbol"] triggerVal = int(symObj.getSelectedValue()) if((triggerVal >= 1) and (triggerVal <= 3)): symbol.setVisible(True) else: symbol.setVisible(False) def adcTriggerTimeVisible(symbol, event): if(event["id"] == "ADC_TRGR_MODE" and event["value"] == 4): symbol.setVisible(True) else: symbol.setVisible(False) def adcCalcTriggerPeriod(symbol, event): trgper = int((adcSym_TRIGGER_TIME.getValue() * adcSym_Clock.getValue() / 1000.0) - 1) #Trigger time is in millisecond if(event["id"] == "ADC_TRIGGER_TIME" or (event["id"] == "ADC_TRGR_MODE" and event["value"] == 4)): symbol.setValue(trgper, 2) else: symbol.clearValue() def adcSymbolVisible(symbol, event): symbol.setVisible(event["value"]) ################################################################################################### ########################### Component ################################# ################################################################################################### def instantiateComponent(adcComponent): global adcInstanceName global interruptSymbolEnable global adcClockSourceInvalidSym adcInstanceName = adcComponent.createStringSymbol("ADC_INSTANCE_NAME", None) adcInstanceName.setVisible(False) adcInstanceName.setDefaultValue(adcComponent.getID().upper()) Log.writeInfoMessage("Running " + adcInstanceName.getValue()) interruptLastNameEnable = "_INTERRUPT_ENABLE" interruptSymbolEnable = adcInstanceName.getValue() + interruptLastNameEnable #------------------------- ATDF Read ------------------------------------- availablePins = [] # array to save available pins channel = ["False", "False", "False", "False", "False", "False", "False", "False", "False", "False", "False", "False"] #array to save available channels adcChannelsValues = [] #array used for combo symbol adcChannelsValues.append("NONE") children = [] val = ATDF.getNode("/avr-tools-device-file/pinouts/pinout@[name=\"" + Database.getSymbolValue("core", "COMPONENT_PACKAGE") + "\"]") children = val.getChildren() for pad in range(0, len(children)): availablePins.append(children[pad].getAttribute("pad")) adc_signals = [] adc = ATDF.getNode("/avr-tools-device-file/devices/device/peripherals/module@[name=\"ADC\"]/instance@[name=\""+adcInstanceName.getValue()+"\"]/signals") adc_signals = adc.getChildren() for pad in range(0, len(adc_signals)): group = adc_signals[pad].getAttribute("group") if (("AD" in group) and ("index" in adc_signals[pad].getAttributeList())): padSignal = adc_signals[pad].getAttribute("pad") if padSignal in availablePins: channel[int(adc_signals[pad].getAttribute("index"))] = "True" adcChannelsValues.append("CH"+adc_signals[pad].getAttribute("index")) adcSym_AvailableChannels = adcComponent.createComboSymbol("ADC_AVAILABLE_CHANNELS", None, channel) adcSym_AvailableChannels.setVisible(False) adcMenu = adcComponent.createMenuSymbol("ADC_MENU", None) adcMenu.setLabel("ADC Configuration") #max no of channels adcSym_NUM_CHANNELS = adcComponent.createIntegerSymbol("ADC_NUM_CHANNELS", adcMenu) adcSym_NUM_CHANNELS.setDefaultValue(12) adcSym_NUM_CHANNELS.setVisible(False) # Provide a source clock selection symbol for masks that supports it valueGroupPath = "/avr-tools-device-file/modules/module@[name=\"ADC\"]/value-group@[name=\"ADC_EMR__SRCCLK\"]" valueGroup = ATDF.getNode(valueGroupPath) if valueGroup is not None: adcSym_EMR_SRCCLK = adcComponent.createKeyValueSetSymbol("ADC_CLK_SRC", adcMenu) adcSym_EMR_SRCCLK.setLabel(valueGroup.getAttribute("caption")) values = valueGroup.getChildren() for index in range(len(values)): adcSym_EMR_SRCCLK.addKey(values[index].getAttribute("name"), values[index].getAttribute("value"), values[index].getAttribute("caption")) adcSym_EMR_SRCCLK.setOutputMode("Key") adcSym_EMR_SRCCLK.setDisplayMode("Key") adcClockSourceInvalidSym = adcComponent.createCommentSymbol("ADC_CLK_SRC_INVALID_COMMENT", adcMenu) adcClockSourceInvalidSym.setLabel("Warning!!! " + adcInstanceName.getValue() + " clock frequency is zero") adcClockSourceInvalidSym.setVisible(False) #Clock prescaler global adcSym_MR_PRESCAL adcSym_MR_PRESCAL = adcComponent.createIntegerSymbol("ADC_MR_PRESCAL", adcMenu) adcSym_MR_PRESCAL.setLabel("Select Prescaler") adcSym_MR_PRESCAL.setDefaultValue(9) adcSym_MR_PRESCAL.setMin(0) adcSym_MR_PRESCAL.setMax(255) #clock selection global adcSym_Clock adcSym_Clock = adcComponent.createIntegerSymbol("ADC_CLK", adcMenu) adcSym_Clock.setLabel("Clock Frequency (Hz)") defaultAdcFreq = int(adcGetPeripheralClock() / (2 * (adcSym_MR_PRESCAL.getValue() + 1))) adcSym_Clock.setDefaultValue(defaultAdcFreq) adcSym_Clock.setVisible(True) adcSym_Clock.setReadOnly(True) adcSym_Clock.setDependencies(adcFreqCalc, ["ADC_MR_PRESCAL", "core." + adcInstanceName.getValue() + "_CLOCK_FREQUENCY"]) adcSym_PRESCAL_WARNING = adcComponent.createCommentSymbol("ADC_PRESCAL_WARNING", adcMenu) adcSym_PRESCAL_WARNING.setLabel("**** ADC Frequency = " + str(defaultAdcFreq) + " Hz. ****") adcSym_PRESCAL_WARNING.setVisible(False) adcSym_PRESCAL_WARNING.setDependencies(adcPrescalWarning, ["ADC_MR_PRESCAL", "core." + adcInstanceName.getValue() + "_CLOCK_FREQUENCY"]) #Result resolution #Added keys here as combining two bit-fields EMR_ASTE and EMR_OSR global adcSym_EMR_OSR_VALUE adcSym_EMR_OSR_VALUE = adcComponent.createKeyValueSetSymbol("ADC_EMR_OSR_VALUE", adcMenu) adcSym_EMR_OSR_VALUE.setLabel("Result Resolution") adcSym_EMR_OSR_VALUE.setDefaultValue(0) adcSym_EMR_OSR_VALUE.setOutputMode("Value") adcSym_EMR_OSR_VALUE.setDisplayMode("Description") valueGroup = ATDF.getNode("/avr-tools-device-file/modules/module@[name=\"ADC\"]/value-group@[name=\"ADC_EMR__OSR\"]") if valueGroup is not None: osrValues = valueGroup.getChildren() for index in range(len(osrValues)): if osrValues[index].getAttribute("name") == "NO_AVERAGE": adcSym_EMR_OSR_VALUE.addKey("NO_AVERAGE", "0", "12-bit") elif osrValues[index].getAttribute("name") == "OSR4": adcSym_EMR_OSR_VALUE.addKey("OSR4_SIN", "1", "13-bit - single trigger averaging") adcSym_EMR_OSR_VALUE.addKey("OSR4_MUL", "2", "13-bit - multi trigger averaging") elif osrValues[index].getAttribute("name") == "OSR16": adcSym_EMR_OSR_VALUE.addKey("OSR16_SIN", "3", "14-bit - single trigger averaging") adcSym_EMR_OSR_VALUE.addKey("OSR16_MUL", "4", "14-bit - multi trigger averaging") elif osrValues[index].getAttribute("name") == "OSR64": adcSym_EMR_OSR_VALUE.addKey("OSR64_SIN", "5", "15-bit - single trigger averaging") adcSym_EMR_OSR_VALUE.addKey("OSR64_MUL", "6", "15-bit - multi trigger averaging") elif osrValues[index].getAttribute("name") == "OSR256": adcSym_EMR_OSR_VALUE.addKey("OSR256_SIN", "7", "16-bit - single trigger averaging") adcSym_EMR_OSR_VALUE.addKey("OSR256_MUL", "8", "16-bit - multi trigger averaging") #Conversion time adcSym_CONV_TIME = adcComponent.createCommentSymbol("ADC_CONV_TIME", adcMenu) defaultConvTime = ((2 * (adcSym_MR_PRESCAL.getValue() + 1)) * 21.0 * 1000000.0 * 1) / adcGetPeripheralClock() adcSym_CONV_TIME.setLabel("**** Conversion Time is " + str(defaultConvTime) + " us ****") adcSym_CONV_TIME.setDependencies(adcCalcConversionTime, ["ADC_MR_PRESCAL", "ADC_EMR_OSR_VALUE", "core." + adcInstanceName.getValue() + "_CLOCK_FREQUENCY"]) #Result sign adcSym_EMR_SIGNMODE_VALUE = adcComponent.createKeyValueSetSymbol("ADC_EMR_SIGNMODE_VALUE", adcMenu) adcSym_EMR_SIGNMODE_VALUE.setLabel("Result Sign") adcSym_EMR_SIGNMODE_VALUE.setDefaultValue(0) adcSym_EMR_SIGNMODE_VALUE.setOutputMode("Key") adcSym_EMR_SIGNMODE_VALUE.setDisplayMode("Description") adcSym_EMR_SIGNMODE_VALUE.addKey("SE_UNSG_DF_SIGN", "0", "Single Ended: Unsigned, Differential: Signed") adcSym_EMR_SIGNMODE_VALUE.addKey("SE_SIGN_DF_UNSG", "1", "Single Ended: Signed, Differential: Unsigned") adcSym_EMR_SIGNMODE_VALUE.addKey("ALL_UNSIGNED", "2", "All Unsigned") adcSym_EMR_SIGNMODE_VALUE.addKey("ALL_SIGNED", "3", "All Signed") #Trigger Mode adcSym_TRGR_MODE = adcComponent.createKeyValueSetSymbol("ADC_TRGR_MODE", adcMenu) adcSym_TRGR_MODE.setLabel("Trigger Mode") adcSym_TRGR_MODE.setDefaultValue(5) adcSym_TRGR_MODE.setOutputMode("Key") adcSym_TRGR_MODE.setDisplayMode("Description") adcSym_TRGR_MODE.addKey("TRGMOD_NO_TRIGGER", "0", "Software Trigger") adcSym_TRGR_MODE.addKey("TRGMOD_EXT_TRIG_RISE", "1", "External Trigger Rising Edge") adcSym_TRGR_MODE.addKey("TRGMOD_EXT_TRIG_FALL", "2", "External Trigger Falling Edge") adcSym_TRGR_MODE.addKey("TRGMOD_EXT_TRIG_ANY", "3", "External Trigger Any Edge") #adcSym_TRGR_MODE.addKey("TRGMOD_PEN_TRIG", "4", "Pen Detect Trigger") #For Touchscreen mode only adcSym_TRGR_MODE.addKey("TRGMOD_PERIOD_TRIG", "4", "ADC Internal Periodic Trigger") adcSym_TRGR_MODE.addKey("TRGMOD_CONTINUOUS", "5", "Continuous") #External Trigger Mode adcSym_MR_TRGSEL_VALUE = adcComponent.createKeyValueSetSymbol("ADC_MR_TRGSEL_VALUE", adcSym_TRGR_MODE) adcSym_MR_TRGSEL_VALUE.setLabel("Select External Trigger Input") adcSym_MR_TRGSEL_VALUE.setVisible(False) adcSym_MR_TRGSEL_VALUE.setDefaultValue(1) adcSym_MR_TRGSEL_VALUE.setOutputMode("Key") adcSym_MR_TRGSEL_VALUE.setDisplayMode("Description") adcSym_MR_TRGSEL_VALUE.addKey("TRGSEL_ADC_TRIG0", "0", "ADTRG") adcSym_MR_TRGSEL_VALUE.addKey("TRGSEL_ADC_TRIG1", "1", "TIOA0") adcSym_MR_TRGSEL_VALUE.addKey("TRGSEL_ADC_TRIG2", "2", "TIOA1") adcSym_MR_TRGSEL_VALUE.addKey("TRGSEL_ADC_TRIG3", "3", "TIOA2") adcSym_MR_TRGSEL_VALUE.addKey("TRGSEL_ADC_TRIG4", "4", "PWM event line 0") adcSym_MR_TRGSEL_VALUE.addKey("TRGSEL_ADC_TRIG5", "5", "PWM event line 1") adcSym_MR_TRGSEL_VALUE.addKey("TRGSEL_ADC_TRIG6", "6", "TIOA3") adcSym_MR_TRGSEL_VALUE.addKey("TRGSEL_ADC_TRIG7", "7", "RTCOUT0") adcSym_MR_TRGSEL_VALUE.setDependencies(adcTriggerVisible, ["ADC_TRGR_MODE"]) #ADC Internal Periodic Trigger global adcSym_TRIGGER_TIME adcSym_TRIGGER_TIME = adcComponent.createIntegerSymbol("ADC_TRIGGER_TIME", adcSym_TRGR_MODE) adcSym_TRIGGER_TIME.setLabel("Trigger Period (ms)") adcSym_TRIGGER_TIME.setDefaultValue(2) adcSym_TRIGGER_TIME.setMin(1) adcSym_TRIGGER_TIME.setMax(int((65536 * 1000.0) / adcSym_Clock.getValue())) adcSym_TRIGGER_TIME.setVisible(False) adcSym_TRIGGER_TIME.setDependencies(adcTriggerTimeVisible, ["ADC_TRGR_MODE"]) adcSym_TRGR_TRGPER = adcComponent.createIntegerSymbol("ADC_TRGR_TRIGGER_PERIOD", adcSym_TRIGGER_TIME) adcSym_TRGR_TRGPER.setVisible(False) adcSym_TRGR_TRGPER.setDependencies(adcCalcTriggerPeriod, ["ADC_TRIGGER_TIME", "ADC_TRGR_MODE"]) #Sleep Mode adcSym_MR_SLEEP = adcComponent.createBooleanSymbol("ADC_MR_SLEEP", adcMenu) adcSym_MR_SLEEP.setLabel("Sleep Mode") adcSym_MR_SLEEP.setDefaultValue(False) adcFastWakeupValues = ["OFF", "ON"] adcSym_MR_FWUP = adcComponent.createComboSymbol("ADC_MR_FWUP", adcSym_MR_SLEEP, adcFastWakeupValues) adcSym_MR_FWUP.setLabel("Fast Wakeup") adcSym_MR_FWUP.setDefaultValue(adcFastWakeupValues[0]) adcSym_MR_FWUP.setVisible(False) adcSym_MR_FWUP.setDependencies(adcSymbolVisible, ["ADC_MR_SLEEP"]) #Automatic Window Comparison adcSym_COMP_WINDOW = adcComponent.createBooleanSymbol("ADC_COMP_WINDOW", adcMenu) adcSym_COMP_WINDOW.setLabel("Automatic Window Comparison") adcSym_COMP_WINDOW.setDefaultValue(False) adcSym_EMR_CMPMODE = adcComponent.createKeyValueSetSymbol("ADC_EMR_CMPMODE", adcSym_COMP_WINDOW) adcSym_EMR_CMPMODE.setLabel("Comparison Mode") adcSym_EMR_CMPMODE.setDefaultValue(0) adcSym_EMR_CMPMODE.setOutputMode("Key") adcSym_EMR_CMPMODE.setDisplayMode("Description") adcSym_EMR_CMPMODE.addKey("CMPMODE_LOW", "0", "Vin < VLo") adcSym_EMR_CMPMODE.addKey("CMPMODE_HIGH", "1", "Vin < VHi") adcSym_EMR_CMPMODE.addKey("CMPMODE_IN", "2", "VLo < Vin < VHi") adcSym_EMR_CMPMODE.addKey("CMPMODE_OUT", "3", "VHi < Vin < VLo") adcSym_EMR_CMPMODE.setVisible(False) adcSym_EMR_CMPMODE.setDependencies(adcSymbolVisible, ["ADC_COMP_WINDOW"]) adcSym_EMR_CMPTYPE = adcComponent.createKeyValueSetSymbol("ADC_EMR_CMPTYPE", adcSym_COMP_WINDOW) adcSym_EMR_CMPTYPE.setLabel("Comparison Type") adcSym_EMR_CMPTYPE.setDefaultValue(0) adcSym_EMR_CMPTYPE.setOutputMode("Key") adcSym_EMR_CMPTYPE.setDisplayMode("Description") adcSym_EMR_CMPTYPE.addKey("CMPTYPE_FLAG_ONLY", "0", "0-No Comparison") adcSym_EMR_CMPTYPE.addKey("CMPTYPE_START_CONDITION", "1", "1-Comparison match") adcSym_EMR_CMPTYPE.setVisible(False) adcSym_EMR_CMPTYPE.setDependencies(adcSymbolVisible, ["ADC_COMP_WINDOW"]) adcCompSelectedChannelValues = adcChannelsValues[1:] adcCompSelectedChannelValues.append("All"); adcSym_EMR_CMPSEL = adcComponent.createComboSymbol("ADC_EMR_CMPSEL", adcSym_COMP_WINDOW, adcCompSelectedChannelValues) adcSym_EMR_CMPSEL.setLabel("Comparison Selected Channel") adcSym_EMR_CMPSEL.setDefaultValue(adcCompSelectedChannelValues[0]) adcSym_EMR_CMPSEL.setVisible(False) adcSym_EMR_CMPSEL.setDependencies(adcSymbolVisible, ["ADC_COMP_WINDOW"]) adcSym_CWR_LOWTHRES = adcComponent.createIntegerSymbol("ADC_CWR_LOWTHRES_VALUE", adcSym_COMP_WINDOW) adcSym_CWR_LOWTHRES.setLabel("Low Threshold") adcSym_CWR_LOWTHRES.setDefaultValue(0) adcSym_CWR_LOWTHRES.setVisible(False) adcSym_CWR_LOWTHRES.setMin(0) adcSym_CWR_LOWTHRES.setMax(16383) adcSym_CWR_LOWTHRES.setDependencies(adcSymbolVisible, ["ADC_COMP_WINDOW"]) adcSym_CWR_HIGHTHRES = adcComponent.createIntegerSymbol("ADC_CWR_HIGHTHRES_VALUE", adcSym_COMP_WINDOW) adcSym_CWR_HIGHTHRES.setLabel("High Threshold") adcSym_CWR_HIGHTHRES.setDefaultValue(0) adcSym_CWR_HIGHTHRES.setVisible(False) adcSym_CWR_HIGHTHRES.setMin(0) adcSym_CWR_HIGHTHRES.setMax(16383) adcSym_CWR_HIGHTHRES.setDependencies(adcSymbolVisible, ["ADC_COMP_WINDOW"]) global adcSym_IER_COMPE adcSym_IER_COMPE = adcComponent.createBooleanSymbol("ADC_IER_COMPE", adcSym_COMP_WINDOW) adcSym_IER_COMPE.setLabel("Comparison Event Interrupt") adcSym_IER_COMPE.setDefaultValue(False) adcSym_IER_COMPE.setVisible(False) adcSym_IER_COMPE.setDependencies(adcSymbolVisible, ["ADC_COMP_WINDOW"]) #------------------------------------------------------------------------------------ #user sequence menu adcUserSeq = adcComponent.createMenuSymbol("ADC_USER_SEQ", None) adcUserSeq.setLabel("User Channel Sequence Configuration") #user sequence comment adcSym_USEQ_COMMENT = adcComponent.createCommentSymbol("ADC_USEQ_COMMENT", adcUserSeq) adcSym_USEQ_COMMENT.setLabel("**** Configure selected channels in the Channel Configuration Menu ****") #enable user sequence adcSym_MR_USEQ = adcComponent.createBooleanSymbol("ADC_MR_USEQ", adcUserSeq) adcSym_MR_USEQ.setLabel("Enable User Sequence Mode") adcSym_MR_USEQ.setDefaultValue(False) for channelID in range(0, len(channel)-1): #channel selection for user sequence adcSym_SEQR1_USCH.append(channelID) adcSym_SEQR1_USCH[channelID] = adcComponent.createComboSymbol("ADC_SEQR1_USCH" + str(channelID + 1), adcSym_MR_USEQ, adcChannelsValues) adcSym_SEQR1_USCH[channelID].setLabel("Select Channel for Sequence Number " + str(channelID + 1)) adcSym_SEQR1_USCH[channelID].setDefaultValue(adcChannelsValues[0]) adcSym_SEQR1_USCH[channelID].setVisible(False) adcSym_SEQR1_USCH[channelID].setDependencies(adcUserSeqVisible, ["ADC_MR_USEQ"]) #-------------------------------------------------------------------------------------- adcCHConfMenu = adcComponent.createMenuSymbol("ADC_CH_CONF", None) adcCHConfMenu.setLabel("Channel Configuration") # Loop runs for 12 channels and visibility of the channel is controlled as per available pins for channelID in range(0, len(channel)): #Channel menu global adcCHMenu adcCHMenu.append(channelID) adcCHMenu[channelID] = adcComponent.createMenuSymbol("CH"+str(channelID), adcCHConfMenu) adcCHMenu[channelID].setLabel("Channel "+str(channelID)) #Show channels as per available pins in package if (channel[channelID] == "False"): adcCHMenu[channelID].setVisible(False) #Channel enable adcSym_CH_CHER.append(channelID) adcSym_CH_CHER[channelID] = adcComponent.createBooleanSymbol("ADC_"+str(channelID)+"_CHER", adcCHMenu[channelID]) adcSym_CH_CHER[channelID].setLabel("Enable Channel " + str(channelID)) adcSym_CH_CHER[channelID].setDefaultValue(False) #enable corresponding channel pair for diff mode, e.g. CH0 and CH1 if (channelID % 2 == 1): adcSym_CH_CHER[channelID].setDependencies(adcCHEnable, ["ADC_"+str(channelID-1)+"_NEG_INP"]) #Channel name adcSym_CH_NAME.append(channelID) adcSym_CH_NAME[channelID] = adcComponent.createStringSymbol("ADC_"+str(channelID)+"_NAME", adcSym_CH_CHER[channelID]) adcSym_CH_NAME[channelID].setLabel("Name") adcSym_CH_NAME[channelID].setDefaultValue("CHANNEL_"+str(channelID)) adcSym_CH_NAME[channelID].setVisible(False) adcSym_CH_NAME[channelID].setDependencies(adcCHNameVisible, ["ADC_"+str(channelID)+"_CHER"]) #Channel positive input adcSym_CH_PositiveInput.append(channelID) adcSym_CH_PositiveInput[channelID] = adcComponent.createStringSymbol("ADC_"+str(channelID)+"_POS_INP", adcSym_CH_CHER[channelID]) adcSym_CH_PositiveInput[channelID].setLabel("Positive Input") adcSym_CH_PositiveInput[channelID].setDefaultValue("AN"+str(channelID)) adcSym_CH_PositiveInput[channelID].setReadOnly(True) adcSym_CH_PositiveInput[channelID].setVisible(False) adcSym_CH_PositiveInput[channelID].setDependencies(adcCHPosInpVisible, ["ADC_"+str(channelID)+"_CHER"]) #Channel negative input adcSym_CH_NegativeInput.append(channelID) adc_EvenChNegInput = ["GND", "AN"+str(channelID+1)] adc_OddChNegInput = ["GND"] if (channelID % 2 == 1): adcSym_CH_NegativeInput[channelID] = adcComponent.createComboSymbol("ADC_"+str(channelID)+"_NEG_INP", adcSym_CH_CHER[channelID], adc_OddChNegInput) adcSym_CH_NegativeInput[channelID].setReadOnly(True) else: adcSym_CH_NegativeInput[channelID] = adcComponent.createComboSymbol("ADC_"+str(channelID)+"_NEG_INP", adcSym_CH_CHER[channelID], adc_EvenChNegInput) if (channel[channelID + 1] == "False"): adcSym_CH_NegativeInput[channelID].setReadOnly(True) adcSym_CH_NegativeInput[channelID].setLabel("Negative Input") adcSym_CH_NegativeInput[channelID].setDefaultValue("GND") adcSym_CH_NegativeInput[channelID].setVisible(False) adcSym_CH_NegativeInput[channelID].setDependencies(adcCHNegInpVisible, ["ADC_"+str(channelID)+"_CHER"]) #Channel interrupt adcSym_CH_IER_EOC.append(channelID) adcSym_CH_IER_EOC[channelID] = adcComponent.createBooleanSymbol("ADC_"+str(channelID)+"_IER_EOC", adcSym_CH_CHER[channelID]) adcSym_CH_IER_EOC[channelID].setLabel("End of conversion interrupt") adcSym_CH_IER_EOC[channelID].setDefaultValue(False) adcSym_CH_IER_EOC[channelID].setVisible(False) adcSym_CH_IER_EOC[channelID].setDependencies(adcCHInterruptVisible, ["ADC_"+str(channelID)+"_CHER"]) # Clock dynamic settings adcSym_ClockControl = adcComponent.createBooleanSymbol("ADC_CLOCK_ENABLE", None) adcSym_ClockControl.setDependencies(adcClockControl, ["ADC_0_CHER", "ADC_1_CHER", "ADC_2_CHER", "ADC_3_CHER", "ADC_4_CHER", \ "ADC_5_CHER", "ADC_6_CHER", "ADC_7_CHER", "ADC_8_CHER", "ADC_9_CHER", "ADC_10_CHER", "ADC_11_CHER"]) adcSym_ClockControl.setVisible(False) # Interrupt Dynamic settings adcSym_InterruptControl = adcComponent.createBooleanSymbol("ADC_INTERRUPT_ENABLE", None) adcSym_InterruptControl.setDependencies(adcInterruptEnableDisableCallback, ["ADC_0_IER_EOC", "ADC_1_IER_EOC", "ADC_2_IER_EOC", "ADC_3_IER_EOC", "ADC_4_IER_EOC",\ "ADC_5_IER_EOC", "ADC_6_IER_EOC", "ADC_7_IER_EOC", "ADC_8_IER_EOC", "ADC_9_IER_EOC", "ADC_10_IER_EOC", "ADC_11_IER_EOC", "ADC_IER_COMPE"]) adcSym_InterruptControl.setVisible(False) # Dependency Status adcSym_ClkEnComment = adcComponent.createCommentSymbol("ADC_CLK_ENABLE_COMMENT", None) adcSym_ClkEnComment.setVisible(False) adcSym_ClkEnComment.setLabel("Warning!!! " + adcInstanceName.getValue() + " Peripheral Clock is Disabled in Clock Manager") adcSym_ClkEnComment.setDependencies(dependencyClockStatus, ["core." + adcInstanceName.getValue() + "_CLOCK_ENABLE", "ADC_0_CHER", "ADC_1_CHER", "ADC_2_CHER", "ADC_3_CHER", "ADC_4_CHER", \ "ADC_5_CHER", "ADC_6_CHER", "ADC_7_CHER", "ADC_8_CHER", "ADC_9_CHER", "ADC_10_CHER", "ADC_11_CHER"]) adcSym_IntEnComment = adcComponent.createCommentSymbol("ADC_INTERRUPT_ENABLE_COMMENT", None) adcSym_IntEnComment.setVisible(False) adcSym_IntEnComment.setLabel("Warning!!! " + adcInstanceName.getValue() + " Interrupt is Disabled in Interrupt Manager") adcSym_IntEnComment.setDependencies(dependencyIntStatus, ["core." + interruptSymbolEnable, "ADC_0_IER_EOC", "ADC_1_IER_EOC", "ADC_2_IER_EOC", "ADC_3_IER_EOC", "ADC_4_IER_EOC",\ "ADC_5_IER_EOC", "ADC_6_IER_EOC", "ADC_7_IER_EOC", "ADC_8_IER_EOC", "ADC_9_IER_EOC", "ADC_10_IER_EOC", "ADC_11_IER_EOC", "ADC_IER_COMPE"]) #-------------------------------------------------------------------------------------- configName = Variables.get("__CONFIGURATION_NAME") ################################################################################################### ########################### Code Generation ################################# ################################################################################################### adc = ATDF.getNode("/avr-tools-device-file/modules/module@[name=\"ADC\"]") adcID = adc.getAttribute("id") adcHeaderFile = adcComponent.createFileSymbol("ADC_HEADER", None) adcHeaderFile.setSourcePath("../peripheral/adc_" + str(adcID) + "/templates/plib_adc.h.ftl") adcHeaderFile.setOutputName("plib_" + adcInstanceName.getValue().lower() + ".h") adcHeaderFile.setDestPath("peripheral/adc/") adcHeaderFile.setProjectPath("config/" + configName +"/peripheral/adc/") adcHeaderFile.setType("HEADER") adcHeaderFile.setMarkup(True) adcCommonHeaderFile = adcComponent.createFileSymbol("ADC_COMMON_HEADER", None) adcCommonHeaderFile.setSourcePath("../peripheral/adc_" + str(adcID) + "/templates/plib_adc_common.h") adcCommonHeaderFile.setOutputName("plib_adc_common.h") adcCommonHeaderFile.setDestPath("peripheral/adc/") adcCommonHeaderFile.setProjectPath("config/" + configName +"/peripheral/adc/") adcCommonHeaderFile.setType("HEADER") adcSource1File = adcComponent.createFileSymbol("ADC_SOURCE", None) adcSource1File.setSourcePath("../peripheral/adc_" + str(adcID) + "/templates/plib_adc.c.ftl") adcSource1File.setOutputName("plib_" + adcInstanceName.getValue().lower() + ".c") adcSource1File.setDestPath("peripheral/adc/") adcSource1File.setProjectPath("config/" + configName +"/peripheral/adc/") adcSource1File.setType("SOURCE") adcSource1File.setMarkup(True) adcSystemInitFile = adcComponent.createFileSymbol("ADC_INIT", None) adcSystemInitFile.setType("STRING") adcSystemInitFile.setOutputName("core.LIST_SYSTEM_INIT_C_SYS_INITIALIZE_PERIPHERALS") adcSystemInitFile.setSourcePath("../peripheral/adc_"+str(adcID)+"/templates/system/initialization.c.ftl") adcSystemInitFile.setMarkup(True) adcSystemDefFile = adcComponent.createFileSymbol("ADC_DEF", None) adcSystemDefFile.setType("STRING") adcSystemDefFile.setOutputName("core.LIST_SYSTEM_DEFINITIONS_H_INCLUDES") adcSystemDefFile.setSourcePath("../peripheral/adc_"+str(adcID)+"/templates/system/definitions.h.ftl") adcSystemDefFile.setMarkup(True)
def intdiv(a, b): return a // b if __name__ == "__main__": print("Hi, I can calculate the integer division of two numers") a = int(input("a = ")) b = int(input("b = ")) print(f"a // b = {intdiv(a, b)}") print("Bye!")
class Solution(object): def combinationSum(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ q = [(target, [])] candidates = sorted(candidates) result = [] while q: num, history = q.pop(0) if num == 0: result.append(history) else: if not history: if num < candidates[0]: continue idx = 0 else: idx = history[-1][0] + 1 if idx >= len(candidates): continue if candidates[idx] > num: continue while True: cnt = 1 while num >= cnt * candidates[idx]: newnum = num - cnt * candidates[idx] newhistory = history[:] newhistory.append((idx, cnt)) q.append((newnum, newhistory)) cnt += 1 idx += 1 if idx >= len(candidates) or candidates[idx] > num: break ret = [] for r in result: l = [] for idx, cnt in r: l.extend([candidates[idx]] * cnt) ret.append(l) return ret
def power_consumption(): pass def deadlines(): pass def idle_cranes(): pass def idle_machines(): pass def buffer_usage(): pass def material_pickup(): pass
def get_package_data(): return { _ASTROPY_PACKAGE_NAME_ + ".tests": [ "coveragerc", "data/*.h5", "data/*.dat", "data/*.npy", "integration_tests/*/*.yml", "integration_tests/*/*.dat", ] }
# Funções def tamanho(sequencia): cont = 0 for _ in sequencia: cont += 1 return cont def contar(sequencia, valor): cont = 0 for x in sequencia: if x == valor: cont += 1 return cont def somar(sequencia): soma = 0 for x in sequencia: soma += x return soma def all_indexes(sequencia, valor): """ Retorna uma lista com todos os índices de <valor> encontrados em <sequência> Se não for encontrado nenhum, retorna uma lista vazia [] """ pass # Código principal lista = [2, 3, 25, 4, 87, 27, 25] n1_lista = tamanho(lista) n2_lista = len(lista) print(n1_lista, n2_lista)
# # Exercism.io # Python track # Problem #1 - Hello World # github.com/marnovo/Exercism # name = input("Tell your name: ") def hello(name=''): if name == '': message = "Hello, World!" else: message = "Hello, " + name + "!" return message print(hello(name))
# EXERCÍCIO 2 # Faça um programa que leia o nome de uma pessoa e mostra uma mensagem de boas vinda. nome = input('Digite o seu nome: ') # print('Modelo 1') print('É um prazer te conhecer, {}!'.format(nome)) # print('Modelo 2') # print('É um prazer te conhecer, '+ nome)
#Challenge042 v1 = float(input(' medida 1: ')) v2 = float(input(' medida 2: ')) v3 = float(input(' medida 3: ')) #if v1+v2+v3 == 180: if v1 == v2 == v3: print('Triangulo equilatero: com todos os lados iguais') elif (v1 == v2 or v3) and (v2 == v1 or v3 ): print('tringulo isoceles dois lados iguais') elif (v1 != v2 or v3) and (v2 != v1 or v3) and (v3 != v1 or v2): print('escaleno') else: print('nao e um triangulo')
# -*- coding: UTF-8 -*- ############################################################################## # # # Copyright (c) 2007-2010 Bernd Kreuss <prof7bit@gmail.com> # # # # Translation file for TorChat # # # ############################################################################## LANGUAGE_CODE = u"en" LANGUAGE_NAME = u"English" LANGUAGE_NAME_ENGLISH = u"English" TRANSLATOR_NAMES = [] #buttons BTN_CANCEL = u"Cancel" BTN_OK = u"Ok" BTN_SAVE_AS = u"Save as..." BTN_CLOSE = u"Close" #status ST_AVAILABLE = u"Available" ST_AWAY = u"Away" ST_EXTENDED_AWAY = u"Extended away" ST_OFFLINE = u"Offline" #TaskbarMenu MTB_SHOW_HIDE_TORCHAT = u"Show/Hide TorChat" MTB_QUIT = u"Quit" #popup menu MPOP_CHAT = u"Chat..." MPOP_SEND_FILE = u"Send file..." MPOP_EDIT_CONTACT = u"Edit contact..." MPOP_DELETE_CONTACT = u"Delete contact..." MPOP_SHOW_OFFLINE_MESSAGES = u"Show queued offline messages" MPOP_CLEAR_OFFLINE_MESSAGES = u"Clear queued offline messages" MPOP_ACTIVATE_LOG = u"Activate logging to file" MPOP_STOP_LOG = u"Stop logging" MPOP_DELETE_EXISTING_LOG = u"Delete existing log file" MPOP_DELETE_AND_STOP_LOG = u"Delete log and stop logging" MPOP_ADD_CONTACT = u"Add contact..." MPOP_ABOUT = u"About TorChat" MPOP_ASK_AUTHOR = u"Ask %s..." MPOP_SETTINGS = u"Settings..." MPOP_EDIT_MY_PROFILE = u"Edit my profile..." MPOP_COPY_ID_TO_CLIPBOARD=u"Copy ID to clipboard" #chat window popup menu CPOP_COPY = u"Copy" #confirm delete message box D_CONFIRM_DELETE_TITLE = u"Confirm deletion" D_CONFIRM_DELETE_MESSAGE = u"Really delete this contact?\n(%s %s)" #warning about log D_LOG_WARNING_TITLE = u"TorChat: Logging is active" D_LOG_WARNING_MESSAGE = u"Logging to file is activated!\n\nLog File: %s\n\nRemember to delete the log file if you have finished debugging because the log file may contain sensitive information." #warning about used port D_WARN_USED_PORT_TITLE = u"TorChat: Port already in use" D_WARN_USED_PORT_MESSAGE = u"Something, probably another TorChat instance, is already listening at %s:%s. You must create another profile using different ports to be able to start TorChat a second time." #warnig about unread messages D_WARN_UNREAD_TITLE = u"TorChat: Unread messages" D_WARN_UNREAD_MESSAGE = u"There are unread messages.\nThey will be lost forever!\n\nDo you really want to exit TorChat now?" #warning about offline buddy D_WARN_BUDDY_OFFLINE_TITLE = u"TorChat: Buddy is offline" D_WARN_BUDDY_OFFLINE_MESSAGE = u"This operation is not possible with offline buddies" #warning about multiple files D_WARN_FILE_ONLY_ONE_TITLE = u"TorChat: Multiple files" D_WARN_FILE_ONLY_ONE_MESSAGE = u"You may not start multiple file transfers with one operation. Start the transfers individually or send a zip-file instead" #warning about file save error D_WARN_FILE_SAVE_ERROR_TITLE = u"TorChat: Error saving file" D_WARN_FILE_SAVE_ERROR_MESSAGE = u"The file '%s' could not be created.\n\n%s" #warning about file already exists D_WARN_FILE_ALREADY_EXISTS_TITLE = u"TorChat: File exists" D_WARN_FILE_ALREADY_EXISTS_MESSAGE = u"The file '%s' already exists.\nOverwrite it?" #dialog: add/edit contact DEC_TITLE_ADD = u"Add new contact" DEC_TITLE_EDIT = u"Edit contact" DEC_TORCHAT_ID = u"TorChat ID" DEC_DISPLAY_NAME = u"Display name" DEC_INTRODUCTION = u"Introduction" DEC_MSG_16_CHARACTERS = u"The address must be 16 characters long, not %i." DEC_MSG_ONLY_ALPANUM = u"The address must only contain numbers and lowercase letters" DEC_MSG_ALREADY_ON_LIST = u"%s is already on your list" #dialog: edit my profile DEP_TITLE = u"Edit my profile" DEP_NAME = u"Name" DEP_TEXT = u"Text" DEP_SET_AVATAR = u"Set Avatar" DEP_REMOVE_AVATAR = u"Remove Avatar" DEP_AVATAR_SELECT_PNG = u"Select .PNG file to use as your avatar (will be scaled to 64*64, may contain transparency)" DEP_PNG_FILES = u"PNG files" DEP_ALL_FILES = u"All files" DEP_WARN_TITLE = u"Avatar selection not possible" DEP_WARN_IS_ALREADY = u"This is already the current avatar" DEP_WARN_MUST_BE_PNG = u"The avatar must be a .png file" #file transfer window DFT_FILE_OPEN_TITLE = u"Send file to %s" DFT_FILE_SAVE_TITLE = u"Save file from %s" DFT_SEND = u"Sending %s\nto %s\n%04.1f%% (%i of %i bytes)" DFT_RECEIVE = u"Receiving %s\nfrom %s\n%04.1f%% (%i of %i bytes)" DFT_WAITING = u"waiting for connection" DFT_STARTING = u"starting transfer" DFT_ABORTED = u"transfer aborted" DFT_COMPLETE = u"transfer complete" DFT_ERROR = u"error" #settings dialaog DSET_TITLE = u"TorChat configuration" DSET_NET_TITLE = u"Network" DSET_NET_ACTIVE = u"active" DSET_NET_INACTIVE = u"inactive" DSET_NET_TOR_ADDRESS = u"Tor proxy address" DSET_NET_TOR_SOCKS = u"Socks port" DSET_NET_TOR_CONTROL = u"Control port" DSET_NET_OWN_HOSTNAME = u"Own TorChat-ID" DSET_NET_LISTEN_INTERFACE = u"Listen interface" DSET_NET_LISTEN_PORT = u"Listen port" DSET_GUI_TITLE = u"User interface" DSET_GUI_LANGUAGE = u"Language" DSET_GUI_OPEN_MAIN_HIDDEN = u"Start with minimized main window" DSET_GUI_OPEN_CHAT_HIDDEN = u"Don't automatically open new windows" DSET_GUI_NOTIFICATION_POPUP = u"Notification pop-up" DSET_GUI_NOTIFICATION_METHOD = u"Notification method" DSET_GUI_FLASH_WINDOW = u"Flash window title on new message" DSET_MISC_TITLE = u"Misc" DSET_MISC_TEMP_IN_DATA = u"Store temporary files inside data directory" DSET_MISC_TEMP_CUSTOM_DIR = u"Temporary directory (leave empty for OS-default)" #notices in the chat window (those in square brackets) NOTICE_DELAYED_MSG_WAITING = u"delayed messages waiting to be sent" NOTICE_DELAYED_MSG_SENT = u"delayed messages have been sent" NOTICE_DELAYED = u"delayed" #messagebox for offline messages MSG_OFFLINE_TITLE = u"TorChat: queued messages" MSG_OFFLINE_EMPTY = u"there are no (more) queued messages for %s" MSG_OFFLINE_QUEUED = u"queued offline messages for %s:\n\n%s" #buddy list mouse hover popup BPOP_BUDDY_IS_OFFLINE = u"Buddy is offline" BPOP_CONNECTED_AWAITING_RETURN_CONN = u"Connected, awaiting return connection..." BPOP_CLIENT_SOFTWARE = u"Client: %s %s" #logging of conversations to file LOG_HEADER = u"This log file is not signed and has no cogency of proof" LOG_STARTED = u"Logging started" LOG_STOPPED = u"Logging stopped" LOG_DELETED = u"Log files have been deleted" LOG_IS_ACTIVATED = u"Logging to file is activated:\n%s" LOG_IS_STOPPED_OLD_LOG_FOUND = u"Logging is stopped but old log file still exists:\n%s" #about box ABOUT_TITLE = u"About TorChat" ABOUT_TEXT = u"""TorChat %(version)s (svn: r%(svn)s) %(copyright)s Translations: %(translators)s Runtime environment: Python: %(python)s wx: %(wx)s TorChat is free software: you can redistribute it and/or \ modify it under the terms of the GNU General Public \ License as published by the Free Software Foundation, \ either version 3 of the License, or (at your option) \ any later version. TorChat is distributed in the hope that it will be useful, \ but WITHOUT ANY WARRANTY; without even the implied \ warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. \ See the GNU General Public License for more details. * And now for something completely different: If you happen to run a software company near Hannover, Germany and \ are in need of a new coder, feel free to regard this little program \ as my application documents and drop me a mail with your answer. """
# @Title: 最长湍流子数组 (Longest Turbulent Subarray) # @Author: KivenC # @Date: 2020-07-15 15:29:06 # @Runtime: 612 ms # @Memory: 17.7 MB class Solution: def maxTurbulenceSize(self, A: List[int]) -> int: n = len(A) if n < 2: return 1 up, down, res = 1, 1, 1 for i in range(1, n): if A[i] > A[i-1]: up, down = down + 1, 1 elif A[i] < A[i-1]: down, up = up + 1, 1 else: up, down = 1, 1 res = max(res, up, down) return res
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class CaseTwoItem(object): def __init__(self, ts, nginx_pods, running_trainers, collector): self.ts = ts self.nginx_pods = nginx_pods self.running_trainers = running_trainers self.cpu_utils = collector.cpu_utils() self.gpu_utils = collector.gpu_utils() #def values(self): # return [str(self.times), str(self.nginx_pods), str(self.running_trainers), str(self.cpu_utils)] class CaseTwoReport(object): def __init__(self): self.items = [] self.avg_cpu_utils = 0.0 self.cnt = 0 def append_item(self, item): # append new item only if Nginx pods changed if not self.items or \ self.items[-1].nginx_pods != item.nginx_pods or \ self.items[-1].running_trainers != item.running_trainers: self.items.append(item) self.avg_cpu_utils += float(item.cpu_utils) self.cnt += 1 def title(self): return ['TIME', 'NGINX PODS', 'RUNNING TRAINERS', 'CLUSTER CPU UTILS'] def to_csv(self, fn): self.avg_cpu_utils /= self.cnt with open(fn, 'w') as f: f.write('|'.join(self.title()) + '\n') for item in self.items: f.write('|'.join([ str(item.ts), str(item.nginx_pods), str( item.running_trainers), item.cpu_utils ]) + '\n')
def isDigit(symbol): ''' Determine if the given character is a digit or not. ''' return symbol.isdigit()
ash_pokedex = ['Pikachu', 'Bulbasaur', 'Koffing', 'Spearow', 'Vulpix', 'Wigglytuff', 'Zubat', 'Rattata', 'Psyduck', 'Squirtle'] brock_pokedex = ['Onix', 'Geodude', 'Zubat', 'Golem', 'Vulpix', 'Tauros', 'Kabutops', 'Omastar', 'Machop', 'Dugtrio'] # Convert Brock's Pokédex to a set brock_pokedex_set = set(brock_pokedex) print(brock_pokedex_set) ''' {'Tauros', 'Golem', 'Onix', 'Omastar', 'Vulpix', 'Dugtrio', 'Zubat', 'Geodude', 'Kabutops', 'Machop'} ''' # Check if Psyduck is in Ash's list and Brock's set print('Psyduck' in ash_pokedex) print('Psyduck' in brock_pokedex_set) ''' True False ''' # Check if Machop is in Ash's list and Brock's set print('Machop' in ash_pokedex) print('Machop' in brock_pokedex_set) ''' False True ''' ''' Membership testing is much faster when you use sets. Did you notice that using a set for member testing is faster than using a list regardless if the item you are checking is in the set? Checking for 'Psyduck' (which was not in Brock's set) is still faster than checking for 'Psyduck' in Ash's list! '''
a = list(" " * 9) step = 0 def printgame(): print('-' * 9) for i in range(3): print("| {} {} {} |".format(a[0 + 3 * i], a[1 + 3 * i], a[2 + 3 * i])) print('-' * 9) while " " in a: playx, playy = input("Enter the coordinates:").split() if (int(playx) or int(playy)) not in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]: print("You should enter numbers!") elif (int(playx) or int(playy)) not in [1, 2, 3]: print("Coordinates should be from 1 to 3!") elif a[(int(playx) - 1) + abs(int(playy) - 3) * 3] != " ": print("This cell is occupied! Choose another one!") else: if step == 0: a[(int(playx) - 1) + abs(int(playy) - 3) * 3] = "X" step = 1 elif step == 1: a[(int(playx) - 1) + abs(int(playy) - 3) * 3] = "O" step = 0 printgame() rule = [a[:3], a[3:6], a[6:], a[0:9:3], a[1:9:3], a[2:9:3], a[0:9:4], a[2:7:2]] if ['X', 'X', 'X'] in rule: print("X wins") elif ['O', 'O', 'O'] in rule: print("O wins") elif a.count(" ") == 0: print("Draw")
#!/usr/bin/python3 def new_in_list(my_list, idx, element): list1 = my_list.copy() leng = len(my_list) if idx < 0: return list1 if idx >= leng: return list1 list1[idx] = element return list1
''' Leap year is an year with 366 days. Leap Year should be divisible by 4. Also it should be divisible by 400 and not divisible by 100. ''' def checkLeapYear(year): if year % 400 == 0: return 1 if year % 100 == 0: return 0 if year % 4 == 0: return 1 return 0 year1 = int(input("Enter the first year:\n")) year2 = int(input("Enter the second year:\n")) print("The leap years between %d and %d are:" % (year1, year2)) for year in range(year1, year2): if checkLeapYear(year) == 1: print(year) ''' Input: 2000 2050 Output: The leap years between 2000 and 2050 are: 2000 2004 2008 2012 2016 2020 2024 2028 2032 2036 2040 2044 2048 '''
#!/usr/bin/env python # -*- coding: utf-8 -*- def Eq(field, value): return {'_field': field, '_value': value} def Gt(field, value): return {'_gt': {field: value}} def Gte(field, value): return {'_gte': {field: value}} def Lt(field, value): return {'_lt': {field: value}} def Lte(field, value): return {'_lte': {field: value}} def And(*criteria): return {'_and': criteria} def Or(*criteria): return {'_or': criteria} def Not(criterion): return {'_not': criterion} def In(field, values): return {'_in': {'_field': field, '_values': values}} def Contains(field): return {'_contains': field} def Id(id): return {'_id': id} def Between(field, from_value, to_value): return {'_between': {'_field': field, '_from': from_value, '_to': to_value}} def ParentId(tpe, id): return {'_parent': {'_type': tpe, '_id': id}} def Parent(tpe, criterion): return {'_parent': {'_type': tpe, '_query': criterion}} def Child(tpe, criterion): return {'_child': {'_type': tpe, '_query': criterion}} def Type(tpe): return {'_type': tpe} def String(query_string): return {'_string': query_string}
class LinkNodeIter: def __init__(self, link): self._link = link def __iter__(self): return self def __next__(self): next_value = self._link if next_value is not None: self._link = next_value.next_link else: raise StopIteration return next_value
class Solution: def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int: count = 0 for index in range(len(points)-1): count += max(abs(points[index][0]-points[index+1][0]), abs(points[index][1]-points[index+1][1])) return count
async def db_get(db, query, **parameters): async with db.execute(query, parameters) as cursor: async for row in cursor: yield dict(row) async def db_get_one(db, column, query, **parameters): async for row in db_get(db, query, **parameters): return row.get(column, None) else: return None async def db_get_first(db, query, **parameters): async for row in db_get(db, query, **parameters): return row else: return None async def insert_one(db, query, **parameters): async with db.execute(query, parameters) as cursor: return cursor.lastrowid
#!/usr/bin/env python3 while True: n = int(input('Quer ver a tabuada de qual número ? <número negativo para parar>')) print('-'*30) if n < 0: break for c in range (1, 11): print(f'{n} x {c} = {n*c}') print('-'*30) print('PROGRAMA TABUADA ENCERRADO ! Volte sempre !')
def test_line_highlight_fragments(test_env): slide = test_env.slide img = test_env.data_path("testimage.svg") slide.image(img) b = slide.box(x="[90%]", y="[30%]", width="30%", height="30%", show="4+") b.rect("black", bg_color="white") b2 = b.box(width="fill") b2.update_style("default", size=15, color="white") b2.rect(bg_color="black") b2.box(padding=10).text("Scaling and placing images") b.fbox().image(img, show_begin=4) test_env.check("imagefrag", 6) def test_line_highlight_no_fragments(test_env): slide = test_env.slide img = test_env.data_path("testimage.svg") slide.image(img, fragments=False) b = slide.box(x="[90%]", y="[30%]", width="30%", height="30%") b.rect("black", bg_color="white") b2 = b.box(width="fill") b2.update_style("default", size=15, color="white") b2.rect(bg_color="black") b2.box(padding=10).text("Scaling and placing images") b.fbox().image(img, fragments=False) test_env.check("imagenofrag") def test_image_show(test_env): """ Regresion test for show attribute when element has no childs """ slide = test_env.slide slide.image(test_env.data_path("testimage2.svg")) test_env.check("imageshowx", 3) def test_image_no_fragments_show_begin(test_env): slide = test_env.slide img = test_env.data_path("testimage.svg") slide.image(img, fragments=False, show_begin=3) test_env.check("nofrag_showbegin", 3)
red = "#c91111" orange = "#e09401" pale_blue = "#13aed5" dark_blue = "#1321d8" purple = "#642197"
"""Wagtail Live Exceptions.""" class RequestVerificationError(Exception): pass class WebhookSetupError(Exception): pass
# -*- coding: UTF-8 -*- logger.info("Loading 8 objects to table lists_list...") # fields: id, ref, designation, list_type, remarks loader.save(create_lists_list(1,None,['Announcements', 'Ank\xfcndigungen', 'Announcements'],1,u'')) loader.save(create_lists_list(2,None,['Weekly newsletter', 'Weekly newsletter', 'Weekly newsletter'],1,u'')) loader.save(create_lists_list(3,None,['General discussion', 'General discussion', 'General discussion'],2,u'')) loader.save(create_lists_list(4,None,['Beginners forum', 'Beginners forum', 'Beginners forum'],2,u'')) loader.save(create_lists_list(5,None,['Developers forum', 'Developers forum', 'Developers forum'],2,u'')) loader.save(create_lists_list(6,None,['PyCon 2014', 'PyCon 2014', 'PyCon 2014'],3,u'')) loader.save(create_lists_list(7,None,['Free Software Day 2014', 'Free Software Day 2014', 'Free Software Day 2014'],3,u'')) loader.save(create_lists_list(8,None,['Schools', 'Schulen', 'Schools'],3,u'')) loader.flush_deferred_objects()
if __name__ == '__main__': N = int(input()) elements = [] posicion = "" dato = "" for i in range(N): commands = input() longitud = len(commands) if commands[0:6] == "insert" : if(commands[8] == " "): posicion = commands[7] dato = commands[9:longitud+1] elif commands[9] == " ": posicion = commands[7:8] dato = commands[10:longitud+1] elements.insert(int(posicion),int(dato)) elif commands == "print": print(elements) elif commands[0:6] == "remove": elements.remove(int(commands[7:longitud+1])) elif commands[0:6] == "append": elements.append(int(commands[7:longitud+1])) elif commands == "sort": elements.sort() elif commands == "pop": elements.pop() else: elements.reverse()
IMG_HEIGHT = 480 IMG_WIDTH = 640 CLASS_NUM = 3 ANCHORS_GROUP = { 32:[[730,145],[288,190],[216,540]], 16:[[365,73],[144,95],[108,270]], 8:[[180,37],[72,44],[54,135]] } ANCHORS_GROUP_AREA = { 32: [x * y for x, y in ANCHORS_GROUP[32]], 16: [x * y for x, y in ANCHORS_GROUP[16]], 8: [x * y for x, y in ANCHORS_GROUP[8]], } color=['#ff0000','#0000ff','#00ff00']
def devedor(*args): try: telaDevedores = args[0] telaErro = args[1] cursor = args[2] banco10 = args[3] data = args[4] id = telaDevedores.codigo.text() sql = ("select id from gerenciarPedido where id = %s and dataa = %s") values = (id, data) cursor.execute(sql, values) dados2 = cursor.fetchall() id2 = dados2[0][0] sql = ("select dataa, hora, nome, telefone, valorTotal from gerenciarPedido where id = %s and dataa = %s") values = (id2, data) cursor.execute(sql, values) inf_cliente = cursor.fetchall() motivo = telaDevedores.motivo_dever.text() sql = "insert into devedores(id, dataa, hora, nome, telefone, valor, motivo) values (%s, %s, %s, %s, %s, %s, %s)" insert = (str(id2), str(inf_cliente[0][0]), str(inf_cliente[0][1]), str(inf_cliente[0][2]), str(inf_cliente[0][3]), str(inf_cliente[0][4]), str(motivo)) cursor.execute(sql, insert) banco10.commit() telaDevedores.hide() except: telaErro.show() telaErro.label.setText('Codigo invalido, tente novamente!')
name1_0_0_0_1_1_0 = None name1_0_0_0_1_1_1 = None name1_0_0_0_1_1_2 = None name1_0_0_0_1_1_3 = None name1_0_0_0_1_1_4 = None
LOCATIONemojis = { "fastbackwards": "<:fast_forward_left:870781340692402226>", "backwards": "<:left_arrow:870781340990197860>", "close": "<:Cross:863313854069997578>", "forwards": "<:right_arrow:870781340314898473>", "fastforwards": "<:fast_forward_right:870781340839202837>", } COGemojis = { "JesterInfo": 863075610048987166, "Feedback": 863075610851147777, "Music": 863075611320647719, "Snipe": 863075611269791794, "Fun": 863075609781075968, "Mod": 863075610784301068, "Games": 863075611329167380, "Utils": 863075611161788478, "Images": 863075611277656124, "Economy": 863075610913800233, "Misc": 863075610979729409, "Levels": 863075611182628895, "Config": 863075611169259550, "Love": 863075611374125056, "JesterJokes": 873327129016811528, "Cryptocurrency": 872473402764570624, "Countries": 872473402638762025, "ChatBot": 872473402693259324, "DiscordTogether": 872473402840076288, "UrbanDictionary": 924074967673503796, "Random": 924074967405051965, "Trivia": 924152372001910834, "Crime": 924411072729985046, "Docs": 925222917946605629, } CLOSE = "<:Cross:863313854069997578>" HOME = "<:Arrow:863313854040506379>" LINK = "<:links:870781340700782612>" CATEGORIES = "<:menus:870781340746932225>" TRASHCAN = "<:trashbin:873564727006089287>" j = "<:J_:863313855286607932>" e = "<:E_:863313854150606848>" s = "<:S:863313855061164062>" t = "<:T:863313855399329812>" r = "<:R_:863313855119360022>"
#!/usr/local/bin/python # Think Like a Programmer Chapter 2: Pure Puzzles exercises def main(): test_pound_shapes = False test_base_conversion = True if test_pound_shapes: poundV() print() poundDiamond() if test_base_conversion: tests = [ # [1, 1, 2, 1], # ValueError test # ['G', 17, 10, 17], # ValueError test # [15, 10, 10, '15'], # ['101', 2, 10, '5'], # ['1000', 2, 10, '8'], # ['A', 16, 10, '10'], # ['10', 16, 10, '16'], [11, 10, 16, 'B'], ['1100', 2, 16, 'C'] ] for t in tests: print("Testing baseConversion({}, {}, {})" .format(t[0], t[1], t[2])) try: res = baseConversion(t[0], t[1], t[2]) if t[3] == res: print("PASSED: baseConversion({}, {}, {}) returned {}" .format(t[0], t[1], t[2], res)) else: print("FAILED: baseConversion({}, {}, {}) returned {}, " "answer: {}".format(t[0], t[1], t[2], res, t[3])) except ValueError: print("PASSED: ValueError test") def poundV(): ''' Using only single output statements of a space, pound, or new line, create: ######## ###### #### ## ''' n = 4 space = ' ' pound = '#' for i in range(n, 0, -1): print((space * (n - i)) + (pound * i * 2) + (space * (n - i))) def poundDiamond(): ''' Using only single output statements of a space, pound, or new line, create: ## #### ###### ######## ######## ###### #### ## ''' n = 4 space = ' ' pound = '#' rangeItem = list(range(1, n + 1)) for i in rangeItem + rangeItem[::-1]: print((space * (n - i)) + (pound * i * 2) + (space * (n - i))) def baseConversion(num, s_base, t_base): ''' Takes a number num as str or int. Converts it from the source base (s_base, an int) into the target base (t_base, an int) and returns new number as a string. Source and target bases must be between 2 and 16. Input: num (str), s_base (int), t_base (int) Output: str ''' num = str(num) digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'] # Input checking if type(s_base) is not int or type(t_base) is not int: raise ValueError if (s_base < 2 or s_base > 16 or t_base < 2 or t_base > 16): raise ValueError # Convert number to base 10 if s_base == 10: # print("Num in base 10 already: {}".format(num)) base_10 = int(num) else: # print("Converting {} to base 10 from base {}".format(num, s_base)) base_10 = sum([digits.index(ch) * (s_base ** i) for i, ch in enumerate(list(num)[::-1])]) # print("Num in base 10 is: {}".format(base_10)) # Convert base-10 number to target base converted = '' if t_base == 10: converted = str(base_10) else: while base_10 > 0: r = base_10 % t_base converted = digits[r] + converted # print("Num: {}, num/{}: {}, digit: {}" # .format(base_10, t_base, r, digits[r])) base_10 //= t_base return converted if __name__ == '__main__': main()
class Table(object): def __init__(self): self.rows = [] def to_ascii_table(self): if not self.rows: return "" lines = [] def print_row(row): line = "" for column, l in zip(row, lens): if column is None: s = "" else: s = str(column) line += "| " + s + " " * (l - len(s)) + " " line += "|\n" lines.append(line) lens = [] for i, column in enumerate(self.rows[0]): lens.append(max(len(str(r[i])) for r in self.rows if r[i] is not None)) width = sum(lens) + 3 * len(self.rows[0]) + 1 separator = ("-" * width) + "\n" lines.append(separator) print_row(self.rows[0]) lines.append(separator) if len(self.rows) == 1: return for row in self.rows[1:]: print_row(row) lines.append(separator) return "".join(lines) def transpose(self): if not self.rows: return table = Table() for i in xrange(len(self.rows[0])): table.add_row([r[i] for r in self.rows]) return table def add_row(self, data): self.rows.append(data) def add_rows(self, rows): self.rows.extend(rows) def add_dictionaries(self, items, columns): self.add_row(columns) for item in items: row = [item.get(column) for column in columns] self.add_row(row)
class DeviceSelectCredential: def __init__(self, number): pass def __call__(self, status): pass
expected_output={ "rlist_id": { "0xf0001ae8": { "flags": "0x0", "packets": 38793, "pps": 0, "remote_ifs": 0, "state": 1, "status": "OK" }, "0xf0001ae9": { "flags": "0x0", "packets": 0, "pps": 0, "remote_ifs": 0, "state": 1, "status": "OK" }, "0xf0001aea": { "flags": "0x0", "packets": 0, "pps": 0, "remote_ifs": 0, "state": 1, "status": "OK" }, "0xf0001aeb": { "flags": "0x0", "packets": 0, "pps": 0, "remote_ifs": 0, "state": 1, "status": "OK" } } }
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: v = self.gf(l1) + self.gf(l2) ll = ListNode(str(v)[::-1][0]) t = ll for i in str(v)[::-1][1:]: t.next = ListNode(i) t = t.next return ll def gf(self, l: ListNode): s = 0 c = 1 while l.next: s += l.val * c c *= 10 l = l.next s += l.val * c return s def ii(ll): l = ListNode(ll[0]) t = l for i in ll[1:]: print(i) t.next = ListNode(i) t = t.next return l def p(lll): print("=====") while lll.next: print(lll.val) lll = lll.next print(lll.val) if __name__ == "__main__": ll1 = [2, 4, 3] ll2 = [5, 6, 4] p(ii(ll1)) # ss = Solution()
def get_fs(client): """Return the db containing file system metadata. Parameters ---------- client --> pymongo.mongo_client.MongoClient class, MongoDB client Returns ------- metadatafs['fs'] --> pymongo.collection.Collection, reference to collection fs """ #get the MongoDb collection called "fs" metadatafs = client['metadatafs'] return metadatafs['fs'] def get_users(client): """Return the db containing users metadata. Parameters ---------- client --> pymongo.mongo_client.MongoClient class, MongoDB client Returns ------- metadatafs['fs'] --> pymongo.collection.Collection, reference to collection users """ #get the MongoDb collection called "users" metadatafs = client['metadatafs'] return metadatafs['users'] def get_groups(client): """Return the db containing groups metadata. Parameters ---------- client --> pymongo.mongo_client.MongoClient class, MongoDB client Returns ------- metadatafs['fs'] --> pymongo.collection.Collection, reference to collection groups """ #get the MongoDb collection called "groups" metadatafs = client['metadatafs'] return metadatafs['groups'] def get_trash(client): """Return the db containing trash chunks to delete. Parameters ---------- client --> pymongo.mongo_client.MongoClient class, MongoDB client Returns ------- metadatafs['fs'] --> pymongo.collection.Collection, reference to collection trash """ #get the MongoDb collection called "trash" metadatafs = client['metadatafs'] return metadatafs['trash']
"""BLE/LSL interfacing parameters for specific devices. TODO: * Simple class (or specification/template) for device parameters """
file = open('rosalind_cons.txt', 'r') target = file.read() d_list = [] class DNAcon: def __init__(self): self.A = 0 self.C = 0 self.G = 0 self.T = 0 def add_A(self, value): self.A += value def add_C(self, value): self.C += value def add_G(self, value): self.G += value def add_T(self, value): self.T += value def inserter(target_str, target_list): raw = target_str while not raw.isspace() or len(raw) == 0: if raw[0] == '>': raw = raw[raw.index('\n') + 1:] try: loc = raw[0: raw.index('>')] loc = loc.replace('\n', '') target_list.append(loc) except: loc = raw[0:] loc = loc.replace('\n', '') target_list.append(loc) return raw = raw[raw.index('>'):] else: return inserter(target, d_list) maxlen = 0 for con in d_list: see = len(con) if see >= maxlen: maxlen = see matrix = [] for i in range(maxlen): target = DNAcon() for con in d_list: try: val = con[i] if val == 'A': target.add_A(1) elif val == 'C': target.add_C(1) elif val == 'G': target.add_G(1) elif val == 'T': target.add_T(1) except: continue matrix.append(target) consensus = '' for dna in matrix: maximum = 0 val = '' if dna.A >= maximum: maximum = dna.A val = 'A' if dna.C >= maximum: maximum = dna.C val = 'C' if dna.G >= maximum: maximum = dna.G val = 'G' if dna.T >= maximum: maximum = dna.T val = 'T' consensus += val print(consensus) for i in range(4): if i == 0: print('A:', end=' ') for dna in matrix: print(dna.A, end=' ') elif i == 1: print('C:', end=' ') for dna in matrix: print(dna.C, end=' ') elif i == 2: print('G:', end=' ') for dna in matrix: print(dna.G, end=' ') elif i == 3: print('T:', end=' ') for dna in matrix: print(dna.T, end=' ') print()
x1, y1 = list(map(int, input().split())) x2, y2 = list(map(int, input().split())) x3, y3 = list(map(int, input().split())) x4 = 0 y4 = 0 if x1 == x2: x4 = x3 elif x2 == x3: x4 = x1 else: x4 = x2 if y1 == y2: y4 = y3 elif y2 == y3: y4 = y1 else: y4 = y2 print("{0} {1}".format(x4, y4))
# -*- coding: utf-8 -*- """ longboxed.comics ~~~~~~~~~~~~~~~~ longboxed comics package """
def non_repeating(data): state = dict() for i in data: if i not in state: state[i] = 1 else: state[i] = state[i] + 1 for i in data: if state[i] == 1: return i return None if __name__ == "__main__": print(non_repeating("aaabbcdde")) print(non_repeating("aaabbeddc")) print(non_repeating("aabb"))
# Databricks notebook source # MAGIC %md # CCU002_02-D01-event_counts # MAGIC # MAGIC **Description** This notebook calculates the number of primary events from HES and death records for events. # MAGIC # MAGIC **Author(s)** Venexia Walker, Tom Bolton # COMMAND ---------- # MAGIC %md ## Define functions # COMMAND ---------- # Define create table function by Sam Hollings # Source: Workspaces/dars_nic_391419_j3w9t_collab/DATA_CURATION_wrang000_functions def create_table(table_name:str, database_name:str='dars_nic_391419_j3w9t_collab', select_sql_script:str=None) -> None: """Will save to table from a global_temp view of the same name as the supplied table name (if no SQL script is supplied) Otherwise, can supply a SQL script and this will be used to make the table with the specificed name, in the specifcied database.""" spark.conf.set("spark.sql.legacy.allowCreatingManagedTableUsingNonemptyLocation","true") if select_sql_script is None: select_sql_script = f"SELECT * FROM global_temp.{table_name}" spark.sql(f"""CREATE TABLE {database_name}.{table_name} AS {select_sql_script} """) spark.sql(f"ALTER TABLE {database_name}.{table_name} OWNER TO {database_name}") def drop_table(table_name:str, database_name:str='dars_nic_391419_j3w9t_collab', if_exists=True): if if_exists: IF_EXISTS = 'IF EXISTS' else: IF_EXISTS = '' spark.sql(f"DROP TABLE {IF_EXISTS} {database_name}.{table_name}") # COMMAND ---------- # MAGIC %md ## Refresh tables # COMMAND ---------- # MAGIC %sql # MAGIC -- Remove cached HES table # MAGIC REFRESH TABLE dars_nic_391419_j3w9t_collab.ccu002_vac_hes_apc_all_years # COMMAND ---------- # MAGIC %sql # MAGIC -- Remove cached deaths table # MAGIC REFRESH TABLE dars_nic_391419_j3w9t_collab.ccu002_vac_deaths_dars_nic_391419_j3w9t # COMMAND ---------- # MAGIC %sql # MAGIC -- Remove cached skinny table # MAGIC REFRESH TABLE dars_nic_391419_j3w9t_collab.curr302_patient_skinny_record # COMMAND ---------- # MAGIC %md ## Define event codes # COMMAND ---------- # MAGIC %sql # MAGIC -- Record the codes that define each event of interest # MAGIC CREATE OR REPLACE GLOBAL TEMPORARY VIEW event_codes AS # MAGIC SELECT # MAGIC * # MAGIC FROM VALUES # MAGIC ('I21','incident myocardial infarction',0), # MAGIC ('I22','incident myocardial infarction',0), # MAGIC ('I23','incident myocardial infarction',0), # MAGIC ('H34','retinal infarction',0), # MAGIC ('I630','ischaemic stroke',0), # MAGIC ('I631','ischaemic stroke',0), # MAGIC ('I632','ischaemic stroke',0), # MAGIC ('I633','ischaemic stroke',0), # MAGIC ('I634','ischaemic stroke',0), # MAGIC ('I635','ischaemic stroke',0), # MAGIC ('I637','ischaemic stroke',0), # MAGIC ('I638','ischaemic stroke',0), # MAGIC ('I639','ischaemic stroke',0), # MAGIC ('I63X','ischaemic stroke',0), # MAGIC ('I64','stroke of unknown type',0), # MAGIC ('I60','stroke, subarachnoid haemorrhage',0), # MAGIC ('I74','other arterial embolism',0), # MAGIC ('I260','pulmonary embolism',0), # MAGIC ('I269','pulmonary embolism',0), # MAGIC ('I80','deep vein thrombosis',0), # MAGIC ('I81','portal vein thrombosis',0), # MAGIC ('I820','other deep vein thrombosis',0), # MAGIC ('I822','other deep vein thrombosis',0), # MAGIC ('I823','other deep vein thrombosis',0), # MAGIC ('I828','other deep vein thrombosis',0), # MAGIC ('I829','other deep vein thrombosis',0), # MAGIC ('O223','thrombosis during pregnancy and puerperium',1), # MAGIC ('O871','thrombosis during pregnancy and puerperium',1), # MAGIC ('O879','thrombosis during pregnancy and puerperium',1), # MAGIC ('O882','thrombosis during pregnancy and puerperium',1), # MAGIC ('O225','cerebral venous thrombosis',1), # MAGIC ('O873','cerebral venous thrombosis',1), # MAGIC ('G08','cerebral venous thrombosis',0), # MAGIC ('I676','cerebral venous thrombosis',0), # MAGIC ('I636','cerebral venous thrombosis',0), # MAGIC ('D693','thrombocytopenia',0), # MAGIC ('D694','thrombocytopenia',0), # MAGIC ('D695','thrombocytopenia',0), # MAGIC ('D696','thrombocytopenia',0), # MAGIC ('D65','disseminated intravascular coagulation',0), # MAGIC ('M311','thrombotic thrombocytopenic purpura',0), # MAGIC ('K559','mesenteric thrombus',0), # MAGIC ('K550','mesenteric thrombus',0), # MAGIC ('I61','intracerebral haemorrhage',0), # MAGIC ('G951','spinal stroke',0) # MAGIC AS tab(CODE, EVENT, WOMEN_ONLY) # COMMAND ---------- # MAGIC %md ## Restrict skinny table # COMMAND ---------- # MAGIC %sql # MAGIC -- Create a reduced skinny table with just sex, date_of_birth and date_of_death # MAGIC CREATE OR REPLACE GLOBAL TEMP VIEW skinny_distinct AS # MAGIC SELECT DISTINCT NHS_NUMBER_DEID, # MAGIC SEX, # MAGIC DATE_OF_BIRTH, # MAGIC DATE_OF_DEATH # MAGIC FROM dars_nic_391419_j3w9t_collab.curr302_patient_skinny_record # MAGIC WHERE NHS_NUMBER_DEID IS NOT NULL # MAGIC AND SEX IS NOT NULL # MAGIC AND DATE_OF_BIRTH IS NOT NULL # COMMAND ---------- # MAGIC %md ## Extract all events # COMMAND ---------- # MAGIC %sql # MAGIC -- Extract all records that contain a relevant event # MAGIC CREATE OR REPLACE GLOBAL TEMPORARY VIEW all_events AS # MAGIC --- from HES APC (4 digit codes) # MAGIC SELECT DISTINCT PERSON_ID_DEID, # MAGIC YEAR(ADMIDATE) AS YEAR, # MAGIC ADMIDATE, # MAGIC DIAG_4_01 AS CODE, # MAGIC "HES_APC" AS SOURCE # MAGIC FROM dars_nic_391419_j3w9t_collab.ccu002_vac_hes_apc_all_years # MAGIC WHERE PERSON_ID_DEID IS NOT NULL # MAGIC AND ADMIDATE >= '2018-01-01' # MAGIC AND ADMIDATE <= '2020-12-31' # MAGIC AND DIAG_4_01 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4) # MAGIC --- from HES APC (3 digit codes) # MAGIC UNION ALL # MAGIC SELECT DISTINCT PERSON_ID_DEID, # MAGIC YEAR(ADMIDATE) AS YEAR, # MAGIC ADMIDATE, # MAGIC DIAG_3_01 AS CODE, # MAGIC "HES_APC" AS SOURCE # MAGIC FROM dars_nic_391419_j3w9t_collab.ccu002_vac_hes_apc_all_years # MAGIC WHERE PERSON_ID_DEID IS NOT NULL # MAGIC AND ADMIDATE >= '2018-01-01' # MAGIC AND ADMIDATE <= '2020-12-31' # MAGIC AND DIAG_3_01 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3) # MAGIC --- from DEATHS (4 digit codes) # MAGIC UNION ALL # MAGIC SELECT DISTINCT DEC_CONF_NHS_NUMBER_CLEAN_DEID AS PERSON_ID_DEID, # MAGIC left(REG_DATE_OF_DEATH,4) AS YEAR, # MAGIC to_date(REG_DATE_OF_DEATH, 'yyyyMMdd') AS ADMIDATE, # MAGIC S_UNDERLYING_COD_ICD10 AS CODE, # MAGIC "DEATHS" AS SOURCE # MAGIC FROM dars_nic_391419_j3w9t_collab.ccu002_vac_deaths_dars_nic_391419_j3w9t # MAGIC WHERE DEC_CONF_NHS_NUMBER_CLEAN_DEID IS NOT NULL # MAGIC AND left(REG_DATE_OF_DEATH,4) >= 2018 # MAGIC AND left(REG_DATE_OF_DEATH,4) <= 2020 # MAGIC AND S_UNDERLYING_COD_ICD10 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4) # MAGIC --- from DEATHS (3 digit codes) # MAGIC UNION ALL # MAGIC SELECT DISTINCT DEC_CONF_NHS_NUMBER_CLEAN_DEID AS PERSON_ID_DEID, # MAGIC left(REG_DATE_OF_DEATH,4) AS YEAR, # MAGIC to_date(REG_DATE_OF_DEATH, 'yyyyMMdd') AS ADMIDATE, # MAGIC left(S_UNDERLYING_COD_ICD10,3) AS CODE, # MAGIC "DEATHS" AS SOURCE # MAGIC FROM dars_nic_391419_j3w9t_collab.ccu002_vac_deaths_dars_nic_391419_j3w9t # MAGIC WHERE DEC_CONF_NHS_NUMBER_CLEAN_DEID IS NOT NULL # MAGIC AND left(REG_DATE_OF_DEATH,4) >= 2018 # MAGIC AND left(REG_DATE_OF_DEATH,4) <= 2020 # MAGIC AND left(S_UNDERLYING_COD_ICD10,3) IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3) # COMMAND ---------- # MAGIC %sql # MAGIC -- Add event names to codes # MAGIC CREATE OR REPLACE GLOBAL TEMP VIEW all_events_annotated AS # MAGIC SELECT x.*, # MAGIC y.EVENT, # MAGIC y.WOMEN_ONLY # MAGIC FROM global_temp.all_events AS x # MAGIC LEFT JOIN global_temp.event_codes AS y ON x.CODE = y.CODE # COMMAND ---------- # MAGIC %md ## Add skinny table information to all events # COMMAND ---------- # MAGIC %sql # MAGIC -- Add skinny table information to events # MAGIC CREATE OR REPLACE GLOBAL TEMP VIEW all_events_annotated_skinny AS # MAGIC SELECT PERSON_ID_DEID, # MAGIC YEAR, # MAGIC ADMIDATE, # MAGIC CODE, # MAGIC SOURCE, # MAGIC EVENT, # MAGIC ind_death28days, # MAGIC SEX, # MAGIC DATE_OF_BIRTH, # MAGIC DATE_OF_DEATH # MAGIC FROM(SELECT x.*, # MAGIC y.SEX, # MAGIC y.DATE_OF_BIRTH, # MAGIC y.DATE_OF_DEATH, # MAGIC CASE WHEN (DATEDIFF(y.DATE_OF_DEATH,x.ADMIDATE)<29) THEN 1 ELSE 0 END AS ind_death28days # MAGIC FROM global_temp.all_events_annotated AS x # MAGIC LEFT JOIN global_temp.skinny_distinct AS y on x.PERSON_ID_DEID = y.NHS_NUMBER_DEID) # MAGIC WHERE ((WOMEN_ONLY=1 AND SEX=2) OR (WOMEN_ONLY=0)) # MAGIC AND SEX IS NOT NULL # MAGIC AND DATE_OF_BIRTH IS NOT NULL # COMMAND ---------- # MAGIC %md ## Extract thrombocytopenia events # COMMAND ---------- # MAGIC %sql # MAGIC -- Create table containing unique non-primary thrombocytopenia events from HES APC # MAGIC CREATE OR REPLACE GLOBAL TEMPORARY VIEW thrombocytopenia AS # MAGIC SELECT DISTINCT PERSON_ID_DEID, # MAGIC ADMIDATE, # MAGIC "HES_APC" AS SOURCE, # MAGIC 1 as thrombocytopenia # MAGIC FROM (SELECT * # MAGIC FROM dars_nic_391419_j3w9t_collab.ccu002_vac_hes_apc_all_years # MAGIC WHERE ADMIDATE >= '2018-01-01' # MAGIC AND ADMIDATE <= '2020-12-31' # MAGIC AND ((DIAG_4_01 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_4_02 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_4_03 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_4_04 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_4_05 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_4_06 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_4_07 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_4_08 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_4_09 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_4_10 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_4_11 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_4_12 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_4_13 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_4_14 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_4_15 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_4_16 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_4_17 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_4_18 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_4_19 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_4_20 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia'))) # MAGIC UNION ALL # MAGIC SELECT * # MAGIC FROM dars_nic_391419_j3w9t_collab.ccu002_vac_hes_apc_all_years # MAGIC WHERE ADMIDATE >= '2018-01-01' # MAGIC AND ADMIDATE <= '2020-12-31' # MAGIC AND ((DIAG_3_01 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_3_02 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_3_03 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_3_04 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_3_05 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_3_06 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_3_07 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_3_08 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_3_09 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_3_10 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_3_11 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_3_12 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_3_13 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_3_14 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_3_15 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_3_16 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_3_17 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_3_18 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_3_19 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia')) # MAGIC OR (DIAG_3_20 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia')))) # MAGIC WHERE PERSON_ID_DEID IS NOT NULL # MAGIC AND ADMIDATE IS NOT NULL # COMMAND ---------- # MAGIC %md ## Add thrombocytopenia flag # COMMAND ---------- # MAGIC %sql # MAGIC -- Using the skinny table as master: inner join all events, annotate events and define indicators # MAGIC CREATE OR REPLACE GLOBAL TEMP VIEW all_events_annotated_skinny_thrombocytopenia AS # MAGIC SELECT x.*, # MAGIC CASE WHEN (y.thrombocytopenia=1 AND x.EVENT!='thrombocytopenia' AND x.SOURCE='HES_APC') THEN 1 ELSE 0 END AS ind_thrombocytopenia # MAGIC FROM global_temp.all_events_annotated_skinny AS x # MAGIC LEFT JOIN global_temp.thrombocytopenia AS y on x.PERSON_ID_DEID = y.PERSON_ID_DEID AND x.ADMIDATE = y.ADMIDATE AND x.SOURCE = y.SOURCE # COMMAND ---------- # MAGIC %md ## Determine source record # COMMAND ---------- # MAGIC %sql # MAGIC -- Determine for each year which patients have events in HES_APC only, DEATHS only, or both # MAGIC CREATE OR REPLACE GLOBAL TEMP VIEW source_record AS # MAGIC SELECT PERSON_ID_DEID, # MAGIC YEAR, # MAGIC EVENT, # MAGIC CASE WHEN SUM(HES_APC)>0 AND SUM(DEATHS)>0 THEN 'HES_APC + DEATHS' # MAGIC WHEN SUM(HES_APC)>0 AND SUM(DEATHS)=0 THEN 'HES_APC only' # MAGIC WHEN SUM(HES_APC)=0 AND SUM(DEATHS)>0 THEN 'DEATHS only' END RECORD # MAGIC FROM (SELECT PERSON_ID_DEID, # MAGIC YEAR, # MAGIC SOURCE, # MAGIC EVENT, # MAGIC CASE WHEN SOURCE="HES_APC" THEN 1 ELSE 0 END AS HES_APC, # MAGIC CASE WHEN SOURCE="DEATHS" THEN 1 ELSE 0 END AS DEATHS # MAGIC FROM global_temp.all_events_annotated_skinny_thrombocytopenia # MAGIC WHERE PERSON_ID_DEID IS NOT null) # MAGIC GROUP BY PERSON_ID_DEID, YEAR, EVENT # COMMAND ---------- # MAGIC %md ## Determine first events # COMMAND ---------- # MAGIC %sql # MAGIC -- Select first event from all events # MAGIC CREATE OR REPLACE GLOBAL TEMP VIEW first_events AS # MAGIC SELECT PERSON_ID_DEID, # MAGIC YEAR, # MAGIC EVENT, # MAGIC "event with thrombocytopenia" AS EVENT_WITH, # MAGIC min(ADMIDATE) as ADMIDATE, # MAGIC SEX, # MAGIC DATE_OF_BIRTH, # MAGIC DATE_OF_DEATH # MAGIC FROM global_temp.all_events_annotated_skinny_thrombocytopenia # MAGIC WHERE ind_thrombocytopenia=1 # MAGIC GROUP BY PERSON_ID_DEID, YEAR, EVENT, EVENT_WITH, SEX, DATE_OF_BIRTH, DATE_OF_DEATH # MAGIC UNION ALL # MAGIC SELECT PERSON_ID_DEID, # MAGIC YEAR, # MAGIC EVENT, # MAGIC "event with death in 28 days" AS EVENT_WITH, # MAGIC min(ADMIDATE) as ADMIDATE, # MAGIC SEX, # MAGIC DATE_OF_BIRTH, # MAGIC DATE_OF_DEATH # MAGIC FROM global_temp.all_events_annotated_skinny_thrombocytopenia # MAGIC WHERE ind_death28days=1 # MAGIC GROUP BY PERSON_ID_DEID, YEAR, EVENT, EVENT_WITH, SEX, DATE_OF_BIRTH, DATE_OF_DEATH # MAGIC UNION ALL # MAGIC SELECT PERSON_ID_DEID, # MAGIC YEAR, # MAGIC EVENT, # MAGIC "event only" AS EVENT_WITH, # MAGIC min(ADMIDATE) as ADMIDATE, # MAGIC SEX, # MAGIC DATE_OF_BIRTH, # MAGIC DATE_OF_DEATH # MAGIC FROM global_temp.all_events_annotated_skinny_thrombocytopenia # MAGIC GROUP BY PERSON_ID_DEID, YEAR, EVENT, EVENT_WITH, SEX, DATE_OF_BIRTH, DATE_OF_DEATH # COMMAND ---------- # MAGIC %md ## Add record information to first events # COMMAND ---------- # MAGIC %sql # MAGIC -- Add record information to first events table and determine death within 28 days # MAGIC CREATE OR REPLACE GLOBAL TEMP VIEW first_events_source AS # MAGIC SELECT DISTINCT x.*, # MAGIC z.RECORD # MAGIC FROM global_temp.first_events AS x # MAGIC INNER JOIN global_temp.source_record AS z ON z.PERSON_ID_DEID = x.PERSON_ID_DEID AND z.YEAR = x.YEAR AND z.EVENT = x.EVENT # COMMAND ---------- # MAGIC %md ## Add age bands to first events # COMMAND ---------- # MAGIC %sql # MAGIC -- Determine age and assign age bands # MAGIC CREATE OR REPLACE GLOBAL TEMP VIEW first_events_source_ageband AS # MAGIC SELECT *, # MAGIC CASE WHEN AGE>=0 AND AGE<19 THEN '0-18' # MAGIC WHEN AGE>=19 AND AGE<31 THEN '19-30' # MAGIC WHEN AGE>=31 AND AGE<40 THEN '31-39' # MAGIC WHEN AGE>=40 AND AGE<50 THEN '40-49' # MAGIC WHEN AGE>=50 AND AGE<60 THEN '50-59' # MAGIC WHEN AGE>=60 AND AGE<70 THEN '60-69' # MAGIC WHEN AGE>=70 AND AGE<80 THEN '70-79' # MAGIC WHEN AGE>=80 AND AGE<90 THEN '80-89' # MAGIC WHEN AGE>=90 AND AGE<116 THEN '90+' # MAGIC WHEN AGE>=116 THEN null END AGE_BAND # MAGIC FROM (SELECT PERSON_ID_DEID, # MAGIC SEX, # MAGIC YEAR, # MAGIC RECORD, # MAGIC EVENT, # MAGIC EVENT_WITH, # MAGIC (DATEDIFF(ADMIDATE, DATE_OF_BIRTH)/365.25) AS AGE # MAGIC FROM global_temp.first_events_source) # COMMAND ---------- # MAGIC %md ## Count number of first events # COMMAND ---------- # MAGIC %sql # MAGIC -- Count number of patients in each sex/year/event/age_band/record combination # MAGIC CREATE OR REPLACE GLOBAL TEMP VIEW ccu002_vacc_event_counts AS # MAGIC SELECT YEAR, # MAGIC CASE WHEN SEX=1 THEN 'Men' # MAGIC WHEN SEX=2 THEN 'Women' END SEX, # MAGIC RECORD, # MAGIC EVENT, # MAGIC EVENT_WITH, # MAGIC AGE_BAND, # MAGIC COUNT(PERSON_ID_DEID) AS N # MAGIC FROM global_temp.first_events_source_ageband # MAGIC GROUP BY YEAR, SEX, RECORD, EVENT, EVENT_WITH, AGE_BAND # COMMAND ---------- # MAGIC %md ## Export table # COMMAND ---------- # MAGIC %sql # MAGIC -- Export cell # MAGIC SELECT * # MAGIC FROM global_temp.ccu002_vacc_event_counts # COMMAND ---------- # MAGIC %md ## Save table # COMMAND ---------- # Save table drop_table('ccu002_vacc_event_counts') create_table('ccu002_vacc_event_counts')
""" Q1 Program to find max from 5 numbers """ ''' #way1 max = 0 list = [100,20,15,500,5] for i in range (0,5): if max < list[i]: max =list[i] print('Max no out of list is',max) ''' #while list[0] == list[-1]: # list[-1] helps you get the last element of the list ''' #Way 2 max = 0 list = [100, 20, 15, 500, 5] i = 0 while i < len(list): if max < list[i]: max = list[i] i=i+1 print('Max no out of list is', max) ''' """ Q2write a code to find minimum number from 5 values """ """ list_min = [20, 45, 15, 10, 90, 200, 56, 5] length = len(list_min) minimum = list_min[1] for i in range(0, length): if minimum > list_min[i]: minimum = list_min[i] print(i,minimum) print("Min no in the list is",minimum) """ """ creating pattern no 4 """ """ for i in range(0, 6): print(" ") symbol = i % 2 print(symbol, end=" ") for j in range(0, i): if symbol == 1: symbol = 0 print(symbol, end=" ") else: symbol = 1 print(symbol, end=" ") """ """ Q5 pattern """ """ for i in range(0, 6): print(" ") symbol = 1 print(symbol, end=" ") for j in range(0, i): if symbol==1: symbol=0 print(symbol, end=" " ) else: symbol=1 print(symbol, end=" " ) """ """ Q6 pattern """ """ for i in range(0,5): print(" ") for j in range(1,6): print(j, end=" ") """ """ Q7 Pattern """ """ count = 1 for i in range(0, 5): print(" ") for j in range(0, 5): print("%02d" % count, end=" ") count += 1 """ """ Q8 Pattern """ for i in range(5,0,-1): symbol = i%2 print(" ") print(symbol, end=" ") for j in range(1, i): if symbol == 1: symbol = 0 print(symbol, end=" ") else: symbol = 1 print(symbol, end=" ")
# 200090310 sm.warp(200000141, 0) sm.dispose()
''' 1) Implement the Node class to create a binary search tree. The constructor should initialize values 'data', 'left', and 'right'. 2) Implement the 'insert' method for the Node class. Insert should accept an argument 'data', then create a new node at the appropriate location in the tree. 3) Implement the 'contains' method for the Node class. Contains should accept a 'data' argument and return the Node in the tree with the same value. ''' class Node: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right def insert(self, data): if data == self.data: raise NotImplemented elif data < self.data and self.left is None: self.left = Node(data) elif data > self.data and self.right is None: self.right = Node(data) elif data < self.data: self.left.insert(data) elif data > self.data: self.right.insert(data) else: raise Exception('Unexpected edge case') def contains(self, data): if data == self.data: return self elif data < self.data and self.left is not None: return self.left.contains(data) elif data > self.data and self.right is not None: return self.right.contains(data) return None
NO_SUCH_OPTION_ERROR_TEMPLATE = "Error: no such option: {}" NO_SUCH_COMMAND_ERROR_TEMPLATE = "Error: No such command \"{}\"" MISSING_COMMAND_ERROR_TEMPLATE = "Error: Missing command."
matriz2 = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] spar = scol = 0 for l in range(0, 3): for c in range(0, 3): matriz2[l][c] = int(input(f'Digite um valor para a posição {l,c}: ')) print('='*50) for l in range(0, 3): for c in range(0, 3): print(f'[{matriz2[l][c]:^5}]', end='') if matriz2[l][c] % 2 == 0: spar += matriz2[l][c] print() scol = matriz2[0][2] + matriz2[1][2] + matriz2[2][2] print(f'A soma dos valores pares é {spar}') print(f'A soma da terceira coluna é {scol}') print(f'O maior valor da segunda linha é {max(matriz2[1])}')
property_value_alias_age_long_to_short = { "Unassigned": "NA", "V10_0": "10.0", "V11_0": "11.0", "V12_0": "12.0", "V12_1": "12.1", "V13_0": "13.0", "V1_1": "1.1", "V2_0": "2.0", "V2_1": "2.1", "V3_0": "3.0", "V3_1": "3.1", "V3_2": "3.2", "V4_0": "4.0", "V4_1": "4.1", "V5_0": "5.0", "V5_1": "5.1", "V5_2": "5.2", "V6_0": "6.0", "V6_1": "6.1", "V6_2": "6.2", "V6_3": "6.3", "V7_0": "7.0", "V8_0": "8.0", "V9_0": "9.0", }
""" The BaseGem class is the framework for all gems and fusions. Base Gem holds all the stats of a gem or fusion in a dict, this dict is modified through helper funcitons, these functions also return the end value. Eventually we might keep ability functions here as well. We are still utilizing child classes. """ class BaseGem(): def __init__(self): # add weapon size, possible abilities self.__attributes = dict( serial=None, stone=None, era=None, health=36, size=1, movement_speed=8, flight_movement_speed=0, arms=2, caste_rank=None, action_slots=2, PP=31, SPR=0, homo=False, hetro=False, CPR=0, attacking=False, blocking=False, disarming=False, onePR=0, twoPR=0, threePR=0, certs=[] ) # # # ~~~~~~~~~~~~~~~HELPER CLASSES FOR ACCESSING AND MODIFYING STATS~~~~~~~~~~~~~~ def set_serial(self, new_serial=None): if new_serial is not None: self.__attributes['serial'] = new_serial return self.__attributes['serial'] def set_stone(self, new_stone=None): if new_stone is not None: self.__attributes['stone'] = new_stone return self.__attributes['stone'] def set_era(self, new_era=None): if new_era is not None: self.__attributes['era'] = new_era return self.__attributes['era'] def add_health(self, health_mod=None): if health_mod is not None: self.__attributes['health'] += health_mod return self.__attributes['health'] # size should probably always be powers of 2 # this also modifies movement_speed def set_size(self, new_size=None): if new_size is not None: self.__attributes['size'] = new_size self.__attributes['movemen_speed'] = new_size * 8 return self.__attributes['size'] def get_movement_speed(self): return self.__attributes['movement_speed'] def add_flight_movement_speed(self, f_movement_speed_mod=None): if f_movement_speed_mod is not None: self.__attributes['flight_movement_speed'] += f_movement_speed_mod return self.__attributes['flight_movement_speed'] def add_arms(self, arms_mod=None): if arms_mod is not None: self.__attributes['arms'] += arms_mod return self.__attributes['arms'] def add_caste_rank(self, caste_rank_mod=None): if caste_rank_mod is not None: self.__attributes['caste_rank'] += caste_rank_mod return self.__attributes['caste_rank'] def add_action_slots(self, action_slots_mod=None): if action_slots_mod is not None: self.__attributes['action_slots'] += action_slots_mod return self.__attributes['action_slots'] def add_PP(self, PP_mod=None): if PP_mod is not None: self.__attributes['PP'] += PP_mod return self.__attributes['PP'] def add_SPR(self, SPR_mod=None): if SPR_mod is not None: self.__attributes['SPR'] += SPR_mod return self.__attributes['SPR'] def set_homo(self, new_homo=None): if new_homo is not None: self.__attributes['homo'] = new_homo return self.__attributes['homo'] def set_hetro(self, new_hetro=None): if new_hetro is not None: self.__attributes['hetro'] = new_hetro return self.__attributes['hetro'] def add_CPR(self, CPR_mod=None): if CPR_mod is not None: self.__attributes['CPR'] += CPR_mod return self.__attributes['CPR'] def set_attacking(self, new_attacking=None): if new_attacking is not None: self.__attributes['attacking'] = new_attacking return self.__attributes['attacking'] def set_blocking(self, new_blocking=None): if new_blocking is not None: self.__attributes['blocking'] = new_blocking return self.__attributes['blocking'] def set_disarming(self, new_disarming=None): if new_disarming is not None: self.__attributes['disarming'] = new_disarming return self.__attributes['disarming'] def add_onePR(self, onePR_mod=None): if onePR_mod is not None: self.__attributes['onePR'] += onePR_mod return self.__attributes['onePR'] def add_twoPR(self, twoPR_mod=None): if twoPR_mod is not None: self.__attributes['twoPR'] += twoPR_mod return self.__attributes['twoPR'] def add_threePR(self, threePR_mod=None): if threePR_mod is not None: self.__attributes['threePR'] += threePR_mod return self.__attributes['threePR'] def add_cert(self, new_cert=None): if new_cert is not None: self.__attributes['certs'].append(new_cert) return self.__attributes['certs'] # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~END OF HELPER CLASSES~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # #
def fib(num): output = [1,1] before_previous_num = 1 previous_num = 1 for i in range(1,num+1): new_num = before_previous_num + previous_num output.append(new_num) before_previous_num = previous_num previous_num = new_num nth = output[num-1] return nth ''' Powers of 2 for some reason :X output = [] i = 0 last_num = 0 new_num = 1 while i < 10: last_num = new_num new_num = last_num+new_num output.append(new_num) i+=1 print(output) '''
class Score: def __init__(self): self.score = 0 def get_score_text(self): score_text = f"Score: {self.score}" return score_text def add_score(self, points): self.score += points
# -*- coding: utf-8 -*- """ Default Constants Used for the Australian Senate Election Audit. """ # The modes in which to run the senate election audit. SIMULATION_MODE = 'simulation' QUICK_MODE = 'quick' REAL_MODE = 'real' # The Australian states with senate election data available to audit. STATES = [ 'ACT', 'NSW', 'NT', 'QLD', 'SA', 'TAS', 'VIC', 'WA', ] # The default number of cast ballots in a simulated senate election audit. DEFAULT_SIMULATED_SENATE_ELECTION_NUM_BALLOTS = 1000000 # The default number of candidates in a simulated senate election audit. DEFAULT_SIMULATED_SENATE_ELECTION_NUM_CANDIDATES = 100 # The default upper bound on the fraction of trials a candidate must lose in a round of an audit to be considered # unpopular. DEFAULT_UNPOPULAR_FREQUENCY_THRESHOLD = 0.03 # The default number of ballots to add to a growing sample at the start of an audit stage. DEFAULT_SAMPLE_INCREMENT_SIZE = 1000 # The default random number seed value. DEFAULT_SEED_VALUE = 1 # The number of header lines in a formal preferences CSV file. FORMAL_PREFERENCES_CSV_NUM_HEADER_LINES = 2 # The keys of the audit configuration JSON. AUDIT_STAGE_KEY = 'audit_stage' SAMPLE_SIZE_KEY = 'sample_size' # The default file name for the election configuration file. CONFIG_FILE_PATH = 'aec_fed2016.json' # The names of files created by the aus-senate-audit software. AUDIT_DIR_NAME = 'audit_{}_seed_{}' ROUND_DIR_NAME = 'stages' AUDIT_INFO_FILE_NAME = 'info.json' AUDIT_ROUND_FILE_NAME = '{}/stage_{}.csv' AGGREGATE_BALLOTS_FILE_NAME = 'aggregate.csv' SELECTED_BALLOTS_FILE_NAME = 'selected_ballots.csv' RESULT_OUTPUT = '{}_result.txt' # The column headers of a formal preferences file (first header line). COLUMN_HEADERS = [ 'ElectorateNm', 'VoteCollectionPointNm', 'VoteCollectionPointId', 'BatchNo', 'PaperNo', 'Preferences', ] # The column header delimiters of a formal preferences file (second header line). COLUMN_HEADER_DELIMS = [ '------------', '---------------------', '---------------------', '-------', '-------', '-----------', ] # The column headers used to track preference matches between electronic ballots and paper ballot interpretations. MATCH_HEADERS = [ 'Match', 'PreferencesAfterAudit', ]
data = ( 'k', # 0x00 'kh', # 0x01 'g', # 0x02 'gh', # 0x03 'ng', # 0x04 'c', # 0x05 'ch', # 0x06 'j', # 0x07 'jh', # 0x08 'ny', # 0x09 'nny', # 0x0a 'tt', # 0x0b 'tth', # 0x0c 'dd', # 0x0d 'ddh', # 0x0e 'nn', # 0x0f 'tt', # 0x10 'th', # 0x11 'd', # 0x12 'dh', # 0x13 'n', # 0x14 'p', # 0x15 'ph', # 0x16 'b', # 0x17 'bh', # 0x18 'm', # 0x19 'y', # 0x1a 'r', # 0x1b 'l', # 0x1c 'w', # 0x1d 's', # 0x1e 'h', # 0x1f 'll', # 0x20 'a', # 0x21 '[?]', # 0x22 'i', # 0x23 'ii', # 0x24 'u', # 0x25 'uu', # 0x26 'e', # 0x27 '[?]', # 0x28 'o', # 0x29 'au', # 0x2a '[?]', # 0x2b 'aa', # 0x2c 'i', # 0x2d 'ii', # 0x2e 'u', # 0x2f 'uu', # 0x30 'e', # 0x31 'ai', # 0x32 '[?]', # 0x33 '[?]', # 0x34 '[?]', # 0x35 'N', # 0x36 '\'', # 0x37 ':', # 0x38 '', # 0x39 '[?]', # 0x3a '[?]', # 0x3b '[?]', # 0x3c '[?]', # 0x3d '[?]', # 0x3e '[?]', # 0x3f '0', # 0x40 '1', # 0x41 '2', # 0x42 '3', # 0x43 '4', # 0x44 '5', # 0x45 '6', # 0x46 '7', # 0x47 '8', # 0x48 '9', # 0x49 ' / ', # 0x4a ' // ', # 0x4b 'n*', # 0x4c 'r*', # 0x4d 'l*', # 0x4e 'e*', # 0x4f 'sh', # 0x50 'ss', # 0x51 'R', # 0x52 'RR', # 0x53 'L', # 0x54 'LL', # 0x55 'R', # 0x56 'RR', # 0x57 'L', # 0x58 'LL', # 0x59 '[?]', # 0x5a '[?]', # 0x5b '[?]', # 0x5c '[?]', # 0x5d '[?]', # 0x5e '[?]', # 0x5f '[?]', # 0x60 '[?]', # 0x61 '[?]', # 0x62 '[?]', # 0x63 '[?]', # 0x64 '[?]', # 0x65 '[?]', # 0x66 '[?]', # 0x67 '[?]', # 0x68 '[?]', # 0x69 '[?]', # 0x6a '[?]', # 0x6b '[?]', # 0x6c '[?]', # 0x6d '[?]', # 0x6e '[?]', # 0x6f '[?]', # 0x70 '[?]', # 0x71 '[?]', # 0x72 '[?]', # 0x73 '[?]', # 0x74 '[?]', # 0x75 '[?]', # 0x76 '[?]', # 0x77 '[?]', # 0x78 '[?]', # 0x79 '[?]', # 0x7a '[?]', # 0x7b '[?]', # 0x7c '[?]', # 0x7d '[?]', # 0x7e '[?]', # 0x7f '[?]', # 0x80 '[?]', # 0x81 '[?]', # 0x82 '[?]', # 0x83 '[?]', # 0x84 '[?]', # 0x85 '[?]', # 0x86 '[?]', # 0x87 '[?]', # 0x88 '[?]', # 0x89 '[?]', # 0x8a '[?]', # 0x8b '[?]', # 0x8c '[?]', # 0x8d '[?]', # 0x8e '[?]', # 0x8f '[?]', # 0x90 '[?]', # 0x91 '[?]', # 0x92 '[?]', # 0x93 '[?]', # 0x94 '[?]', # 0x95 '[?]', # 0x96 '[?]', # 0x97 '[?]', # 0x98 '[?]', # 0x99 '[?]', # 0x9a '[?]', # 0x9b '[?]', # 0x9c '[?]', # 0x9d '[?]', # 0x9e '[?]', # 0x9f 'A', # 0xa0 'B', # 0xa1 'G', # 0xa2 'D', # 0xa3 'E', # 0xa4 'V', # 0xa5 'Z', # 0xa6 'T`', # 0xa7 'I', # 0xa8 'K', # 0xa9 'L', # 0xaa 'M', # 0xab 'N', # 0xac 'O', # 0xad 'P', # 0xae 'Zh', # 0xaf 'R', # 0xb0 'S', # 0xb1 'T', # 0xb2 'U', # 0xb3 'P`', # 0xb4 'K`', # 0xb5 'G\'', # 0xb6 'Q', # 0xb7 'Sh', # 0xb8 'Ch`', # 0xb9 'C`', # 0xba 'Z\'', # 0xbb 'C', # 0xbc 'Ch', # 0xbd 'X', # 0xbe 'J', # 0xbf 'H', # 0xc0 'E', # 0xc1 'Y', # 0xc2 'W', # 0xc3 'Xh', # 0xc4 'OE', # 0xc5 '[?]', # 0xc6 '[?]', # 0xc7 '[?]', # 0xc8 '[?]', # 0xc9 '[?]', # 0xca '[?]', # 0xcb '[?]', # 0xcc '[?]', # 0xcd '[?]', # 0xce '[?]', # 0xcf 'a', # 0xd0 'b', # 0xd1 'g', # 0xd2 'd', # 0xd3 'e', # 0xd4 'v', # 0xd5 'z', # 0xd6 't`', # 0xd7 'i', # 0xd8 'k', # 0xd9 'l', # 0xda 'm', # 0xdb 'n', # 0xdc 'o', # 0xdd 'p', # 0xde 'zh', # 0xdf 'r', # 0xe0 's', # 0xe1 't', # 0xe2 'u', # 0xe3 'p`', # 0xe4 'k`', # 0xe5 'g\'', # 0xe6 'q', # 0xe7 'sh', # 0xe8 'ch`', # 0xe9 'c`', # 0xea 'z\'', # 0xeb 'c', # 0xec 'ch', # 0xed 'x', # 0xee 'j', # 0xef 'h', # 0xf0 'e', # 0xf1 'y', # 0xf2 'w', # 0xf3 'xh', # 0xf4 'oe', # 0xf5 'f', # 0xf6 '[?]', # 0xf7 '[?]', # 0xf8 '[?]', # 0xf9 '[?]', # 0xfa ' // ', # 0xfb '[?]', # 0xfc '[?]', # 0xfd '[?]', # 0xfe )
def user_url(): """this fuction is used to take the username as input, then generate the profile url Returns: [string] -- [profile url] """ username = input("enter the username - ") url = "https://www.instagram.com/{}/".format(username) return url
class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: def helper(ans, res, nums): if not nums: ans.append(res[:]) else: element = nums.pop() helper(ans, res, nums) res.append(element) helper(ans, res, nums) res.pop() nums.append(element) return ans return helper([], [], nums)
#!/usr/bin/env python3 # imports go here # # Free Coding session for 2015-03-31 # Written by Matt Warren # def foo(): print("completely out of ideas") if __name__ == "__main__": foo()
"""Advent of Code Day 13 - Packet Scanners""" def severity(layers, delay): """Calculate cost of getting caught when traversing a Firewall.""" layers_list = layers.strip().split('\n') severity = 0 for layer in layers_list: layer_parts = (str(layer).split(':')) layer_num = int(layer_parts[0]) layer_range = int(str(layer_parts[1]).strip()) if (layer_num + delay) % ((layer_range - 1) * 2) == 0: severity += layer_num * layer_range if layer_num == 0: severity += 1 # Prevents being caught on 0 not counting if delay == 0: print('Bypassing with no delay results in overall severity of ' + str(severity - 1)) if severity == 0: return delay with open('inputs/day_13.txt') as f: firewall = f.read() delay = 0 while severity(firewall, delay) is None: delay += 1 # Answer One print('The smallest delay that would bypass the firewall is:', delay, 'picoseconds.')
# see https://www.codewars.com/kata/5ba38ba180824a86850000f7/solutions/python def solve(arr): i = 0 while i < len(arr): if arr.count(arr[i]) > 1: arr.pop(i) else: i+= 1 return arr print(solve([3,4,4,3,6,3]) == [4,6,3]) print(solve([1,2,1,2,1,2,3]) == [1,2,3]) print(solve([1,2,3,4]) == [1,2,3,4]) print(solve([1,1,4,5,1,2,1]) == [4,5,2,1])
"""Given two numbers and an arithmetic operator (the name of it, as a string), return the result of the two numbers having that operator used on them. a and b will both be positive integers, and a will always be the first number in the operation, and b always the second. The four operators are "add", "subtract", "divide", "multiply". A few examples: arithmetic(5, 2, "add") => returns 7 arithmetic(5, 2, "subtract") => returns 3 arithmetic(5, 2, "multiply") => returns 10 arithmetic(5, 2, "divide") => returns 2.5 ArithmeticFunction.arithmetic(5, 2, "add") => returns 7 ArithmeticFunction.arithmetic(5, 2, "subtract") => returns 3 ArithmeticFunction.arithmetic(5, 2, "multiply") => returns 10 ArithmeticFunction.arithmetic(5, 2, "divide") => returns 2 Try to do it without using if statements!""" def add( num1,num2): return num1+num2 def subtract( num1,num2): return num1-num2 def multiply ( num1,num2): return num1 * num2 def divide (num1,num2): return num1 / num2 def arithmetic( num1,num2,function): if ( function == "add"): return add(num1,num2) if ( function == "subtract"): return subtract(num1,num2) if ( function == "multiply"): return multiply(num1,num2) if ( function == "divide"): return divide(num1,num2) #RW 28/05/2021 """def arithmetic(a, b, operator): return { 'add': a + b, 'subtract': a - b, 'multiply': a * b, 'divide': a / b, }[operator] #Gives error Ex: on 1,0,'add' #But very clever """
class Solution(object): def fractionToDecimal(self, numerator, denominator): """ :type numerator: int :type denominator: int :rtype: str """ ans = "-" if numerator * denominator < 0 else "" numerator = abs(numerator) denominator = abs(denominator) ans += str(numerator / denominator) if numerator % denominator: ans += "." numerator = (numerator % denominator) * 10 if numerator == 0: return ans d = {} res = [] while True: r = numerator % denominator v = numerator / denominator if numerator in d: idx = d[numerator] return ans + "".join(res[:idx]) + "(" + "".join(res[idx:]) + ")" res.append(str(v)) if v == 0: d[numerator] = len(res) - 1 numerator *= 10 continue d[numerator] = len(res) - 1 numerator = r * 10 if r == 0: return ans + "".join(res) return ans + "".join(res)
# __init__.py/Open GoPro, Version 2.0 (C) Copyright 2021 GoPro, Inc. (http://gopro.com/OpenGoPro). # This copyright was auto-generated on Wed, Sep 1, 2021 5:05:46 PM """Demos to show how to use Open GoPro package"""
FPS = 60 SCREEN_WIDTH = 1300 SCREEN_HEIGHT = 800 ground_height = SCREEN_HEIGHT // 6 ground_rect = ((0, SCREEN_HEIGHT - ground_height), (SCREEN_WIDTH, SCREEN_HEIGHT)) menu_font_size = min(SCREEN_WIDTH, SCREEN_HEIGHT) // 18 num_of_evil_clouds = 15 field_for_movement_height = 3 * SCREEN_HEIGHT // 5 radius_of_evil_clouds = min(SCREEN_WIDTH, SCREEN_HEIGHT) // 30 clouds_velocity = min(SCREEN_WIDTH, SCREEN_HEIGHT) // 240 clouds_lifetime = 60 tank_speed = SCREEN_WIDTH // 200 tank_width = SCREEN_WIDTH // 5 tank_height = SCREEN_HEIGHT // 14 tank_wheel_radius = tank_width // 7 tank_turret_radius = tank_height // 2 tank_turret_speed = 1 tank_muzzle_length = tank_width // 2 tank_x0 = SCREEN_WIDTH // 3 tank_y0 = SCREEN_HEIGHT - 5 * ground_height // 4 bombs_radius = min(SCREEN_WIDTH, SCREEN_HEIGHT) // 50 bombs_center_radius = bombs_radius // 3 bombs_speed = clouds_velocity bombs_time = 3 * clouds_lifetime number_of_bombs = 3 * num_of_evil_clouds time_velocity_factor = min(SCREEN_WIDTH, SCREEN_HEIGHT) // 500 rocket_length = tank_muzzle_length // 3 rocket_speed = min(SCREEN_WIDTH, SCREEN_HEIGHT) // 60 rocket_radius = 3 * bombs_center_radius // 2 num_of_rockets = 4 creature_hp = 100 g = min(SCREEN_WIDTH, SCREEN_HEIGHT) // 600 delta_r = 10 delta_alpha = 2 bomb_damage = creature_hp // 4 tank_bomb_damage = creature_hp // 2 rocket_damage = creature_hp # ======================================================================== file_names = ['start_menu_text.txt', 'end_menu_text.txt'] hp_string = "Your HP is " rockets = "Rockets " bombs = "Bombs " win_string = "Вы победили!!!" loose_string = "Вы проиграли..." # ======================================================================== if __name__ == "__main__": print("It's a config file")
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: for i in reversed(range(len(num))): k, num[i] = divmod(num[i] + k, 10) while k > 0: num = [k % 10] + num k //= 10 return num
""" Aula 008 Desafio 17 Faça um programa que leia o comprimento do cateto oposto e do cateto adjacente de um triângulo retângulo, calcule e mostre o comprimento da hipotenusa. """
# Complete the printLinkedList function below. # # For your reference: # # SinglyLinkedListNode: # int data # SinglyLinkedListNode next # # def printLinkedList(head): if(head is not None): print(head.data) printLinkedList(head.next)
class BalanceUnderLimitError(Exception): pass class BalanceOverLimitError(Exception): pass
""" Global settings and constants """ TEMP_IMAGE_FILE="/home/pi/tmp/capture.jpg" CAPTURE_SLEEP=0.5 MUSIC_ROOT="/home/pi/Music" DEFAULT_VOLUME=40
class Person: def __init__(self, name, age): self.name = name self.age = age class Child(Person): def __init__(self, name, age): super().__init__(name, age) # """"Test Code""" # child = Child('Boris', 18) # print(child.__dict__)
nbPaquets = int(input()) poidsPaquet = int(input()) poidsTotal = nbPaquets * poidsPaquet if (poidsTotal > 105): print("Surcharge !")
def test_root_api(api_client): status_code, body, _ = api_client.get('/') assert 200 == status_code assert 'API' in body assert {{cookiecutter.project_short_description}} == body['API']
# 序列是一块用于存放多个值的连续内存空间,并按照一定顺序排列,每个元素都有一个索引 # python中常见的序列:列表、元组、集合、字典和字符串 # 索引,python中的序列索引从0开始(从左到右),从-1开始(从右到左) words = ["AA", "BB", "CC", "DD", "EE"] print(words[2]) print(words[-1]) # 切片,访问序列中一定范围的元素,可以通过切片生成新的序列 # 语法格式:sname[start:end:step],其中start如果不指定默认为0,end若不指定默认为序列的长度,step若不指定默认为1 print(words[1:3]) print(words[0:5:2]) # 复制整个列表时,可以同时省略start和end copy_words = words[:] print(copy_words == words) print(copy_words) # 序列相加,python中支持两种类型相同的序列相加(使用+号),不会去重元素。 # 相加的两个序列必须是同种类型(同为列表,元组、集合等),序列中的元素类型可以不相同 prices = [10.90, 21.86, 15.56] names = ["python入门", "Java入门"] print(prices + names) # print(prices + "prices"),因是不同类型,会导致运行异常TypeError: can only concatenate list (not "str") to list # 序列乘法,使用数字n乘以序列,会生成新的序列,新序列中重复n次原来的序列 print(prices * 2) empty_list = [None] * 5 print(empty_list) # 检查元素是否是序列的成员,语法结构 value in sequence print(10.90 in prices) print(18.88 in prices) print(18.88 not in prices) # 检查序列的长度(使用len()函数)、最大值(使用max()函数)和最小值(使用min()函数) print(len(prices)) print(max(prices)) print(min(names)) # 序列的常用内置函数 # list() 将序列转为列表 price_list = list(prices) print(type(prices), type(price_list)) # str() 将序列转为字符串 price_str = str(prices) print(price_str) print(type(prices), type(price_str)) # sum() 计算元素和 print(sum(prices)) # sorted() 对序列进行排序 print(sorted(prices)) # reversed() 反向序列中的元素 for price in reversed(prices): print(price, end=" ") print() # enumerate() 将序列组合为组合为索引序列,常在for循环中用 for price in enumerate(prices): print(price, end=" ")
PATH_MESHES = '../output' PATH_DATASET = '../input' PATH_UNIT_MESHES = '../unit_meshes' STR_LEGO_2_4 = 'lego_2_4.stl' STR_CUBE = 'cube.stl'
general = "ffmpeg -f gdigrab -framerate 20 -offset_x" # Encoding method: # amd: hevc_amf # nvidia: hevc_nvenc encoder = "hevc_nvenc"