content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""This problem was asked by Yahoo.
Write an algorithm that computes the reversal of a directed graph.
For example, if a graph consists of A -> B -> C, it should become A <- B <- C.
""" | """This problem was asked by Yahoo.
Write an algorithm that computes the reversal of a directed graph.
For example, if a graph consists of A -> B -> C, it should become A <- B <- C.
""" |
test = {
'name': 'Loops',
'points': 0,
'suites': [
{
'cases': [
{
'code': r"""
>>> n = 3
>>> while n >= 0: # If this loops forever, just type Infinite Loop
... n -= 1
... print(n)
6d6f378f0affa7f84aa38e519e353617
f26f... | test = {'name': 'Loops', 'points': 0, 'suites': [{'cases': [{'code': '\n >>> n = 3\n >>> while n >= 0: # If this loops forever, just type Infinite Loop\n ... n -= 1\n ... print(n)\n 6d6f378f0affa7f84aa38e519e353617\n f26f9ec9ba426ebfdd8a43b22c8c74a0\n ... |
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
x = bin(x^y)
l = len(x)
sum = 0
for i in range(l):
if x[i] == '1':
sum += 1
return sum | class Solution(object):
def hamming_distance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
x = bin(x ^ y)
l = len(x)
sum = 0
for i in range(l):
if x[i] == '1':
sum += 1
return sum |
def Courses():
courses = [
{
'id' : 1,
'title' : 'Learn AJax',
'body' : 'Lorem Ipsum dolor sit amet',
'category' : 'Web Development'
},
{
'id' : 2,
'title' : 'Learn Angularjs',
'body' : 'Lorem Ipsum dolor sit amet',
'category' : 'Web Development'
},
{
'id' : 3,
'title' : 'Learn ... | def courses():
courses = [{'id': 1, 'title': 'Learn AJax', 'body': 'Lorem\tIpsum dolor sit amet', 'category': 'Web Development'}, {'id': 2, 'title': 'Learn Angularjs', 'body': 'Lorem\tIpsum dolor sit amet', 'category': 'Web Development'}, {'id': 3, 'title': 'Learn Angular Material', 'body': 'Lorem\tIpsum dolor sit ... |
class VirtualHelixItemController():
def __init__(self, virtualhelix_item, model_virtual_helix):
self._virtual_helix_item = virtualhelix_item
self._model_virtual_helix = model_virtual_helix
self.connectSignals()
# end def
def connectSignals(self):
vh_item = self._virtual_heli... | class Virtualhelixitemcontroller:
def __init__(self, virtualhelix_item, model_virtual_helix):
self._virtual_helix_item = virtualhelix_item
self._model_virtual_helix = model_virtual_helix
self.connectSignals()
def connect_signals(self):
vh_item = self._virtual_helix_item
... |
def write_to_file(file, data):
with open(file, 'a') as file:
print(data)
file.write(str(data))
def read_from_file(file):
with open(file, 'r') as file:
lines = file.readlines()
print("Usernames & password")
for line in lines:
print(f'{line}')
... | def write_to_file(file, data):
with open(file, 'a') as file:
print(data)
file.write(str(data))
def read_from_file(file):
with open(file, 'r') as file:
lines = file.readlines()
print('Usernames & password')
for line in lines:
print(f'{line}')
return li... |
"""pcmc-bot / blocs / Ready-check
Classes to raise an exception when accessing attributes not
respecting a given rule
"""
class NotReadyError(RuntimeError):
"""An attribute is tried to be accessed before it is ready.
Inherits from :exc:`RuntimeError`.
"""
pass
class _RCDict(dict):
def __init_... | """pcmc-bot / blocs / Ready-check
Classes to raise an exception when accessing attributes not
respecting a given rule
"""
class Notreadyerror(RuntimeError):
"""An attribute is tried to be accessed before it is ready.
Inherits from :exc:`RuntimeError`.
"""
pass
class _Rcdict(dict):
def __init__... |
""" List: Collection or Array """
"""
Lists are just like the arrays declared in other languages, in which you
can store multiple values in a single varible.
In Python lists are written with square brackets.
A single list can contain strings, integers, as well as objects
"""
""" Create a empty list """
... | """ List: Collection or Array """
'\n Lists are just like the arrays declared in other languages, in which you\n can store multiple values in a single varible.\n In Python lists are written with square brackets.\n A single list can contain strings, integers, as well as objects\n'
' Create a empty list '
my_list... |
# Week-10 Challe
latter1 = input("Enter first Latter in Your Name: ")
latter2 = input("Enter Last Latter in Your Name: ")
print("First Latter is {}".format(latter1), "Scocend Latter is {}".format(latter2) )
print("-----")
print("-----")
my_palance = "Dear {}, Your current balance is {}{}"
name = "Mohammed Asmri"
palan... | latter1 = input('Enter first Latter in Your Name: ')
latter2 = input('Enter Last Latter in Your Name: ')
print('First Latter is {}'.format(latter1), 'Scocend Latter is {}'.format(latter2))
print('-----')
print('-----')
my_palance = 'Dear {}, Your current balance is {}{}'
name = 'Mohammed Asmri'
palance = 53.44
currency... |
# Dictionary to store calculated fibonacci terms to save computational time while computing larger fibonacci terms.
aDict = {
# 1st and 2nd term in fibonacci series is 0 and 1 respectively
1: 0,
2: 1
}
numFibCalls = 0
def fibonacci_efficient(n, aDict):
global numFibCalls
numFibCalls += 1
if n ... | a_dict = {1: 0, 2: 1}
num_fib_calls = 0
def fibonacci_efficient(n, aDict):
global numFibCalls
num_fib_calls += 1
if n in aDict:
return aDict[n]
else:
ans = fibonacci_efficient(n - 1, aDict) + fibonacci_efficient(n - 2, aDict)
aDict[n] = ans
return ans
n = int(input('What... |
for i in range(int(input("How many numbers do you want to be in your list?"))):
nums= [input("What list of numbers do you want to sort using the power of BUBBLES? Here's a number:")]
to_sort=[nums]
for i in range(0, len(to_sort)):
for j in range (i+1, len(to_sort)):
if to_sort[i]> to_sort[j]:
... | for i in range(int(input('How many numbers do you want to be in your list?'))):
nums = [input("What list of numbers do you want to sort using the power of BUBBLES? Here's a number:")]
to_sort = [nums]
for i in range(0, len(to_sort)):
for j in range(i + 1, len(to_sort)):
if to_sort[i] > to_sort[j]:
... |
cp_file = file(simenv.checkpoint_name, "r")
cp_lines = []
common_lines = []
in_common = False
for line in cp_file:
if line == "OBJECT common TYPE common {\n":
in_common = True
if in_common:
common_lines.append(line)
if line == "}\n":
in_common = False
else:
cp_lines.append(lin... | cp_file = file(simenv.checkpoint_name, 'r')
cp_lines = []
common_lines = []
in_common = False
for line in cp_file:
if line == 'OBJECT common TYPE common {\n':
in_common = True
if in_common:
common_lines.append(line)
if line == '}\n':
in_common = False
else:
cp_lin... |
def fbx_mat_properties_from_texture(tex):
"""
Returns a set of FBX metarial properties that are affected by the given texture.
Quite obviously, this is a fuzzy and far-from-perfect mapping! Amounts of influence are completely lost, e.g.
Note tex is actually expected to be a texture slot.
"""
# M... | def fbx_mat_properties_from_texture(tex):
"""
Returns a set of FBX metarial properties that are affected by the given texture.
Quite obviously, this is a fuzzy and far-from-perfect mapping! Amounts of influence are completely lost, e.g.
Note tex is actually expected to be a texture slot.
"""
ble... |
# currying_chain.py
def construct_module_declaration(
subsequent_module_name: str,
number_of_input: int,
chain_len: int,
common_in: str
) -> str:
'''Declares the module with its name and appropriate number of input and
output wires'''
module_declaration = 'module {}(input '.format(sub... | def construct_module_declaration(subsequent_module_name: str, number_of_input: int, chain_len: int, common_in: str) -> str:
"""Declares the module with its name and appropriate number of input and
output wires"""
module_declaration = 'module {}(input '.format(subsequent_module_name)
for i in range(numb... |
_base_ = [
'../_base_/models/cgnet.py',
'../_base_/datasets/cityscapes_Non-semantic_1-to-1.py',
'../_base_/default_runtime.py'
]
# optimizer
optimizer = dict(type='Adam', lr=0.001, eps=1e-08, weight_decay=0.0005)
optimizer_config = dict()
# learning policy
lr_config = dict(policy='poly', power=0.9, min_lr=... | _base_ = ['../_base_/models/cgnet.py', '../_base_/datasets/cityscapes_Non-semantic_1-to-1.py', '../_base_/default_runtime.py']
optimizer = dict(type='Adam', lr=0.001, eps=1e-08, weight_decay=0.0005)
optimizer_config = dict()
lr_config = dict(policy='poly', power=0.9, min_lr=0.0001, by_epoch=False)
runner = dict(type='I... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Let's Encrypt PDNS plugin"""
# import inspect
#
# # https://github.com/certbot/certbot/issues/6504#issuecomment-473462138
# # https://github.com/certbot/certbot/issues/6040
# # https://github.com/certbot/certbot/issues/4351
# # https://github.com/certbot/certbot/pull/6... | """Let's Encrypt PDNS plugin""" |
def measure(decision_tree, test_set, target_attribute):
"""
Measure the accuracy of tree on the given test set.
Parameters
----------
decision_tree: DecisionTree
test_set: DataFrame
target_attribute: str
Returns
-------
accuracy: float
Number between 0.00 and 1.00. Mult... | def measure(decision_tree, test_set, target_attribute):
"""
Measure the accuracy of tree on the given test set.
Parameters
----------
decision_tree: DecisionTree
test_set: DataFrame
target_attribute: str
Returns
-------
accuracy: float
Number between 0.00 and 1.00. Mult... |
def unique(collect):
if not collect:
return False
setarr = set(collect)
key = len(collect) == len(setarr)
return key
| def unique(collect):
if not collect:
return False
setarr = set(collect)
key = len(collect) == len(setarr)
return key |
#
# Copyright Cloudlab URV 2020
#
# 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 writin... | def load_config(config_data=None):
if 'aws' not in config_data and 'aws_s3' not in config_data:
raise exception("'aws' and 'aws_s3' sections are mandatory in the configuration")
required_parameters_0 = ('access_key_id', 'secret_access_key')
if not set(required_parameters_0) <= set(config_data['aws']... |
#code
def rotatedindex(array, x):
for i in range(0,n):
if(x==array[i]):
return i
return -1
if __name__ == "__main__":
t = int(input())
arr=[]
for j in range(0,t):
n = int(input())
list1 = list(map(int, input().split()[:n]))
x = int(input())
result = rota... | def rotatedindex(array, x):
for i in range(0, n):
if x == array[i]:
return i
return -1
if __name__ == '__main__':
t = int(input())
arr = []
for j in range(0, t):
n = int(input())
list1 = list(map(int, input().split()[:n]))
x = int(input())
result =... |
'''
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Now your job is to find the total Hamming distance between all pairs of the given numbers.
Example:
Input: 4, 14, 2
Output: 6
Explanation: In binary representation, the 4 is 0100, 14 is 1110, and... | """
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Now your job is to find the total Hamming distance between all pairs of the given numbers.
Example:
Input: 4, 14, 2
Output: 6
Explanation: In binary representation, the 4 is 0100, 14 is 1110, and... |
# Copyright 2018 Red Hat, Inc.
#
# 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, ... | def get_fake_context(**config):
"""Generates a fake context description for testing."""
fake_credential = {'user': 'fake_user', 'host': 'fake_host', 'port': -1, 'key': 'fake_key', 'password': 'fake_password'}
return {'task': {'uuid': 'fake_task_uuid'}, 'ovn_multihost': {'controller': {'fake-controller-node'... |
"""
Every email consists of a local name and a domain name, separated by the @ sign.
For example, in alice@leetcode.com, alice is the local name, and leetcode.com is the domain name.
Besides lowercase letters, these emails may contain '.'s or '+'s.
If you add periods ('.') between some characters in the local name pa... | """
Every email consists of a local name and a domain name, separated by the @ sign.
For example, in alice@leetcode.com, alice is the local name, and leetcode.com is the domain name.
Besides lowercase letters, these emails may contain '.'s or '+'s.
If you add periods ('.') between some characters in the local name pa... |
# iDrac, OME ==========> Terraform, Nagios, Ansible, xeonss ...
# (delay, backlog, latest features not available)
# (understanding standards, hardcoded expressions)
# +ves of redfish standard: Clear definitions, clear interpretation,
# still nuances exist
# Solution: [consumptions] | [python redfish bindings] |... | def info():
message = 'Examples folder' |
def CallPluginFunctions (_Plugins, _Function, *_Args):
for Plugin in _Plugins:
if _Function in dir (Plugin):
Method = getattr (Plugin, _Function)
if _Args:
Method (*_Args)
else:
Method ()
| def call_plugin_functions(_Plugins, _Function, *_Args):
for plugin in _Plugins:
if _Function in dir(Plugin):
method = getattr(Plugin, _Function)
if _Args:
method(*_Args)
else:
method() |
class FocusManager(object):
""" Provides a set of static methods,attached properties,and events for determining and setting focus scopes and for setting the focused element within the scope. """
@staticmethod
def AddGotFocusHandler(element,handler):
""" AddGotFocusHandler(element: DependencyObject,handler: Rou... | class Focusmanager(object):
""" Provides a set of static methods,attached properties,and events for determining and setting focus scopes and for setting the focused element within the scope. """
@staticmethod
def add_got_focus_handler(element, handler):
""" AddGotFocusHandler(element: DependencyObj... |
def valid_card_req():
return {
"number": "4242424242424242",
"expMonth": "12",
"expYear": "2055",
"cvc": "123",
"cardholderName": "Python Test",
}
def disputed_card_req():
return {
"number": "4242000000000018",
"expMonth": "12",
"expYear": "2... | def valid_card_req():
return {'number': '4242424242424242', 'expMonth': '12', 'expYear': '2055', 'cvc': '123', 'cardholderName': 'Python Test'}
def disputed_card_req():
return {'number': '4242000000000018', 'expMonth': '12', 'expYear': '2055', 'cvc': '123', 'cardholderName': 'Python Test'}
def fraud_warning_c... |
while True:
try:
n = int(input())
starting = list(map(int, input().split()))[:n]
ending = list(map(int, input().split()))[:n]
cmp = [0] * n
for i in range(n):
for j in range(n):
if starting[i] == ending[j]:
cmp[j] = i... | while True:
try:
n = int(input())
starting = list(map(int, input().split()))[:n]
ending = list(map(int, input().split()))[:n]
cmp = [0] * n
for i in range(n):
for j in range(n):
if starting[i] == ending[j]:
cmp[j] = i + 25
... |
class Utils:
@staticmethod
def contains(needle, haystack, search_type='contains', options=[]):
if not type(needle) == list:
needle = [needle]
if 'lowercase' in options:
needle = [x.lower() for x in needle]
haystack = haystack.lower()
if type(haystack)... | class Utils:
@staticmethod
def contains(needle, haystack, search_type='contains', options=[]):
if not type(needle) == list:
needle = [needle]
if 'lowercase' in options:
needle = [x.lower() for x in needle]
haystack = haystack.lower()
if type(haystack)... |
# Copyright (c) 2014 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'test_targetfilename_executable',
'type': 'executable',
'sources': ['hello.cc'],
'msvs_setti... | {'targets': [{'target_name': 'test_targetfilename_executable', 'type': 'executable', 'sources': ['hello.cc'], 'msvs_settings': {'VCLinkerTool': {'OutputFile': '$(TargetDir)\\$(TargetFileName)'}}}, {'target_name': 'test_targetfilename_loadable_module', 'type': 'loadable_module', 'sources': ['hello.cc'], 'msvs_settings':... |
__title__ = 'efinance'
__version__ = '0.3.6'
__author__ = 'micro sheep'
__url__ = 'https://github.com/Micro-sheep/efinance'
__author_email__ = 'micro-sheep@outlook.com'
__keywords__ = ['finance', 'quant', 'stock', 'fund', 'futures']
__description__ = 'A finance tool to get stock,fund and futures data base on eastmoney'... | __title__ = 'efinance'
__version__ = '0.3.6'
__author__ = 'micro sheep'
__url__ = 'https://github.com/Micro-sheep/efinance'
__author_email__ = 'micro-sheep@outlook.com'
__keywords__ = ['finance', 'quant', 'stock', 'fund', 'futures']
__description__ = 'A finance tool to get stock,fund and futures data base on eastmoney'... |
class Model(object):
"""An interface for a classifying model
This interface was inspired from this TensorFlow tutorial:
https://www.tensorflow.org/get_started/mnist/mechanics
inference: takes in an input_data op that produces the training data,
for example: tf.placeholder, and produces a logits... | class Model(object):
"""An interface for a classifying model
This interface was inspired from this TensorFlow tutorial:
https://www.tensorflow.org/get_started/mnist/mechanics
inference: takes in an input_data op that produces the training data,
for example: tf.placeholder, and produces a logi... |
def main():
a = int(input())
b = int(input())
if a >0 and b > 0:
ans = 1
elif a > 0 and b < 0:
ans = 4
elif a < 0 and b > 0:
ans = 2
else:
ans = 3
print(ans)
return
if __name__ == "__main__":
main() | def main():
a = int(input())
b = int(input())
if a > 0 and b > 0:
ans = 1
elif a > 0 and b < 0:
ans = 4
elif a < 0 and b > 0:
ans = 2
else:
ans = 3
print(ans)
return
if __name__ == '__main__':
main() |
# -*- coding: utf-8 -*-
"""
easybimehlanding
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
class FireInsurancePolicyFilter(object):
"""Implementation of the 'FireInsurancePolicyFilter' model.
TODO: type model description here.
Attributes:
... | """
easybimehlanding
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
class Fireinsurancepolicyfilter(object):
"""Implementation of the 'FireInsurancePolicyFilter' model.
TODO: type model description here.
Attributes:
insurance_policy_type (string): TOD... |
#implementing priority queue
class PriorityQueueBase:
"""abstract base class for a priority queue"""
class _item:
"""lightweight class to store priority queue item"""
__slots__ = '_key', '_value'
def __init__(self, k, v):
self._key = k
self._value = v
... | class Priorityqueuebase:
"""abstract base class for a priority queue"""
class _Item:
"""lightweight class to store priority queue item"""
__slots__ = ('_key', '_value')
def __init__(self, k, v):
self._key = k
self._value = v
def __it__(self, other):
... |
"""
complexity O(2^n), O(n) space because we're storing all the n numbers
"""
def getNthFib(n):
# Write your code here.
dictf = {}
dictf[0] = 0
dictf[1] = 1
if n in dictf.keys():
return dictf[n]
else:
return getNthFib(n-1) + getNthFib(n-2)
if __name__ == '__main__':
n = 12
print(getNthFib(n))... | """
complexity O(2^n), O(n) space because we're storing all the n numbers
"""
def get_nth_fib(n):
dictf = {}
dictf[0] = 0
dictf[1] = 1
if n in dictf.keys():
return dictf[n]
else:
return get_nth_fib(n - 1) + get_nth_fib(n - 2)
if __name__ == '__main__':
n = 12
print(get_nth_... |
#!/usr/bin/env python3
#-------------------------------------------------------------------------------
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isBalanced(s... | class Solution(object):
def is_balanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
balance = abs(self.getMaxHeight(root.left) - self.getMaxHeight(root.right))
if balance > 1:
return False
re... |
# -*- coding:utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Belgium - Payroll',
'category': 'Localization',
'depends': ['hr_payroll'],
'description': """
Belgian Payroll Rules.
======================
* Employee Details
* Employee Contracts
*... | {'name': 'Belgium - Payroll', 'category': 'Localization', 'depends': ['hr_payroll'], 'description': '\nBelgian Payroll Rules.\n======================\n\n * Employee Details\n * Employee Contracts\n * Passport based Contract\n * Allowances/Deductions\n * Allow to configure Basic/Gross/Net Salary\n * Em... |
def solve():
# No need for fancy math here, just solve directly
ans = sum(x for x in range(1000) if (x % 3 == 0 or x % 5 == 0))
return str(ans)
if __name__ == "__main__":
print(solve()) | def solve():
ans = sum((x for x in range(1000) if x % 3 == 0 or x % 5 == 0))
return str(ans)
if __name__ == '__main__':
print(solve()) |
#Date: 022822
#Difficulty: Medium
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
seen={}
left=0
length=0
for right in range(len(s)):
if s[right] not in seen:
seen[s[right]]=ri... | class Solution(object):
def length_of_longest_substring(self, s):
"""
:type s: str
:rtype: int
"""
seen = {}
left = 0
length = 0
for right in range(len(s)):
if s[right] not in seen:
seen[s[right]] = right
else:
... |
# name = input("Enter your name ?").strip()
# print(len(name))
# print(name)
print(" hello python world".strip())
print(" hello python world ".rstrip()) | print(' hello python world'.strip())
print(' hello python world '.rstrip()) |
class Node:
def __init__(self, data) -> None:
self.data = data
self.next = None
node1 = Node(10)
node2 = Node(20)
node3 = Node(30)
head = node1
node1.next = node2
node2.next = node3
class LinkedList:
def __init__(self, data) -> None:
self.head = Node(data)
def insertEnd(self,... | class Node:
def __init__(self, data) -> None:
self.data = data
self.next = None
node1 = node(10)
node2 = node(20)
node3 = node(30)
head = node1
node1.next = node2
node2.next = node3
class Linkedlist:
def __init__(self, data) -> None:
self.head = node(data)
def insert_end(self, da... |
#! python3
print('Enter the first number to add:')
first = input()
print('Enter the second number to add:')
second = input()
print('Enter the third number to add:')
third = input()
print('The sum is ' + first + second + third)
| print('Enter the first number to add:')
first = input()
print('Enter the second number to add:')
second = input()
print('Enter the third number to add:')
third = input()
print('The sum is ' + first + second + third) |
db_file_name = 'bills.db'
table_name = 'bills'
elasticsearch_server_addr = 'http://localhost:9200'
# IMPORTANT:
# enable https://www.google.com/settings/security/lesssecureapps
# in specifed gmail account in order to login from code and to start smtp server
email_acc = 'california.bills.notifier.bot@gmail.com'
email_... | db_file_name = 'bills.db'
table_name = 'bills'
elasticsearch_server_addr = 'http://localhost:9200'
email_acc = 'california.bills.notifier.bot@gmail.com'
email_pass = 'Jfej4_3io487eMfke'
email_server = 'smtp.gmail.com'
email_port = 587
site_addr = 'http://54.180.108.54/' |
def fcfs(processes):
CT=TAT=WT=T=cur=0
for i in processes:
WT+=max(0, cur-i[0])
cur=max(i[0], cur)+i[1]
CT+=cur
TAT+=cur-i[0]
T+=i[1]
return tuple(round(i/len(processes), 2) for i in (CT, TAT, WT, T)) | def fcfs(processes):
ct = tat = wt = t = cur = 0
for i in processes:
wt += max(0, cur - i[0])
cur = max(i[0], cur) + i[1]
ct += cur
tat += cur - i[0]
t += i[1]
return tuple((round(i / len(processes), 2) for i in (CT, TAT, WT, T))) |
# -*- coding: utf-8 -*-
"""
Created on 2017/3/24
@author: will4906
"""
# from logbook import Logger
# from service import log
# # # from service.account import *
# # # from service.proxy import *
# #
# # logger = Logger('main')
# #
# # if __name__ == '__main__':
# # # stupid()
# # # update_proxy()
# # # n... | """
Created on 2017/3/24
@author: will4906
""" |
#! /usr/bin/env python
# -- coding: utf-8 --
# ULL - Sistemas Inteligentes 2018/2019
#
# User class and functions to create, write and read users
USERS_DATA = "../Data/users.txt"
LAST_USER_ID = "../Data/last_user_id.txt"
class User:
def __init__(self, uid, age = 30, height = 170, weight = 70, sex = "M", exerci... | users_data = '../Data/users.txt'
last_user_id = '../Data/last_user_id.txt'
class User:
def __init__(self, uid, age=30, height=170, weight=70, sex='M', exercise_level=0.5, goal='maintain'):
self.uid = uid
self.age = age
self.height = height
self.weight = weight
self.sex = se... |
# -*- coding: utf-8 -*-
"""
Definition of the values for each parameter of the hcp_pipeline.
"""
## Location of the folder for the data of a single subject
dir_hcp_subj = '/Users/paolo/Datasets/HCP/RAW_DATA/100307/'
dir_hcp_subj = '/Users/paolo/Datasets/HCP/TEST/124422/'
# 100307 124422 161731 199655 201111 239944 2... | """
Definition of the values for each parameter of the hcp_pipeline.
"""
dir_hcp_subj = '/Users/paolo/Datasets/HCP/RAW_DATA/100307/'
dir_hcp_subj = '/Users/paolo/Datasets/HCP/TEST/124422/'
dir_hcp_t1 = 'T1w'
dir_hcp_dwi = 'T1w/Diffusion'
dir_hcp_out = 'Tractography'
par_b_shell = 1000
par_b_tag = 'b1k'
par_b0_threshol... |
f = 'apolonia.txt'
with open(f, 'r') as _f:
source = _f.read()
print(source.split('\n'))
| f = 'apolonia.txt'
with open(f, 'r') as _f:
source = _f.read()
print(source.split('\n')) |
#!/usr/bin/python3
"""
module with 1 function, add integers
"""
def add_integer(a, b):
"""returns a + b"""
if isinstance(a, (int, float)) and isinstance(b, (int, float)):
return int(a) + int(b)
else:
raise TypeError("{:} must be an integer"
.format('b' if isinstance... | """
module with 1 function, add integers
"""
def add_integer(a, b):
"""returns a + b"""
if isinstance(a, (int, float)) and isinstance(b, (int, float)):
return int(a) + int(b)
else:
raise type_error('{:} must be an integer'.format('b' if isinstance(a, (int, float)) else 'a')) |
#-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*-
class algorithm(object):
'algorithm'
@staticmethod
def remove_empties(l, recurse = True):
'Return a list of the non empty items in l'
assert isinstance(l, list)
def is_empty(x):
return x in [ (), [], Non... | class Algorithm(object):
"""algorithm"""
@staticmethod
def remove_empties(l, recurse=True):
"""Return a list of the non empty items in l"""
assert isinstance(l, list)
def is_empty(x):
return x in [(), [], None, '']
result = [x for x in l if not is_empty(x)]
... |
#mi taller: Juan-gonzalez
#UCC
#2017-1
print("numero uno:")
#comentari 1
a=input()
#input tiene como funcion leer las entradas
b=int(a)
#int tiene como funcion convertir las cadenas a numeros
print(a)
print(b)
print("numero dos:")
holaamor=input()
c=int(holaamor)
print(holaamor)
print(c)
suma=a+holaamor
otrasuma=b+c
pr... | print('numero uno:')
a = input()
b = int(a)
print(a)
print(b)
print('numero dos:')
holaamor = input()
c = int(holaamor)
print(holaamor)
print(c)
suma = a + holaamor
otrasuma = b + c
print(suma)
print(otrasuma) |
'''VetCond
==========
The CPL conditioning project in the vet school.
'''
__version__ = '0.1-dev'
| """VetCond
==========
The CPL conditioning project in the vet school.
"""
__version__ = '0.1-dev' |
"""
globals
"""
__version__ = "0.1.4"
LIBRARY = "pyclickup"
API_URL = "https://api.clickup.com/api/v1/"
TEST_API_URL = "https://private-anon-efe850a7d7-clickup.apiary-mock.com/api/v1/"
TEST_TOKEN = "access_token"
DEFAULT_STATUSES = [
{"status": "Open", "type": "open", "orderindex": 0, "color": "#d3d3d3"},
... | """
globals
"""
__version__ = '0.1.4'
library = 'pyclickup'
api_url = 'https://api.clickup.com/api/v1/'
test_api_url = 'https://private-anon-efe850a7d7-clickup.apiary-mock.com/api/v1/'
test_token = 'access_token'
default_statuses = [{'status': 'Open', 'type': 'open', 'orderindex': 0, 'color': '#d3d3d3'}, {'status': 'to... |
class User:
"""
Class that generates new instances of users.
"""
user_list = []
def __init__(self,first_name,second_name,username,password):
self.first_name = first_name
self.second_name = second_name
self.username = username
self.password = password
def save_u... | class User:
"""
Class that generates new instances of users.
"""
user_list = []
def __init__(self, first_name, second_name, username, password):
self.first_name = first_name
self.second_name = second_name
self.username = username
self.password = password
def sav... |
def outer():
i = 10
def inner():
print("inner i=", i)
inner()
print("Outer i=", i)
outer()
| def outer():
i = 10
def inner():
print('inner i=', i)
inner()
print('Outer i=', i)
outer() |
#
# Copyright (c) 2017-2018 Joy Diamond. All rights reserved.
#
@gem('Sapphire.Tokenize1Header')
def gem():
show = 0
@share
def tokenize_header_parenthesis_atom():
assert qd() is 0
assert qk() is none
assert qn() is none
s = qs()
m = definition_header_parenthes... | @gem('Sapphire.Tokenize1Header')
def gem():
show = 0
@share
def tokenize_header_parenthesis_atom():
assert qd() is 0
assert qk() is none
assert qn() is none
s = qs()
m = definition_header_parenthesis_match(s, qj())
if m is none:
raise_unknown_line... |
class Visible():
def __init__(self, color):
self._color = color
def draw(self):
pass
| class Visible:
def __init__(self, color):
self._color = color
def draw(self):
pass |
# Aiden B.
# 2/23/2021
# lab 1.04
# Part 1 or 2
part=input("run part 1 or 2?")
print("I am a genie. You have three wishes.")
w1=input("What would you like to wish for?\n")
w2=input("What would you like to wish for?\n")
w3=input("What would you like to wish for?\n")
if part=="1":
print("Your wishes are "+w1+", "... | part = input('run part 1 or 2?')
print('I am a genie. You have three wishes.')
w1 = input('What would you like to wish for?\n')
w2 = input('What would you like to wish for?\n')
w3 = input('What would you like to wish for?\n')
if part == '1':
print('Your wishes are ' + w1 + ', ' + w2 + ', and ' + w3)
elif part == '2... |
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
num = x
res = 0
while num > 0:
res = res * 10 + num%10
num = num//10
return x == res
if __name__ == "__main__":
sol = Solution()
n = 121
pr... | class Solution:
def is_palindrome(self, x: int) -> bool:
if x < 0:
return False
num = x
res = 0
while num > 0:
res = res * 10 + num % 10
num = num // 10
return x == res
if __name__ == '__main__':
sol = solution()
n = 121
print(... |
# Do not edit this file directly.
# It was auto-generated by: code/programs/reflexivity/reflexive_refresh
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file")
def xorgLibXrender():
http_archive(
name = "xorg_libXrender",
... | load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_file')
def xorg_lib_xrender():
http_archive(name='xorg_libXrender', build_file='//bazel/deps/xorg_libXrender:build.BUILD', sha256='f7ec77bdde44d3caa991100760da7ae0af6fa4555b5796bb000f57d8... |
def Pascal_Triangle(n):
for row in range(1, n + 1):
# Initializing the Initial Value of Pascal Value as 1
pascal_value = 1
# For printing blank spaces
for i in range(1, n - row + 1):
print(' ', end=' ')
# For calculating the pascal value
for i in ran... | def pascal__triangle(n):
for row in range(1, n + 1):
pascal_value = 1
for i in range(1, n - row + 1):
print(' ', end=' ')
for i in range(1, row + 1):
s = ' ' + str(pascal_value) + ' '
print(s, end=' ')
pascal_value = int(pascal_value * (row - i... |
# -*- coding: UTF-8 -*-
class Solution:
# other guy wonderful code
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d = {}
for i, num in enumerate(nums):
if target - num in d:
re... | class Solution:
def two_sum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d = {}
for (i, num) in enumerate(nums):
if target - num in d:
return [d[target - num], i]
d[num] = i
de... |
Q = int(input())
def lcs(X, Y):
dp = [[0] * (len(X)+1) for _ in range(len(Y)+1)]
for i in range(1,len(Y)+1):
for j in range(1,len(X)+1):
if X[j-1]==Y[i-1]:
dp[i][j] = dp[i-1][j-1] + 1
else:
dp[i][j] = max(dp[i][j-1],dp[i-1][j])
return dp[-1][-... | q = int(input())
def lcs(X, Y):
dp = [[0] * (len(X) + 1) for _ in range(len(Y) + 1)]
for i in range(1, len(Y) + 1):
for j in range(1, len(X) + 1):
if X[j - 1] == Y[i - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i][j - 1], dp[i - 1... |
#!/usr/bin/env python3
MAX_STATION = 19
def validate_station(name, station):
if not 0 <= station <= MAX_STATION:
raise ValueError('%s out of range: no station %d' % (name, station))
def validate_direction(direction):
if len(direction) != 1 or direction not in 'DU':
raise ValueError('direction... | max_station = 19
def validate_station(name, station):
if not 0 <= station <= MAX_STATION:
raise value_error('%s out of range: no station %d' % (name, station))
def validate_direction(direction):
if len(direction) != 1 or direction not in 'DU':
raise value_error('direction out of range: no dire... |
pkgname = "exiv2"
pkgver = "0.27.5"
pkgrel = 0
build_style = "cmake"
configure_args = [
"-DEXIV2_BUILD_SAMPLES=OFF", "-DEXIV2_ENABLE_BMFF=ON",
"-DEXIV2_BUILD_UNIT_TESTS=OFF"
]
make_check_target = "unit_test"
hostmakedepends = ["cmake", "ninja", "pkgconf"]
makedepends = ["libexpat-devel", "zlib-devel"]
pkgdesc =... | pkgname = 'exiv2'
pkgver = '0.27.5'
pkgrel = 0
build_style = 'cmake'
configure_args = ['-DEXIV2_BUILD_SAMPLES=OFF', '-DEXIV2_ENABLE_BMFF=ON', '-DEXIV2_BUILD_UNIT_TESTS=OFF']
make_check_target = 'unit_test'
hostmakedepends = ['cmake', 'ninja', 'pkgconf']
makedepends = ['libexpat-devel', 'zlib-devel']
pkgdesc = 'Image me... |
def yaml_write(data, filename):
f = open(filename, "w+")
for key in data:
f.write(f"{key}:\n- {data[key]}\n")
def yaml_read(data, filename):
try:
with open(filename) as f:
for lineKey in f:
key = lineKey[:-2]
lineVal = next(f)
val... | def yaml_write(data, filename):
f = open(filename, 'w+')
for key in data:
f.write(f'{key}:\n- {data[key]}\n')
def yaml_read(data, filename):
try:
with open(filename) as f:
for line_key in f:
key = lineKey[:-2]
line_val = next(f)
va... |
class WorkflowClient:
""" Client used for all the operations that can be done to the workflow module.
"""
def __init__(self, session):
self.session = session
def users(self):
""" Gets list of users.
"""
return self.session.get('/workflow/users/')
def campaigns(self,... | class Workflowclient:
""" Client used for all the operations that can be done to the workflow module.
"""
def __init__(self, session):
self.session = session
def users(self):
""" Gets list of users.
"""
return self.session.get('/workflow/users/')
def campaigns(self... |
"""A module for loading crate universe dependencies"""
load("@rules_rust//crate_universe:defs.bzl", "crate", "crate_universe")
def deps():
crate_universe(
name = "basic_deps",
packages = [
crate.spec(
name = "lazy_static",
semver = "=1.4",
),... | """A module for loading crate universe dependencies"""
load('@rules_rust//crate_universe:defs.bzl', 'crate', 'crate_universe')
def deps():
crate_universe(name='basic_deps', packages=[crate.spec(name='lazy_static', semver='=1.4')], supported_targets=['x86_64-apple-darwin', 'x86_64-unknown-linux-gnu']) |
def get_soundex(name):
"""Get the soundex code for the string"""
name = name.upper()
soundex = ""
soundex += name[0]
dictionary = {"BFPV": "1", "CGJKQSXZ":"2", "DT":"3", "L":"4", "MN":"5", "R":"6", "AEIOUHWY":"."}
for char in name[1:]:
for key in dictionary.keys():
if char in... | def get_soundex(name):
"""Get the soundex code for the string"""
name = name.upper()
soundex = ''
soundex += name[0]
dictionary = {'BFPV': '1', 'CGJKQSXZ': '2', 'DT': '3', 'L': '4', 'MN': '5', 'R': '6', 'AEIOUHWY': '.'}
for char in name[1:]:
for key in dictionary.keys():
if c... |
#!/usr/bin/python3
class ParsedUniversalDependencies(object):
"""Represents the parsed Universal Dependencies information from a sentence.
For more infomration on Universal Dependencies parts-of-speech (POS) tags, see
https://universaldependencies.org/u/pos/index.html .
"""
def __init__(self,
... | class Parseduniversaldependencies(object):
"""Represents the parsed Universal Dependencies information from a sentence.
For more infomration on Universal Dependencies parts-of-speech (POS) tags, see
https://universaldependencies.org/u/pos/index.html .
"""
def __init__(self, adj: str=None, adp: str... |
def compress(iterable, mask):
index = 0
while index != len(iterable):
if mask[index] is True:
yield iterable[index]
index += 1
arr_2 = list(compress(["Ivo", "Rado", "Panda"], [True, False, True]))
print(arr_2)
| def compress(iterable, mask):
index = 0
while index != len(iterable):
if mask[index] is True:
yield iterable[index]
index += 1
arr_2 = list(compress(['Ivo', 'Rado', 'Panda'], [True, False, True]))
print(arr_2) |
t=int(input())
t1=0
a=[0]*54
a[1]=2
a[2]=3
a[3]=5
for i in range(4,54):
a[i]=a[i-1]+a[i-2]
while(t1!=t):
t1=t1+1
n=int(input())
print("Scenario #"+str(t1)+":",end="",sep="")
print()
print(a[n])
print()
| t = int(input())
t1 = 0
a = [0] * 54
a[1] = 2
a[2] = 3
a[3] = 5
for i in range(4, 54):
a[i] = a[i - 1] + a[i - 2]
while t1 != t:
t1 = t1 + 1
n = int(input())
print('Scenario #' + str(t1) + ':', end='', sep='')
print()
print(a[n])
print() |
class Heap(object):
def __init__(self, array = []):
self.array = array
def insert(self, value):
pass
class Min_Heap(Heap):
def __init__(self, array):
super().__init__(array)
def insert(self, value):
self.array.append(value)
pos = len(... | class Heap(object):
def __init__(self, array=[]):
self.array = array
def insert(self, value):
pass
class Min_Heap(Heap):
def __init__(self, array):
super().__init__(array)
def insert(self, value):
self.array.append(value)
pos = len(self.array) - 1
whi... |
class Dependency:
"""
Information about a change or patchset dependency
Schema described here
https://gerrit-review.googlesource.com/Documentation/json.html#dependency
"""
def __init__(self, jsonObject):
self._id = jsonObject.get("id", None)
self._number = jsonObject.get("numbe... | class Dependency:
"""
Information about a change or patchset dependency
Schema described here
https://gerrit-review.googlesource.com/Documentation/json.html#dependency
"""
def __init__(self, jsonObject):
self._id = jsonObject.get('id', None)
self._number = jsonObject.get('numbe... |
def getDeviceConfigs(deviceIdentifier=''):
# TODO read from separate yaml file
# TODO validate configuration for missing/invalid values and for uniqueness property 'uniquePrefix'
deviceConfigs = [
{
'patchConfType': 'csv',
'uniquePrefix': 'wb12',
'vendor': 'Waldo... | def get_device_configs(deviceIdentifier=''):
device_configs = [{'patchConfType': 'csv', 'uniquePrefix': 'wb12', 'vendor': 'Waldorf', 'model': 'Blofeld', 'yearOfConstruction': 2007, 'patchSetName': 'Factory 2012', 'midiPort': 3, 'midiChannel': 11, 'color': 'darkgoldenrod', 'csvPath': 'csv/patchlist/Waldorf - Blofeld... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Pieter Huycke
email: pieter.huycke@ugent.be
GitHub: phuycke
"""
#%%
distance_from_sun = 16637000000 # distance at 25/09/2009 in miles
voyager_velocity = 38241 # voyager velocity in miles/hour
days_since_september = int(input('Days passed sin... | """
@author: Pieter Huycke
email: pieter.huycke@ugent.be
GitHub: phuycke
"""
distance_from_sun = 16637000000
voyager_velocity = 38241
days_since_september = int(input('Days passed since 25/09/2009: '))
hours_since_september = days_since_september * 24
current_distance_imperial = hours_since_september * voyager_veloc... |
# Hello WOrld
print("Hello World")
x = 1
if x == 1:
print("X = 1")
| print('Hello World')
x = 1
if x == 1:
print('X = 1') |
class NoiseMapTile:
"""
A tile in a noise map. Consists of an X and Y position
as well as a noise value that can be interpreted however
you like.
A low noise value = low terrain, a high one = high terrain.
"""
def __init__(self, x, y, noise_value):
self.x = x
self.y = y
... | class Noisemaptile:
"""
A tile in a noise map. Consists of an X and Y position
as well as a noise value that can be interpreted however
you like.
A low noise value = low terrain, a high one = high terrain.
"""
def __init__(self, x, y, noise_value):
self.x = x
self.y = y
... |
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
slow = 0
for fast in range(len(nums)):
if nums[fast] != 0:
nums[fast], nums[slow] = nums[sl... | class Solution(object):
def move_zeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
slow = 0
for fast in range(len(nums)):
if nums[fast] != 0:
(nums[fast], nums[slow]) = (nu... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright 2017 Fedele Mantuano (https://www.linkedin.com/in/fmantuano/)
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/... | """
Copyright 2017 Fedele Mantuano (https://www.linkedin.com/in/fmantuano/)
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 applic... |
# -*- coding: utf-8 -*-
"""
Created on Sun May 12 17:15:43 2019
@author: yoelr
"""
# def cartesian_samples(parameter_values):
# tuple_ = tuple
# initial_sample = []
# sorted_ = sorted
# paramvals = []
# for args in parameter_values:
# args = sorted_(args)
# paramvals.append(args)
# ... | """
Created on Sun May 12 17:15:43 2019
@author: yoelr
""" |
def state_update(S, K, i_round):
for i in range (i_round):
feedback = S[0] ^ S[47] ^ (0x1 - (S[70] & S[85])) ^ S[91] ^ (K[(i % klen)])
for j in range(127):
S.insert(0, S.pop())
# print(S)
S[127] = feedback
return S
#128-bit key
#96-bit nonce
#64-bit tag
#128-bit ... | def state_update(S, K, i_round):
for i in range(i_round):
feedback = S[0] ^ S[47] ^ 1 - (S[70] & S[85]) ^ S[91] ^ K[i % klen]
for j in range(127):
S.insert(0, S.pop())
S[127] = feedback
return S
klen = 128
s = [0] * 128
k = [0] * 128
a = state_update(S, K, 2048) |
# Copyright 2021 Garena Online Private Limited
#
# 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 agr... | """EnvPool workspace initialization, load after workspace0."""
load('@pybind11_bazel//:python_configure.bzl', 'python_configure')
load('@rules_foreign_cc//foreign_cc:repositories.bzl', 'rules_foreign_cc_dependencies')
load('@mypy_integration//repositories:repositories.bzl', mypy_integration_repositories='repositories')... |
class Post:
id = None # type: str
date_submitted = None # type: str
user = None # type: str
message = None # type: str
sentiment = None # type: float
url = None
| class Post:
id = None
date_submitted = None
user = None
message = None
sentiment = None
url = None |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class Office365SourceTypesEnum(object):
"""Implementation of the 'Office365SourceTypes' enum.
Filter by Office365 types such as 'kUser', 'kSite', etc.
Only items from the specified source types are returned.
Attributes:
KDOMAIN: TODO: ty... | class Office365Sourcetypesenum(object):
"""Implementation of the 'Office365SourceTypes' enum.
Filter by Office365 types such as 'kUser', 'kSite', etc.
Only items from the specified source types are returned.
Attributes:
KDOMAIN: TODO: type description here.
KOUTLOOK: TODO: type descrip... |
# Copyright 2017 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... | """Unit tests for shell.bzl."""
load('//:lib.bzl', 'asserts', 'shell', 'unittest')
def _shell_array_literal_test(ctx):
"""Unit tests for shell.array_literal."""
env = unittest.begin(ctx)
asserts.equals(env, '()', shell.array_literal([]))
asserts.equals(env, "('1')", shell.array_literal([1]))
assert... |
def get_gene_background_header(global_variables):
header_list = []
# adds the background information
if global_variables["GENE_SYMBOL_FLAG"]:
header_list.append("symbol")
if global_variables["GENE_BIOTYPE_FLAG"]:
header_list.append("biotype")
if global_variables["GENE_CHROMOSOME_FL... | def get_gene_background_header(global_variables):
header_list = []
if global_variables['GENE_SYMBOL_FLAG']:
header_list.append('symbol')
if global_variables['GENE_BIOTYPE_FLAG']:
header_list.append('biotype')
if global_variables['GENE_CHROMOSOME_FLAG']:
header_list.append('chromo... |
# sum all numbers in lista until the first even (included)
lista=[1, 5, -2, 'Hey', 4, 3, 7]
summa = 0
for elem in lista:
if type(elem) is int:
summa += elem
if elem % 2 == 0:
break
print('The sum until the first even included is:', summa)
| lista = [1, 5, -2, 'Hey', 4, 3, 7]
summa = 0
for elem in lista:
if type(elem) is int:
summa += elem
if elem % 2 == 0:
break
print('The sum until the first even included is:', summa) |
al=0
gas=0
die=0
while True:
codigo=int(input())
if(codigo==1):
al=al+1
elif(codigo==2):
gas=gas+1
elif(codigo==3):
die=die+1
elif(codigo==4):
break
print(f"MUITO OBRIGADO\nAlcool:{al}\nGasolina: {gas}\nDiesel: {die}") | al = 0
gas = 0
die = 0
while True:
codigo = int(input())
if codigo == 1:
al = al + 1
elif codigo == 2:
gas = gas + 1
elif codigo == 3:
die = die + 1
elif codigo == 4:
break
print(f'MUITO OBRIGADO\nAlcool:{al}\nGasolina: {gas}\nDiesel: {die}') |
'''
Created on Feb 24, 2016
@author: T0157129
'''
'''
Cast a string into boolean.
The trueVal list represents the accepted values for True.
Return the boolean value.
'''
def strToBool(string):
trueVal=['True', 'true', 't', '1']
if string in trueVal:
return True
else:
return Fa... | """
Created on Feb 24, 2016
@author: T0157129
"""
'\n Cast a string into boolean.\n The trueVal list represents the accepted values for True.\n Return the boolean value.\n'
def str_to_bool(string):
true_val = ['True', 'true', 't', '1']
if string in trueVal:
return True
else:
retur... |
class HardWorker(object):
u"Almost Sisyphos"
def __init__(self, task):
self.task = task
def work_hard(self, repeat=100):
for i in range(repeat):
self.task()
def add_simple_stuff():
x = 1+1
HardWorker(add_simple_stuff).work_hard(repeat=100)
# cython worker.py | class Hardworker(object):
u"""Almost Sisyphos"""
def __init__(self, task):
self.task = task
def work_hard(self, repeat=100):
for i in range(repeat):
self.task()
def add_simple_stuff():
x = 1 + 1
hard_worker(add_simple_stuff).work_hard(repeat=100) |
student_list1 = ['tim', 'drake', 'ashish', 'shubham']
student_list2 = ['andrew', 'harshit', 'lary', 'shubham', 'chris']
def checkStudent(student_list2):
for student in student_list2:
if student == 'chris':
print('Available')
checkStudent(student_list2) | student_list1 = ['tim', 'drake', 'ashish', 'shubham']
student_list2 = ['andrew', 'harshit', 'lary', 'shubham', 'chris']
def check_student(student_list2):
for student in student_list2:
if student == 'chris':
print('Available')
check_student(student_list2) |
def Insertion_sort(list):
for i in range(1,len(list)):
j = i - 1
temp=list[i]
while j >= 0 and temp < list[j]:
list[j + 1] = list[j]
j = j - 1
list[j+1]=temp
return list
if __name__ == "__main__":
list= [8,4,23,42,16,15]
print(Insertion_sort(li... | def insertion_sort(list):
for i in range(1, len(list)):
j = i - 1
temp = list[i]
while j >= 0 and temp < list[j]:
list[j + 1] = list[j]
j = j - 1
list[j + 1] = temp
return list
if __name__ == '__main__':
list = [8, 4, 23, 42, 16, 15]
print(insertio... |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 23 10:16:07 2020
@author: Ruben Andre Barreiro
"""
# Open the File 'planets.csv'
file = open('../files/planets.csv')
# Read the Lines, from the File 'planets.csv'
lines = file.readlines()
# Close the File 'planets.csv',
# after read their lines
file.close()
# Read a ... | """
Created on Wed Sep 23 10:16:07 2020
@author: Ruben Andre Barreiro
"""
file = open('../files/planets.csv')
lines = file.readlines()
file.close()
lines
print(lines)
def planet_period(planet):
lines = open('../files/planets.csv').readlines()
for line in lines:
parts = line.split(',')
if parts... |
# https://www.hackerrank.com/challenges/ctci-ransom-note/problem
def checkMagazine(magazine, note):
magazine.sort()
note.sort()
for w in note:
if not w in magazine:
print("No")
return
else:
magazine.remove(w)
print("Yes")
magazine = input().rstrip().... | def check_magazine(magazine, note):
magazine.sort()
note.sort()
for w in note:
if not w in magazine:
print('No')
return
else:
magazine.remove(w)
print('Yes')
magazine = input().rstrip().split()
note = input().rstrip().split()
check_magazine(magazine, n... |
"""
[2015-10-30] Challenge #238 [Hard] Searching a Dungeon
https://www.reddit.com/r/dailyprogrammer/comments/3qtr01/20151030_challenge_238_hard_searching_a_dungeon/
# Description
Our hero is lost in a dungeon. You will be given ASCII maps of a few floors, her starting position, and her goal. On
some floors there are ... | """
[2015-10-30] Challenge #238 [Hard] Searching a Dungeon
https://www.reddit.com/r/dailyprogrammer/comments/3qtr01/20151030_challenge_238_hard_searching_a_dungeon/
# Description
Our hero is lost in a dungeon. You will be given ASCII maps of a few floors, her starting position, and her goal. On
some floors there are ... |
"""
Provide implementation of the receipt interfaces.
"""
class ReceiptInterface:
"""
Implements receipt interface.
"""
def get(self, identifiers):
"""
Get a list of the transaction's receipts by identifiers.
"""
pass
| """
Provide implementation of the receipt interfaces.
"""
class Receiptinterface:
"""
Implements receipt interface.
"""
def get(self, identifiers):
"""
Get a list of the transaction's receipts by identifiers.
"""
pass |
class Bird:
def __init__(self, id, name):
self.id = id
self.name = name
def intro(self):
print("There are many types of birds.")
def flight(self):
print("Most of the birds can fly but some cannot.")
class Sparrow(Bird):
def __init__(self, id, name, age,... | class Bird:
def __init__(self, id, name):
self.id = id
self.name = name
def intro(self):
print('There are many types of birds.')
def flight(self):
print('Most of the birds can fly but some cannot.')
class Sparrow(Bird):
def __init__(self, id, name, age, factor):
... |
# [Silent Crusade] Into the Gate
STARLING = 9120221
sm.setSpeakerID(STARLING)
response = sm.sendAskYesNo("I bet this weird gate has something to do with all the monsters going crazy. I think we oughtta take a closer look. You ready?")
if response:
sm.sendNext("I'm counting on you to keep me safe from the big, ba... | starling = 9120221
sm.setSpeakerID(STARLING)
response = sm.sendAskYesNo('I bet this weird gate has something to do with all the monsters going crazy. I think we oughtta take a closer look. You ready?')
if response:
sm.sendNext("I'm counting on you to keep me safe from the big, bad, scary monsters! Let's go!")
s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.