content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
PACKAGE = "python-ptrace"
VERSION = "0.9"
WEBSITE = "http://python-ptrace.readthedocs.org/"
LICENSE = "GNU GPL v2"
| package = 'python-ptrace'
version = '0.9'
website = 'http://python-ptrace.readthedocs.org/'
license = 'GNU GPL v2' |
def findmax(items):
if len(items) == 0:
return None
m = items[0]
i = 1
while i < len(items):
if m < items[i]:
m = items[i]
i = i + 1
return m
| def findmax(items):
if len(items) == 0:
return None
m = items[0]
i = 1
while i < len(items):
if m < items[i]:
m = items[i]
i = i + 1
return m |
# -*- coding: utf-8 -*-
"""
Model Map refurbishment_level table
:author: Sergio Aparicio Vegas
:version: 0.2
:date: 29 Nov 2017
"""
__docformat__ = "restructuredtext"
class RefurbishmentLevel():
""" Refurbishment level options """
def __init__(self):
self.__id = 0
self._... | """
Model Map refurbishment_level table
:author: Sergio Aparicio Vegas
:version: 0.2
:date: 29 Nov 2017
"""
__docformat__ = 'restructuredtext'
class Refurbishmentlevel:
""" Refurbishment level options """
def __init__(self):
self.__id = 0
self.__level = ''
def __str__(se... |
#!/usr/bin/python
patch_size = [25, 31, 35]
scale_factor = [1.15, 1.2, 1.3]
num_levels = [4, 8, 10]
max_dist = [35, 40, 45, 50]
fp_runscript = open("/home/kivan/source/cv-stereo/scripts/egomotion_kitti_eval/run_validation_orb2.sh", 'w')
fp_runscript.write("#!/bin/bash\n\n")
cnt = 0
for i in range(len(patch_size)):
... | patch_size = [25, 31, 35]
scale_factor = [1.15, 1.2, 1.3]
num_levels = [4, 8, 10]
max_dist = [35, 40, 45, 50]
fp_runscript = open('/home/kivan/source/cv-stereo/scripts/egomotion_kitti_eval/run_validation_orb2.sh', 'w')
fp_runscript.write('#!/bin/bash\n\n')
cnt = 0
for i in range(len(patch_size)):
for j in range(len... |
"""Automatically generated by oppfest.
To update, run python3 -m script.oppfest
"""
# fmt: off
MQTT = {
"tasmota": [
"tasmota/discovery/#"
]
}
| """Automatically generated by oppfest.
To update, run python3 -m script.oppfest
"""
mqtt = {'tasmota': ['tasmota/discovery/#']} |
class Queue:
def __init__(self, size):
if size <= 0:
raise "Size must be 1 or greater."
self.start = 0
self.end = 0
self.count = 0
self.size = size
self.items = [None] * size
def enqueue(self, data):
if self.count >= self.size:
r... | class Queue:
def __init__(self, size):
if size <= 0:
raise 'Size must be 1 or greater.'
self.start = 0
self.end = 0
self.count = 0
self.size = size
self.items = [None] * size
def enqueue(self, data):
if self.count >= self.size:
ra... |
"""
Zachary Cook
Class representing a lab user.
"""
"""
Class for a user.
"""
class User():
"""
Constructor for the user.
"""
def __init__(self,id,maxSessionTime,accessType="UNAUTHORIZED"):
self.id = id
self.accessType = accessType
self.maxSessionTime = maxSessionTime
"""
Returns the user's id.
"""
de... | """
Zachary Cook
Class representing a lab user.
"""
'\nClass for a user.\n'
class User:
"""
Constructor for the user.
"""
def __init__(self, id, maxSessionTime, accessType='UNAUTHORIZED'):
self.id = id
self.accessType = accessType
self.maxSessionTime = maxSessionTime
"\n\tReturn... |
def dist_whittaker(datamtx, strict=True):
""" returns whittaker distance (manhattan distance with sample normalization) btw rows. This script interfaces with Cogent for adding the extra metric in QIIME in beta_diversity.py
dist(a,b) = 0.5*manhattan distance(ai/A, bi/B) where ai is each element of a, and A... | def dist_whittaker(datamtx, strict=True):
""" returns whittaker distance (manhattan distance with sample normalization) btw rows. This script interfaces with Cogent for adding the extra metric in QIIME in beta_diversity.py
dist(a,b) = 0.5*manhattan distance(ai/A, bi/B) where ai is each element of a, and A ... |
# -----------------------------------------------------------------------------
# Staff Assistance Flow
# -----------------------------------------------------------------------------
staff_assistance_customer_email_inputtext = "xpath=//*[@id='emailInput']"
staff_assistance_company_input ... | staff_assistance_customer_email_inputtext = "xpath=//*[@id='emailInput']"
staff_assistance_company_input = "//*[@id='customerInput']"
staff_assistance_company_dropdown = "xpath=//*[@id='customerInput']/div/div[2]/div"
staff_assistance_company_select_button = "xpath=//button[contains(text(),'Done')]"
staff_assistance_co... |
# ------------------------------
# 187. Repeated DNA Sequences
#
# Description:
# You are given two non-empty linked lists representing two non-negative integers. The most significant digit
# comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
#
# You may a... | class Solution(object):
def find_repeated_dna_sequences(self, s):
"""
:type s: str
:rtype: List[str]
"""
s_len = len(s)
s_dict = {}
res = set()
for i in range(s_len - 9):
if s[i:i + 10] in s_dict:
res.add(s[i:i + 10])
... |
# Python Program To Copy An Image Into Another Files
'''
Function Name : Copy An Image Into Another Files
Function Date : 24 Sep 2020
Function Author : Prasad Dangare
Input : --
Output : --
'''
# Open The File In Binary Modes
f1 = open('new.jpg.png', 'rb')
f2 = open('new... | """
Function Name : Copy An Image Into Another Files
Function Date : 24 Sep 2020
Function Author : Prasad Dangare
Input : --
Output : --
"""
f1 = open('new.jpg.png', 'rb')
f2 = open('neww.jpg.jpg', 'wb')
bytes = f1.read()
f2.write(bytes)
f1.close()
f2.close() |
# Oefening: Vraag de geboortedatum van de gebruiker en zeg de leeftijd.
huidig_jaar = 2017
huidige_maand = 10
huidige_dag = 24
jaar = int(input("In welk jaar ben je geboren? "))
maand = int(input("En in welke maand? (getal) "))
# De dag moeten we pas weten als de geboortemaand deze maand is!
# Je kan het hier nat... | huidig_jaar = 2017
huidige_maand = 10
huidige_dag = 24
jaar = int(input('In welk jaar ben je geboren? '))
maand = int(input('En in welke maand? (getal) '))
leeftijd = huidig_jaar - jaar
if maand > huidige_maand:
leeftijd -= 1
elif maand == huidige_maand:
dag = int(input('En welke dag? (getal) '))
if dag > h... |
# 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
# dist... | class Networkapimixin(object):
def peer_list(self):
""" GET /network/peers
Use the Network APIs to retrieve information about the network of peer
nodes comprising the blockchain network.
```golang
message PeersMessage {
repeated PeerEndpoint peers = 1;
... |
# Problem for Prof Charnesky's mid term review sheet at:
# https://canvas.umd.umich.edu/courses/522665/pages/midterm-practice?module_item_id=9243802
# 1 Classes and Unit Test question
# Given the following UML, write the class
# Pizza
# toppings : []
# slices : int
# base_cost : float
# price_per_topping : int
# get_to... | class Pizza:
def __init__(self, toppings, slices, base_cost=2.5, price_per_topping=1):
self._toppings = toppings
self._slices = slices
self._base_cost = base_cost
self._price_per_topping = price_per_topping
def get_total_price(self):
return (self._base_cost + self._pric... |
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(self, value):
if self.value:
if value < self.value:
if self.left:
self.left.insert(value)
else:
... | class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(self, value):
if self.value:
if value < self.value:
if self.left:
self.left.insert(value)
else:
... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | acr_resource_provider = 'Microsoft.ContainerRegistry'
acr_resource_type = ACR_RESOURCE_PROVIDER + '/registries'
storage_resource_type = 'Microsoft.Storage/storageAccounts'
webhook_resource_type = ACR_RESOURCE_TYPE + '/webhooks'
webhook_api_version = '2017-06-01-preview'
managed_registry_api_version = '2017-06-01-previe... |
class Settings:
""" All Game Settings """
def __init__(self):
self.screen_width = 1000
self.screen_height = 600
self.bg_color = (180, 255, 255)
self.ship_speed = 1.25
self.ship_limit = 3
self.bullet_speed = 1
self.bullet_width = 3
self.... | class Settings:
""" All Game Settings """
def __init__(self):
self.screen_width = 1000
self.screen_height = 600
self.bg_color = (180, 255, 255)
self.ship_speed = 1.25
self.ship_limit = 3
self.bullet_speed = 1
self.bullet_width = 3
self.bullet_heig... |
total = 0
for num in range(101):
total = total + num
print (total)
| total = 0
for num in range(101):
total = total + num
print(total) |
def totalFruit(self, tree):
count = {}
i = res = 0
for j, v in enumerate(tree):
count[v] = count.get(v, 0) + 1
while len(count) > 2:
count[tree[i]] -= 1
if count[tree[i]] == 0: del count[tree[i]]
i += 1
res = max(res, j - i + 1)
return res
| def total_fruit(self, tree):
count = {}
i = res = 0
for (j, v) in enumerate(tree):
count[v] = count.get(v, 0) + 1
while len(count) > 2:
count[tree[i]] -= 1
if count[tree[i]] == 0:
del count[tree[i]]
i += 1
res = max(res, j - i + 1)
... |
a, b = input().split()
st = ''
num_a = int(a)
num_b = int(b)
if num_a % 2 == 0 :
answer = -num_a
st += str(-num_a)
else :
answer = num_a
st += str(num_a)
if a == b :
if int(a) % 2 == 0 :
print("-", a, "=-", a, sep='')
else :
print(a, "=+", a, sep='')
exit()
while ... | (a, b) = input().split()
st = ''
num_a = int(a)
num_b = int(b)
if num_a % 2 == 0:
answer = -num_a
st += str(-num_a)
else:
answer = num_a
st += str(num_a)
if a == b:
if int(a) % 2 == 0:
print('-', a, '=-', a, sep='')
else:
print(a, '=+', a, sep='')
exit()
while num_a != num_b:... |
result =1
i=1
while i<=100:
result=result*i
i=i+1
pass
print("the factorial is {}".format(result)) | result = 1
i = 1
while i <= 100:
result = result * i
i = i + 1
pass
print('the factorial is {}'.format(result)) |
class TOS(QTextEdit):
tos_signal = pyqtSignal()
error_signal = pyqtSignal(object)
class Plugin(TrustedCoinPlugin):
def __init__(self, parent, config, name):
super().__init__(parent, config, name)
@hook
def on_new_window(self, window):
wallet = window.wallet
if not isinstance(wallet, self.wallet_class):
re... | class Tos(QTextEdit):
tos_signal = pyqt_signal()
error_signal = pyqt_signal(object)
class Plugin(TrustedCoinPlugin):
def __init__(self, parent, config, name):
super().__init__(parent, config, name)
@hook
def on_new_window(self, window):
wallet = window.wallet
if not isinst... |
#
# PySNMP MIB module ZHONE-PHY-SONET-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZHONE-PHY-SONET-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:47:49 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_size_constraint, value_range_constraint, constraints_intersection, single_value_constraint) ... |
### SATISFACTORY RESPONSE
## Not found code
OK = 200
OK_NOCONTENT = 204
### CLIENT ERROR
## Not found code
NOT_FOUND = 404
UNAUTHORIZED = 401
### SERVER ERROR
## Internal server error
INTERNAL_ERROR = 500
| ok = 200
ok_nocontent = 204
not_found = 404
unauthorized = 401
internal_error = 500 |
"""
Time complexity O(n)
"""
# Search for maximum number
l = [2, 4, 5, 1, 80, 5, 99]
maximum = l[0]
for item in l:
if item > maximum:
maximum = item
print(maximum)
| """
Time complexity O(n)
"""
l = [2, 4, 5, 1, 80, 5, 99]
maximum = l[0]
for item in l:
if item > maximum:
maximum = item
print(maximum) |
# DESCRIPTION
# Return the root node of a binary search tree that matches the given preorder traversal.
# It's guaranteed that for the given test cases there is always possible to find a
# binary search tree with the given requirements.
# EXAMPLE
# Input: [8,5,1,7,10,12]
# Output: [8,5,10,1,7,null,12]
# Definition f... | class Solution:
def bst_from_preorder(self, preorder: List[int]) -> TreeNode:
"""
Time: O(N), Must iterate over every element of the list
Space: O(N), max space needed for recursive stack
"""
self.index = 0
return self.bst_build(preorder, float('inf'))
def bst_b... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
## mergesort
class Solution(object):
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.... | class Solution(object):
def sort_list(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
(p, s, f) = (None, head, head)
while f and f.next:
(p, s, f) = (s, s.next, f.next.next)
... |
def find_floor(brackets: str) -> int:
return sum(1 if c == '(' else -1 for c in brackets)
def find_basement_entry(brackets: str) -> int:
return [n + 1 for n in range(len(brackets)) if find_floor(brackets[:n + 1]) == -1][0]
if __name__ == '__main__':
with open('input') as f:
bracket_text = f.read... | def find_floor(brackets: str) -> int:
return sum((1 if c == '(' else -1 for c in brackets))
def find_basement_entry(brackets: str) -> int:
return [n + 1 for n in range(len(brackets)) if find_floor(brackets[:n + 1]) == -1][0]
if __name__ == '__main__':
with open('input') as f:
bracket_text = f.read(... |
result = [
None,
6,
['a', 'b', 'c', {'uu': 5.6, 'oo': [Ellipsis], 'ii': {Ellipsis}}],
{'uu': 5.6, 'oo': [Ellipsis], 'ii': {Ellipsis}},
{'uu': 5.6, 'oo': [Ellipsis], 'ii': {Ellipsis}},
['a', 'b', 'c', {'uu': 5.6, 'oo': [Ellipsis], 'ii': {Ellipsis}}],
None,
6
]
def is_equal(a, b, message... | result = [None, 6, ['a', 'b', 'c', {'uu': 5.6, 'oo': [Ellipsis], 'ii': {Ellipsis}}], {'uu': 5.6, 'oo': [Ellipsis], 'ii': {Ellipsis}}, {'uu': 5.6, 'oo': [Ellipsis], 'ii': {Ellipsis}}, ['a', 'b', 'c', {'uu': 5.6, 'oo': [Ellipsis], 'ii': {Ellipsis}}], None, 6]
def is_equal(a, b, message):
comparable_a = [a[0], a[1], ... |
p1, p2 = map(int, input().split())
m = (p1 + p2) / 2
if m >= 7:
print(f'{m} - Aprovado', end='')
elif m < 5:
print(f'{m} - Reprovado', end='')
else:
print(f'{m} - De Recuperacao', end='')
| (p1, p2) = map(int, input().split())
m = (p1 + p2) / 2
if m >= 7:
print(f'{m} - Aprovado', end='')
elif m < 5:
print(f'{m} - Reprovado', end='')
else:
print(f'{m} - De Recuperacao', end='') |
"""680. Valid Palindrome II
https://leetcode.com/problems/valid-palindrome-ii/
"""
class Solution:
def validPalindrome(self, s: str) -> bool:
def helper(i: int, j: int, flag: bool) -> bool:
while i < j:
if s[i] == s[j]:
i += 1
j -= 1
... | """680. Valid Palindrome II
https://leetcode.com/problems/valid-palindrome-ii/
"""
class Solution:
def valid_palindrome(self, s: str) -> bool:
def helper(i: int, j: int, flag: bool) -> bool:
while i < j:
if s[i] == s[j]:
i += 1
j -= 1
... |
#
# PySNMP MIB module RADIUS-ACCOUNTING-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RADIUS-ACCOUNTING-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:44:47 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, single_value_constraint, value_size_constraint, constraints_intersection) ... |
#Prints the number in matrix form
def print_numbers(number):
for i in range(1,number+1):
for j in range(1, number+1):
print(i,end=" ")
print()
number=int(input("please enter a number: "))
if number%2==0:
print_numbers(number+1)
else:
print_numbers(number-1)
| def print_numbers(number):
for i in range(1, number + 1):
for j in range(1, number + 1):
print(i, end=' ')
print()
number = int(input('please enter a number: '))
if number % 2 == 0:
print_numbers(number + 1)
else:
print_numbers(number - 1) |
class Blackjack():
def __init__(self, cards):
self.cards = cards
def hand(self):
"""makes a list of your card values
Returns:
list: e.g. [1, 12]
"""
deck = {
1: 1,
2: 2,
3: 3,
4: 4,
5: 5,
... | class Blackjack:
def __init__(self, cards):
self.cards = cards
def hand(self):
"""makes a list of your card values
Returns:
list: e.g. [1, 12]
"""
deck = {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10, 'j': 10, 'q': 10, 'k': 10, 'a': 11}
... |
def bar_spec(data):
return {
"config": {
"view": {"continuousWidth": 400, "continuousHeight": 300},
"mark": {"opacity": 0.75}
},
"layer": [
{
"mark": {"type": "bar", "color": "red"},
"encoding": {
"x": {... | def bar_spec(data):
return {'config': {'view': {'continuousWidth': 400, 'continuousHeight': 300}, 'mark': {'opacity': 0.75}}, 'layer': [{'mark': {'type': 'bar', 'color': 'red'}, 'encoding': {'x': {'type': 'nominal', 'field': 'subject'}, 'y': {'type': 'quantitative', 'field': 'percentage of input passed filter'}}}, ... |
#!/usr/bin/env python
#
# Copyright (C) 2017 ShadowMan
#
class FatalError(Exception):
pass
class FrameHeaderParseError(Exception):
pass
class ConnectClosed(Exception):
pass
class RequestError(Exception):
pass
class LoggerWarning(RuntimeWarning):
pass
class DeamonError(Exception):
pass... | class Fatalerror(Exception):
pass
class Frameheaderparseerror(Exception):
pass
class Connectclosed(Exception):
pass
class Requesterror(Exception):
pass
class Loggerwarning(RuntimeWarning):
pass
class Deamonerror(Exception):
pass
class Senddatapackerror(Exception):
pass
class Invalidre... |
#!/usr/bin/env python
#coding: utf-8
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @return a ListNode
def addTwoNumbers(self, l1, l2):
h = ch = ListNode(-1)
n1, n2, c = l1, l2, 0
... | class Listnode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def add_two_numbers(self, l1, l2):
h = ch = list_node(-1)
(n1, n2, c) = (l1, l2, 0)
while n1 or n2:
a = n1.val if n1 else 0
b = n2.val if n2 else 0
... |
def is_uppercase(letter: str):
return True if 65 <= ord(letter) <= 90 else False
def is_lowercase(letter: str):
return True if 97 <= ord(letter) <= 122 else False
def check_same_case(first: str, second: str) -> bool:
if is_uppercase(first) and is_uppercase(second):
return True
if is_lowerca... | def is_uppercase(letter: str):
return True if 65 <= ord(letter) <= 90 else False
def is_lowercase(letter: str):
return True if 97 <= ord(letter) <= 122 else False
def check_same_case(first: str, second: str) -> bool:
if is_uppercase(first) and is_uppercase(second):
return True
if is_lowercase(... |
# ========================= VMWriter CLASS
class VMEncoder(object):
"""
VM encoder for the CompilationEngine of the Jack compiler.
"""
def encodePush(self, segment, index):
"""
Creates VM push command based on the input.
args:
segment: (str) segment to operate on
... | class Vmencoder(object):
"""
VM encoder for the CompilationEngine of the Jack compiler.
"""
def encode_push(self, segment, index):
"""
Creates VM push command based on the input.
args:
segment: (str) segment to operate on
index: (int) index of the desir... |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
listL1, listL... | class Listnode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def add_two_numbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
(list_l1, list_l2) = ('', '')
while l1... |
""" z-matrix writers
"""
def write(syms, key_mat, name_mat, val_dct, mat_delim=' ', setval_sign='='):
""" write a z-matrix to a string
"""
mat_str = matrix_block(syms=syms, key_mat=key_mat, name_mat=name_mat,
delim=mat_delim)
setval_str = setval_block(val_dct=val_dct, setval... | """ z-matrix writers
"""
def write(syms, key_mat, name_mat, val_dct, mat_delim=' ', setval_sign='='):
""" write a z-matrix to a string
"""
mat_str = matrix_block(syms=syms, key_mat=key_mat, name_mat=name_mat, delim=mat_delim)
setval_str = setval_block(val_dct=val_dct, setval_sign=setval_sign)
zma_s... |
n=int(input("enter a number"))
m=int(input("enter a number"))
if n%m==0:
print(n,"is dividible by",m)
else:
print(n,"is not divisible by",m)
if n%2==0:
print(n,"is even")
else:
print(n,"is odd")
| n = int(input('enter a number'))
m = int(input('enter a number'))
if n % m == 0:
print(n, 'is dividible by', m)
else:
print(n, 'is not divisible by', m)
if n % 2 == 0:
print(n, 'is even')
else:
print(n, 'is odd') |
"""Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
"""
class Solution(object):
def addDigits(self, num):
while num >= 10:
num =... | """Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
"""
class Solution(object):
def add_digits(self, num):
while num >= 10:
num ... |
file_extractors = {}
def file_extractor(extension):
"""
This decorator registers functions to be used as extractors.
Only functions decorated with this are considered metadata extractors, and will
be called when the file extension matches the configured one.
:param extension: the extension to ma... | file_extractors = {}
def file_extractor(extension):
"""
This decorator registers functions to be used as extractors.
Only functions decorated with this are considered metadata extractors, and will
be called when the file extension matches the configured one.
:param extension: the extension to mat... |
MAX = 'x'
MIN = 'o'
def get_player(s):
return MAX if len([1 for i in s if i == ' ']) % 2 == 1 else MIN
def next_player(p):
return MAX if p == MIN else MIN
def get_actions(s):
return [i for i in range(9) if s[i] == ' ']
def result(s, a):
player = get_player(s)
s2 = list(s)
s2[a] = player
... | max = 'x'
min = 'o'
def get_player(s):
return MAX if len([1 for i in s if i == ' ']) % 2 == 1 else MIN
def next_player(p):
return MAX if p == MIN else MIN
def get_actions(s):
return [i for i in range(9) if s[i] == ' ']
def result(s, a):
player = get_player(s)
s2 = list(s)
s2[a] = player
... |
# What are the factors of 18?
# factor: an integer which when multiplied with another integer, results in the product 18.
# Hence when 18 is divided by this number, the dividend is an integer and there are no remainders.
num = 18
for i in range(1, num+1):
if num % i == 0:
print(i, end=' ')
| num = 18
for i in range(1, num + 1):
if num % i == 0:
print(i, end=' ') |
def main():
for _ in range(int(input())):
n = int(input())
arr = list(map(int, input().strip().split()))
if n == 1:
print(arr[0])
else:
n += 1
arr.append(1001)
left, right = 0, 1
res = ''
while left <= right and ... | def main():
for _ in range(int(input())):
n = int(input())
arr = list(map(int, input().strip().split()))
if n == 1:
print(arr[0])
else:
n += 1
arr.append(1001)
(left, right) = (0, 1)
res = ''
while left <= right ... |
#########################################################################################
# IMPORTANT: This file should be copied to setting.py and then completed before use #
#########################################################################################
# Rocky Version
VERSION = '0.3.5'
# Path to js... | version = '0.3.5'
hosts = 'file.json'
ports_path = 'path/ports/'
router_name_servers = ['8.8.8.8', '1.1.1.1']
rocky_rsa = ''
robot_rsa = ''
administrator_encryp_pass = ''
api_user_pass = ''
radius_server_address = ''
radius_server_secret = ''
device_config_path = 'path/repo/'
map_access_list = [{'source_address': '', '... |
###########################################################
# #
# Solving factorial problem with recursive function #
# #
###########################################################
def factorial(n):
... | def factorial(n):
if n == 2:
return 2
return n * factorial(n - 1)
print(factorial(int(input()))) |
"""Enter n, use the recursion method (for example,
derive the latter term from the relationship between the preceding items,
it is a one-loop question) and caculate the sum of 1+2!+3!+...+n! and output the result."""
n = int(input('Give me a integer: '))
s = term = 1
for i in range(2, n+1):
term *= i
s += t... | """Enter n, use the recursion method (for example,
derive the latter term from the relationship between the preceding items,
it is a one-loop question) and caculate the sum of 1+2!+3!+...+n! and output the result."""
n = int(input('Give me a integer: '))
s = term = 1
for i in range(2, n + 1):
term *= i
s += t... |
# -*- coding: utf-8 -*-
"""
1417. Reformat The String
Given alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits).
You have to find a permutation of the string where no letter is followed by another letter and no digit
is followed by another digit. That is, no two... | """
1417. Reformat The String
Given alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits).
You have to find a permutation of the string where no letter is followed by another letter and no digit
is followed by another digit. That is, no two adjacent characters hav... |
#
# University of Luxembourg
# Laboratory of Algorithmics, Cryptology and Security (LACS)
#
# FigureOfMerit (FOM)
#
# Copyright (C) 2015 University of Luxembourg
#
# Written in 2015 by Daniel Dinu <dumitru-daniel.dinu@uni.lu>
#
# This file is part of FigureOfMerit.
#
# This program is free software; you can redistribut... | __author__ = 'daniel.dinu' |
__all__ = (
'ESputnikException',
'InvalidAuthDataError',
'IncorrectDataError'
)
class ESputnikException(AttributeError):
pass
class InvalidAuthDataError(ESputnikException):
def __init__(self, code, message):
self.code = code
self.message = message
class IncorrectDataError(Inval... | __all__ = ('ESputnikException', 'InvalidAuthDataError', 'IncorrectDataError')
class Esputnikexception(AttributeError):
pass
class Invalidauthdataerror(ESputnikException):
def __init__(self, code, message):
self.code = code
self.message = message
class Incorrectdataerror(InvalidAuthDataError)... |
class TextFieldFsm:
def __init__(self, title, position, need_hide=False, initial_text=""):
self.title = title
self.position = position
self.need_hide = need_hide
self.initial_text = initial_text
| class Textfieldfsm:
def __init__(self, title, position, need_hide=False, initial_text=''):
self.title = title
self.position = position
self.need_hide = need_hide
self.initial_text = initial_text |
BINDIR = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/bin'
DATADIR = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/share'
DATAROOTDIR = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/share'
DESTDIR ... | bindir = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/bin'
datadir = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/share'
datarootdir = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/share'
destdir = '/'
docdir = '/usr/local/Cella... |
wanted_profit = float(input())
is_wanted_profit_gained = False
total_amount = 0
cocktail = input()
while cocktail != 'Party!':
number_of_cocktails = int(input())
cocktail_price = len(cocktail)
order_price = cocktail_price * number_of_cocktails
if order_price % 2 != 0:
order_price = order_price ... | wanted_profit = float(input())
is_wanted_profit_gained = False
total_amount = 0
cocktail = input()
while cocktail != 'Party!':
number_of_cocktails = int(input())
cocktail_price = len(cocktail)
order_price = cocktail_price * number_of_cocktails
if order_price % 2 != 0:
order_price = order_price -... |
# Define a class to receive the characteristics of each line detection
class Line():
def __init__(self):
# was the line detected in the last iteration?
self.detected = False
# x values of the last n fits of the line
self.recent_xfitted = []
#average x values of the fitted ... | class Line:
def __init__(self):
self.detected = False
self.recent_xfitted = []
self.bestx = None
self.best_fit = None
self.current_fit = [np.array([False])]
self.radius_of_curvature = None
self.line_base_pos = None
self.diffs = np.array([0, 0, 0], dty... |
load("@io_bazel_rules_dotnet//dotnet:defs.bzl", "core_library", "core_nunit3_test", "core_resource")
COMMON_DEFINES = [
"NETSTANDARD2_0",
"NETCOREAPP2_0",
"SERIALIZATION",
"ASYNC",
#"PLATFORM_DETECTION",
"PARALLEL",
"TASK_PARALLEL_LIBRARY_API",
]
core_library(
name = "nunit.framework.d... | load('@io_bazel_rules_dotnet//dotnet:defs.bzl', 'core_library', 'core_nunit3_test', 'core_resource')
common_defines = ['NETSTANDARD2_0', 'NETCOREAPP2_0', 'SERIALIZATION', 'ASYNC', 'PARALLEL', 'TASK_PARALLEL_LIBRARY_API']
core_library(name='nunit.framework.dll', srcs=glob(['src/NUnitFramework/framework/**/*.cs']) + ['sr... |
# Strings Part-1 - Definition,casting and indexing
my_string = "Python101!"
another_string = 'Welcome '
# quoting the quote !
dialog = 'He asked , "But sir, python is a snake?!" '
reply = "Monty replied , 'Of course it is.' "
multi_line = """ You cans freely type here , without worrying about
using \n to go on to a n... | my_string = 'Python101!'
another_string = 'Welcome '
dialog = 'He asked , "But sir, python is a snake?!" '
reply = "Monty replied , 'Of course it is.' "
multi_line = ' You cans freely type here , without worrying about\nusing \n to go on to a new line... '
txt_num = str(123)
print(txt_num)
letter = my_string[0]
print(l... |
"""
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5
max. difference = 6-... | """
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5
max. difference = 6-... |
def solution(l):
parsed = [e.split(".") for e in l]
toSort = [map(int, e) for e in parsed]
sortedINTs = sorted(toSort)
sortedJoined = [('.'.join(str(ee) for ee in e)) for e in sortedINTs]
return sortedJoined | def solution(l):
parsed = [e.split('.') for e in l]
to_sort = [map(int, e) for e in parsed]
sorted_in_ts = sorted(toSort)
sorted_joined = ['.'.join((str(ee) for ee in e)) for e in sortedINTs]
return sortedJoined |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
if __name__ == '__main__':
print("************************************************************************")
print("* WELCOME TO ZEROMCMP (OpenSource MultiCloud Management Platform) *")
print("**************************************************************... | if __name__ == '__main__':
print('************************************************************************')
print('* WELCOME TO ZEROMCMP (OpenSource MultiCloud Management Platform) *')
print('************************************************************************') |
class Settings:
def __init__(self):
self.screen_width = 900
self.screen_height = 700
self.bg_color = (230, 230, 230)
self.ship_speed_factor = 1
# bullet
self.bullet_speed_factor = 1
self.bullet_width = 4
self.bullet_height = 4
self.bullet_color... | class Settings:
def __init__(self):
self.screen_width = 900
self.screen_height = 700
self.bg_color = (230, 230, 230)
self.ship_speed_factor = 1
self.bullet_speed_factor = 1
self.bullet_width = 4
self.bullet_height = 4
self.bullet_color = (60, 60, 60)
... |
def main() -> None:
S = input()
print("Yes" if "AC" in [S[i:i+2] for i in range(len(S)-1)] else "No")
if __name__ == '__main__':
main()
| def main() -> None:
s = input()
print('Yes' if 'AC' in [S[i:i + 2] for i in range(len(S) - 1)] else 'No')
if __name__ == '__main__':
main() |
i= 1
while i<=3:
print("Guess:", i)
i=i+1
print("sorry you failed") | i = 1
while i <= 3:
print('Guess:', i)
i = i + 1
print('sorry you failed') |
config = {
# application info
'name': "texfuuin", # navbar application name
'db_path': "./texfuuin-db.json", # path to tinydb file
'port': 5000, # port to listen in production mod... | config = {'name': 'texfuuin', 'db_path': './texfuuin-db.json', 'port': 5000, 'devel': True, 'recaptcha-sitekey': '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI', 'recaptcha-secretkey': '6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe', 'default_user': 'anonymous', 'admin_trip': '50a3cf2', 'trip_salt': 'kasdjhfkasdhfklasjdhfksjadhf... |
src = Split('''
aos/soc_impl.c
hal/uart.c
hal/flash.c
main.c
''')
deps = Split('''
kernel/rhino
platform/arch/arm/armv7m
platform/mcu/wm_w600/
kernel/vcall
kernel/init
''')
global_macro = Split('''
STDIO_UART=0
CONFIG_NO_TCPIP
... | src = split('\n aos/soc_impl.c\n hal/uart.c\n hal/flash.c \n\tmain.c\n')
deps = split('\n kernel/rhino\n platform/arch/arm/armv7m\n platform/mcu/wm_w600/\n kernel/vcall\n kernel/init\n')
global_macro = split('\n STDIO_UART=0 \n CONFIG_NO_TCPIP\n ... |
# Test helper functions and classes
class ParameterPassLevel:
FLAG = 0
INI_KEY = 1
MARKER = 2
def _assert_result_outcomes(
result, passed=0, skipped=0, failed=0, error=0, dynamic_rerun=0
):
outcomes = result.parseoutcomes()
_check_outcome_field(outcomes, "passed", passed)
_check_outcome_... | class Parameterpasslevel:
flag = 0
ini_key = 1
marker = 2
def _assert_result_outcomes(result, passed=0, skipped=0, failed=0, error=0, dynamic_rerun=0):
outcomes = result.parseoutcomes()
_check_outcome_field(outcomes, 'passed', passed)
_check_outcome_field(outcomes, 'skipped', skipped)
_chec... |
# O(1) time | O(1) space
def validIPAddresses(string):
ipAddressesFound = []
for i in range(1, min(len(string), 4)): # from index 0 - 4
currentIPAddressParts = ["","","",""]
currentIPAddressParts[0] = string[:i] # before the first period
if not isValidPart(currentIPAddressParts[0]):
continue
for j... | def valid_ip_addresses(string):
ip_addresses_found = []
for i in range(1, min(len(string), 4)):
current_ip_address_parts = ['', '', '', '']
currentIPAddressParts[0] = string[:i]
if not is_valid_part(currentIPAddressParts[0]):
continue
for j in range(i + 1, i + min(len... |
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": (
"rest_framework_simplejwt.authentication.JWTAuthentication",
# TODO: 'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
# django-oauth-toolkit >= 1.0.0
# 'rest_framework_social_oauth2.authentication.SocialAuthenticati... | rest_framework = {'DEFAULT_AUTHENTICATION_CLASSES': ('rest_framework_simplejwt.authentication.JWTAuthentication',), 'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',), 'DEFAULT_PARSER_CLASSES': ('rest_framework.parsers.JSONParser', 'rest_framework.parsers.FormParser', 'rest_framework.parsers.MultiPa... |
def is_merge(s, part1, part2):
all_chars = len(s) == len(part1) + len(part2)
if not all_chars:
return False
d = {}
for i, c in enumerate(s):
d[c] = i
indices1, indices2 = [d[c] for c in part1], [d[c] for c in part2]
part1_good = indices1 == sorted(indices1)
part2_good = indic... | def is_merge(s, part1, part2):
all_chars = len(s) == len(part1) + len(part2)
if not all_chars:
return False
d = {}
for (i, c) in enumerate(s):
d[c] = i
(indices1, indices2) = ([d[c] for c in part1], [d[c] for c in part2])
part1_good = indices1 == sorted(indices1)
part2_good =... |
def Duplicate_Charaters(Test_String):
Duplicates = []
for char in Test_String:
if Test_String.count(char) > 1 and char not in Duplicates:
Duplicates.append(char)
return Duplicates
Test_String = input("Enter a String: ")
print(*(Duplicate_Charaters(Test_String)))
| def duplicate__charaters(Test_String):
duplicates = []
for char in Test_String:
if Test_String.count(char) > 1 and char not in Duplicates:
Duplicates.append(char)
return Duplicates
test__string = input('Enter a String: ')
print(*duplicate__charaters(Test_String)) |
#!python3
def main():
with open('21.txt', 'r') as f, open('21_out.txt', 'w') as f_out:
lines = f.readlines()
# Part 1
answer = 0
print(answer)
print(answer, file=f_out)
# Part 2
print(answer)
print(answer, file=f_out)
if __name__ == '__main__':
... | def main():
with open('21.txt', 'r') as f, open('21_out.txt', 'w') as f_out:
lines = f.readlines()
answer = 0
print(answer)
print(answer, file=f_out)
print(answer)
print(answer, file=f_out)
if __name__ == '__main__':
main() |
class HashState:
def __init__(self, player, cards, leading, upper, lower, tricks):
self.current_player = player
self.cards = cards
self.upper_bound = upper
self.lower_bound = lower
self.leading_suite = leading
self.tricks_left = tricks
def get_current_player(... | class Hashstate:
def __init__(self, player, cards, leading, upper, lower, tricks):
self.current_player = player
self.cards = cards
self.upper_bound = upper
self.lower_bound = lower
self.leading_suite = leading
self.tricks_left = tricks
def get_current_player(sel... |
# -*- coding: utf-8 -*-
# License: See LICENSE file.
required_states = ['position']
required_matrices = ['cellular_binary_grass']
def run(name, world, matrices, states, extra_life=10):
y,x = states['position']
#if matrices['cellular_binary_grass'][int(y),int(x)]:
# Eat the cell under the agent's position... | required_states = ['position']
required_matrices = ['cellular_binary_grass']
def run(name, world, matrices, states, extra_life=10):
(y, x) = states['position']
matrices['cellular_binary_grass'][int(y), int(x)] = False |
class Config:
def __init__(self, classified_types: [str]):
self.classified_types = classified_types
| class Config:
def __init__(self, classified_types: [str]):
self.classified_types = classified_types |
nterms = int(input("Stevilo cifr? "))
n1, n2 = 0, 1
count = 0
if nterms <= 0:
print("Vnesi pozitivno stevilo: ")
elif nterms == 1:
print("Sekvenca do ",nterms,": ")
print(n1)
else:
print("Sekvenca:")
while count < nterms:
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
coun... | nterms = int(input('Stevilo cifr? '))
(n1, n2) = (0, 1)
count = 0
if nterms <= 0:
print('Vnesi pozitivno stevilo: ')
elif nterms == 1:
print('Sekvenca do ', nterms, ': ')
print(n1)
else:
print('Sekvenca:')
while count < nterms:
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth... |
issues=[
dict(name='Habit',number=5,season='Winter 2012',
description='commit to a change, experience it, and record'),
dict(name='Interview', number=4, season='Autumn 2011',
description="this is your opportunity to inhabit another's mind"),
dict(name= 'Digital Presence', number= 3, season= ... | issues = [dict(name='Habit', number=5, season='Winter 2012', description='commit to a change, experience it, and record'), dict(name='Interview', number=4, season='Autumn 2011', description="this is your opportunity to inhabit another's mind"), dict(name='Digital Presence', number=3, season='Summer 2011', description='... |
def bestSum(t, arr, memo=None):
"""
m: target sum, t
n: len(arr)
time = O(n^m*m)
space = O(m*m) [in each stack frame, I am storing an array, which in worst case would be m]
// Memoized complexity
time = O(n*m*m)
space = O(m*m)
"""
if memo is None:
memo = {}
if t in memo:
return memo[t]
if t == 0:
r... | def best_sum(t, arr, memo=None):
"""
m: target sum, t
n: len(arr)
time = O(n^m*m)
space = O(m*m) [in each stack frame, I am storing an array, which in worst case would be m]
// Memoized complexity
time = O(n*m*m)
space = O(m*m)
"""
if memo is None:
memo = {}
if t in memo:
return mem... |
"""Expectations that can be placed on an HTTP request"""
class ResponseExpectation(object):
"""An expectation placed on an HTTP response."""
def __init__(self):
pass
def validate(self, validation, response):
"""If the expectation is met, do nothing. If the expectation is
not met... | """Expectations that can be placed on an HTTP request"""
class Responseexpectation(object):
"""An expectation placed on an HTTP response."""
def __init__(self):
pass
def validate(self, validation, response):
"""If the expectation is met, do nothing. If the expectation is
not met,... |
num = 1
factors = list()
while num <= 100:
if (num % 10) == 0:
factors.append(num)
num = num + 1
print("Factors :",factors)
| num = 1
factors = list()
while num <= 100:
if num % 10 == 0:
factors.append(num)
num = num + 1
print('Factors :', factors) |
#! /usr/bin/env python3
"""
Print patterns based on Pascal's Triangle.
"""
class Triangle:
"""Represents a Pascal's Triangle which can be rendered as text.
"""
def __init__(self, num_rows):
self.num_rows = num_rows
self.rows = [[1]]
prev_row = [1]
for row_num in range(1, n... | """
Print patterns based on Pascal's Triangle.
"""
class Triangle:
"""Represents a Pascal's Triangle which can be rendered as text.
"""
def __init__(self, num_rows):
self.num_rows = num_rows
self.rows = [[1]]
prev_row = [1]
for row_num in range(1, num_rows):
th... |
dict(
source=["/home/yzhang3151/project/NMT/experiments/nmt/binarized_text.diag.shuf.h5"],
target=["/home/yzhang3151/project/NMT/experiments/nmt/binarized_text.drug.shuf.h5"],
indx_word="/home/yzhang3151/project/NMT/experiments/nmt/ivocab.diag.pkl",
indx_word_target="/home/yzhang3151/project/NMT/experiments/nmt/ivocab.... | dict(source=['/home/yzhang3151/project/NMT/experiments/nmt/binarized_text.diag.shuf.h5'], target=['/home/yzhang3151/project/NMT/experiments/nmt/binarized_text.drug.shuf.h5'], indx_word='/home/yzhang3151/project/NMT/experiments/nmt/ivocab.diag.pkl', indx_word_target='/home/yzhang3151/project/NMT/experiments/nmt/ivocab.d... |
#!/usr/bin/python -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
# Basic list exercises
# Fill in the code for the functions below. main() is already set ... | def match_ends(words):
return len([word for word in words if len(word) >= 2 and word[0] == word[-1]])
def front_x(words):
strings_with_x = sorted([word for word in words if word[0] == 'x'])
other_strings = sorted([word for word in words if word[0] != 'x'])
return strings_with_x + other_strings
def sor... |
#HERE IS WHERE YOU CHANGE THE URL TO YOUR MOODLE SERVER
#MAKE SURE ALL THE PHP FILES ARE IN THE API FOLDER FOR THIS TO WORK
#CAN CHANGE THE API KEY HERE AS WELL
loginAPIcall = 'http://157.245.126.159/api/login.php'
getPointsAPIcall = 'http://157.245.126.159/api/get_user_points.php'
removePointsAPIcall = 'http://157.24... | login_ap_icall = 'http://157.245.126.159/api/login.php'
get_points_ap_icall = 'http://157.245.126.159/api/get_user_points.php'
remove_points_ap_icall = 'http://157.245.126.159/api/cut_user_points.php'
transactions_ap_icall = 'http://157.245.126.159/api/get_user_pointlist.php'
change_nickname_ap_icall = 'http://157.245.... |
#
# PySNMP MIB module DELL-NETWORKING-FIB-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DELL-NETWORKING-FIB-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:37:54 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 ... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_size_constraint, constraints_intersection, value_range_constraint, constraints_union) ... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 is None:
return l2
elif l2 is None:
return l... | class Listnode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def merge_two_lists(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 is None:
return l2
elif l2 is None:
return l1
head = ph = list_node(-1... |
class AuthNError(Exception):
"""AuthN is missing something. Either URL and/or API Keys
Args:
Exception ([type]): [description]
"""
pass
| class Authnerror(Exception):
"""AuthN is missing something. Either URL and/or API Keys
Args:
Exception ([type]): [description]
"""
pass |
def fib(n):
f1 = 1
f2 = 2
s = 2
while f2 < n:
nxt = f1 + f2
f1 = f2
f2 = nxt
if nxt & 1 == 0:
s += nxt
return s
print(fib(4000000))
| def fib(n):
f1 = 1
f2 = 2
s = 2
while f2 < n:
nxt = f1 + f2
f1 = f2
f2 = nxt
if nxt & 1 == 0:
s += nxt
return s
print(fib(4000000)) |
num1=100
num2=200
num3=300
| num1 = 100
num2 = 200
num3 = 300 |
class FieldType:
def __init__(self):
pass
Invalid = 0
Integer = 1
Text = 2
Note = 3
DateTime = 4
Counter = 5
Choice = 6
Lookup = 7
Boolean = 8
Number = 9
Currency = 10
URL = 11
Computed = 12
Threading = 13
Guid = 14
MultiChoice = 15
GridCh... | class Fieldtype:
def __init__(self):
pass
invalid = 0
integer = 1
text = 2
note = 3
date_time = 4
counter = 5
choice = 6
lookup = 7
boolean = 8
number = 9
currency = 10
url = 11
computed = 12
threading = 13
guid = 14
multi_choice = 15
grid... |
'''Challenges Set 1 Challenge 3 Single-byte XOR cipher'''
# http://www.data-compression.com/english.html
CHARACTER_FREQ = {
'a': 0.0651738, 'b': 0.0124248, 'c': 0.0217339, 'd': 0.0349835, 'e': 0.1041442, 'f': 0.0197881, 'g': 0.0158610,
'h': 0.0492888, 'i': 0.0558094, 'j': 0.0009033, 'k': 0.0050529, 'l':... | """Challenges Set 1 Challenge 3 Single-byte XOR cipher"""
character_freq = {'a': 0.0651738, 'b': 0.0124248, 'c': 0.0217339, 'd': 0.0349835, 'e': 0.1041442, 'f': 0.0197881, 'g': 0.015861, 'h': 0.0492888, 'i': 0.0558094, 'j': 0.0009033, 'k': 0.0050529, 'l': 0.033149, 'm': 0.0202124, 'n': 0.0564513, 'o': 0.0596302,... |
bids_schema = {
# BIDS identification bits
'modality': {
'type': 'string',
'required': True
},
'subject_id': {
'type': 'string',
'required': True
},
'session_id': {'type': 'string'},
'run_id': {'type': 'string'},
'acq_id': {'type': 'string'},
'task_id... | bids_schema = {'modality': {'type': 'string', 'required': True}, 'subject_id': {'type': 'string', 'required': True}, 'session_id': {'type': 'string'}, 'run_id': {'type': 'string'}, 'acq_id': {'type': 'string'}, 'task_id': {'type': 'string'}, 'run_id': {'type': 'string'}, 'AccelNumReferenceLines': {'type': 'integer'}, '... |
# Python - 2.7.6
class Ship:
def __init__(self, draft, crew):
self.draft = draft
self.crew = crew
def is_worth_it(self):
return (self.draft - self.crew * 1.5) > 20
| class Ship:
def __init__(self, draft, crew):
self.draft = draft
self.crew = crew
def is_worth_it(self):
return self.draft - self.crew * 1.5 > 20 |
# Copyright 2018 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | load('//go/private:providers.bzl', 'GoStdLib')
def _pure_transition_impl(settings, attr):
return {'//go/config:pure': True}
pure_transition = transition(implementation=_pure_transition_impl, inputs=['//go/config:pure'], outputs=['//go/config:pure'])
def _stdlib_files_impl(ctx):
libs = ctx.attr._stdlib[0][GoSt... |
def is_palindrome(word: str) -> bool:
word = word.replace(' ','').lower() #Take out every space and convert to lowercase the entire string
assert len(word) > 0 , 'Error: Cannot process empty words'
return word == word[::-1]
def main():
word: str = input('Write a word: ')
if is_palindrome(word):
... | def is_palindrome(word: str) -> bool:
word = word.replace(' ', '').lower()
assert len(word) > 0, 'Error: Cannot process empty words'
return word == word[::-1]
def main():
word: str = input('Write a word: ')
if is_palindrome(word):
print(f'{word} is a palindrome!')
else:
print(f'... |
# Python allows you to assign values to multiple variables in one line:
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
# And you can assign the same value to multiple variables in one line:
x = y = z = "Orange"
print(x)
print(y)
print(z)
| (x, y, z) = ('Orange', 'Banana', 'Cherry')
print(x)
print(y)
print(z)
x = y = z = 'Orange'
print(x)
print(y)
print(z) |
frogs = input().split()
while True:
line = input()
tokens = line.split()
command = tokens[0]
if command == 'Join':
name = tokens[1]
frogs.append(name)
elif command == 'Jump':
name = tokens[1]
index = int(tokens[2])
if 0 <= index < len(frogs):
... | frogs = input().split()
while True:
line = input()
tokens = line.split()
command = tokens[0]
if command == 'Join':
name = tokens[1]
frogs.append(name)
elif command == 'Jump':
name = tokens[1]
index = int(tokens[2])
if 0 <= index < len(frogs):
frogs... |
print('===== DESAFIO 065 =====')
op = ''
count = 0
media = 0
maior = menor = 0
while op != 'n':
num = int(input('digite um valor: '))
count += 1
media += num
if count == 1:
maior = num
menor = num
else:
if num > maior:
maior = num
if num < menor:
... | print('===== DESAFIO 065 =====')
op = ''
count = 0
media = 0
maior = menor = 0
while op != 'n':
num = int(input('digite um valor: '))
count += 1
media += num
if count == 1:
maior = num
menor = num
else:
if num > maior:
maior = num
if num < menor:
... |
def max_sub_array_of_size_k(k, arr):
# TODO: Write your code here
if not arr:
return -1
curSum = 0
i = 0
j = len(arr) -1
while i < j:
subarr = arr[i:k]
print(subarr)
total = 0
for num in subarr:
total += num
if total > curSum:
... | def max_sub_array_of_size_k(k, arr):
if not arr:
return -1
cur_sum = 0
i = 0
j = len(arr) - 1
while i < j:
subarr = arr[i:k]
print(subarr)
total = 0
for num in subarr:
total += num
if total > curSum:
cur_sum = total
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.