content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
# # MIT License # # brutemind framework for python # Copyright (C) 2018 Michael Lin, Valeriy Garnaga # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. class Data(object): DATA_URL = "http://fremont1.cto911.com/esdoc/data/" def __init__(self, inputTrainCsvZipUrl, outputTrainCsvZipUrl, inputTestCsvZipUrl, outputTestCsvZipUrl, zipPassword=None, refreshData=True): self.inputTrainCsvZipUrl = inputTrainCsvZipUrl self.outputTrainCsvZipUrl = outputTrainCsvZipUrl self.inputTestCsvZipUrl = inputTestCsvZipUrl self.outputTestCsvZipUrl = outputTestCsvZipUrl self.zipPassword = zipPassword self.refreshData = refreshData def load_valuation(refresh_data=True): inputTrainCsvZipUrl = '{}valuation_train_inputs.zip'.format(Data.DATA_URL) outputTrainCsvZipUrl = '{}valuation_train_outputs.zip'.format(Data.DATA_URL) inputTestCsvZipUrl = None outputTestCsvZipUrl = None return Data(inputTrainCsvZipUrl, outputTrainCsvZipUrl, inputTestCsvZipUrl, outputTestCsvZipUrl, refresh_data) def load_iris(refresh_data=True): inputTrainCsvZipUrl = '{}iris_train_inputs.zip'.format(Data.DATA_URL) outputTrainCsvZipUrl = '{}iris_train_outputs.zip'.format(Data.DATA_URL) inputTestCsvZipUrl = None outputTestCsvZipUrl = None return Data(inputTrainCsvZipUrl, outputTrainCsvZipUrl, inputTestCsvZipUrl, outputTestCsvZipUrl, refresh_data) def load_diabetes(refresh_data=True): inputTrainCsvZipUrl = '{}diabetes_train_inputs.zip'.format(Data.DATA_URL) outputTrainCsvZipUrl = '{}diabetes_train_outputs.zip'.format(Data.DATA_URL) inputTestCsvZipUrl = None outputTestCsvZipUrl = None return Data(inputTrainCsvZipUrl, outputTrainCsvZipUrl, inputTestCsvZipUrl, outputTestCsvZipUrl, refresh_data) def load_mnist(refresh_data=True): inputTrainCsvZipUrl = '{}mnist_train_inputs.zip'.format(Data.DATA_URL) outputTrainCsvZipUrl = '{}mnist_train_outputs.zip'.format(Data.DATA_URL) inputTestCsvZipUrl = '{}mnist_test_inputs.zip'.format(Data.DATA_URL) outputTestCsvZipUrl = '{}mnist_test_outputs.zip'.format(Data.DATA_URL) return Data(inputTrainCsvZipUrl, outputTrainCsvZipUrl, inputTestCsvZipUrl, outputTestCsvZipUrl, refresh_data)
class Data(object): data_url = 'http://fremont1.cto911.com/esdoc/data/' def __init__(self, inputTrainCsvZipUrl, outputTrainCsvZipUrl, inputTestCsvZipUrl, outputTestCsvZipUrl, zipPassword=None, refreshData=True): self.inputTrainCsvZipUrl = inputTrainCsvZipUrl self.outputTrainCsvZipUrl = outputTrainCsvZipUrl self.inputTestCsvZipUrl = inputTestCsvZipUrl self.outputTestCsvZipUrl = outputTestCsvZipUrl self.zipPassword = zipPassword self.refreshData = refreshData def load_valuation(refresh_data=True): input_train_csv_zip_url = '{}valuation_train_inputs.zip'.format(Data.DATA_URL) output_train_csv_zip_url = '{}valuation_train_outputs.zip'.format(Data.DATA_URL) input_test_csv_zip_url = None output_test_csv_zip_url = None return data(inputTrainCsvZipUrl, outputTrainCsvZipUrl, inputTestCsvZipUrl, outputTestCsvZipUrl, refresh_data) def load_iris(refresh_data=True): input_train_csv_zip_url = '{}iris_train_inputs.zip'.format(Data.DATA_URL) output_train_csv_zip_url = '{}iris_train_outputs.zip'.format(Data.DATA_URL) input_test_csv_zip_url = None output_test_csv_zip_url = None return data(inputTrainCsvZipUrl, outputTrainCsvZipUrl, inputTestCsvZipUrl, outputTestCsvZipUrl, refresh_data) def load_diabetes(refresh_data=True): input_train_csv_zip_url = '{}diabetes_train_inputs.zip'.format(Data.DATA_URL) output_train_csv_zip_url = '{}diabetes_train_outputs.zip'.format(Data.DATA_URL) input_test_csv_zip_url = None output_test_csv_zip_url = None return data(inputTrainCsvZipUrl, outputTrainCsvZipUrl, inputTestCsvZipUrl, outputTestCsvZipUrl, refresh_data) def load_mnist(refresh_data=True): input_train_csv_zip_url = '{}mnist_train_inputs.zip'.format(Data.DATA_URL) output_train_csv_zip_url = '{}mnist_train_outputs.zip'.format(Data.DATA_URL) input_test_csv_zip_url = '{}mnist_test_inputs.zip'.format(Data.DATA_URL) output_test_csv_zip_url = '{}mnist_test_outputs.zip'.format(Data.DATA_URL) return data(inputTrainCsvZipUrl, outputTrainCsvZipUrl, inputTestCsvZipUrl, outputTestCsvZipUrl, refresh_data)
class Solution: def arrangeCoins(self, n: int) -> int: res =1 while res*(res+1)<=2*n: res +=1 res-=1 return res
class Solution: def arrange_coins(self, n: int) -> int: res = 1 while res * (res + 1) <= 2 * n: res += 1 res -= 1 return res
# # PySNMP MIB module Unisphere-Data-MPLS-CONF (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Unisphere-Data-MPLS-CONF # Produced by pysmi-0.3.4 at Mon Apr 29 21:24:50 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, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ConstraintsIntersection, SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsIntersection", "SingleValueConstraint", "ConstraintsUnion", "ValueSizeConstraint") AgentCapabilities, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "AgentCapabilities", "NotificationGroup", "ModuleCompliance") ObjectIdentity, MibIdentifier, Unsigned32, TimeTicks, Counter32, Integer32, Bits, Counter64, NotificationType, ModuleIdentity, iso, MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "ObjectIdentity", "MibIdentifier", "Unsigned32", "TimeTicks", "Counter32", "Integer32", "Bits", "Counter64", "NotificationType", "ModuleIdentity", "iso", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Gauge32", "IpAddress") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") usDataAgents, = mibBuilder.importSymbols("Unisphere-Data-Agents", "usDataAgents") usdMplsMinorLayerConfGroup, usdMplsExplicitPathConfGroup, usdMplsTunnelProfileConfGroup, usdMplsLsrGlobalConfGroup, usdMplsMajorLayerConfGroup = mibBuilder.importSymbols("Unisphere-Data-MPLS-MIB", "usdMplsMinorLayerConfGroup", "usdMplsExplicitPathConfGroup", "usdMplsTunnelProfileConfGroup", "usdMplsLsrGlobalConfGroup", "usdMplsMajorLayerConfGroup") usdMplsAgent = ModuleIdentity((1, 3, 6, 1, 4, 1, 4874, 5, 2, 51)) usdMplsAgent.setRevisions(('2001-12-05 21:41',)) if mibBuilder.loadTexts: usdMplsAgent.setLastUpdated('200112052141Z') if mibBuilder.loadTexts: usdMplsAgent.setOrganization('Unisphere Networks, Inc.') usdMplsAgentV1 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 51, 1)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): usdMplsAgentV1 = usdMplsAgentV1.setProductRelease('Version 1 of the MultiProtocol Label Switching (MPLS) component of the\n Unisphere Routing Switch SNMP agent. This version of the MPLS component\n is supported in the Unisphere RX 4.0 and subsequent system releases.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): usdMplsAgentV1 = usdMplsAgentV1.setStatus('current') mibBuilder.exportSymbols("Unisphere-Data-MPLS-CONF", usdMplsAgentV1=usdMplsAgentV1, PYSNMP_MODULE_ID=usdMplsAgent, usdMplsAgent=usdMplsAgent)
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, constraints_intersection, single_value_constraint, constraints_union, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ConstraintsIntersection', 'SingleValueConstraint', 'ConstraintsUnion', 'ValueSizeConstraint') (agent_capabilities, notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'AgentCapabilities', 'NotificationGroup', 'ModuleCompliance') (object_identity, mib_identifier, unsigned32, time_ticks, counter32, integer32, bits, counter64, notification_type, module_identity, iso, mib_scalar, mib_table, mib_table_row, mib_table_column, gauge32, ip_address) = mibBuilder.importSymbols('SNMPv2-SMI', 'ObjectIdentity', 'MibIdentifier', 'Unsigned32', 'TimeTicks', 'Counter32', 'Integer32', 'Bits', 'Counter64', 'NotificationType', 'ModuleIdentity', 'iso', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Gauge32', 'IpAddress') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') (us_data_agents,) = mibBuilder.importSymbols('Unisphere-Data-Agents', 'usDataAgents') (usd_mpls_minor_layer_conf_group, usd_mpls_explicit_path_conf_group, usd_mpls_tunnel_profile_conf_group, usd_mpls_lsr_global_conf_group, usd_mpls_major_layer_conf_group) = mibBuilder.importSymbols('Unisphere-Data-MPLS-MIB', 'usdMplsMinorLayerConfGroup', 'usdMplsExplicitPathConfGroup', 'usdMplsTunnelProfileConfGroup', 'usdMplsLsrGlobalConfGroup', 'usdMplsMajorLayerConfGroup') usd_mpls_agent = module_identity((1, 3, 6, 1, 4, 1, 4874, 5, 2, 51)) usdMplsAgent.setRevisions(('2001-12-05 21:41',)) if mibBuilder.loadTexts: usdMplsAgent.setLastUpdated('200112052141Z') if mibBuilder.loadTexts: usdMplsAgent.setOrganization('Unisphere Networks, Inc.') usd_mpls_agent_v1 = agent_capabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 51, 1)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): usd_mpls_agent_v1 = usdMplsAgentV1.setProductRelease('Version 1 of the MultiProtocol Label Switching (MPLS) component of the\n Unisphere Routing Switch SNMP agent. This version of the MPLS component\n is supported in the Unisphere RX 4.0 and subsequent system releases.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): usd_mpls_agent_v1 = usdMplsAgentV1.setStatus('current') mibBuilder.exportSymbols('Unisphere-Data-MPLS-CONF', usdMplsAgentV1=usdMplsAgentV1, PYSNMP_MODULE_ID=usdMplsAgent, usdMplsAgent=usdMplsAgent)
# coding=utf-8 class App: TESTING = True SQLALCHEMY_DATABASE_URI = 'mysql://lvye_pay:p@55word@127.0.0.1:3306/lvye_pay' SQLALCHEMY_ECHO = True class Biz: VALID_NETLOCS = ['test_pay.lvye.com:5100'] HOST_URL = 'http://test_pay.lvye.com:5100' CHECKOUT_URL = 'http://dev_pay.lvye.com:5102/checkout/{sn}' TEST_CHANNELS = {'zyt_sample'}
class App: testing = True sqlalchemy_database_uri = 'mysql://lvye_pay:p@55word@127.0.0.1:3306/lvye_pay' sqlalchemy_echo = True class Biz: valid_netlocs = ['test_pay.lvye.com:5100'] host_url = 'http://test_pay.lvye.com:5100' checkout_url = 'http://dev_pay.lvye.com:5102/checkout/{sn}' test_channels = {'zyt_sample'}
# 1 grafo = [ { "vertice": 'a', "arestas": ['c', 'd', 'f'] }, { "vertice": 'b', "arestas": ['d', 'e'] }, { "vertice": 'c', "arestas": ['a', 'f'] }, { "vertice": 'd', "arestas": ['a', 'b', 'e', 'f'] }, { "vertice": 'e', "arestas": ['b', 'd'] }, { "vertice": 'f', "arestas": ['a', 'c', 'd'] }, { "vertice": 'g', "arestas": [] } ] for i in grafo: print(i)
grafo = [{'vertice': 'a', 'arestas': ['c', 'd', 'f']}, {'vertice': 'b', 'arestas': ['d', 'e']}, {'vertice': 'c', 'arestas': ['a', 'f']}, {'vertice': 'd', 'arestas': ['a', 'b', 'e', 'f']}, {'vertice': 'e', 'arestas': ['b', 'd']}, {'vertice': 'f', 'arestas': ['a', 'c', 'd']}, {'vertice': 'g', 'arestas': []}] for i in grafo: print(i)
thinkers = ['Plato','PlayDo','Gumby'] while True: try: thinker = thinkers.pop() print(thinker) except IndexError as e: print("We tried to pop too many thinkers") print(e) break
thinkers = ['Plato', 'PlayDo', 'Gumby'] while True: try: thinker = thinkers.pop() print(thinker) except IndexError as e: print('We tried to pop too many thinkers') print(e) break
# Time Complexity : O(n) ; Space Complexity : O(n) # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: nodes = set() while headA: nodes.add(headA) headA = headA.next while headB: if headB in nodes: return headB headB = headB.next return None # Time Complexity : O(2n) ; Space Complexity : O(1) # Constant Space # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: lena,lenb = 0,0 tempa,tempb = headA,headB while tempa: lena += 1 tempa = tempa.next while tempb: lenb += 1 tempb = tempb.next if lena>lenb: for i in range(lena-lenb): headA = headA.next elif lena<lenb: for i in range(lenb-lena): headB = headB.next while headA and headB: if headA == headB: return headA headA = headA.next headB = headB.next return None # Time Complexity : O(2n) ; Space Complexity : O(1) ; TRICKY # Constant Space # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: lena,lenb = 0,0 if headA == None or headB == None: return None A_pointer = headA B_pointer = headB while A_pointer != B_pointer: A_pointer = headB if A_pointer == None else A_pointer.next B_pointer = headA if B_pointer == None else B_pointer.next return A_pointer
class Solution: def get_intersection_node(self, headA: ListNode, headB: ListNode) -> ListNode: nodes = set() while headA: nodes.add(headA) head_a = headA.next while headB: if headB in nodes: return headB head_b = headB.next return None class Solution: def get_intersection_node(self, headA: ListNode, headB: ListNode) -> ListNode: (lena, lenb) = (0, 0) (tempa, tempb) = (headA, headB) while tempa: lena += 1 tempa = tempa.next while tempb: lenb += 1 tempb = tempb.next if lena > lenb: for i in range(lena - lenb): head_a = headA.next elif lena < lenb: for i in range(lenb - lena): head_b = headB.next while headA and headB: if headA == headB: return headA head_a = headA.next head_b = headB.next return None class Solution: def get_intersection_node(self, headA: ListNode, headB: ListNode) -> ListNode: (lena, lenb) = (0, 0) if headA == None or headB == None: return None a_pointer = headA b_pointer = headB while A_pointer != B_pointer: a_pointer = headB if A_pointer == None else A_pointer.next b_pointer = headA if B_pointer == None else B_pointer.next return A_pointer
_YES_ANSWERS_ = ["y","yes"] _NO_ANSWERS_ = ["n", "no"] def getInput(_string): val = raw_input(_string) return val def getYesNoAnswer(_string): while True: val = raw_input(_string).lower() if val in _YES_ANSWERS_: return True if val in _NO_ANSWERS_: return False
_yes_answers_ = ['y', 'yes'] _no_answers_ = ['n', 'no'] def get_input(_string): val = raw_input(_string) return val def get_yes_no_answer(_string): while True: val = raw_input(_string).lower() if val in _YES_ANSWERS_: return True if val in _NO_ANSWERS_: return False
#!/usr/bin/env python3 # File: xRpcFaker.py def SayHello(token): return f"Hello {token}!"
def say_hello(token): return f'Hello {token}!'
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] b = [even for even in a if even % 2 == 0] print(b) c = [even*3 for even in a] print(c)
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] b = [even for even in a if even % 2 == 0] print(b) c = [even * 3 for even in a] print(c)
class Fenwick_Tree: def __init__(self, size): self.size = size + 1 self.array = [0 for _ in range(self.size)] def __len__(self): ''' Called when len is called on object ''' return self.size def lsb(self, index:int) -> int: ''' Returns integer value of least significant bit which is 1 If index is 352(101100000), then return value is 32(100000) ''' return index & -index def prev(self, index:int) -> int: ''' Returns last index whose element is added to element at given index ''' return index - self.lsb(index) def next(self, index:int) -> int: ''' Returns next index where element of current index is added ''' return index + self.lsb(index) def check_index(self, index:int) -> None: ''' Index bound checking Throws an exception if index is out of bounds ''' if index < 0 or index >= self.size: raise ValueError("Index out of bounds") def array_to_fenwick(self, array:list) -> None: ''' Converts the given array into a Fenwick array Writes over the data present in the object before calling this function ''' self.size = len(array) + 1 self.array = [0] for i in array: self.array.append(i) for i in range(1, self.size): next_index = self.next(i) if next_index < self.size: self.array[next_index] += self.array[i] def add(self, index:int, value:int) -> None: ''' Adds value to element at index and updates the Fenwick tree accordingly ''' index += 1 self.check_index(index) while index < self.size: self.array[index] += value index = self.next(index) def insert(self, index:int, value:int) -> None: ''' Replaces old value at index with given value ''' self.add(index, value - self.get_value_at(index)) def range_sum(self, left:int, right:int) -> int: ''' Gets the sum of all elements between left index (inclusive) and right index( exclusive) ''' if left > right: left, right = right, left self.check_index(left) self.check_index(right) s = 0 while right > left: s += self.array[right] right = self.prev(right) while left > right: s -= self.array[left] left = self.prev(left) return s def prefix_sum(self, index:int): ''' Gets the sum of all elements between first element and (index - 1)th element ''' self.check_index(index) s = 0 while index > 0: s += self.array[index] index = self.prev(index) return s def get_value_at(self, index:int) -> int: ''' Gets the value at the given index ''' return self.range_sum(index, index + 1) def get_array(self) -> list: ''' Returns the orginal values of array ''' array = self.array.copy() for i in range(self.size - 1, 0, -1): next_index = self.next(i) if next_index < self.size: array[next_index] -= array[i] array.pop(0) return array
class Fenwick_Tree: def __init__(self, size): self.size = size + 1 self.array = [0 for _ in range(self.size)] def __len__(self): """ Called when len is called on object """ return self.size def lsb(self, index: int) -> int: """ Returns integer value of least significant bit which is 1 If index is 352(101100000), then return value is 32(100000) """ return index & -index def prev(self, index: int) -> int: """ Returns last index whose element is added to element at given index """ return index - self.lsb(index) def next(self, index: int) -> int: """ Returns next index where element of current index is added """ return index + self.lsb(index) def check_index(self, index: int) -> None: """ Index bound checking Throws an exception if index is out of bounds """ if index < 0 or index >= self.size: raise value_error('Index out of bounds') def array_to_fenwick(self, array: list) -> None: """ Converts the given array into a Fenwick array Writes over the data present in the object before calling this function """ self.size = len(array) + 1 self.array = [0] for i in array: self.array.append(i) for i in range(1, self.size): next_index = self.next(i) if next_index < self.size: self.array[next_index] += self.array[i] def add(self, index: int, value: int) -> None: """ Adds value to element at index and updates the Fenwick tree accordingly """ index += 1 self.check_index(index) while index < self.size: self.array[index] += value index = self.next(index) def insert(self, index: int, value: int) -> None: """ Replaces old value at index with given value """ self.add(index, value - self.get_value_at(index)) def range_sum(self, left: int, right: int) -> int: """ Gets the sum of all elements between left index (inclusive) and right index( exclusive) """ if left > right: (left, right) = (right, left) self.check_index(left) self.check_index(right) s = 0 while right > left: s += self.array[right] right = self.prev(right) while left > right: s -= self.array[left] left = self.prev(left) return s def prefix_sum(self, index: int): """ Gets the sum of all elements between first element and (index - 1)th element """ self.check_index(index) s = 0 while index > 0: s += self.array[index] index = self.prev(index) return s def get_value_at(self, index: int) -> int: """ Gets the value at the given index """ return self.range_sum(index, index + 1) def get_array(self) -> list: """ Returns the orginal values of array """ array = self.array.copy() for i in range(self.size - 1, 0, -1): next_index = self.next(i) if next_index < self.size: array[next_index] -= array[i] array.pop(0) return array
class NofieldnameField(object): pass class FieldnameField(object): fieldname = 'hello' class RepeatedFieldnameField(FieldnameField): pass
class Nofieldnamefield(object): pass class Fieldnamefield(object): fieldname = 'hello' class Repeatedfieldnamefield(FieldnameField): pass
# ## ADD THIS TO YOUR .gitignore FILE ## # APPLICATION_TITLE = 'WikiGenomes' # DJango Secret key secret_key = '<django secret key>' # OAUTH Consumer Credentials---you must register a consumer at consumer_key = '<wikimedia oauth consumer key>' consumer_secret = '<wikimedia oauth consumer secret>' # Configurations for django settings.py # ALLOWED_HOSTS add IP or domain name to list. allowed_hosts = ['wikigenomes.org'] # TIME_ZONE wg_timezone = 'America/Los_Angeles' # ## Application customization ## # ## Taxids of the organisms that will included in the instance # ## If left blank, the 120 bacterial reference genomes https://www.ncbi.nlm.nih.gov/genome/browse/reference/ that currently populate WikiGenomes # ## You may also provide a list of taxids from the list of representative species at NCBI RefSeq at the same url # ## - to get the desired taxids into Wikidata for use in your WikiGenomes instance, create an issue at https://github.com/SuLab/scheduled-bots # ## providing the list of taxids, the name and a brief description of your application. You will then be notified through GitHub when the issue is resolved # ## when the genomes, thier genes an proteins have been loaded to Wikidata taxids = []
application_title = 'WikiGenomes' secret_key = '<django secret key>' consumer_key = '<wikimedia oauth consumer key>' consumer_secret = '<wikimedia oauth consumer secret>' allowed_hosts = ['wikigenomes.org'] wg_timezone = 'America/Los_Angeles' taxids = []
name = 'AL_USDMaya' version = '0.0.1' uuid = 'c1c2376f-3640-4046-b55e-f11461431f34' authors = ['AnimalLogic'] description = 'USD to Maya translator. This rez package is purely an example and should be modifyed to your own needs' private_build_requires = [ 'cmake-2.8+', 'gcc-4.8', 'gdb-7.10' ] requires = [ 'usd-0.7', 'usdImaging-0.7', 'glew-2.0', 'python-2.7+<3', 'doubleConversion-1', 'stdlib-4.8', 'zlib-1.2', 'googletest', ] variants = [ ['CentOS-6.2+<7'] ] def commands(): prependenv('PATH', '{root}/src') prependenv('PYTHONPATH', '{root}/lib/python') prependenv('LD_LIBRARY_PATH', '{root}/lib') prependenv('MAYA_PLUG_IN_PATH', '{root}/plugin') prependenv('MAYA_SCRIPT_PATH', '{root}/lib:{root}/share/usd/plugins/usdMaya/resources') prependenv('PXR_PLUGINPATH', '{root}/share/usd/plugins') prependenv('CMAKE_MODULE_PATH', '{root}/cmake')
name = 'AL_USDMaya' version = '0.0.1' uuid = 'c1c2376f-3640-4046-b55e-f11461431f34' authors = ['AnimalLogic'] description = 'USD to Maya translator. This rez package is purely an example and should be modifyed to your own needs' private_build_requires = ['cmake-2.8+', 'gcc-4.8', 'gdb-7.10'] requires = ['usd-0.7', 'usdImaging-0.7', 'glew-2.0', 'python-2.7+<3', 'doubleConversion-1', 'stdlib-4.8', 'zlib-1.2', 'googletest'] variants = [['CentOS-6.2+<7']] def commands(): prependenv('PATH', '{root}/src') prependenv('PYTHONPATH', '{root}/lib/python') prependenv('LD_LIBRARY_PATH', '{root}/lib') prependenv('MAYA_PLUG_IN_PATH', '{root}/plugin') prependenv('MAYA_SCRIPT_PATH', '{root}/lib:{root}/share/usd/plugins/usdMaya/resources') prependenv('PXR_PLUGINPATH', '{root}/share/usd/plugins') prependenv('CMAKE_MODULE_PATH', '{root}/cmake')
def findMatching(numbers, value): for number1 in numbers: for number2 in numbers: variables = [number1, number2] if (len(set(variables)) != len(variables)): continue if number1 + number2 == value: print("{} + {} = {}, {} * {} = {}".format(number1,number2,value,number1,number2,number1*number2)) return numbers = [] with open("./1/input.txt") as inputFile: for line in inputFile: numbers.append(int(line)) findMatching(numbers, 2020)
def find_matching(numbers, value): for number1 in numbers: for number2 in numbers: variables = [number1, number2] if len(set(variables)) != len(variables): continue if number1 + number2 == value: print('{} + {} = {}, {} * {} = {}'.format(number1, number2, value, number1, number2, number1 * number2)) return numbers = [] with open('./1/input.txt') as input_file: for line in inputFile: numbers.append(int(line)) find_matching(numbers, 2020)
def triangle_reduce(triangle): last = triangle.pop() for i, n in enumerate(triangle[-1]): if last[i] > last[i+1]: triangle[-1][i] = triangle[-1][i] + last[i] else: triangle[-1][i] = triangle[-1][i] + last[i+1] return triangle def solve(triangle): while len(triangle) > 1: triangle = triangle_reduce(triangle) return triangle[0][0]
def triangle_reduce(triangle): last = triangle.pop() for (i, n) in enumerate(triangle[-1]): if last[i] > last[i + 1]: triangle[-1][i] = triangle[-1][i] + last[i] else: triangle[-1][i] = triangle[-1][i] + last[i + 1] return triangle def solve(triangle): while len(triangle) > 1: triangle = triangle_reduce(triangle) return triangle[0][0]
class GoogleCredentialsException(Exception): def __init__(self): message = "GCP_JSON or GCP_B64 env variable not set properly" super().__init__(message) class TaskNotFound(Exception): def __init__(self, name: str): message = f"Task {name} not registered." super().__init__(message)
class Googlecredentialsexception(Exception): def __init__(self): message = 'GCP_JSON or GCP_B64 env variable not set properly' super().__init__(message) class Tasknotfound(Exception): def __init__(self, name: str): message = f'Task {name} not registered.' super().__init__(message)
s = "kBNCR9joiFtdAv19AhJ0mHVKassinaPSifCT5bnIrindoudUarwnZxwclalDWjgYudhVD5Sf3Z7looEZCuKQaBIAYTEKn0kQnm2rbwp3KLYsemipalmatusENYyIr6BvCNbuYXeDPFh49tBZQg2Hhw7QrPrAVpyo4RMRRIulZUMBhVNnK1kHFdFM3wxVsvBo3Kq6." a = 23 b = 29 c = 107 d = 118 print (s[a:b + 1] + " " + s[c:d + 1])
s = 'kBNCR9joiFtdAv19AhJ0mHVKassinaPSifCT5bnIrindoudUarwnZxwclalDWjgYudhVD5Sf3Z7looEZCuKQaBIAYTEKn0kQnm2rbwp3KLYsemipalmatusENYyIr6BvCNbuYXeDPFh49tBZQg2Hhw7QrPrAVpyo4RMRRIulZUMBhVNnK1kHFdFM3wxVsvBo3Kq6.' a = 23 b = 29 c = 107 d = 118 print(s[a:b + 1] + ' ' + s[c:d + 1])
def rotate(list, n): return list[n:] + list[:n] def filter_equal_values(lhs, rhs): return [a for a, b in zip(lhs, rhs) if a == b] def sum_as_integers(list_of_strings): return sum(map(int, list_of_strings)) def part_one(input): lhs = list(input) rhs = rotate(lhs, 1) values = filter_equal_values(lhs, rhs) return sum_as_integers(values) def part_two(input): lhs = list(input) rhs = rotate(lhs, len(lhs) // 2) values = filter_equal_values(lhs, rhs) return sum_as_integers(values) if __name__ == "__main__": input = '9513446799636685297929646689682997114316733445451534532351778534251427172168183621874641711534917291674333857423799375512628489423332297538215855176592633692631974822259161766238385922277893623911332569448978771948316155868781496698895492971356383996932885518732997624253678694279666572149831616312497994856288871586777793459926952491318336997159553714584541897294117487641872629796825583725975692264125865827534677223541484795877371955124463989228886498682421539667224963783616245646832154384756663251487668681425754536722827563651327524674183443696227523828832466473538347472991998913211857749878157579176457395375632995576569388455888156465451723693767887681392547189273391948632726499868313747261828186732986628365773728583387184112323696592536446536231376615949825166773536471531487969852535699774113163667286537193767515119362865141925612849443983484245268194842563154567638354645735331855896155142741664246715666899824364722914296492444672653852387389477634257768229772399416521198625393426443499223611843766134883441223328256883497423324753229392393974622181429913535973327323952241674979677481518733692544535323219895684629719868384266425386835539719237716339198485163916562434854579365958111931354576991558771236977242668756782139961638347251644828724786827751748399123668854393894787851872256667336215726674348886747128237416273154988619267824361227888751562445622387695218161341884756795223464751862965655559143779425283154533252573949165492138175581615176611845489857169132936848668646319955661492488428427435269169173654812114842568381636982389224236455633316898178163297452453296667661849622174541778669494388167451186352488555379581934999276412919598411422973399319799937518713422398874326665375216437246445791623283898584648278989674418242112957668397484671119761553847275799873495363759266296477844157237423239163559391553961176475377151369399646747881452252547741718734949967752564774161341784833521492494243662658471121369649641815562327698395293573991648351369767162642763475561544795982183714447737149239846151871434656618825566387329765118727515699213962477996399781652131918996434125559698427945714572488376342126989157872118279163127742349' print(part_one(input)) print(part_two(input))
def rotate(list, n): return list[n:] + list[:n] def filter_equal_values(lhs, rhs): return [a for (a, b) in zip(lhs, rhs) if a == b] def sum_as_integers(list_of_strings): return sum(map(int, list_of_strings)) def part_one(input): lhs = list(input) rhs = rotate(lhs, 1) values = filter_equal_values(lhs, rhs) return sum_as_integers(values) def part_two(input): lhs = list(input) rhs = rotate(lhs, len(lhs) // 2) values = filter_equal_values(lhs, rhs) return sum_as_integers(values) if __name__ == '__main__': input = '9513446799636685297929646689682997114316733445451534532351778534251427172168183621874641711534917291674333857423799375512628489423332297538215855176592633692631974822259161766238385922277893623911332569448978771948316155868781496698895492971356383996932885518732997624253678694279666572149831616312497994856288871586777793459926952491318336997159553714584541897294117487641872629796825583725975692264125865827534677223541484795877371955124463989228886498682421539667224963783616245646832154384756663251487668681425754536722827563651327524674183443696227523828832466473538347472991998913211857749878157579176457395375632995576569388455888156465451723693767887681392547189273391948632726499868313747261828186732986628365773728583387184112323696592536446536231376615949825166773536471531487969852535699774113163667286537193767515119362865141925612849443983484245268194842563154567638354645735331855896155142741664246715666899824364722914296492444672653852387389477634257768229772399416521198625393426443499223611843766134883441223328256883497423324753229392393974622181429913535973327323952241674979677481518733692544535323219895684629719868384266425386835539719237716339198485163916562434854579365958111931354576991558771236977242668756782139961638347251644828724786827751748399123668854393894787851872256667336215726674348886747128237416273154988619267824361227888751562445622387695218161341884756795223464751862965655559143779425283154533252573949165492138175581615176611845489857169132936848668646319955661492488428427435269169173654812114842568381636982389224236455633316898178163297452453296667661849622174541778669494388167451186352488555379581934999276412919598411422973399319799937518713422398874326665375216437246445791623283898584648278989674418242112957668397484671119761553847275799873495363759266296477844157237423239163559391553961176475377151369399646747881452252547741718734949967752564774161341784833521492494243662658471121369649641815562327698395293573991648351369767162642763475561544795982183714447737149239846151871434656618825566387329765118727515699213962477996399781652131918996434125559698427945714572488376342126989157872118279163127742349' print(part_one(input)) print(part_two(input))
def KSA(key): S = bytearray(range(256)) j = 0 for i in range(256): j = (j + S[i] + key[i % len(key)]) % 256 S[i], S[j] = S[j], S[i] return S def PRGA(S): i = 0 j = 0 while True: i = (i + 1) % 256 j = (j + S[i]) % 256 S[i], S[j] = S[j], S[i] K = S[(S[i] + S[j]) % 256] yield K def RC4(key): S = KSA(key) return PRGA(S)
def ksa(key): s = bytearray(range(256)) j = 0 for i in range(256): j = (j + S[i] + key[i % len(key)]) % 256 (S[i], S[j]) = (S[j], S[i]) return S def prga(S): i = 0 j = 0 while True: i = (i + 1) % 256 j = (j + S[i]) % 256 (S[i], S[j]) = (S[j], S[i]) k = S[(S[i] + S[j]) % 256] yield K def rc4(key): s = ksa(key) return prga(S)
# # PySNMP MIB module ARP-Spoofing-Prevent-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ARP-Spoofing-Prevent-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:09:30 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsUnion", "ValueRangeConstraint", "ConstraintsIntersection") dlink_common_mgmt, = mibBuilder.importSymbols("DLINK-ID-REC-MIB", "dlink-common-mgmt") SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") Unsigned32, Counter64, NotificationType, Bits, TimeTicks, ModuleIdentity, Integer32, Counter32, ObjectIdentity, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, Gauge32, iso = mibBuilder.importSymbols("SNMPv2-SMI", "Unsigned32", "Counter64", "NotificationType", "Bits", "TimeTicks", "ModuleIdentity", "Integer32", "Counter32", "ObjectIdentity", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "Gauge32", "iso") RowStatus, MacAddress, DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "MacAddress", "DisplayString", "TextualConvention") swARPSpoofingPreventMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 171, 12, 62)) if mibBuilder.loadTexts: swARPSpoofingPreventMIB.setLastUpdated('0805120000Z') if mibBuilder.loadTexts: swARPSpoofingPreventMIB.setOrganization('D-Link Corp.') class PortList(OctetString): subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(0, 127) swARPSpoofingPreventCtrl = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 12, 62, 1)) swARPSpoofingPreventInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 12, 62, 2)) swARPSpoofingPreventMgmt = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 12, 62, 3)) swARPSpoofingPreventMgmtTable = MibTable((1, 3, 6, 1, 4, 1, 171, 12, 62, 3, 1), ) if mibBuilder.loadTexts: swARPSpoofingPreventMgmtTable.setStatus('current') swARPSpoofingPreventMgmtEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 12, 62, 3, 1, 1), ).setIndexNames((0, "ARP-Spoofing-Prevent-MIB", "swARPSpoofingPreventMgmtGatewayIP"), (0, "ARP-Spoofing-Prevent-MIB", "swARPSpoofingPreventMgmtGatewayMAC")) if mibBuilder.loadTexts: swARPSpoofingPreventMgmtEntry.setStatus('current') swARPSpoofingPreventMgmtGatewayIP = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 62, 3, 1, 1, 1), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: swARPSpoofingPreventMgmtGatewayIP.setStatus('current') swARPSpoofingPreventMgmtGatewayMAC = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 62, 3, 1, 1, 2), MacAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: swARPSpoofingPreventMgmtGatewayMAC.setStatus('current') swARPSpoofingPreventMgmtPorts = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 62, 3, 1, 1, 3), PortList()).setMaxAccess("readcreate") if mibBuilder.loadTexts: swARPSpoofingPreventMgmtPorts.setStatus('current') swARPSpoofingPreventMgmtStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 62, 3, 1, 1, 4), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: swARPSpoofingPreventMgmtStatus.setStatus('current') mibBuilder.exportSymbols("ARP-Spoofing-Prevent-MIB", swARPSpoofingPreventMgmtGatewayIP=swARPSpoofingPreventMgmtGatewayIP, swARPSpoofingPreventCtrl=swARPSpoofingPreventCtrl, swARPSpoofingPreventMgmtStatus=swARPSpoofingPreventMgmtStatus, swARPSpoofingPreventMgmtTable=swARPSpoofingPreventMgmtTable, swARPSpoofingPreventMgmt=swARPSpoofingPreventMgmt, PYSNMP_MODULE_ID=swARPSpoofingPreventMIB, swARPSpoofingPreventMgmtEntry=swARPSpoofingPreventMgmtEntry, PortList=PortList, swARPSpoofingPreventMgmtPorts=swARPSpoofingPreventMgmtPorts, swARPSpoofingPreventMIB=swARPSpoofingPreventMIB, swARPSpoofingPreventInfo=swARPSpoofingPreventInfo, swARPSpoofingPreventMgmtGatewayMAC=swARPSpoofingPreventMgmtGatewayMAC)
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, value_size_constraint, constraints_union, value_range_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'SingleValueConstraint', 'ValueSizeConstraint', 'ConstraintsUnion', 'ValueRangeConstraint', 'ConstraintsIntersection') (dlink_common_mgmt,) = mibBuilder.importSymbols('DLINK-ID-REC-MIB', 'dlink-common-mgmt') (snmp_admin_string,) = mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpAdminString') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (unsigned32, counter64, notification_type, bits, time_ticks, module_identity, integer32, counter32, object_identity, mib_identifier, mib_scalar, mib_table, mib_table_row, mib_table_column, ip_address, gauge32, iso) = mibBuilder.importSymbols('SNMPv2-SMI', 'Unsigned32', 'Counter64', 'NotificationType', 'Bits', 'TimeTicks', 'ModuleIdentity', 'Integer32', 'Counter32', 'ObjectIdentity', 'MibIdentifier', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'IpAddress', 'Gauge32', 'iso') (row_status, mac_address, display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'RowStatus', 'MacAddress', 'DisplayString', 'TextualConvention') sw_arp_spoofing_prevent_mib = module_identity((1, 3, 6, 1, 4, 1, 171, 12, 62)) if mibBuilder.loadTexts: swARPSpoofingPreventMIB.setLastUpdated('0805120000Z') if mibBuilder.loadTexts: swARPSpoofingPreventMIB.setOrganization('D-Link Corp.') class Portlist(OctetString): subtype_spec = OctetString.subtypeSpec + value_size_constraint(0, 127) sw_arp_spoofing_prevent_ctrl = mib_identifier((1, 3, 6, 1, 4, 1, 171, 12, 62, 1)) sw_arp_spoofing_prevent_info = mib_identifier((1, 3, 6, 1, 4, 1, 171, 12, 62, 2)) sw_arp_spoofing_prevent_mgmt = mib_identifier((1, 3, 6, 1, 4, 1, 171, 12, 62, 3)) sw_arp_spoofing_prevent_mgmt_table = mib_table((1, 3, 6, 1, 4, 1, 171, 12, 62, 3, 1)) if mibBuilder.loadTexts: swARPSpoofingPreventMgmtTable.setStatus('current') sw_arp_spoofing_prevent_mgmt_entry = mib_table_row((1, 3, 6, 1, 4, 1, 171, 12, 62, 3, 1, 1)).setIndexNames((0, 'ARP-Spoofing-Prevent-MIB', 'swARPSpoofingPreventMgmtGatewayIP'), (0, 'ARP-Spoofing-Prevent-MIB', 'swARPSpoofingPreventMgmtGatewayMAC')) if mibBuilder.loadTexts: swARPSpoofingPreventMgmtEntry.setStatus('current') sw_arp_spoofing_prevent_mgmt_gateway_ip = mib_table_column((1, 3, 6, 1, 4, 1, 171, 12, 62, 3, 1, 1, 1), ip_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: swARPSpoofingPreventMgmtGatewayIP.setStatus('current') sw_arp_spoofing_prevent_mgmt_gateway_mac = mib_table_column((1, 3, 6, 1, 4, 1, 171, 12, 62, 3, 1, 1, 2), mac_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: swARPSpoofingPreventMgmtGatewayMAC.setStatus('current') sw_arp_spoofing_prevent_mgmt_ports = mib_table_column((1, 3, 6, 1, 4, 1, 171, 12, 62, 3, 1, 1, 3), port_list()).setMaxAccess('readcreate') if mibBuilder.loadTexts: swARPSpoofingPreventMgmtPorts.setStatus('current') sw_arp_spoofing_prevent_mgmt_status = mib_table_column((1, 3, 6, 1, 4, 1, 171, 12, 62, 3, 1, 1, 4), row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: swARPSpoofingPreventMgmtStatus.setStatus('current') mibBuilder.exportSymbols('ARP-Spoofing-Prevent-MIB', swARPSpoofingPreventMgmtGatewayIP=swARPSpoofingPreventMgmtGatewayIP, swARPSpoofingPreventCtrl=swARPSpoofingPreventCtrl, swARPSpoofingPreventMgmtStatus=swARPSpoofingPreventMgmtStatus, swARPSpoofingPreventMgmtTable=swARPSpoofingPreventMgmtTable, swARPSpoofingPreventMgmt=swARPSpoofingPreventMgmt, PYSNMP_MODULE_ID=swARPSpoofingPreventMIB, swARPSpoofingPreventMgmtEntry=swARPSpoofingPreventMgmtEntry, PortList=PortList, swARPSpoofingPreventMgmtPorts=swARPSpoofingPreventMgmtPorts, swARPSpoofingPreventMIB=swARPSpoofingPreventMIB, swARPSpoofingPreventInfo=swARPSpoofingPreventInfo, swARPSpoofingPreventMgmtGatewayMAC=swARPSpoofingPreventMgmtGatewayMAC)
def regras(x): if x < 100: if x % 2 == 0: return x else: return (x + x) lista = [100, 200, 1000, 3000, 2, 3, 4, 5, 6, 7, 8] print(list(filter(regras,lista))) #https://pt.stackoverflow.com/q/321682/101
def regras(x): if x < 100: if x % 2 == 0: return x else: return x + x lista = [100, 200, 1000, 3000, 2, 3, 4, 5, 6, 7, 8] print(list(filter(regras, lista)))
def merge(a1, a2): ma = [] i1, i2 = 0, 0 while i1 < len(a1) and i2 < len(a2): if a1[i1] < a2[i2]: ma.append(a1[i1]) i1 += 1 else: ma.append(a2[i2]) i2 += 1 while i1 < len(a1): ma.append(a1[i1]) i1 += 1 while i2 < len(a2): ma.append(a2[i2]) i2 += 1 return ma
def merge(a1, a2): ma = [] (i1, i2) = (0, 0) while i1 < len(a1) and i2 < len(a2): if a1[i1] < a2[i2]: ma.append(a1[i1]) i1 += 1 else: ma.append(a2[i2]) i2 += 1 while i1 < len(a1): ma.append(a1[i1]) i1 += 1 while i2 < len(a2): ma.append(a2[i2]) i2 += 1 return ma
def wrap(string, max_width): wrapper = textwrap.TextWrapper(width=max_width) word_list = wrapper.wrap(text=string) lastWrap = word_list[-1] for element in word_list: if element != lastWrap: print(element) return lastWrap
def wrap(string, max_width): wrapper = textwrap.TextWrapper(width=max_width) word_list = wrapper.wrap(text=string) last_wrap = word_list[-1] for element in word_list: if element != lastWrap: print(element) return lastWrap
needed_money = float(input()) owned_money = float(input()) days_counter = 0 spending_counter = 0 while True: action = input() amount = float(input()) days_counter += 1 if action == "spend": owned_money -= amount spending_counter += 1 if owned_money < 0: owned_money = 0 if spending_counter >= 5: print("You can\'t save the money.") print(f"{days_counter}") break else: owned_money += amount spending_counter = 0 if owned_money >= needed_money: print(f"You saved the money for {days_counter} days.") break
needed_money = float(input()) owned_money = float(input()) days_counter = 0 spending_counter = 0 while True: action = input() amount = float(input()) days_counter += 1 if action == 'spend': owned_money -= amount spending_counter += 1 if owned_money < 0: owned_money = 0 if spending_counter >= 5: print("You can't save the money.") print(f'{days_counter}') break else: owned_money += amount spending_counter = 0 if owned_money >= needed_money: print(f'You saved the money for {days_counter} days.') break
DESCRIBE_GATEWAYS = [ { "Attachments": [ { "State": "available", "VpcId": "vpc-XXXXXXX", }, ], "InternetGatewayId": "igw-1234XXX", "OwnerId": "012345678912", "Tags": [ { "Key": "Name", "Value": "InternetGateway", }, ], }, { "Attachments": [ { "State": "available", "VpcId": "vpc-XXXXXXX", }, ], "InternetGatewayId": "igw-7e3a7c18", "OwnerId": "012345678912", "Tags": [ { "Key": "AWSServiceAccount", "Value": "697148468905", }, ], }, { "Attachments": [ { "State": "available", "VpcId": "vpc-XXXXXXX", }, ], "InternetGatewayId": "igw-f1c81494", "OwnerId": "012345678912", "Tags": [], }, ]
describe_gateways = [{'Attachments': [{'State': 'available', 'VpcId': 'vpc-XXXXXXX'}], 'InternetGatewayId': 'igw-1234XXX', 'OwnerId': '012345678912', 'Tags': [{'Key': 'Name', 'Value': 'InternetGateway'}]}, {'Attachments': [{'State': 'available', 'VpcId': 'vpc-XXXXXXX'}], 'InternetGatewayId': 'igw-7e3a7c18', 'OwnerId': '012345678912', 'Tags': [{'Key': 'AWSServiceAccount', 'Value': '697148468905'}]}, {'Attachments': [{'State': 'available', 'VpcId': 'vpc-XXXXXXX'}], 'InternetGatewayId': 'igw-f1c81494', 'OwnerId': '012345678912', 'Tags': []}]
# Time: O(n^2); Space: O(1) def time_required_to_buy(tickets, k): time = 0 while tickets[k] > 0: for i, t in enumerate(tickets): if t > 0: time += 1 tickets[i] -= 1 if tickets[k] == 0: break return time # Time: O(n); Space: O(1) def time_required_to_buy2(tickets, k): time = tickets[k] # it has to buy all at kth position for i in range(len(tickets)): if i < k: time += min(tickets[i], tickets[k]) # for all pos before k it will exhaust all tickets or get till number till kth place elif i > k: time += min(tickets[i], tickets[k] - 1) # for all pos after k it can exhaust all tickets or get 1 less than the kth gets finished return time # Test cases: print(time_required_to_buy(tickets=[2, 3, 2], k=2)) print(time_required_to_buy(tickets=[5, 1, 1, 1], k=0))
def time_required_to_buy(tickets, k): time = 0 while tickets[k] > 0: for (i, t) in enumerate(tickets): if t > 0: time += 1 tickets[i] -= 1 if tickets[k] == 0: break return time def time_required_to_buy2(tickets, k): time = tickets[k] for i in range(len(tickets)): if i < k: time += min(tickets[i], tickets[k]) elif i > k: time += min(tickets[i], tickets[k] - 1) return time print(time_required_to_buy(tickets=[2, 3, 2], k=2)) print(time_required_to_buy(tickets=[5, 1, 1, 1], k=0))
# -*- coding: utf-8 -*- proxies = ( # '115.229.93.123:9000', # '114.249.116.183:9000', # '14.118.252.68:6666', # '115.229.93.123:9000', )
proxies = ()
# Django settings for yawf_sample project. DEBUG = True TEMPLATE_DEBUG = DEBUG DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'test.db', # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } SITE_ID = 1 # Make this unique, and don't share it with anybody. SECRET_KEY = 'ufq^a%n=9#nbs(_p09c5gvqt(f-7td3$h8tmfbl)(1o9p)226u' MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', # Uncomment the next line for simple clickjacking protection: # 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'yawf_sample.urls' INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'yawf', 'yawf.message_log', 'yawf_sample.simple', 'reversion', 'django.contrib.admin', ) # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.CallbackFilter', 'callback': lambda r: not DEBUG } }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', }, 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, 'yawf': { 'handlers': ['console'], 'level': 'WARNING', 'propagate': True, } } } YAWF_CONFIG = { 'DYNAMIC_WORKFLOW_ENABLED': True, 'MESSAGE_LOG_ENABLED': True, 'USE_SELECT_FOR_UPDATE': False, } SOUTH_TESTS_MIGRATE = False
debug = True template_debug = DEBUG databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'test.db', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': ''}} site_id = 1 secret_key = 'ufq^a%n=9#nbs(_p09c5gvqt(f-7td3$h8tmfbl)(1o9p)226u' middleware_classes = ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware') root_urlconf = 'yawf_sample.urls' installed_apps = ('django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'yawf', 'yawf.message_log', 'yawf_sample.simple', 'reversion', 'django.contrib.admin') logging = {'version': 1, 'disable_existing_loggers': False, 'filters': {'require_debug_false': {'()': 'django.utils.log.CallbackFilter', 'callback': lambda r: not DEBUG}}, 'handlers': {'console': {'level': 'DEBUG', 'class': 'logging.StreamHandler'}, 'mail_admins': {'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler'}}, 'loggers': {'django.request': {'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True}, 'yawf': {'handlers': ['console'], 'level': 'WARNING', 'propagate': True}}} yawf_config = {'DYNAMIC_WORKFLOW_ENABLED': True, 'MESSAGE_LOG_ENABLED': True, 'USE_SELECT_FOR_UPDATE': False} south_tests_migrate = False
# DAY 4- ACTIVITY 3 # Program Description: This is a simple word bank program. It takes in the user's input and turns it into a string # which will then be stored into the word bank list. After the user is done inputting his desired words, the program # will print out the elements inside the word bank list. # The list that will act as the word bank. bankList = [] continueRunning = True while continueRunning: # will use try-except method just in case something is wrong with the inputs that the user had entered. try: # the program will convert the user's input into a string. # Then, it will append the word into the bankList. print ( "\n-------------------- ENTER DETAILS --------------------" ) word = str ( input ( " Enter a word ( string ) : " ) ) print ( "-------------------------------------------------------\n" ) bankList.append( word ) print ( " {} has been stored in the word bank. \n".format( word ) ) print ( "-------------------------------------------------------\n" ) # Here, the program will ask the user if he would like to continue using the program. # If yes, the user will be able to continue adding more words into the bank list. # If not, the program will print out the elements inside the bankList. hasChosen = False while hasChosen == False: try: userChoice = str ( input ( " Would you like to try again? Y/y if Yes and N/n if No. " ) ) if userChoice.lower() == "y" or userChoice.lower() == "yes" : hasChosen = True elif userChoice.lower() == "n" or userChoice.lower() == "no" : print ( "\n-------------------------------------------------------\n" ) print ( " The word bank contains: " ) for x in bankList: print ( " - {}.".format( x ) ) print ( "\n-------------------------------------------------------\n" ) continueRunning = False hasChosen = True else: print ( " Invalid Input. " ) except: print ( " Invalid Input. " ) except: print ( " Invalid Input. " )
bank_list = [] continue_running = True while continueRunning: try: print('\n-------------------- ENTER DETAILS --------------------') word = str(input(' Enter a word ( string ) : ')) print('-------------------------------------------------------\n') bankList.append(word) print(' {} has been stored in the word bank. \n'.format(word)) print('-------------------------------------------------------\n') has_chosen = False while hasChosen == False: try: user_choice = str(input(' Would you like to try again? Y/y if Yes and N/n if No. ')) if userChoice.lower() == 'y' or userChoice.lower() == 'yes': has_chosen = True elif userChoice.lower() == 'n' or userChoice.lower() == 'no': print('\n-------------------------------------------------------\n') print(' The word bank contains: ') for x in bankList: print(' - {}.'.format(x)) print('\n-------------------------------------------------------\n') continue_running = False has_chosen = True else: print(' Invalid Input. ') except: print(' Invalid Input. ') except: print(' Invalid Input. ')
############################################################################### # Monitor plot arrays # ############################################################################### tag = "monitor" varpos = { 'time': 0, 'x': 1, 'y': 2, 'z': 3, 'uindex': 4, 'i': 5, 'j': 6, 'k': 7, 'head': 8, 'temp': 9, 'pres': 10, 'satn': 11, 'epot': 12, 'conc0001': 13, # 'vx': 13, # 'vy': 14, # 'vz': 15, # 'bhpr': 16, # 'kz' : 17, }
tag = 'monitor' varpos = {'time': 0, 'x': 1, 'y': 2, 'z': 3, 'uindex': 4, 'i': 5, 'j': 6, 'k': 7, 'head': 8, 'temp': 9, 'pres': 10, 'satn': 11, 'epot': 12, 'conc0001': 13}
def greeting_user(fname,lname): print(f"Hi {fname} {lname} !") print("How are you?") print("start") greeting_user("Lois") # we can add positional argument, this means position of the argument can shifted around # greeting_user(lname= "tracy", fname="Andrew") print("end")
def greeting_user(fname, lname): print(f'Hi {fname} {lname} !') print('How are you?') print('start') greeting_user('Lois') print('end')
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def flatten(self, root): if not root: return while root: if root.left: node = root.left while node.right: node = node.right node.right = root.right root.right = root.left root.left = None root = root.right
class Solution(object): def flatten(self, root): if not root: return while root: if root.left: node = root.left while node.right: node = node.right node.right = root.right root.right = root.left root.left = None root = root.right
#Nesting Loops in Loops outer = ['Li','Na','K'] inner = ['F', 'Cl', 'Br'] for metal in outer: for halogen in inner: print(metal + halogen)
outer = ['Li', 'Na', 'K'] inner = ['F', 'Cl', 'Br'] for metal in outer: for halogen in inner: print(metal + halogen)
# https://codeforces.com/contest/1327/problem/A for _ in range(int(input())): n, k = map(int, input().split()) print("YES" if n % 2 == k % 2 and n >= k * k else "NO")
for _ in range(int(input())): (n, k) = map(int, input().split()) print('YES' if n % 2 == k % 2 and n >= k * k else 'NO')
__all__ = [ 'box.py', 'servers.py', 'network.py' ]
__all__ = ['box.py', 'servers.py', 'network.py']
def main(): while True: text = input("Text: ") if len(text) > 0: break letter = 0 word = 1 sentence = 0 for c in text: c = c.upper() if c >= "A" and c <= "Z": letter += 1 if c == " ": word += 1 if c == "." or c == "!" or c == "?": sentence += 1 # print(f"letter: {letter} word: {word} sentence: {sentence}") index = coleman_liau_index(letter, word, sentence) if index > 16: print("Grade 16+") elif index < 1: print("Before Grade 1") else: print(f"Grade {index}") def coleman_liau_index(letter, word, sentence): return round(0.0588 * (letter * 100.0 / word) - 0.296 * (sentence * 100.0 / word) - 15.8) if __name__ == "__main__": main()
def main(): while True: text = input('Text: ') if len(text) > 0: break letter = 0 word = 1 sentence = 0 for c in text: c = c.upper() if c >= 'A' and c <= 'Z': letter += 1 if c == ' ': word += 1 if c == '.' or c == '!' or c == '?': sentence += 1 index = coleman_liau_index(letter, word, sentence) if index > 16: print('Grade 16+') elif index < 1: print('Before Grade 1') else: print(f'Grade {index}') def coleman_liau_index(letter, word, sentence): return round(0.0588 * (letter * 100.0 / word) - 0.296 * (sentence * 100.0 / word) - 15.8) if __name__ == '__main__': main()
class ComposeScript: def __init__(self, name, deploy=None, ready_check=None, output_extraction=None, cleanup_on=None, unique_by=None): self.name = name self.deploy = deploy if deploy is not None else [] self.cleanup_on = cleanup_on self.unique_by = unique_by self.ready_check = ready_check self.output_extraction = output_extraction
class Composescript: def __init__(self, name, deploy=None, ready_check=None, output_extraction=None, cleanup_on=None, unique_by=None): self.name = name self.deploy = deploy if deploy is not None else [] self.cleanup_on = cleanup_on self.unique_by = unique_by self.ready_check = ready_check self.output_extraction = output_extraction
while True: try: S = input() count = 0 for k in input(): if k in S: count += 1 print(count) except: break
while True: try: s = input() count = 0 for k in input(): if k in S: count += 1 print(count) except: break
# def main(): # x, y, z = (int(x) for x in input().strip().split()) # result = 0 # if 1 <= x <= 31 and 1 <= y <= 12: # result += 1 # if 1 <= y <= 31 and 1 <= x <= 12: # result += 1 # print(result % 2) # # # main() def main(): a, b, c = map(int, input().split()) if a == b: print(1) elif b <= 12 and a <= 12: print(0) else: print(1) main()
def main(): (a, b, c) = map(int, input().split()) if a == b: print(1) elif b <= 12 and a <= 12: print(0) else: print(1) main()
buy_schema = { 'items': [ { 'itemKey': { 'inventoryType': 'CHAMPION', 'itemId': -1 }, 'purchaseCurrencyInfo': { 'currencyType': 'IP', 'price': -1, 'purchasable': True }, 'quantity': 1, 'source': 'cdp' } ] }
buy_schema = {'items': [{'itemKey': {'inventoryType': 'CHAMPION', 'itemId': -1}, 'purchaseCurrencyInfo': {'currencyType': 'IP', 'price': -1, 'purchasable': True}, 'quantity': 1, 'source': 'cdp'}]}
class Tabs: MEMBERS = "Members" SITES = "Sites" ROLES = "Roles" DETAILS = "Details" class Details: NAME = "Name" EORI_NUMBER = "EORI number" SIC_NUMBER = "SIC code" VAT_NUMBER = "VAT number" REGISTRATION_NUMBER = "Registration number" CREATED_AT = "Created at" PRIMARY_SITE = "Primary site" TYPE = "Type"
class Tabs: members = 'Members' sites = 'Sites' roles = 'Roles' details = 'Details' class Details: name = 'Name' eori_number = 'EORI number' sic_number = 'SIC code' vat_number = 'VAT number' registration_number = 'Registration number' created_at = 'Created at' primary_site = 'Primary site' type = 'Type'
def scope_test(): def do_local(): spam = 'local spam' def do_nonLocal(): nonlocal spam spam = 'non local spam' def do_global(): global spam spam = 'global spam' spam = 'test spam' do_local() print('after local assignment: ', spam) do_nonLocal() print('after non-local assignment: ', spam) do_global() print('after global assignment: ', spam) scope_test() print('in global scope: ', spam)
def scope_test(): def do_local(): spam = 'local spam' def do_non_local(): nonlocal spam spam = 'non local spam' def do_global(): global spam spam = 'global spam' spam = 'test spam' do_local() print('after local assignment: ', spam) do_non_local() print('after non-local assignment: ', spam) do_global() print('after global assignment: ', spam) scope_test() print('in global scope: ', spam)
#!/usr/bin/env python # -*- coding: utf-8 -*- class InvalidTokenTypeError(Exception): pass class InvalidNodeTypeError(Exception): pass class InvalidTargetNodeTypeError(Exception): pass
class Invalidtokentypeerror(Exception): pass class Invalidnodetypeerror(Exception): pass class Invalidtargetnodetypeerror(Exception): pass
a,b,c = input().split() a,b,c = [float(a),float(b),float(c)] if a+b <= c or b+c <= a or c+a <= b: print("NAO FORMA TRIANGULO") else: if a*a == b*b+c*c or b*b == a*a+c*c or c*c == b*b+a*a: print("TRIANGULO RETANGULO") elif a*a > b*b+c*c or b*b > a*a+c*c or c*c > b*b+a*a: print("TRIANGULO OBTUSANGULO") else: print("TRIANGULO ACUTANGULO") if a == b == c: print("TRIANGULO EQUILATERO") elif a == b != c or a == c != b or c == b != a: print("TRIANGULO ISOSCELES")
(a, b, c) = input().split() (a, b, c) = [float(a), float(b), float(c)] if a + b <= c or b + c <= a or c + a <= b: print('NAO FORMA TRIANGULO') else: if a * a == b * b + c * c or b * b == a * a + c * c or c * c == b * b + a * a: print('TRIANGULO RETANGULO') elif a * a > b * b + c * c or b * b > a * a + c * c or c * c > b * b + a * a: print('TRIANGULO OBTUSANGULO') else: print('TRIANGULO ACUTANGULO') if a == b == c: print('TRIANGULO EQUILATERO') elif a == b != c or a == c != b or c == b != a: print('TRIANGULO ISOSCELES')
def print_without_vowels(s): ''' s: the string to convert Finds a version of s without vowels and whose characters appear in the same order they appear in s. Prints this version of s. Does not return anything ''' # Your code here newString = "" for item in s: if item not in "aeiouAEIOU": newString += item print(newString) # print(print_without_vowels("a")) print_without_vowels("a")
def print_without_vowels(s): """ s: the string to convert Finds a version of s without vowels and whose characters appear in the same order they appear in s. Prints this version of s. Does not return anything """ new_string = '' for item in s: if item not in 'aeiouAEIOU': new_string += item print(newString) print_without_vowels('a')
expected_1 = ({ '__feature_4': [ 42., 67., 6., 92., 80., 10., 90., 5., 100., 40., 23., 44., 81., 53., 37., 7., 79., 45., 87.], '__feature_2': [ 91., 15., 36., 51., 32., 11., 38., 56., 21., 34., 75., 77., 98., 71., 95., 4., 83., 70., 33.], '__feature_3': [ 17., 82., 26., 99., 72., 35., 54., 22., 20., 25., 29., 94., 66., 84., 55., 12., 43., 1., 16.], '__feature_0': [ 63., 89., 49., 24., 41., 48., 58., 47., 61., 14., 59., 96., 88., 65., 19., 74., 97., 50., 57.], '__feature_1': [ 27., 52., 18., 76., 60., 62., 30., 8., 86., 78., 31., 39., 93., 2., 28., 46., 85., 3., 73.]}, 19) expected_2 = ({ 'cuatro': [ 17., 82., 26., 99., 72., 35., 54., 22., 20., 25., 29., 94., 66., 84., 55., 12., 43., 1., 16.], 'dos': [ 27., 52., 18., 76., 60., 62., 30., 8., 86., 78., 31., 39., 93., 2., 28., 46., 85., 3., 73.], 'tres': [ 91., 15., 36., 51., 32., 11., 38., 56., 21., 34., 75., 77., 98., 71., 95., 4., 83., 70., 33.], 'cinco': [ 42., 67., 6., 92., 80., 10., 90., 5., 100., 40., 23., 44., 81., 53., 37., 7., 79., 45., 87.], 'uno': [ 63., 89., 49., 24., 41., 48., 58., 47., 61., 14., 59., 96., 88., 65., 19., 74., 97., 50., 57.]}, 19) expected_3 = ({ 'cuatro': [ 17., 82., 26., 99., 72., 35., 54., 22., 20., 25., 29., 94., 66., 84., 55., 12., 43., 1., 16.], 'tres': [ 91., 15., 36., 51., 32., 11., 38., 56., 21., 34., 75., 77., 98., 71., 95., 4., 83., 70., 33.]}, 19) expected_single_row = { 'single': [ 91., 15., 36., 51., 32., 11., 38., 56., 21., 34., 75., 77., 98., 71., 95., 4., 83., 70., 33.]}
expected_1 = ({'__feature_4': [42.0, 67.0, 6.0, 92.0, 80.0, 10.0, 90.0, 5.0, 100.0, 40.0, 23.0, 44.0, 81.0, 53.0, 37.0, 7.0, 79.0, 45.0, 87.0], '__feature_2': [91.0, 15.0, 36.0, 51.0, 32.0, 11.0, 38.0, 56.0, 21.0, 34.0, 75.0, 77.0, 98.0, 71.0, 95.0, 4.0, 83.0, 70.0, 33.0], '__feature_3': [17.0, 82.0, 26.0, 99.0, 72.0, 35.0, 54.0, 22.0, 20.0, 25.0, 29.0, 94.0, 66.0, 84.0, 55.0, 12.0, 43.0, 1.0, 16.0], '__feature_0': [63.0, 89.0, 49.0, 24.0, 41.0, 48.0, 58.0, 47.0, 61.0, 14.0, 59.0, 96.0, 88.0, 65.0, 19.0, 74.0, 97.0, 50.0, 57.0], '__feature_1': [27.0, 52.0, 18.0, 76.0, 60.0, 62.0, 30.0, 8.0, 86.0, 78.0, 31.0, 39.0, 93.0, 2.0, 28.0, 46.0, 85.0, 3.0, 73.0]}, 19) expected_2 = ({'cuatro': [17.0, 82.0, 26.0, 99.0, 72.0, 35.0, 54.0, 22.0, 20.0, 25.0, 29.0, 94.0, 66.0, 84.0, 55.0, 12.0, 43.0, 1.0, 16.0], 'dos': [27.0, 52.0, 18.0, 76.0, 60.0, 62.0, 30.0, 8.0, 86.0, 78.0, 31.0, 39.0, 93.0, 2.0, 28.0, 46.0, 85.0, 3.0, 73.0], 'tres': [91.0, 15.0, 36.0, 51.0, 32.0, 11.0, 38.0, 56.0, 21.0, 34.0, 75.0, 77.0, 98.0, 71.0, 95.0, 4.0, 83.0, 70.0, 33.0], 'cinco': [42.0, 67.0, 6.0, 92.0, 80.0, 10.0, 90.0, 5.0, 100.0, 40.0, 23.0, 44.0, 81.0, 53.0, 37.0, 7.0, 79.0, 45.0, 87.0], 'uno': [63.0, 89.0, 49.0, 24.0, 41.0, 48.0, 58.0, 47.0, 61.0, 14.0, 59.0, 96.0, 88.0, 65.0, 19.0, 74.0, 97.0, 50.0, 57.0]}, 19) expected_3 = ({'cuatro': [17.0, 82.0, 26.0, 99.0, 72.0, 35.0, 54.0, 22.0, 20.0, 25.0, 29.0, 94.0, 66.0, 84.0, 55.0, 12.0, 43.0, 1.0, 16.0], 'tres': [91.0, 15.0, 36.0, 51.0, 32.0, 11.0, 38.0, 56.0, 21.0, 34.0, 75.0, 77.0, 98.0, 71.0, 95.0, 4.0, 83.0, 70.0, 33.0]}, 19) expected_single_row = {'single': [91.0, 15.0, 36.0, 51.0, 32.0, 11.0, 38.0, 56.0, 21.0, 34.0, 75.0, 77.0, 98.0, 71.0, 95.0, 4.0, 83.0, 70.0, 33.0]}
# inteiros idade = 22 ano = 2021 # reais altura = 1.63 saldo = 10.50 # palavras (strings) nome = 'Luisa' sobrenome = 'Moura'
idade = 22 ano = 2021 altura = 1.63 saldo = 10.5 nome = 'Luisa' sobrenome = 'Moura'
def example_filter1(string): return "Example1: " + string def get_template_filter(): return example_filter1 def returns_string_passed(string): return string def title_string(string): return string.title()
def example_filter1(string): return 'Example1: ' + string def get_template_filter(): return example_filter1 def returns_string_passed(string): return string def title_string(string): return string.title()
#Programming Part variables #kinect_add = "./x64/Release/AzureKinectDK.exe" kinect_add = "C:/Users/User/Desktop/EVCIDNet-master/x64/Release/AzureKinectDK.exe" result_add = "./AzureKinectDK/output/result.txt" flag1_add = "./AzureKinectDK/output/flag1.txt" #image capture start flag flag2_add = "./AzureKinectDK/output/flag2.txt" #image capture finish flag flag3_add = "./AzureKinectDK/output/flag3.txt" #camera turn off and program terminate flag flag = [flag1_add, flag2_add, flag3_add] color_addr = "./AzureKinectDK/output/color.png" point_addr = "./AzureKinectDK/output/point.png" json_addr = "./AzureKinectDK/output/demo.json" json_dict = {"licenses": [{"name": "", "id": 0, "url": ""}], "info": {"contributor": "", "date_created": "", "description": "", "url": "", "version": "", "year": ""}, "categories": [{"id": 1, "name": "HolePairLeft", "supercategory": ""}, {"id": 2, "name": "HolePairRight", "supercategory": ""}, {"id": 3, "name": "ACHole", "supercategory": ""}], "images": [], "annotations": []} Error_coordinate = [[77777 for i in range(3)] for i in range(3)] #Communication Part variables regiaddrX1 = 8 regiaddrY1 = 9 regiaddrZ1 = 10 regiaddrX2 = 11 regiaddrY2 = 12 regiaddrZ2 = 13 regiaddrX3 = 14 regiaddrY3 = 15 regiaddrZ3 = 18 regiaddrC = 19 regiaddr = [regiaddrX1,regiaddrY1,regiaddrZ1,regiaddrX2,regiaddrY2,regiaddrZ2,regiaddrX3,regiaddrY3,regiaddrZ3,regiaddrC] robot_addr = "192.168.137.100" port_num = 502 offset = 32768 #int 16 max range flag1_signal = 1 flag3_signal = 0 #confirm_signal = "C" #terminate_signal = "D"
kinect_add = 'C:/Users/User/Desktop/EVCIDNet-master/x64/Release/AzureKinectDK.exe' result_add = './AzureKinectDK/output/result.txt' flag1_add = './AzureKinectDK/output/flag1.txt' flag2_add = './AzureKinectDK/output/flag2.txt' flag3_add = './AzureKinectDK/output/flag3.txt' flag = [flag1_add, flag2_add, flag3_add] color_addr = './AzureKinectDK/output/color.png' point_addr = './AzureKinectDK/output/point.png' json_addr = './AzureKinectDK/output/demo.json' json_dict = {'licenses': [{'name': '', 'id': 0, 'url': ''}], 'info': {'contributor': '', 'date_created': '', 'description': '', 'url': '', 'version': '', 'year': ''}, 'categories': [{'id': 1, 'name': 'HolePairLeft', 'supercategory': ''}, {'id': 2, 'name': 'HolePairRight', 'supercategory': ''}, {'id': 3, 'name': 'ACHole', 'supercategory': ''}], 'images': [], 'annotations': []} error_coordinate = [[77777 for i in range(3)] for i in range(3)] regiaddr_x1 = 8 regiaddr_y1 = 9 regiaddr_z1 = 10 regiaddr_x2 = 11 regiaddr_y2 = 12 regiaddr_z2 = 13 regiaddr_x3 = 14 regiaddr_y3 = 15 regiaddr_z3 = 18 regiaddr_c = 19 regiaddr = [regiaddrX1, regiaddrY1, regiaddrZ1, regiaddrX2, regiaddrY2, regiaddrZ2, regiaddrX3, regiaddrY3, regiaddrZ3, regiaddrC] robot_addr = '192.168.137.100' port_num = 502 offset = 32768 flag1_signal = 1 flag3_signal = 0
#!/usr/bin/env python # -*- coding: utf-8 -*- '''conftest.py for cpac. Read more about conftest.py under: https://pytest.org/latest/plugins.html ''' # import pytest def pytest_addoption(parser): parser.addoption('--platform', action='store', nargs=1, default=[]) parser.addoption('--tag', action='store', nargs=1, default=[]) def pytest_generate_tests(metafunc): # This is called for every test. Only get/set command line arguments # if the argument is specified in the list of test 'fixturenames'. platform = metafunc.config.option.platform tag = metafunc.config.option.tag if 'platform' in metafunc.fixturenames: metafunc.parametrize('platform', platform) if 'tag' in metafunc.fixturenames: metafunc.parametrize('tag', tag)
"""conftest.py for cpac. Read more about conftest.py under: https://pytest.org/latest/plugins.html """ def pytest_addoption(parser): parser.addoption('--platform', action='store', nargs=1, default=[]) parser.addoption('--tag', action='store', nargs=1, default=[]) def pytest_generate_tests(metafunc): platform = metafunc.config.option.platform tag = metafunc.config.option.tag if 'platform' in metafunc.fixturenames: metafunc.parametrize('platform', platform) if 'tag' in metafunc.fixturenames: metafunc.parametrize('tag', tag)
# last data structure # Sets are unorded collection of unique objects my_set = {1, 2, 4, 4, 5, 5, 5, 4, 3, 3} print(my_set) # useful methods new_set = my_set.copy() print(new_set) my_set.add(100) print(my_set)
my_set = {1, 2, 4, 4, 5, 5, 5, 4, 3, 3} print(my_set) new_set = my_set.copy() print(new_set) my_set.add(100) print(my_set)
text = "PER" s = input() n = 0 d = 0 for i in s: if n > 2: n = 0 if i != text[n]: d += 1 n += 1 print(d)
text = 'PER' s = input() n = 0 d = 0 for i in s: if n > 2: n = 0 if i != text[n]: d += 1 n += 1 print(d)
def sum_list(lst): my_list = lst if len(my_list) == 1: return my_list[0] return my_list[0] + sum_list(my_list[1:]) lst = [1,2,3,4] print(sum_list(lst))
def sum_list(lst): my_list = lst if len(my_list) == 1: return my_list[0] return my_list[0] + sum_list(my_list[1:]) lst = [1, 2, 3, 4] print(sum_list(lst))
# path to folder with data BASEPATH = '/home/michal/Develop/oshiftdata/' # name of the Elasticsearch index INDEX_NAME = 'pagesbtext' # type of the Elasticsearch index INDEX_TYPE = 'page' # host address of MongoDB MONGODB_HOST = "127.0.1.1" # port of MongoDB MONGODB_PORT = 27017 # name of MongoDB database MONGODB_DB = "skool" # name of collection, where bodytexts are saved MONGODB_COLLECTION = "page" # username for accessing database MONGODB_USER = None # password for accessing database MONGODB_PASS = None # ELASTIC_HOST # ELASTIC_PORT # url on which classification server will listen URL = "localhost" # port on which classification server will listen PORT = 8001 # connection string to classification server CSTRING = "http://localhost:8001" # filenames of files with serialized model DEFAULT_FILENAMES = { 'CountVectorizer': 'cv', 'TfIdf': 'tfidf', 'Classifier': 'cls', 'MultiLabelBinarizer': 'mlb' }
basepath = '/home/michal/Develop/oshiftdata/' index_name = 'pagesbtext' index_type = 'page' mongodb_host = '127.0.1.1' mongodb_port = 27017 mongodb_db = 'skool' mongodb_collection = 'page' mongodb_user = None mongodb_pass = None url = 'localhost' port = 8001 cstring = 'http://localhost:8001' default_filenames = {'CountVectorizer': 'cv', 'TfIdf': 'tfidf', 'Classifier': 'cls', 'MultiLabelBinarizer': 'mlb'}
class Solution: def uniquePaths(self, m: int, n: int) -> int: if m <= 0 or n <= 0: raise Exception("Invalid Matrix Size") dp = [[0] * n for _ in range(m)] for i in range(m): for j in range(n): if i == 0 and j == 0: dp[i][j] = 1 elif i == 0 and j != 0: dp[i][j] = dp[i][j - 1] elif i != 0 and j == 0: dp[i][j] = dp[i - 1][j] else: dp[i][j] = dp[i][j - 1] + dp[i - 1][j] return dp[-1][-1]
class Solution: def unique_paths(self, m: int, n: int) -> int: if m <= 0 or n <= 0: raise exception('Invalid Matrix Size') dp = [[0] * n for _ in range(m)] for i in range(m): for j in range(n): if i == 0 and j == 0: dp[i][j] = 1 elif i == 0 and j != 0: dp[i][j] = dp[i][j - 1] elif i != 0 and j == 0: dp[i][j] = dp[i - 1][j] else: dp[i][j] = dp[i][j - 1] + dp[i - 1][j] return dp[-1][-1]
honored_guest = ['YULIU', 'Jim', 'Shi'] print(honored_guest[0] + ' and ' + honored_guest[1] + ' and ' + honored_guest[2] + ' ' + "eat dinner") print("Shi cannot come here to eat dinner") honored_guest.sort() print(honored_guest) honored_guest.remove('Shi') print(honored_guest)
honored_guest = ['YULIU', 'Jim', 'Shi'] print(honored_guest[0] + ' and ' + honored_guest[1] + ' and ' + honored_guest[2] + ' ' + 'eat dinner') print('Shi cannot come here to eat dinner') honored_guest.sort() print(honored_guest) honored_guest.remove('Shi') print(honored_guest)
n=[5,6,7] # Atomic valences nc=[5,6,7] # Atomic valences l=2 # Orbital angular momentum of the shel J=0.79 # Slatter integrals F2=J*11.9219653179191 from the atomic physics program, must check this for Fe as I just used Haule's value for Mn here cx=0.0 # 0.052 # spin-orbit coupling from the atomic physics program qOCA=1 # OCA diagrams are computes in addition to NCA diagrams Eoca=1. # If the atomi energy of any state, involved in the diagram, is higher that Eoca from the ground state, the diagram ms is neglected mOCA=1e-3 # If maxtrix element of OCA diagram is smaller, it is neglected Ncentral=[6] # OCA diagrams are selected such that central occupancy is in Ncentral Ex=[0.5,0.5,0.5] # Energy window treated exactly - relevant only in magnetic state Ep=[3.0,3.0,3.0] # Energy window treated approximately qatom=0
n = [5, 6, 7] nc = [5, 6, 7] l = 2 j = 0.79 cx = 0.0 q_oca = 1 eoca = 1.0 m_oca = 0.001 ncentral = [6] ex = [0.5, 0.5, 0.5] ep = [3.0, 3.0, 3.0] qatom = 0
count_sum_1 = 0 count_sum_2 = 0 with open('input', 'r') as f: groups = f.read().split('\n\n') # Part One for group in groups: yes_set = set(group.strip()) if '\n' in yes_set: yes_set.remove('\n') yes_count = len(yes_set) # print(f'yes_count = {yes_count}, yes_set = {yes_set}') count_sum_1 += yes_count print(f'count_sum_1 = {count_sum_1}') # Part Two for group in groups: group = group.strip().split('\n') ques_set = set(group[0]) if len(group) == 1: ques_count = len(ques_set) else: for g in group: ques_set = ques_set.intersection(set(g)) ques_count = len(ques_set) # print(f'ques_count = {ques_count}, ques_set = {ques_set}') count_sum_2 += ques_count print(f'count_sum_2 = {count_sum_2}')
count_sum_1 = 0 count_sum_2 = 0 with open('input', 'r') as f: groups = f.read().split('\n\n') for group in groups: yes_set = set(group.strip()) if '\n' in yes_set: yes_set.remove('\n') yes_count = len(yes_set) count_sum_1 += yes_count print(f'count_sum_1 = {count_sum_1}') for group in groups: group = group.strip().split('\n') ques_set = set(group[0]) if len(group) == 1: ques_count = len(ques_set) else: for g in group: ques_set = ques_set.intersection(set(g)) ques_count = len(ques_set) count_sum_2 += ques_count print(f'count_sum_2 = {count_sum_2}')
def wordPattern(self, pattern: str, str: str) -> bool: m = {} words = str.split() if len(pattern) != len(words): return False result = True for i in range(len(pattern)): if pattern[i] not in m: if words[i] in m.values(): return False m[pattern[i]] = words[i] elif m[pattern[i]] != words[i]: result = False return result
def word_pattern(self, pattern: str, str: str) -> bool: m = {} words = str.split() if len(pattern) != len(words): return False result = True for i in range(len(pattern)): if pattern[i] not in m: if words[i] in m.values(): return False m[pattern[i]] = words[i] elif m[pattern[i]] != words[i]: result = False return result
#!usr/bin/python3.4 #!/usr/bin/python3.4 # Problem Set 0 # Name: xin zhong # Collaborators: # Time: 8:58-9:03 # last_name = input("Enter your last name:\n**") first_name = input("Enter your first name:\n**") print(first_name) print(last_name)
last_name = input('Enter your last name:\n**') first_name = input('Enter your first name:\n**') print(first_name) print(last_name)
class Solution: def solveNQueens(self, n: int) -> List[List[str]]: ans = [] cols = [False] * n diag1 = [False] * (2 * n - 1) diag2 = [False] * (2 * n - 1) def dfs(i: int, board: List[int]) -> None: if i == n: ans.append(board) return for j in range(n): if cols[j] or diag1[i + j] or diag2[j - i + n - 1]: continue cols[j] = diag1[i + j] = diag2[j - i + n - 1] = True dfs(i + 1, board + ['.' * j + 'Q' + '.' * (n - j - 1)]) cols[j] = diag1[i + j] = diag2[j - i + n - 1] = False dfs(0, []) return ans
class Solution: def solve_n_queens(self, n: int) -> List[List[str]]: ans = [] cols = [False] * n diag1 = [False] * (2 * n - 1) diag2 = [False] * (2 * n - 1) def dfs(i: int, board: List[int]) -> None: if i == n: ans.append(board) return for j in range(n): if cols[j] or diag1[i + j] or diag2[j - i + n - 1]: continue cols[j] = diag1[i + j] = diag2[j - i + n - 1] = True dfs(i + 1, board + ['.' * j + 'Q' + '.' * (n - j - 1)]) cols[j] = diag1[i + j] = diag2[j - i + n - 1] = False dfs(0, []) return ans
var = 'foo' def ex2(): var = 'bar' print('inside the function var is ', var) ex2() print('outside the function var is ', var) # should be bar, foo
var = 'foo' def ex2(): var = 'bar' print('inside the function var is ', var) ex2() print('outside the function var is ', var)
class Hello: def __init__(self, name): self.name = name def greeting(self): print(f'Hello {self.name}')
class Hello: def __init__(self, name): self.name = name def greeting(self): print(f'Hello {self.name}')
listA = [1] listB = [1, 2, 3, 4, listA] listC = [1] listB *= 3 print(listB) print(listB[9] == listA) print(listB[4] is listA) print(listB[9] is listA) print(listB[9] is listC) print('-------------------------') print(listB.count(listA)) print(listB.count(listC)) print(listB.index(listC, 5)) print(listB.index(listC, 5, 10)) print('-------------------------') listA *= 3 print(listB)
list_a = [1] list_b = [1, 2, 3, 4, listA] list_c = [1] list_b *= 3 print(listB) print(listB[9] == listA) print(listB[4] is listA) print(listB[9] is listA) print(listB[9] is listC) print('-------------------------') print(listB.count(listA)) print(listB.count(listC)) print(listB.index(listC, 5)) print(listB.index(listC, 5, 10)) print('-------------------------') list_a *= 3 print(listB)
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright SquirrelNetwork def string_generator(data_incoming): data = data_incoming.copy() del data['hash'] keys = sorted(data.keys()) string_arr = [] for key in keys: string_arr.append(key+'='+data[key]) string_cat = '\n'.join(string_arr) return string_cat
def string_generator(data_incoming): data = data_incoming.copy() del data['hash'] keys = sorted(data.keys()) string_arr = [] for key in keys: string_arr.append(key + '=' + data[key]) string_cat = '\n'.join(string_arr) return string_cat
def fizzbuzz(x): if x % 3 == 0 and x % 5 != 0: r = 'Fizz' elif x % 3 != 0 and x % 5 ==0: r = 'Buzz' elif x % 3 == 0 and x % 5 ==0: r = 'FizzBuzz' else: r = x return r
def fizzbuzz(x): if x % 3 == 0 and x % 5 != 0: r = 'Fizz' elif x % 3 != 0 and x % 5 == 0: r = 'Buzz' elif x % 3 == 0 and x % 5 == 0: r = 'FizzBuzz' else: r = x return r
class Tile: def __init__(self): self.first_visit = True self.tree_fallen = False def describe(self): print("You are walking through the trees. It looks like the path on " "your west leads to a small wooden hut.\n") if not self.first_visit and not self.tree_fallen: print("You saw a tree fall and it didn't make any sound and " "WOW... that was weird because you were there and " "observed it!\n") self.tree_fallen = True self.first_visit = False # "If a tree falls in a forest and no one is around to hear it, # does it make a sound?" is a philosophical thought experiment that # raises questions regarding observation and knowledge of reality. def action(self, player, do): print("Wat?!") def leave(self, player, direction): if direction == "s": print("Careful now! Nasty rocks all over to the south.\n" "(Meaning you just can't go to that direction. Sorry!)") return False else: return True
class Tile: def __init__(self): self.first_visit = True self.tree_fallen = False def describe(self): print('You are walking through the trees. It looks like the path on your west leads to a small wooden hut.\n') if not self.first_visit and (not self.tree_fallen): print("You saw a tree fall and it didn't make any sound and WOW... that was weird because you were there and observed it!\n") self.tree_fallen = True self.first_visit = False def action(self, player, do): print('Wat?!') def leave(self, player, direction): if direction == 's': print("Careful now! Nasty rocks all over to the south.\n(Meaning you just can't go to that direction. Sorry!)") return False else: return True
#!/usr/bin/python3 with open('input.txt') as f: input = list(map(int, f.read().splitlines())) PREMABLE_LENGTH = 25 idx = PREMABLE_LENGTH while idx < len(input): section = input[idx - PREMABLE_LENGTH:idx] target = input[idx] found = False for i, j in enumerate(section): if target - j in section[i+1:]: idx += 1 found = True break if not found: print(target) break invalid = input[idx] section = input[:idx] start = 0 end = 1 tot = sum(section[start:end]) while tot != invalid: if tot < invalid: end += 1 if tot > invalid: start += 1 tot = sum(section[start:end]) print(min(section[start:end]) + max(section[start:end]))
with open('input.txt') as f: input = list(map(int, f.read().splitlines())) premable_length = 25 idx = PREMABLE_LENGTH while idx < len(input): section = input[idx - PREMABLE_LENGTH:idx] target = input[idx] found = False for (i, j) in enumerate(section): if target - j in section[i + 1:]: idx += 1 found = True break if not found: print(target) break invalid = input[idx] section = input[:idx] start = 0 end = 1 tot = sum(section[start:end]) while tot != invalid: if tot < invalid: end += 1 if tot > invalid: start += 1 tot = sum(section[start:end]) print(min(section[start:end]) + max(section[start:end]))
FRAGMENT_LOG = ''' fragment fragmentLog on Log { id_ level message time } '''
fragment_log = '\nfragment fragmentLog on Log {\n id_\n level\n message\n time\n}\n'
def LevenshteinDistance(v, w): v = '-' + v w = '-' + w S = [[0 for i in range(len(w))] for j in range(len(v))] for i in range(1, len(S)): S[i][0] = S[i - 1][0] + 1 for j in range(1, len(S[0])): S[0][j] = S[0][j - 1] + 1 for i in range(1, len(v)): for j in range(1, len(w)): diag = S[i - 1][j - 1] + (1 if v[i] != w[j] else 0) down = S[i - 1][j] + 1 right = S[i][j - 1] + 1 S[i][j] = min([down, right, diag]) return S[len(v) - 1][len(w) - 1] if __name__ == "__main__": v = input().rstrip() w = input().rstrip() print(LevenshteinDistance(v, w))
def levenshtein_distance(v, w): v = '-' + v w = '-' + w s = [[0 for i in range(len(w))] for j in range(len(v))] for i in range(1, len(S)): S[i][0] = S[i - 1][0] + 1 for j in range(1, len(S[0])): S[0][j] = S[0][j - 1] + 1 for i in range(1, len(v)): for j in range(1, len(w)): diag = S[i - 1][j - 1] + (1 if v[i] != w[j] else 0) down = S[i - 1][j] + 1 right = S[i][j - 1] + 1 S[i][j] = min([down, right, diag]) return S[len(v) - 1][len(w) - 1] if __name__ == '__main__': v = input().rstrip() w = input().rstrip() print(levenshtein_distance(v, w))
with open("water.in", "r") as input_file: input_list = [line.strip() for line in input_file] with open("water.out", "w") as output_file: for binary_diameter in input_list: print(round((2/3 * 3.14 * (int(binary_diameter, 2) ** 3)) / 1000), file=output_file)
with open('water.in', 'r') as input_file: input_list = [line.strip() for line in input_file] with open('water.out', 'w') as output_file: for binary_diameter in input_list: print(round(2 / 3 * 3.14 * int(binary_diameter, 2) ** 3 / 1000), file=output_file)
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Copyright (c) 2016 Vobile Inc. All Rights Reserved. Author: xu_xiaorong Email: xu_xiaorong@mycompany.cn Created_at: 2016-08-10 13:46:10 ''' LOG_HANDLER = None # None means stdout, syslog means syslog LOG_LEVEL = 'INFO' QUEUE_NAME = "querier_queue" QUEUE_EXCHANGE = "querier_exchange" QUEUE_ROUTING_KEY = "querier_routing_key" MATCH_THRESHOLD = "22 22" #"sample reference"
""" Copyright (c) 2016 Vobile Inc. All Rights Reserved. Author: xu_xiaorong Email: xu_xiaorong@mycompany.cn Created_at: 2016-08-10 13:46:10 """ log_handler = None log_level = 'INFO' queue_name = 'querier_queue' queue_exchange = 'querier_exchange' queue_routing_key = 'querier_routing_key' match_threshold = '22 22'
def get_unithash(n: int): int(n) if (n == 0): return 0 elif (n % 9 == 0): return 9 else: return n % 9 def set_unithash(num: str, l: int): sanitation=[] sanitation[:0]=num for i in range(0,len(sanitation)): if (sanitation[i].isdigit())==False: sanitation[i]=abs(ord(sanitation[i])-96) num = ''.join([str(j) for j in sanitation]) hash = [(num[i:i+int(l)]) for i in range(0, len(num), int(l))] final_hash = [] for i in range(0,len(hash)): final_hash.append(get_unithash(int(hash[i]))) fin_hash = ''.join([str(i) for i in final_hash]) return int(fin_hash) #l = length of each group after number is broken #num = the actual number to be hashed
def get_unithash(n: int): int(n) if n == 0: return 0 elif n % 9 == 0: return 9 else: return n % 9 def set_unithash(num: str, l: int): sanitation = [] sanitation[:0] = num for i in range(0, len(sanitation)): if sanitation[i].isdigit() == False: sanitation[i] = abs(ord(sanitation[i]) - 96) num = ''.join([str(j) for j in sanitation]) hash = [num[i:i + int(l)] for i in range(0, len(num), int(l))] final_hash = [] for i in range(0, len(hash)): final_hash.append(get_unithash(int(hash[i]))) fin_hash = ''.join([str(i) for i in final_hash]) return int(fin_hash)
class md_description: def __init__(self, path, prefix_ref, repetion_number, title_output, total_running): self.path = path self.prefix_ref = prefix_ref self.repetion_number = repetion_number self.title_output = title_output self.total_running = total_running # path where MD files are def get_path(self): return self.path # prefix for reference files: md for md.xtc, md.tpr and md.edr def get_prefix_ref(self): return self.prefix_ref # number of MD repetion def get_repetion_number(self): return self.repetion_number # title for output file name def get_title_output(self): return self.title_output # total running time in ps def get_total_running(self): return self.total_running # MD files must be prefix.rep. Ex: md.1, md.2 def get_simulation_prefix(self): return str(self.get_prefix_ref()) + "." + str(self.get_repetion_number())
class Md_Description: def __init__(self, path, prefix_ref, repetion_number, title_output, total_running): self.path = path self.prefix_ref = prefix_ref self.repetion_number = repetion_number self.title_output = title_output self.total_running = total_running def get_path(self): return self.path def get_prefix_ref(self): return self.prefix_ref def get_repetion_number(self): return self.repetion_number def get_title_output(self): return self.title_output def get_total_running(self): return self.total_running def get_simulation_prefix(self): return str(self.get_prefix_ref()) + '.' + str(self.get_repetion_number())
class Solution: def minimumTotal(self, triangle: List[List[int]]) -> int: if triangle == []: return 0 for idx in range(1, len(triangle)): row = triangle[idx] prev_row = triangle[idx - 1] row[0] += prev_row[0] row[-1] += prev_row[-1] for idx in range(2, len(triangle)): row = triangle[idx] prev_row = triangle[idx - 1] for col in range(1, len(row) - 1): row[col] += min(prev_row[col - 1], prev_row[col]) return min(triangle[-1])
class Solution: def minimum_total(self, triangle: List[List[int]]) -> int: if triangle == []: return 0 for idx in range(1, len(triangle)): row = triangle[idx] prev_row = triangle[idx - 1] row[0] += prev_row[0] row[-1] += prev_row[-1] for idx in range(2, len(triangle)): row = triangle[idx] prev_row = triangle[idx - 1] for col in range(1, len(row) - 1): row[col] += min(prev_row[col - 1], prev_row[col]) return min(triangle[-1])
# -*- coding: utf-8 -*- AMOUNT_INDEX = 0 TYPE_INDEX = 1 RAT_TYPE = 'R' RABBIT_TYPE = 'C' FROG_TYPE = 'S' def main(): n = int(input()) animal_total = 0 rat_total = 0 rabbit_total = 0 frog_total = 0 for i in range(n): input_line = input().split() amount = int(input_line[AMOUNT_INDEX]) type = input_line[TYPE_INDEX] animal_total += amount if type == RAT_TYPE: rat_total += amount elif type == RABBIT_TYPE: rabbit_total += amount elif type == FROG_TYPE: frog_total += amount print('Total: {:d} cobaias'.format(animal_total)) print('Total de coelhos: {:d}'.format(rabbit_total)) print('Total de ratos: {:d}'.format(rat_total)) print('Total de sapos: {:d}'.format(frog_total)) print('Percentual de coelhos: {:.2f} %'.format((rabbit_total * 100) / animal_total)) print('Percentual de ratos: {:.2f} %'.format((rat_total * 100) / animal_total)) print('Percentual de sapos: {:.2f} %'.format((frog_total * 100) / animal_total)) if __name__ == '__main__': main()
amount_index = 0 type_index = 1 rat_type = 'R' rabbit_type = 'C' frog_type = 'S' def main(): n = int(input()) animal_total = 0 rat_total = 0 rabbit_total = 0 frog_total = 0 for i in range(n): input_line = input().split() amount = int(input_line[AMOUNT_INDEX]) type = input_line[TYPE_INDEX] animal_total += amount if type == RAT_TYPE: rat_total += amount elif type == RABBIT_TYPE: rabbit_total += amount elif type == FROG_TYPE: frog_total += amount print('Total: {:d} cobaias'.format(animal_total)) print('Total de coelhos: {:d}'.format(rabbit_total)) print('Total de ratos: {:d}'.format(rat_total)) print('Total de sapos: {:d}'.format(frog_total)) print('Percentual de coelhos: {:.2f} %'.format(rabbit_total * 100 / animal_total)) print('Percentual de ratos: {:.2f} %'.format(rat_total * 100 / animal_total)) print('Percentual de sapos: {:.2f} %'.format(frog_total * 100 / animal_total)) if __name__ == '__main__': main()
# # This is a smaller script to just test the servos in the head # Start all services arduino = Runtime.start("arduino","Arduino") jaw = Runtime.start("jaw","Servo") rothead = Runtime.start("RotHead","Servo") leftEyeX = Runtime.start("LeftEyeX","Servo") rightEyeX = Runtime.start("RightEyeX","Servo") eyeY = Runtime.start("EyeY","Servo") # # Connect the Arduino arduino.connect("/dev/ttyACM0") # # Start of main script jaw.attach(arduino,9) jaw.setMinMax(80,120) # Connect the head turn left and right rothead.setRest(100) rothead.attach(arduino,8) rothead.setVelocity(20) rothead.rest() # Connect the left eye leftEyeX.setMinMax(50,110) leftEyeX.setRest(80) leftEyeX.attach(arduino,10) leftEyeX.rest() # Connect the right eye rightEyeX.setMinMax(60,120) rightEyeX.setRest(90) rightEyeX.attach(arduino,11) rightEyeX.rest() # Make the left eye follow the right # runtime.subscribe("rightEyeX","publishServoEvent","leftEyeY","MoveTo") # rightEyeX.eventsEnabled(True) # Connect eyes up/down eyeY.setMinMax(60,140) eyeY.setRest(90) eyeY.attach(arduino,12) eyeY.rest() def lookRight(): rightEyeX.moveTo(120) def lookLeft(): rightEyeX.moveTo(60) def lookForward(): rightEyeX.rest() eyeY.rest() def lookDown(): EyeY.moveTo(60) def lookUp(): EyeY.moveTo(140) def headRight(): rothead.moveTo(70) def headLeft(): rothead.moveTo(130) def headForward(): rothead.rest() lookRight() sleep(2) lookLeft() sleep(2) lookForward() sleep(2) lookUp() sleep(2) lookDown() sleep(2) lookForward() sleep(2) headRight() sleep(5) headLeft() # sleep(5) # headForward() # sleep(5)
arduino = Runtime.start('arduino', 'Arduino') jaw = Runtime.start('jaw', 'Servo') rothead = Runtime.start('RotHead', 'Servo') left_eye_x = Runtime.start('LeftEyeX', 'Servo') right_eye_x = Runtime.start('RightEyeX', 'Servo') eye_y = Runtime.start('EyeY', 'Servo') arduino.connect('/dev/ttyACM0') jaw.attach(arduino, 9) jaw.setMinMax(80, 120) rothead.setRest(100) rothead.attach(arduino, 8) rothead.setVelocity(20) rothead.rest() leftEyeX.setMinMax(50, 110) leftEyeX.setRest(80) leftEyeX.attach(arduino, 10) leftEyeX.rest() rightEyeX.setMinMax(60, 120) rightEyeX.setRest(90) rightEyeX.attach(arduino, 11) rightEyeX.rest() eyeY.setMinMax(60, 140) eyeY.setRest(90) eyeY.attach(arduino, 12) eyeY.rest() def look_right(): rightEyeX.moveTo(120) def look_left(): rightEyeX.moveTo(60) def look_forward(): rightEyeX.rest() eyeY.rest() def look_down(): EyeY.moveTo(60) def look_up(): EyeY.moveTo(140) def head_right(): rothead.moveTo(70) def head_left(): rothead.moveTo(130) def head_forward(): rothead.rest() look_right() sleep(2) look_left() sleep(2) look_forward() sleep(2) look_up() sleep(2) look_down() sleep(2) look_forward() sleep(2) head_right() sleep(5) head_left()
post1 = {"_id": 2, 'name': {'first': 'Dave', 'last': 'Ellis'}, 'contact': {'address': '510 N Division Street, Carson City, MI 48811', 'phone': '(989) 220-8277', 'location': 'Carson City'}, 'position': 'Disciple', 'mentor': 'Seth Roberts', 'status': 'Meeting' #Contacted, Meeting, Interests, Surveys } post2 = {"_id": 3, 'name': {'first': 'Steve', 'last': 'Williams'}, 'contact': {'address': '6039 E. Lake Moncalm Road, Edmore, MI 48829', 'phone': '(989) 565-0174', 'location': 'Cedar Lake'}, 'position': 'Disciple', 'mentor': 'Seth Roberts', 'status': 'Contacted' #Contacted, Meeting, Interests, Surveys } post3 = {"_id": 4, 'name': {'first': 'Nancy', 'last': 'Coon'}, 'contact': {'address': '11960 E. Edgar Road, Vestaburg, MI 48891', 'phone': '(989) 268-1001', 'location': 'Vestaburg'}, 'position': 'Disciple', 'mentor': 'Seth Roberts', 'status': 'Contacted' #Contacted, Meeting, Interests, Surveys }
post1 = {'_id': 2, 'name': {'first': 'Dave', 'last': 'Ellis'}, 'contact': {'address': '510 N Division Street, Carson City, MI 48811', 'phone': '(989) 220-8277', 'location': 'Carson City'}, 'position': 'Disciple', 'mentor': 'Seth Roberts', 'status': 'Meeting'} post2 = {'_id': 3, 'name': {'first': 'Steve', 'last': 'Williams'}, 'contact': {'address': '6039 E. Lake Moncalm Road, Edmore, MI 48829', 'phone': '(989) 565-0174', 'location': 'Cedar Lake'}, 'position': 'Disciple', 'mentor': 'Seth Roberts', 'status': 'Contacted'} post3 = {'_id': 4, 'name': {'first': 'Nancy', 'last': 'Coon'}, 'contact': {'address': '11960 E. Edgar Road, Vestaburg, MI 48891', 'phone': '(989) 268-1001', 'location': 'Vestaburg'}, 'position': 'Disciple', 'mentor': 'Seth Roberts', 'status': 'Contacted'}
print ("hello world") print ("hello again") print ("I like typing this.") print("This is fun") print('Yay! Printing.') print ("I'd much rather you 'not'.") print ('I "said" do not touch this.')
print('hello world') print('hello again') print('I like typing this.') print('This is fun') print('Yay! Printing.') print("I'd much rather you 'not'.") print('I "said" do not touch this.')
# coding=utf-8 class SelectionSort: def find_minimum_idx(self, array: list) -> int: min_element = array[0] min_idx = 0 for idx in range(1, len(array)): if array[idx] < min_element: min_idx = idx min_element = array[idx] return min_idx def sort(self, array: list) -> list: result = [] for _ in range(len(array)): min_idx = self.find_minimum_idx(array) result.append(array.pop(min_idx)) return result
class Selectionsort: def find_minimum_idx(self, array: list) -> int: min_element = array[0] min_idx = 0 for idx in range(1, len(array)): if array[idx] < min_element: min_idx = idx min_element = array[idx] return min_idx def sort(self, array: list) -> list: result = [] for _ in range(len(array)): min_idx = self.find_minimum_idx(array) result.append(array.pop(min_idx)) return result
def part_1(raw_data): raw_data.sort() median = raw_data[len(raw_data)//2] ans = 0 for val in raw_data: ans += abs(val - median) return ans def part_2(raw_data): average = int(round(sum(raw_data) / len(raw_data), 0)) adjusted_average = average - 1 ans = 0 for val in raw_data: distance = abs(val - adjusted_average) ans += (distance * (distance + 1)) // 2 return ans def file_reader(file_name): input_file = open(file_name, 'r') inputs_raw = input_file.readlines()[0].replace('\n', '').split(',') return [int(i) for i in inputs_raw] print(part_1(file_reader('input_07.txt'))) print(part_2(file_reader('input_07.txt')))
def part_1(raw_data): raw_data.sort() median = raw_data[len(raw_data) // 2] ans = 0 for val in raw_data: ans += abs(val - median) return ans def part_2(raw_data): average = int(round(sum(raw_data) / len(raw_data), 0)) adjusted_average = average - 1 ans = 0 for val in raw_data: distance = abs(val - adjusted_average) ans += distance * (distance + 1) // 2 return ans def file_reader(file_name): input_file = open(file_name, 'r') inputs_raw = input_file.readlines()[0].replace('\n', '').split(',') return [int(i) for i in inputs_raw] print(part_1(file_reader('input_07.txt'))) print(part_2(file_reader('input_07.txt')))
def h(): print('Wen Chuan') m = yield 5 print(m) d = yield 12 print('We are one') c = h() next(c) c.send('Fight') # next(c) def h1(): print('Wen Cha') m = yield 5 print(m) d = yield 12 print('We are together') c = h1() m = next(c) d = c.send('Fighting') print('We will never forger the date', m, '.', d)
def h(): print('Wen Chuan') m = (yield 5) print(m) d = (yield 12) print('We are one') c = h() next(c) c.send('Fight') def h1(): print('Wen Cha') m = (yield 5) print(m) d = (yield 12) print('We are together') c = h1() m = next(c) d = c.send('Fighting') print('We will never forger the date', m, '.', d)
test_list = [1, 2, 3, 4, 5, 6, 7] def rotate_by_one_left(array): temp = array[0] for i in range(len(array)-1): array[i] = array[i+1] array[-1] = temp def rotate_list(array, count): print("Rotate list {} by {}".format(array, count)) for i in range(count): # rotate_by_one_left(array) rotate_by_one_right(array) print("Rotated list {} by {}".format(array, count)) def rotate_by_one_right(array): temp = array[-1] for i in range(len(array)-1, 0, -1): array[i] = array[i-1] array[0] = temp # [1,2,3,4,5,6,7] = [7,1,2,3,4,5,6] if __name__ == "__main__": rotate_list(test_list, 1)
test_list = [1, 2, 3, 4, 5, 6, 7] def rotate_by_one_left(array): temp = array[0] for i in range(len(array) - 1): array[i] = array[i + 1] array[-1] = temp def rotate_list(array, count): print('Rotate list {} by {}'.format(array, count)) for i in range(count): rotate_by_one_right(array) print('Rotated list {} by {}'.format(array, count)) def rotate_by_one_right(array): temp = array[-1] for i in range(len(array) - 1, 0, -1): array[i] = array[i - 1] array[0] = temp if __name__ == '__main__': rotate_list(test_list, 1)
__author__ = "Dariusz Izak, Agnieszka Gromadka IBB PAS" __version__ = "1.6.3" __all__ = ["utilities"]
__author__ = 'Dariusz Izak, Agnieszka Gromadka IBB PAS' __version__ = '1.6.3' __all__ = ['utilities']
while True: n = int(input()) if n == 0: break for q in range(n): e = str(input()).split() nome = e[0] ano = int(e[1]) dif = int(e[2]) if q == 0: menor = ano - dif ganha = nome if menor > ano - dif: menor = ano - dif ganha = nome print(ganha)
while True: n = int(input()) if n == 0: break for q in range(n): e = str(input()).split() nome = e[0] ano = int(e[1]) dif = int(e[2]) if q == 0: menor = ano - dif ganha = nome if menor > ano - dif: menor = ano - dif ganha = nome print(ganha)
n = int(input()) narr = list(map(int,input().split())) mi = narr.index(min(narr)) ma = narr.index(max(narr)) narr[mi] , narr[ma] = narr[ma] , narr[mi] print(*narr)
n = int(input()) narr = list(map(int, input().split())) mi = narr.index(min(narr)) ma = narr.index(max(narr)) (narr[mi], narr[ma]) = (narr[ma], narr[mi]) print(*narr)
class Lcg(object): def __init__(self, seed): self.seed = seed self.st = seed def cur(self): return (self.st & 0b1111111111111110000000000000000) >> 16 def adv(self): self.st = (1103515245 * self.st + 12345) % (0b100000000000000000000000000000000) def gen(self): x = self.cur() self.adv() return x
class Lcg(object): def __init__(self, seed): self.seed = seed self.st = seed def cur(self): return (self.st & 2147418112) >> 16 def adv(self): self.st = (1103515245 * self.st + 12345) % 4294967296 def gen(self): x = self.cur() self.adv() return x
def tournamentWinner(competitions, results): ''' This fuction takes two arrays one of which contains competitions, another array contains results of the competitions and returns a string which is the winning team. This implementation has O(n) time complexity where n is the number of competitions, O(i) space complexity where i is the number of team. args: ------------- competitions (list) : nested array. Each element in the outer most list contains two teams. First one is home team and second one is awy team. results (list) : contains result of each competition. 0 if away team wins and 1 if home team wins. output: ------------- winner (str) : name of the champion of the tournament. ''' # dictionary 'scores' stores all team scores scores = {} #updating scores of each team by iteration over results and competitions. for i in range(len(results)): if results[i] == 0: if competitions[i][1] in scores: scores[competitions[i][1]] += 3 else: scores[competitions[i][1]] = 3 else: if competitions[i][0] in scores: scores[competitions[i][0]] += 3 else: scores[competitions[i][0]] = 3 # finding the max scorer from 'scores' dictionary max_score = 0 winner = '' for key in scores: score = scores[key] if score > max_score: max_score = score winner = str(key) return winner
def tournament_winner(competitions, results): """ This fuction takes two arrays one of which contains competitions, another array contains results of the competitions and returns a string which is the winning team. This implementation has O(n) time complexity where n is the number of competitions, O(i) space complexity where i is the number of team. args: ------------- competitions (list) : nested array. Each element in the outer most list contains two teams. First one is home team and second one is awy team. results (list) : contains result of each competition. 0 if away team wins and 1 if home team wins. output: ------------- winner (str) : name of the champion of the tournament. """ scores = {} for i in range(len(results)): if results[i] == 0: if competitions[i][1] in scores: scores[competitions[i][1]] += 3 else: scores[competitions[i][1]] = 3 elif competitions[i][0] in scores: scores[competitions[i][0]] += 3 else: scores[competitions[i][0]] = 3 max_score = 0 winner = '' for key in scores: score = scores[key] if score > max_score: max_score = score winner = str(key) return winner
class BlenderAddonManager(): ''' Class to manage all workflows around addon installation and update. ''' def __init__(self): pass def index(self): ''' Indexes all addons and save its metadata into the addon database. ''' pass def poll_remote_sources(self): ''' Polls remote addon sources to gather recent addon versions. ''' pass def download_addon(self): pass def install_addon(self): pass def remove_addon(self): pass
class Blenderaddonmanager: """ Class to manage all workflows around addon installation and update. """ def __init__(self): pass def index(self): """ Indexes all addons and save its metadata into the addon database. """ pass def poll_remote_sources(self): """ Polls remote addon sources to gather recent addon versions. """ pass def download_addon(self): pass def install_addon(self): pass def remove_addon(self): pass
class MyClass: def add(self, a, b): return a + b obj = MyClass() ret = obj.add(3, 4) print(ret)
class Myclass: def add(self, a, b): return a + b obj = my_class() ret = obj.add(3, 4) print(ret)
class Solution: def numUniqueEmails(self, emails: List[str]) -> int: def f(email): (localname, domain) = email.split('@') localname = localname.split('+')[0] localname = localname.replace('.','') return localname + "@" + domain return len(set(map(f, emails)))
class Solution: def num_unique_emails(self, emails: List[str]) -> int: def f(email): (localname, domain) = email.split('@') localname = localname.split('+')[0] localname = localname.replace('.', '') return localname + '@' + domain return len(set(map(f, emails)))
# count from zero to 10 for i in range(0,10): print (i) print("") # count by 2 for i in range(0,10,2): print(i) print("") # count by 5 start at 50 to 100 for i in range(50,100,5): print(i)
for i in range(0, 10): print(i) print('') for i in range(0, 10, 2): print(i) print('') for i in range(50, 100, 5): print(i)
str_btn_prev = "Previous" str_btn_next = "Next" str_btn_download = "Download" str_btn_reset = "Reset Annotation" str_btn_delete_bbox = "Delete Bbox" srt_validation_not_ok = "<b style=\"color:green\">NO ACTION REQUIRED</b>" srt_validation_ok = "<b style=\"color:RED\">ACTION REQUIRED</b>" info_new_ds = "New dataset with meta_annotations" info_missing = "Missing image" info_no_more_images = "No available images" info_total = "Total" info_class = "Class" info_class_name = "Class name" info_ann_images = "Annotated images" info_ann_objects = "Annotated objects" info_positions = "Positions:" info_completed = "Completed images:" info_incomplete = "Incomplete images:" info_completed_obj = "Completed objects:" info_incomplete_obj = "Incomplete objects:" info_ds_output = "Generated dataset will be saved at: " warn_select_class = "<b style=\"color:RED\">You must assing a class to all bbox before continuing</b>" warn_skip_wrong = "Skipping wrong annotation" warn_img_path_not_exits = "Image path does not exists " warn_task_not_supported = "Task type not supported" warn_no_images = "No images provided" warn_little_classes = "At least one class must be provided" warn_binary_only_two = "Binary datasets contain only 2 classes" warn_display_function_needed = "Non image data requires the definition of the custom display function" warn_no_images_criteria = "No images meet the specified criteria" warn_incorrect_class = "Class not present in dataset" warn_incorrect_property = "Meta-Annotation not present in dataset"
str_btn_prev = 'Previous' str_btn_next = 'Next' str_btn_download = 'Download' str_btn_reset = 'Reset Annotation' str_btn_delete_bbox = 'Delete Bbox' srt_validation_not_ok = '<b style="color:green">NO ACTION REQUIRED</b>' srt_validation_ok = '<b style="color:RED">ACTION REQUIRED</b>' info_new_ds = 'New dataset with meta_annotations' info_missing = 'Missing image' info_no_more_images = 'No available images' info_total = 'Total' info_class = 'Class' info_class_name = 'Class name' info_ann_images = 'Annotated images' info_ann_objects = 'Annotated objects' info_positions = 'Positions:' info_completed = 'Completed images:' info_incomplete = 'Incomplete images:' info_completed_obj = 'Completed objects:' info_incomplete_obj = 'Incomplete objects:' info_ds_output = 'Generated dataset will be saved at: ' warn_select_class = '<b style="color:RED">You must assing a class to all bbox before continuing</b>' warn_skip_wrong = 'Skipping wrong annotation' warn_img_path_not_exits = 'Image path does not exists ' warn_task_not_supported = 'Task type not supported' warn_no_images = 'No images provided' warn_little_classes = 'At least one class must be provided' warn_binary_only_two = 'Binary datasets contain only 2 classes' warn_display_function_needed = 'Non image data requires the definition of the custom display function' warn_no_images_criteria = 'No images meet the specified criteria' warn_incorrect_class = 'Class not present in dataset' warn_incorrect_property = 'Meta-Annotation not present in dataset'
# User inputs database = input(f'\nEnter the name of the database you want to create: ') environment = input(f'\nEnter the name of the environment (DTAP) you want to create: ') # Setting variables strdatabase = str(database) strenvironment = str(environment) # Composing the code line10 = ('CREATE ROLE IF NOT EXISTS RL_' + strdatabase + '_' + strenvironment +'_ADMIN;') line13 = ('GRANT ALL PRIVILEGES ON ACCOUNT TO ROLE RL_' + strdatabase + '_' + strenvironment +'_ADMIN;') line15 = ('GRANT ROLE RL_' + strdatabase + '_' + strenvironment +'_ADMIN TO USER JOHAN;') line20 = ('USE ROLE RL_' + strdatabase + '_' + strenvironment +'_ADMIN;') line30 = ('CREATE DATABASE DB_' + strdatabase + '_' + strenvironment +';') # Writing the lines to file file1='V1.1__createdatabase.sql' with open(file1,'w') as out: out.write('{}\n{}\n{}\n{}\n{}\n'.format(line10,line13,line15,line20,line30)) # Checking if the data is # written to file or not file1 = open('V1.1__createdatabase.sql', 'r') print(file1.read()) file1.close()
database = input(f'\nEnter the name of the database you want to create: ') environment = input(f'\nEnter the name of the environment (DTAP) you want to create: ') strdatabase = str(database) strenvironment = str(environment) line10 = 'CREATE ROLE IF NOT EXISTS RL_' + strdatabase + '_' + strenvironment + '_ADMIN;' line13 = 'GRANT ALL PRIVILEGES ON ACCOUNT TO ROLE RL_' + strdatabase + '_' + strenvironment + '_ADMIN;' line15 = 'GRANT ROLE RL_' + strdatabase + '_' + strenvironment + '_ADMIN TO USER JOHAN;' line20 = 'USE ROLE RL_' + strdatabase + '_' + strenvironment + '_ADMIN;' line30 = 'CREATE DATABASE DB_' + strdatabase + '_' + strenvironment + ';' file1 = 'V1.1__createdatabase.sql' with open(file1, 'w') as out: out.write('{}\n{}\n{}\n{}\n{}\n'.format(line10, line13, line15, line20, line30)) file1 = open('V1.1__createdatabase.sql', 'r') print(file1.read()) file1.close()
# twitter hashtag to find TWITTER_HASHTAG = "#StarWars" # twitter api credentials (https://apps.twitter.com/) TWITTER_CONSUMER_KEY = "" TWITTER_CONSUMER_SECRET = "" TWITTER_ACCESS_TOKEN = "" TWITTER_ACCESS_TOKEN_SECRET = "" # delay in seconds between reading tweets DELAY_TO_READ_TWEET = 30.0
twitter_hashtag = '#StarWars' twitter_consumer_key = '' twitter_consumer_secret = '' twitter_access_token = '' twitter_access_token_secret = '' delay_to_read_tweet = 30.0
# -*- coding: utf-8 -*- __author__ = 'Michael Odintsov' __email__ = 'templarrrr@gmail.com' __version__ = '0.1.0'
__author__ = 'Michael Odintsov' __email__ = 'templarrrr@gmail.com' __version__ = '0.1.0'
class UnionFind(object): def __init__(self, n): self.parent = list(range(n)) self.rank = [0] * n def find(self, u): if u != self.parent[u]: self.parent[u] = self.find(self.parent[u]) return self.parent[u] def isConnected(self, u, v): return self.find(u) == self.find(v) def union(self, u, v): pu = self.find(u) pv = self.find(v) if pu == pv: return False if self.rank[pv] > self.rank[pu]: self.parent[pu] = pv elif self.rank[pu] > self.rank[pv]: self.parent[pv] = pu else: self.parent[pu] = pv self.rank[pv] += 1 return True u = UnionFind(6) u.union(3, 4) u.union(2, 3) u.union(1, 2) u.union(0, 1)
class Unionfind(object): def __init__(self, n): self.parent = list(range(n)) self.rank = [0] * n def find(self, u): if u != self.parent[u]: self.parent[u] = self.find(self.parent[u]) return self.parent[u] def is_connected(self, u, v): return self.find(u) == self.find(v) def union(self, u, v): pu = self.find(u) pv = self.find(v) if pu == pv: return False if self.rank[pv] > self.rank[pu]: self.parent[pu] = pv elif self.rank[pu] > self.rank[pv]: self.parent[pv] = pu else: self.parent[pu] = pv self.rank[pv] += 1 return True u = union_find(6) u.union(3, 4) u.union(2, 3) u.union(1, 2) u.union(0, 1)
with open('input') as input: lines = input.readlines() number_sequence = lines[0].split(',') board_numbers = [] called_indexes = [] # Flatten data structure for boards for i, line in enumerate(lines): if i == 0: continue if line == '\n': continue stripped_line = line.strip('\n') num_list = line.split() for num in num_list: board_numbers.append(num) def checkForWin(board_numbers, called_indexes, num): for i, space in enumerate(board_numbers): if space == num: # print(f"Space at index {i} contains called number {num}") called_indexes.append(i) # Check for win based on indexes board_index = i // 25 row_pos = i % 5 row_start = i - row_pos col_start = i - (i % 25 - row_pos) # print(f"X value = {i % 5}") # print(f"line_start = {line_start}") horizontal_win = True for j in range(row_start, row_start+5): if j not in called_indexes: horizontal_win = False vertical_win = True for j in range(col_start, col_start+25, 5): if j not in called_indexes: vertical_win = False if horizontal_win or vertical_win: print(f"Winner on board {board_index}") return board_index # "Call" numbers and check for winner winner = None for num in number_sequence: winner = checkForWin(board_numbers, called_indexes, num) if winner != None: board_start = winner*25 unmarked_sum = 0 for i in range(board_start, board_start+25): if i not in called_indexes: unmarked_sum += int(board_numbers[i]) print(f"SOLUTION = {unmarked_sum} * {num} = {int(unmarked_sum) * int(num)}") break
with open('input') as input: lines = input.readlines() number_sequence = lines[0].split(',') board_numbers = [] called_indexes = [] for (i, line) in enumerate(lines): if i == 0: continue if line == '\n': continue stripped_line = line.strip('\n') num_list = line.split() for num in num_list: board_numbers.append(num) def check_for_win(board_numbers, called_indexes, num): for (i, space) in enumerate(board_numbers): if space == num: called_indexes.append(i) board_index = i // 25 row_pos = i % 5 row_start = i - row_pos col_start = i - (i % 25 - row_pos) horizontal_win = True for j in range(row_start, row_start + 5): if j not in called_indexes: horizontal_win = False vertical_win = True for j in range(col_start, col_start + 25, 5): if j not in called_indexes: vertical_win = False if horizontal_win or vertical_win: print(f'Winner on board {board_index}') return board_index winner = None for num in number_sequence: winner = check_for_win(board_numbers, called_indexes, num) if winner != None: board_start = winner * 25 unmarked_sum = 0 for i in range(board_start, board_start + 25): if i not in called_indexes: unmarked_sum += int(board_numbers[i]) print(f'SOLUTION = {unmarked_sum} * {num} = {int(unmarked_sum) * int(num)}') break
ten_things = "Apples Oranges Crows Telephone Light Sugar" print ("Wait there's not 10 things in that list, let's fix that.") stuff = ten_things.split(' ') more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"] while len(stuff) != 10: next_one = more_stuff.pop() print ("Adding: ", next_one) stuff.append(next_one) print ("There's %d items now." % len(stuff)) print ("There we go: ", stuff) print ("Let's do some things with stuff.") print (stuff[1]) print (stuff[-1]) # whoa! fancy print (stuff.pop()) print (' '.join(stuff)) # what? cool print ('#'.join(stuff[3:5])) # super stellar!
ten_things = 'Apples Oranges Crows Telephone Light Sugar' print("Wait there's not 10 things in that list, let's fix that.") stuff = ten_things.split(' ') more_stuff = ['Day', 'Night', 'Song', 'Frisbee', 'Corn', 'Banana', 'Girl', 'Boy'] while len(stuff) != 10: next_one = more_stuff.pop() print('Adding: ', next_one) stuff.append(next_one) print("There's %d items now." % len(stuff)) print('There we go: ', stuff) print("Let's do some things with stuff.") print(stuff[1]) print(stuff[-1]) print(stuff.pop()) print(' '.join(stuff)) print('#'.join(stuff[3:5]))