content
stringlengths
7
1.05M
# 6. Zigzag Conversion # Runtime: 103 ms, faster than 20.89% of Python3 online submissions for Zigzag Conversion. # Memory Usage: 14.7 MB, less than 13.84% of Python3 online submissions for Zigzag Conversion. class Solution: def convert(self, s: str, numRows: int) -> str: if numRows == 1: return s rows = [[] for _ in range(numRows)] # In the first and last rows, the interval between two adjacent elements is the larget. largest_interval = (numRows * 2) - 2 for r in range(numRows): i = r # In other rows, The sum of the intervals of every three elements is equal to the larget interval. curr_interval = largest_interval - 2 * r if curr_interval == 0: curr_interval = largest_interval while i < len(s): rows[r].append(s[i]) i += curr_interval if curr_interval != largest_interval: curr_interval = largest_interval - curr_interval ans = [] for row in rows: ans.extend(row) return "".join(ans)
# # PySNMP MIB module AGENTX-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AGENTX-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:15:42 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ValueSizeConstraint, SingleValueConstraint, ConstraintsIntersection, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsIntersection", "ConstraintsUnion") SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup") Counter64, mib_2, NotificationType, Bits, iso, Unsigned32, MibIdentifier, TimeTicks, ObjectIdentity, Integer32, ModuleIdentity, Gauge32, IpAddress, Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols("SNMPv2-SMI", "Counter64", "mib-2", "NotificationType", "Bits", "iso", "Unsigned32", "MibIdentifier", "TimeTicks", "ObjectIdentity", "Integer32", "ModuleIdentity", "Gauge32", "IpAddress", "Counter32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn") TimeStamp, DisplayString, TextualConvention, TDomain, TruthValue = mibBuilder.importSymbols("SNMPv2-TC", "TimeStamp", "DisplayString", "TextualConvention", "TDomain", "TruthValue") agentxMIB = ModuleIdentity((1, 3, 6, 1, 2, 1, 74)) agentxMIB.setRevisions(('2000-01-10 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: agentxMIB.setRevisionsDescriptions(('Initial version published as RFC 2742.',)) if mibBuilder.loadTexts: agentxMIB.setLastUpdated('200001100000Z') if mibBuilder.loadTexts: agentxMIB.setOrganization('AgentX Working Group') if mibBuilder.loadTexts: agentxMIB.setContactInfo('WG-email: agentx@dorothy.bmc.com Subscribe: agentx-request@dorothy.bmc.com WG-email Archive: ftp://ftp.peer.com/pub/agentx/archives FTP repository: ftp://ftp.peer.com/pub/agentx http://www.ietf.org/html.charters/agentx-charter.html Chair: Bob Natale ACE*COMM Corporation Email: bnatale@acecomm.com WG editor: Mark Ellison Ellison Software Consulting, Inc. Email: ellison@world.std.com Co-author: Lauren Heintz Cisco Systems, EMail: lheintz@cisco.com Co-author: Smitha Gudur Independent Consultant Email: sgudur@hotmail.com ') if mibBuilder.loadTexts: agentxMIB.setDescription('This is the MIB module for the SNMP Agent Extensibility Protocol (AgentX). This MIB module will be implemented by the master agent. ') class AgentxTAddress(TextualConvention, OctetString): description = 'Denotes a transport service address. This is identical to the TAddress textual convention (SNMPv2-SMI) except that zero-length values are permitted. ' status = 'current' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(0, 255) agentxObjects = MibIdentifier((1, 3, 6, 1, 2, 1, 74, 1)) agentxGeneral = MibIdentifier((1, 3, 6, 1, 2, 1, 74, 1, 1)) agentxConnection = MibIdentifier((1, 3, 6, 1, 2, 1, 74, 1, 2)) agentxSession = MibIdentifier((1, 3, 6, 1, 2, 1, 74, 1, 3)) agentxRegistration = MibIdentifier((1, 3, 6, 1, 2, 1, 74, 1, 4)) agentxDefaultTimeout = MibScalar((1, 3, 6, 1, 2, 1, 74, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255)).clone(5)).setUnits('seconds').setMaxAccess("readonly") if mibBuilder.loadTexts: agentxDefaultTimeout.setStatus('current') if mibBuilder.loadTexts: agentxDefaultTimeout.setDescription('The default length of time, in seconds, that the master agent should allow to elapse after dispatching a message to a session before it regards the subagent as not responding. This is a system-wide value that may override the timeout value associated with a particular session (agentxSessionTimeout) or a particular registered MIB region (agentxRegTimeout). If the associated value of agentxSessionTimeout and agentxRegTimeout are zero, or impractical in accordance with implementation-specific procedure of the master agent, the value represented by this object will be the effective timeout value for the master agent to await a response to a dispatch from a given subagent. ') agentxMasterAgentXVer = MibScalar((1, 3, 6, 1, 2, 1, 74, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: agentxMasterAgentXVer.setStatus('current') if mibBuilder.loadTexts: agentxMasterAgentXVer.setDescription('The AgentX protocol version supported by this master agent. The current protocol version is 1. Note that the master agent must also allow interaction with earlier version subagents. ') agentxConnTableLastChange = MibScalar((1, 3, 6, 1, 2, 1, 74, 1, 2, 1), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: agentxConnTableLastChange.setStatus('current') if mibBuilder.loadTexts: agentxConnTableLastChange.setDescription('The value of sysUpTime when the last row creation or deletion occurred in the agentxConnectionTable. ') agentxConnectionTable = MibTable((1, 3, 6, 1, 2, 1, 74, 1, 2, 2), ) if mibBuilder.loadTexts: agentxConnectionTable.setStatus('current') if mibBuilder.loadTexts: agentxConnectionTable.setDescription('The agentxConnectionTable tracks all current AgentX transport connections. There may be zero, one, or more AgentX sessions carried on a given AgentX connection. ') agentxConnectionEntry = MibTableRow((1, 3, 6, 1, 2, 1, 74, 1, 2, 2, 1), ).setIndexNames((0, "AGENTX-MIB", "agentxConnIndex")) if mibBuilder.loadTexts: agentxConnectionEntry.setStatus('current') if mibBuilder.loadTexts: agentxConnectionEntry.setDescription('An agentxConnectionEntry contains information describing a single AgentX transport connection. A connection may be used to support zero or more AgentX sessions. An entry is created when a new transport connection is established, and is destroyed when the transport connection is terminated. ') agentxConnIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 2, 2, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 4294967295))) if mibBuilder.loadTexts: agentxConnIndex.setStatus('current') if mibBuilder.loadTexts: agentxConnIndex.setDescription('agentxConnIndex contains the value that uniquely identifies an open transport connection used by this master agent to provide AgentX service. Values of this index should not be re-used. The value assigned to a given transport connection is constant for the lifetime of that connection. ') agentxConnOpenTime = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 2, 2, 1, 2), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: agentxConnOpenTime.setStatus('current') if mibBuilder.loadTexts: agentxConnOpenTime.setDescription('The value of sysUpTime when this connection was established and, therefore, its value when this entry was added to the table. ') agentxConnTransportDomain = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 2, 2, 1, 3), TDomain()).setMaxAccess("readonly") if mibBuilder.loadTexts: agentxConnTransportDomain.setStatus('current') if mibBuilder.loadTexts: agentxConnTransportDomain.setDescription('The transport protocol in use for this connection to the subagent. ') agentxConnTransportAddress = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 2, 2, 1, 4), AgentxTAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: agentxConnTransportAddress.setStatus('current') if mibBuilder.loadTexts: agentxConnTransportAddress.setDescription('The transport address of the remote (subagent) end of this connection to the master agent. This object may be zero-length for unix-domain sockets (and possibly other types of transport addresses) since the subagent need not bind a filename to its local socket. ') agentxSessionTableLastChange = MibScalar((1, 3, 6, 1, 2, 1, 74, 1, 3, 1), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: agentxSessionTableLastChange.setStatus('current') if mibBuilder.loadTexts: agentxSessionTableLastChange.setDescription('The value of sysUpTime when the last row creation or deletion occurred in the agentxSessionTable. ') agentxSessionTable = MibTable((1, 3, 6, 1, 2, 1, 74, 1, 3, 2), ) if mibBuilder.loadTexts: agentxSessionTable.setStatus('current') if mibBuilder.loadTexts: agentxSessionTable.setDescription('A table of AgentX subagent sessions currently in effect. ') agentxSessionEntry = MibTableRow((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1), ).setIndexNames((0, "AGENTX-MIB", "agentxConnIndex"), (0, "AGENTX-MIB", "agentxSessionIndex")) if mibBuilder.loadTexts: agentxSessionEntry.setStatus('current') if mibBuilder.loadTexts: agentxSessionEntry.setDescription('Information about a single open session between the AgentX master agent and a subagent is contained in this entry. An entry is created when a new session is successfully established and is destroyed either when the subagent transport connection has terminated or when the subagent session is closed. ') agentxSessionIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))) if mibBuilder.loadTexts: agentxSessionIndex.setStatus('current') if mibBuilder.loadTexts: agentxSessionIndex.setDescription("A unique index for the subagent session. It is the same as h.sessionID defined in the agentx header. Note that if a subagent's session with the master agent is closed for any reason its index should not be re-used. A value of zero(0) is specifically allowed in order to be compatible with the definition of h.sessionId. ") agentxSessionObjectID = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 2), ObjectIdentifier()).setMaxAccess("readonly") if mibBuilder.loadTexts: agentxSessionObjectID.setStatus('current') if mibBuilder.loadTexts: agentxSessionObjectID.setDescription("This is taken from the o.id field of the agentx-Open-PDU. This attribute will report a value of '0.0' for subagents not supporting the notion of an AgentX session object identifier. ") agentxSessionDescr = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 3), SnmpAdminString()).setMaxAccess("readonly") if mibBuilder.loadTexts: agentxSessionDescr.setStatus('current') if mibBuilder.loadTexts: agentxSessionDescr.setDescription('A textual description of the session. This is analogous to sysDescr defined in the SNMPv2-MIB in RFC 1907 [19] and is taken from the o.descr field of the agentx-Open-PDU. This attribute will report a zero-length string value for subagents not supporting the notion of a session description. ') agentxSessionAdminStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("up", 1), ("down", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: agentxSessionAdminStatus.setStatus('current') if mibBuilder.loadTexts: agentxSessionAdminStatus.setDescription("The administrative (desired) status of the session. Setting the value to 'down(2)' closes the subagent session (with c.reason set to 'reasonByManager'). ") agentxSessionOpenTime = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 5), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: agentxSessionOpenTime.setStatus('current') if mibBuilder.loadTexts: agentxSessionOpenTime.setDescription('The value of sysUpTime when this session was opened and, therefore, its value when this entry was added to the table. ') agentxSessionAgentXVer = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: agentxSessionAgentXVer.setStatus('current') if mibBuilder.loadTexts: agentxSessionAgentXVer.setDescription('The version of the AgentX protocol supported by the session. This must be less than or equal to the value of agentxMasterAgentXVer. ') agentxSessionTimeout = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setUnits('seconds').setMaxAccess("readonly") if mibBuilder.loadTexts: agentxSessionTimeout.setStatus('current') if mibBuilder.loadTexts: agentxSessionTimeout.setDescription("The length of time, in seconds, that a master agent should allow to elapse after dispatching a message to this session before it regards the subagent as not responding. This value is taken from the o.timeout field of the agentx-Open-PDU. This is a session-specific value that may be overridden by values associated with the specific registered MIB regions (see agentxRegTimeout). A value of zero(0) indicates that the master agent's default timeout value should be used (see agentxDefaultTimeout). ") agentxRegistrationTableLastChange = MibScalar((1, 3, 6, 1, 2, 1, 74, 1, 4, 1), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: agentxRegistrationTableLastChange.setStatus('current') if mibBuilder.loadTexts: agentxRegistrationTableLastChange.setDescription('The value of sysUpTime when the last row creation or deletion occurred in the agentxRegistrationTable. ') agentxRegistrationTable = MibTable((1, 3, 6, 1, 2, 1, 74, 1, 4, 2), ) if mibBuilder.loadTexts: agentxRegistrationTable.setStatus('current') if mibBuilder.loadTexts: agentxRegistrationTable.setDescription('A table of registered regions. ') agentxRegistrationEntry = MibTableRow((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1), ).setIndexNames((0, "AGENTX-MIB", "agentxConnIndex"), (0, "AGENTX-MIB", "agentxSessionIndex"), (0, "AGENTX-MIB", "agentxRegIndex")) if mibBuilder.loadTexts: agentxRegistrationEntry.setStatus('current') if mibBuilder.loadTexts: agentxRegistrationEntry.setDescription('Contains information for a single registered region. An entry is created when a session successfully registers a region and is destroyed for any of three reasons: this region is unregistered by the session, the session is closed, or the subagent connection is closed. ') agentxRegIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 4294967295))) if mibBuilder.loadTexts: agentxRegIndex.setStatus('current') if mibBuilder.loadTexts: agentxRegIndex.setDescription('agentxRegIndex uniquely identifies a registration entry. This value is constant for the lifetime of an entry. ') agentxRegContext = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 2), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: agentxRegContext.setStatus('current') if mibBuilder.loadTexts: agentxRegContext.setDescription('The context in which the session supports the objects in this region. A zero-length context indicates the default context. ') agentxRegStart = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 3), ObjectIdentifier()).setMaxAccess("readonly") if mibBuilder.loadTexts: agentxRegStart.setStatus('current') if mibBuilder.loadTexts: agentxRegStart.setDescription('The starting OBJECT IDENTIFIER of this registration entry. The session identified by agentxSessionIndex implements objects starting at this value (inclusive). Note that this value could identify an object type, an object instance, or a partial object instance. ') agentxRegRangeSubId = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 4), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: agentxRegRangeSubId.setStatus('current') if mibBuilder.loadTexts: agentxRegRangeSubId.setDescription("agentxRegRangeSubId is used to specify the range. This is taken from r.region_subid in the registration PDU. If the value of this object is zero, no range is specified. If it is non-zero, it identifies the `nth' sub-identifier in r.region for which this entry's agentxRegUpperBound value is substituted in the OID for purposes of defining the region's upper bound. ") agentxRegUpperBound = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 5), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: agentxRegUpperBound.setStatus('current') if mibBuilder.loadTexts: agentxRegUpperBound.setDescription('agentxRegUpperBound represents the upper-bound sub-identifier in a registration. This is taken from the r.upper_bound in the registration PDU. If agentxRegRangeSubid (r.region_subid) is zero, this value is also zero and is not used to define an upper bound for this registration. ') agentxRegPriority = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 6), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: agentxRegPriority.setStatus('current') if mibBuilder.loadTexts: agentxRegPriority.setDescription('The registration priority. Lower values have higher priority. This value is taken from r.priority in the register PDU. Sessions should use the value of 127 for r.priority if a default value is desired. ') agentxRegTimeout = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setUnits('seconds').setMaxAccess("readonly") if mibBuilder.loadTexts: agentxRegTimeout.setStatus('current') if mibBuilder.loadTexts: agentxRegTimeout.setDescription('The timeout value, in seconds, for responses to requests associated with this registered MIB region. A value of zero(0) indicates the default value (indicated by by agentxSessionTimeout or agentxDefaultTimeout) is to be used. This value is taken from the r.timeout field of the agentx-Register-PDU. ') agentxRegInstance = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 8), TruthValue()).setMaxAccess("readonly") if mibBuilder.loadTexts: agentxRegInstance.setStatus('current') if mibBuilder.loadTexts: agentxRegInstance.setDescription("The value of agentxRegInstance is `true' for registrations for which the INSTANCE_REGISTRATION was set, and is `false' for all other registrations. ") agentxConformance = MibIdentifier((1, 3, 6, 1, 2, 1, 74, 2)) agentxMIBGroups = MibIdentifier((1, 3, 6, 1, 2, 1, 74, 2, 1)) agentxMIBCompliances = MibIdentifier((1, 3, 6, 1, 2, 1, 74, 2, 2)) agentxMIBCompliance = ModuleCompliance((1, 3, 6, 1, 2, 1, 74, 2, 2, 1)).setObjects(("AGENTX-MIB", "agentxMIBGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): agentxMIBCompliance = agentxMIBCompliance.setStatus('current') if mibBuilder.loadTexts: agentxMIBCompliance.setDescription('The compliance statement for SNMP entities that implement the AgentX protocol. Note that a compliant agent can implement all objects in this MIB module as read-only. ') agentxMIBGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 74, 2, 1, 1)).setObjects(("AGENTX-MIB", "agentxDefaultTimeout"), ("AGENTX-MIB", "agentxMasterAgentXVer"), ("AGENTX-MIB", "agentxConnTableLastChange"), ("AGENTX-MIB", "agentxConnOpenTime"), ("AGENTX-MIB", "agentxConnTransportDomain"), ("AGENTX-MIB", "agentxConnTransportAddress"), ("AGENTX-MIB", "agentxSessionTableLastChange"), ("AGENTX-MIB", "agentxSessionTimeout"), ("AGENTX-MIB", "agentxSessionObjectID"), ("AGENTX-MIB", "agentxSessionDescr"), ("AGENTX-MIB", "agentxSessionAdminStatus"), ("AGENTX-MIB", "agentxSessionOpenTime"), ("AGENTX-MIB", "agentxSessionAgentXVer"), ("AGENTX-MIB", "agentxRegistrationTableLastChange"), ("AGENTX-MIB", "agentxRegContext"), ("AGENTX-MIB", "agentxRegStart"), ("AGENTX-MIB", "agentxRegRangeSubId"), ("AGENTX-MIB", "agentxRegUpperBound"), ("AGENTX-MIB", "agentxRegPriority"), ("AGENTX-MIB", "agentxRegTimeout"), ("AGENTX-MIB", "agentxRegInstance")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): agentxMIBGroup = agentxMIBGroup.setStatus('current') if mibBuilder.loadTexts: agentxMIBGroup.setDescription('All accessible objects in the AgentX MIB. ') mibBuilder.exportSymbols("AGENTX-MIB", agentxConnTransportAddress=agentxConnTransportAddress, agentxRegistrationTable=agentxRegistrationTable, agentxMIBGroups=agentxMIBGroups, agentxSession=agentxSession, agentxDefaultTimeout=agentxDefaultTimeout, agentxConformance=agentxConformance, agentxGeneral=agentxGeneral, PYSNMP_MODULE_ID=agentxMIB, agentxConnTransportDomain=agentxConnTransportDomain, agentxSessionTableLastChange=agentxSessionTableLastChange, AgentxTAddress=AgentxTAddress, agentxRegInstance=agentxRegInstance, agentxMIBCompliances=agentxMIBCompliances, agentxRegistration=agentxRegistration, agentxConnIndex=agentxConnIndex, agentxConnOpenTime=agentxConnOpenTime, agentxRegIndex=agentxRegIndex, agentxMIB=agentxMIB, agentxSessionIndex=agentxSessionIndex, agentxRegistrationTableLastChange=agentxRegistrationTableLastChange, agentxSessionEntry=agentxSessionEntry, agentxRegRangeSubId=agentxRegRangeSubId, agentxConnTableLastChange=agentxConnTableLastChange, agentxSessionAgentXVer=agentxSessionAgentXVer, agentxSessionOpenTime=agentxSessionOpenTime, agentxRegTimeout=agentxRegTimeout, agentxMIBGroup=agentxMIBGroup, agentxSessionTable=agentxSessionTable, agentxSessionObjectID=agentxSessionObjectID, agentxRegStart=agentxRegStart, agentxSessionTimeout=agentxSessionTimeout, agentxConnectionTable=agentxConnectionTable, agentxConnectionEntry=agentxConnectionEntry, agentxRegPriority=agentxRegPriority, agentxMIBCompliance=agentxMIBCompliance, agentxRegistrationEntry=agentxRegistrationEntry, agentxRegUpperBound=agentxRegUpperBound, agentxConnection=agentxConnection, agentxObjects=agentxObjects, agentxSessionAdminStatus=agentxSessionAdminStatus, agentxMasterAgentXVer=agentxMasterAgentXVer, agentxRegContext=agentxRegContext, agentxSessionDescr=agentxSessionDescr)
class Layer: def __init(self): self.input=None self.output=None def forward(self,input): #to return the output layer pass def backward(self,output_gradient,learning_rate): #change para and return input derivative pass
class Capture: def capture(self): pass
def f(n): if n == 0: return 0 elif n == 1: return 1 else: return f(n-1)+f(n-2) n=int(input()) values = [str(f(x)) for x in range(0, n+1)] print(",".join(values))
#TODO Create Functions for PMTA ## TORISPHERICAL TOP HEAD 2:1 - Min thickness allowed and PMTA class TorisphericalCalcs: def __init__(self): self.L_top_head = None self.r_top_head = None self.ratio_L_r_top = None self.M_factor_top_head = None self.t_min_top_head = None self.t_nom_top_head_plate =None self.t_top_head_nom_after_conf = None self.top_head_pmta = None self.L_bottom_head = None self.r_bottom_head = None self.ratio_L_r_bottom = None self.M_factor_bottom_head = None self.t_min_bottom_head = None self.t_nom_bottom_head_plate = None self.t_bottom_head_nom_after_conf = None self.bottom_head_pmta = None def tor_top_min_thick_allowed(self,Rcor, P, Shot_top_head, E, conf_loss, C): self.L_top_head = 0.904 * (2 * Rcor) self.r_top_head = 0.173 * (2 * Rcor) self.ratio_L_r_top = self.L_top_head/self.r_top_head self.M_factor_top_head = (1/4) * (3 + (self.ratio_L_r_top)**(1/2)) self.t_min_top_head = (P * self.L_top_head * self.M_factor_top_head) / ((2 * Shot_top_head * E) - 0.2 * P) self.t_nom_top_head_plate = self.t_min_top_head + conf_loss + C self.t_top_head_nom_after_conf = self.t_min_top_head + C print(f"\n\nTorispherical Top Head Min thickness allowed: \n\nTop Head radius (L) is {self.L_top_head} mm \nTop Head Toroidal radius (r) is {self.r_top_head} mm \nTop Head M factor (M) is {self.M_factor_top_head}") print(f"Top Head minimun thickness due circuferencial stress is {self.t_min_top_head} mm.") print(f"Top Head plate Thickness w/ Corrosion allowance and conf. loss is {self.t_nom_top_head_plate} mm. Ps.: Choose equal or higher comercial plate") print(f"Top Head Nominal Thicknes after conformation is {self.t_top_head_nom_after_conf} mm") return self.L_top_head, self.r_top_head, self.ratio_L_r_top , self.M_factor_top_head, self.t_nom_top_head_plate, self.t_top_head_nom_after_conf, self.t_min_top_head def tor_top_head_pmta (self,Rcor, Shot_top_head, E): self.L_top_head = 0.904 * (2 * Rcor) self.r_top_head = 0.173 * (2 * Rcor) self.ratio_L_r_top = self.L_top_head/self.r_top_head self.M_factor_top_head = (1/4) * (3 + (self.ratio_L_r_top)**(1/2)) self.top_head_pmta = (2*self.t_min_top_head*Shot_top_head*E)/(self.L_top_head*self.M_factor_top_head + 0.2*self.t_min_top_head) print(f"Top Head MAWP is: {self.top_head_pmta} kPa") return self.top_head_pmta def tor_top_head_stress_calc(self, P, E): self.top_head_stress = P * (self.L_top_head * self.M_factor_top_head + 0.2 * self.t_min_top_head) / (2 * self.t_min_top_head * E) print(f"Top head stress is {self.top_head_stress} kPa") return self.top_head_stress ## TORISPHERICAL BOTTOM HEAD 2:1 - Min thickness allowed and PMTA def tor_bottom_min_thick_allowed(self,Rcor,Pwater_col, P, Shot_bottom_head, E, conf_loss, C ): self.L_bottom_head = 0.904 * (2 * Rcor) self.r_bottom_head = 0.173 * (2 * Rcor) self.ratio_L_r_bottom = self.L_bottom_head/self.r_bottom_head self.M_factor_bottom_head = (1/4) * (3 + (self.ratio_L_r_bottom)**(1/2)) self.t_min_bottom_head = ((P+Pwater_col) * self.L_bottom_head * self.M_factor_bottom_head) / ((2 * Shot_bottom_head * E) - 0.2 * P) self.t_nom_bottom_head_plate = self.t_min_bottom_head + conf_loss + C self.t_bottom_head_nom_after_conf = self.t_min_bottom_head + C print(f"\n\nTorispherical Bottom Head Min thickness allowed: \n\nBottom Head radius (L) is {self.L_bottom_head} mm \nBottom Head Toroidal radius (r) is {self.r_bottom_head} mm \nBottom Head M factor (M) is {self.M_factor_bottom_head}") print(f"Bottom Head minimun thickness due circuferencial stress is {self.t_min_bottom_head} mm.") print(f"Bottom Head plate Thickness w/ Corrosion allowance and conf. loss is {self.t_nom_bottom_head_plate} mm. Ps.: Choose equal or higher comercial plate") print(f"Bottom Head Nominal Thicknes after conformation is {self.t_bottom_head_nom_after_conf} mm") return self.L_bottom_head, self.r_bottom_head, self.ratio_L_r_bottom, self.M_factor_bottom_head, self.t_min_bottom_head, self.t_nom_bottom_head_plate, self.t_bottom_head_nom_after_conf def tor_bottom_head_pmta (self,Rcor, E, Shot_bottom_head): self.L_bottom_head = 0.904 * (2 * Rcor) self.r_bottom_head = 0.173 * (2 * Rcor) self.ratio_L_r_bottom = self.L_bottom_head/self.r_bottom_head self.M_factor_bottom_head = (1/4) * (3 + (self.ratio_L_r_bottom)**(1/2)) self.bottom_head_pmta = (2*self.t_min_bottom_head*Shot_bottom_head*E)/(self.L_bottom_head*self.M_factor_bottom_head + 0.2*self.t_min_bottom_head) print(f"Bottom Head MAWP is: {self.bottom_head_pmta} kPa") return self.bottom_head_pmta def tor_bottom_head_stress_calc(self,Pwater_col, P, E): self.bottom_head_stress = (P+Pwater_col) * (self.L_bottom_head * self.M_factor_bottom_head + 0.2 * self.t_min_bottom_head) / (2 * self.t_min_bottom_head * E) print(f"Bottom head stress is {self.bottom_head_stress} kPa") return self.bottom_head_stress
''' Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. Example 1: Input: 5 Output: True Explanation: The binary representation of 5 is: 101 Example 2: Input: 7 Output: False Explanation: The binary representation of 7 is: 111. Example 3: Input: 11 Output: False Explanation: The binary representation of 11 is: 1011. Example 4: Input: 10 Output: True Explanation: The binary representation of 10 is: 1010. ''' class Solution(object): def hasAlternatingBits(self, n): """ :type n: int :rtype: bool """ last_bit = n & 1 n >>= 1 while n > 0: tmp = n & 1 if tmp == last_bit: return False last_bit = tmp n >>= 1 return True
# Collaborators (including web sites where you got help: (enter none if you didn't need help) # claryse adams def avg_temp(user_list): total = 0 for x in range(1, len(user_list)): total += user_list[x] average = total/(len(user_list)-1) average = round(average, 2) return average if __name__ == '__main__': with open("temps.txt") as file_object: contents = file_object.readlines() int() list_length = len(contents) for i in range(1, list_length): contents[i] = contents[i].rstrip() contents[i] = int(contents[i]) print(contents) print(avg_temp(contents))
def fry(): print('The eggs have been fried')
class Data: def __init__(self, dia, mes, ano): self.dia = dia self.mes = mes self.ano = ano print(self) @classmethod def de_string(cls, data_string): dia, mes, ano = map(int, data_string.split("-")) data = cls(dia, mes, ano) return data @staticmethod def is_date_valid(data_string): dia, mes, ano = map(int, data_string.split("-")) return dia <= 31 and mes <= 12 and ano <= 2030 data = Data(10, 10, 10) data1 = data.de_string("10-10-2020") print(data1) vdd = data1.is_date_valid("10-10-2020") print(vdd)
""" Created by adam on 5/20/18 """ __author__ = 'adam' class IModifierList(object): """ Interface for classes which act on a list of strings by modifying the input strings and returning a list of modified strings. Used for tasks like lemmatizing etc """ def __init__(self): pass def run(self, wordbag, **kwargs): """ Processes list of strings :param wordbag: List of strings to run :param kwargs: :return: List of strings, modified """ raise NotImplementedError class IModifier(object): """ Interface for classes which modify the input string and return the modified string. Used for tasks like stemming lemmatizing etc """ def __init__(self): pass def run(self, text, **kwargs): raise NotImplementedError def _check_is_single_word(self, text): """ Some implmentations of IModifier allow for sentences. Others want just one word at a time. This is called by the latter and checks to make sure that it has the correct input :param text: String to screen for multiple words """ assert (type(text) is str) assert (text.count(" ") is 0) if __name__ == '__main__': pass
class DummyContext: context = {} dummy_context = DummyContext()
# # @lc app=leetcode id=783 lang=python3 # # [783] Minimum Distance Between BST Nodes # # https://leetcode.com/problems/minimum-distance-between-bst-nodes/description/ # # algorithms # Easy (51.05%) # Likes: 524 # Dislikes: 157 # Total Accepted: 49.9K # Total Submissions: 97K # Testcase Example: '[4,2,6,1,3,null,null]' # # Given a Binary Search Tree (BST) with the root node root, return the minimum # difference between the values of any two different nodes in the tree. # # Example : # # # Input: root = [4,2,6,1,3,null,null] # Output: 1 # Explanation: # Note that root is a TreeNode object, not an array. # # The given tree [4,2,6,1,3,null,null] is represented by the following # diagram: # # ⁠ 4 # ⁠ / \ # ⁠ 2 6 # ⁠ / \ # ⁠ 1 3 # # while the minimum difference in this tree is 1, it occurs between node 1 and # node 2, also between node 3 and node 2. # # # Note: # # # The size of the BST will be between 2 and 100. # The BST is always valid, each node's value is an integer, and each node's # value is different. # # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def minDiffInBST(self, root: TreeNode) -> int: vals = [] def util(root): if not root: return util(root.left) vals.append(root.val) util(root.right) util(root) return min([vals[i + 1] - vals[i] for i in range(len(vals) - 1)]) # @lc code=end
class NameScope(object,INameScopeDictionary,INameScope,IDictionary[str,object],ICollection[KeyValuePair[str,object]],IEnumerable[KeyValuePair[str,object]],IEnumerable): """ Implements base WPF support for the System.Windows.Markup.INameScope methods that store or retrieve name-object mappings into a particular XAML namescope. Adds attached property support to make it simpler to get or set XAML namescope names dynamically at the element level.. NameScope() """ def Add(self,*__args): """ Add(self: NameScope,key: str,value: object) Adds an item to the collection. key: The string key,which is the name of the XAML namescope mapping to add. value: The object value,which is the object reference of the XAML namescope mapping to add. Add(self: NameScope,item: KeyValuePair[str,object]) """ pass def Clear(self): """ Clear(self: NameScope) Removes all items from the collection. """ pass def Contains(self,item): """ Contains(self: NameScope,item: KeyValuePair[str,object]) -> bool """ pass def ContainsKey(self,key): """ ContainsKey(self: NameScope,key: str) -> bool Returns whether a provided name already exists in this System.Windows.NameScope. key: The string key to find. Returns: true if the specified key identifies a name for an existing mapping in this System.Windows.NameScope. false if the specified key does not exist in the current System.Windows.NameScope. """ pass def CopyTo(self,array,arrayIndex): """ CopyTo(self: NameScope,array: Array[KeyValuePair[str,object]],arrayIndex: int) """ pass def FindName(self,name): """ FindName(self: NameScope,name: str) -> object Returns the corresponding object in the XAML namescope maintained by this System.Windows.NameScope,based on a provided name string. name: Name portion of an existing mapping to retrieve the object portion for. Returns: The requested object that is mapped with name. Can return null if name was provided as null or empty string,or if no matching object was found. """ pass @staticmethod def GetNameScope(dependencyObject): """ GetNameScope(dependencyObject: DependencyObject) -> INameScope Provides the attached property get accessor for the System.Windows.NameScope.NameScope attached property. dependencyObject: The object to get the XAML namescope from. Returns: A XAML namescope,as an System.Windows.Markup.INameScope instance. """ pass def RegisterName(self,name,scopedElement): """ RegisterName(self: NameScope,name: str,scopedElement: object) Registers a new name-object pair into the current XAML namescope. name: The name to use for mapping the given object. scopedElement: The object to be mapped to the provided name. """ pass def Remove(self,*__args): """ Remove(self: NameScope,key: str) -> bool Removes a mapping for a specified name from the collection. key: The string key,which is the name of the XAML namescope mapping to remove. Returns: true if item was successfully removed from the collection,otherwise false. Also returns false if the item was not found in the collection. Remove(self: NameScope,item: KeyValuePair[str,object]) -> bool """ pass @staticmethod def SetNameScope(dependencyObject,value): """ SetNameScope(dependencyObject: DependencyObject,value: INameScope) Provides the attached property set accessor for the System.Windows.NameScope.NameScope attached property. dependencyObject: Object to change XAML namescope for. value: The new XAML namescope,using an interface cast. """ pass def TryGetValue(self,key,value): """ TryGetValue(self: NameScope,key: str) -> (bool,object) Gets the value associated with the specified key. key: The key of the value to get. Returns: true if the System.Windows.NameScope contains a mapping for the name provided as key. Otherwise,false. """ pass def UnregisterName(self,name): """ UnregisterName(self: NameScope,name: str) Removes a name-object mapping from the XAML namescope. name: The name of the mapping to remove. """ pass def __add__(self,*args): """ x.__add__(y) <==> x+yx.__add__(y) <==> x+y """ pass def __contains__(self,*args): """ __contains__(self: IDictionary[str,object],key: str) -> bool """ pass def __getitem__(self,*args): """ x.__getitem__(y) <==> x[y] """ pass def __init__(self,*args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass def __iter__(self,*args): """ __iter__(self: IEnumerable) -> object """ pass def __len__(self,*args): """ x.__len__() <==> len(x) """ pass def __repr__(self,*args): """ __repr__(self: object) -> str """ pass def __setitem__(self,*args): """ x.__setitem__(i,y) <==> x[i]= """ pass Count=property(lambda self: object(),lambda self,v: None,lambda self: None) """Returns the number of items in the collection of mapped names in this System.Windows.NameScope. Get: Count(self: NameScope) -> int """ IsReadOnly=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets a value indicating whether the collection is read-only. Get: IsReadOnly(self: NameScope) -> bool """ Keys=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets a collection of the keys in the System.Windows.NameScope dictionary. Get: Keys(self: NameScope) -> ICollection[str] """ Values=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets a collection of the values in the System.Windows.NameScope dictionary. Get: Values(self: NameScope) -> ICollection[object] """ NameScopeProperty=None
# Copyright 2020 BBC Research & Development # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== experiment_name = "exp1_bn" # experiment name experiment_path = "experiment/path" # experiment base path output_path = experiment_path + experiment_name # Model parameters core_model = "bn_model" # [bn_model, in_model, bn_sn_model, in_sn_model, ibn_model] d_scales = 1 # number of multi discriminator scales # Data parameters data_path = "data/path" # data path for train and test input_shape = (256, 256) # input shape input_color_mode = 'rgb' # input colour space (same as data path content) output_color_mode = 'lab' # output colour space interpolation = 'nearest' # interpolation for reshaping operations chunk_size = 10000 # reading chunk size samples_rate = 1. # percentage of output samples within data path shuffle = True # shuffle during training seed = 42 # seed for shuffle operation # Training parameters epochs = 200 # training epochs batch_size = 16 # batch size for train and validation. batch_size = 1 for test l1_lambda = 100 # l1 weight into global loss function lr_d = 0.0002 # learning rate for discriminator lr_g = 0.0002 # learning rate for generator beta = 0.5 # learning beta display_step = 10 # step size for updating tensorboard log file plots_per_epoch = 20 # prediction logs per epoch weights_per_epoch = 20 # weight checkpoints per epoch multi_gpu = False # enable multi gpu model gpus = 2 # number of available gpus workers = 10 # number of worker threads max_queue_size = 10 # queue size for worker threads use_multiprocessing = False # use multiprocessing
# -*- coding: utf-8 -*- __author__ = 'Wael Ben Zid El Guebsi' __email__ = 'benzid.wael@hotmail.fr' __version__ = '0.0.0'
# coding: utf-8 n = int(input()) li = [int(i) for i in input().split()] print(sum(li)/n)
class Question: def __init__(self, text, answer): self.text = text self.answer = answer new_q = Question("lkajsdkf", "False")
#!/usr/bin/env python3 """Mtools version.""" __version__ = '1.6.4-dev'
def buildMaskSplit(noiseGShape, noiseGTexture, categoryVectorDim, attribKeysOrder, attribShift, keySplits=None, mixedNoise=False): r""" Build a 8bits mask that split a full input latent vector into two intermediate latent vectors: one for the shape network and one for the texture network. """ # latent vector split # Reminder, a latent vector is organized as follow # [z1,......, z_N, c_1, ....., c_C] # N : size of the noise part # C : size of the conditional part (ACGAN) # Here we will split the vector in # [y1, ..., y_N1, z1,......, z_N2, c_1, ....., c_C] N1 = noiseGShape N2 = noiseGTexture if not mixedNoise: maskShape = [1 for x in range(N1)] + [0 for x in range(N2)] maskTexture = [0 for x in range(N1)] + [1 for x in range(N2)] else: maskShape = [1 for x in range(N1 + N2)] maskTexture = [1 for x in range(N1 + N2)] # Now the conditional part # Some conditions apply to the shape, other to the texture, and sometimes # to both if attribKeysOrder is not None: C = categoryVectorDim if keySplits is not None: maskShape = maskShape + [0 for x in range(C)] maskTexture = maskTexture + [0 for x in range(C)] for key in keySplits["GShape"]: index = attribKeysOrder[key]["order"] shift = N1 + N2 + attribShift[index] for i in range(shift, shift + len(attribKeysOrder[key]["values"])): maskShape[i] = 1 for key in keySplits["GTexture"]: index = attribKeysOrder[key]["order"] shift = N1 + N2 + attribShift[index] for i in range(shift, shift + len(attribKeysOrder[key]["values"])): maskTexture[i] = 1 else: maskShape = maskShape + [1 for x in range(C)] maskTexture = maskTexture + [1 for x in range(C)] return maskShape, maskTexture
def find_three_values_that_sum(lines, sum=2020): for idx1, line1 in enumerate(lines): for idx2, line2 in enumerate(lines[idx1:]): for idx3, line3 in enumerate(lines[idx1+idx2:]): num1 = int(line1) num2 = int(line2) num3 = int(line3) if (num1 + num2 + num3 == sum): print(f'Found the matching values (idx):value: ({idx1}): {num1}, ({idx2}): {num2}, ({idx3}): {num3}') return num1, num2, num3 def find_two_values_that_sum(lines, sum=2020): for idx1, line1 in enumerate(lines): for idx2, line2 in enumerate(lines[idx1:]): num1 = int(line1) num2 = int(line2) if (num1 + num2 == sum): print(f'Found the matching values (idx):value: ({idx1}): {num1}, ({idx2}): {num2}') return num1, num2 def main(): filename = 'input-p1.txt' with open(filename, 'r') as f: lines = f.readlines() print(f'Read in file: {filename} Number of lines: {len(lines)}') num1, num2 = find_two_values_that_sum(lines, sum=2020) print(f'Multiply two values together: {num1 * num2}') num1, num2, num3 = find_three_values_that_sum(lines, sum=2020) print(f'Multiply three values together: {num1 * num2 * num3}') if __name__ == '__main__': main()
Invitados=[] Invitados.append('Ciria Garcia') Invitados.append('Esperanza Zul') Invitados.append('Bryce Harper') Msj="Me gustaria mucho que usted " + Invitados[0].title() + " pudiera acompañarme esta noche a cenar." Msj1="Me encantaria poder compartir esta cena con mi abuela " + Invitados[1].title() + "." Msj2="Seria grandioso conocer y poder cenar con el gran " + Invitados[2].title() + "." del Invitados[2] Invitados.insert(0, 'Natalia Lafourcade') print (Invitados) "Ejericio 3.9 " len(Invitados) print("El numero de invitados registrados:") print(len(Invitados))
class Constants(object): """ Constant declarations. """ API_URL = 'https://i.instagram.com/api/v1/' VERSION = '9.2.0' IG_SIG_KEY = '012a54f51c49aa8c5c322416ab1410909add32c966bbaa0fe3dc58ac43fd7ede' EXPERIMENTS = 'ig_android_ad_holdout_16m5_universe,ig_android_progressive_jpeg,ig_creation_growth_holdout,ig_android_oppo_app_badging,ig_android_ad_remove_username_from_caption_universe,ig_android_enable_share_to_whatsapp,ig_android_direct_drawing_in_quick_cam_universe,ig_android_ad_always_send_ad_attribution_id_universe,ig_android_universe_video_production,ig_android_direct_plus_button,ig_android_ads_heatmap_overlay_universe,ig_android_http_stack_experiment_2016,ig_android_infinite_scrolling,ig_fbns_blocked,ig_android_post_auto_retry_v7_21,ig_fbns_push,ig_android_video_playback_bandwidth_threshold,ig_android_direct_link_preview,ig_android_direct_typing_indicator,ig_android_preview_capture,ig_android_feed_pill,ig_android_profile_link_iab,ig_android_story_caption,ig_android_network_cancellation,ig_android_histogram_reporter,ig_android_anrwatchdog,ig_android_search_client_matching,ig_android_follow_request_text_buttons,ig_android_feed_zoom,ig_android_drafts_universe,ig_android_disable_comment,ig_android_user_detail_endpoint,ig_android_os_version_blocking,ig_android_blocked_list,ig_android_event_creation,ig_android_high_res_upload_2,ig_android_2fac,ig_android_mark_reel_seen_on_Swipe_forward,ig_android_comment_redesign,ig_android_ad_sponsored_label_universe,ig_android_mentions_dismiss_rule,ig_android_disable_chroma_subsampling,ig_android_share_spinner,ig_android_video_reuse_surface,ig_explore_v3_android_universe,ig_android_media_favorites,ig_android_nux_holdout,ig_android_insta_video_universe,ig_android_search_null_state,ig_android_universe_reel_video_production,liger_instagram_android_univ,ig_android_direct_emoji_picker,ig_feed_holdout_universe,ig_android_direct_send_auto_retry_universe,ig_android_samsung_app_badging,ig_android_disk_usage,ig_android_business_promotion,ig_android_direct_swipe_to_inbox,ig_android_feed_reshare_button_nux,ig_android_react_native_boost_post,ig_android_boomerang_feed_attribution,ig_fbns_shared,ig_fbns_dump_ids,ig_android_react_native_universe,ig_show_promote_button_in_feed,ig_android_ad_metadata_behavior_universe,ig_android_video_loopcount_int,ig_android_inline_gallery_backoff_hours_universe,ig_android_rendering_controls,ig_android_profile_photo_as_media,ig_android_async_stack_image_cache,ig_video_max_duration_qe_preuniverse,ig_video_copyright_whitelist,ig_android_render_stories_with_content_override,ig_android_ad_intent_to_highlight_universe,ig_android_swipe_navigation_x_angle_universe,ig_android_disable_comment_public_test,ig_android_profile,ig_android_direct_blue_tab,ig_android_enable_share_to_messenger,ig_android_fetch_reel_tray_on_resume_universe,ig_android_promote_again,ig_feed_event_landing_page_channel,ig_ranking_following,ig_android_pending_request_search_bar,ig_android_feed_ufi_redesign,ig_android_pending_edits_dialog_universe,ig_android_business_conversion_flow_universe,ig_android_show_your_story_when_empty_universe,ig_android_ad_drop_cookie_early,ig_android_app_start_config,ig_android_fix_ise_two_phase,ig_android_ppage_toggle_universe,ig_android_pbia_normal_weight_universe,ig_android_profanity_filter,ig_ios_su_activity_feed,ig_android_search,ig_android_boomerang_entry,ig_android_mute_story,ig_android_inline_gallery_universe,ig_android_ad_remove_one_tap_indicator_universe,ig_android_view_count_decouple_likes_universe,ig_android_contact_button_redesign_v2,ig_android_periodic_analytics_upload_v2,ig_android_send_direct_typing_indicator,ig_android_ad_holdout_16h2m1_universe,ig_android_react_native_comment_moderation_settings,ig_video_use_sve_universe,ig_android_inline_gallery_no_backoff_on_launch_universe,ig_android_immersive_viewer,ig_android_discover_people_icon,ig_android_profile_follow_back_button,is_android_feed_seen_state,ig_android_dense_feed_unit_cards,ig_android_drafts_video_universe,ig_android_exoplayer,ig_android_add_to_last_post,ig_android_ad_remove_cta_chevron_universe,ig_android_ad_comment_cta_universe,ig_android_ad_chevron_universe,ig_android_ad_comment_cta_universe,ig_android_search_event_icon,ig_android_channels_home,ig_android_feed,ig_android_dv2_realtime_private_share,ig_android_non_square_first,ig_android_video_interleaved_v2,ig_android_video_cache_policy,ig_android_react_native_universe_kill_switch,ig_android_video_captions_universe,ig_android_follow_search_bar,ig_android_last_edits,ig_android_two_step_capture_flow,ig_android_video_download_logging,ig_android_share_link_to_whatsapp,ig_android_facebook_twitter_profile_photos,ig_android_swipeable_filters_blacklist,ig_android_ad_pbia_profile_tap_universe,ig_android_use_software_layer_for_kc_drawing_universe,ig_android_react_native_ota,ig_android_direct_mutually_exclusive_experiment_universe,ig_android_following_follower_social_context' LOGIN_EXPERIMENTS = 'ig_android_reg_login_btn_active_state,ig_android_ci_opt_in_at_reg,ig_android_one_click_in_old_flow,ig_android_merge_fb_and_ci_friends_page,ig_android_non_fb_sso,ig_android_mandatory_full_name,ig_android_reg_enable_login_password_btn,ig_android_reg_phone_email_active_state,ig_android_analytics_data_loss,ig_fbns_blocked,ig_android_contact_point_triage,ig_android_reg_next_btn_active_state,ig_android_prefill_phone_number,ig_android_show_fb_social_context_in_nux,ig_android_one_tap_login_upsell,ig_fbns_push,ig_android_phoneid_sync_interval' SIG_KEY_VERSION = '4' ANDROID_VERSION = 18 ANDROID_RELEASE = '4.3'
"Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k" class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: if not nums or len(nums) == 1: return False pairs = dict() for idx, num in enumerate(nums): if num in pairs: if abs(pairs[num] - idx) <= k: return True pairs[num] = idx return False
class Solution: def generate(self, numRows: int): result = [] if not numRows: return result for i in range(1, numRows + 1): temp = [1] * i lo = 1 hi = i - 2 while lo <= hi: temp[lo] = temp[hi] = result[i - 2][lo] + result[i - 2][lo - 1] lo += 1 hi -= 1 result.append(temp) return result
# @Title: 和为K的子数组 (Subarray Sum Equals K) # @Author: KivenC # @Date: 2018-07-19 18:00:52 # @Runtime: 84 ms # @Memory: N/A class Solution(object): def subarraySum(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ # key为前n项的和,value为该和出现的次数 sum_dic = {0: 1} temp, count = 0, 0 for num in nums: temp += num # 寻找key为temp-k的值 count += sum_dic.get(temp-k, 0) # 每出现一次和为temp,则该value加一 sum_dic[temp] = sum_dic.get(temp, 0) + 1 return count
""" This problem was asked by Microsoft. Given an array of numbers, find the length of the longest increasing subsequence in the array. The subsequence does not necessarily have to be contiguous. For example, given the array [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15], the longest increasing subsequence has length 6: it is 0, 2, 6, 9, 11, 15. """ memo_dict = None def helper(arr, seq=[], recur_depth = 0): if len(arr) == 0: memo_dict[seq[recur_depth]] = seq[recur_depth:] return seq longest_seq = [] for i in range(len(arr)): if arr[i] > seq[-1]: res = helper(arr[i+1:], seq+[arr[i]], recur_depth+1) if len(res) >= len(longest_seq): longest_seq = res memo_dict[seq[recur_depth]] = longest_seq[recur_depth:] return longest_seq def long_subsequence(arr): longest = [] global memo_dict memo_dict = {} for i in range(len(arr)): if arr[i] in memo_dict: res = memo_dict[arr[i]] else: res = helper(arr[i+1:], [arr[i]]) # print("->>>> res: {}".format(res)) if len(res) > len(longest): longest = res return len(longest) if __name__ == '__main__': print(long_subsequence([0, 4, 6, 2, 3, 5, 9])) # 5 print(long_subsequence([0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15])) # 6 print(long_subsequence([11])) # 1 print(long_subsequence([])) # 0
class Empty(Exception): pass class LinkedQueue: """FIFO queue implkementation using a singly linked list for storage""" class _Node: """Lightweight, nonpublic claass for storing a singly linked node.""" __slots__ = ( "_element", "_next", ) # streamline memory usage as we expect to have many instances of a node class def __init__(self, element, next): # Initialize node fields self._element = element # reference to user's element self._next = next # reference to next node def __init__(self) -> None: self._head = None self._tail = None self._size = 0 def __len__(self): """Return the number of elements in the queue""" return self._size def is_empty(self): """Return True if the queue is empty""" return self._size == 0 def first(self): """Return but do not remove the element at the front of the queue""" if self.is_empty(): raise Empty("Queue is Empty") return self._head._element def dequeue(self): """Remove and reutrn the first element of the queue Raise Empty exception if the queue is empty""" if self.is_empty(): raise Empty("Queue is Empty") answer = self._head._element self._head = self._head._next self._size -= 1 if self.is_empty(): # special case as queue is empty self._tail = None # removed head had been the tail return answer def enqueue(self, e): """Add an element to the back of the queue""" newest = self._Node(e, None) if self.is_empty(): self._head = newest else: self._tail._next = newest self._tail = newest self._size += 1
# 1921. Eliminate Maximum Number of Monsters # You are playing a video game where you are defending your city from a group of n monsters. # You are given a 0-indexed integer array dist of size n, where dist[i] is the initial # distance in meters of the ith monster from the city. # The monsters walk toward the city at a constant speed. The speed of each monster is # given to you in an integer array speed of size n, where speed[i] is the speed of the # ith monster in meters per minute. # The monsters start moving at minute 0. You have a weapon that you can choose to use # at the start of every minute, including minute 0. You cannot use the weapon in the # middle of a minute. The weapon can eliminate any monster that is still alive. # You lose when any monster reaches your city. If a monster reaches the city exactly # at the start of a minute, it counts as a loss, and the game ends before you can use # your weapon in that minute. # Return the maximum number of monsters that you can eliminate before you lose, or n # if you can eliminate all the monsters before they reach the city. # Example 1: # Input: dist = [1,3,4], speed = [1,1,1] # Output: 3 # Explanation: # At the start of minute 0, the distances of the monsters are [1,3,4], you eliminate the first monster. # At the start of minute 1, the distances of the monsters are [X,2,3], you don't do anything. # At the start of minute 2, the distances of the monsters are [X,1,2], you eliminate the second monster. # At the start of minute 3, the distances of the monsters are [X,X,1], you eliminate the third monster. # All 3 monsters can be eliminated. # Example 2: # Input: dist = [1,1,2,3], speed = [1,1,1,1] # Output: 1 # Explanation: # At the start of minute 0, the distances of the monsters are [1,1,2,3], you eliminate the first monster. # At the start of minute 1, the distances of the monsters are [X,0,1,2], so you lose. # You can only eliminate 1 monster. # Example 3: # Input: dist = [3,2,4], speed = [5,3,2] # Output: 1 # Explanation: # At the start of minute 0, the distances of the monsters are [3,2,4], you eliminate the first monster. # At the start of minute 1, the distances of the monsters are [X,0,2], so you lose. # You can only eliminate 1 monster. # Constraints: # n == dist.length == speed.length # 1 <= n <= 105 # 1 <= dist[i], speed[i] <= 105 # Solution # Sort the monsters by arrival times # If the moster arrives earlier than we can shoot, then we lost class Solution: def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int: if not dist or not speed or len(dist) == 0 or len(speed) == 0 or len(dist) != len(speed): return 0 l = len(speed) orders = [] for i in range(l): orders.append([dist[i], speed[i]]) orders.sort(key=lambda x: math.ceil(x[0] / x[1])) for i in range(l): if orders[i][0] <= i * orders[i][1]: # arrive earlier than we can shoot return i return l
__author__ = 'Chetan' class Wizard(): def __init__(self, src, rootdir): self.choices = [] self.rootdir = rootdir self.src = src def preferences(self, command): self.choices.append(command) def execute(self): for choice in self.choices: if list(choice.values())[0]: print("Copying binaries --", self.src, " to ", self.rootdir) else: print("No Operation") def rollback(self): print("Deleting the unwanted..", self.rootdir) if __name__ == '__main__': ## Client code wizard = Wizard('python3.5.gzip', '/usr/bin/') ## Steps for installation. ## Users chooses to install Python only wizard.preferences({'python':True}) wizard.preferences({'java':False}) wizard.execute()
####################################################### # # ManageRacacatPinController.py # Python implementation of the Class ManageRacacatPinController # Generated by Enterprise Architect # Created on: 15-Apr-2020 4:57:23 PM # Original author: Giu Platania # ####################################################### class ManageRacacatPinController: # default constructor def __init__(self): pass
N = int(input()) ans = 0 if N < 10 ** 3: print(0) elif 10 ** 3 <= N < 10 ** 6: print(N - 10 ** 3 + 1) elif 10 ** 6 <= N < 10 ** 9: print(10 ** 6 - 10 ** 3 + (N - 10 ** 6 + 1)*2) elif 10 ** 9 <= N < 10 ** 12: print(10 ** 6 - 10 ** 3 + (10 ** 9 - 10 ** 6)*2 + (N - 10 ** 9 + 1)*3) elif 10 ** 12 <= N < 10 ** 15: print(10 ** 6 - 10 ** 3 + (10 ** 9 - 10 ** 6)*2 + (10 ** 12 - 10 ** 9)*3 + (N - 10 ** 12 + 1)*4) else: print(10 ** 6 - 10 ** 3 + (10 ** 9 - 10 ** 6)*2 + (10 ** 12 - 10 ** 9)*3 + (10 ** 15 - 10 ** 12)*4 + 5)
valor = 12 def teste_git(testes): result = testes ** 33 return result print(teste_git(valor))
def show_first(word): print(word[0]) show_first("abc")
numero = int(input("Digite um número: ")) if ((numero % 5) == 0): print("Buzz") else: print(numero)
def new_multiplayer(bot, message): """ /new_multiplayer command handler """ chat_id = message.chat.id bot.send_message(chat_id=chat_id, text="Not implemented yet")
def count_positives_sum_negatives(arr): if not arr: return [] positive_array_count = 0 negative_array_count = 0 neither_array = 0 for i in arr: if i > 0: positive_array_count = positive_array_count + 1 elif i == 0: neither_array = neither_array + i else: negative_array_count = negative_array_count + i return [positive_array_count, negative_array_count]
input_shape = 56, 56, 3 num_class = 80 total_epoches = 50 batch_size = 64 train_num = 11650 val_num = 1254 iterations_per_epoch = train_num // batch_size + 1 test_iterations = val_num // batch_size + 1 weight_decay = 1e-3 label_smoothing = 0.1 ''' numeric characteristics ''' mean = [154.64720717, 163.98750114, 175.11027269] std = [88.22176357, 82.46385599, 78.50590683] # eigval = [18793.85624672, 1592.25590705, 360.43236465] eigval = [137.09068621, 39.90308142, 18.98505635] eigvec = [[-0.61372719, -0.62390345, 0.48382169], [-0.59095847, -0.0433538, -0.80553618], [-0.52355231, 0.78029798, 0.34209362]]
def sort3(a, b, c): i = [] i.append(a), i.append(b), i.append(c) i = sorted(i) return i a, b, c = input(), input(), input() print(*sort3(a, b, c))
''' occurrences_dict loop values: occurrences_dict[value] += 1 ''' # numbers_string = '-2.5 4 3 -2.5 -5.54 4 3 3 -2.5 3' # numbers_string = '2 4 4 5 5 2 3 3 4 4 3 3 4 3 5 3 2 5 4 3' numbers_string = input() occurrence_counts = {} # No such thing as tuple comprehension, this is generator numbers = [float(x) for x in numbers_string.split(' ')] for number in numbers: # Not the best solution # if number in occurrence_counts: # occurrence_counts[number] += 1 # else: # occurrence_counts[number] = 1 if number not in occurrence_counts: occurrence_counts[number] = 0 occurrence_counts[number] += 1 for number, count in occurrence_counts.items(): print(f'{number:.1f} - {count} times')
count = 0 total = 0 while True: Enter = input('Enter a number:\n') try: if Enter == "Done": break else: inp = int(Enter) total = total + inp count = count + 1 average = total / count except: print('Invalid input') print('Total:', total, 'Count:', count, 'Average:', average)
# # PySNMP MIB module BEGEMOT-IP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BEGEMOT-IP-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:37:03 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) # ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ValueSizeConstraint, ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsUnion") begemot, = mibBuilder.importSymbols("BEGEMOT-MIB", "begemot") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") iso, Gauge32, ModuleIdentity, Counter64, Integer32, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, MibIdentifier, ObjectIdentity, Unsigned32, Counter32, NotificationType, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "Gauge32", "ModuleIdentity", "Counter64", "Integer32", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "MibIdentifier", "ObjectIdentity", "Unsigned32", "Counter32", "NotificationType", "TimeTicks") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") begemotIp = ModuleIdentity((1, 3, 6, 1, 4, 1, 12325, 1, 3)) if mibBuilder.loadTexts: begemotIp.setLastUpdated('200602130000Z') if mibBuilder.loadTexts: begemotIp.setOrganization('German Aerospace Center') if mibBuilder.loadTexts: begemotIp.setContactInfo(' Hartmut Brandt Postal: German Aerospace Center Oberpfaffenhofen 82234 Wessling Germany Fax: +49 8153 28 2843 E-mail: harti@freebsd.org') if mibBuilder.loadTexts: begemotIp.setDescription('The MIB for IP stuff that is not in the official IP MIBs.') begemotIpObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 12325, 1, 3, 1)) mibBuilder.exportSymbols("BEGEMOT-IP-MIB", begemotIp=begemotIp, PYSNMP_MODULE_ID=begemotIp, begemotIpObjects=begemotIpObjects)
SECRET_KEY = 'fake-key-here' # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'data_ingest', ] MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ] ROOT_URLCONF = 'data_ingest.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'test_data_ingest', 'USER': 'postgres', 'PASSWORD': 'test_data_password', 'HOST': 'localhost', 'PORT': '5432', } } # Rest Framework REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True
# RUN: test-parser.sh %s # RUN: test-output.sh %s x = 1 # PARSER-LABEL:x = 1i y = 2 # PARSER-NEXT:y = 2i print("Start") # PARSER-NEXT:print("Start") # OUTPUT-LABEL: Start if x == 1: # PARSER-NEXT:if (x == 1i): if y == 3: # PARSER-NEXT: if (y == 3i): print("A") # PARSER-NEXT: print("A") else: # PARSER-NEXT:else: print("C") # PARSER-NEXT: print("C") print("D") # PARSER-NEXT:print("D") # OUTPUT-NEXT: D if x == 1: # PARSER-NEXT:if (x == 1i): if y == 3: # PARSER-NEXT: if (y == 3i): print("A") # PARSER-NEXT: print("A") else: # PARSER-NEXT: else: print("B") # PARSER-NEXT: print("B") else: # PARSER-NEXT:else: print("C") # PARSER-NEXT: print("C") print("D") # PARSER-NEXT:print("D") # OUTPUT-NEXT: B # OUTPUT-NEXT: D if x == 1: # PARSER-NEXT:if (x == 1i): if y == 3: # PARSER-NEXT: if (y == 3i): print("A") # PARSER-NEXT: print("A") else: # PARSER-NEXT: else: print("B") # PARSER-NEXT: print("B") print("D") # PARSER-NEXT:print("D") # OUTPUT-NEXT: B # OUTPUT-NEXT: D if x == 1: # PARSER-NEXT:if (x == 1i): if y == 3: # PARSER-NEXT: if (y == 3i): print("A") # PARSER-NEXT: print("A") else: # PARSER-NEXT: else: print("X") # PARSER-NEXT: print("X") if y == 2: # PARSER-NEXT: if (y == 2i): print("B") # PARSER-NEXT: print("B") else: # PARSER-NEXT: else: print("E") # PARSER-NEXT: print("E") else: # PARSER-NEXT:else: print("C") # PARSER-NEXT: print("C") print("D") # PARSER-NEXT:print("D") # OUTPUT-NEXT: X # OUTPUT-NEXT: B # OUTPUT-NEXT: D
class CameraNotConnected(Exception): pass class WiredControlAlreadyEstablished(Exception): pass
""" Project Euler: Problem #002 """ def solve(lim = 4 * 1000 * 1000): """ Naive solution with a function. :param lim: Max number to sum up to. :returns: The sum of the even Fibo-numbers. """ a, b = 0, 1 sum = 0 while b < lim: if not b % 2: sum += b a, b = b, a + b # <-- tuple assignment to avoid tmp var return sum def solve_alt(lim): """ Alternative solution using a generator. **Note**: Must sum over the generator at the end. :param lim: Max number to sum up to. :returns: The sum of the odd Fibo-numbers. """ def numGen(lim): a, b = 0, 1 while b < lim: if not b % 2: yield b # <-- generator a, b = b, a + b # <-- tuple assignment to avoid tmp var return sum(numGen(lim)) if __name__ == '__main__': print("Check: {}".format(eu002(100)))
# https://codeforces.com/problemset/problem/116/A n = int(input()) stops = [list(map(int, input().split())) for _ in range(n)] p, peak_p = 0, 0 for stop in stops: p -= stop[0] p += stop[1] peak_p = max(p, peak_p) print(peak_p)
def int_to_char(word): arr = list(word) num_str = "" while True: if not arr[0].isdigit(): break num_str += arr[0] arr.pop(0) num = int(num_str) arr.insert(0, chr(num)) return "".join(arr) def switch_letters(word): list_chars = list(word) list_chars[1], list_chars[-1] = list_chars[-1], list_chars[1] return "".join(list_chars) def decrypt_word(word): word = int_to_char(word) word = switch_letters(word) return word words = input().split() words = [decrypt_word(word) for word in words] print(" ".join(words))
PROJECT_ID = 'dmp-y-tests' DATASET_NAME = 'test_gpl' BUCKET_NAME = 'bucket_gpl' LOCAL_DIR_PATH = '/tmp/gpl_directory'
def print_inicia_jogo(): print("Bem-vindo ao jogo do NIM! Escolha:\n") print("1 - para jogar uma partida isolada") print("2 - para jogar um campeonato") def vencedor(ganha_comp, ganha_usuario): if ganha_comp: return print("Fim do jogo! O computador ganhou!") elif ganha_usuario: return print("Fim do jogo! Você ganhou!") def print_rest_peca(n): if n > 1: return print("Agora restam apenas", n ,"peças no tabuleiro.") elif n == 1: return print("Agora restam apenas uma peça no tabuleiro.") def computador_escolhe_jogada(n, m): i = 1 while i <= m: if (n - i) % (m + 1) == 0: return i i += 1 return i - 1 def usuario_escolhe_jogada(n, m): jogada = int(input("Quantas peças você vai tirar? ")) if jogada > 0 and jogada <= m and jogada <= n: return jogada else: while not(jogada > 0 and jogada <= m and jogada <= n): print("Oops! Jogada inválida! Tente de novo.") jogada = int(input("Quantas peças você vai tirar? ")) if jogada > 0 and jogada <= m and jogada <= n: return jogada def partida(): n = int(input("Quantas peças? ")) m = int(input("Limite de peça por jogada? ")) comp_ganha = False usuario_ganhou = False if (n) % (m + 1) == 0: print("Voce começa!") while n > 0: ## Usuário começa valor_usuario = usuario_escolhe_jogada(n, m) n = n - valor_usuario if valor_usuario == 1: print("Você retirou uma peça.") print_rest_peca(n) else: print("Você retirou ", valor_usuario,"peças") print_rest_peca(n) if n == 0: usuario_ganhou = True break valor_computador = computador_escolhe_jogada(n, m) n = n - valor_computador if valor_computador == 1: print("Computador tirou uma peça.") print_rest_peca(n) else: print("Computador tirou ",valor_computador,"peças.") print_rest_peca(n) if n == 0: comp_ganha = True vencedor(comp_ganha, usuario_ganhou) else: print("Computador começa!") while n > 0: valor_computador = computador_escolhe_jogada(n, m) n = n - valor_computador if valor_computador == 1: print("O computador tirou uma peça.") print_rest_peca(n) else: print("\nO computador tirou ",valor_computador,"peças.") print_rest_peca(n) if n == 0: comp_ganha = True break valor_usuario = usuario_escolhe_jogada(n, m) n = n - valor_usuario if valor_usuario == 1: print("Você retirou uma peça.") print_rest_peca(n) else: print("Você retirou ", valor_usuario,"peças") print_inicia_jogo(n) if n == 0: usuario_ganhou = True vencedor(comp_ganha, usuario_ganhou) def campeonato(): i = 1 while i <= 3 : print("**** Rodada ", i , "****") partida() i += 1 print("**** Final do campeonato! ****") print("\nPlacar: Você 0 X 3 Computador") def main(): print_inicia_jogo() jogar = 3 while (jogar != 1 or jogar != 2): jogar = int(input()) if jogar == 1: partida() estive_aqui = True elif jogar == 2: campeonato() estive_aqui = True main()
def commonDiv(num, den, divs = None) : if not divs : divs = divisors(den) for i in divs[1:] : if not num % i : return True return False def validNums(den, minNum, maxNum) : divs = divisors(den) return [i for i in range(minNum,maxNum+1) if not commonDiv(i, den, divs)] def countBetween(lowNum, lowDen, highNum, highDen, maxDen) : total = 0 for i in range(2,maxDen+1) : minNum = i*lowNum/lowDen+1 maxNum = (i*highNum-1)/highDen nums = validNums(i, minNum, maxNum) total += len(nums) #print "%d -> %d to %d (%s) %d" % (i, minNum, maxNum, ','.join([str(i) for i in nums]), total) return total countBetween(1, 3, 1, 2, 12000)
# Exception Handling function def exception_handling(number1, number2, operator): # Only digit exception try: int(number1) except: return "Error: Numbers must only contain digits." try: int(number2) except: return "Error: Numbers must only contain digits." # More than 4 digit no. exception try: if len(number1) > 4 or len(number2) > 4: raise BaseException except: return "Error: Numbers cannot be more than four digits." # Operator must be + | - exception. try: if operator != '+' and operator != '-': raise BaseException except: return "Error: Operator must be '+' or '-'." return "" def arithmetic_arranger(problems, displayMode=False): start = True side_space = " " line1 = line2 = line3 = line4 = "" # Too many Problem exception try: if len(problems) > 5: raise BaseException except: return "Error: Too many problems." for prob in problems: # Splitting the Problem into separate strings separated_problem = prob.split() # storing number 1 number1 = separated_problem[0] # Storing the operator sign operator = separated_problem[1] # storing number 2 number2 = separated_problem[2] exp = exception_handling(number1, number2, operator) if exp != "": return exp no1 = int(number1) no2 = int(number2) # space contains the max no. os spaces required. space = max(len(number1), len(number2)) # For first arithmetic arragement if start == True: line1 += number1.rjust(space + 2) line2 += operator + ' ' + number2.rjust(space) line3 += '-' * (space + 2) if displayMode == True: if operator == '+': line4 += str(no1 + no2).rjust(space + 2) else: line4 += str(no1 - no2).rjust(space + 2) start = False # Other than first arithmetic arragement else: line1 += number1.rjust(space + 6) line2 += operator.rjust(5) + ' ' + number2.rjust(space) line3 += side_space + '-' * (space + 2) if displayMode == True: if operator == '+': line4 += side_space + str(no1 + no2).rjust(space + 2) else: line4 += side_space + str(no1 - no2).rjust(space + 2) # displayMode is Ture then append line4 if displayMode == True: return line1 + '\n' + line2 + '\n' + line3 + '\n' + line4 return line1 + '\n' + line2 + '\n' + line3
TWITTER_TAGS = [ "agdq2021", "gamesdonequick.com", "agdq", "sgdq", "gamesdonequick", "awesome games done quick", "games done quick", "summer games done quick", "gdq", ] TWITCH_CHANNEL = "gamesdonequick" TWITCH_HOST = "irc.twitch.tv" TWITCH_PORT = 6667 # Update this value to change the current event: EVENT_SHORTHAND = "AGDQ2021" # The following should stay pretty stable between events DONATION_URL = ( "https://gamesdonequick.com/tracker/event/{}".format(EVENT_SHORTHAND) ) SCHEDULE_URL = "https://gamesdonequick.com/schedule" DONATION_INDEX_URL = ( "https://gamesdonequick.com/tracker/donations/{}".format(EVENT_SHORTHAND) ) DONATION_DETAIL_URL = "https://gamesdonequick.com/tracker/donation" DONOR_URL = "https://gamesdonequick.com/tracker/donor"
''' Problem : Find out duplicate number between 1 to N numbers. - Find array sum - Subtract sum of First (n-1) natural numbers from it to find the result. Author : Alok Tripathi ''' # Method to find duplicate in array def findDuplicate(arr, n): return sum(arr) - (((n - 1) * n) // 2) #it will return int not float # Driver method if __name__ == "__main__": arr = [1, 2, 3, 3, 4] n = len(arr) print(findDuplicate(arr, n))
#!/bin/python def ParseCsv(csvFile, interval): bytesList = [] framesList = [] ctn = 0 intervalCtr = 0 frameSun = 0 byteSun = 0 for i in range (0, 10*interval): id, frames, bytes = csvFile[i].split(';') frameSun += int(frames) byteSun += int(bytes) intervalCtr += 1 if interval == intervalCtr: framesList.append(int(frameSun/interval)) bytesList.append(int((byteSun/interval) - (frameSun/interval * 14))) frameSun = 0 byteSun = 0 intervalCtr = 0 return [framesList, bytesList] def LhfAnalyser(): with open('attacker.csv') as fp1: attacker = ParseCsv(fp1.read().splitlines(), 5) with open('victim.csv') as fp3: victim = ParseCsv(fp3.read().splitlines(), 5) with open('amplifier_input.csv') as fp4: amplifierInput = ParseCsv(fp4.read().splitlines(), 5) with open('amplifier_output.csv') as fp5: amplifierOutput = ParseCsv(fp5.read().splitlines(), 5) bytesCsv = open("bytesLhf.csv", 'w') framesCsv = open("framesLhf.csv", 'w') amplifierBytes = open("ampBytes.csv", 'w') amplifierFrames = open("ampFrames.csv", 'w') bp = open("bytesframesLhf.csv", 'w') framesCsv.write("Level;Atk;AmpIn;AmpOut;Vic\n") #framesCsv.write("0;0;0;0;0\n") bytesCsv.write("Level;Atk;AmpIn;AmpOut;Vic\n") #bytesCsv.write("0;0;0;0;0\n") amplifierBytes.write("Level;Input;Output;Amplificação\n") #amplifierBytes.write("0;0;0\n") amplifierFrames.write("Level;Input;Output;Amplificação\n") #amplifierFrames.write("0;0;0\n") bp.write("Level;Input;Output\n") for i in range(0, 10): framesCsv.write(str(i+1) + ';' + str(attacker[0][i]) + ';' + str(amplifierInput[0][i]) + ';' + str(amplifierOutput[0][i]) + ';' + str(victim[0][i]) + '\n') bytesCsv.write(str(i+1) + ';' + str(attacker[1][i]) + ';' + str(amplifierInput[1][i]) + ';' + str(amplifierOutput[1][i]) + ';' + str(victim[1][i]) + '\n') amplifierFrames.write(str(i+1) + ';' + str(amplifierInput[0][i]) + ';' + str(amplifierOutput[0][i]) + ';' + str(round(amplifierOutput[0][i]/amplifierInput[0][i], 2)) + '\n') amplifierBytes.write(str(i+1) + ';' + str(amplifierInput[1][i]) + ';' + str(amplifierOutput[1][i]) + ';' + str(round(amplifierOutput[1][i]/amplifierInput[1][i], 2)) + '\n') bp.write(str(i+1) + ';' + str(round(amplifierInput[1][i]/amplifierInput[0][i], 2)) + ';' + str(round(amplifierOutput[1][i]/amplifierOutput[0][i], 2)) + '\n') LhfAnalyser()
def get_score(player_deck): score_sum=0 for i in player_deck: try: score_sum+=int(i[1]) except: if i[1] in ['K', 'Q', 'J']: score_sum+=10 if i[1]=='Ace': if (score_sum+11)<=21: score_sum+=11 else: score_sum+=1 return score_sum
def ok(msg): """OK message :msg: TODO :returns: TODO """ return {"message": str(msg)} def err(msg): """Error message :msg: TODO :returns: TODO """ return {"error": str(msg)}
#MenuTitle: Count Layer and Edit Note # -*- coding: utf-8 -*- # Edit by Tanukizamurai __doc__=""" Count glyphs layers and add value to glyphs note. """ font = Glyphs.font selectedLayers = font.selectedLayers for thisLayer in selectedLayers: thisGlyph = thisLayer.parent layerCount = len(thisLayer.parent.layers) #count layer glyphName = thisLayer.parent.name glyphNote = thisGlyph.note if glyphNote is None: glyphNote = '' splitNote = glyphNote.split() splitNote.insert(0, 'layercount:' + str(layerCount) + ' ') #insert at head of note finalNote = ' '.join(splitNote) thisGlyph.note = finalNote #update note print('add_note glyph:' + glyphName + ' ' + finalNote)
class Solution: def simplifyPath(self, path): """ :type path: str :rtype: str """ files = path.split('/') stack = list() for f in files: if len(f) == 0 or f == '.': continue elif f == '..': if len(stack): stack.pop() else: continue else: stack.append(f) return '/'+'/'.join(stack)
# coding: utf-8 n = int(input()) a = [int(i) for i in input().split()] for i in range(n): if i < n-1 and a[i+1]<a[i]: break if i==n-1: ans = 0 else: ans = n-1-i a = a[i+1:]+a[:i+1] for i in range(n-1): if a[i] > a[i+1]: print(-1) break else: print(ans)
# Scrapy settings for dirbot project SPIDER_MODULES = ['dirbot.spiders'] NEWSPIDER_MODULE = 'dirbot.spiders' DEFAULT_ITEM_CLASS = 'dirbot.items.Website' ITEM_PIPELINES = { 'dirbot.pipelines.RequiredFieldsPipeline': 1, 'dirbot.pipelines.FilterWordsPipeline': 2, 'dirbot.pipelines.DbPipeline': 3, } # Database settings DB_API_NAME = 'MySQLdb' DB_ARGS = { 'host': 'localhost', 'db': 'dirbot', 'user': 'root', 'passwd': '123', 'charset': 'utf8', 'use_unicode': True, }
class Solution: def getHeight(self, root): if root is None: return 0 lh = self.getHeight(root.left) + 1 rh = self.getHeight(root.right) + 1 return max(lh, rh) def isBalanced(self, root): if root is None: return True leftHeight = self.getHeight(root.left) rightHeight = self.getHeight(root.right) return abs(leftHeight - rightHeight) <= 1 and self.isBalanced(root.left) and self.isBalanced(root.right) ''' Given a sorted array with unique ints, write algo to create binary search tree with min height [1,2,3,4,5,6,7], len 7, middle 3 4 2 6 1 3 5 7 [1,2], len 1, middle 0 1 2 [1,2,3], len 2, middle 1 1 2 3 [1,2,3,4], len 3, middle 1 1 2 3 4 ''' # print(arrToBst([])) # print(arrToBst([1])) # print(arrToBst([1, 2])) # print(arrToBst([1, 2, 3])) # print(arrToBst([1, 2, 3, 4])) # print(arrToBst([1, 2, 3, 4, 5])) print("******* In order 1 *******") # postOrder(root, []) # preOrder(root, []) # inOrder(root, [])
class Solution(object): def nthUglyNumber(self, n): """ :type n: int :rtype: int """ # Dynamic programming, keep track of multiples of ugly 2s, 3s, and 5s # Quick return if n <= 0: return 0 # Create dp array dp = [1] * n # Indices to keep track of last 2, 3, 5 multiple of ugly number idx_2 = idx_3 = idx_5 = 0 # Now loop for i in range(1, n): dp[i] = min(dp[idx_2] * 2, dp[idx_3] * 3, dp[idx_5] * 5) if dp[i] == dp[idx_2] * 2: idx_2 += 1 if dp[i] == dp[idx_3] * 3: idx_3 += 1 if dp[i] == dp[idx_5] * 5: idx_5 += 1 # Return last element in table return dp[-1]
# %% ####################################### def merge_arrays(*lsts: list): """Merges all arrays into one flat list. Examples: >>> lst_abc = ['a','b','c']\n >>> lst_123 = [1,2,3]\n >>> lst_names = ['John','Alice','Bob']\n >>> merge_arrays(lst_abc,lst_123,lst_names)\n ['a', 'b', 'c', 1, 2, 3, 'John', 'Alice', 'Bob'] """ merged_list = [] [merged_list.extend(e) for e in lsts] return merged_list
def get_products_of_all_ints_except_at_index(int_list): if len(int_list) < 2: raise IndexError('Getting the product of numbers at other ' 'indices requires at least 2 numbers') # We make a list with the length of the input list to # hold our products products_of_all_ints_except_at_index = [None] * len(int_list) # For each integer, we find the product of all the integers # before it, storing the total product so far each time product_so_far = 1 for i in range(len(int_list)): products_of_all_ints_except_at_index[i] = product_so_far product_so_far *= int_list[i] # For each integer, we find the product of all the integers # after it. since each index in products already has the # product of all the integers before it, now we're storing # the total product of all other integers product_so_far = 1 for i in range(len(int_list) - 1, -1, -1): products_of_all_ints_except_at_index[i] *= product_so_far product_so_far *= int_list[i] return products_of_all_ints_except_at_index
count = 0 # A global count variable def remember(): global count count += 1 # Count this invocation print(str(count)) remember() remember() remember() remember() remember()
# -*- coding: utf-8 -*- """ Created on Sat Nov 16 17:54:07 2019 @author: SaiLikhithK """ def merge_and_count(b,c): res_arr, inv_count = [], 0 while len(b) > 0 or len(c) > 0: if len(b) > 0 and len(c) > 0: if b[0] < c[0]: res_arr.append(b[0]) b = b[1:] else: res_arr.append(c[0]) c = c[1:] inv_count += len(b) elif len(b) > 0: res_arr.append(b[0]) b = b[1:] elif len(c) > 0: res_arr.append(c[0]) c = c[1:] return res_arr, inv_count def sort_and_count(a): arr_len = len(a) if arr_len <= 1: return a, 0 b,x = sort_and_count(a[:(int)(arr_len/2)]) c,y = sort_and_count(a[(int)(arr_len/2):]) d,z = merge_and_count(b,c) return d, x+y+z #Test Cases t1 = [1,3,5,2,4,6] print ("Testing using", t1) print ("Expecting:", 3) print ("Returned:", sort_and_count(t1)[1]) t2 = [1,5,3,2,4] print ("\nTesting using", t2) print ("Expecting:", 4) print ("Returned:", sort_and_count(t2)[1]) t3 = [5,4,3,2,1] print ("\nTesting using", t3) print ("Expecting:", 10) print ("Returned:", sort_and_count(t3)[1]) t4 = [1,6,3,2,4,5] print ("\nTesting using", t4) print ("Expecting:", 5) print ("Returned:", sort_and_count(t4)[1]) t5 = [1,2,3,4,5,6] print ("\nTesting using", t5) print ("Expecting:", 0) print ("Returned:", sort_and_count(t5)[1]) print ("\n\nFinal run against IntergerArray.txt") with open('IntegerArray.txt', 'r') as f: print (sort_and_count([int(l) for l in f])[1])
class IncapBlocked(ValueError): """ Base exception for exceptions in this module. :param response: The response which was being processed when this error was raised. :type response: requests.Response :param *args: Additional arguments to pass to :class:`ValueError`. """ def __init__(self, response, *args): self.response = response super(IncapBlocked, self).__init__(*args) class MaxRetriesExceeded(IncapBlocked): """ Raised when the number attempts to bypass incapsula has exceeded the amount specified. :param response: The response which was being processed when this error was raised. :type response: requests.Response :param *args: Additional arguments to pass to :class:`ValueError`. """ pass class RecaptchaBlocked(IncapBlocked): """ Raised when re-captcha is encountered. :param response: The response which contains the re-captcha. :type response: requests.Response :param *args: Additional arguments to pass to :class:`ValueError`. """ pass
#!/usr/bin/env python # encoding: utf-8 ''' @author: Jason Lee @license: (C) Copyright @ Jason Lee @contact: jiansenll@163.com @file: median.py @time: 2019/6/15 14:18 @desc: ''' class Solution: """ @param A: An integer array. @param B: An integer array. @return: a double whose format is *.5 or *.0 """ def findMedianSortedArrays(self, A, B): m, n = len(A), len(B) if m == 0 and n == 0: return 0.0 total = m + n if total % 2 == 1: return self.kth_largest(A, B, total // 2 + 1) * 1.0 else: # a = self.kth_largest(A, B, total // 2) # b = self.kth_largest(A, B, total // 2 + 1) a, b = self.kth_largest_two(A, B, total // 2) return (a + b) / 2.0 def kth_largest(self, A, B, kth): m, n = len(A), len(B) if m == 0: return B[kth-1] if n == 0: return A[kth-1] if kth == 1: return min(A[0], B[0]) mid = kth // 2 a, b = float("inf"), float("inf") if m >= mid: a = A[mid - 1] if n >= mid: b = B[mid - 1] if a < b: return self.kth_largest(A[mid:], B, kth - mid) else: return self.kth_largest(A, B[mid:], kth - mid) def kth_largest_two(self, A, B, kth): m, n = len(A), len(B) if m == 0: return B[kth-1], B[kth] if n == 0: return A[kth-1], A[kth] if kth == 1: if A[0] <= B[0]: a = A[0] b = min(A[1], B[0]) if m >= 2 else B[0] else: a = B[0] b = min(A[0], B[1]) if n >= 2 else A[0] return a, b mid = kth // 2 a, b = float("inf"), float("inf") if m >= mid: a = A[mid - 1] if n >= mid: b = B[mid - 1] if a < b: return self.kth_largest_two(A[mid:], B, kth - mid) else: return self.kth_largest_two(A, B[mid:], kth - mid) if __name__ == '__main__': a = [1,2,3] b = [4,5,6,7,8,9,10,11,12,13,14,15,16] res = Solution() c = res.findMedianSortedArrays(a, b) print(c)
def find_rc(rc): rc = rc[:: -1] replacements = {"A": "T", "T": "A", "G": "C", "C": "G"} rc = "".join([replacements.get(c, c) for c in rc]) return rc print(find_rc('ATTA'))
"""Configuration settings for baseball team manager program.""" # The starting players list of lists players = [ ['Joe', 'P', 10, 2, 0.2], ['Tom', 'SS', 11, 4, 0.364], ['Ben', '3B', 0, 0, 0.0], ] # valid baseball team positions valid_positions = ('C', '1B', '2B', '3B', 'SS', 'LF', 'CF', 'RF', 'P')
first_name = input("Please enter your first name: ") print(f"Your first name is: {first_name}") print("a regular string: " + first_name) print('a regular string' + first_name) # string literal with the r prefix print(r'a regular string')
""" Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array. """ class Solution: # @param A, a list of integers # @param target, an integer to be searched # @return an integer def search(self, A, target): return self.search_1(A, target) def search_1(self, A, target): start = 0 end = len(A) - 1 while start + 1 < end: mid = (start + end) / 2 if target == A[mid]: return mid if A[start] < A[mid]: # First half sorted if A[start] <= target < A[mid]: # In first half end = mid else: # In second half start = mid else: # Second half sorted if A[mid] < target <= A[end]: # In second half start = mid else: end = mid if A[start] == target: return start if A[end] == target: return end return -1 # Switching to NC way, use start+1 < end instead def search_rec(self, A, target): return self.search_helper(A, target, 0, len(A) - 1) def search_helper(self, A, target, start, end): if start > end: return -1 mid = (start + end) / 2 if A[mid] == target: return mid elif A[mid] > A[end]: # First half sorted if A[start] <= target and target < A[mid]: return self.search_helper(A, target, start, mid - 1) else: return self.search_helper(A, target, mid + 1, end) else: # Second half sorted if A[mid] < target and target <= A[end]: return self.search_helper(A, target, mid + 1, end) else: return self.search_helper(A, target, start, mid - 1)
# A variable lets you save some information to use later # You can save numbers! my_var = 1 print(my_var) # Or strings! my_var = "MARIO" print(my_var) # Or anything else you need!
def code_to_color(code): assert len(code) in (4, 5, 7, 9), f'Bad format color code: {code}' if len(code) == 4 or len(code) == 5: # "#RGB" or "#RGBA" return tuple(map(lambda x: int(x, 16) * 17, code[1:])) elif len(code) == 7 or len(code) == 9: # "#RRGGBB" or "#RRGGBBAA" return tuple(map(lambda x, y: int(x + y, 16), code[::1], code[1::1])) def color_to_code(color): code = '#' for c in color: code += str(hex(c)) return code colormap = { 'k': (0, 0, 0), 'black': (0, 0, 0), 'r': (255, 0, 0), 'red': (255, 0, 0), 'g': (0, 255, 0), 'green': (0, 255, 0), 'b': (0, 0, 255), 'blue': (0, 0, 255), 'w': (255, 255, 255), 'white': (255, 255, 255), } def lookup_colormap(color): return colormap[color] class Color: def __init__(self, rgb): assert isinstance(rgb, (str, list, tuple)) if isinstance(rgb, str): if rgb[0] == '#': self.rgb = code_to_color(rgb) else: self.rgb = lookup_colormap(rgb) elif isinstance(rgb, (list, tuple)): self.rgb = tuple(rgb) @property def code(self): return color_to_code(self.rgb) @property def gray(self): return int( 0.2126 * self.rgb[0] + 0.7152 * self.rgb[1] + 0.0722 * self.rgb[2])
class Payload: @staticmethod def login_payload(username, password): return {'UserName': username, 'Password': password, 'ValidateUser': '1', 'dbKeyAuth': 'JusticePA', 'SignOn': 'Sign+On'} @staticmethod def payload(param_parser, last_name, first_name, middle_name, birth_date): payload = { '__EVENTTARGET': '', '__EVENTARGUMENT': '', '__VIEWSTATE': param_parser.view_state, '__VIEWSTATEGENERATOR': param_parser.view_state_generator, '__EVENTVALIDATION': param_parser.event_validation, 'NodeID': param_parser.node_id, 'NodeDesc': 'All+Locations', 'SearchBy': '1', 'ExactName': 'on', 'CaseSearchMode': 'CaseNumber', 'CaseSearchValue': '', 'CitationSearchValue': '', 'CourtCaseSearchValue': '', 'PartySearchMode': 'Name', 'AttorneySearchMode': 'Name', 'LastName': last_name, 'FirstName': first_name, 'cboState': 'AA', 'MiddleName': middle_name, 'DateOfBirth': birth_date, 'DriverLicNum': '', 'CaseStatusType': '0', 'DateFiledOnAfter': '', 'DateFiledOnBefore': '', 'chkCriminal': 'on', 'chkFamily': 'on', 'chkCivil': 'on', 'chkProbate': 'on', 'chkDtRangeCriminal': 'on', 'chkDtRangeFamily': 'on', 'chkDtRangeCivil': 'on', 'chkDtRangeProbate': 'on', 'chkCriminalMagist': 'on', 'chkFamilyMagist': 'on', 'chkCivilMagist': 'on', 'chkProbateMagist': 'on', 'DateSettingOnAfter': '', 'DateSettingOnBefore': '', 'SortBy': 'fileddate', 'SearchSubmit': 'Search', 'SearchType': 'PARTY', 'SearchMode': 'NAME', 'NameTypeKy': 'ALIAS', 'BaseConnKy': 'DF', 'StatusType': 'true', 'ShowInactive': '', 'AllStatusTypes': 'true', 'CaseCategories': '', 'RequireFirstName': 'True', 'CaseTypeIDs': '', 'HearingTypeIDs': '', 'SearchParams': "SearchBy~~Search+By:~~Defendant~~Defendant||chkExactName~~Exact+Name:~~on~~on||PartyNameOption~~Party+Search+Mode:~~Name~~Name||LastName~~Last+Name:~~" + last_name + "~~" + last_name + "||FirstName~~First+Name:~~" + first_name + "~~" + first_name + "||MiddleName~~Middle+Name:~~" + middle_name + "~~" + middle_name+ "||DateOfBirth~~Date+of+Birth:~~" + birth_date + "~~" + birth_date + "||AllOption~~All~~0~~All||selectSortBy~~Sort+By:~~Filed+Date~~Filed+Date" } return payload class URL: @staticmethod def login_url(): return 'https://publicaccess.courts.oregon.gov/PublicAccessLogin/login.aspx'
class Solution: def addBinary(self, a: str, b: str) -> str: max_len = max(len(a), len(b)) a = a.zfill(max_len) b = b.zfill(max_len) result = '' # initialize the carry carry = 0 # Traverse the string for i in range(max_len - 1, -1, -1): r = carry r += 1 if a[i] == '1' else 0 r += 1 if b[i] == '1' else 0 result = ('1' if r % 2 == 1 else '0') + result carry = 0 if r < 2 else 1 # Compute the carry. if carry !=0 : result = '1' + result return result.zfill(max_len)
''' Locating suspicious data You will now inspect the suspect record by locating the offending row. You will see that, according to the data, Joyce Chepchumba was a man that won a medal in a women's event. That is a data error as you can confirm with a web search. INSTRUCTIONS 70XP Create a Boolean Series with a condition that captures the only row that has medals.Event_gender == 'W' and medals.Gender == 'Men'. Be sure to use the & operator. Use the Boolean Series to create a DataFrame called suspect with the suspicious row. Print suspect. This has been done for you, so hit 'Submit Answer' to see the result. ''' # Create the Boolean Series: sus sus = (medals.Event_gender == 'W') & (medals.Gender == 'Men') # Create a DataFrame with the suspicious row: suspect suspect = medals[(medals.Event_gender == 'W') & (medals.Gender == 'Men')] # Print suspect print(suspect)
class InvalidSymbolException(Exception): pass class InvalidMoveException(Exception): pass class InvalidCoordinateInputException(Exception): pass
def odd_nums(number: int) -> int: for num in range(1, number + 1, 2): yield num pass n = 15 generator = odd_nums(n) for _ in range(1, n + 1, 2): print(next(generator)) next(generator)
def find_nemo(array): for item in array: if item == 'nemo': print('found NEMO') nemo = ['nemo'] find_nemo(nemo)
def loss_function(X_values, X_media, X_org): # X_media = { # "labels": ["facebook", "tiktok"], # "coefs": [6.454, 1.545], # "drs": [0.6, 0.7] # } # X_org = { # "labels": ["const"], # "coefs": [-27.5], # "values": [1] # } y = 0 for i in range(len(X_values)): transform = X_values[i] ** X_media["drs"][i] contrib = X_media["coefs"][i] * transform y += contrib for i in range(len(X_org)): contrib = X_org["coefs"][i] * X_org["values"][i] y += contrib return -y
"""map() and filter(): ('list' only a literal list if you call list over it) map(func, list) -> Returns 'list' with func applied to items. strings = map(str, [hello, world]) strings == ['hello', 'world'] filter(func, list) -> Returns 'list' of items that func already applies to. even = filter(lambda n: n % 2, [3, 4, 5, 6]) even == [4, 6] """ def circle_area(r): return 3.14 * (r * r) nums = input( "Please type each of the radii values. Separate with spaces. Ex: '5 3 86 11 4'\n").split( " ") # nums = map(int, nums) # radii = list(map(circle_area, nums)) # list(map(print, radii)) # # for i in radii: # # print(i) for i in nums: x = circle_area(int(i)) print(x)
def getcommonletters(strlist): return ''.join([x[0] for x in zip(*strlist) \ if reduce(lambda a,b:(a == b) and a or None,x)]) def findcommonstart(strlist): strlist = strlist[:] prev = None while True: common = getcommonletters(strlist) if common == prev: break strlist.append(common) prev = common return getcommonletters(strlist)
# DO NOT comment out # (REQ) REQUIRED # ***************************************************************************** # DATA DISCOVERY ENGINE - MAIN (REQ) # ***************************************************************************** # name also used on metadata SITE_NAME = "NIAID Data Portal" SITE_DESC = 'An aggregator of open datasets, with a particular focus on allergy and infectious diseases' API_URL = "https://crawler.biothings.io/api/" SITE_URL = "https://discovery.biothings.io/niaid/" # SITE_URL = "http://localhost:8000/" CONTACT_REPO = "https://github.com/SuLab/niaid-data-portal" CONTACT_EMAIL = "cd2h-metadata@googlegroups.com" # ***************************************************************************** # DATA DISCOVERY ENGINE - METADATA (REQ) # ***************************************************************************** METADATA_CONTENT_URL = "http://discovery.biothings.io/" METADATA_DESC = 'An aggregator of open datasets, with a particular focus on allergy and infectious diseases' METADATA_FEATURED_IMAGE = "https://i.postimg.cc/vZYnpSML/featured.jpg" METADATA_MAIN_COLOR = "#1C5D5D" # ***************************************************************************** # DATA DISCOVERY ENGINE - COLORS (REQ) # ***************************************************************************** MAIN_COLOR = "#113B56" SEC_COLOR = "#0F627C" # ***************************************************************************** # DATA DISCOVERY ENGINE - IMAGES (REQ) # ***************************************************************************** # create a folder with <name> and put all icons there STATIC_IMAGE_FOLDER = 'niaid' # ***************************************************************************** # REPOSITORY NAMES # ***************************************************************************** # List of all possible repositories. # NOTE: Everything should be automated; if you want to change the sort order in the heatmap in /schema, though, you need to alter schema.vue:repoOrder REPOSITORIES = [{ "name": "Omics DI", "id": "omicsdi", "synonyms": ["omicsdi", "indexed_omicsdi"], "img_src": "static/img/repositories/omicsdi.png", "url": "https://www.omicsdi.org/", "description": "" }, { "name": "NCBI GEO", "id": "ncbi_geo", "synonyms": ["indexed_ncbi_geo", "ncbi_geo", "ncbi geo"], "img_src": "static/img/repositories/geo.gif", "url": "https://www.ncbi.nlm.nih.gov/geo/", "description": "" }, { "name": "Zenodo", "id": "zenodo", "synonyms": ["indexed_zenodo", "zenodo"], "img_src": "static/img/repositories/zenodo.svg", "url": "https://zenodo.org/", "description": "" }, { "name": "Harvard Dataverse", "id": "harvard_dataverse", "synonyms": ["indexed_harvard_dataverse", "harvard_dataverse", "harvard dataverse"], "img_src": "static/img/repositories/dataverse_small.png", "url": "https://dataverse.harvard.edu/", "description": "" }, { "name": "NYU Data Catalog", "id": "nyu", "synonyms": ["indexed_nyu", "nyu"], "img_src": "static/img/repositories/nyu.png", "url": "https://datacatalog.med.nyu.edu/", "description": "" }, { "name": "ImmPort", "id": "immport", "synonyms": ["indexed_immport", "immport"], "img_src": "static/img/repositories/immport.png", "url": "https://www.immport.org/home", "description": "" }, { "name": "Data Discovery Engine", "id": "discovery", "synonyms": ["indexed_discovery", "discovery"], "img_src": "static/img/repositories/dde.png", "url": "https://discovery.biothings.io/dataset", "description": "" } ]
# pylint: skip-file POKEAPI_POKEMON_LIST_EXAMPLE = { "count": 949, "previous": None, "results": [ { "url": "https://pokeapi.co/api/v2/pokemon/21/", "name": "spearow" }, { "url": "https://pokeapi.co/api/v2/pokemon/22/", "name": "fearow" } ] } POKEAPI_POKEMON_DATA_EXAMPLE_FIRST = { "forms": [ { "url": "https://pokeapi.co/api/v2/pokemon-form/21/", "name": "spearow" } ], "stats": [ { "stat": { "url": "https://pokeapi.co/api/v2/stat/6/", "name": "speed" }, "effort": 1, "base_stat": 70 }, { "stat": { "url": "https://pokeapi.co/api/v2/stat/5/", "name": "special-defense" }, "effort": 0, "base_stat": 31 }, { "stat": { "url": "https://pokeapi.co/api/v2/stat/4/", "name": "special-attack" }, "effort": 0, "base_stat": 31 }, { "stat": { "url": "https://pokeapi.co/api/v2/stat/3/", "name": "defense" }, "effort": 0, "base_stat": 30 }, { "stat": { "url": "https://pokeapi.co/api/v2/stat/2/", "name": "attack" }, "effort": 0, "base_stat": 60 }, { "stat": { "url": "https://pokeapi.co/api/v2/stat/1/", "name": "hp" }, "effort": 0, "base_stat": 40 } ], "name": "spearow", "weight": 20, "sprites": { "back_female": None, "back_shiny_female": None, "back_default": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/21.png", "front_female": None, "front_shiny_female": None, "back_shiny": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/shiny/21.png", "front_default": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/21.png", "front_shiny": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/shiny/21.png" }, "id": 21, "order": 30, "base_experience": 52 } POKEAPI_POKEMON_DATA_EXAMPLE_SECOND = { "forms": [ { "url": "https://pokeapi.co/api/v2/pokemon-form/22/", "name": "fearow" } ], "stats": [ { "stat": { "url": "https://pokeapi.co/api/v2/stat/6/", "name": "speed" }, "effort": 2, "base_stat": 100 }, { "stat": { "url": "https://pokeapi.co/api/v2/stat/5/", "name": "special-defense" }, "effort": 0, "base_stat": 31 }, { "stat": { "url": "https://pokeapi.co/api/v2/stat/4/", "name": "special-attack" }, "effort": 0, "base_stat": 31 }, { "stat": { "url": "https://pokeapi.co/api/v2/stat/3/", "name": "defense" }, "effort": 0, "base_stat": 65 }, { "stat": { "url": "https://pokeapi.co/api/v2/stat/2/", "name": "attack" }, "effort": 0, "base_stat": 90 }, { "stat": { "url": "https://pokeapi.co/api/v2/stat/1/", "name": "hp" }, "effort": 0, "base_stat": 40 } ], "name": "fearow", "weight": 100, "sprites": { "back_female": None, "back_shiny_female": None, "back_default": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/22.png", "front_female": None, "front_shiny_female": None, "back_shiny": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/shiny/22.png", "front_default": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/22.png", "front_shiny": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/shiny/22.png" }, "id": 22, "order": 30, "base_experience": 52 }
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class Mapping: def __init__(self, iterable): self.items_list = [] self.__update(iterable) def __update(self, iterable): for item in iterable: self.items_list.append(item) def test_parent(self): print(self.__update) class MappingSubclass(Mapping): def __update(self, keys, values): # provides new signature for update() # but does not break __init__() for item in zip(keys, values): self.items_list.append(item) def test_child(self): print(self.__update) # print(Mapping.__update) # Results in error print(Mapping._Mapping__update) print(MappingSubclass._Mapping__update) print(MappingSubclass._MappingSubclass__update) parent = Mapping([]) child = MappingSubclass([]) parent.test_parent() child.test_parent() child.test_child()
class Solution: def removeElement(self, nums: List[int], val: int) -> int: i = 0 length = len(nums) while i < length: if nums[i] == val: nums[i:] = nums[i + 1:] length -= 1 else: i += 1 return length
# 7x^1 - 2x^2 + 1x^3 + 2x^4 = 3 # 2x^1 + 8x^2 + 3x^3 + 1x^4 = -2 # -1x^1 + 0x^2 + 5x^3 + 2x^4 = 5 # 0x^1 + 2x^2 - 1x^3 + 4x^4 = 4 def getX1(x2,x3,x4): return (3+2*x2-x3-2*x4)/7 def getX2(x1,x3,x4): return (-2-2*x1-3*x3-x4)/8 def getX3(x1,x2,x4): return (5+x1-2*x4)/5 def getX4(x1,x2,x3): return (4-2*x2+x3)/4 x1=0 x2=0 x3=0 x4=0 #error=0.00001 x1a = 0.00001 x2a = 0.00001 x3a = 0.00001 x4a = 0.00001 for i in range(5): x1 = getX1(x2,x3, x4) x2 = getX2(x1,x3, x4) x3 = getX3(x1,x2, x4) x4 = getX4(x1,x2, x3) #print("VALUES {0}{1}{2}{3}".format(x1,x2,x3,x4)) ex1 = abs((x1a-x1)/x1a) ex2 = abs((x2a-x2)/x2a) ex3 = abs((x3a-x3)/x3a) ex4 = abs((x4a-x4)/x4a) #if ex1 < error and ex2 < error and ex3 < error: #break x1a = x1 x2a = x2 x3a = x3 x4a = x4 print("FINAL: {0}\t{1}\t{2}\t{3}".format(x1,x2,x3,x4)) print("Errores: {0}\t{1}\t{2}\t{3}".format(ex1,ex2,ex3,ex4))
def calc_fact(num): total = 0 final_tot = 1 for x in range(num): total = final_tot * (x+1) final_tot = total print(total) calc_fact(10) # excepted output: 3628800
# criando função sem print e sem return def erro(x=10, y=10): x+y print(erro())
""" Напишите рекурсивную функцию sum(a, b), возвращающую сумму двух целых неотрицательных чисел. Из всех арифметических операций допускаются только +1 и -1. Также нельзя использовать циклы. Формат ввода Вводятся два удовлетворяющих условию задачи числа. Числа не превышают 900. Формат вывода Выведите ответ на задачу. """ def sum(a, b): if b != 0: return sum(a + 1, b - 1) else: return a a = int(input()) b = int(input()) print(sum(a, b))
idade = int(input('Digite sua idade: ')) sexo = str(input('Digite o sexo M ou F: ')).upper() #if idade > 18: # print('Você já tem que pagar suas contas') #elif idade == 18: # print('Vai começar a se fuder agora') #else: # print('Pode deixar que os seus Pais pagam a conta.') if sexo == 'M': if idade >= 18: print('Homem maior de idade') else: print('Homem menor de idade') elif sexo == 'F': if idade >= 18: print('Mulher maior de idade') else: print('Mulher menor de idade') else: print('Sexo não definido') print() print('Testando IF de outra forma') if idade >= 18: if sexo == 'M': print('Homem maior de idade') else: print('Mulher maior de idade') elif idade < 18: if sexo == 'M': print('Homem menor de idade') else: print('Mulher menor de idade') else: print('Sexo não definido')
z = int(input()) y = int(input()) x = int(input()) space = x * y * z box = int(0) box_space = int(0) while box != "Done": box = input() if box != "Done": box = float(box) box = int(box) box_space += box if box_space > space: print(f"No more free space! You need {box_space - space} Cubic meters more.") break if box == "Done": if space - box_space >= 0: print(f"{space - box_space} Cubic meters left.") if box_space - space >= 0: print(f"No more free space! You need {box_space - space} Cubic meters more.")
DEBUG_MODE = False #DIR_BASE = '/tmp/sms' DIR_BASE = '/var/spool/sms' DIR_INCOMING = 'incoming' DIR_OUTGOING = 'outgoing' DIR_CHECKED = 'checked' DIR_FAILED = 'failed' DIR_SENT = 'sent' # Default international phone code DEFAULT_CODE = '62' # Unformatted messages will forward to FORWARD_TO = ('62813123123', '62813123124')
#=============================================================== # DMXIS Macro (c) 2010 db audioware limited #=============================================================== sel = GetAllSelCh(False) if len(sel)>0: for ch in sel: RemoveFixture(ch)
class Solution(object): def getRow(self, rowIndex): """ :type numRows: int :rtype: List[List[int]] """ if rowIndex == 0: return [1] if rowIndex == 1: return [1, 1] r = [1, 1] for n in range(2, rowIndex + 1): row = [] for k in range(0, n + 1): if k == 0 or k == n: row.append(1) continue row.append(r[k - 1] + r[k]) r = row return r def test_get_row(): s = Solution() assert [1] == s.getRow(0) assert [1, 1] == s.getRow(1) assert [1, 2, 1] == s.getRow(2) assert [1, 3, 3, 1] == s.getRow(3) assert [1, 4, 6, 4, 1] == s.getRow(4)
#!/usr/bin/python3 def echo(input): return input def count_valid(data, anagrams=True): valid = 0 if anagrams: sort = echo else: sort = sorted for line in data: words = [] for word in line.split(): if sort(word) not in words: words.append(sort(word)) else: break else: valid += 1 return valid if __name__ == "__main__": with open("4") as dfile: data = dfile.readlines() print("Solution 1:", count_valid(data)) print("Solution 2:", count_valid(data, False))
def initialize(): global detected, undetected, unsupported, total, report_id detected = {} undetected = {} unsupported = {} total = {} report_id = {} def initialize_colours(): global HEADER, OKBLUE, OKCYAN, OKGREEN, WARNING, FAIL, ENDC, BOLD, UNDERLINE, ALERT, GRAY, WHITE, END global C HEADER = '\033[95m' OKBLUE = '\033[94m' OKCYAN = '\033[96m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' RED = '\033[91m\033[1m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' ALERT = '\033[91m\033[4m\033[1m' GRAY = '\033[90m' WHITE = '\033[1m\033[97m' END = '\033[0m' C = '\033[1m' def initialize_flask(): global mal_df, mal_file_dict, ctime, djvu_files mal_df = None mal_file_dict = {} ctime = '' djvu_files = []
""" Problem 2_1: Write a function 'problem2_1()' that sets a variable lis = list(range(20,30)) and does all of the following, each on a separate line: (a) print the element of lis with the index 3 (b) print lis itself (c) write a 'for' loop that prints out every element of lis. Recall that len() will give you the length of such a data collection if you need that. Use end=" " to put one space between the elements of the list lis. Allow the extra space at the end of the list to stand, don't make a special case of it. """ def problem2_1(): lis = list(range(20, 30)) print(lis[3]) print(lis) for n in lis: print(str(n)+" ", end='') #print(problem2_1())