content
stringlengths
7
1.05M
class Solution: def combinationSum(self, candidates, target): # candidates.sort() # dp = [[[]]] + [[] for i in range(target)] # for i in range(1, target + 1): # for number in candidates: # if number > i: # break # for L in dp[i - number]: # if not L or number >= L[-1]: # dp[i] = dp[i] + [L + [number]] # return dp[target] res = [] candidates.sort() def dfs(remain, stack): if not remain: res.append(stack) return for item in candidates: if item > remain: break elif not stack or item >= stack[-1]: dfs(remain - item, stack + [item]) dfs(target, []) return res
# OpenWeatherMap API Key api_key_owm= "b80fd2ed7964ad60c921362b393b0613" # Google API Key api_key_g = "YOUR KEY HERE!"
n = int(input("입력 횟수: ")) for i in range(n): temp = int(input("값: ")) if temp > n: n = temp print("최댓값:", n)
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def plusOne(self, head): """ :type head: ListNode :rtype: ListNode """ def reverse(cur): pre = None while cur: tmp = cur.next cur.next = pre pre = cur cur = tmp return pre p = head = reverse(head) carry = 1 pre = None while p: val = (p.val + carry) % 10 carry = 1 if val < p.val else 0 p.val = val pre = p p = p.next if carry == 1: pre.next = ListNode(1) return reverse(head)
# demonstrate template string functions def main(): # Usual string formatting with format() str1 = "You're watching {0} by {1}".format("Advanced Python", "Joe Marini") print(str1) # TODO: create a template with placeholders # TODO: use the substitute method with keyword arguments # TODO: use the substitute method with a dictionary if __name__ == "__main__": main()
def test_devices(spotify_user_auth): assert spotify_user_auth.devices() def test_recently_played_tracks(spotify_user_auth): assert spotify_user_auth.recently_played_tracks() def test_play_album(spotify_user_auth, reise_reise_album_id): assert spotify_user_auth.play(album_id=reise_reise_album_id) is not None def test_play_single_track(spotify_user_auth, them_bones_track_id): assert spotify_user_auth.play(track_ids=them_bones_track_id) is not None assert spotify_user_auth.pause() is not None def test_play_multiple_tracks( spotify_user_auth, them_bones_track_id, cover_me_track_id ): assert ( spotify_user_auth.play(track_ids=[them_bones_track_id, cover_me_track_id]) is not None ) assert spotify_user_auth.pause() is not None def test_play_artist(spotify_user_auth, depeche_mode_artist_id): assert spotify_user_auth.play(artist_id=depeche_mode_artist_id) is not None assert spotify_user_auth.pause() is not None def test_play_with_no_args(spotify_user_auth): assert spotify_user_auth.play() is not None def test_currently_playing(spotify_user_auth): assert spotify_user_auth.currently_playing() def test_currently_playing_info(spotify_user_auth): assert spotify_user_auth.currently_playing_info() def test_next(spotify_user_auth): assert spotify_user_auth.next() is not None def test_previous(spotify_user_auth): assert spotify_user_auth.previous() is not None def test_repeat(spotify_user_auth): assert spotify_user_auth.repeat() is not None def test_shuffle(spotify_user_auth): assert spotify_user_auth.shuffle() is not None def test_seek(spotify_user_auth): assert spotify_user_auth.seek(10000) is not None # 10 seconds def test_volume(spotify_user_auth): assert spotify_user_auth.volume(72) is not None assert spotify_user_auth.volume(32) is not None def test_pause(spotify_user_auth): assert spotify_user_auth.pause() is not None def test_queue(spotify_user_auth, them_bones_track_id): assert spotify_user_auth.queue(them_bones_track_id) is not None
# O(log n) def binary_search(items, item): bottom = 0 top = len(items) - 1 while bottom <= top: middle = int((bottom + top) / 2) guess = items[middle] if guess == item: return middle if guess > item: top = middle - 1 else: bottom = middle + 1 return None items = [1,29,30,40,57,72,100] print(binary_search(items, 30)) print(binary_search(items, 404))
class Solution: # One Liner (Accepted + Top Voted), O(n) time and space def getConcatenation(self, nums: List[int]) -> List[int]: return nums + nums # Extend (Sample), O(n) time and space def getConcatenation(self, nums: List[int]) -> List[int]: ans = nums ans.extend(nums) return ans
def challenge_to_string(scheme, params): s = scheme for name, value in params.items(): s += ' {}="{}"'.format(name, value.replace('\\', '\\\\').replace('"', '\\"')) return s class WWWAuthenticateMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): request.auth_challenges = [] response = self.get_response(request) for i, challenge in enumerate(request.auth_challenges): whatever = 'WWW-Authenticate' + str(i) response._headers[whatever] = ('WWW-Authenticate', challenge_to_string(*challenge)) return response
URL_HOST_FILES = [ # "https://adaway.org/hosts.txt", "http://winhelp2002.mvps.org/hosts.txt", "http://hosts-file.net/ad_servers.txt", "http://pgl.yoyo.org/adservers/serverlist.php?hostformat=hosts&showintro=0&mimetype=plaintext", "http://someonewhocares.org/hosts/hosts", ]
songs = ["Like a Rolling Stone", "Satisfaction", "Imagine", "What's Going On", "Respect", "Good Vibrations"] playcounts = [78, 29, 44, 21, 89, 5] plays = {key:value for key, value in zip(songs, playcounts)} print(plays) plays["Purple Haze"] = 1 plays["Respect"] = 94 library = {"The Best Songs": plays, "Sunday Feelings": {}} print(library)
#count the no. of same string and print for ex wwwwrrrig will be w4r3ig def countnsay(s): n = len(s) say = "" cur = "" count = 1 for i in range(n-1): curr = s[i] nxt = s[i+1] if curr == nxt: count +=1 elif(count>1): cur+=curr say+=(str(curr)+str(count)) count = 1 else: cur+=curr say+=str(curr) cur += curr say+=(str(s[n-1])+str(count)) print(cur) print(say) s = "wwwwaaadexxxxxx" countnsay(s)
# Index of practices ''' Part I - List 1) Create a empty list 2) Append to list 2.1) One bye One 2.2) By '*' 2.3) By extend() 2.4) By for 3) Joint 2 lists 4) Lenth a list 5) Pick out from list 5.1) Pick 1 ( By [index] ) 5.2) Pick by for 5.3) If exist ( By 'in') 6) Delete in list 6.1) Delete one 6.2) Empty a list ( By 'clear()') Part II - Operaters of List max() min() len() ------ list( seq ) --------- sort() index() copy() Part III - Tuple 1) Create a tuple 2) Joint 2 tuples 3) Lenth a tuple 4) Pick out from tuple 5) Delete a tuple Part IV - Operaters of List max() min() len() ------ tuple(seq) '''
""" 2309 : 일곱 난쟁이 URL : https://www.acmicpc.net/problem/2309 Input : 20 7 23 19 10 15 25 8 13 Output : 7 8 10 13 19 20 23 """ heights = [int(input()) for _ in range(9)] heights = sorted(heights) height_sum = sum(heights) found = False for i in range(9): for j in range(i + 1, 9): if (height_sum - heights[i] - heights[j]) == 100: heights[i] = 0 heights[j] = 0 found = True break if found: break heights = sorted(heights)[2:] for height in heights: print(height)
N = int(input()) M = [] for i in range(N): x, y = [int(x) for x in input().split()] M.append([x, y]) areatotal = 0 for i in range(N): if i != 0: for j in range(i, -1, -1): if M[i][0] > M[j][0]: menorx = M[j][0] if M[i][1] > M[j][1]: menory = M[j][1] for j in range(i, -1, -1): try: if menorx < M[j][0] < M[i][0]: menorx = M[j][0] except: if menory < M[j][1] < M[i][1]: menory = M[j][1] try: if menory < M[j][1] < M[i][1]: menory = M[j][1] except: if menorx < M[j][0] < M[i][0]: menorx = M[j][0] areamenor = 0 try: areamenor += menorx * M[i][1] except: sla = 0 try: areamenor += menory * M[i][0] except: sla = 0 areaquad = M[i][0] * M[i][1] - areamenor else: areaquad = M[i][0] * M[i][1] areatotal += areaquad print(areatotal)
"""Variables globales de la clase PyTikZ""" def init(): global ruta_raiz global ruta_imagen global carpetas_necesarias ruta_raiz = "" ruta_imagen = "" #"imagen" -> Todas las carpetas en "imagen", son las que se encuentra en "C:\Users\juanf\Pictures" (Window) o "sdcard/dcim" (Android). carpetas_necesarias = { "imagen":["Pytikz"] }
def distance(s1, s2): d = 0 l1 = list(s1) l2 = list(s2) for i in range(len(l1)): if l2.count(l1[i]) == 0: d += 1 continue l2_index = l2.index(l1[i], i) l2_distance = l2_index - i if l2_distance > 0: l2.pop(l2_distance) d += l2_distance return d if __name__ == '__main__': print(distance('biting', 'sitting')) # 2
""" """ class MyIterator: def __init__(self, c): self.c = c self.i = 0 def __next__(self): if self.i < len(self.c.mylist): self.i += 1 return self.c.mylist[self.i - 1] else: raise StopIteration def __hasNext__(self): return self.i<len(self.c.mylist) class MyCollection: def __init__(self, n): self.mylist = list(range(n)) def __iter__(self): return MyIterator(self) c1 = MyCollection(20) """ for e in c1: print(e) """ it1 = iter(c1) it2 = iter(c1) print(next(it1)) # it1.__next__() # 0 print(next(it2)) # it1.__next__() # 0 # we expect 0; we get it! print(it2.__hasNext__()) print(hasNext(it1))
def main(): a = [1, 2, 3] print(a[0]) print(a[1]) print(a[2]) a.append(4) print(a[3]) a += [5, 6, 7] a = a + [8, 9, 10] print(a[4]) print(a[-1]) if __name__ == '__main__': main()
# set comprehension odd_number_set = { x for x in range(10) if x % 2 == 1 } # expected output: ''' {1, 3, 5, 7, 9} ''' print( odd_number_set )
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: longest = 0 longestSub = "" for char in s: if char not in longestSub: longestSub += char else: while char in longestSub: longestSub = longestSub[1:] longestSub += char if len(longestSub) > longest: longest = len(longestSub) return longest
n = int(input()) k_lst = [int(input()) for _ in range(n)] k_lst.sort(reverse=True) cnt = 1 for i in range(n-1): if k_lst[i] == k_lst[i+1]: continue if k_lst[i] > k_lst[i+1]: cnt += 1 print(cnt)
""" 냉난방기의 온도를 조절하는 리모콘이 있다. 리모컨의 온도 조절 버튼은 총 6개로 다음과 같다. - 1도 증가, 감소 - 5도 증가, 감소 - 10도 증가, 감소 현재 설정된 온도와 목표 온도가 주어지면 최소 몇 번의 버튼을 눌러야 목표 온도를 설정할 수 있는지를 구하는 프로그램을 작성하시오. """ global a, b, res a, b = map(int, input().split()) res = 60 def solution(temp, cnt): global a, b, res if cnt > res: return if temp == b: if cnt < res: res = cnt return if temp < b: solution(temp+10, cnt+1) solution(temp+5, cnt+1) solution(temp+1, cnt+1) else: solution(temp-10, cnt+1) solution(temp-5, cnt+1) solution(temp-1, cnt+1) solution(a, 0) print(res)
N = int(input()) A = {} for i in range(N): A[i] = [] for j in range(int(input())): A[i].append([int(n) for n in input().split()])
# -*- coding: utf-8 -*- # Digital Ocean api urls ACCOUNT_INFO = 'account/' ACTION_LIST = 'actions/' DOMAIN_LIST = 'domains/' DROPLETS = 'droplets/' IMAGES = 'images/' KEYS = 'account/keys/' REGIONS = 'regions/' SIZES = 'sizes/'
class MissingUserDatabaseURLError(Exception): def __init__(self): self.message = 'Users database URL is not provided' super().__init__(self.message)
# -*- coding: utf-8 -*- __author__ = 'Aaron Bassett' __email__ = 'engineering@getadministrate.com' __version__ = '0.14.0'
# Copyright 2016 Srinivas Venkattaramanujam (author: Srinivas Venkattaramanujam) # Licensed under the Apache License, Version 2.0 (the "License") # Until we have a config file class Config: TRAIN_FEATS = '/speech1/DIT_PROJ/srini/TIMIT/s5/working_dir/train_90/feats.scp' TRAIN_ALIGNMENTS = '/speech1/DIT_PROJ/srini/TIMIT/s5/working_dir/labels/train/ali_tr.scp' CV_FEATS = '/speech1/DIT_PROJ/srini/TIMIT/s5/working_dir/cv_10/feats.scp' CV_ALIGNMENTS = '/speech1/DIT_PROJ/srini/TIMIT/s5/working_dir/labels/train/ali_cv.scp' TEST_FEATS = '/speech1/DIT_PROJ/srini/TIMIT/s5/working_dir/test/feats.scp'
#! /root/anaconda3/bin/python t = (1, 2, 3, 4, 5) del t try: print(t) except NameError: print(NameError)
""" Author: Ben Carlson Project: 100DaysPython File: module1_day01_installing.py Creation Date: 2019-06-03 Description: Use this script to confirm successful installation of the PyCharm IDE """ print("Hello World!")
# -*- coding:utf-8 -*- ''' @Author: yanwii @Date: 2018-08-16 15:18:52 ''' class BatchManager(object): def __init__(self, batch_size=1): self.batch_size = batch_size self.data = [] self.batch_data = [] self.head_vocab = {"unk":0} self.tail_vocab = {"unk":0} self.relation_vocab = {"unk":0} self.load_data() self.prepare_batch() def add_vocab(self, word, vocab={}): if word not in vocab: vocab[word] = len(vocab.keys()) return vocab[word] def load_data(self): with open("data/train") as fopen: lines = fopen.readlines() for line in lines: head, tail, relation = line.strip().split(",") h_v = self.add_vocab(head, self.head_vocab) t_v = self.add_vocab(tail, self.tail_vocab) r_v = self.add_vocab(relation, self.relation_vocab) self.data.append([[h_v], [t_v], [r_v]]) self.head_vocab_size = len(self.head_vocab) + 1 self.tail_vocab_size = len(self.tail_vocab) + 1 self.relation_vocab_size = len(self.relation_vocab) + 1 def prepare_batch(self): index = 0 while True: if index + self.batch_size >= len(self.data): data = self.data[-self.batch_size:] self.batch_data.append(data) break else: data = self.data[index:index+self.batch_size] index += self.batch_size self.batch_data.append(data) def iteration(self): idx = 0 while True: yield self.batch_data[idx] idx += 1 if idx > len(self.batch_data)-1: idx = 0 def get_batch(self): for data in self.batch_data: yield data
# _*_ coding:utf8- a=raw_input("enter password:") class ep3: def __init__(self,a): self.a=a def pd(self): if len(self.a)>=8: return self.a else: print("invalid password ,chang du bu gou") exit(0) def pd2(self): a=self.pd() b = a.isalnum() if( b==True): return a else: print("invalid password ,no have zi mu or no have shu") exit(0) def pd3(self): a=self.pd2() s=0 for i in range(len(a)): if a[i]>='0'and a[i]<='9': s=s+1 else: s=s if s>2: print("true") else: print("invalid password") A=ep3(a) A.pd3() ''' 反转 a1=raw_input("enter a number:") a=list(a1) a.reverse() print(a) ''' ''' a1={'1':1,'2':2,'aa':{1,2}} print a1.keys() print a1.values() print a1.items() for i,j in a1.items(): print i,j print a1.get('4','lallal') print a1.get('1','hahhhh') print a1.pop('1') print a1 print a1.popitem() a1['11']=1 print a1 ''' ''' #path1='/root/a.txt' path='/root/wangan.txt' #file_save=open(path1,'a',encoding='utf-8') with open(path,'r',encoding='utf-8',errors='ignore') as f: #while 1: line =f.readline().strip('\n').split(',') print(line) #try: #res=line[-2] #if '@' in res: #file_save.write(res+'\n') # print (res) #except Exception as e: # print(e) #print(line) # finally: # print('over') '''
""" Kullanıcıdan bir dik üçgenin dik olan iki kenarını(a,b) alın ve hipotenüs uzunluğunu bulmaya çalışın. Hipotenüs Formülü: a^2 + b^2 = c^2 """ print("Dik üçgenin hipotenüs uzunluğunu bulma") print("a²+b²=c²") a = int(input("a'yı giriniz :")) b = int(input("b'yı giriniz :")) c = (a**2+b**2)**0.5 print(a**2,"+",b**2,"=","{:.2f}".format(c**2)) print(a,"²+",b,"²=","{:.2f}".format(c),"²",sep="") print("c =","{:.2f}".format(c)) #Problem Çözüldü
class IncompleteStructureError(Exception): """An exception to raise when a structure is incomplete.""" def __init__(self, message): self.message = message class NonStandardAminoAcidError(Exception): """An exception to raise when a structure contains a Non-standard amino acid.""" def __init__(self, *args): super().__init__(*args) #TODO The one instance where this was called in stucture_utils.py was commented out. May not be needed. class MissingBackboneAtomsError(Exception): """An exception to raise when a protein backbone is incomplete.""" def __init__(self, message): self.message = message class SequenceError(Exception): """An exception to raise when a sequence is not as expected.""" def __init__(self, *args): super().__init__(*args) class ContigMultipleMatchingError(Exception): """An exception to raise when a sequence is ambiguous due to multiple matching contig locations.""" def __init__(self, *args): super().__init__(*args) class ShortStructureError(Exception): """An exception to raise when a sequence too short to be meaningful.""" def __init__(self, *args): super().__init__(*args) class MissingAtomsError(Exception): """An exception to raise when a residue is missing atoms and bond angles can't be calculated.""" def __init__(self, *args): super().__init__(*args) class NoneStructureError(Exception): """An exception to raise when a parsed structure becomes None.""" def __init__(self, *args): super().__init__(*args)
def parse(d): return ( ([frozenset(c) for c in g.split()] for g in l.split("|")) for l in d.split("\n") ) def aoc(data): return sum(len(d) in (2, 3, 4, 7) for _, b in parse(data) for d in b)
# # @lc app=leetcode.cn id=453 lang=python3 # # [453] 最小移动次数使数组元素相等 # # @lc code=start class Solution: def minMoves(self, nums: List[int]) -> int: minnum = min(nums) res = 0 for i in nums: if i != minnum: res += i - minnum return res # @lc code=end
# Copyright 2018 The Bazel 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. """Kotlin Toolchains This file contains macros for defining and registering specific toolchains. ### Examples To override a tool chain use the appropriate macro in a `BUILD` file to declare the toolchain: ```bzl load("@io_bazel_rules_kotlin//kotlin:toolchains.bzl", "define_kt_jvm_toolchain") define_kt_jvm_toolchain( name= "custom_toolchain", api_version = "1.1", language_version = "1.1", ) ``` and then register it in the `WORKSPACE`: ```bzl register_toolchains("//:custom_toolchain") ``` """ # The toolchain rules are not made private, at least the jvm ones so that they may be introspected in Intelij. _common_attrs = { 'language_version': attr.string(default="1.2", values=["1.1", "1.2"]), 'api_version': attr.string(default="1.2", values=["1.1", "1.2"]), "coroutines": attr.string(default="enable", values=["enable", "warn", "error"]), } _kt_jvm_attrs = dict(_common_attrs.items() + { 'jvm_target': attr.string(default="1.8", values=["1.6", "1.8"]), }.items()) def _kotlin_jvm_toolchain_impl(ctx): toolchain = platform_common.ToolchainInfo( language_version = ctx.attr.language_version, api_version = ctx.attr.api_version, jvm_target = ctx.attr.jvm_target, coroutines = ctx.attr.coroutines ) return [toolchain] kt_jvm_toolchain = rule( implementation = _kotlin_jvm_toolchain_impl, attrs = _kt_jvm_attrs ) """The kotlin jvm toolchain Args: language_version: the -languag_version flag [see](https://kotlinlang.org/docs/reference/compatibility.html). api_version: the -api_version flag [see](https://kotlinlang.org/docs/reference/compatibility.html). jvm_target: the -jvm_target flag. coroutines: the -Xcoroutines flag, enabled by default as it's considered production ready 1.2.0 onward. """ def define_kt_jvm_toolchain(name, language_version=None, api_version=None, jvm_target=None, coroutines=None): """Define a Kotlin JVM Toolchain, the name is used in the `toolchain` rule so can be used to register the toolchain in the WORKSPACE file.""" impl_name = name + "_impl" kt_jvm_toolchain( name = impl_name, language_version = language_version, api_version = api_version, jvm_target = jvm_target, coroutines = coroutines, visibility = ["//visibility:public"] ) native.toolchain( name = name, toolchain_type = "@io_bazel_rules_kotlin//kotlin:kt_jvm_toolchain_type", toolchain = impl_name, visibility = ["//visibility:public"] ) def kt_register_jvm_toolchain(): """Register the default JVM toolchain.""" native.register_toolchains("@io_bazel_rules_kotlin//kotlin:default_jvm_toolchain")
class Solution(object): def letterCasePermutation(self, S): """ :type S: str :rtype: List[str] """ res = [] self.dfs(S, res, "") return res def dfs(self, S, res, word): if not S: res.append(word) return if S[0].isalpha(): self.dfs(S[1:], res, word + S[0].upper()) self.dfs(S[1:], res, word + S[0].lower()) else: self.dfs(S[1:], res, word + S[0]) S = "a1b2" p = Solution() print(p.letterCasePermutation(S))
# AND : both need to be TRUE # has_high_income = True # has_good_credit = False # if has_high_income and has_good_credit: # print('Eligible for loan') # OR : at least one needs to be TRUE has_high_income = False has_good_credit = True if has_high_income or has_good_credit: print('Eligible for loan') # NOT : has_good_credit = True has_criminal_record = False if has_good_credit and not has_criminal_record: print('Eligible for loan!') # EXAMPLE weight = input('What is your weight? ') weight_type = input('(L)bs or (K)g ') if weight_type.upper() == 'L': converted_weight = int(weight) * .45 print(f'Your {weight}lbs equals {converted_weight} kilos.') if weight_type.upper() == 'K': converted_weight = int(weight) / .45 print(f'Your {weight}kg equals {converted_weight} pounds.')
# from testfixtures import TempDirectory # import pytest """ def test_reset_no_flags_should_delete_all_configs(tmpdir): mock_dir = tmpdir.mkdir("temp") pypcmgr_config = mock_dir.join(".pypcmgrconfig") hook_config = mock_dir.join(".pre-commit-config.yaml") assert len(mock_dir.listdir()) == ["temp"] def test_create_file(tmpdir): p = tmpdir.mkdir("sub").join("hello.txt") p.write("content") assert p.read() == "content" assert len(tmpdir.listdir()) == 1 """
board=[] for i in range(10): board.append(list(map(int,input().split()))) #입력 x, y = 1, 1 board[x][y]=9 while True: if(board[x][y]==2): # 좌표가 2면 9로바꾸고 스탑 = 먹이를 먹음 board[x][y]=9 # 다음으로 넘어가 만약 y축으로 한칸 옮기고 break # 1이 아닐 경우 9로 바꾸고 y+1 if(board[x][y+1]!=1): # 2와 1 둘다 아닐 경우 x축으로 이동 1이 아닐경우 board[x][y]=9 # x축 +1 y+=1 # 계속 진행하다보면 먹이를 먹고 9로 바꿔 스탑 else: if(board[x+1][y]!=1): board[x][y]=9 x+=1 else: board[x][y]=9 break for i in range(10): for j in range(10): print(board[i][j], end=' ') #출력 print()
PGS_TOKEN = 'C888EE7F420841CF92D0B0063EDDFC7D' PGS_EMAIL = 'pagseguro@panfleteria.com.br' # from datetime import datetime # from datetime import date # from datetime import timedelta # dates = [d0] # dates_two = list() # def date_paginator(x, y): # print x, y # if pages == 1 and pages_mods == 0: # _date = d0 + timedelta(days=30) # date_paginator(d0, _date) # else: # for i in range(pages): # _date = d0 + timedelta(days=30 * (i + 1)) # dates.append(_date) # if pages_mods > 0 and pages_mods < 30: # new_date = dates[-1:][0] + timedelta(days=pages_mods) # dates.append(new_date) # if dates: # for i in range(len(dates) - 1): # date_paginator(dates[i], dates[i + 1]) # class DateRangePagination: # """docstring for DateRangePagination""" # def __init__(self, initial_date): # self.initial_date = datetime.strptime(initial_date, "%Y-%m-%d").date() # self.dates = [self.initial_date] # self.date_limit = datetime.now().date() # def get_ranges(self): # print self.initial_date # def set_ranges(): # d0 = date(2008, 8, 18) # d1 = date(2008, 11, 18) # delta = d1 - d0 # pages = delta.days / 30 # pages_mods = delta.days % 30 # pass # def get_days(self,): # pass
# Irmãos - OBI 2020 c = int(input()) b = int(input()) dif = b - c a = b + dif print(a)
class Presenter: def __init__(self): pass @staticmethod def date_slashes_as_dashes(date_str): if date_str.find("/") == -1: return date_str else: mdy = date_str.split("/") return mdy[2] + "-" + mdy[0] + "-" + mdy[1] @staticmethod def value_without_symbols(value_str): return value_str.replace("$", "").replace(",", "").replace(")", "").replace("(", "-") @staticmethod def decimal_as_percentage(percent_fraction): return str(round(100 * percent_fraction, 1)) + "%"
# see: numpy.core.overrides def set_module(module): def decorator(func): if module is not None: func.__module__ = module return func return decorator
""" Given a string s, return the longest palindromic substring in s. Example 1: Input: s = "babad" Output: "bab" Explanation: "aba" is also a valid answer. Example 2: Input: s = "cbbd" Output: "bb" Constraints: 1 <= s.length <= 1000 s consist of only digits and English letters. """ class Solution: def longestPalindrome(self, s: str) -> str: ans = [0, 0] # odd for i in range(len(s)): left = i - 1 right = i + 1 while left >= 0 and right < len(s): if s[left] == s[right]: if right - left > ans[1] - ans[0]: ans = [left, right] left -= 1 right += 1 else: break # even for i in range(len(s)): left = i right = i + 1 while left >= 0 and right < len(s): if s[left] == s[right]: if right - left > ans[1] - ans[0]: ans = [left, right] left -= 1 right += 1 else: break return s[ans[0]: ans[1] + 1]
class Movie(): """Class that represents a Movie""" def __init__(self, movie_title, storyline, poster_image, trailer_youtube, duration): """Inits all data of a movie Args: movie_title(str): Movie title storyline(str): Movie storyline poster_image(str): Movie poster image trailer_youtube(str): Movie youtube url duration(str): Duration of the movie """ self.title = movie_title self.storyline = storyline self.poster_image_url = poster_image self.trailer_youtube_url = trailer_youtube self.duration = duration
# # PySNMP MIB module Unisphere-Data-DS3-CONF (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Unisphere-Data-DS3-CONF # Produced by pysmi-0.3.4 at Mon Apr 29 21:23:40 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, ValueRangeConstraint, ConstraintsIntersection, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueRangeConstraint", "ConstraintsIntersection", "ValueSizeConstraint", "SingleValueConstraint") dsx3FarEndConfigEntry, dsx3TotalEntry, dsx3FarEndCurrentEntry, dsx3SendCode, dsx3IntervalEntry, dsx3CurrentEntry, dsx3ConfigEntry, dsx3FracEntry, dsx3FarEndTotalEntry, dsx3FarEndIntervalEntry = mibBuilder.importSymbols("RFC1407-MIB", "dsx3FarEndConfigEntry", "dsx3TotalEntry", "dsx3FarEndCurrentEntry", "dsx3SendCode", "dsx3IntervalEntry", "dsx3CurrentEntry", "dsx3ConfigEntry", "dsx3FracEntry", "dsx3FarEndTotalEntry", "dsx3FarEndIntervalEntry") NotificationGroup, AgentCapabilities, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "AgentCapabilities", "ModuleCompliance") iso, ObjectIdentity, Gauge32, Counter32, Unsigned32, IpAddress, Bits, Integer32, ModuleIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, MibIdentifier, TimeTicks, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "ObjectIdentity", "Gauge32", "Counter32", "Unsigned32", "IpAddress", "Bits", "Integer32", "ModuleIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "MibIdentifier", "TimeTicks", "NotificationType") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") usDataAgents, = mibBuilder.importSymbols("Unisphere-Data-Agents", "usDataAgents") usdDs3Group2, usdDs3Group, usdDs3Group4, usdDs3FarEndGroup, usdDs3Group5, usdDs3Group3 = mibBuilder.importSymbols("Unisphere-Data-DS3-MIB", "usdDs3Group2", "usdDs3Group", "usdDs3Group4", "usdDs3FarEndGroup", "usdDs3Group5", "usdDs3Group3") usdDs3Agent = ModuleIdentity((1, 3, 6, 1, 4, 1, 4874, 5, 2, 11)) usdDs3Agent.setRevisions(('2002-08-27 18:48', '2001-04-18 19:41',)) if mibBuilder.loadTexts: usdDs3Agent.setLastUpdated('200208271848Z') if mibBuilder.loadTexts: usdDs3Agent.setOrganization('Unisphere Networks, Inc.') usdDs3AgentV1 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 11, 1)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): usdDs3AgentV1 = usdDs3AgentV1.setProductRelease('Version 1 of the DS3 component of the Unisphere Routing Switch SNMP\n agent. This version of the DS3 component was supported in the Unisphere\n RX 1.0 system release.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): usdDs3AgentV1 = usdDs3AgentV1.setStatus('obsolete') usdDs3AgentV2 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 11, 2)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): usdDs3AgentV2 = usdDs3AgentV2.setProductRelease('Version 2 of the DS3 component of the Unisphere Routing Switch SNMP\n agent. This version of the DS3 component was supported in the Unisphere\n RX 1.1 thru RX 2.5 system releases.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): usdDs3AgentV2 = usdDs3AgentV2.setStatus('obsolete') usdDs3AgentV3 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 11, 3)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): usdDs3AgentV3 = usdDs3AgentV3.setProductRelease('Version 3 of the DS3 component of the Unisphere Routing Switch SNMP\n agent. This version of the DS3 component was supported in the Unisphere\n RX 2.6 thru RX 2.9 system releases.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): usdDs3AgentV3 = usdDs3AgentV3.setStatus('obsolete') usdDs3AgentV4 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 11, 4)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): usdDs3AgentV4 = usdDs3AgentV4.setProductRelease('Version 4 of the DS3 component of the Unisphere Routing Switch SNMP\n agent. This version of the DS3 component was supported in the Unisphere\n RX 3.x system releases.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): usdDs3AgentV4 = usdDs3AgentV4.setStatus('obsolete') usdDs3AgentV5 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 11, 5)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): usdDs3AgentV5 = usdDs3AgentV5.setProductRelease('Version 5 of the DS3 component of the Unisphere Routing Switch SNMP\n agent. This version of the DS3 component is supported in the Unisphere\n RX 4.0 and subsequent system releases.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): usdDs3AgentV5 = usdDs3AgentV5.setStatus('current') mibBuilder.exportSymbols("Unisphere-Data-DS3-CONF", PYSNMP_MODULE_ID=usdDs3Agent, usdDs3AgentV4=usdDs3AgentV4, usdDs3AgentV3=usdDs3AgentV3, usdDs3Agent=usdDs3Agent, usdDs3AgentV2=usdDs3AgentV2, usdDs3AgentV5=usdDs3AgentV5, usdDs3AgentV1=usdDs3AgentV1)
while True: try: a = ord(input()[:1]) except EOFError: break b = ord(input()[:1]) print((b-a+26) % 26)
# program to count the numbers of occurrences of characters in the given string and store them in a dictionary string = input("Enter a string: ") d = {} for i in string: if i not in d.keys(): d[i] = 1 else: d[i] += 1 print(d)
class Config(object): ''' Each environment will be a class that inherits from the main class config Configurations that will be the same across all environment will go into config, while configuration that are specific to an environment will go into the relevant environment below ''' SECRET_KEY = "My$uper$ecretKey4Now" SERVER_TIME_ZONE = "Africa/Johannesburg" DEFAULT_DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S" class Production(Config): FLASK_ENV = 'production' PRODUCTION = True class Testing(Config): FLASK_ENV = 'testing' TESTING = True class Development(Config): FLASK_ENV = 'development' DEBUG = True
collected_data = { "form_id": "2", "name": "Test", "client_id": "11", "form_element_templates": [ {"name": "Full name", "value": "john doe"}, {"name": "Gender", "value": "male"}, {"name": "Country", "value": "morocco"}, ], } form_element_field = { "id": "2", "name": "test", "form_element_fields": [ { "id": "101", "form_element_template_id": "7", "form_id": "2", "form_element_template": { "id": "7", "name": "Gender", "form_element_type_id": "19", "form_element_type": { "id": "19", "name": "checkbox", }, "form_element_list_values": [ { "id": "12", "form_element_template_id": "7", "filled_form_id": "null", "value": "male", }, { "id": "13", "form_element_template_id": "7", "filled_form_id": "null", "value": "female", }, ], }, }, { "id": "102", "form_element_template_id": "8", "form_id": "2", "form_element_template": { "id": "8", "name": "Full name", "form_element_type_id": "20", "form_element_type": { "id": "20", "name": "text", "form_element_template_id": "8", }, "form_element_list_values": [], }, }, ], } filled_form_for_update = [ { "id": "87", "form_element_template_id": "7", "client_id": "11", "value": "null", "selected_list_values": [ { "id": "300", "form_element_list_values_id": "12", "filled_form_id": "87", "form_element_list_value": { "id": "12", "form_element_template_id": "7", "value": "male", }, } ], "form_element_template": { "id": "7", "name": "Gender", "form_element_type_id": "19", "form_element_type": { "id": "19", "name": "checkbox", }, "form_element_list_values": [ { "id": "12", "form_element_template_id": "7", "filled_form_id": "null", "value": "male", }, { "id": "13", "form_element_template_id": "7", "filled_form_id": "null", "value": "female", }, ], }, }, { "id": "82", "form_element_template_id": "8", "client_id": "11", "value": "jone doe", "selected_list_values": [], "form_element_template": { "id": "8", "name": "Full name", "form_element_type_id": "20", "form_element_type": { "id": "20", "name": "text", }, "form_element_list_values": [], }, }, ]
def numPrimo(numero): flag=True for i in range (2,numero): resto=numero%i if resto==0: flag=False return flag #main num=2 while num>0: num=int(input("Insira um número par maior que 2: ")) if num>0 and num%2==0: primo1=0 primo2=0 original=num num=int(num/2) if num%2==1: incr=0 else: incr=1 while primo1+primo2!=original: i=num-incr if numPrimo(i)==True: primo1=i i=num+incr if numPrimo(i)==True: primo2=i incr=incr+1 print(original,"=",primo1,"+",primo2)
""" List of constants used in the project """ SERVER_PORT = 8082 MAX_KEY_LENGTH = 21
""" It should receive a sequence of n numbers. If no argument is provided, return sum of numbers 1..100. Look closely to the type of the function's default argument ... """ def sum_numbers(numbers=None): if numbers is None: return sum(range(1, 101)) else: return sum(numbers) if __name__ == '__main__': numbers = 1, 2, 3 x = sum_numbers(numbers) print(x)
# # @lc app=leetcode.cn id=16 lang=python3 # # [16] 最接近的三数之和 # # https://leetcode-cn.com/problems/3sum-closest/description/ # # algorithms # Medium (45.81%) # Likes: 564 # Dislikes: 0 # Total Accepted: 151.1K # Total Submissions: 329.6K # Testcase Example: '[-1,2,1,-4]\n1' # # 给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target # 最接近。返回这三个数的和。假定每组输入只存在唯一答案。 # # # # 示例: # # 输入:nums = [-1,2,1,-4], target = 1 # 输出:2 # 解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。 # # # # # 提示: # # # 3 <= nums.length <= 10^3 # -10^3 <= nums[i] <= 10^3 # -10^4 <= target <= 10^4 # # # # @lc code=start class Solution: def threeSumClosest(self, nums: List[int], target: int) -> int: n = len(nums) if not nums or n < 3: return None ans = float('inf') nums.sort() for i in range(n): if i > 0 and nums[i] == nums[i-1]: continue l,r = i+1,n-1 while l < r: sum = nums[i] + nums[l] + nums[r] if abs(sum-target) <= abs(ans-target): ans = sum if sum > target: r -= 1 if sum < target: l += 1 if sum == target: return sum return ans # @lc code=end
""" 15 / 15 test cases passed. Runtime: 40 ms Memory Usage: 15 MB """ class Solution: def numberOfArithmeticSlices(self, nums: List[int]) -> int: n = len(nums) if n < 3: return 0 dp = [0] * n for i in range(1, n - 1): if nums[i] - nums[i - 1] == nums[i + 1] - nums[i]: dp[i + 1] = dp[i] + 1 return sum(dp)
liga = f"Moi je m'appelle 'Lolita'\n" ligb = f"Lo ou bien Lola, du pareil au même\n" ligc = f"Quand je rêve aux loups, c\'est Lola qui saigne\n" ligd = f"[...]\n" lige = f"C\'est pas ma faute\n" ligf = f"Et quand je donne ma langue aux chats je vois les autres\n" ligg = f"Tout prêts à se jeter sur moi, c'est pas ma faute à moi\n" ligh = f"Si j\'entends tout autour de moi\n" ligi = f"L.O.L.I.T.A, moi 'Lolita'\n" print (liga + ligb + liga + ligc + ligd + lige + ligf + ligg + ligh + ligi)
def is_correct_bracket_seq(n): """ На вход подаётся последовательность из скобок трёх видов: [], (), {}. Напишите функцию которая принимает на вход скобочную последовательность и возвращает True, если последовательность правильная, а иначе False. """ while '()' in n or '[]' in n or '{}' in n: n = n.replace('()', '') n = n.replace('[]', '') n = n.replace('{}', '') return not n if __name__ == '__main__': n = input() bracket_seq = is_correct_bracket_seq(n) print(bracket_seq)
#!/usr/bin pypy3 # ------------------------ Simplest form of learning ------------------------ weight = .5 input = .5 target = .8 step_amount = .001 # <= How much to move weights each iteration for iteration in range(1101) : # <= repeat the learning many times so that # error can keep getting smaller prediction = input * weight error = (prediction - target) ** 2 print(f"Error: {round(error, 3)} prediction: {round(prediction, 3)}") # Try up up_prediction = input * (weight + step_amount) up_error = (target - up_prediction) ** 2 # Try down down_prediction = input * (weight - step_amount) down_error = (target - down_prediction) ** 2 if (down_error < up_error) : weight = weight - step_amount if (down_error > up_error) : weight += step_amount # $ pypy3 error-update-advance.py # Error: 0.301 Prediction:0.25 # Error: 0.301 Prediction:0.250 # ........................... # Error: 0.0 prediction: 0.798 # Error: 0.0 prediction: 0.799 # Error: 0.0 prediction: 0.799 # Error: 0.0 prediction: 0.8
# AWS GENERAL SETTINGS: AWS_REGION = "us-east-1" AWS_PROFILE = "default" # The same profile used by your AWS CLI installation SSH_KEY_NAME = "key.pem" # Expected to be in ~/.ssh AWS_BUCKET = "dummybucket" # EC2 AND ECS INFORMATION: ECS_CLUSTER = "default_cluster" # SQS QUEUE INFORMATION: SQS_DEAD_LETTER_QUEUE = "arn:aws:sqs:us-east-1:XXXXXXXXXXXX:DeadMessages" # SNS INFORMATION: MONITOR_SNS = "arn:aws:sns:us-east-1:XXXXXXXXXXXX:Monitor"
inp = open('input_d18.txt').read() xl = len(inp)-1 yl = 400000 tiles = [[False for _ in range(xl)] for _ in range(yl)] # True if trap def get_tile(x,y): if x < 0 or x >= xl or y < 0 or y >= yl: return False return tiles[y][x] def is_trap(x,y): left,center,right = get_tile(x-1,y-1),get_tile(x,y-1),get_tile(x+1,y-1) if left and center and not right: return True if center and right and not left: return True if left and not right and not center: return True if right and not left and not center: return True return False count = 0 for x in range(xl): tiles[0][x] = (True if inp[x] == '^' else False) if inp[x] == '.': count += 1 for y in range(1,yl): for x in range(xl): tiles[y][x] = is_trap(x,y) if not tiles[y][x]: count += 1 # for y in range(yl): # for x in range(xl): # if not tiles[y][x]: # count += 1 print(count)
# # PySNMP MIB module MERU-CONFIG-STATICSTATION-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MERU-CONFIG-STATICSTATION-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:01:15 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueSizeConstraint, ConstraintsUnion, ConstraintsIntersection, ValueRangeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "ValueRangeConstraint", "SingleValueConstraint") Ipv6Address, = mibBuilder.importSymbols("IPV6-TC", "Ipv6Address") mwConfiguration, = mibBuilder.importSymbols("MERU-SMI", "mwConfiguration") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") MibIdentifier, enterprises, TimeTicks, Integer32, ModuleIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, Counter64, Counter32, ObjectIdentity, iso, Bits, Gauge32, Unsigned32, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "enterprises", "TimeTicks", "Integer32", "ModuleIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "Counter64", "Counter32", "ObjectIdentity", "iso", "Bits", "Gauge32", "Unsigned32", "NotificationType") TimeStamp, TextualConvention, TruthValue, DateAndTime, RowStatus, MacAddress, TimeInterval, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TimeStamp", "TextualConvention", "TruthValue", "DateAndTime", "RowStatus", "MacAddress", "TimeInterval", "DisplayString") mwConfigStaticStation = ModuleIdentity((1, 3, 6, 1, 4, 1, 15983, 1, 1, 4, 16)) if mibBuilder.loadTexts: mwConfigStaticStation.setLastUpdated('200506050000Z') if mibBuilder.loadTexts: mwConfigStaticStation.setOrganization('Meru Networks') mwStaticStationTable = MibTable((1, 3, 6, 1, 4, 1, 15983, 1, 1, 4, 16, 1), ) if mibBuilder.loadTexts: mwStaticStationTable.setStatus('current') mwStaticStationEntry = MibTableRow((1, 3, 6, 1, 4, 1, 15983, 1, 1, 4, 16, 1, 1), ).setIndexNames((0, "MERU-CONFIG-STATICSTATION-MIB", "mwStaticStationTableIndex")) if mibBuilder.loadTexts: mwStaticStationEntry.setStatus('current') mwStaticStationTableIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 15983, 1, 1, 4, 16, 1, 1, 1), Integer32()) if mibBuilder.loadTexts: mwStaticStationTableIndex.setStatus('current') mwStaticStationIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 15983, 1, 1, 4, 16, 1, 1, 2), IpAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: mwStaticStationIpAddress.setStatus('current') mwStaticStationMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 15983, 1, 1, 4, 16, 1, 1, 3), MacAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: mwStaticStationMacAddress.setStatus('current') mwStaticStationRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 15983, 1, 1, 4, 16, 1, 1, 4), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: mwStaticStationRowStatus.setStatus('current') mibBuilder.exportSymbols("MERU-CONFIG-STATICSTATION-MIB", mwStaticStationEntry=mwStaticStationEntry, mwStaticStationTableIndex=mwStaticStationTableIndex, mwStaticStationRowStatus=mwStaticStationRowStatus, mwConfigStaticStation=mwConfigStaticStation, mwStaticStationMacAddress=mwStaticStationMacAddress, PYSNMP_MODULE_ID=mwConfigStaticStation, mwStaticStationTable=mwStaticStationTable, mwStaticStationIpAddress=mwStaticStationIpAddress)
"""Serializers""" def serialize_greeting(greeting): """.""" return { 'id': None, 'type': 'greeting', 'attributes': { 'word': greeting.get('word', None), 'propertyTwo': greeting.get('propertyTwo', None), 'propertyThree': greeting.get('propertyThree', None), } }
def f8(n): m = n sum = 0 while m!=0: x = m%10 sum = sum + x**3 m = m//10 if sum == n: print(n, " is an Armstrong number") else: print(n, " is not an Armstrong number") f8(153) f8(125)
# Define the number of memory threads MEMORY_THREAD_NUM = 4 # Define the number of ebs threads EBS_THREAD_NUM = 4 # Define the number of proxy worker threads PROXY_THREAD_NUM = 4 # Number of tiers MIN_TIER = 1 MAX_TIER = 2 # Define port offset SERVER_PORT = 6560 NODE_JOIN_BASE_PORT = 6660 NODE_DEPART_BASE_PORT = 6760 SELF_DEPART_BASE_PORT = 6860 REPLICATION_FACTOR_BASE_PORT = 6960 REQUEST_PULLING_BASE_PORT = 6460 GOSSIP_BASE_PORT = 7060 REPLICATION_FACTOR_CHANGE_BASE_PORT = 7160 # used by proxies SEED_BASE_PORT = 6560 NOTIFY_BASE_PORT = 6660 KEY_ADDRESS_BASE_PORT = 6760 # used by monitoring nodes DEPART_DONE_BASE_PORT = 6760 LATENCY_REPORT_BASE_PORT = 6860 # used by benchmark threads COMMAND_BASE_PORT = 6560 class Thread(): def __init__(self, ip, tid): self.ip = ip self.tid = tid self._base = 'tcp://*:' self._ip_base = 'tcp://' + self.ip + ':' def get_ip(self): return self.ip def get_tid(self): return self.tid class UserThread(Thread): def get_request_pull_connect_addr(self): return self._ip_base + str(self.tid + REQUEST_PULLING_BASE_PORT) def get_request_pull_bind_addr(self): return self._base + str(self.tid + REQUEST_PULLING_BASE_PORT) def get_key_address_connect_addr(self): return self._ip_base + str(self.tid + KEY_ADDRESS_BASE_PORT) def get_key_address_bind_addr(self): return self._base + str(self.tid + KEY_ADDRESS_BASE_PORT) class ProxyThread(Thread): def get_key_address_connect_addr(self): return self._ip_base + str(self.tid + KEY_ADDRESS_BASE_PORT) def key_address_bind_addr(self): return self._base + str(self.tid + KEY_ADDRESS_BASE_PORT)
t=input().split() hi=int(t[0]) hf=int(t[1]) if hi==hf: ht=24 elif hi>hf: ht=(24-hi)+hf elif hi<hf: ht=hf-hi print("O JOGO DUROU %d HORA(S)" %ht)
# Atharv Kolhar # Python Bytes """ Write a Program to convert Integers to Roman Symbols Between number 1 to 1000 """ def integer_to_roman(number): n = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000] rn = ['I', 'IV', 'V', 'IX', 'X', 'XL', 'L', 'XC', 'C', 'CD', 'D', 'CM', 'M'] roman_num = "" i = len(n) - 1 remainder = number while remainder != 0: quotient = remainder // n[i] remainder = remainder % n[i] roman_num += quotient * rn[i] i -= 1 # i = i - 1 return roman_num print(integer_to_roman(2022))
N = int(input()) ROCK, PAPER, SCISSORS = 'R', 'P', 'S' beating_move_by_move = { ROCK: PAPER, PAPER: SCISSORS, SCISSORS: ROCK, } MAX_CHARS = 500 IMPOSSIBLE = 'IMPOSSIBLE' for case_id in range(1, N + 1): nb_robots = int(input()) robot_programs = [input() for _ in range(nb_robots)] best_combination = '' can_win = True for char_index in range(MAX_CHARS): moves_to_beat = [*{robot_program[char_index % len(robot_program)] for robot_program in robot_programs}] if len(moves_to_beat) == 1: winning_move = beating_move_by_move[moves_to_beat[0]] best_combination += winning_move robot_programs = [] break elif len(moves_to_beat) == 2: best_move = '?' if ROCK not in moves_to_beat: best_move = SCISSORS elif PAPER not in moves_to_beat: best_move = ROCK elif SCISSORS not in moves_to_beat: best_move = PAPER best_combination += best_move robot_programs = [ robot_program for robot_program in robot_programs if beating_move_by_move[robot_program[char_index % len(robot_program)]] != best_move ] elif len(moves_to_beat) == 3: break print('Case #{}: {}'.format(case_id, best_combination if len(robot_programs) == 0 else IMPOSSIBLE))
class Pessoa: ano_atual = 2019 def __init__(self, nome, idade): self.nome = nome self.idade = idade def get_ano_nascimento(self): print(self.ano_atual - self.idade) @classmethod #Eu nao entendi a logica aq, sem nexo def por_ano_nascimento(cls, nome, ano_nascimento): idade = cls.ano_atual - ano_nascimento return cls(nome, idade) p1 = Pessoa('Pedro', 23) print(p1) print(p1.nome, p1.idade) p1.get_ano_nascimento()
##Q3. Write a program to print table of 2 ############################################################################################################# ##Program Objective: to print table of 2 ## ##Coded by: KNR ## ##Date: 17/09/2019 22:20 ## ##Lang: Python 3.7.4 ## ##Version: 1.0 ## ############################################################################################################# # Method-1: Using for loop ##print("--------------------------------------------------") ## ##for i in range(1,11): ## print("{} x {} = {}".format(2,i,2*i)) ## ##print("--------------------------------------------------") # Method-2: Using while loop print("--------------------------------------------------") i = 1 while i<=10: print("{} x {} = {}".format(2,i,2*i)) i+=1 print("--------------------------------------------------")
def funcaoOrig(x): return(x - 2) def raizFuncao(a, b): erro = 0.1 cont = 0 while((funcaoOrig(a)) * (funcaoOrig(b)) >= 0): print(f'\nErro!\nCom os valores {a} e {b}, eh impossivel calcularmos as raizes da funcao original!') a = float(input('\nDigite outro valor para a: ')) b = float(input('Digite outro valor para b: ')) while(abs(a - b) > erro): x = (a + b) / 2 if((funcaoOrig(a)) * (funcaoOrig(x)) < 0): b = x else: a = x cont += 1 print(f'\nA raiz da funcao eh: {x} com precisao de {erro} em {cont} iteracoes')
def make_default_resolver(field_attr_name): def resolver(source, args, info): property = getattr(source, field_attr_name, None) if callable(property): return property() return property resolver.__name__ = 'resolve_{}'.format(field_attr_name) return resolver
""" Physical parameters of the laboratory Crazyflie quadrotors. Additional sources: https://bitcraze.io/2015/02/measuring-propeller-rpm-part-3 https://wiki.bitcraze.io/misc:investigations:thrust https://commons.erau.edu/cgi/viewcontent.cgi?article=2057&context=publication Notes: k_thrust is inferred from 14.5 g thrust at 2500 rad/s k_drag is mostly made up """ quad_params = { 'mass': 0.030, # kg 'Ixx': 1.43e-5, # kg*m^2 'Iyy': 1.43e-5, # kg*m^2 'Izz': 2.89e-5, # kg*m^2 'arm_length': 0.046, # meters 'rotor_speed_min': 0, # rad/s 'rotor_speed_max': 2500, # rad/s 'k_thrust': 2.3e-08, # N/(rad/s)**2 'k_drag': 7.8e-11, # Nm/(rad/s)**2 }
# Time: O(n) # Space: O(1) class Solution(object): def validMountainArray(self, A): """ :type A: List[int] :rtype: bool """ i = 0 while i+1 < len(A) and A[i] < A[i+1]: i += 1 j = len(A)-1 while j-1 >= 0 and A[j-1] > A[j]: j -= 1 return 0 < i == j < len(A)-1
strs = ["flower","flow","flight"] if len(strs) == 0: print("") exit() prefix = strs[0] for str in strs: while(str.find(prefix) != 0): prefix = prefix[0:len(prefix)-1] if len(prefix) == 0: print("") exit() print(prefix)
d1 = {1:'Sugandh', 2:'Divya', 3:'Mintoo'} print(d1) # D1 print("deleting an item from the dictionary...") del d1[3] print(d1) # D2 print("deleting an entire dictionary...") del d1 print(d1) # D3
''' Template untuk solusi Lab 09 kelas A. ''' class Bangunan: ''' Sebuah bangunan. ''' def __init__(self, nama_bangunan, lama_sewa, harga_sewa): self.nama = nama_bangunan self.lama_sewa = lama_sewa self.harga_sewa = harga_sewa def get_harga_sewa(self): ''' Mengembalikan harga sewa. ''' return self.harga_sewa class Restoran(Bangunan): ''' Sebuah restoran. ''' def __init__(self, nama_restoran, lama_sewa=0): Bangunan.__init__(self, nama_restoran, lama_sewa, 30000000) # Silahkan ditambahkan class-class lainnya atau jika ingin memodifikasi daftar_bangunan = None while True: masukan = input().split() if masukan[0] == "BANGUN": # dapatkan nilai ini dari masukan_split sesuai indexnya nama = None jenis_bangunan = None # lakukan selection untuk menentukan tipe Pegawai if jenis_bangunan == "HOTEL": bangunan = None elif jenis_bangunan == "RESTORAN": bangunan = Restoran(nama) elif jenis_bangunan == "RUMAHSAKIT": bangunan = None # masukan bangunan yang sudah dibuat ke dalam dictionary # cetak pesan sesuai format elif masukan[0] == "INFO": pass elif masukan[0] == "JUALMAKANAN": pass elif masukan[0] == "TERIMATAMU": pass elif masukan[0] == "OBATIPASIEN": pass elif masukan[0] == "HITUNGUANG": pass
# list的使用 # 1.新建一个列表fruits fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana'] # 新增一个元素 # append: 在list列表后增加元素 fruits.append("pear") print(fruits) # insert: 指定位置增加元素 fruits.insert(0, "pear") print(fruits) # 指定元素的位置 # count:从1开始 print(fruits.count("pear")) print(fruits.count("apple")) # 搞错了,这个不是指定元素的位置,这个是指定元素的个数 # index:从0开始 print(fruits.index("pear")) print(fruits.index("pear", 6)) #从5开始计数,则pear出现的位置是在什么地方呢? # list推导式 result = [len(fruit) for fruit in fruits] # 显示的是所有水果的字符串大小 print(result)
def crime_list(z): #function definition f=open(z,"r") #open csv file in read mode d1=dict() d2=dict() list1=[] list2=[] for line in f: line.strip() for lines in line.split(','): list1.append(lines[-1]) list2.append(lines[-2]) for y in list1: if y not in d1: d1[y]=1 else: d1[y]=d[y]+1 for z in list2: if z not in d2: d2[z]=1 else: d2[z]+=1 print("crime name",' '*15,"crimeid",' '*15,"crimecount") #printing Headers for k1,v in d1.items(): for k2,v in d2.items(): print(k1,k2,v, "\n") file="Crime.csv" crime_list(file) #function call
def part1(lines): total = 0 for box in lines: dim = list(map(int, box.split("x"))) lw = dim[0] * dim[1] wh = dim[1] * dim[2] hl = dim[2] * dim[0] total += 2*lw + 2*wh + 2*hl + min(lw,wh,hl) return total def part2(lines): total = 0 for box in lines: dim = sorted(list(map(int, box.split("x")))) total += dim[0] + dim[0] + dim[1] + dim[1] + dim[0]*dim[1]*dim[2] return total if __name__ == "__main__": with open("../input.txt") as file: lines = file.read().splitlines() print(part1(lines)) print(part2(lines))
def _findwinners(players): best = -1 winners = [] for i in range(len(players)): if players[i]: if best == -1 or players[i] > best: best = players[i] winners = [i] elif players[i] == best: winners.append(i) return winners def _splitpot(winners, pot): amount = pot // len(winners) winnings = [amount] * len(winners) winningsamount = amount * len(winners) for i in range(len(winnings)): if winningsamount >= amount: break winnings[i] += 1 winningsamount += 1 return winnings def payout(players, pots): payouts = [0] * len(players) for pot in pots: if pot['chips'] > 0: winners = _findwinners(players) if (len(winners) > 0): winnings = _splitpot(winners, pot['chips']) for i in range(len(winners)): payouts[winners[i]] += winnings[i] for allin in pot['players']: players[allin] = False return payouts if __name__ == '__main__': payouts = payout([False, [8, 13], [7, 14], False], [{ 'chips': 100, 'players': [] }]) if payouts != [0, 100, 0, 0]: print('Test1 failed') payouts = payout([False, [8, 13], [7, 14], False], [{ 'chips': 100, 'players': [1] }, { 'chips': 50, 'players': [] }]) if payouts != [0, 100, 50, 0]: print('Test2 failed') payouts = payout([False, [8, 13], [7, 14], [8, 13]], [{ 'chips': 100, 'players': [] }]) if payouts != [0, 50, 0, 50]: print('Test3 failed')
__add_idle_call = None __remove_idle_call = None __add_timeout_call = None __remove_timeout_call = None __setup_event_loop = None __start_event_loop = None __stop_event_loop = None __idle_call_dict = {} __timeout_call_dict = {} def add_idle_call(func, *args, **kwargs): global __add_idle_call global __idle_call_dict if __add_idle_call is not None: __idle_call_dict[func] = __add_idle_call(func, *args, **kwargs) else: # toolkit does not support this or is not loaded: func(*args, **kwargs) def remove_idle_call(func): global __remove_idle_call global __idle_call_dict if __remove_idle_call is not None: __remove_idle_call(__idle_call_dict[func]) def add_timeout_call(timeout, func, *args, **kwargs): global __add_timeout_call global __timeout_call_dict if __add_timeout_call is not None: __timeout_call_dict[func] = __add_timeout_call(timeout, func, *args, **kwargs) else: # toolkit does not support this or is not loaded: func(*args, **kwargs) def remove_timeout_call(func): global __remove_timeout_call global __timeout_call_dict if __remove_timeout_call is not None: __remove_timeout_call(__timeout_call_dict[func]) def start_event_loop(): global __start_event_loop if __start_event_loop is not None: return __start_event_loop() def stop_event_loop(): global __stop_event_loop if __stop_event_loop is not None: return __stop_event_loop() def load_toolkit_functions( add_idle_call, remove_idle_call, add_timeout_call, remove_timeout_call, start_event_loop, stop_event_loop): """ 'add_idle_call' should take a function as 1st argument, the return value is passed back to 'remove_idle_call'. Internally a cache is maintained in which keys are functions and values are return values. 'add_timeout_call' and 'remove_timeout_call' work analogously start_event_loop and stop_event_loop don't take arguments and should be self-explanatory. """ global __add_idle_call global __remove_idle_call global __add_timeout_call global __remove_timeout_call global __start_event_loop global __stop_event_loop assert callable(add_idle_call) assert callable(remove_idle_call) assert callable(add_timeout_call) assert callable(remove_timeout_call) assert callable(start_event_loop) assert callable(stop_event_loop) __add_idle_call = add_idle_call __remove_idle_call = remove_idle_call __add_timeout_call = add_timeout_call __remove_timeout_call = remove_timeout_call __start_event_loop = start_event_loop __stop_event_loop = stop_event_loop """ Decorators: """ def run_when_idle(func): def callback(*args, **kwargs): return add_idle_call(func, *args, **kwargs) return callback def run_every(timeout): def wrapper(func): def callback(*args, **kwargs): return add_timeout_call(func, timeout, *args, **kwargs) return callback return wrapper
"""Maps between model names and more readable versions. Model/code names (on the left) are used internally by Cavecalc. Readable names are largely used in the GUI. Conversion between them is handled by the setter.NameSwitcher class. """ database = "PHREEQC Database Filename" phreeqc_log_file = "Log PHREEQC input" phreeqc_log_file_name = "PHREEQC Log Filename" out_dir = "Output Directory" temperature = "Temperature (Degrees C)" co2_decrement = "CO2(g) removal per step (fraction)" calcite_sat_limit = "Calcite supersaturation limit (SI)" bedrock = "Bedrock (moles)" bedrock_mineral = "Bedrock Lithology" bedrock_pyrite = "Bedrock Pyrite (moles)" bedrock_d44Ca = "Bedrock d44Ca (per mil)" bedrock_d13C = "Bedrock d13C (per mil)" bedrock_d18O = "Bedrock d18O (per mil)" bedrock_MgCa = "Bedrock Mg/Ca (mmol/mol)" bedrock_SrCa = "Bedrock Sr/Ca (mmol/mol)" bedrock_BaCa = "Bedrock Ba/Ca (mmol/mol)" atmo_exchange = "Second Gas Fraction (0-1)" gas_volume = "Gas Volume (L)" atm_O2 = "Second Gas O2 (%)" atm_pCO2 = "Second Gas pCO2 (ppmv)" atm_d13C = "Second Gas d13C (per mil)" atm_R14C = "Second Gas R14C (pmc)" atm_d18O = "Rainfall d18O (per mil)" init_O2 = "Initial O2 (%)" init_pCO2 = "Initial pCO2 (ppmv)" init_d13C = "Initial d13C (per mil)" init_R14C = "Initial R14C (pmc)" init_solution_d13c = "Initial Solution d13C (per mil) - OVERWRITE" cave_O2 = "Cave Air O2 (%)" cave_pCO2 = "Cave Air pCO2 (ppmv)" cave_d13C = "Cave Air d13C (per mil)" cave_R14C = "Cave Air R14C (pmc)" cave_d18O = "Cave Air d18O (per mil)" cave_air_volume = "Cave Air Volume (L)" soil_pH = "Soil pH (approx.)" soil_O2 = "Soil Gas O2 (%)" soil_pCO2 = "Soil Gas pCO2 (ppmv)" soil_Ca = "Soil Ca (mmol/kgw)" soil_Mg = "Soil Mg (mmol/kgw)" soil_Sr = "Soil Sr (mmol/kgw)" soil_Ba = "Soil Ba (mmol/kgw)" soil_d13C = "Soil Gas d13C (per mil)" soil_R14C = "Soil Gas R14C (pmc)" soil_d44Ca = "Soil d44Ca (per mil)" kinetics_mode = "Degassing/Precipitation Mode" reprecip = "Allow Calcite Reprecipitation" totals = "Totals" molalities = "Molalities" isotopes = "Isotopes"
def avg(list): return (float(sum(list)) / len(list)) def apply(map, f_x, f_y): return {f_x(x): f_y(y) for x,y in map.items()} def linear(a, b): return (lambda x: (a * x + b)) def read_csv(filename): file = open(filename, "r") labels = file.readline()[:-1].split(',') print("We get {} from {}".format(labels[1], labels[0])) map = {} for line in file: x, y = line.split(',') map[int(x)] = int(y) file.close() return (map) def distance(map): def partial(single_cost): def total(f): sum = 0 for (x,y) in map.items(): sum += single_cost(f, x, y) return (sum / len(map)) return (total) return (partial) def train(): F = read_csv("data.csv") mx, my = max(F.keys()), max(F.values()) delta = distance(apply(F, lambda x: x/mx, lambda y: y/my)) dx = delta(lambda f,x,y: y - f(x)) dy = delta(lambda f,x,y: (y - f(x)) * x) cost = delta(lambda f,x,y: (y - f(x)) ** 2) theta = gradient_descent([dx, dy, cost]) return (theta[0] * my, theta[1] * my / mx) def gradient_descent(distance_functions): count = 0 learning_rate = 1.5 theta = [0, 0] prev_cost = 200 cur_cost = 100 while (count < 1000 and abs(cur_cost - prev_cost) > 10e-11): f = linear(theta[1], theta[0]) prev_cost = cur_cost cur_cost = distance_functions[2](f) for i in range(2): theta[i] += learning_rate * distance_functions[i](f) count += 1 print("Performed {} iterations".format(count)) return (theta)
class test: def __init__(self): pass def printer(self): print("hello world!") if __name__=='__main__': foo = test() foo.printer()
res = client.get_arrays_space() print(res) if type(res) == pypureclient.responses.ValidResponse: print(list(res.items)) # list array space of file systems res = client.get_arrays_space(type='file-system') print(res) if type(res) == pypureclient.responses.ValidResponse: print(list(res.items)) # list historical array space res = client.get_arrays_space(start_time=START_TIME, end_time=END_TIME, resolution=30000) print(res) if type(res) == pypureclient.responses.ValidResponse: print(list(res.items))
# Created by MechAviv # Map ID :: 940001210 # Eastern Region of Pantheon : East Sanctum sm.curNodeEventEnd(True) sm.setTemporarySkillSet(0) sm.setInGameDirectionMode(True, True, False, False) sm.forcedInput(0) sm.forcedInput(2) sm.sendDelay(30) sm.forcedInput(0) OBJECT_1 = sm.sendNpcController(3000103, -300, 220) sm.showNpcSpecialActionByObjectId(OBJECT_1, "summon", 0) OBJECT_2 = sm.sendNpcController(3000104, -450, 220) sm.showNpcSpecialActionByObjectId(OBJECT_2, "summon", 0) OBJECT_3 = sm.sendNpcController(3000110, -120, 220) sm.showNpcSpecialActionByObjectId(OBJECT_3, "summon", 0) OBJECT_4 = sm.sendNpcController(3000114, -100, 220) sm.showNpcSpecialActionByObjectId(OBJECT_4, "summon", 0) OBJECT_5 = sm.sendNpcController(3000111, 130, 220) sm.showNpcSpecialActionByObjectId(OBJECT_5, "summon", 0) OBJECT_6 = sm.sendNpcController(3000115, 250, 220) sm.showNpcSpecialActionByObjectId(OBJECT_6, "summon", 0) sm.setSpeakerID(3000104) sm.removeEscapeButton() sm.setSpeakerType(3) sm.sendNext("Nothing here, big surprise...") sm.showEffect("Effect/Direction9.img/effect/story/BalloonMsg1/3", 1200, 0, -120, 0, OBJECT_2, False, 0) sm.showEffect("Effect/Direction9.img/effect/story/BalloonMsg1/3", 1200, 0, -120, -2, -2, False, 0) sm.showEffect("Effect/Direction9.img/effect/story/BalloonMsg1/4", 1200, 0, -120, 0, OBJECT_1, False, 0) sm.sendDelay(1200) sm.setSpeakerID(3000103) sm.removeEscapeButton() sm.setSpeakerType(3) sm.sendNext("Well, those priests are keeping busy. It's funny, though...I don't recognize any of them.") sm.setSpeakerID(3000103) sm.removeEscapeButton() sm.flipDialoguePlayerAsSpeaker() sm.setSpeakerType(3) sm.sendSay("Shhh! Something is not right. Velderoth!") sm.setSpeakerID(3000104) sm.removeEscapeButton() sm.setSpeakerType(3) sm.sendSay("You're right. They look suspicious. I'm going to run back to base and get help. You two stay here and keep an eye on them, okay? But no heroics. You get out of here if they spot you.") sm.showEffect("Effect/Direction9.img/effect/story/BalloonMsg0/0", 1200, 0, -120, 0, OBJECT_1, False, 0) sm.sendDelay(900) sm.setSpeakerID(3000103) sm.removeEscapeButton() sm.setSpeakerType(3) sm.sendNext("What are you talking about?") sm.sendNpcController(OBJECT_2, False) sm.setSpeakerID(3000103) sm.removeEscapeButton() sm.flipDialoguePlayerAsSpeaker() sm.setSpeakerType(3) sm.sendSay("They attacked the East Sanctum? What are they trying to do with the Relic?)") sm.setSpeakerID(3000110) sm.removeEscapeButton() sm.setSpeakerType(3) sm.sendSay("The relic's disappearance should weaken the shields.") # Unhandled Stat Changed [HP] Packet: 00 00 00 04 00 00 00 00 00 00 02 02 00 00 FF 00 00 00 00 sm.setSpeakerID(3000114) sm.removeEscapeButton() sm.setSpeakerType(3) sm.sendSay("I thought the relic was cursed... should we really be touching it?") sm.setSpeakerID(3000110) sm.removeEscapeButton() sm.setSpeakerType(3) sm.sendSay("I did not realize they allowed superstitious nincompoops entry to our order! Will you balk at the call of destiny?") sm.setSpeakerID(3000110) sm.removeEscapeButton() sm.flipDialoguePlayerAsSpeaker() sm.setSpeakerType(3) sm.sendSay("Are they trying to take the Relic?") sm.setSpeakerID(3000103) sm.removeEscapeButton() sm.setSpeakerType(3) sm.sendSay("We gotta stop them!") sm.moveNpcByObjectId(OBJECT_1, False, 300, 100) sm.sendDelay(300) sm.forcedInput(2) sm.showEffect("Effect/Direction9.img/effect/story/BalloonMsg1/1", 1200, 0, -120, 0, OBJECT_3, False, 0) sm.showEffect("Effect/Direction9.img/effect/story/BalloonMsg1/1", 1200, 0, -120, 0, OBJECT_4, False, 0) sm.showEffect("Effect/Direction9.img/effect/story/BalloonMsg1/1", 1200, 0, -120, 0, OBJECT_5, False, 0) sm.showEffect("Effect/Direction9.img/effect/story/BalloonMsg1/1", 1200, 0, -120, 0, OBJECT_6, False, 0) sm.sendDelay(600) sm.forcedInput(0) sm.showEffect("Effect/Direction9.img/effect/story/BalloonMsg1/7", 900, 0, -120, 0, OBJECT_1, False, 0) sm.sendDelay(900) sm.showFieldEffect("kaiser/tear_rush", 0) sm.sendDelay(3000) # Unhandled Message [COLLECTION_RECORD_MESSAGE] Packet: 2A 01 00 00 00 2F 00 31 30 3A 31 3A 32 3A 31 31 3D 34 3B 31 30 3A 31 3A 32 3A 31 32 3D 35 3B 31 30 3A 31 3A 33 3A 31 35 3D 34 3B 31 30 3A 31 3A 33 3A 31 36 3D 35 sm.sendNpcController(OBJECT_1, False) sm.setTemporarySkillSet(0) sm.setInGameDirectionMode(False, True, False, False) sm.sendNpcController(OBJECT_3, False) sm.sendNpcController(OBJECT_4, False) sm.sendNpcController(OBJECT_5, False) sm.sendNpcController(OBJECT_6, False) sm.warp(940001220, 0)
# dictionary of key signatures keySigSemanticToLP = { "Cm": "\\key c \\minor ", "CM": "\\key c \\major ", "C#m": "\\key cis \\minor ", "C#M": "\\key cis \\major ", "Cbm": "\\key ces \\minor ", "CbM": "\\key ces \\major ", "Dm": "\\key d \\minor ", "DM": "\\key d \\major ", "D#m": "\\key dis \\minor ", "D#M": "\\key dis \\major ", "Dbm": "\\key des \\minor ", "DbM": "\\key des \\major ", "Em": "\\key e \\minor ", "EM": "\\key e \\major ", "E#m": "\\key eis \\minor ", "E#M": "\\key eis \\major ", "Ebm": "\\key ees \\minor ", "EbM": "\\key ees \\major ", "Fm": "\\key f \\minor ", "FM": "\\key f \\major ", "F#m": "\\key fis \\minor ", "F#M": "\\key fis \\major ", "Fbm": "\\key fes \\minor ", "FbM": "\\key fes \\major ", "Gm": "\\key g \\minor ", "GM": "\\key g \\major ", "G#m": "\\key gis \\minor ", "G#M": "\\key gis \\major ", "Gbm": "\\key ges \\minor ", "GbM": "\\key ges \\major ", "Am": "\\key a \\minor ", "AM": "\\key a \\major ", "A#m": "\\key ais \\minor ", "A#M": "\\key ais \\major ", "Abm": "\\key aes \\minor ", "AbM": "\\key aes \\major ", "Bm": "\\key b \\minor ", "BM": "\\key b \\major ", "B#m": "\\key bis \\minor ", "B#M": "\\key bis \\major ", "Bbm": "\\key bes \\minor ", "BbM": "\\key bes \\major " } # dictionary of note lengths # need to add double dots lengthToNum = { "quadruple_whole": "\\longa ", "quadruple_whole.": "\\longa. ", "double_whole": "\\breve ", "double_whole.": "\\breve. ", "whole": "1 ", "whole.": "1. ", "whole..": "1.. ", "half": "2 ", "half.": "2. ", "half..": "2.. ", "quarter": "4 ", "quarter.": "4. ", "quarter..": "4. ", "eighth": "8 ", "eighth.": "8. ", "eighth..": "8.. ", "sixteenth": "16 ", "sixteenth.": "16. ", "sixteenth..": "16.. ", "thirty_second": "32 ", "thirty_second.": "32. ", "thirty_second..": "32.. ", "sixty_fourth": "64 ", "sixty_fourth.": "64. ", "sixty_fourth.,": "64.. ", "hundred_twenty_eighth": "128 " } # dictionary of note pitches letterToNote = { "C": "c ", "C#": "cis ", "Cb": "ces ", "D": "d ", "D#": "dis ", "Db": "des ", "E": "e ", "E#": "eis ", "Eb": "ees ", "F": "f ", "F#": "fis ", "Fb": "fes ", "G": "g ", "G#": "gis ", "Gb": "ges ", "A": "a ", "A#": "ais ", "Ab": "aes ", "B": "b ", "B#": "bis ", "Bb": "bes " } # dictionary of clefs clefDict = { "C1": "soprano ", "C2": "mezzosoprano ", "C3": "alto ", "C4": "tenor ", "C5": "baritone ", "F3": "baritone ", "F4": "bass ", "F5": "subbass ", "G1": "french ", "G2": "treble " } BEATS_PER_MEASURE = "1" def parser(toparse): """ parses each command output of the semantic model, returns the equivalent LilyPond command inputs: toparse -- TODO outputs: TODO """ divided_string = toparse.split("-") global BEATS_PER_MEASURE if divided_string[0] == "clef": return "\\clef " + clefDict[divided_string[1]] + "\n" elif divided_string[0] == "keySignature": return keySigSemanticToLP[divided_string[1]] + "\n" elif divided_string[0] == "timeSignature": BEATS_PER_MEASURE = divided_string[1][0] if divided_string[1] == "C": return "\\time 4/4 \n" elif divided_string[1] == "C/": return "\\time 2/2 \n" else: return "\\time " + divided_string[1] + "\n" # this is the number of beats, so somehow we need to keep track of the time signature elif divided_string[0] == "multirest": if BEATS_PER_MEASURE != 0: return "\\compressFullBarRests \n \t R1*" +\ str(int(divided_string[1])//int(BEATS_PER_MEASURE)) + "\n " else: return "\\compressFullBarRests \n \t R1*" +\ divided_string[1] + "\n " elif divided_string[0] == "barline": return " \\bar \"|\" " # return " " elif divided_string[0] == "rest": ending = "" if divided_string[1][-7:] == "fermata": ending = "\\fermata " divided_string[1] = divided_string[1][:-8] return "r" + lengthToNum[divided_string[1]] + ending + " " elif divided_string[0] == "note": note_info = divided_string[1].split("_", 1) ending = "" if note_info[1][-7:] == "fermata": ending = "\\fermata " note_info[1] = note_info[1][:-8] if int(note_info[0][-1]) == 3: return letterToNote[note_info[0][:-1]] +\ lengthToNum[note_info[1]] + ending elif int(note_info[0][-1]) < 3: return letterToNote[note_info[0][:-1]] +\ (3 - int(note_info[0][-1])) * "," +\ lengthToNum[note_info[1]] + ending elif int(note_info[0][-1]) > 3: return letterToNote[note_info[0][:-1]] +\ (int(note_info[0][-1]) - 3) * "\'" +\ lengthToNum[note_info[1]] + ending elif divided_string[0] == "gracenote": note_info = divided_string[1].split("_", 1) if int(note_info[0][-1]) == 3: notepart = letterToNote[note_info[0][:-1]] +\ lengthToNum[note_info[1]] elif int(note_info[0][-1]) < 3: notepart = letterToNote[note_info[0][:-1]] +\ (3 - int(note_info[0][-1])) * "," + lengthToNum[note_info[1]] elif int(note_info[0][-1]) > 3: notepart = letterToNote[note_info[0][:-1]] +\ (int(note_info[0][-1]) - 3) * "\'" + lengthToNum[note_info[1]] return "\\grace { " + notepart + " }" elif divided_string[0] == "tie": return "~" else: return "% could not find a match for the musical element" + toparse def generate_music(model_output, piece_title): """ calls the parser to parse the input, sends it to a LilyPond file to generate a PDF inputs: model_output -- string output produced by the semantic model piece_title -- title of the piece, which becomes the filename outputs: TODO """ element_list = model_output.split("\n") lilyPond = "\\version \"2.20.0\" \n\header{\n title = \"" +\ piece_title + "\"\n}\n\\score{ {\n" # f = open(piece_title + ".ly", "w+") # f.write("\\version \"2.20.0\" \n\header{\n title = \"" + piece_title + "\"\n}\n\\score{ {\n") for x in range(len(element_list)-1): next_elem = parser(element_list[x]) print(next_elem) lilyPond += next_elem # f.write(parser(element_list[x])) lilyPond += "} \n \\midi{} \n \\layout{} }" return lilyPond # f.write("\\midi{} \n \\layout{} }") # f.close()
class PyDisFishError(Exception): """Base error class for the module""" pass class FetchError(PyDisFishError): """Error that's raised when _fetch_list() fails This is probably something either on your end or discord's """ pass class NotReady(PyDisFishError): """Error that's raised when trying to check a URL before Phisherman is ready you should use Phisherman.ready to tell when the domain list has been fetched """ pass
# 2019-01-31 # number sorting and reading in list score = [[80, 85, 90], [82, 87, 92], [75, 92, 84]] for i in range(len(score)): student = score[i] score_sum = 0 for j in student: score_sum += j # append the sum of scores score[i] = [score_sum] + score[i] # sorts the students according to the total sum number score.sort(reverse=True) for s in score: print(s[0], s[1], s[2], s[3])
mysql={ 'host':"localhost", 'user':'root', 'password':'Liscannor10', 'database': 'datarepresentation' }
# Soma ímpares múltiplos de três soma = 0 x = 0 for i in range(1, 501, 2): if i % 3 == 0: x += 1 soma += i print(f"A soma dos {x} valores e {soma} ")
d = dict() d['0']='O' d['1']='l' d['3']='E' d['4']='A' d['5']='S' d['6']='G' d['8']='B' d['9']='g' s = input() for c in s: print(d[c] if c in d else c, end='')
MIN_SQUARE = 0 MAX_SQUARE = 63 MAX_INT = 2 ** 64 - 1 STARTING_FEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" # DIRECTIONS NORTH = 8 EAST = 1 SOUTH = -8 WEST = -1 NE = 9 SE = -7 SW = -9 NW = 7 NWW = NW + WEST NNW = NORTH + NW NNE = NORTH + NE NEE = NE + EAST SEE = SE + EAST SSE = SOUTH + SE SSW = SOUTH + SW SWW = SW + WEST INFINITY = float("inf") MAX_PLY = 31 QUIESCENCE_SEARCH_DEPTH_PLY = 5
num = input()[::-1] # num = num[::-1] for i in num: if int(i)==0: print("ZERO") else: symbol = chr(int(i) + 33) print(symbol*int(i))
""" Faça uma função e um programa de teste para o cálculo do volume de uma esfera. Sendo que o raio é passado por parâmetro: V = 4/3 * π * R³ 3.14159265 Doctests: >>> volumecir(50) 523598.33 >>> volumecir(12) 7238.22 >>> volumecir(87) 2758328.59 >>> volumecir(5) 523.60 """ def volumecir(raio: int): resp = float((4 * 3.14159265 * raio ** 3) / 3) # resp = f'{resp:.2f}' # resp = float(resp) return resp
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'targets': [ { 'target_name': 'libwebp_dec', 'type': 'static_library', 'dependencies' : [ 'libwebp_dsp', 'libwebp_dsp_neon', 'libwebp_utils', ], 'include_dirs': ['.'], 'sources': [ '<(DEPTH)/third_party/libwebp/src/dec/alpha.c', '<(DEPTH)/third_party/libwebp/src/dec/buffer.c', '<(DEPTH)/third_party/libwebp/src/dec/frame.c', '<(DEPTH)/third_party/libwebp/src/dec/idec.c', '<(DEPTH)/third_party/libwebp/src/dec/io.c', '<(DEPTH)/third_party/libwebp/src/dec/quant.c', '<(DEPTH)/third_party/libwebp/src/dec/tree.c', '<(DEPTH)/third_party/libwebp/src/dec/vp8.c', '<(DEPTH)/third_party/libwebp/src/dec/vp8l.c', '<(DEPTH)/third_party/libwebp/src/dec/webp.c', ], }, { 'target_name': 'libwebp_demux', 'type': 'static_library', 'include_dirs': ['.'], 'sources': [ 'demux/demux.c', ], }, { 'target_name': 'libwebp_dsp', 'type': 'static_library', 'include_dirs': ['.'], 'sources': [ '<(DEPTH)/third_party/libwebp/src/dsp/alpha_processing.c', '<(DEPTH)/third_party/libwebp/src/dsp/cpu.c', '<(DEPTH)/third_party/libwebp/src/dsp/dec.c', '<(DEPTH)/third_party/libwebp/src/dsp/dec_clip_tables.c', '<(DEPTH)/third_party/libwebp/src/dsp/dec_mips32.c', '<(DEPTH)/third_party/libwebp/src/dsp/dec_sse2.c', '<(DEPTH)/third_party/libwebp/src/dsp/enc.c', '<(DEPTH)/third_party/libwebp/src/dsp/enc_avx2.c', '<(DEPTH)/third_party/libwebp/src/dsp/enc_mips32.c', '<(DEPTH)/third_party/libwebp/src/dsp/enc_sse2.c', '<(DEPTH)/third_party/libwebp/src/dsp/lossless.c', '<(DEPTH)/third_party/libwebp/src/dsp/lossless_mips32.c', '<(DEPTH)/third_party/libwebp/src/dsp/lossless_sse2.c', '<(DEPTH)/third_party/libwebp/src/dsp/upsampling.c', '<(DEPTH)/third_party/libwebp/src/dsp/upsampling_sse2.c', '<(DEPTH)/third_party/libwebp/src/dsp/yuv.c', '<(DEPTH)/third_party/libwebp/src/dsp/yuv_mips32.c', '<(DEPTH)/third_party/libwebp/src/dsp/yuv_sse2.c', ], # 'conditions': [ # ['OS == "android"', { # 'includes': [ 'android/cpufeatures.gypi' ], # }], # ['order_profiling != 0', { # 'target_conditions' : [ # ['_toolset=="target"', { # 'cflags!': [ '-finstrument-functions' ], # }], # ], # }], # ], }, { 'target_name': 'libwebp_dsp_neon', 'conditions': [ ['target_arch == "arm" and arm_version >= 7 and (arm_neon == 1 or arm_neon_optional == 1)', { 'type': 'static_library', 'include_dirs': ['.'], 'sources': [ '<(DEPTH)/third_party/libwebp/src/dsp/dec_neon.c', '<(DEPTH)/third_party/libwebp/src/dsp/enc_neon.c', '<(DEPTH)/third_party/libwebp/src/dsp/lossless_neon.c', '<(DEPTH)/third_party/libwebp/src/dsp/upsampling_neon.c', ], # behavior similar to *.c.neon in an Android.mk 'cflags!': [ '-mfpu=vfpv3-d16' ], 'cflags': [ '-mfpu=neon' ], },{ # "target_arch != "arm" or arm_version < 7" 'type': 'none', }], ['order_profiling != 0', { 'target_conditions' : [ ['_toolset=="target"', { 'cflags!': [ '-finstrument-functions' ], }], ], }], ], }, { 'target_name': 'libwebp_enc', 'type': 'static_library', 'include_dirs': ['.'], 'sources': [ '<(DEPTH)/third_party/libwebp/src/enc/alpha.c', '<(DEPTH)/third_party/libwebp/src/enc/analysis.c', '<(DEPTH)/third_party/libwebp/src/enc/backward_references.c', '<(DEPTH)/third_party/libwebp/src/enc/config.c', '<(DEPTH)/third_party/libwebp/src/enc/cost.c', '<(DEPTH)/third_party/libwebp/src/enc/filter.c', '<(DEPTH)/third_party/libwebp/src/enc/frame.c', '<(DEPTH)/third_party/libwebp/src/enc/histogram.c', '<(DEPTH)/third_party/libwebp/src/enc/iterator.c', '<(DEPTH)/third_party/libwebp/src/enc/picture.c', '<(DEPTH)/third_party/libwebp/src/enc/picture_csp.c', '<(DEPTH)/third_party/libwebp/src/enc/picture_psnr.c', '<(DEPTH)/third_party/libwebp/src/enc/picture_rescale.c', '<(DEPTH)/third_party/libwebp/src/enc/picture_tools.c', '<(DEPTH)/third_party/libwebp/src/enc/quant.c', '<(DEPTH)/third_party/libwebp/src/enc/syntax.c', '<(DEPTH)/third_party/libwebp/src/enc/token.c', '<(DEPTH)/third_party/libwebp/src/enc/tree.c', '<(DEPTH)/third_party/libwebp/src/enc/vp8l.c', '<(DEPTH)/third_party/libwebp/src/enc/webpenc.c', ], }, { 'target_name': 'libwebp_utils', 'type': 'static_library', 'include_dirs': ['.'], 'sources': [ '<(DEPTH)/third_party/libwebp/src/utils/bit_reader.c', '<(DEPTH)/third_party/libwebp/src/utils/bit_writer.c', '<(DEPTH)/third_party/libwebp/src/utils/color_cache.c', '<(DEPTH)/third_party/libwebp/src/utils/filters.c', '<(DEPTH)/third_party/libwebp/src/utils/huffman.c', '<(DEPTH)/third_party/libwebp/src/utils/huffman_encode.c', '<(DEPTH)/third_party/libwebp/src/utils/quant_levels.c', '<(DEPTH)/third_party/libwebp/src/utils/quant_levels_dec.c', '<(DEPTH)/third_party/libwebp/src/utils/random.c', '<(DEPTH)/third_party/libwebp/src/utils/rescaler.c', '<(DEPTH)/third_party/libwebp/src/utils/thread.c', '<(DEPTH)/third_party/libwebp/src/utils/utils.c', ], }, { 'target_name': 'libwebp_mux', 'type': 'static_library', 'include_dirs': ['.'], 'sources': [ '<(DEPTH)/third_party/libwebp/src/mux/muxedit.c', '<(DEPTH)/third_party/libwebp/src/mux/muxinternal.c', '<(DEPTH)/third_party/libwebp/src/mux/muxread.c', ], }, { 'target_name': 'libwebp_enc_mux', 'type': 'static_library', 'dependencies': [ 'libwebp_mux', ], 'include_dirs': [ '<(DEPTH)/third_party/libwebp/src', ], 'sources': [ '<(DEPTH)/third_party/libwebp/examples/gif2webp_util.c', ], }, { 'target_name': 'libwebp', 'type': 'none', 'dependencies' : [ 'libwebp_dec', 'libwebp_demux', 'libwebp_dsp', 'libwebp_dsp_neon', 'libwebp_enc', 'libwebp_enc_mux', 'libwebp_utils', ], 'direct_dependent_settings': { 'include_dirs': ['.'], }, 'conditions': [ ['OS!="win"', {'product_name': 'webp'}], ], }, ], }
class CronDayOfWeek(int): """ Job Manager cron scheduling day of week. Zero represents Sunday. -1 represents all days of a week and only supported for cron schedule create and modify. Range : [-1..6]. """ @staticmethod def get_api_name(): return "cron-day-of-week"
class Solution: def isPowerOfFour1(self, num): """ :type num: int :rtype: bool """ x = 1 while x != num: if x < num: x <<= 2 else: return False return True def isPowerOfFour2(self, num): """ :type num: int :rtype: bool """ return num > 0 and (num & (num - 1)) == 0 and (num & 0b01010101010101010101010101010101) == num