content stringlengths 7 1.05M |
|---|
##!FAIL: UnsupportedNodeError[Return]@5:4
def f(x):
""" int -> NoneType """
return
|
#Defining a hash function
"""def get_hash(key):
h=0
for char in key:
h += ord(char)
return h%100
print(get_hash("hirwa"))
"""
#Creating a hash Table class
class Hashtable:
def __init__(self):
self.MAX=100
self.arr=[None for i in range(self.MAX)]
def get_hash(self,key):
... |
# Name, Variables, Functions
def print_two(*args):
arg1, arg2 = args
print(f"arg1: {arg1}, arg2: {arg2}")
print(f"Type1: {type(arg1)}. Type2: {type(arg2)}")
def print_take_2(one, two):
print(f"Value1: {one}, Value2: {two}")
def print_take_1(one):
print(f"Value: {one}")
def print_none():
... |
COL_WITH_NAN_SIGNIFICATION = ["BsmtQual", "BsmtCond", "BsmtExposure",
"BsmtFinType1", "BsmtFinType2", "GarageType",
"GarageFinish", "GarageQual", "GarageCond",
"PoolQC", "Fence", "MiscFeature", "Alley"]
CONTINUOUS_COL = ["LotFron... |
num = int(input("Digite um valor: "))
ant = num - 1
sus = num + 1
print(f"Analisando o valor {num}, o seu antecessor é {num - 1} e o sucessor é {num + 1}.")
|
lista_telefonica = {}
def lista(nome):
if nome in lista_telefonica:
print(f'Nome: {nome.title()} - Número: {lista_telefonica[nome]}')
else:
pergunta = str(input('Não existe esse nome na lista, quer gravar? '))
if pergunta == 'sim':
numero = input('Digite o número de telefone:... |
def dec2bin(x):
cache = []
res = ''
while x:
num = x % 2
x = x // 2
cache.append(num)
while cache:
res += str(cache.pop())
return res
print(dec2bin(10),bin(10))
|
_config = {}
def Get(key):
global _config
return _config[key]
def Set(key, value):
global _config
_config[key] = value
|
n1 = float(input('Escreva um valor em metros:'))
cm = n1 * 100
mm = n1 * 1000
print(f'o valor em centimetro é: {cm} e o valor em milímetros é: {mm}')
print(f'o valor em metros é:{n1}')
|
class Case:
def __init__(self, number: str, status: str, title: str, body: str):
self.number = number
self.status = status
self.title = title
self.body = body
|
def update_transition_matrix(self, opponent_move):
global POSSIBLE_MOVES
if len(self.moves) <= len(LAST_POSSIBLE_MOVES[0]):
return None
for i in range(len(self.transition_sum_matrix[self.last_moves])):
self.transition_sum_matrix[self.last_moves][i] *= self.decay
self.transition_sum_matri... |
class Vertex:
def __init__(self, name):
self.name = name
class Graph:
vertices = {}
edges = []
edge_indices = {}
def add_vertex(self, vertex):
if isinstance(vertex, Vertex) and vertex.name not in self.vertices:
self.vertices[vertex.name] = vertex
for row ... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def sortList(self, head: ListNode) -> ListNode:
if not head:
return
if head.next == None:
return head
def find_mid(h... |
def parse(input_file):
with open(input_file, 'r') as f:
return f.read().split('\n\n')
def clean_input(answers):
return [a.replace('\n', '') for a in answers]
def get_uniques(answers):
return [set(a) for a in answers]
def get_unique_count(answers):
return [len(a) for a in answers]
def get_agr... |
fib_num= lambda n:fib_num(n-1)+fib_num(n-2) if n>2 else 1
print(fib_num(6))
def test1_fib_num():
assert (fib_num(6)==8)
def test2_fib_num():
assert (fib_num(5)==5)
def test3_fib_num():
n = 10
assert (fib_num(2*n)==fib_num(n+1)**2 - fib_num(n-1)**2)
|
# cohort.migrations
# Cohort app database migrations.
#
# Author: Benjamin Bengfort <benjamin@bengfort.com>
# Created: Thu Dec 26 15:06:39 2019 -0600
#
# Copyright (C) 2019 Georgetown University
# For license information, see LICENSE.txt
#
# ID: __init__.py [] benjamin@bengfort.com $
"""
Cohort app database migrati... |
# Given a non-empty array of integers, every element appears twice except for one. Find that single one.
# Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
# Input: [2,2,1]
# Output: 1
# Input: [4,1,2,1,2]
# Output: 4
# Input: [1,1,4,4,6,6,7]
# Output: 7 Spa... |
people = ['Jonas', 'Julio', 'Mike', 'Mez']
ages = [25, 30, 31, 39]
for person, age in zip(people, ages):
print(person, age)
|
def main() -> None:
n = int(input())
s = [list(map(lambda x: int(x) - 1, input())) for _ in range(n)]
time = [[-1] * 10 for _ in range(n)]
for i in range(n):
for j in range(10):
time[i][s[i][j]] = j
mn = 1 << 60
for d in range(10):
count = [0] * 10
... |
#!/usr/bin/env python
"""
Created by howie.hu at 2021-04-08.
Description:字符级CNN分类模型实现
论文地址:https://arxiv.org/pdf/1509.01626.pdf
Changelog: all notable changes to this file will be documented
"""
|
# encoding: utf-8
print("I will now count my chickens:")
print("Hens", 25 + 30 / 6)
print("Roosters", 100 - 25 * 3 % 4)
print("Now I will count the eggs:")
print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
print("Is it true that 3 + 2 < 5 - 7?")
print(3 + 2 < 5 - 7)
print("What is 3 + 2?", 3 + 2)
print("What is 5 - 7?", ... |
'''
1) Create a Clusterfile
2) Add metadata to created Clusterfile
3) Create a bunch of Datasets
- Add them to created Clusterfile
'''
|
class EurecomDataset(Dataset):
def __init__(self,domain,variation,training_dir=None,transform=None):
self.transform = transform
self.training_dir = training_dir
# For each variant keep a list
self.thermal_illu = []
self.thermal_exp = []
self.thermal_pose = []
... |
#!/usr/bin/env python3
# ex31: Making Decisions
print("You enter a dark room with two doors. Do you go through door #1 or door #2?")
door = input("> ")
if door == "1":
print("There's a giant bear here eating a cheese cake. What do you do?")
print("1. Take the cake.")
print("2. Scream at the bear.")
... |
"""This problem was asked by Facebook.
Suppose you are given two lists of n points, one list p1, p2, ..., pn on the
line y = 0 and the other list q1, q2, ..., qn on the line y = 1.
Imagine a set of n line segments connecting each point pi to qi.
Write an algorithm to determine how many pairs of the line segments in... |
class item:
def __init__(self, name, cap, dur, flav, text, cal):
self.name = name
self.cap = cap
self.dur = dur
self.fla = flav
self.tex = text
self.cal = cal
return
it = [item('Frosting', 4, -2, 0, 0, 5),
item('Candy', 0, 5, -1, 0, 8),
item('Butterscotch', -1, 0, 5, 0, 6),
... |
t = int(input())
for _ in range(t):
n = int(input())
s = input()
s = list(s)
index = 0
while index < n - 1:
s[index], s[index + 1] = s[index + 1], s[index]
index += 2
for i in range(n):
s[i] = chr(ord('z') - (ord(s[i]) - ord('a')))
print("".join(s))
|
# -*- coding: utf-8 -*-
"""
sub_analysis_proxy.py generated by WhatsOpt.
"""
|
"""
James Haywood, Unit 4.01
This unit was pretty good, especially the logic lab. That was fun, if a
bit OCD-inducing with the wire layout (you know what I mean.) Assignment 3
seemed almost too easy though, so I'd make that tougher.
"""
|
# -*- coding: utf-8 -*-
# Author: Jiajun Ren <jiajunren0522@gmail.com>
electron = "e"
electrons = "es"
phonon = "ph"
class EphTable(tuple):
@classmethod
def all_phonon(cls, site_num):
return cls([phonon] * site_num)
@classmethod
def from_mol_list(cls, mol_list, scheme):
eph_list = ... |
sentence = 'This awesome spaghetti is awesome'
better_sentence = sentence.replace('awesome', 'fabulous')
print(better_sentence)
date = '12/01/2035'
print(date.replace('/', '-'))
|
# if you have a list = [], or a string = '', it will evaluate as a False value
our_list = []
our_string = ''
if our_list:
print('This list has something in it.')
if our_string:
print('This string is not empty.')
teams = ['knicks', 'kings', 'heat', 'pacers', 'celtics', 'pelicans']
for team in teams:
if team.star... |
class Node:
def __init__(self, key, value):
self.key = key
self.val = value
self.next = self.pre = None
self.pre = None
class LRUCache:
def remove(self, node):
node.pre.next, node.next.pre = node.next, node.pre
self.dic.pop(node.key)
def add(self, nod... |
TOKENIZE_TEXT_INPUT_SCHEMA = {
"type": "object",
"properties": {
"text": {"type": "string"},
},
"required": ["text"],
"additionalProperties": False
}
TOKENIZE_TEXT_OUTPUT_SCHEMA = {
"type": "array",
"items": {
"type": "array",
"items": {
"type": "array",
... |
class Solution:
def convertToTitle(self, n: int) -> str:
return self.solution1(n)
def solution1(self, n: int) -> str:
ans = []
while n > 0:
n, r = divmod(n-1, 26)
ans.append(chr(r + ord('A')))
return ''.join(ans[::-1])
# time limit exceeded
def s... |
# You are given a set of positive numbers and a target sum ‘S’.
# Each number should be assigned either a ‘+’ or ‘-’ sign.
# We need to find the total ways to assign symbols to make the sum of the numbers equal to the target ‘S’.
# Example:
# Input: {1, 1, 2, 3}, S=1
# Output: 3
# Explanation: The given set has '3' ... |
"""Prediction of Optimal Price based on Listing Properties"""
def get_optimal_pricing(**listing):
''' Just return 100 for now - will call out to a proper predictive model later'''
print(listing)
price = listing.get('price', 0)
price = price+10 if price else 100
return price |
def print_separator():
#print('--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------')
print('')
def print_components_menu(generate, download, convert, c... |
def validate_morph(morph):
if not "key" in morph:
print(" - key is missing")
return False
if not "type" in morph:
print(" - type is missing")
return False
if not "origin" in morph:
print(" - origin is missing")
return False
morph_type = morph["type"]
... |
num = int(raw_input("Enter a number: "))
fact=1;
for i in range(num ,1,-1):
fact *= i
print(fact)
|
CMD_GROUP_CONFIG = {
"auth": "Command group for generating authorization tokens",
"sys": "Command group for Mix API system scope",
"ns": "Command group for Mix namespace",
'project': "Command group for Mix API project scope",
'channel': "Command group for Mix API (project) channel scope",
'job':... |
n=int(input());r=0;k=2
n*=2
while n>=k:
r+=k*(n//k-n//(2*k))
k*=2
print(r)
|
# -*- coding: utf-8 -*-
"""Pystapler: application server framework for Python.
This framework is inspired by Kohsuke Kawaguchi's Stapler framework for Java
(stapler.kohsuke.org), but obviously adapted to Python. It implements WSGI
support using the popular Werkzeug utility library.
See the README.md file for more inf... |
JINJA_FUNCTIONS = []
def add_jinja_global(arg=None):
def decorator(func):
JINJA_FUNCTIONS.append(func)
return func
if callable(arg):
return decorator(arg) # return 'wrapper'
else:
return decorator # ... or 'decorator'
|
'''
Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below.
American keyboard
Example 1:
Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]
'''
class Solution(object):
def findWords(self, words):
... |
ALL_EVENTS = """
query (
$studyId: String,
$fileId: String,
$versionId: String,
$createdAt_Gt: DateTime,
$createdAt_Lt: DateTime,
$username: String,
$eventType: String,
) {
allEvents(
studyKfId: $studyId,
fileKfId: $fileId,
versionKfId: $versionId,
created... |
"""
Given an array S of n integers, are there elements a, b, c in S
such that a + b + c = 0?
Find all unique triplets in the array which gives the sum of zero.
Note: The solution set must not contain duplicate triplets.
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1,... |
class Solution:
def minPathSum(self, grid):
'''
the first row each column equal the sum of itself with the previous colmuns.
The same applied for the first column, the first column of each row equals the sume of itself with the previous ones in.
'''
rows, cols = len(grid), le... |
# Modified from: https://github.com/junit-team/junit5-samples/tree/master/junit5-jupiter-starter-bazel
load("@rules_jvm_external//:defs.bzl", "DEFAULT_REPOSITORY_NAME")
load("@rules_jvm_external//:specs.bzl", "maven")
load("//tools:maven_utils.bzl", "format_maven_jar_dep_name", "format_maven_jar_name")
"""External de... |
class Morton(object):
def __init__(self, dimensions=2, bits=32):
assert dimensions > 0, 'dimensions should be greater than zero'
assert bits > 0, 'bits should be greater than zero'
def flp2(x):
'''Greatest power of 2 less than or equal to x, branch-free.'''
x |= x ... |
config = {
'http': {
'400': '400 Bad Request',
'401': '401 Unauthorized',
'500': '500 Internal Server Error',
'503': '503 Service Unavailable',
},
}
|
loss_window = vis.line(
Y=torch.zeros((1),device=device),
X=torch.zeros((1),device=device),
opts=dict(xlabel='epoch',ylabel='Loss',title='training loss',legend=['Loss']))
vis.line(X=torch.ones((1,1),device=device)*epoch,Y=torch.Tensor([epoch_loss],device=device).unsqueeze(0),win=loss_window,update='append')
|
### PRIMITIVE
class fixed2:
def __init__(self, xu = 0.0, yv = 0.0):
self.two = [xu, yv]
def __copy__(self):
return fixed2(*self.two[:])
def __str__(self):
return str(self.two)
@property
def x(self):
return self.two[0]
@x.setter
def x(self, value):
... |
def test_get_work_serie(work_object_serie):
details = work_object_serie.get_details()
assert isinstance(details, dict)
assert len(details) == 19
def test_rating_work_serie(work_object_serie):
main_rating = work_object_serie.get_main_rating()
assert isinstance(main_rating, str)
assert main_rati... |
def common_function():
print('This is coming from the common function')
return 'Hello Common'
|
def acos(): pass
def acosh(): pass
def asin(): pass
def asinh(): pass
def atan(): pass
def atanh(): pass
def cos(): pass
def cosh(): pass
def exp(): pass
def isinf(): pass
def isnan(): pass
def log(): pass
def log10(): pass
def phase(): pass
def polar(): pass
def rect(): pass
def sin(): pass
def sinh()... |
def sumOfTwo(a, b, v):
# result = {True for x in a for y in b if x + y == v}
# print(type(result))
# print(result)
# return True if True in result else False
for i in a:
for j in b:
if i + j == v:
return True
return False
a = [0, 1, 2, 3]
b = [1... |
class PrefixUnaryExpressionSyntax(object):
def __init__(self, kind, operator_token, operand):
self.kind = kind
self.operator_token = operator_token
self.operand = operand
def __str__(self):
return f"{self.operator_token}{self.operand}"
|
'''
Escreva um programa que leia um valor inteiro N. Este N é a quantidade de linhas de saída que serão apresentadas na execução do programa.
Entrada
O arquivo de entrada contém um número inteiro positivo N.
Saída
Imprima a saída conforme o exemplo fornecido.
'''
N = int(input())
cont = 1
for i in range(N):
pri... |
#
# PySNMP MIB module CISCO-PAE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-PAE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:09:18 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... |
arr = list(map(int, input().split()))
flag=True
for i in range(len(arr)):
if arr[i]!=arr[len(arr)-1-i]:
flag=False
break
if flag:
print('symmetric')
else:
print('not symmetric') |
def selectionSort(lst):
for selectedLocation in range(len(lst)-1,0,-1):
maxPosition=0
for currentindex in range(1,selectedLocation+1): #since range(0,4) is exclusive to 4
if lst[currentindex]>lst[maxPosition]:
maxPosition = currentindex
lst[selectedLocation], lst[ma... |
def get_coupons(self):
return self.handle_response(
self.request("/coupons"),
"coupons"
)
def create_coupon(self, **kwargs):
return self.handle_response(
self.request("/coupons", "POST", kwargs),
"uniqid"
)
def get_coupon(self, uniqid):
return self.handle_response... |
def main() -> None:
if __name__ == "__main__":
champernownes_constant = ''.join(str(x) for x in range(1, 1_000_000 + 1))
ans = int(champernownes_constant[1 - 1])
ans *= int(champernownes_constant[10 - 1])
ans *= int(champernownes_constant[100 - 1])
ans *= int(champernownes_c... |
def remove_every_other(lst):
"""Return a new list of other item.
>>> lst = [1, 2, 3, 4, 5]
>>> remove_every_other(lst)
[1, 3, 5]
This should return a list, not mutate the original:
>>> lst
[1, 2, 3, 4, 5]
"""
return lst[::2]
lst = [1, 2, 3, 4, 5]
print(F"remo... |
# coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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 applicab... |
nome = str(input('Digite o seu nome completo: ')).title().strip()
print('Muito prazer em te conhecer, {}!!'.format(nome))
separa = nome.split()
print('Seu primeiro nome é: {}'.format(separa[0]))
print('Seu último nome é: {}'.format(separa[len(separa)-1]))
|
"""
PASSENGERS
"""
numPassengers = 3168
passenger_arriving = (
(3, 6, 9, 6, 1, 0, 8, 5, 3, 4, 5, 0), # 0
(4, 10, 5, 4, 2, 0, 4, 5, 6, 5, 3, 0), # 1
(4, 6, 6, 4, 2, 0, 6, 12, 3, 6, 1, 0), # 2
(3, 6, 9, 1, 2, 0, 2, 10, 1, 5, 0, 0), # 3
(5, 6, 8, 6, 3, 0, 2, 7, 9, 4, 1, 0), # 4
(4, 5, 6, 2, 2, 0, 4, 8, 3, 4,... |
ies = []
ies.append({ "ie_type" : "Node ID", "ie_value" : "Node ID", "presence" : "M", "instance" : "0", "comment" : "This IE shall contain the unique identifier of the sending Node."})
ies.append({ "ie_type" : "Cause", "ie_value" : "Cause", "presence" : "M", "instance" : "0", "comment" : "This IE shall indicate the ac... |
# coding: utf-8
# # Variable Types - Boolean
# In the last lesson we learnt how to index and slice strings. We also learnt how to use some common string functions such as the <code>len()</code> function.
#
# In this lesson, we'll learn about Boolean values. Boolean values evaluate to either True or False and are co... |
RAW_PATH = "./data/raw/"
INTERIM_PATH = "./data/interim/"
REFINED_PATH = "./data/refined/"
EXTERNAL_PATH = "./data/external/"
SUBMIT_PATH = "./data/submission/"
MODELS_PATH = "./data/models/"
CAL_DTYPES = {
"event_name_1": "category",
"event_name_2": "category",
"event_type_1": "category",
"event_type... |
# model settings
norm_cfg = dict(type='SyncBN', requires_grad=True)
model = dict(
type='CascadeEncoderDecoder',
num_stages=2,
pretrained='open-mmlab://resnet50_v1c',
backbone=dict(
type='ResNetV1c',
depth=50,
num_stages=4,
out_indices=(0, 1, 2, 3),
dilations=(1, 1... |
# HEADER: graph-level graphviz/dot attributes, including
# - default node style (e.g. rounded boxes, ovals, etc)
# - default edge style
HEADER = """
digraph{
rankdir=LR
//ranksep=0.3
node[shape=box
style="rounded,filled"
fillcolor="#FFFFCC"
fontname=helvetica fontsize=12]
edge[fontname=cour... |
{
'variables': {
'chromium_code': 1,
'pdf_engine%': 0, # 0 PDFium
},
'target_defaults': {
'cflags': [
'-fPIC',
],
},
'targets': [
{
'target_name': 'pdf',
'type': 'loadable_module',
'msvs_guid': '647863C0-C7A3-469A-B1ED-AD7283C34BED',
'dependencies': [
... |
"""
Basic Heapsort program.
"""
def heapify(arr, n, i):
"""
Heapifies subtree rooted at index i
n - size of the heap
"""
largest = i
l = 2 * i + 1
r = 2 * i + 2
# see if left child of root exists and is
# greater than root
if l < n and arr[largest] < arr[l]:
largest =... |
initials = [
"b",
"c",
"ch",
"d",
"f",
"g",
"h",
"j",
"k",
"l",
"m",
"n",
"p",
"q",
"r",
"s",
"sh",
"t",
"w",
"x",
"y",
"z",
"zh",
]
finals = [
"a1",
"a2",
"a3",
"a4",
"a5",
... |
## -*- encoding: utf-8 -*-
"""
This file (./numbertheory_doctest.sage) was *autogenerated* from ./numbertheory.tex,
with sagetex.sty version 2011/05/27 v2.3.1.
It contains the contents of all the sageexample environments from this file.
You should be able to doctest this file with:
sage -t ./numbertheory_doctest.sage
I... |
class Translation(object):
START_TEXT = "**Bu bot isim değiştirme ve video dönüştürme botudur.\nDosyanın adını değiştirmek için bir medya göndermeniz yeterli\nDaha fazla ayrıntı için /help komutunu kullanın **"
######################
HELP_USER = """**>>Dosya veya Video gönderin\n>>istenen seçeneği seçin\n>>D... |
class Programa:
def __init__(self, nome, ano):
self._nome = nome.title()
self.ano = ano
self._likes = 0
@property
def likes(self):
return self.__likes
def dar_like(self):
self._likes += 1
@property
def nome(self):
return self._nome
@nome.se... |
# -*- coding: utf-8 -*-
def main():
s = input()
n = len(s)
ans = 0
for i in range(1, n + 1):
cur = s[i - 1]
if cur == 'U':
upper = 1
else:
upper = 2
ans += (n - i) * upper
if cur == 'U':
lower = 2
... |
'''
Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.
In a UNIX-style file system, a period . refers to the current directory. Furthermore, a double period .. moves the directory up a level.
Note that the returned canonical path must always begin with a ... |
#import In.entity
class Thodar(In.entity.Entity):
'''Thodar Entity class.
'''
entity_type = ''
entity_id = 0
#def __init__(self, data = None, items = None, **args):
#super().__init__(data, items, **args)
@IN.register('Thodar', type = 'Entitier')
class ThodarEntitier(In.entity.EntityEntitier):
'''Base T... |
""" Unification in SymPy
See sympy.unify.core docstring for algorithmic details
See http://matthewrocklin.com/blog/work/2012/11/01/Unification/ for discussion
"""
# from .usympy import unify, rebuild
# from .rewrite import rewriterule
|
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis
# orthologue
# (c) 1998-2020 all rights reserved
#
# class declaration
class Element:
"""
The base class for all HTML elements
"""
# public data
tag = None # the element tag, i.e. "div", "p", "table"
attributes = None # a dictionary that maps ... |
# Given an array of meeting time intervals consisting of start and end times
# [[s1,e1],[s2,e2],...] (si < ei), determine if a person could attend all meetings.
#
# Example 1:
#
# Input: [[0,30],[5,10],[15,20]]
# Output: false
# Example 2:
#
# Input: [[7,10],[2,4]]
# Output: true
class Solution:
def canAttendMeet... |
# Copyright 2015 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... |
class _Object(object):
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
def __repr__(self):
return "'%s'" % self.name
STRING = 'Hello world!'
INTEGER = 42
FLOAT = -1.2
BOOLEAN = True
NONE_VALUE = None
ESCAPES = 'one \\ two \\\\ ${non_existing}'
NO_VALUE... |
#!/usr/bin/python3
# iterators.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Group, LLC
def main():
fh = open('lines.txt')
for line in fh.readlines():
print(line)
if __name__ == "__main__": main()
|
def adder(num1, num2):
return num1 + num2
def main():
print(adder(5, 3))
main()
|
def _create(src, out):
"""Creates a `struct` specifying a source file and an output file that should be used to update it.
Args:
src: A `File` designating a file in the workspace.
out: A `File` designating a file in the output directory.
Returns:
A `struct`.
"""
return stru... |
class RateLimitExceeded(Exception):
def __init__(self, key: str, retry_after: float):
self.key = key
self.retry_after = retry_after
super().__init__()
|
#DEFINE ALL THE FORMS HERE AS JSON
#DEFINITIONS ARE LOADED AS DIJIT WIDGETS
#VARIABLES LISTED HERE AS DICTIONARY NEEDS TO BE IMPORTED BACK INTO MODELS.PY WHEN FORMS ARE DEFINED
TASK_DETAIL_FORM_CONSTANTS = {
'name':{
'max_length': 30,
"data-dojo-type": "dij... |
print('Digite M se for homem')
print('Digite F se for mulher')
sexo = str(input('Você é de qual sexo: '))
while sexo != 'M' and sexo != 'F':
sexo = str(input('Você digitou errado, digite novamente: '))
print('Está certo')
|
def standard_deviation(x):
n = len(x)
mean = sum(x) / n
ssq = sum((x_i-mean)**2 for x_i in x)
stdev = (ssq/n)**0.5
return(stdev)
|
m = int(input())
for i in range(0,m):
n = int(input())
bandera = True
for i in range(0,n):
temp = input()
for j in range(0,n):
if i==int(n/2):
if j==int(n/2):
if temp[j]!='#':
bandera=False
br... |
#This exercise is Part 2 of 4 of the Tic Tac Toe exercise series. The other exercises are: Part 1, Part 3, and Part 4.
#
#As you may have guessed, we are trying to build up to a full tic-tac-toe board. However, this is significantly more
# than half an hour of coding, so we’re doing it in pieces.
#
#Today, we will sim... |
# Use the file name mbox-short.txt as the file name
fname = input("Enter file name: ")
fh = open(fname)
avg = 0.0;
count = 0;
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue
pos = line.find(':');
substring = line[pos+1:];
snum = substring.strip();
num = float(snum);
... |
def factorial(num: int) -> int:
product = 1
for mult in range(1, num + 1):
product *= mult
return product
algorithm = factorial
name = 'for loop'
|
n = int(input())
for i in range(1, n+1, 2):
for j in range(i):
print("*", end="")
for j in range(n+n-i-i):
print(" ", end="")
for j in range(i):
print("*", end="")
print()
for i in range(n-2, 0, -2):
for j in range(i):
print("*", end="")
for j in range... |
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __lt__(self, other):
return self.x < other.x
def __str__(self):
return "(" + str(self.x) + "," + str(self.y) + ")"
def test():
points = [Point(2, 1), Point(1, 1)]
points.sort()
for p in points:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.