content
stringlengths
7
1.05M
def getBuiltinTargs(): return { "1": { "name": "1", "ptype": "maven2", "patterns": [".*"], "defincpat": ["**"], "defexcpat": [] }, "2": { "name": "2", "ptype": "maven1", "patterns": [".*"], "defincpat": ["**"], "defexcpat": [] }, "3": { "name": "3", "ptype": "maven2", "patterns": ["(?!.*-sources.*).*"], "defincpat": ["**"], "defexcpat": ["**/*-sources.*/**"] }, "4": { "name": "4", "ptype": "maven2", "patterns": [".*maven-metadata\.xml.*"], "defincpat": ["**/*maven-metadata.xml*"], "defexcpat": [] }, "any": { "name": "any", "ptype": "any", "patterns": [".*"], "defincpat": ["**"], "defexcpat": [] }, "site": { "name": "site", "ptype": "site", "patterns": [".*"], "defincpat": ["**"], "defexcpat": [] }, "npm": { "name": "npm", "ptype": "npm", "patterns": [".*"], "defincpat": ["**"], "defexcpat": [] }, "nuget": { "name": "nuget", "ptype": "nuget", "patterns": [".*"], "defincpat": ["**"], "defexcpat": [] }, "rubygems": { "name": "rubygems", "ptype": "rubygems", "patterns": [".*"], "defincpat": ["**"], "defexcpat": [] } } def getBuiltinPrivs(targs): return { "All M1 Repositories": { "name": "All M1 Repositories", "target": targs["2"], "repo": "*", "builtin": True }, "All M2 Repositories": { "name": "All M2 Repositories", "target": targs["1"], "repo": "*", "builtin": True }, "All npm Repositories": { "name": "All npm Repositories", "target": targs["npm"], "repo": "*", "builtin": True }, "All NuGet Repositories": { "name": "All NuGet Repositories", "target": targs["nuget"], "repo": "*", "builtin": True }, "All Repositories": { "name": "All Repositories", "target": targs["any"], "repo": "*", "builtin": True }, "All Rubygems Repositories": { "name": "All Rubygems Repositories", "target": targs["rubygems"], "repo": "*", "builtin": True }, "All Site Repositories": { "name": "All Site Repositories", "target": targs["site"], "repo": "*", "builtin": True } } def getBuiltinPrivmap(privs): return { "repository-all": { "id": "repository-all", "repo": "*", "type": "view", "needadmin": False }, "T6": { "id": "T6", "method": "create", "priv": privs["All M1 Repositories"], "type": "target", "needadmin": False }, "T8": { "id": "T8", "method": "delete", "priv": privs["All M1 Repositories"], "type": "target", "needadmin": False }, "T2": { "id": "T2", "method": "read", "priv": privs["All M1 Repositories"], "type": "target", "needadmin": False }, "T4": { "id": "T4", "method": "update", "priv": privs["All M1 Repositories"], "type": "target", "needadmin": False }, "T5": { "id": "T5", "method": "create", "priv": privs["All M2 Repositories"], "type": "target", "needadmin": False }, "T7": { "id": "T7", "method": "delete", "priv": privs["All M2 Repositories"], "type": "target", "needadmin": False }, "T1": { "id": "T1", "method": "read", "priv": privs["All M2 Repositories"], "type": "target", "needadmin": False }, "T3": { "id": "T3", "method": "update", "priv": privs["All M2 Repositories"], "type": "target", "needadmin": False }, "npm-create": { "id": "npm-create", "method": "create", "priv": privs["All npm Repositories"], "type": "target", "needadmin": False }, "npm-delete": { "id": "npm-delete", "method": "delete", "priv": privs["All npm Repositories"], "type": "target", "needadmin": False }, "npm-read": { "id": "npm-read", "method": "read", "priv": privs["All npm Repositories"], "type": "target", "needadmin": False }, "npm-update": { "id": "npm-update", "method": "update", "priv": privs["All npm Repositories"], "type": "target", "needadmin": False }, "nuget-create": { "id": "nuget-create", "method": "create", "priv": privs["All NuGet Repositories"], "type": "target", "needadmin": False }, "nuget-delete": { "id": "nuget-delete", "method": "delete", "priv": privs["All NuGet Repositories"], "type": "target", "needadmin": False }, "nuget-read": { "id": "nuget-read", "method": "read", "priv": privs["All NuGet Repositories"], "type": "target", "needadmin": False }, "nuget-update": { "id": "nuget-update", "method": "update", "priv": privs["All NuGet Repositories"], "type": "target", "needadmin": False }, "T11": { "id": "T11", "method": "create", "priv": privs["All Repositories"], "type": "target", "needadmin": False }, "T12": { "id": "T12", "method": "delete", "priv": privs["All Repositories"], "type": "target", "needadmin": False }, "T9": { "id": "T9", "method": "read", "priv": privs["All Repositories"], "type": "target", "needadmin": False }, "T10": { "id": "T10", "method": "update", "priv": privs["All Repositories"], "type": "target", "needadmin": False }, "rubygems-create": { "id": "rubygems-create", "method": "create", "priv": privs["All Rubygems Repositories"], "type": "target", "needadmin": False }, "rubygems-delete": { "id": "rubygems-delete", "method": "delete", "priv": privs["All Rubygems Repositories"], "type": "target", "needadmin": False }, "rubygems-read": { "id": "rubygems-read", "method": "read", "priv": privs["All Rubygems Repositories"], "type": "target", "needadmin": False }, "rubygems-update": { "id": "rubygems-update", "method": "update", "priv": privs["All Rubygems Repositories"], "type": "target", "needadmin": False }, "site-create": { "id": "site-create", "method": "create", "priv": privs["All Site Repositories"], "type": "target", "needadmin": False }, "site-delete": { "id": "site-delete", "method": "delete", "priv": privs["All Site Repositories"], "type": "target", "needadmin": False }, "site-read": { "id": "site-read", "method": "read", "priv": privs["All Site Repositories"], "type": "target", "needadmin": False }, "site-update": { "id": "site-update", "method": "update", "priv": privs["All Site Repositories"], "type": "target", "needadmin": False }, "1000": { "id": "1000", "method": "*", "permission": "nexus:*", "type": "application", "needadmin": True }, "analytics-all": { "id": "analytics-all", "method": "*", "permission": "nexus:analytics", "type": "application", "needadmin": False }, "83": { "id": "83", "method": "*", "permission": "apikey:access", "type": "application", "needadmin": False }, "54": { "id": "54", "method": "read", "permission": "nexus:artifact", "type": "application", "needadmin": False }, "65": { "id": "65", "method": "create,read", "permission": "nexus:artifact", "type": "application", "needadmin": False }, "atlas-all": { "id": "atlas-all", "method": "*", "permission": "nexus:atlas", "type": "application", "needadmin": False }, "browse-remote-repo": { "id": "browse-remote-repo", "method": "read", "permission": "nexus:browseremote", "type": "application", "needadmin": False }, "capabilities-create-read": { "id": "capabilities-create-read", "method": "create,read", "permission": "nexus:capabilities", "type": "application", "needadmin": False }, "capabilities-delete-read": { "id": "capabilities-delete-read", "method": "delete,read", "permission": "nexus:capabilities", "type": "application", "needadmin": False }, "capabilities-read": { "id": "capabilities-read", "method": "read", "permission": "nexus:capabilities", "type": "application", "needadmin": False }, "capabilities-update-read": { "id": "capabilities-update-read", "method": "update,read", "permission": "nexus:capabilities", "type": "application", "needadmin": False }, "capability-types-read": { "id": "capability-types-read", "method": "read", "permission": "nexus:capabilityTypes", "type": "application", "needadmin": False }, "19": { "id": "19", "method": "read", "permission": "nexus:identify", "type": "application", "needadmin": False }, "21": { "id": "21", "method": "delete,read", "permission": "nexus:cache", "type": "application", "needadmin": True }, "43": { "id": "43", "method": "read", "permission": "nexus:configuration", "type": "application", "needadmin": False }, "nexus-healthcheck-read": { "id": "nexus-healthcheck-read", "method": "read", "permission": "nexus:healthcheck", "type": "application", "needadmin": False }, "nexus-healthcheck-update": { "id": "nexus-healthcheck-update", "method": "update", "permission": "nexus:healthcheck", "type": "application", "needadmin": False }, "nexus-healthcheck-summary-read": { "id": "nexus-healthcheck-summary-read", "method": "read", "permission": "nexus:healthchecksummary", "type": "application", "needadmin": False }, "ldap-conn-read": { "id": "ldap-conn-read", "method": "read", "permission": "nexus:ldapconninfo", "type": "application", "needadmin": False }, "ldap-conn-update": { "id": "ldap-conn-update", "method": "update", "permission": "nexus:ldapconninfo", "type": "application", "needadmin": True }, "ldap-test-auth-conf": { "id": "ldap-test-auth-conf", "method": "update", "permission": "nexus:ldaptestauth", "type": "application", "needadmin": True }, "ldap-test-user-group-conf": { "id": "ldap-test-user-group-conf", "method": "update", "permission": "nexus:ldaptestuserconf", "type": "application", "needadmin": True }, "ldap-user-group-conf-read": { "id": "ldap-user-group-conf-read", "method": "read", "permission": "nexus:ldapusergroupconf", "type": "application", "needadmin": False }, "ldap-user-group-conf-update": { "id": "ldap-user-group-conf-update", "method": "update", "permission": "nexus:ldapusergroupconf", "type": "application", "needadmin": True }, "ldap-user-role-map-create": { "id": "ldap-user-role-map-create", "method": "create", "permission": "nexus:ldapuserrolemap", "type": "application", "needadmin": True }, "ldap-user-role-map-delete": { "id": "ldap-user-role-map-delete", "method": "delete,read", "permission": "nexus:ldapuserrolemap", "type": "application", "needadmin": True }, "ldap-user-role-map-read": { "id": "ldap-user-role-map-read", "method": "read", "permission": "nexus:ldapuserrolemap", "type": "application", "needadmin": False }, "ldap-user-role-map-update": { "id": "ldap-user-role-map-update", "method": "update", "permission": "nexus:ldapuserrolemap", "type": "application", "needadmin": True }, "77": { "id": "77", "method": "read,update", "permission": "nexus:logconfig", "type": "application", "needadmin": False }, "2": { "id": "2", "method": "read", "permission": "nexus:authentication", "type": "application", "needadmin": False }, "42": { "id": "42", "method": "read", "permission": "nexus:logs", "type": "application", "needadmin": False }, "metrics-endpoints": { "id": "metrics-endpoints", "method": "*", "permission": "nexus:metrics-endpoints", "type": "application", "needadmin": False }, "66": { "id": "66", "method": "update,read", "permission": "nexus:command", "type": "application", "needadmin": False }, "plugin-infos-read": { "id": "plugin-infos-read", "method": "read", "permission": "nexus:pluginconsoleplugininfos", "type": "application", "needadmin": False }, "55": { "id": "55", "method": "read", "permission": "nexus:repostatus", "type": "application", "needadmin": False }, "73": { "id": "73", "method": "read", "permission": "nexus:componentrealmtypes", "type": "application", "needadmin": False }, "76": { "id": "76", "method": "delete,read", "permission": "nexus:metadata", "type": "application", "needadmin": False }, "20": { "id": "20", "method": "delete,read", "permission": "nexus:attributes", "type": "application", "needadmin": False }, "18": { "id": "18", "method": "delete,read", "permission": "nexus:index", "type": "application", "needadmin": False }, "5": { "id": "5", "method": "create,read", "permission": "nexus:repositories", "type": "application", "needadmin": True }, "8": { "id": "8", "method": "delete,read", "permission": "nexus:repositories", "type": "application", "needadmin": True }, "6": { "id": "6", "method": "read", "permission": "nexus:repositories", "type": "application", "needadmin": False }, "7": { "id": "7", "method": "update,read", "permission": "nexus:repositories", "type": "application", "needadmin": True }, "70": { "id": "70", "method": "read", "permission": "nexus:componentscontentclasses", "type": "application", "needadmin": False }, "13": { "id": "13", "method": "create,read", "permission": "nexus:repogroups", "type": "application", "needadmin": True }, "16": { "id": "16", "method": "delete,read", "permission": "nexus:repogroups", "type": "application", "needadmin": True }, "14": { "id": "14", "method": "read", "permission": "nexus:repogroups", "type": "application", "needadmin": False }, "15": { "id": "15", "method": "update,read", "permission": "nexus:repogroups", "type": "application", "needadmin": True }, "79": { "id": "79", "method": "create,read", "permission": "nexus:repositorymirrors", "type": "application", "needadmin": False }, "78": { "id": "78", "method": "read", "permission": "nexus:repositorymirrors", "type": "application", "needadmin": False }, "82": { "id": "82", "method": "read", "permission": "nexus:repositorymirrorsstatus", "type": "application", "needadmin": False }, "81": { "id": "81", "method": "read", "permission": "nexus:repositorypredefinedmirrors", "type": "application", "needadmin": False }, "22": { "id": "22", "method": "create,read", "permission": "nexus:routes", "type": "application", "needadmin": False }, "25": { "id": "25", "method": "delete,read", "permission": "nexus:routes", "type": "application", "needadmin": False }, "23": { "id": "23", "method": "read", "permission": "nexus:routes", "type": "application", "needadmin": False }, "24": { "id": "24", "method": "update,read", "permission": "nexus:routes", "type": "application", "needadmin": False }, "67": { "id": "67", "method": "read", "permission": "nexus:repometa", "type": "application", "needadmin": False }, "45": { "id": "45", "method": "create,read", "permission": "nexus:targets", "type": "application", "needadmin": True }, "48": { "id": "48", "method": "delete,read", "permission": "nexus:targets", "type": "application", "needadmin": True }, "46": { "id": "46", "method": "read", "permission": "nexus:targets", "type": "application", "needadmin": False }, "47": { "id": "47", "method": "update,read", "permission": "nexus:targets", "type": "application", "needadmin": True }, "9": { "id": "9", "method": "create,read", "permission": "nexus:repotemplates", "type": "application", "needadmin": False }, "12": { "id": "12", "method": "delete,read", "permission": "nexus:repotemplates", "type": "application", "needadmin": False }, "10": { "id": "10", "method": "read", "permission": "nexus:repotemplates", "type": "application", "needadmin": False }, "11": { "id": "11", "method": "update,read", "permission": "nexus:repotemplates", "type": "application", "needadmin": False }, "74": { "id": "74", "method": "read", "permission": "nexus:componentsrepotypes", "type": "application", "needadmin": False }, "44": { "id": "44", "method": "read", "permission": "nexus:feeds", "type": "application", "needadmin": False }, "69": { "id": "69", "method": "read", "permission": "nexus:tasktypes", "type": "application", "needadmin": False }, "71": { "id": "71", "method": "read", "permission": "nexus:componentscheduletypes", "type": "application", "needadmin": False }, "26": { "id": "26", "method": "create,read", "permission": "nexus:tasks", "type": "application", "needadmin": True }, "29": { "id": "29", "method": "delete,read", "permission": "nexus:tasks", "type": "application", "needadmin": True }, "27": { "id": "27", "method": "read", "permission": "nexus:tasks", "type": "application", "needadmin": False }, "68": { "id": "68", "method": "read,delete", "permission": "nexus:tasksrun", "type": "application", "needadmin": True }, "28": { "id": "28", "method": "update,read", "permission": "nexus:tasks", "type": "application", "needadmin": True }, "17": { "id": "17", "method": "read", "permission": "nexus:index", "type": "application", "needadmin": False }, "1001": { "id": "1001", "method": "*", "permission": "security:*", "type": "application", "needadmin": True }, "3": { "id": "3", "method": "read", "permission": "nexus:settings", "type": "application", "needadmin": False }, "4": { "id": "4", "method": "update,read", "permission": "nexus:settings", "type": "application", "needadmin": True }, "49": { "id": "49", "method": "update,read", "permission": "nexus:status", "type": "application", "needadmin": True }, "1": { "id": "1", "method": "read", "permission": "nexus:status", "type": "application", "needadmin": False }, "56": { "id": "56", "method": "update", "permission": "nexus:repostatus", "type": "application", "needadmin": True }, "64": { "id": "64", "method": "create,read", "permission": "security:userschangepw", "type": "application", "needadmin": False }, "57": { "id": "57", "method": "create,read", "permission": "security:usersforgotpw", "type": "application", "needadmin": False }, "58": { "id": "58", "method": "create,read", "permission": "security:usersforgotid", "type": "application", "needadmin": False }, "75": { "id": "75", "method": "read", "permission": "security:componentsuserlocatortypes", "type": "application", "needadmin": False }, "80": { "id": "80", "method": "read", "permission": "security:privilegetypes", "type": "application", "needadmin": False }, "30": { "id": "30", "method": "create,read", "permission": "security:privileges", "type": "application", "needadmin": True }, "33": { "id": "33", "method": "delete,read", "permission": "security:privileges", "type": "application", "needadmin": True }, "31": { "id": "31", "method": "read", "permission": "security:privileges", "type": "application", "needadmin": False }, "32": { "id": "32", "method": "update,read", "permission": "security:privileges", "type": "application", "needadmin": True }, "59": { "id": "59", "method": "delete,read", "permission": "security:usersreset", "type": "application", "needadmin": True }, "34": { "id": "34", "method": "create,read", "permission": "security:roles", "type": "application", "needadmin": True }, "37": { "id": "37", "method": "delete,read", "permission": "security:roles", "type": "application", "needadmin": True }, "35": { "id": "35", "method": "read", "permission": "security:roles", "type": "application", "needadmin": False }, "36": { "id": "36", "method": "update,read", "permission": "security:roles", "type": "application", "needadmin": True }, "72": { "id": "72", "method": "create,read", "permission": "security:userssetpw", "type": "application", "needadmin": True }, "38": { "id": "38", "method": "create,read", "permission": "security:users", "type": "application", "needadmin": True }, "41": { "id": "41", "method": "delete,read", "permission": "security:users", "type": "application", "needadmin": True }, "39": { "id": "39", "method": "read", "permission": "security:users", "type": "application", "needadmin": False }, "40": { "id": "40", "method": "update,read", "permission": "security:users", "type": "application", "needadmin": True }, "51": { "id": "51", "method": "delete,read", "permission": "nexus:wastebasket", "type": "application", "needadmin": False }, "50": { "id": "50", "method": "read", "permission": "nexus:wastebasket", "type": "application", "needadmin": False }, "wonderland-all": { "id": "wonderland-all", "method": "*", "permission": "nexus:wonderland", "type": "application", "needadmin": False }, "yum-alias-read": { "id": "yum-alias-read", "method": "read", "permission": "nexus:yumAlias", "type": "application", "needadmin": False }, "yum-alias-create-read": { "id": "yum-alias-create-read", "method": "create,update,read", "permission": "nexus:yumAlias", "type": "application", "needadmin": False }, "yum-repository-read": { "id": "yum-repository-read", "method": "read", "permission": "nexus:yumVersionedRepositories", "type": "application", "needadmin": False } } def getBuiltinRoles(privmap): return { "analytics": { "groupName": "analytics", "description": "Gives access to Analytics", "privileges": [ privmap["analytics-all"] ], "roles": [], "admin": False, "builtin": True }, "atlas": { "groupName": "atlas", "description": "Gives access to Atlas support tools", "privileges": [ privmap["atlas-all"] ], "roles": [], "admin": False, "builtin": True }, "metrics-endpoints": { "groupName": "metrics-endpoints", "description": "Allows access to metrics endpoints.", "privileges": [ privmap["metrics-endpoints"] ], "roles": [], "admin": False, "builtin": True }, "nx-admin": { "groupName": "nx-admin", "description": "Administration role for Nexus", "privileges": [ privmap["1001"], privmap["1000"], privmap["83"] ], "roles": [], "admin": True, "builtin": True }, "anonymous": { "groupName": "anonymous", "description": "Anonymous role for Nexus", "privileges": [ privmap["1"], privmap["57"], privmap["58"], privmap["70"], privmap["74"], privmap["54"] ], "roles": [ "ui-healthcheck-read", "ui-search", "ui-repo-browser", ], "admin": False, "builtin": True }, "nx-apikey-access": { "groupName": "nx-apikey-access", "description": "API-Key Access role for Nexus.", "privileges": [ privmap["83"] ], "roles": [], "admin": False, "builtin": True }, "nx-deployment": { "groupName": "nx-deployment", "description": "Deployment role for Nexus", "privileges": [ privmap["83"] ], "roles": [ "ui-basic", "anonymous", ], "admin": False, "builtin": True }, "nx-developer": { "groupName": "nx-developer", "description": "Developer role for Nexus", "privileges": [], "roles": [ "ui-basic", "nx-deployment", ], "admin": False, "builtin": True }, "nexus-yum-admin": { "groupName": "nexus-yum-admin", "description": "Gives access to read versioned yum repositories and administrate version aliases", "privileges": [ privmap["yum-repository-read"], privmap["yum-alias-create-read"], privmap["yum-alias-read"] ], "roles": [], "admin": False, "builtin": True }, "nexus-yum-user": { "groupName": "nexus-yum-user", "description": "Gives access to read versioned yum repositories", "privileges": [ privmap["yum-repository-read"] ], "roles": [], "admin": False, "builtin": True }, "any-all-view": { "groupName": "any-all-view", "description": "Gives access to view ALL Repositories in Nexus.", "privileges": [], "roles": [], "admin": False, "builtin": True }, "repo-all-full": { "groupName": "repo-all-full", "description": "Gives access to create/read/update/delete ALL content of ALL Maven1 and Maven2 repositories in Nexus.", "privileges": [ privmap["T4"], privmap["T5"], privmap["T6"], privmap["T7"], privmap["T8"], privmap["repository-all"], privmap["T1"], privmap["T2"], privmap["T3"] ], "roles": [], "admin": False, "builtin": True }, "repo-all-read": { "groupName": "repo-all-read", "description": "Gives access to read ALL content of ALL Maven1 and Maven2 repositories in Nexus.", "privileges": [ privmap["repository-all"], privmap["T1"], privmap["T2"] ], "roles": [], "admin": False, "builtin": True }, "maven1-all-view": { "groupName": "maven1-all-view", "description": "Gives access to view ALL Maven1 Repositories in Nexus.", "privileges": [], "roles": [], "admin": False, "builtin": True }, "maven2-all-view": { "groupName": "maven2-all-view", "description": "Gives access to view ALL Maven2 Repositories in Nexus.", "privileges": [], "roles": [], "admin": False, "builtin": True }, "npm-all-full": { "groupName": "npm-all-full", "description": "Gives access to create/read/update/delete ALL content of ALL npm Repositories in Nexus.", "privileges": [ privmap["npm-read"], privmap["npm-create"], privmap["npm-delete"], privmap["npm-update"] ], "roles": [ "npm-all-view", ], "admin": False, "builtin": True }, "npm-all-read": { "groupName": "npm-all-read", "description": "Gives access to read ALL content of ALL npm Repositories in Nexus.", "privileges": [ privmap["npm-read"] ], "roles": [ "npm-all-view", ], "admin": False, "builtin": True }, "npm-all-view": { "groupName": "npm-all-view", "description": "Gives access to view ALL npm Repositories in Nexus.", "privileges": [], "roles": [], "admin": False, "builtin": True }, "nuget-all-full": { "groupName": "nuget-all-full", "description": "Gives access to create/read/update/delete ALL content of ALL NuGet Repositories in Nexus.", "privileges": [ privmap["nuget-read"], privmap["nuget-create"], privmap["nuget-delete"], privmap["nuget-update"] ], "roles": [ "nuget-all-view", ], "admin": False, "builtin": True }, "nuget-all-read": { "groupName": "nuget-all-read", "description": "Gives access to read ALL content of ALL NuGet Repositories in Nexus.", "privileges": [ privmap["nuget-read"] ], "roles": [ "nuget-all-view", ], "admin": False, "builtin": True }, "nuget-all-view": { "groupName": "nuget-all-view", "description": "Gives access to view ALL NuGet Repositories in Nexus.", "privileges": [], "roles": [], "admin": False, "builtin": True }, "repository-any-full": { "groupName": "repository-any-full", "description": "Gives access to create/read/update/delete ALL content of ALL repositories in Nexus.", "privileges": [ privmap["T10"], privmap["T12"], privmap["repository-all"], privmap["T9"], privmap["T11"] ], "roles": [], "admin": False, "builtin": True }, "repository-any-read": { "groupName": "repository-any-read", "description": "Gives access to read ALL content of ALL repositories in Nexus.", "privileges": [ privmap["repository-all"], privmap["T9"] ], "roles": [], "admin": False, "builtin": True }, "rubygems-all-full": { "groupName": "rubygems-all-full", "description": "Gives access to create/read/update/delete ALL content of ALL Rubygems Repositories in Nexus.", "privileges": [ privmap["rubygems-create"], privmap["rubygems-delete"], privmap["rubygems-read"], privmap["rubygems-update"] ], "roles": [ "rubygems-all-view", ], "admin": False, "builtin": True }, "rubygems-all-read": { "groupName": "rubygems-all-read", "description": "Gives access to read ALL content of ALL Rubygems Repositories in Nexus.", "privileges": [ privmap["rubygems-read"] ], "roles": [ "rubygems-all-view", ], "admin": False, "builtin": True }, "rubygems-all-view": { "groupName": "rubygems-all-view", "description": "Gives access to view ALL Rubygems Repositories in Nexus.", "privileges": [], "roles": [], "admin": False, "builtin": True }, "site-all-full": { "groupName": "site-all-full", "description": "Gives access to create/read/update/delete ALL content of ALL Site Repositories in Nexus.", "privileges": [ privmap["site-create"], privmap["site-update"], privmap["site-delete"], privmap["repository-all"], privmap["site-read"] ], "roles": [], "admin": False, "builtin": True }, "site-all-read": { "groupName": "site-all-read", "description": "Gives access to read ALL content of ALL Site Repositories in Nexus.", "privileges": [ privmap["repository-all"], privmap["site-read"] ], "roles": [], "admin": False, "builtin": True }, "site-all-view": { "groupName": "site-all-view", "description": "Gives access to view ALL Site Repositories in Nexus.", "privileges": [], "roles": [], "admin": False, "builtin": True }, "ui-basic": { "groupName": "ui-basic", "description": "Generic privileges for users in the Nexus UI", "privileges": [ privmap["1"], privmap["2"], privmap["64"] ], "roles": [], "admin": False, "builtin": True }, "ui-capabilities-admin": { "groupName": "ui-capabilities-admin", "description": "Gives access to Capabilities Administration screen in Nexus UI", "privileges": [ privmap["capabilities-read"], privmap["capability-types-read"], privmap["14"], privmap["capabilities-update-read"], privmap["6"], privmap["capabilities-delete-read"], privmap["capabilities-create-read"] ], "roles": [], "admin": False, "builtin": True }, "ui-group-admin": { "groupName": "ui-group-admin", "description": "Gives access to the Group Administration screen in Nexus UI", "privileges": [ privmap["13"], privmap["14"], privmap["15"], privmap["repository-all"], privmap["16"], privmap["6"] ], "roles": [ "ui-repo-browser", ], "admin": False, "builtin": True }, "ui-healthcheck-full": { "groupName": "ui-healthcheck-full", "description": "Gives access to view and enable/disable the health check for repositories, along with some additional artifact data", "privileges": [ privmap["nexus-healthcheck-update"] ], "roles": [ "ui-healthcheck-read", ], "admin": False, "builtin": True }, "ui-healthcheck-read": { "groupName": "ui-healthcheck-read", "description": "Gives access to view the health check summary for repositories", "privileges": [ privmap["nexus-healthcheck-summary-read"], privmap["nexus-healthcheck-read"] ], "roles": [], "admin": False, "builtin": True }, "ui-ldap-admin": { "groupName": "ui-ldap-admin", "description": "Gives access to configure the LDAP server used for authentication.", "privileges": [ privmap["ldap-conn-read"], privmap["ldap-user-group-conf-update"], privmap["ldap-user-role-map-create"], privmap["ldap-conn-update"], privmap["ldap-test-auth-conf"], privmap["ldap-user-role-map-update"], privmap["ldap-user-role-map-read"], privmap["ldap-user-role-map-delete"], privmap["ldap-user-group-conf-read"], privmap["ldap-test-user-group-conf"] ], "roles": [ "ui-server-admin", ], "admin": False, "builtin": True }, "ui-logs-config-files": { "groupName": "ui-logs-config-files", "description": "Gives access to the Logs and Config Files screen in Nexus UI", "privileges": [ privmap["42"], privmap["43"] ], "roles": [], "admin": False, "builtin": True }, "ui-plugin-console": { "groupName": "ui-plugin-console", "description": "Gives access to the Plugin Console screen in Nexus UI.", "privileges": [ privmap["plugin-infos-read"] ], "roles": [], "admin": False, "builtin": True }, "ui-privileges-admin": { "groupName": "ui-privileges-admin", "description": "Gives access to the Privilege Administration screen in Nexus UI", "privileges": [ privmap["33"], privmap["46"], privmap["14"], privmap["6"], privmap["80"], privmap["30"], privmap["31"], privmap["32"] ], "roles": [], "admin": False, "builtin": True }, "ui-repository-admin": { "groupName": "ui-repository-admin", "description": "Gives access to the Repository Administration screen in Nexus UI", "privileges": [ privmap["78"], privmap["79"], privmap["repository-all"], privmap["5"], privmap["6"], privmap["7"], privmap["8"], privmap["81"], privmap["82"], privmap["74"], privmap["10"] ], "roles": [ "ui-repo-browser", ], "admin": False, "builtin": True }, "ui-repo-browser": { "groupName": "ui-repo-browser", "description": "Gives access to the Repository Browser screen in Nexus UI", "privileges": [ privmap["55"], privmap["14"], privmap["6"], privmap["browse-remote-repo"] ], "roles": [], "admin": False, "builtin": True }, "ui-repository-targets-admin": { "groupName": "ui-repository-targets-admin", "description": "Gives access to the Repository Target Administration screen in Nexus UI", "privileges": [ privmap["45"], privmap["46"], privmap["47"], privmap["48"], privmap["70"], privmap["74"] ], "roles": [], "admin": False, "builtin": True }, "ui-roles-admin": { "groupName": "ui-roles-admin", "description": "Gives access to the Role Administration screen in Nexus UI", "privileges": [ privmap["34"], privmap["35"], privmap["36"], privmap["37"], privmap["31"] ], "roles": [], "admin": False, "builtin": True }, "ui-routing-admin": { "groupName": "ui-routing-admin", "description": "Gives access to the Routing Administration screen in Nexus UI", "privileges": [ privmap["22"], privmap["23"], privmap["24"], privmap["14"], privmap["25"], privmap["6"] ], "roles": [], "admin": False, "builtin": True }, "ui-scheduled-tasks-admin": { "groupName": "ui-scheduled-tasks-admin", "description": "Gives access to the Scheduled Task Administration screen in Nexus UI", "privileges": [ privmap["68"], privmap["14"], privmap["69"], privmap["26"], privmap["27"], privmap["6"], privmap["28"], privmap["29"], privmap["71"] ], "roles": [], "admin": False, "builtin": True }, "ui-search": { "groupName": "ui-search", "description": "Gives access to the Search screen in Nexus UI", "privileges": [ privmap["17"], privmap["19"], privmap["54"] ], "roles": [], "admin": False, "builtin": True }, "ui-server-admin": { "groupName": "ui-server-admin", "description": "Gives access to the Server Administration screen in Nexus UI", "privileges": [ privmap["3"], privmap["4"], privmap["73"] ], "roles": [], "admin": False, "builtin": True }, "ui-system-feeds": { "groupName": "ui-system-feeds", "description": "Gives access to the System Feeds screen in Nexus UI", "privileges": [ privmap["44"] ], "roles": [], "admin": False, "builtin": True }, "ui-users-admin": { "groupName": "ui-users-admin", "description": "Gives access to the User Administration screen in Nexus UI", "privileges": [ privmap["35"], privmap["38"], privmap["39"], privmap["72"], privmap["40"], privmap["41"], privmap["75"] ], "roles": [], "admin": False, "builtin": True }, "wonderland": { "groupName": "wonderland", "description": "Gives access to Wonderland", "privileges": [ privmap["wonderland-all"] ], "roles": [], "admin": False, "builtin": True } }
def add(x,y): """add two numbers together""" return x + y
# -*- coding: utf-8 -*- """ Created on Thu Aug 10 15:43:09 2017 @author: juherask """ DEBUG_VERBOSITY = 3 COST_EPSILON = 1e-10 CAPACITY_EPSILON = 1e-10 # how many seconds we give to a MIP solver MAX_MIP_SOLVER_RUNTIME = 60*10 # 10m MIP_SOLVER_THREADS = 1 # 0 is automatic (parallel computing) BENCHMARKS_BASEPATH = r"C:\Users\juherask\Dissertation\Phases\Benchmarks" LKH_EXE_PATH = r"C:\Users\juherask\Dissertation\Phases\Selection\solvers\lkh\lkh.exe" LKH_EXACT_DISTANCES_PRECISION_DECIMALS = 1000.0 # of the form 0.123 ACOTSP_EXE_PATH = r"C:\Users\juherask\Dissertation\Phases\Selection\solvers\ACOTSP\acotsp.exe" ACOTSP_EXACT_DISTANCES_PRECISION_DECIMALS = 1000.0 # of the form 0.123
EXT_STANDARD = 1 INT_STANDARD = 2 EXT_HQ = 3 INT_HQ = 4 EXT_HOUSE = 5 INT_HOUSE = 6 EXT_COGHQ = 7 INT_COGHQ = 8 EXT_KS = 9 INT_KS = 10
class MaxAlgorithm: #최대값 알고리즘 def __init__(self, ns): self.nums = ns self.maxNum = 0 self.maxNumIdx = 0 def setMaxIdxAndNum(self): self.maxNum = self.nums[0] self.maxNumIdx = 0 for i, n in enumerate(self.nums): if self.maxNum < n: self.maxNum = n self.maxNumIdx = i def getMaxNum(self): return self.maxNum def getMaxNumIdx(self): return self.maxNumIdx nums = [1, 3, 7, 6, 7, 7, 7, 12, 12, 17] maxAlo = MaxAlgorithm(nums) #nums의 최대값 구하기 maxAlo.setMaxIdxAndNum() maxNum = maxAlo.getMaxNum() #maxNum을 가져와서 17가져오기 print(maxNum)# 17 indexes = [ 0 for i in range(maxNum + 1)] # 최대값보다 하나 큰 인덱스만큼 0으로 리스트 만들기 print(indexes) for n in nums:#nums를 indexes에 넣어주며 갯수만큼 더하는 과정 indexes[n] = indexes[n] + 1 print(indexes) maxAlo = MaxAlgorithm(indexes)#indexes에서의 맥스값 구하기 maxAlo.setMaxIdxAndNum() maxNum = maxAlo.getMaxNum() maxNumIdx = maxAlo.getMaxNumIdx()#그 맥스값의 인덱스 구하기 print(f"maxnum: {maxNum}") print(f"maxnumIdx: {maxNumIdx}") print(f"{maxNumIdx} happened {maxNum} times")
# Basics """ Summary: Dictionary are a list of Key and Value {Key: Value} You can create a key connected to its own definition e.g. {"Bug": "An error in a program that prevents the program from running as expected"} You can also create more keys, separating each key /w a comma. { "Bug": "An error in a program that prevents the program from running as expected", "Loop": The action of doing something over and over again." } """ programming_dictionary = { "Bug": "An error in a program that prevents the program from running as expected.", "Function": "A piece of code that you can easily call over and over again.", } # adding a new item to dictionary programming_dictionary["Item"] = "This is a new Value definition." print(programming_dictionary) # editing an item to dictionary programming_dictionary["Bug"] = "This value has been edited." print(programming_dictionary) # example of retrive code - creating a loop through a dictionary for key in programming_dictionary: print(key) print(programming_dictionary)
# Leo colorizer control file for dart mode. # This file is in the public domain. # Properties for dart mode. properties = { "commentEnd": "*/", "commentStart": "/*", "electricKeys": ":", "indentCloseBrackets": "]}", "indentNextLine": "\\s*(((if|while)\\s*\\(|else\\s*|else\\s+if\\s*\\(|for\\s*\\(.*\\))[^{;]*)", "indentOpenBrackets": "{[", "lineComment": "//", "unalignedCloseBrackets": ")", "unalignedOpenBrackets": "(", "unindentThisLine": "^.*(default:\\s*|case.*:.*)$", "wordBreakChars": ",+-=<>/?^&*", } dart_main_attributes_dict = { # From python.py "default": "null", "digit_re": "", "escape": "\\", "highlight_digits": "true", "ignore_case": "false", "no_word_sep": "", } # Dictionary of attributes dictionaries for dart mode. attributesDictDict = { "dart_main": dart_main_attributes_dict, } # Keywords dict for dart_expression ruleset. dart_main_keywords_dict = { # keywords3 and keywords4. "assertionerror": "keyword4", "badnumberformatexception": "keyword4", "bool": "keyword3", "clock": "keyword4", "closureargumentmismatchexception": "keyword4", "collection": "keyword4", "comparable": "keyword4", "const": "keyword1", "date": "keyword4", "dispatcher": "keyword4", "double": "keyword3", "duration": "keyword4", "emptyqueueexception": "keyword4", "exception": "keyword4", "expect": "keyword4", "expectexception": "keyword4", "fallthrougherror": "keyword4", "false": "literal2", "function": "keyword4", "hashable": "keyword4", "hashmap": "keyword4", "hashset": "keyword4", "illegalaccessexception": "keyword4", "illegalargumentexception": "keyword4", "illegaljsregexpexception": "keyword4", "implements": "keyword1", "indexoutofrangeexception": "keyword4", "int": "keyword3", "integerdivisionbyzeroexception": "keyword4", "is": "keyword1", "isolate": "keyword4", "iterable": "keyword4", "iterator": "keyword4", "linkedhashmap": "keyword4", "list": "keyword4", "map": "keyword4", "match": "keyword4", "math": "keyword4", "new": "keyword1", "nomoreelementsexception": "keyword4", "nosuchmethodexception": "keyword4", "notimplementedexception": "keyword4", "null": "literal2", "nullpointerexception": "keyword4", "num": "keyword3", "object": "keyword4", "objectnotclosureexception": "keyword4", "outofmemoryexception": "keyword4", "pattern": "keyword4", "promise": "keyword4", "proxy": "keyword4", "queue": "keyword4", "receiveport": "keyword4", "regexp": "keyword4", "sendport": "keyword4", ### "set": "keyword4", "stackoverflowexception": "keyword4", "stopwatch": "keyword4", "string": "keyword4", "stringbuffer": "keyword4", "strings": "keyword4", "super": "literal2", "this": "literal2", "timezone": "keyword4", "true": "literal2", "typeerror": "keyword4", "unsupportedoperationexception": "keyword4", "void": "keyword3", "wrongargumentcountexception": "keyword4", # keyword1 "abstract": "keyword1", "assert": "keyword1", "break": "keyword1", "case": "keyword1", "catch": "keyword1", "class": "keyword1", "continue": "keyword1", "default": "keyword1", "do": "keyword1", "else": "keyword1", "extends": "keyword1", "factory": "keyword1", "final": "keyword1", "finally": "keyword1", "for": "keyword1", "get": "keyword1", "if": "keyword1", "import": "keyword1", "in": "keyword1", "interface": "keyword1", "library": "keyword1", "negate": "keyword1", "operator": "keyword1", "return": "keyword1", "set": "keyword1", "source": "keyword1", "static": "keyword1", "switch": "keyword1", "throw": "keyword1", "try": "keyword1", "typedef": "keyword1", "var": "keyword1", "while": "keyword1", } # Dictionary of keywords dictionaries for dart mode. keywordsDictDict = { "dart_main": dart_main_keywords_dict, } # Rules for main ruleset. def dart_rule2(colorer, s, i): return colorer.match_span(s, i, kind="comment3", begin="/**", end="*/", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="",exclude_match=False, no_escape=False, no_line_break=False, no_word_break=False) def dart_rule3(colorer, s, i): return colorer.match_span(s, i, kind="comment1", begin="/*", end="*/", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="",exclude_match=False, no_escape=False, no_line_break=False, no_word_break=False) def dart_rule4(colorer, s, i): return colorer.match_span(s, i, kind="literal1", begin="@\"\"\"", end="\"\"\"", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="",exclude_match=False, no_escape=False, no_line_break=False, no_word_break=False) def dart_rule5(colorer, s, i): return colorer.match_span(s, i, kind="literal1", begin="@'''", end="'''", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="",exclude_match=False, no_escape=False, no_line_break=False, no_word_break=False) def dart_rule6(colorer, s, i): return colorer.match_span(s, i, kind="literal1", begin="@\"", end="\"", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="",exclude_match=False, no_escape=False, no_line_break=True, no_word_break=False) def dart_rule7(colorer, s, i): return colorer.match_span(s, i, kind="literal1", begin="@'", end="'", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="",exclude_match=False, no_escape=False, no_line_break=True, no_word_break=False) def dart_rule8(colorer, s, i): return colorer.match_span(s, i, kind="literal1", begin="\"\"\"", end="\"\"\"", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="dart::dart_literal1",exclude_match=False, no_escape=False, no_line_break=False, no_word_break=False) def dart_rule9(colorer, s, i): return colorer.match_span(s, i, kind="literal1", begin="'''", end="'''", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="dart::dart_literal1",exclude_match=False, no_escape=False, no_line_break=False, no_word_break=False) def dart_rule10(colorer, s, i): return colorer.match_span(s, i, kind="literal1", begin="\"", end="\"", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="dart::dart_literal1",exclude_match=False, no_escape=False, no_line_break=True, no_word_break=False) def dart_rule11(colorer, s, i): return colorer.match_span(s, i, kind="literal1", begin="'", end="'", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="dart::dart_literal1",exclude_match=False, no_escape=False, no_line_break=True, no_word_break=False) def dart_rule12(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="=", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def dart_rule13(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="!", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def dart_rule14(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq=">=", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def dart_rule15(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="<=", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def dart_rule16(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="+", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def dart_rule17(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="-", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def dart_rule18(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="/", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def dart_rule19(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="*", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def dart_rule20(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq=">", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def dart_rule21(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="<", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def dart_rule22(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="%", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def dart_rule23(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="&", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def dart_rule24(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="|", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def dart_rule25(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="^", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def dart_rule26(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="<<", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def dart_rule27(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq=">>>", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def dart_rule28(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq=">>", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def dart_rule29(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="~/", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def dart_rule30(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq=".", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def dart_rule31(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq=";", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def dart_rule32(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="]", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def dart_rule33(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="[", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def dart_rule34(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="}", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def dart_rule35(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="{", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") # def dart_rule36(colorer, s, i): # return colorer.match_mark_previous(s, i, kind="function", pattern="(", # at_line_start=False, at_whitespace_end=False, at_word_start=False, exclude_match=False) def dart_rule37(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq=")", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def dart_rule38(colorer, s, i): return colorer.match_keywords(s, i) # Rules formerly in expression ruleset. def dart_rule39(colorer, s, i): return colorer.match_seq(s, i, kind="comment2", seq="//-->", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def dart_rule40(colorer, s, i): return colorer.match_eol_span(s, i, kind="comment2", seq="//", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="", exclude_match=False) def dart_rule41(colorer, s, i): return colorer.match_eol_span(s, i, kind="keyword2", seq="#!", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="", exclude_match=False) def dart_rule42(colorer, s, i): return colorer.match_seq(s, i, kind="keyword2", seq="#library", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def dart_rule43(colorer, s, i): return colorer.match_seq(s, i, kind="keyword2", seq="#import", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def dart_rule44(colorer, s, i): return colorer.match_seq(s, i, kind="keyword2", seq="#source", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def dart_rule45(colorer, s, i): return colorer.match_seq(s, i, kind="keyword2", seq="#resource", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def dart_rule46(colorer, s, i): return colorer.match_keywords(s, i) # Rules dict for main ruleset. rulesDict1 = { "#": [dart_rule41,dart_rule42,dart_rule43,dart_rule44,dart_rule45,], "@": [dart_rule4,dart_rule5,dart_rule6,dart_rule7,dart_rule38,], # Added. "/": [dart_rule39,dart_rule40, dart_rule2,dart_rule3,dart_rule18,], # Added. "'": [dart_rule9,dart_rule11,], # Added. '"': [dart_rule8,dart_rule10,], # Added. # "@": [dart_rule46,], # "0": [dart_rule46,], # "1": [dart_rule46,], # "2": [dart_rule46,], # "3": [dart_rule46,], # "4": [dart_rule46,], # "5": [dart_rule46,], # "6": [dart_rule46,], # "7": [dart_rule46,], # "8": [dart_rule46,], # "9": [dart_rule46,], "A": [dart_rule46,], "B": [dart_rule46,], "C": [dart_rule46,], "D": [dart_rule46,], "E": [dart_rule46,], "F": [dart_rule46,], "G": [dart_rule46,], "H": [dart_rule46,], "I": [dart_rule46,], "J": [dart_rule46,], "K": [dart_rule46,], "L": [dart_rule46,], "M": [dart_rule46,], "N": [dart_rule46,], "O": [dart_rule46,], "P": [dart_rule46,], "Q": [dart_rule46,], "R": [dart_rule46,], "S": [dart_rule46,], "T": [dart_rule46,], "U": [dart_rule46,], "V": [dart_rule46,], "W": [dart_rule46,], "X": [dart_rule46,], "Y": [dart_rule46,], "Z": [dart_rule46,], "a": [dart_rule46,], "b": [dart_rule46,], "c": [dart_rule46,], "d": [dart_rule46,], "e": [dart_rule46,], "f": [dart_rule46,], "g": [dart_rule46,], "h": [dart_rule46,], "i": [dart_rule46,], "j": [dart_rule46,], "k": [dart_rule46,], "l": [dart_rule46,], "m": [dart_rule46,], "n": [dart_rule46,], "o": [dart_rule46,], "p": [dart_rule46,], "q": [dart_rule46,], "r": [dart_rule46,], "s": [dart_rule46,], "t": [dart_rule46,], "u": [dart_rule46,], "v": [dart_rule46,], "w": [dart_rule46,], "x": [dart_rule46,], "y": [dart_rule46,], "z": [dart_rule46,], } # x.rulesDictDict for dart mode. rulesDictDict = { "dart_main": rulesDict1, } # Import dict for dart mode. importDict = {}
ACCOUNT_ID = "1234567890" def parameter_arn(region, parameter_name): if parameter_name[0] == "/": parameter_name = parameter_name[1:] return "arn:aws:ssm:{0}:{1}:parameter/{2}".format( region, ACCOUNT_ID, parameter_name )
class Node: def __init__(self, data): self.data = data self.next = None class PilhaListaEncadeada: def __init__(self): self.head = None def isempty(self): if self.head == None: return True else: return False def empilhar(self, data): if self.head == None: self.head = Node(data) else: newnode = Node(data) newnode.next = self.head self.head = newnode def exclui(self): if self.isempty(): return None else: poppednode = self.head self.head = self.head.next poppednode.next = None return poppednode.data def desempilha(self): if self.isempty(): return None else: list = self.head self.head = self.head.next list.next = None return list.data def inicio(self): if self.isempty(): return None else: return self.head.data def imprimir(self): iternode = self.head if self.isempty(): print("Pilha Está Vazia ") else: while (iternode != None): print(iternode.data, "->", end = " ") iternode = iternode.next return Pilha = PilhaListaEncadeada() Pilha.empilhar(1) Pilha.empilhar(2) Pilha.empilhar(3) Pilha.empilhar(4) Pilha.empilhar(5) Pilha.empilhar(6) Pilha.empilhar(7) Pilha.imprimir() print("\nPrimeiro Elemento:", Pilha.inicio()) Pilha.exclui() Pilha.imprimir() print("\nRemovendo o primeiro elemento da pilha....") print("\nAgora o Primeiro Elemento é:", Pilha.inicio()) print("\nDesempilhando o elemento:",Pilha.desempilha()) print("\nA Pilha agora é composta por") Pilha.imprimir()
#!/bin/python # Enter your code here. Read input from STDIN. Print output to STDOUT N = int(raw_input()) n= N w = 'Weird' nw = 'Not Weird' if n % 2 == 1: print(w) elif n % 2 == 0 and (n>=2 and n<5): print(nw) elif n % 2 == 0 and (n>=6 and n<=20): print(w) elif n % 2 == 0 and (n>20): print(nw)
# Sage version information for Python scripts # This file is auto-generated by the sage-update-version script, do not edit! version = '9.3.rc0' date = '2021-03-23' banner = 'SageMath version 9.3.rc0, Release Date: 2021-03-23'
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def __str__(self): return str(self.val) def print_list(head: ListNode): cur = head while cur is not None: print(cur.val, end=' ') cur = cur.next if cur is not None: print('->', end=' ') print() def build_list(values): head = None prev = None for i, v in enumerate(values): if i == 0: head = ListNode(v) prev = head continue cur = ListNode(v) prev.next = cur prev = cur return head class Solution: def swapPairs(self, head: ListNode) -> ListNode: if head is None or head.next is None: return head cur = head next_node = head.next cur.next = next_node.next next_node.next = cur cur.next = Solution().swapPairs(cur.next) return next_node # tests head = build_list([1, 2, 3, 4, 5]) print_list(head) head = Solution().swapPairs(head) print_list(head) head = build_list([]) print_list(head) head = Solution().swapPairs(head) print_list(head) head = build_list([1]) print_list(head) head = Solution().swapPairs(head) print_list(head)
""" Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. Example 1: https://assets.leetcode.com/uploads/2020/11/05/minpath.jpg Input: grid = [[1,3,1],[1,5,1],[4,2,1]] Output: 7 Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum. Example 2: Input: grid = [[1,2,3],[4,5,6]] Output: 12 Constraints: 1. m == grid.length 2. n == grid[i].length 3. 1 <= m, n <= 200 4. 0 <= grid[i][j] <= 100 """ class Solution: def minPathSum(self, grid) -> int: m, n = len(grid), len(grid[0]) for i in range(m): for j in range(n): if i == 0 and j == 0: pass elif i == 0: grid[i][j] += grid[0][j-1] elif j == 0: grid[i][j] += grid[i-1][0] else: grid[i][j] += min(grid[i-1][j], grid[i][j-1]) return grid[-1][-1]
REDFIN_TABLE_SCHEMA = { 'SCHEMA': { 'SALE_TYPE': 'VARCHAR(50)', 'SOLD_DATE': 'DATE', 'PROPERTY_TYPE': 'VARCHAR(50)', 'ADDRESS': 'VARCHAR(100) NOT NULL', 'CITY': 'VARCHAR(50) NOT NULL', 'STATE': 'VARCHAR(50) NOT NULL', 'ZIPCODE': 'BIGINT', 'PRICE': 'BIGINT', 'BEDS': 'BIGINT', 'BATHS': 'DOUBLE PRECISION', 'SQFT': 'BIGINT', 'LOT_SIZE': 'BIGINT', 'YEAR_BUILT': 'BIGINT', 'DAYS_ON_MARKET': 'BIGINT', 'DOLLAR_PER_SQFT': 'BIGINT', 'HOA_MONTHLY': 'BIGINT', 'STATUS': 'VARCHAR(50)', 'URL': 'VARCHAR(100)', 'MLS_NUM': 'VARCHAR(50)', 'LATITUDE': 'DOUBLE PRECISION', 'LONGITUDE': 'DOUBLE PRECISION'}, 'PRIMARY_KEY': 'ADDRESS, CITY, STATE, ZIPCODE', 'POSITION': ['SALE_TYPE', 'SOLD_DATE', 'PROPERTY_TYPE', 'ADDRESS', 'CITY', 'STATE', 'ZIPCODE', 'PRICE', 'BEDS', 'BATHS', 'SQFT', 'LOT_SIZE', 'YEAR_BUILT', 'DAYS_ON_MARKET', 'DOLLAR_PER_SQFT', 'HOA_MONTHLY', 'STATUS', 'URL', 'MLS_NUM', 'LATITUDE', 'LONGITUDE'] }
# Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, crie duas listas extras que vão conter apenas os valores pares e os valores ímpares digitados, respectivamente. Ao final, mostre o conteúdo das três listas geradas. lista = list() pares = list() impares = list() while True: numero = int(input('Digite um valor: ')) lista.append(numero) if numero != 0: if numero % 2 == 0: pares.append(numero) else: impares.append(numero) continuar = ' ' while continuar not in 'SN': continuar = str(input('Quer continuar? [S/N]: ')).strip().upper()[0] if continuar in 'N': break print(f'Os valores digitados foram: {lista}') print(f'Os valores pares foram: {pares}') print(f'Os ímpares foram: {impares}')
message = 'My name is ' 'Tom' print(message)
list1 = ["apple", "banana", "cherry"] list2 = list1.copy() print(list2) list3 = list(list1) print(list3) list4 = list('T am a list') print(list4) # join 2 lists list5 = list1 + list4 print(list5) for x in list4: list1.append(x) print(list1) list2.extend(list4) print(list2) # list constructor list7 = list(("apple", "banana", "cherry")) # note the double round-brackets print(list7) print(list4.count(' ')) # reverse list list7.reverse() print(list7) # sort list cars = ['Ford', 'BMW', 'Volvo', 'Kia', 'Hyundai', 'Toyota', 'Honda', 'Mazda', 'Mitsubishi', 'Nissan'] cars.sort() print(cars) cars.sort(key=lambda e: len(e), reverse=True) print(cars)
""" URLify: Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the "true" length of the string. (Note: If implementing in Java, please use a character array so that you can perform this operation in place.) EXAMPLE Input: "Mr 3ohn Smith" Output: "Mr%203ohn%20Smith" """ def urlify(usr_str): return str(usr_str).replace(' ', '%20') # inp_str = input("Enter String \n") print(urlify(input("Enter String \n")))
r""" ``scanInfo`` --- Scan information ==================================== .. code-block:: python import gempython.vfatqc.utils.scanInfo Documentation ------------- """ #default values for the algorithm to update the trim values in the iterative trimmer sigmaOffsetDefault=0 highNoiseCutDefault=63 highTrimCutoffDefault=50 highTrimWeightDefault=1.5
class SessionStorage: """Class to save data into session section organized by section_id.""" def __init__(self, session): self.session = session def set(self, section_id, key, value): """Set data to session section.""" session_part = self.session.get(section_id, {}) session_part[key] = value self.session[section_id] = session_part def get(self, section_id, key, default=None): """Get data from session section.""" session_part = self.session.get(section_id, {}) return session_part.get(key, default) def clear(self, section_id): """Clear session section.""" try: del self.session[section_id] self.session.modified = True except KeyError: pass # It is ok, value is already cleared.
_MODELS = dict() def register(fn): global _MODELS _MODELS[fn.__name__] = fn return fn def get_model(args=None): if args.model is None: return _MODELS return _MODELS[args.model](args.num_classes)
Izhikevich = Neuron( parameters= { 'a': Array(value=0.02, dtype=np.float32), 'b': Array(value=0.2), 'c': Value(value=-65.), 'd': Value(value=-2.), 'VT': Value(value=30.), }, equations = { 'v': Array(eq="dv/dt = 0.04 * v^2 + 5.0 * v + 140.0 - u + I + ge - gi", value=0.0, method='midpoint'), 'u': Array( eq="du/dt = a * (b * v - u)", value=0.0, method='midpoint', min=0.0, max=100., ), 'ge': Array(eq=None, value=0.0, during_refractory=False), 'gi': Array(eq="tau*dgi/dt=-gi", during_refractory=False), }, update= ['v', 'u'], update2 = ['v', 'u', 'ge', 'gi'], spike = "v > VT", reset = ["v = c", "u += d"], refractory = None, # the default, or 5.0, or "tau_ref", name = "Izhikevich", description = """ Some text describing what the neuron does, equations that can be parsed for the report, etc. """ ) default_spiking_synapse = Synapse( psp = "w", operator = "sum" # optional ) STDP = Synapse( parameters = { 'tau_plus': Value(value=20.), 'tau_minus': Array(value=20.), # one per post neuron 'tau': Matrix(value = 10.0) # one per synapse }, equations = { 'x': Matrix(eq="tau_plus * dx/dt = -x", method="event-driven"), 'y': Matrix(eq="tau_minus * dy/dt = -y", method="event-driven"), }, transmit = "w", on_pre = [ "x +=1 ", "w +=y ", ], on_post = [ "y +=1", "w -=x", ], name = "STDP", description= """ Spike timing dependent plasticity """ ) # Create the network net = Network(dt=0.1) # Add a population pop = net.add(10, Izhikevich) print(pop.a) pop.a = np.linspace(1.0, 10.0, pop.size) print(pop.a) # Connect the population with itself proj = net.connect(pre=pop, post=pop, target=pop.ge, synapse=default_spiking_synapse) proj.fill(w=1.0, d=5.0) # default is a single weight for the whole population, not learnable proj.fill(w=1.0, d=5.0, connector=Dense(self_connection=False), format='lil') proj.fill(w=Uniform(0.0, 1.0), d=5.0, connector=Sparse(p=0.1)) proj.fill(w=1.0, d=5.0, connector=One2One()) proj.fill(w=np.ones((pop.size, pop.size)), d=0.0) # Monitor net.monitor([pop.v, proj.w]) # Compile the network net.compile(backend='openmp') # single, openmp, mpi, cuda, etc # Simulate net.simulate(1000, monitor=True) # Retrieve the simulated data data = net.recorded()
# Licensed under a 3-clause BSD style license - see LICENSE.rst """Gammapy integration and system tests. This package can be used for tests that involved several Gammapy sub-packages, or that don't fit anywhere else. """
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # 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. # # NOTE: This class is auto generated by the jdcloud code generator program. class Pod(object): def __init__(self, podId=None, name=None, description=None, az=None, hostname=None, instanceType=None, restartPolicy=None, terminationGracePeriodSeconds=None, vpcId=None, subnetId=None, privateIpAddress=None, dnsConfig=None, logConfig=None, hostAliases=None, volumes=None, containers=None, podStatus=None, elasticIp=None, primaryNetworkInterface=None, tags=None, charge=None, createTime=None): """ :param podId: (Optional) pod ID :param name: (Optional) pod 名称 :param description: (Optional) 描述信息,默认为空。 :param az: (Optional) 可用区 :param hostname: (Optional) 主机名 :param instanceType: (Optional) pod 所需的计算资源规格 :param restartPolicy: (Optional) pod重启策略 :param terminationGracePeriodSeconds: (Optional) 优雅关闭的时间 :param vpcId: (Optional) 主网卡所属vpcId :param subnetId: (Optional) 主网卡所属子网的ID :param privateIpAddress: (Optional) 主网卡主IP地址 :param dnsConfig: (Optional) pod内容器的/etc/resolv.conf配置 :param logConfig: (Optional) 容器日志配置信息;默认会在本地分配10MB的存储空间 :param hostAliases: (Optional) pod内容器的/etc/hosts配置 :param volumes: (Optional) 属于Pod的volume列表,提供挂载到containers上。 :param containers: (Optional) pod内的容器信息 :param podStatus: (Optional) pod状态信息 :param elasticIp: (Optional) 主网卡主IP关联的弹性IP规格 :param primaryNetworkInterface: (Optional) 主网卡配置信息 :param tags: (Optional) :param charge: (Optional) 计费配置;如不指定,默认计费类型是后付费-按使用时常付费 :param createTime: (Optional) Pod创建时间 """ self.podId = podId self.name = name self.description = description self.az = az self.hostname = hostname self.instanceType = instanceType self.restartPolicy = restartPolicy self.terminationGracePeriodSeconds = terminationGracePeriodSeconds self.vpcId = vpcId self.subnetId = subnetId self.privateIpAddress = privateIpAddress self.dnsConfig = dnsConfig self.logConfig = logConfig self.hostAliases = hostAliases self.volumes = volumes self.containers = containers self.podStatus = podStatus self.elasticIp = elasticIp self.primaryNetworkInterface = primaryNetworkInterface self.tags = tags self.charge = charge self.createTime = createTime
reta1 = float(input('comprimento 1: ')) reta2 = float(input('comprimento 2: ')) reta3 = float(input('comprimento 3: ')) if (reta1 < reta2 + reta3) and reta1 > abs(reta2 - reta3): if(reta2 < reta1 + reta3) and reta2 > abs(reta1 - reta3): if(reta3 < reta1 + reta2) and reta3 > abs(reta1 - reta2): print('Pode formar um triangulo') print('Esse é um triângulo: ') if reta1 == reta2 == reta3: print('Equilatero') elif reta1 == reta2 or reta1 == reta3 or reta2 == reta3: print('Isósceles') else: print('Escaleno')
# class SVNRepo: # @classmethod # def isBadVersion(cls, id) # # Run unit tests to check whether verison `id` is a bad version # # return true if unit tests passed else false. # You can use SVNRepo.isBadVersion(10) to check whether version 10 is a # bad version. class Solution: """ @param n: An integer @return: An integer which is the first bad version. """ def findFirstBadVersion(self, n): # write your code here start, end = 1, n while start + 1 < end: mid = start + (end - start) // 2 if SVNRepo.isBadVersion(mid): end = mid else: start = mid if SVNRepo.isBadVersion(start): return start return end
#Lists Challenge 9: Basketball Roster Program print("Welcome to the Basketball Roster Program") #Get user input and define our roster roster = [] player = input("\nWho is your point guard: ").title() roster.append(player) player = input("Who is your shooting guard: ").title() roster.append(player) player = input("Who is your small forward: ").title() roster.append(player) player = input("Who is your power forward: ").title() roster.append(player) player = input("Who is your center: ").title() roster.append(player) #Display roster print("\n\tYour starting 5 for the upcoming basketball season") print("\t\tPoint Guard:\t\t" + roster[0]) print("\t\tShooting Guard:\t\t" + roster[1]) print("\t\tSmall Forward:\t\t" + roster[2]) print("\t\tPower Forward:\t\t" + roster[3]) print("\t\tCenter:\t\t\t" + roster[4]) #Remove an injured player injured_player = roster.pop(2) print("\nOh no, " + injured_player + " is injured.") roster_length = len(roster) print("Your roster only has " + str(roster_length) + " players.") #Add a new player added_player = input("Who will take " + injured_player + "'s spot: ").title() roster.insert(2, added_player) #Display roster print("\n\tYour starting 5 for the upcoming basketball season") print("\t\tPoint Guard:\t\t" + roster[0]) print("\t\tShooting Guard:\t\t" + roster[1]) print("\t\tSmall Forward:\t\t" + roster[2]) print("\t\tPower Forward:\t\t" + roster[3]) print("\t\tCenter:\t\t\t" + roster[4]) print("\nGood luck " + roster[2] + " you will do great!") roster_length = len(roster) print("Your roster now has " + str(roster_length) + " players.")
# Helper merge sort function def mergeSort(arr): # Clone the array for the merge later arrClone = arr.clone() mergeSortAux(arr, arrClone, 0, len(arr) - 1) # Actual merge sort def mergeSortAux(arr, arrClone, low, high): if low < high: mid = (low + high) / 2 # Sort left mergeSortAux(arr, arrClone, low, mid) # Sort right mergeSortAux(arr, arrClone, mid + 1, high) # Merge merge(arr, arrClone, low, mid, high) # Merge definition that sorts two sub arrays def merge(arr, arrClone, low, mid, high): i = low j = mid + 1 # Copy the clone array parts over for k in range(low, high): arrClone[k] = arr[k] for k in range(low, high): if i > mid: arr[k] = arrClone[j] j += 1 elif j > high: arr[k] = arrClone[i] i += 1 elif arrClone[i] > arrClone[j]: arr[k] = arrClone[j] j += 1 else: arr[k] = arrClone[i] i += 1
""" Exceptions """ class SubFrameError(Exception): """General error.""" pass
valor = [] while True: x = (int(input('Digite um valor: '))) if x not in valor: valor.append(x) print('Prontinho, adicionado com sucesso. :)') else: print('Valor duplicado, não vou adicionar. :(') y = str(input('quer continuar ? S ou N? ')).strip().upper()[0] if y in 'Nn': break print(f'os números cadastrados foram {sorted(valor)}')
# You can comment by putting # in front of a text. #First off we will start off with the humble while loop. #Now notice the syntax: first we declare our variable, #while condition is followed with a colon, #in order to concenate a string with a number #we must turn it into a string as well. #Finally don't forget the incremental counter which will allow us #to actually exit the file!!!! n = 0 while n <= 5: print ("While is now " + str(n)) n = n+1 #Now we will move on to the for loop. #range will give us a collection of numbers. For now, the old fella #will explain the real things later on. #range syntax: range(start, stop, step) for n in range(5): print (n) mySum = 1 for i in range(1, 12, 1): print("i is now " + str(i)) if i == 11: print("Oh snap we are now over 11!") break #Note that it will always stop one step before the stop value in the range. #Also check this little loop out. varA = 200 varB = 100 if type(varA) == str or type(varB) == str: print("string involved") elif varA > varB: print("bigger") elif varA == varB: print("equal") else: print("smaller") #Checkin types, elif statements, elses... What else do you need? #This little snippet is a pretty cool one. #You can find the sum of X and all the numbers before X. #As seen on MIT6.001X Week 1.2 question 3 in while loops! n = 0 X = 10 while X > 0: n += X X -= 1 print (n) #Now how do the same in a for loop?? n = 0 X = 10 for i in range(X, 0, -1): n += i print (n) #Wew so hard!
class DailySchedule: def __init__(self, day_number: int, day_off: bool = False): self.day_number = day_number self.day_off = day_off self.lessons: list[tuple[str, str, str]] = []
my_list = [] print('Введите кол-во элементов массива и его элементы') for a in range(0, int(input())): # t = int(input()) my_list.append(int(input())) my_list.sort() print('my_list =', my_list, 'type: ', type(my_list)) # list check def binary_search(sorted_list, item): low = 0 high = len(sorted_list) - 1 while low <= high: mid = round((low + high) / 2) # print('mid:', mid) guess = sorted_list[mid] if guess == item: return mid if guess > item: high = mid - 1 else: low = mid / 2 return None print('searched_element') searched_element = int(input()) print(binary_search(my_list, searched_element))
class SpaceSequenceEditor: display_channel = None display_mode = None draw_overexposed = None grease_pencil = None overlay_type = None preview_channels = None proxy_render_size = None show_backdrop = None show_frame_indicator = None show_frames = None show_grease_pencil = None show_metadata = None show_safe_areas = None show_safe_center = None show_seconds = None show_separate_color = None show_strip_offset = None use_marker_sync = None view_type = None waveform_draw_type = None def draw_handler_add(self): pass def draw_handler_remove(self): pass
""" 斐波那契数,通常用 F(n) 表示,形成的序列称为斐波那契数列。该数列由 0 和 1 开始,后面的每一项数字都是前面两项数字的和。也就是: F(0) = 0,   F(1) = 1 F(N) = F(N - 1) + F(N - 2), 其中 N > 1. 给定 N,计算 F(N)。   示例 1: 输入:2 输出:1 解释:F(2) = F(1) + F(0) = 1 + 0 = 1. 示例 2: 输入:3 输出:2 解释:F(3) = F(2) + F(1) = 1 + 1 = 2. 示例 3: 输入:4 输出:3 解释:F(4) = F(3) + F(2) = 2 + 1 = 3. """ class Solution: def __init__(self, N: int): self.memo = [0 for _ in range(n + 1)] def fib(self, N: int) -> int: if N <= 0: return 0 elif N == 1: return 1 if memo[N] == 0: memo[N] = self.fib(N - 1) + self.fib(N - 2) return memo[N] def fib2(self, N: int) -> int: if N <= 0: return 0 elif N == 1: return 1 a = [n for n in range(N + 1)] for i in range(2, N+1): a[i] = a[i - 1] + a[i - 2] return a[N] def fib3(self, N: int) -> int: if N <= 1: return N a, b = 0, 1 while N > 1: sum = a + b a = b b = sum N -= 1 return b if __name__ == '__main__': n = 20 memo = [0 for _ in range(n + 1)] solution = Solution(n) result = solution.fib3(n) print(result)
# Write for loops that iterate over the elements of a list without the use of the range # function for the following tasks. # c. Counting how many elements in a list are negative. list = [ -5, 10, 15, -20, -2, 0, -8, 94 ] numNegativeElements = 0 for item in list: if item < 0: numNegativeElements += 1 print("Number of negative elements:", numNegativeElements)
# Letter Phone # https://www.interviewbit.com/problems/letter-phone/ # # Given a digit string, return all possible letter combinations that the number could represent. # # A mapping of digit to letters (just like on the telephone buttons) is given below. # # The digit 0 maps to 0 itself. # The digit 1 maps to 1 itself. # # Input: Digit string "23" # Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. # # Make sure the returned strings are lexicographically sorted. # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # class Solution: MAP = { '0': '0', '1': '1', '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz', } def _letterCombinations(self, i, A, sub): if(i == len(A) - 1): return [sub + char for char in Solution.MAP[A[i]]] res = list() for char in Solution.MAP[A[i]]: res.extend(self._letterCombinations(i + 1, A, sub + char)) return res # @param A : string # @return a list of strings def letterCombinations(self, A): return self._letterCombinations(0, A, '')
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def test_install_extension(lib): lib.cmd('extension install hello') lib.cmd('hello') def test_install_extension_with_github_syntax(lib): lib.cmd('extension install clk-project/hello') lib.cmd('hello') def test_update_extension(lib): lib.cmd('extension install hello') lib.cmd('extension update hello') lib.cmd('hello --update-extension') def test_copy_extension(lib): lib.cmd('extension create someext') lib.cmd('parameter --global-someext set echo test') assert lib.cmd('echo') == 'test' lib.cmd('extension disable someext') assert lib.cmd('echo') == '' lib.cmd('extension copy someext someext2') assert lib.cmd('echo') == 'test' lib.cmd('extension disable someext2') assert lib.cmd('echo') == '' def test_move_extension(lib): lib.cmd('extension create someext') lib.cmd('parameter --global-someext set echo test') assert lib.cmd('echo') == 'test' lib.cmd('extension disable someext') assert lib.cmd('echo') == '' lib.cmd('extension rename someext someext2') assert lib.cmd('echo') == 'test' lib.cmd('extension disable someext2') assert lib.cmd('echo') == '' lib.cmd('extension enable someext') assert lib.cmd('echo') == ''
# Números primos # Escreva uma função que recebe um número e verifica se é ou não um número primo. Para fazer essa verificação, calcule o resto da divisão do número por 2 e depois por todos os números ímpares até o número recebido. Se o resto de uma dessas divisões for igual a zero, o número não é primo. Observe que 0 e 1 não são primos e que 2 é o único número primo que é par (adaptado do Ex. 5.23 livro do Nilo Ney). # Sua função deve retornar True ou False. # Observação: este exercício vai te ajudar nos exercícios 32, 33, 34, 51 e 75 ;) # O nome da sua função deve ser eh_primo. def eh_primo (num): if num < 2 or num > 2 and num % 2 == 0: return False else: i = 3 while i < num: if num % i == 0: return False i += 2 return True
""" Module contains class coordinates Class coordinates represent a pair of coordinates of a single cell on a 10x10 board """ class Coordinates: """ Represents coordinates of a single cell Represents coordinates of a single cell with x and y coordinates where x abs is a top row in range a-j and y abs is leftmost columnt 1-10 """ def __init__(self, x:str, y:int): """ Constructor of the class coordinates :param x: a string of a single letter in range a-b :param y: an integer in range [1-10] """ if all([y>0, y<11]) and x in ['a','b','c','d','e','f','g','h','i','j']: self.x = x self.y = y else: raise Exception('invalid coordinates values') def match(self, coordinates) -> bool: """ check if one object has the same coordinates as another :param coordinates: :return: True or False """ if coordinates.x == self.x and coordinates.y == self.y: return True return False def next_y(self): """ next y coordinate :return: next y value """ if self.y<10: return self.y+1 else: return None # raise Exception('can not go beyond the limit') def prev_y(self): """ perv y coordinate :return: prev y value """ if self.y > 1: return self.y - 1 else: return None # raise Exception('can not go beyond the limit') def next_x(self): """ next x coordinate :return: next x value """ letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] index = letters.index(self.x) if index < 9: return letters[index + 1] else: return None # raise Exception('can not go beyond the limit') def prev_x(self): """ prev x coordinate :return: prev x value """ letters = ['a','b','c','d','e','f','g','h','i','j'] index = letters.index(self.x) if index > 0 : return letters[index-1] else: return None # raise Exception('can not go beyond the limit')
class Producto: def __init__(self, codigo: str, nombre: str, precio: float) -> None: self.codigo = codigo self.nombre = nombre self.precio = precio def __str__(self) -> str: return f'(Código: {self.codigo}, Nombre: {self.nombre}, Precio: {self.precio})'
''' ref: https://www.datacamp.com/community/tutorials/decorators-python ''' def uppercase_decorator(function): def wrapper(): func = function() make_uppercase = func.upper() return make_uppercase return wrapper def say_hi(): return 'hi there' decorate = uppercase_decorator(say_hi) decorate() print(decorate()) print('----------------------------------------------------------------------------') print('----------------------------------------------------------------------------') ''' Here is the decorator annotated as @uppercase_decorator ''' @uppercase_decorator def say_hello(): return 'hello there' print(say_hello()) print('----------------------------------------------------------------------------') print('----------------------------------------------------------------------------') ''' Applying Multiple Decorators to a Single Function ''' def split_string(function): def wrapper(): func = function() splitted_string = func.split() return splitted_string return wrapper ''' Application of decorators is from the bottom up. Had we interchanged the order, we'd have seen an error since lists don't have an upper attribute. The sentence has first been converted to uppercase and then split into a list. ''' @split_string # second applied @uppercase_decorator # first applied def say_hello(): return 'hello there' print(say_hello()) print('----------------------------------------------------------------------------') print('----------------------------------------------------------------------------') ''' Function defination with parameters ''' def decorator_with_arguments(function): def wrapper_accepting_arguments(arg1, arg2): print("Parameters passed to the function are: {0}, {1}".format(arg1,arg2)) function(arg1, arg2) return wrapper_accepting_arguments @decorator_with_arguments def cities(city_one, city_two): print("Cities I love are {0} and {1}".format(city_one, city_two)) cities("Duluth", "Leesburg") print('----------------------------------------------------------------------------') print('----------------------------------------------------------------------------') def a_decorator_passing_arguments(function_to_decorate): def a_wrapper_accepting_arguments(*args,**kwargs): print('The positional arguments are', args) print('The keyword arguments are', kwargs) function_to_decorate(*args, *kwargs) return a_wrapper_accepting_arguments @a_decorator_passing_arguments def function_with_positional_keyword_arguments(param1, param2, service="glue", region='us-east-1'): print("This has both keyword and arguments") print(f'param1: {param1} param2: {param2} service: {service} region: {region}') function_with_positional_keyword_arguments('first-parameter', 'second-parameter') print('----------------------------------------------------------------------------') print('----------------------------------------------------------------------------') function_with_positional_keyword_arguments('first-parameter', 'second-parameter', 's3', 'us-east-2')
''' Given a string s, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation. Example 1: Input: "aacecaaa" Output: "aaacecaaa" Example 2: Input: "abcd" Output: "dcbabcd" ''' # 2018-10-10 # 214. Shortest Palindrome # https://leetcode.com/problems/shortest-palindrome/description/ # 119 / 120 test cases passed. # Time Limit Exceeded class Solution1: def shortestPalindrome(self, s): """ :type s: str :rtype: str """ # 得到每个点为中心的回文子串 len_s = len(s) if not len_s: return "" palindrome_single = [] palindrome_double = [] for i in range(len_s): j = 1 while i - j >= 0 and i + j < len_s: if s[i - j : i + j + 1] == s[i - j : i + j + 1][::-1]: j += 1 else: break d = 1 while i - d >= 0 and i + d < len_s: if s[i - d : i + d + 2] == s[i - d : i + d + 2][::-1]: d += 1 else: break palindrome_single.append(j-1) palindrome_double.append(d-1) # print(palindrome) # print(palindrome_double, palindrome_single) mid = len_s // 2 # 奇数 mark = 0 for i in range(mid, -1, -1): if palindrome_single[i] == i: mark = i break single = "".join(s[mark:][::-1]) + "".join(s[mark+1:]) # 偶数 mark = 0 for i in range(mid, -1, -1): if palindrome_double[i] == i: mark = i break double = "".join(s[mark+2:][::-1]) + "".join(s[mark:]) if len(double) < len(single) and double[:]==double[::-1] and len(double) >= len_s: # len(double) >= len_s for "aaaaa" return double return single class Solution2: def shortestPalindrome(self, s): """ :type s: str :rtype: str """ len_s = len(s) if not len_s: return "" start, max_len = 0, 0 palindrome = [0 for _ in range(len_s)] for i in range(len_s): if i - max_len >= 0 and s[i - max_len : i + 1] == s[i - max_len : i + 1][::-1]: start = i - max_len max_len += 1 if start == 0: palindrome[i] = max_len if i - max_len - 1 >= 0 and s[i - max_len - 1 : i + 1] == s[i - max_len - 1 : i + 1][::-1]: start = i - max_len - 1 max_len += 2 if start == 0: palindrome[i] = max_len max_index = palindrome.index(max(palindrome)) return "".join(s[max_index + 1:][::-1]) + "".join(s[:]) class Solution3: def shortestPalindrome(self, s): """ :type s: str :rtype: str """ r = s[::-1] for i in range(len(s) + 1): if s.startswith(r[i:]): return r[:i] + s s = "abbacd" test = Solution3() res = test.shortestPalindrome(s) print(res)
# Copyright Google Inc. All Rights Reserved. # # Use of this source code is governed by an MIT-style license that can be # found in the LICENSE file at https://angular.io/license """Test utility to extract the "flat_module_metadata" from transitive Angular deps. """ def _extract_flat_module_index(ctx): return [DefaultInfo(files = depset(transitive = [ dep.angular.flat_module_metadata for dep in ctx.attr.deps if hasattr(dep, "angular") ]))] extract_flat_module_index = rule( implementation = _extract_flat_module_index, attrs = { "deps": attr.label_list(), }, )
def calcula_fatorial(numero): """ Calcula o fatorial de um número recursivamente """ if numero == 0: return 1 return numero * calcula_fatorial(numero - 1) def main(): numero = int(input()) fatorial = calcula_fatorial(numero) print(fatorial) main()
MAX_CHAR_GROUP_NAME = 30 MAX_CHAR_CONTEXT_NAME = 30 MAX_CHAR_DEVICE_NAME = 30 MAX_DEVICES = 10 MAX_GROUPS = 10 MAX_CONTEXTS = 10 MAX_ACTIONS = 10 MAX_TRIGGERS = 10 # in seconds INTERVAL_PUB_GROUP_DATA = 120 INTERVAL_ONLINE = 60 STATE_NO_CONNECTION = 1 STATE_CONNECTED_INTERNET = 2 STATE_CONNECTED_NO_INTERNET = 3
# -*- coding: utf-8 -*- """ Created on Fri Sep 25 19:44:16 2020 @author: Ravi """ #Topological Sorting using recursive DFS # {1: [3], 2: [3], 4: [0, 1], 5: [0, 2]} # topological order = [3,1,2,1,0,4,5] # 1->3 # 2->3 # 4->0->1 class Graph: def __init__(self,edges): self.explored = set() self.edges = edges self.graph_dict = {1: [2], 2: [3, 4], 3: [11, 8], 4: [5, 7], 5: [6], 6: [7], 7: [5], 8: [7, 9, 10], 9: [6, 10], 10: [11], 11: [8]}# {1: [3], 2: [3], 4: [0, 1], 5: [0, 2]} self.order = [] # for start,end in self.edges: # if start not in self.graph_dict: # self.graph_dict[start] = [end] # else: # self.graph_dict[start].append(end) # print(self.graph_dict) self.nodes = list(self.graph_dict.keys()) def topological_ordering(self): for i in self.nodes: if i not in self.explored: self.order.append(i) self.dfs_helper(i) def dfs_helper(self,start): if start not in self.explored: self.explored.add(start) if start in self.graph_dict: for edg in self.graph_dict[start]: if edg not in self.explored: self.order.append(edg) #this sould be commented out for reverse self.dfs_helper(edg) # self.order.append(start) {computes reverse topsort} def print(self): print(self.order) if __name__ == '__main__': routes =[ (5, 2), (5, 0), (4, 0), (4, 1), (2, 3), (3, 1) # (1,None) ] routes2 = [ ('a','c'), ('a','b'), ('b','e'), ('c','e'), ('c','d'), ('d','f'), ('e','f') ] graph = Graph(routes) graph.topological_ordering() graph.print() # graph.Topological_ordering()
def login(client, username, password): payload = dict(username=username, password=password) return client.post('/login', data=payload, follow_redirects=True) def logout(client): return client.get('/logout', follow_redirects=True)
largest_number=None smallest_number=None while True: order=input('Enter a number: ') if order=='done': break try: number=int(order) except Exception as e: print("Invalid Input") continue if largest_number is None: largest_number=number if smallest_number is None: smallest_number=number if largest_number<number: largest_number=number if smallest_number>number: smallest_number=number print(largest_number) print(smallest_number)
# XXXXXXXXXXX class Node: def __init__(self, value, prev_item=None, next_item=None): self.value = value self.prev_item = prev_item self.next_item = next_item class Queue(): def __init__(self, max_size): self.max_size = max_size self.size = 0 self.head = None self.last = None def push_back(self, x): node = Node(value=x) if self.max_size != self.size: if self.size == 0: self.head = node self.last = node else: node.prev_item = self.last self.last.next_item = node self.last = node self.size += 1 else: print('error') def push_front(self, x): node = Node(value=x) if self.max_size != self.size: if self.size == 0: self.head = node self.last = node else: node.next_item = self.head self.head.prev_item = node self.head = node self.size += 1 else: print('error') def pop_back(self): if self.size == 0: print('error') else: x = self.last self.last = self.last.prev_item self.size -= 1 print(x.value) def pop_front(self): if self.size == 0: print('error') else: x = self.head self.head = self.head.next_item self.size -= 1 print(x.value) def get_size(self): print(self.size) def run(): num_com = int(input()) max_size = int(input()) q = Queue(max_size) for _ in range(num_com): command = input().split() if command[0] == 'push_back': q.push_back(command[1]) if command[0] == 'push_front': q.push_front(command[1]) if command[0] == 'pop_back': q.pop_back() if command[0] == 'pop_front': q.pop_front() if __name__ == '__main__': run()
""" Proszę zmodyfikować poprzedni program aby wypisywał znalezione n-ki. """ def print_ns(T, product, n, idx=0, ns=[]): if product == 1 and n == 0: for i in range(len(ns)): print(ns[i], end=" ") print() return 1 if n == 0: return 0 count = 0 for i in range(idx, len(T)): if product % T[i] == 0: new_ns = ns[:] new_ns.append(T[i]) count += print_ns(T, product // T[i], n - 1, i + 1, new_ns) return count T = [4, 6, 1, 7, 8, 3, 8, 9, 4, 21, 6, 12, 9, 6, 2] print(print_ns(T, 16, 3))
#!/usr/bin/python3.6 # created by cicek on 12.10.2018 15:09 digits = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450" d_list = list(digits) i, res = 0, 1 product_array = [] while ((i+12) < len(d_list)): for x in range(0, 13): res *= int(d_list[i+x]) product_array.append(res) res = 1 i += 1 product_array.sort() print(product_array[-1])
# coding=utf-8 # @Time : 2020/2/15 # @Author : Wang Xiaoxiao # @University : Dalian University of Technology # @FileName : SegmentTree.py # @Software : PyCharm # @github : https://github.com/i-love-linux/BasicDataStructure class SegmentTree: """ 时间复杂度分析:n为数组大小 更新set:O(logn) 查询query:O(logn) 空间复杂度分析:n为数组大小 O(n) """ def __init__(self, arr, merger=(lambda a, b: a + b)): self.__data = arr self.__tree = [None for _ in range(len(arr) * 4)] self.__merger = merger # merger是lambda表达式 self.__buildSegmentTree(0, 0, len(arr) - 1) # 创建线段树 # 在treeIndex的位置创建表示区间[l...r]的线段树 def __buildSegmentTree(self, treeIndex, l, r): if l == r: self.__tree[treeIndex] = self.__data[l] return leftTreeIndex = self.__leftChild(treeIndex) rightTreeIndex = self.__rightChild(treeIndex) mid = l + int((r - l) / 2) self.__buildSegmentTree(leftTreeIndex, l, mid) self.__buildSegmentTree(rightTreeIndex, mid + 1, r) self.__tree[treeIndex] = self.__merger(self.__tree[leftTreeIndex], self.__tree[rightTreeIndex]) def getSize(self): return len(self.__data) def get(self, index): if index < 0 or index >= len(self.__data): raise Exception("Index is illegal.") return self.__data[index] # 返回完全二叉树的数组表示中,一个索引所表示的元素的左孩子节点的索引 def __leftChild(self, index): return 2 * index + 1 # 返回完全二叉树的数组表示中,一个索引所表示的元素的右孩子节点的索引 def __rightChild(self, index): return 2 * index + 2 # 返回区间[queryL, queryR]的值 def query(self, queryL, queryR): if queryL < 0 or queryL > len(self.__data) or queryR < 0 or queryR > len(self.__data): raise Exception("Index is illegal.") return self.__query(0, 0, len(self.__data) - 1, queryL, queryR) # 在以treeIndex为根的线段树中[l...r]的范围里,搜索区间[queryL...queryR]的值 def __query(self, treeIndex, l, r, queryL, queryR): if l == queryL and r == queryR: return self.__tree[treeIndex] # treeIndex的节点分为[l...mid]和[mid+1...r]两部分 mid = l + int((r - l) / 2) leftTreeIndex = self.__leftChild(treeIndex) rightTreeIndex = self.__rightChild(treeIndex) if queryL >= mid + 1: return self.__query(rightTreeIndex, mid + 1, r, queryL, queryR) elif queryR <= mid: return self.__query(leftTreeIndex, l, mid, queryL, queryR) leftResult = self.__query(leftTreeIndex, l, mid, queryL, mid) rightResult = self.__query(rightTreeIndex, mid + 1, r, mid + 1, queryR) return self.__merger(leftResult, rightResult) # 将index位置的值,更新为e def set(self, index, e): if index < 0 or index >= len(self.__data): raise Exception("Index is illegal.") self.__data[index] = e self.__set(0, 0, len(self.__data) - 1, index, e) # 在以treeIndex为根的线段树中更新index的值为e def __set(self, treeIndex, l, r, index, e): if l == r: self.__tree[treeIndex] = e return # treeIndex的节点分为[l...mid]和[mid+1...r]两部分 mid = l + int((r - l) / 2) leftTreeIndex = self.__leftChild(treeIndex) rightTreeIndex = self.__rightChild(treeIndex) if index >= mid + 1: self.__set(rightTreeIndex, mid + 1, r, index, e) else: # index < mid + 1 self.__set(leftTreeIndex, l, mid, index, e) self.__tree[treeIndex] = self.__merger(self.__tree[leftTreeIndex], self.__tree[rightTreeIndex]) def __str__(self): res = "[" for i in range(len(self.__tree)): if self.__tree[i] is not None: res += str(self.__tree[i]) else: res += "None" if i != len(self.__tree) - 1: res += ", " res += "]" return res
#crie um programa onde o usuario possa digitar varios valores numericos e cadastre-os em uma #lista. Caso o numero já exista lá dentro, ele nao será adicionado. No final serao exibidos todos #os valores unicos digitados em ordem crescente num = [] while True: n = (int(input('Digite um valor: '))) if n not in num: num.append(n) print('Valor adicionado com sucesso...') else: print('Valor duplicado! Não vou adicionar...') cont = str(input('Quer continuar? [S/N] ')).strip().upper()[0] if cont == 'N': break print('-=-'*15) num.sort() print(f'Voce digitou os valores {num}')
user_schema = { "type": "object", "properties": { "name": {"type": "string"} }, "required": ["name"], "additionalProperties": False } get_users_query_params_schema = { "type": ["object", "null"], "properties": { "page": {"type": "string"} }, "additionalProperties": False }
## =============================================================================== ## Authors: AFRL/RQQA ## Organization: Air Force Research Laboratory, Aerospace Systems Directorate, Power and Control Division ## ## Copyright (c) 2017 Government of the United State of America, as represented by ## the Secretary of the Air Force. No copyright is claimed in the United States under ## Title 17, U.S. Code. All Other Rights Reserved. ## =============================================================================== ## This file was auto-created by LmcpGen. Modifications will be overwritten. class LoiterDirection: VehicleDefault = 0 CounterClockwise = 1 Clockwise = 2 def get_LoiterDirection_str(str): """ Returns a numerical value from a string """ if str == "VehicleDefault": return LoiterDirection.VehicleDefault if str == "CounterClockwise": return LoiterDirection.CounterClockwise if str == "Clockwise": return LoiterDirection.Clockwise def get_LoiterDirection_int(val): """ Returns a string representation from an int """ if val == LoiterDirection.VehicleDefault: return "VehicleDefault" if val == LoiterDirection.CounterClockwise: return "CounterClockwise" if val == LoiterDirection.Clockwise: return "Clockwise" return LoiterDirection.VehicleDefault
#!/usr/bin/env python class HostType: GPCHECK_HOSTTYPE_UNDEFINED = 0 GPCHECK_HOSTTYPE_APPLIANCE = 1 GPCHECK_HOSTTYPE_GENERIC_LINUX = 2 def hosttype_str(type): if type == HostType.GPCHECK_HOSTTYPE_APPLIANCE: return "GPDB Appliance" elif type == HostType.GPCHECK_HOSTTYPE_GENERIC_LINUX: return "Generic Linux Cluster" else: return "Undetected Platform" class sysctl: def __init__(self): self.variables = dict() # dictionary of values self.errormsg = None class omreport: def __init__(self): self.biossetup = dict() # key value pairs self.biossetup_errormsg = None self.bootorder = list() # list of Devices in order of boot self.bootorder_errormsg = None self.remoteaccess = dict() # key value pairs self.remoteaccess_errormsg = None self.vdisks = list() # list of dicts, 1 for each virtual disk self.vdisks_errormsg = None self.controller = dict() # key value pairs self.controller_errormsg = None self.omversion = None self.omversion_errormsg = None self.bios = dict() # key value pairs self.bios_errormsg = None self.alerts = list() # list of alerts... each alert is a dictionary of key value pairs self.alerts_errormsg = None class chkconfig: def __init__(self): self.services = dict() # hash of services, each entry is hash of run levels and boolean value self.xinetd = dict() # hash of services, value is boolean self.errormsg = None class grubconf: def __init__(self): self.serial_declaration = False self.terminal_declaration = False self.ttyS1_declaration = False self.errormsg = None def __str__(self): return "serial_declaration(%s) terminal_declaration(%s) ttyS1_declaration(%s)" % (self.serial_declaration, self.terminal_declaration, self.ttyS1_declaration) class inittab: def __init__(self): self.s1 = False self.defaultRunLevel = None self.errormsg = None def __str__(self): return "s1_declaration(%s) default_run_level(%s)" % (self.s1, self.defaultRunLevel) class uname: def __init__(self): self.output = None self.errormsg = None def __str__(self): return self.output class connectemc: def __init__(self): self.output = None self.errormsg = None def __str__(self): return self.output class securetty: def __init__(self): self.errormsg = None self.data = set() class bcu: def __init__(self): self.firmware = None self.biosversion = None self.errormsg = None def __str__(self): return "firmware_version=%s|biosversion=%s" % (self.firmware, self.biosversion) class ioschedulers: def __init__(self): self.devices = dict() # key is device name value is scheduler name self.errormsg = '' class blockdev: def __init__(self): self.ra = dict() # key is device name value is getra value self.errormsg = '' class rclocal: def __init__(self): self.isexecutable = False # check that /etc/rc.d/rc.local is executable permissions def __str__(self): return "executable(%s)" % self.isexecutable class limitsconf_entry: def __init__(self, domain, type, item, value): self.domain = domain self.type = type self.item = item self.value = value def __str__(self): return "%s %s %s %s" % (self.domain, self.type, self.item, self.value) class limitsconf: def __init__(self): self.lines = list() self.errormsg = None def __str__(self): output = "" for line in self.lines: output = "%s\n%s" % (output, line) return output class GpMount: def __init__(self): self.partition = None self.dir= None self.type = None self.options = set() # mount options def __str__(self): optionstring = '' first = True for k in self.options: if not first: optionstring = "%s," % optionstring thisoption = k optionstring = "%s%s" % (optionstring, thisoption) first = False return "%s on %s type %s (%s)" % (self.partition, self.dir, self.type, optionstring) class ntp: def __init__(self): self.running = False self.hosts = set() self.currentime = None self.errormsg = None def __str__(self): return "(running %s) (time %f) (peers: %s)" % (self.running, self.currenttime, self.hosts) class mounts: def __init__(self): self.entries = dict() # dictionary key=partition value=mount object self.errormsg = None def __str__(self): output = '' for k in self.entries.keys(): output = "%s\n%s" % (output, self.entries[k].__str__()) return output class GenericLinuxOutputData: def __init__(self): self.mounts = None self.uname = None self.blockdev = None self.ioschedulers = None self.sysctl = None self.limitsconf = None self.ntp = None def __str__(self): grc = "============= SYSCTL=========================\n" gre = "============= SYSCTL ERRORMSG================\n" output = "%s%s\n%s%s" % (grc, self.sysctl.variables.__str__(), gre, self.sysctl.errormsg) grc = "============= LIMITS=========================\n" gre = "============= LIMITS ERRORMSG================\n" output = "%s\n%s%s\n%s%s" % (output, grc, self.limitsconf.__str__(), gre, self.limitsconf.errormsg) mnt = "============= MOUNT==========================\n" mte = "============= MOUNT ERRORMSG=================\n" output = "%s\n%s%s\n%s%s" % (output, mnt, self.mounts.__str__(), mte, self.mounts.errormsg) grc = "============= UNAME==========================\n" gre = "============= UNAME ERRORMSG=================\n" output = "%s\n%s%s\n%s%s" % (output, grc, self.uname.__str__(), gre, self.uname.errormsg) grc = "============= IO SCHEDULERS==================\n" gre = "============= IO SCHEDULERS ERRORMSG========\n" output = "%s\n%s%s\n%s%s" % (output, grc, self.ioschedulers.devices.__str__(), gre, self.ioschedulers.errormsg) grc = "============= BLOCKDEV RA ====================\n" gre = "============= BLOCKDEV RA ERRORMSG============\n" output = "%s\n%s%s\n%s%s" % (output, grc, self.blockdev.ra.__str__(), gre, self.blockdev.errormsg) grc = "============= NTPD ===========================\n" gre = "============= NTPD ERRORMSG===================\n" output = "%s\n%s%s\n%s%s" % (output, grc, self.ntp.__str__(), gre, self.ntp.errormsg) return output class ApplianceOutputData: def __init__(self): self.chkconfig = None self.omreport = None self.grubconf = None self.mounts = None self.inittab = None self.uname = None self.securetty = None self.bcu = None self.blockdev = None self.rclocal = None self.ioschedulers = None self.sysctl = None self.limitsconf = None self.connectemc = None self.ntp = None def __str__(self): ser = "=============SERVICES=======================\n" xin = "=============XINETD =======================\n" err = "=============CHKCONFIG ERRORMSG=============\n" output = "%s%s\n%s%s\n%s%s" % (ser, self.chkconfig.services.__str__(), xin, self.chkconfig.xinetd.__str__(), err, self.chkconfig.errormsg) omr = "=============OMREPORT VERSION ==============\n" ome = "=============OMREPORT VERSION ERRORMSG======\n" output = "%s\n%s%s\n%s%s" % (output, omr, self.omreport.omversion, ome, self.omreport.omversion_errormsg) omr = "=============OMREPORT BIOS==================\n" ome = "=============OMREPORT BIOS ERRORMSG=========\n" output = "%s\n%s%s\n%s%s" % (output, omr, self.omreport.bios.__str__(), ome,self.omreport.bios_errormsg) omr = "=============OMREPORT BIOSSETUP=============\n" ome = "=============OMREPORT BIOSSETUP ERRORMSG====\n" output = "%s\n%s%s\n%s%s" % (output, omr, self.omreport.biossetup.__str__(), ome,self.omreport.biossetup_errormsg) omr = "=============OMREPORT CONTROLLER============\n" ome = "=============OMREPORT CONTROLLER ERRORMSG===\n" output = "%s\n%s%s\n%s%s" % (output, omr, self.omreport.controller.__str__(), ome,self.omreport.controller_errormsg) boo = "=============OMREPORT BOOTORDER=============\n" boe = "=============OMREPORT BOOTORDER ERRORMSG====\n" output = "%s\n%s%s\n%s%s" % (output, boo, self.omreport.bootorder.__str__(), boe, self.omreport.bootorder_errormsg) omr = "=============OMREPORT REMOTEACCESS==========\n" ome = "=============OMREPORT REMOTEACCESS ERRORMSG=\n" output = "%s\n%s%s\n%s%s" % (output, omr, self.omreport.remoteaccess.__str__(), ome,self.omreport.remoteaccess_errormsg) omr = "=============OMREPORT ALERTS==========\n" ome = "=============OMREPORT ALERTS ERRORMSG=\n" output = "%s\n%s%s\n%s%s" % (output, omr, self.omreport.alerts.__str__(), ome,self.omreport.alerts_errormsg) omr = "=============OMREPORT VIRTUAL DISKS=========\n" ome = "=============OMREPORT VIRTUAL DISKS ERRORMSG\n" output = "%s\n%s%s\n%s%s" % (output, omr, self.omreport.vdisks.__str__(), ome,self.omreport.vdisks_errormsg) grc = "============= GRUB.CONF======================\n" gre = "============= GRUB.CONF ERRORMSG=============\n" output = "%s\n%s%s\n%s%s" % (output, grc, self.grubconf.__str__(), gre, self.grubconf.errormsg) grc = "============= SYSCTL=========================\n" gre = "============= SYSCTL ERRORMSG================\n" output = "%s\n%s%s\n%s%s" % (output, grc, self.sysctl.variables.__str__(), gre, self.sysctl.errormsg) grc = "============= LIMITS=========================\n" gre = "============= LIMITS ERRORMSG================\n" output = "%s\n%s%s\n%s%s" % (output, grc, self.limitsconf.__str__(), gre, self.limitsconf.errormsg) mnt = "============= MOUNT==========================\n" mte = "============= MOUNT ERRORMSG=================\n" output = "%s\n%s%s\n%s%s" % (output, mnt, self.mounts.__str__(), mte, self.mounts.errormsg) grc = "============= INITTAB========================\n" gre = "============= INITTAB ERRORMSG===============\n" output = "%s\n%s%s\n%s%s" % (output, grc, self.inittab.__str__(), gre, self.inittab.errormsg) grc = "============= UNAME==========================\n" gre = "============= UNAME ERRORMSG=================\n" output = "%s\n%s%s\n%s%s" % (output, grc, self.uname.__str__(), gre, self.uname.errormsg) grc = "============= CONNECTEMC=====================\n" gre = "============= CONNECtEMC ERRORMSG============\n" output = "%s\n%s%s\n%s%s" % (output, grc, self.connectemc.__str__(), gre, self.connectemc.errormsg) grc = "============= SECURETTY======================\n" gre = "============= SECURETTY ERRORMSG=============\n" output = "%s\n%s%s\n%s%s" % (output, grc, self.securetty.data.__str__(), gre, self.securetty.errormsg) grc = "============= IO SCHEDULERS==================\n" gre = "============= IO SCHEDULERS ERRORMSG========\n" output = "%s\n%s%s\n%s%s" % (output, grc, self.ioschedulers.devices.__str__(), gre, self.ioschedulers.errormsg) grc = "============= BLOCKDEV RA ====================\n" gre = "============= BLOCKDEV RA ERRORMSG============\n" output = "%s\n%s%s\n%s%s" % (output, grc, self.blockdev.ra.__str__(), gre, self.blockdev.errormsg) grc = "============= BCU CNA ========================\n" gre = "============= BCU CNA ERRORMSG================\n" output = "%s\n%s%s\n%s%s" % (output, grc, self.bcu.__str__(), gre, self.bcu.errormsg) grc = "============= /etc/rc.d/rc.local =============\n" output = "%s\n%s%s" % (output, grc, self.rclocal.__str__()) grc = "============= NTPD ===========================\n" gre = "============= NTPD ERRORMSG===================\n" output = "%s\n%s%s\n%s%s" % (output, grc, self.ntp.__str__(), gre, self.ntp.errormsg) return output
true = True false = False abi = [ { "inputs": [], "stateMutability": "nonpayable", "type": "constructor" }, { "stateMutability": "payable", "type": "fallback" }, { "inputs": [], "name": "client_cancellation", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "client_delete_random_index", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "uint256", "name": "i", "type": "uint256" } ], "name": "client_download_MSRI", "outputs": [ { "internalType": "bytes", "name": "", "type": "bytes" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "uint256", "name": "i", "type": "uint256" } ], "name": "client_download_encrypted_keys", "outputs": [ { "internalType": "bytes", "name": "", "type": "bytes" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "client_generate_random_index", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "client_get_RIAlength", "outputs": [ { "internalType": "uint8", "name": "", "type": "uint8" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "client_get_current_RIA_length", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "client_get_update_period", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "bytes", "name": "str", "type": "bytes" } ], "name": "client_register", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "client_registration_check", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address payable", "name": "addr", "type": "address" } ], "name": "contract_transfer_to_relay", "outputs": [], "stateMutability": "payable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "Addr", "type": "address" } ], "name": "getClientFlag", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "addr", "type": "address" } ], "name": "getRIA", "outputs": [ { "internalType": "uint16[]", "name": "", "type": "uint16[]" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "uint16", "name": "i", "type": "uint16" } ], "name": "getRelayFlag", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "getclientNum", "outputs": [ { "internalType": "uint24", "name": "", "type": "uint24" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "uint16", "name": "i", "type": "uint16" } ], "name": "getinfo", "outputs": [ { "internalType": "bytes", "name": "", "type": "bytes" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "getrelayIndex", "outputs": [ { "internalType": "uint16", "name": "", "type": "uint16" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "Addr", "type": "address" }, { "internalType": "bool", "name": "flag", "type": "bool" } ], "name": "modifyClientFlag", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "uint16", "name": "i", "type": "uint16" }, { "internalType": "bool", "name": "flag", "type": "bool" } ], "name": "modifyRelayFlag", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "relay_cancellation", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "uint256", "name": "i", "type": "uint256" } ], "name": "relay_download_clients_public_keys", "outputs": [ { "internalType": "bytes", "name": "", "type": "bytes" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "relay_get_clientlist_length", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "relay_get_upload_period", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "relay_register", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "relay_registration_check", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "bytes", "name": "info", "type": "bytes" }, { "internalType": "uint256", "name": "num", "type": "uint256" }, { "internalType": "bytes[]", "name": "keys", "type": "bytes[]" } ], "name": "relay_upload_SRI_and_keys", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "uint256", "name": "i", "type": "uint256" }, { "internalType": "uint256", "name": "num", "type": "uint256" }, { "internalType": "bytes[]", "name": "keys", "type": "bytes[]" } ], "name": "relay_upload_keys", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "uint8", "name": "num", "type": "uint8" } ], "name": "setRIAlength", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "uint256", "name": "period", "type": "uint256" } ], "name": "setRIAperiod", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "uint256", "name": "period", "type": "uint256" } ], "name": "setSRIperiod", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "stateMutability": "payable", "type": "receive" } ]
# Copyright 2020 The FedLearner Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an 'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # coding: utf-8 # TODO THIS FILE SHOULD BE MERGED WITH fedlearner.common.common # TODO MIND THE SUBTLE DIFFERENCES DUE TO ES COMPATIBILITY WHEN MERGING # YYYY-MM-DD'T'hh:mm:ss.SSSSSSZ _es_datetime_format = 'strict_date_optional_time' RAW_DATA_MAPPINGS = { 'dynamic': True, 'dynamic_templates': [ { 'strings': { 'match_mapping_type': 'string', 'mapping': { 'type': 'keyword' } } } ], 'properties': { 'partition': { 'type': 'short' }, 'application_id': { 'ignore_above': 128, 'type': 'keyword' }, 'event_time': { 'format': _es_datetime_format, 'type': 'date' }, 'process_time': { 'format': _es_datetime_format, 'type': 'date' } } } DATA_JOIN_MAPPINGS = { 'dynamic': True, # for dynamically adding string fields, use keyword to reduce space 'dynamic_templates': [ { 'strings': { 'match_mapping_type': 'string', 'mapping': { 'type': 'keyword' } } } ], 'properties': { 'partition': { 'type': 'short' }, 'joined': { 'type': 'byte' }, 'label': { 'ignore_above': 32, 'type': 'keyword' }, 'type': { 'ignore_above': 32, 'type': 'keyword' }, 'has_click_id': { 'type': 'boolean' }, 'has_example_id': { 'type': 'boolean' }, 'application_id': { 'ignore_above': 128, 'type': 'keyword' }, 'process_time': { 'format': _es_datetime_format, 'type': 'date' }, 'event_time': { 'format': _es_datetime_format, 'type': 'date' } } } METRICS_MAPPINGS = { 'dynamic': True, 'dynamic_templates': [ { 'strings': { 'match_mapping_type': 'string', 'mapping': { 'type': 'keyword' } } } ], 'properties': { 'name': { 'type': 'keyword' }, 'value': { 'type': 'float' }, 'date_time': { 'format': _es_datetime_format, 'type': 'date' }, 'tags': { 'properties': { 'partition': { 'type': 'short' }, 'application_id': { 'ignore_above': 128, 'type': 'keyword' }, 'data_source_name': { 'ignore_above': 128, 'type': 'keyword' }, 'joiner_name': { 'ignore_above': 32, 'type': 'keyword' }, 'role': { 'ignore_above': 32, 'type': 'keyword' }, 'event_time': { 'type': 'date', 'format': _es_datetime_format } } } } } ALIAS_NAME = {'metrics': 'metrics_v2', 'raw_data': 'raw_data', 'data_join': 'data_join'} INDEX_MAP = {'metrics': METRICS_MAPPINGS, 'raw_data': RAW_DATA_MAPPINGS, 'data_join': DATA_JOIN_MAPPINGS} def get_es_template(index_type, shards): assert index_type in ALIAS_NAME alias_name = ALIAS_NAME[index_type] template = {'index_patterns': ['{}-*'.format(alias_name)], 'settings': { 'index': { 'lifecycle': { 'name': 'fedlearner_{}_ilm'.format(index_type), 'rollover_alias': alias_name }, 'codec': 'best_compression', 'routing': { 'allocation': { 'total_shards_per_node': '1' } }, 'refresh_interval': '60s', 'number_of_shards': str(shards), 'number_of_replicas': '1', } }, 'mappings': INDEX_MAP[index_type]} return template
""" uzlib 模块实现了使用 DEFLATE 算法解压缩二进制数据 (常用的 zlib 库和 gzip 文档)。目前不支持压缩。 """ def decompress(data) -> None: """打开一个文件,关联到内建函数open()。所有端口 (用于访问文件系统) 需要支持模式参数,但支持其他参数不同的端口。""" ...
class Stack(): def __init__(self): self.lista = [] def push(self, a): self.lista.append(a) def pop(self): if self.isEmpty(): print('Ação negada, a pilha está vazia') else: return self.lista.pop() def isEmpty(self): return len(self.lista) == 0 def __str__(self): return str(self.lista) pilha = Stack() reversa = Stack() input_data = input('\nDigite qualquer frase: ') input_data = input_data.lower() # Inverte a string lida for i in input_data: pilha.push(i) size = len(input_data) for j in range(size): reversa.push(pilha.pop()) print(f'Reverso = {reversa}') # Testa se a string lida é um palíndromo for i in input_data: pilha.push(i) test = True for k in range(size): if test == False: break else: if pilha.pop() == reversa.pop(): test = True else: test = False if test: print(f'A string "{input_data}" é um palíndromo\n') else: print(f'A string "{input_data}" não é um palíndromo\n')
my_list = list(range(1, 11)) print(my_list) def maxInList(aList): # non-recursion method max_number = aList[0] for i in range(1, len(aList)): if max_number < aList[i]: max_number = aList[i] return max_number def minInList(aList): # non-recursion method min_number = aList[0] for i in range(1, len(aList)): if min_number > aList[i]: min_number = aList[i] return min_number print(maxInList(my_list)) print(minInList(my_list))
#!/usr/bin/env python # # Copyright (c) 2018 10X Genomics, Inc. All rights reserved. # MATRIX_MEM_GB_MULTIPLIER = 2 # TODO reduce this once we're confident about the actual memory bounds NUM_MATRIX_ENTRIES_PER_MEM_GB = 50e6 # Empirical obs: with new CountMatrix setup, take ~ 50 bytes/bc NUM_MATRIX_BARCODES_PER_MEM_GB = 2000000 MIN_MEM_GB = 3 MIN_MEM_GB_NOWHITELIST = 64 GZIP_SUFFIX = '.gz' LZ4_SUFFIX = '.lz4' H5_COMPRESSION_LEVEL = 1 H5_FILETYPE_KEY = 'filetype' H5_FEATURE_REF_ATTR = 'features' H5_BCS_ATTR = 'barcodes' H5_MATRIX_DATA_ATTR = 'data' H5_MATRIX_INDICES_ATTR = 'indices' H5_MATRIX_INDPTR_ATTR = 'indptr' H5_MATRIX_SHAPE_ATTR = 'shape' H5_MATRIX_ATTRS = {H5_MATRIX_DATA_ATTR: 'int32', H5_MATRIX_INDICES_ATTR: 'int64', H5_MATRIX_INDPTR_ATTR: 'int64', H5_MATRIX_SHAPE_ATTR: 'int32'} H5_CHEMISTRY_DESC_KEY = 'chemistry_description' H5_LIBRARY_ID_MAPPING_KEY = 'library_ids' H5_ORIG_GEM_GROUP_MAPPING_KEY = 'original_gem_groups' H5_METADATA_ATTRS = [H5_LIBRARY_ID_MAPPING_KEY, H5_ORIG_GEM_GROUP_MAPPING_KEY, H5_CHEMISTRY_DESC_KEY]
# 8. Write a program that swaps the values of three variables x,y, and z, so that x gets the value # of y, y gets the value of z, and z gets the value of x. x, y, z = 5, 10, 15 x, y, z = y, z, x # The power of Python ;) # print(x, y, z) : 10 15 5
class SomentePares(list): def append(self, inteiro): if not isinstance(inteiro, int): raise TypeError('Somente inteiros') # raise lança uma exceção if inteiro % 2: raise ValueError('Somente Pares') super().append(inteiro) sp = SomentePares() sp.append(10) # Efeitos de uma exceção #Ela serve pra parar o programa def algo(): print('POO com Python') # Por exemplo, posso fazer um if e se aquele if for verdadeiro, eu coloco a exceção raise Exception ('Lançando excecao') print('Depois da exceção') return 'sucesso!' # Se tiver uma função dentro da outra, e na segunda função ter uma exceção e ela for ativada, o resto da primeira função não será executado # COMO REAGIR A EXCEÇÕES # geralmente se utiliza o try... excepet def algo2(): raise Exception('excecao') try: algo2() except: print('Eu peguei uma exceção') print('excutado apos uma exceção') # Nesse codigo acima ele pega qualquer tipo de exceção ''' def divisao(divisor): try: if divisor == 13: raise ValueError('13 Não é legal!') return 10 / divisor except ZeroDivisionError: return 'Divisao por zero' except TypeError: return 'Entre com um valor numerico' except ValueError: print('Não utilize o numero 13') else: print('Nenhuma exceção ocorreu') raise print(divisao(13)) ''' try: raise ValueError('alguma coisa') except ValueError as e: print('Os argumentos da exceção foram', e.args) finally: print('Isso sempre será executado') #Hierarquia de exceções # Quando utiliza except ela vai pegar todas as exceções que ocorrer
vts = list() vts.append(0) vtx = list() total = 0 def dfs(cur, visited:list): global vtx, total if cache[cur] != -1: total += cache[cur] return if not vtx[cur]: if cur == tg + 3: total += 1 return visited = visited.copy() visited.append(cur) for i in vtx[cur]: if not i in visited: dfs(i, visited) while True: try: vts.append(int(input())) except EOFError: break tg = max(vts) vts.append(tg + 3) vts.sort() vtx = [0]*(tg + 4) cache = [-1]*(tg + 4) cnt = len(vts) - 1 for i in range(cnt): vtx[vts[i]] = list() vtx[vts[i]].append(vts[i + 1]) if i + 2 <= cnt and vts[i + 2] - vts[i] <= 3: vtx[vts[i]].append(vts[i+2]) if i + 3 <= cnt and vts[i + 3] - vts[i] <= 3: vtx[vts[i]].append(vts[i+3]) for i in range(cnt + 1): if vtx[cnt - i] == 0: continue total = 0 dfs(cnt - i, list()) cache[cnt - i] = total print(total)
alunos = list() notas = list() c = 0 while True: alunos.append([str(input('Nome: '))]) notas.append([float(input('Nota 1: '))]) notas[c].append(float(input('Nota 2: '))) alunos[c].append((notas[c][0] + notas[c][1]) / 2) c += 1 continuar = str(input('Quer continuar? ')).upper().strip() if continuar == 'N': break print('-=' * 20) print('N° NOME MÉDIA') print('-' * 20) for pos, val in enumerate(range(len(alunos))): print(f'{pos:<8}{alunos[pos][0]:<35}{alunos[pos][1]:>}') print('-' * 20) while True: num = int(input('Montar notas de qual aluno? (999 interrompe): ')) if num == 999: break print(f'Notas de {alunos[num][0]} são {notas[num]}') print('-' * 20)
#!/usr/bin/env prey async def main(): await x("ls -a") cd("..") a = await x("ls") await asyncio.sleep(2)
"""Default configuration Use env var to override """ DEBUG = True SECRET_KEY = "changeme" SQLALCHEMY_DATABASE_URI = "sqlite:////tmp/microbiome_api.db" SQLALCHEMY_TRACK_MODIFICATIONS = False
class Solution: def halvesAreAlike(self, s: str) -> bool: num_vowels=0 num_vowels1=0 split = -( ( -len(s) )//2 ) p1, p2 = s[:split], s[split:] for char in p1: if char in "aeiouAEIOU": num_vowels = num_vowels+1 for char in p2: if char in "aeiouAEIOU": num_vowels1 = num_vowels1+1 return num_vowels== num_vowels1
class BaseValidationError(ValueError): pass class LogInFileNotParsedError(BaseValidationError): pass
# -*- coding: utf-8 -*- class TransitionType(object): def __init__(self, utc_offset, is_dst, abbrev): self.utc_offset = utc_offset self.is_dst = is_dst self.abbrev = abbrev def __repr__(self): return '<TransitionType [{}, {}, {}]>'.format( self.utc_offset, self.is_dst, self.abbrev )
""" 16175. General Election 작성자: xCrypt0r 언어: Python 3 사용 메모리: 29,380 KB 소요 시간: 172 ms 해결 날짜: 2020년 9월 19일 """ def main(): for _ in range(int(input())): N, M = map(int, input().split()) votes = [0] * N for _ in range(M): for i, v in enumerate(map(int, input().split())): votes[i] += v print(votes.index(max(votes)) + 1) if __name__ == '__main__': main()
class SingleLinkedListNode(object): def __init__(self, value, nxt): self.value = value self.next = nxt def __repr__(self): nval = self.next and self.next.value or None return f"[{self.value}:{repr(nval)}]" class SingleLinkedList(object): def __init__(self): self.begin = None self.end = None def push(self, obj): """Appends a new value on the end of the list.""" node = SingleLinkedListNode(obj, None) if self.begin == None: # nothing net self.begin = node self.end = self.begin else: self.end.next = node self.end = node assert self.begin != self.end assert self.end.next == None def pop(self): """Removes the last item and returns it.""" if self.end == None: return None elif self.end == self.begin: node = self.begin self.end = self.begin = None return node.value else: node = self.begin while node.next != self.end: node = node.next assert self.end != node self.end = node return node.next.value def shift(self, obj): """Another name for push.""" def unshift(self): """Removes the first item and returns it.""" def remove(self, obj): """Finds a matching item and removes it from the list.""" def first(self): """Returns a *reference* to the first item, does not remove.""" def last(self): """Returns a reference to the last item, does not remove.""" def count(self): """Counts the number of elements in the list.""" node = self.begin count = 0 while node: count += 1 node = node.next return count def get(self, index): """Get the value at index.""" def dump(self, mark): """Debugging function that dumps the contents of the list."""
""" 0997. Find the Town Judge In a town, there are N people labelled from 1 to N. There is a rumor that one of these people is secretly the town judge. If the town judge exists, then: The town judge trusts nobody. Everybody (except for the town judge) trusts the town judge. There is exactly one person that satisfies properties 1 and 2. You are given trust, an array of pairs trust[i] = [a, b] representing that the person labelled a trusts the person labelled b. If the town judge exists and can be identified, return the label of the town judge. Otherwise, return -1. Example 1: Input: N = 2, trust = [[1,2]] Output: 2 Example 2: Input: N = 3, trust = [[1,3],[2,3]] Output: 3 Example 3: Input: N = 3, trust = [[1,3],[2,3],[3,1]] Output: -1 Example 4: Input: N = 3, trust = [[1,2],[2,3]] Output: -1 Example 5: Input: N = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]] Output: 3 Constraints: 1 <= N <= 1000 0 <= trust.length <= 10^4 trust[i].length == 2 trust[i] are all different trust[i][0] != trust[i][1] 1 <= trust[i][0], trust[i][1] <= N """ class Solution: def findJudge(self, N: int, trust: List[List[int]]) -> int: trusted = [0] * N for a, b in trust: trusted[a - 1] -= 1 trusted[b - 1] += 1 for i in range(N): if trusted[i] == N - 1: return i + 1 return -1
class Solution: def findLonelyPixel(self, picture: List[List[str]]) -> int: """Array. Running time: O(m * n) where m and n are the size of picture. """ m, n = len(picture), len(picture[0]) row, col = [0] * m , [0] * n for i in range(m): for j in range(n): if picture[i][j] == 'B': row[i] += 1 col[j] += 1 res = 0 for i in range(m): for j in range(n): if picture[i][j] == 'B' and row[i] == col[j] == 1: res += 1 return res
#!/usr/bin/env python # coding: utf-8 # In given array find the duplicate odd number . # # Note: There is only one duplicate odd number # # <b> Ex [1,4,6,3,1] should return 1 </b> # In[3]: def dup_odd_num(num): count=0 for i in range(len(num)): if num[i] % 2 != 0: count+=1 if count > 1: return num[i] return False print(dup_odd_num([1,3,2,3])) # In[ ]: def dup_odd_num(num): count=0 dic={} for i in range(len(num)): if num[i] % 2 != 0: dic[0]=count dic[1]=num[i] count+=1 return dic[1] # In[28]: print(dup_odd_num([3,4,6,8,]))
# -*- coding: utf-8 -*- class OcelotError(Exception): """Base for custom ocelot errors""" pass class ZeroProduction(OcelotError): """Reference production exchange has amount of zero""" pass class IdenticalVariables(OcelotError): """The same variable name is used twice""" pass class InvalidMultioutputDataset(OcelotError): pass class OutputDirectoryError(OcelotError): pass class ParameterizationError(OcelotError): pass class UnsupportedDistribution(OcelotError): """Manipulation of this uncertainty type is not supported""" pass class InvalidExchange(OcelotError): """This exchange in invalid in the given system model""" pass class MultipleGlobalDatasets(OcelotError): """Multiple global datasets for the same activity name and reference product are not allowed""" pass class UnparsableFormula(OcelotError): """Formula contains elements that can't be parsed""" pass class InvalidMarketExchange(Exception): """Markets aren't allowed to consume their own reference product""" pass class InvalidMarket(Exception): """Markets can only have one reference product""" pass class UnresolvableActivityLink(OcelotError): """Activity link can't be uniquely resolved to an exchange""" pass class MissingMandatoryProperty(Exception): """Exchange is missing a mandatory property""" pass class OverlappingActivities(OcelotError): """Markets overlap, preventing correct linking""" pass class IdenticalDatasets(OcelotError): """Multiple datasets with the same identifying attributes were found""" pass class OverlappingMarkets(OcelotError): """Markets overlap, preventing correct linking""" pass class InvalidTransformationFunction(OcelotError): """Metadata could not be retrieved for this function""" pass class MissingSupplier(OcelotError): """Input from global or RoW market is needed, but this market doesn't exist""" pass class MissingAlternativeProducer(OcelotError): """Alternative producer for byproduct not found""" pass class MarketGroupError(OcelotError): """Error with market group definition or suppliers""" pass
# -*- coding: utf-8 -*- # ******************************************************* # Copyright (c) VMware, Inc. 2020-2021. All Rights Reserved. # SPDX-License-Identifier: MIT # ******************************************************* # * # * DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT # * WARRANTIES OR CONDITIONS OF ANY KIND, WHETHER ORAL OR WRITTEN, # * EXPRESS OR IMPLIED. THE AUTHOR SPECIFICALLY DISCLAIMS ANY IMPLIED # * WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, # * NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. """Engine fixtures for testing""" IOCS_1 = [{ "id": "j39sbv7", "match_type": "equality", "values": ["127.0.0.1"], "severity": 1, }, { "id": "kfsd982m", "match_type": "equality", "values": ["127.0.0.2"], "severity": 1, }, { "id": "slkf038", "match_type": "equality", "values": ["app.exe"], "severity": 10, }, { "id": "0kdl4uf9", "match_type": "regex", "values": [".*google.*"], "severity": 3, }] IOCS_2 = [{ "id": "s9dlk2m1", "match_type": "query", "values": ["netconn_ipv4:127.0.0.1"], "severity": 2, }] IOCS_3 = [{ "id": "jsoq301n", "match_type": "equality", "values": ["127.0.0.1"], "severity": 1, }, { "id": "ci2js01l", "match_type": "equality", "values": ["127.0.0.2"], "severity": 1, }, { "id": "d83nsmc4", "match_type": "equality", "values": ["app.exe"], "severity": 10, }, { "id": "cj01nsbds", "match_type": "equality", "values": ["127.0.0.3"], "severity": 1, }, { "id": "feh48sk1", "match_type": "equality", "values": ["127.0.0.4"], "severity": 1, }, { "id": "d02kfn63", "match_type": "equality", "values": ["bad.exe"], "severity": 10, }, { "id": "cje828jc", "match_type": "regex", "values": [".*google.*"], "severity": 3, }, { "id": "s9dlk2m1", "match_type": "query", "values": ["netconn_ipv4:127.0.0.1"], "severity": 2, }] IOC_HASH = [{ "id": "j39sbv7", "match_type": "equality", "values": ["405f03534be8b45185695f68deb47d4daf04dcd6df9d351ca6831d3721b1efc4"], "severity": 1, }] IOCS_INVALID = [{ "id": "s9dlk2m1", "match_type": "query", "values": ["netconn_ipv4:127.0.0.1"], "severity": -10, }] UNFINISHED_STATE = { "file_size": 2000000, "file_name": "blort.exe", "os_type": "WINDOWS", "engine_name": "!!REPLACE!!", "time_sent": "2020-01-15T12:00:00" } FINISHED_STATE = { "file_size": 2000000, "file_name": "foobar.exe", "os_type": "WINDOWS", "engine_name": "!!REPLACE!!", "time_sent": "2020-01-14T12:00:00", "time_returned": "2020-01-14T12:05:00" } MESSAGE_VALID = { "iocs": IOCS_1, "engine_name": "TEST_ENGINE", "binary_hash": "0995f71c34f613207bc39ed4fcc1bbbee396a543fa1739656f7ddf70419309fc", "success": True } MESSAGE_VALID_1 = { "iocs": IOCS_2, "engine_name": "TEST_ENGINE", "binary_hash": "0995f71c34f613207bc39ed4fcc1bbbee396a543fa1739656f7ddf70419309fc", "success": True } MESSAGE_VALID_2 = { "iocs": IOCS_3, "engine_name": "TEST_ENGINE", "binary_hash": "0995f71c34f613207bc39ed4fcc1bbbee396a543fa1739656f7ddf70419309fc", "success": True } ENGINE_FAILURE = { "iocs": [], "engine_name": "TEST_ENGINE", "binary_hash": "0995f71c34f613207bc39ed4fcc1bbbee396a543fa1739656f7ddf70419309fc", "success": False } MESSAGE_INVALID = { "INVALID": "Bad schema", "binary_hash": "0995f71c34f613207bc39ed4fcc1bbbee396a543fa1739656f7ddf70419309fc" }
a = int(input()) b = int(input()) count = 0 x = 0 a1 = str(a) b1 = str(b) if len(a1) == len(b1): for i in a1: for j in b1[x::]: if i != j: count += 1 x += 1 break print(count)
valores =[] valores_quadrado =[] for i in range(10): valores.append(int(input("Digite um numero inteiro: "))) for i in valores: valores_quadrado.append(i**2) print("Valores da lista ao quadrado: ",valores_quadrado) print("Soma dos quadrados: ",sum(valores_quadrado))
def str_seems_like_json(txt): for c in txt: if c not in "\r\n\t ": return c == '{' return False def bytes_seems_like_json(binary): for b in binary: if b not in [13, 10, 9, 32]: return b == 123 return False
#!/usr/bin/env python3 # Atcoder ABC 157 # Problem B a = [] for i in range(3): a.append(list(map(int, input().split()))) n = int(input()) for _ in range(n): #b_n roop b = int(input()) for i in range(3): for j in range(3): if b == a[i][j]: a[i][j] = 0 #make a 0 for i in range(3): bingo = False if sum(a[i]) == 0: #横チェック print("Yes") exit() if sum([a[0][i], a[1][i], a[2][i]]) == 0: #縦チェック print("Yes") exit() if sum([a[0][0], a[1][1], a[2][2]]) == 0: #斜めチェック print("Yes") exit() if sum([a[2][0], a[1][1], a[0][2]]) == 0: #逆斜めチェック print("Yes") exit() #n(Yes)=0のとき print("No")
user_features = { "demographic": { "age": 20, "gender": "M", "city": "Taipei", "career": "Software Engineer", }, "is_volunteer": True, "python_experience": 4, "tags": ["youtube", "AI"], "vectors": [0, 0, 0] } article_data = [ { "title": "2021 PyCon TW x PyHug Meetup", "image_url": "https://pbs.twimg.com/media/E_Skh8MVQAUmPHm.jpg", "subtitle": "PyHug 簡介: 歡迎來到 PyHUG。我們是一群活動於新竹周邊的 Python 程式員。 我們會定期舉辦技術討論與程式設計的聚會。非常歡迎你加入我們!", }, { "title": "#7 | FAANG 工作環境跟外面有什麼不一樣?想進入 FAANG 就要聽這集!- Kir Chou", "image_url": "https://i.imgur.com/GrMYBUa.png", "subtitle": "這次邀請到的來賓是正在日本 Google 工作的 Kir 跟我們分享他在兩間 FAANG 工作過的經驗。想知道 Kir 在 FAANG 擔任軟體工程師的時候怎麼使用 Python 以及在公司內部推動重要的專案?另外,聽說他沒有刷題就加入 FAANG?!Wow 懶得刷題的聽眾快來聽,這集聽到賺到!PyCast 終於回歸拉!主持人在今年大會過後忙到被 👻 抓走沒時間錄新節目QQ為了讓 PyCast 再次偉大,邀請 Apple Podcast 的聽眾動動手指給我們五星跟留言建議🙏🏼🙏🏼🙏🏼#faang #japan #swe #makepycastgreatagain", }, { "title": "贊助商 - Berry AI", "image_url": "https://i.imgur.com/ktvzhsu.jpg", "subtitle": "Berry AI 是一間位於台北的 AI 新創,致力於運用電腦視覺技術幫助速食業者蒐集數據,改善現有營運流程。技術團隊由一群充滿熱情的 AI 及軟體工程師組成,分別來自海內外知名學術機構與大型科技公司。此外,我們得到台灣上市公司飛捷科技的注資與支持,該公司擁有多年為大型企業落地工業電腦的經驗,提供穩定的資金來源與客戶關係。如今,Berry AI 已與數間全球 Top-10 速食業者展開合作,業務與團隊都迅速擴張中。欲了解更多訊息,請瀏覽 berry-ai.com。", }, { "title": "他媽的給我買票喔!", "image_url": "https://i.imgur.com/WYiNl3z.png", "subtitle": "公道價八萬一", }]
DEFAULT_SESSION_DURATION = 43200 # 12 hours SANDBOX_SESSION_DURATION = 60 * 60 # 1 hour BASTION_PROFILE_ENV_NAME = 'FIGGY_AWS_PROFILE' AWS_REGIONS = ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'af-south-1', 'ap-east-1', 'ap-east-2', 'ap-northeast-3', 'ap-northeast-2', 'ap-northeast-1', 'ap-southeast-1', 'ap-southeast-2', 'ca-central-1', 'cn-north-1', 'cn-northwest-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-north-1', 'me-south-1', 'sa-east-1', 'us-gov-east-1', 'us-gov-west-1'] AWS_CFG_ACCESS_KEY_ID = 'aws_access_key_id' AWS_CFG_SECRET_KEY = 'aws_secret_access_key' AWS_CFG_TOKEN = 'aws_session_token' AWS_CFG_REGION = 'region' AWS_CFG_OUTPUT = 'output' RESTRICTED_ENV_VARS = ['AWS_ACCESS_KEY_ID', 'AWS_DEFAULT_REGION', 'AWS_PROFILE', 'AWS_SECRET_ACCESS_KEY', 'AWS_SESSION_TOKEN']
# # SOFTWARE HISTORY # # Date Ticket# Engineer Description # ------------ ---------- ----------- -------------------------- # Sep 16, 2016 pmoyer Generated class GetStationsRequest(object): def __init__(self): self.pluginName = None def getPluginName(self): return self.pluginName def setPluginName(self, pluginName): self.pluginName = pluginName
def compute(): ans = sum(1 for i in range(10000) if is_lychrel(i)) return str(ans) def is_lychrel(n): for i in range(50): n += int(str(n)[ : : -1]) if str(n) == str(n)[ : : -1]: return False return True if __name__ == "__main__": print(compute())
# lecture 3.6, slide 2 # bisection search for square root x = 12345 epsilon = 0.01 numGuesses = 0 low = 0.0 high = x ans = (high + low)/2.0 while abs(ans**2 - x) >= epsilon: print('low = ' + str(low) + ' high = ' + str(high) + ' ans = ' + str(ans)) numGuesses += 1 if ans**2 < x: low = ans else: high = ans ans = (high + low)/2.0 print('numGuesses = ' + str(numGuesses)) print(str(ans) + ' is close to square root of ' + str(x))
"""Implementation of Kotlin JS rules.""" load("@io_bazel_rules_kotlin//kotlin/internal:defs.bzl", "KtJsInfo") def kt_js_import_impl(ctx): """Implementation for kt_js_import. Args: ctx: rule context Returns: Providers for the build rule. """ if len(ctx.files.jars) != 1: fail("a single jar should be supplied, multiple jars not supported") jar_file = ctx.files.jars[0] args = ctx.actions.args() args.add("--jar", jar_file) args.add("--out_pattern", "\\.js$") args.add("--out", ctx.outputs.js) args.add("--aux_pattern", "\\.js\\.map$") args.add("--aux", ctx.outputs.js_map) tools, _, input_manifest = ctx.resolve_command(tools = [ctx.attr._importer]) ctx.actions.run( inputs = [jar_file], tools = tools, executable = ctx.executable._importer, outputs = [ ctx.outputs.js, ctx.outputs.js_map, ], arguments = [args], input_manifests = input_manifest, ) return [ DefaultInfo( files = depset([ctx.outputs.js, ctx.outputs.js_map]), ), KtJsInfo( js = ctx.outputs.js, js_map = ctx.outputs.js_map, jar = jar_file, srcjar = ctx.files.srcjar[0], ), ]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Question 010 Source : http://www.pythonchallenge.com/pc/return/bull.html what are you looking at ? len(a[30]) = ? a = [1, 11, 21, 1211, 111221] Solution : http://villemin.gerard.free.fr/Puzzle/SeqComme.htm """ a = ["1"] for i in range(31): # init value value = "" # init temporary variable last_char = "" number_count = 0 chars = list(a[i]) last_char = chars[0] # read all chars for char in chars: if last_char != char: value += str(number_count) + last_char last_char = char number_count = 0 number_count += 1 value += str(number_count) + last_char a.append(value) print(a) print(len(a[30])) # 5808
#!/usr/bin/env python3 # imports go here # # Free Coding session for 2015-03-02 # Written by Matt Warren # class SimpleClass: def main(self): return "HI" def main2(self): return "HELLO AGAIN" if __name__ == '__main__': sc = SimpleClass() assert(sc.main.__name__ == 'main') fn = getattr(sc, 'main') assert(fn() == 'HI') fn = getattr(sc, 'main', sc.main2) assert(fn() == 'HI') fn = getattr(sc, 'main3', sc.main2) assert(fn() == 'HELLO AGAIN') setattr(sc, 'main3', fn) fn = getattr(sc, 'main3', sc.main2) assert(fn() == 'HELLO AGAIN') assert(sc.main3() == 'HELLO AGAIN')
r =int(input("enter the row:")) for i in range(1, r+1): for j in range(1, i+1): print("*", end = " ") print("\n") x = r for j in range(1, r): for i in range(1, x): print("*", end = " ") x = x - 1 print("\n")
app.config.from_envvar('FLASKR_SETTINGS', silent=True) def connect_db(): """Connects to the specific database.""" rv = sqlite3.connect(app.config['DATABASE']) rv.row_factory = sqlite3.Row return rv
# -*- coding: utf-8 -*- """ Project: EverydayWechat-Github Creator: DoubleThunder Create time: 2019-07-12 19:09 Introduction: """
with open("input.txt") as fin: points, folds = [x.splitlines() for x in fin.read().split("\n\n")] points = [tuple(int(x) for x in line.split(",")) for line in points] folds = [x.split()[2].split("=") for x in folds] def p1(points, i): axis, line = folds[i] line = int(line) res = set() if axis == "y": for x, y in points: if y > line: y = line - (y - line) res.add((x, y)) else: for x, y in points: if x > line: x = line - (x - line) res.add((x, y)) return res def p2(points): for i in range(len(folds)): points = p1(points, i) x = max(points)[0] y = max(points, key=lambda p: p[1])[1] grid = [[" " for _ in range(x + 1)] for _ in range(y + 1)] for a, b in points: grid[b][a] = "█" return grid print(len(p1(points, 0))) for thing in p2(points): print("".join(thing))
class Solution: ''' 给定一个字符串 s ,找出 至多 包含 k 个不同字符的最长子串 T。 示例 1: 输入: s = "eceba", k = 2 输出: 3 解释: 则 T 为 "ece",所以长度为 3。 示例 2: 输入: s = "aa", k = 1 输出: 2 解释: 则 T 为 "aa",所以长度为 2。 ''' def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int: ''' i: 添加元素到哈希表 j: 数量达到上限后, 减少哈希表中的元素 ''' if not s or not k: return 0 n = len(s) memo, j, ans = {}, 0, 0 for i in range(n): memo[s[i]] = memo.get(s[i], 0) + 1 while len(memo.keys()) > k: if memo.get(s[j]) - 1 == 0: memo.pop(s[j]) else: memo[s[j]] = memo.get(s[j]) - 1 j=j+1 ans = max(ans, i-j+1) # print(memo, ans, i, j) return ans
n = input('Qual é o seu nome? ') if n == 'Mariana': print('Seu nome é muito bonito!') elif n == 'Maria' or n == 'Pedro' or n == 'Paulo': print('Seu nome é bem comum no Brasil.') else: print('Seu nome é bem normal...') print('Tenha um bom dia, \033[33m{}\033[33m!'.format(n))
SERVIDOR_DESTINO = "BIGSQL" YAML_SCOOP_IMPORT = "sqoop-import" YAML_SCOOP_EXPORT = "sqoop-export" YAML_BIGSQL_EXEC = "bigsql-import" YAML_HDFS_IMPORT = "hdfs-import" YAML_HDFS_EXPORT = "hdfs-export" YAML_PYTHON_SCRIPT = "python-script" YAML_ORIGEM = "origem" YAML_DESTINO = "destino" YAML_TABLE = "tabela" YAML_QUERY = "consulta" YAML_SCRIPT_FINAL = "script_final" YAML_SPLITBY = "chave" YAML_TIPO_TABELA = "tipo_tabela" YAML_QUANDO_EXISTIR = "se_existir" YAML_ACAO_SUBSTITUIR = "substituir" YAML_ACAO_IGNORAR = "ignorar" YAML_ACAO_INCREMENTAR = "incrementar" YAML_ACAO_ERRO = "erro" YAML_ACAO_CARREGAR = "carregar" YAML_REMOVER_TABELA_GERADA = "remover_tabela_gerada" YAML_SERVIDORES_TRANSACIONAIS = "servidores" YAML_SCHEMA = "schema" YAML_LISTA_ARQUIVOS = "arquivos" YAML_LISTA_TABELAS = "tabelas" YAML_ARQUIVO_SCRIPT = "nome_arquivo_script" YAML_ARQUIVO_SAIDA = "nome_arquivo_saida" YAML_SCRIPT_PRE = "script_pre_processamento" YAML_SCRIPT_POS = "script_pos_processamento" YAML_ARQUIVO_ENTRADA = "nome_arquivo_entrada" YAML_ESTRUTURA = "estrutura" YAML_ARQUIVO_ESTRUTURA = "nome_arquivo_estrutura" YAML_CONVERSAO_AUTOMATICA = "converter_tipos_na_stage" YAML_FORMATO_TABELA = "nome_tabela" YAML_FORMATO_SEQUENCIA = "sequencia" YAML_CONFIG = "configuracao" YAML_DIR_LOGS = "diretorio_logs" YAML_DIR_SCRIPTS = "diretorio_scripts" YAML_DIR_SAIDA = "diretorio_saida" YAML_DIR_ENTRADA = "diretorio_entrada" YAML_DIR_ESTRUTURA = "diretorio_estrutura" YAML_DIR_BACKUP = "diretorio_backup" YAML_CONTINUA_ERRO = "continuar_em_erro" YAML_TABELA_CONTROLE = "tabela_controle" YAML_TABELA_CONTROLE_SQOOP = "sqoop.tabela_controle" YAML_TABELA_CONTROLE_BIGSQL = "bigsql.tabela_controle" YAML_WEB_HDFS_HOST = "webhdfs_host" YAML_HDFS_TEMP_DIR = "hdfs_temp_dir" YAML_EXECUTA_EM_ERRO = "executar_em_erro" YAML_MAIL_TO = "reportar" YAML_SEP_COLUNA = "delimitador_coluna" YAML_SEP_LINHA = "delimitador_linha" YAML_CABECALHO = "cabecalho_primeira_linha" YAML_TIPO_ARQUIVO = "tipo_arquivo" #YAML_QUOTATION = "delimitador_texto"
"""1423. Maximum Points You Can Obtain from Cards""" class Solution(object): def maxScore(self, cardPoints, k): """ :type cardPoints: List[int] :type k: int :rtype: int """ points = res = sum(cardPoints[:k]) c = cardPoints[::-1] for i in range(k): points += c[i] - cardPoints[k-i-1] res = max(res, points) return res
{ # Ports for the left-side motors "leftMotorPorts": [0, 1], # Ports for the right-side motors "rightMotorPorts": [2, 3], # NOTE: Inversions of the slaves (i.e. any motor *after* the first on # each side of the drive) are *with respect to their master*. This is # different from the other poject types! # Inversions for the left-side motors "leftMotorsInverted": [False, False], # Inversions for the right side motors "rightMotorsInverted": [False, False], # If your robot has only one encoder, remove all of the right encoder fields # Encoder pulses-per-revolution (*NOT* cycles per revolution!) # This value should be the pulses per revolution *of the wheels*, and so # should take into account gearing between the encoder and the wheels "encoderPPR": 512, # Whether the left encoder is inverted "leftEncoderInverted": False, # Whether the right encoder is inverted: "rightEncoderInverted": False, # The total gear reduction between the motor and the wheels, expressed as # a fraction [motor turns]/[wheel turns] "gearing": 1, # Wheel diameter (in units of your choice - will dictate units of analysis) "wheelDiameter": 0.333, # Your gyro type (one of "NavX", "Pigeon", "ADXRS450", "AnalogGyro", or "None") "gyroType": "None", # Whatever you put into the constructor of your gyro # Could be: # "SPI.Port.kMXP" (MXP SPI port for NavX or ADXRS450), # "I2C.Port.kOnboard" (Onboard I2C port for NavX) # "0" (Pigeon CAN ID or AnalogGyro channel), # "new TalonSRX(3)" (Pigeon on a Talon SRX), # "" (NavX using default SPI, ADXRS450 using onboard CS0, or no gyro) "gyroPort": "", }