content stringlengths 7 1.05M |
|---|
#def divisor is from:
#https://www.w3resource.com/python-exercises/basic/python-basic-1-exercise-24.php
def divisor(n):
for i in range(n):
x = len([i for i in range(1, n+1) if not n % i])
return x
nums = []
i = 0
while i < 20:
preNum = int(input())
if(preNum > 0):
nums.append([diviso... |
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
low = 0
high = len(nums) - 1
while low <= high:
mid = (low + high)//2
if nums[mid] == target:
... |
s, t = 7, 11
a, b = 5, 15
m, n = 3, 2
apple = [-2, 2, 1]
orange = [5, -6]
a_score, b_score = 0, 0
''' too slow
for i in apple:
if (a + i) in list(range(s, t+1)):
a_score +=1
for i in orange:
if (b + i) in list(range(s, t+1)):
b_score +=1
'''
for i in apple:
if (a+i >= s) and (a+i <= t):
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File name: system.py
# Description: Basic System Functions
# Author: irreq (irreq@protonmail.com)
# Date: 17/12/2021
"""Documentation"""
def set_brightness(brightness):
"""Sets brightness for Thinkpad Laptop"""
if int(brightness) > 15:
raise TypeError(... |
class Customer:
id = 1
def __init__(self, name, address, email):
self.name = name
self.address = address
self.email = email
self.id = Customer.id
Customer.id += 1
def __repr__(self):
return f"Customer <{self.id}> {self.name}; Address: {self.address}; Email: ... |
SECRET_KEY = "abc"
FILEUPLOAD_ALLOWED_EXTENSIONS = ["png"]
# FILEUPLOAD_PREFIX = "/cool/upload"
# FILEUPLOAD_LOCALSTORAGE_IMG_FOLDER = "images/boring/"
FILEUPLOAD_RANDOM_FILE_APPENDIX = True
FILEUPLOAD_CONVERT_TO_SNAKE_CASE = True
|
"""
Exercise 5
Write a program to read through the mail box data and when you find line that
starts with "From", you will split the line into words using the split
function. We are interested in who sent the message which is the second word
on the From line.
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
You w... |
# 6. Math Power
def math_power(n, p):
power_output = n ** p
print(power_output)
number = float(input())
power = float(input())
math_power(number, power) |
# https://atcoder.jp/contests/math-and-algorithm/tasks/math_and_algorithm_bj
n = int(input())
xx = [0] * n
yy = [0] * n
for i in range(n):
xx[i], yy[i] = map(int, input().split())
xx.sort()
yy.sort()
ax = 0
ay = 0
cx = 0
cy = 0
for i in range(n):
ax += xx[i] * i - cx
cx += xx[i]
ay += yy[i] * i - cy
... |
"""Defines a rule for runtime test targets."""
load("@io_bazel_rules_go//go:def.bzl", "go_test")
# runtime_test is a macro that will create targets to run the given test target
# with different runtime options.
def runtime_test(
lang,
image,
shard_count = 50,
size = "enormous",
... |
_version_major = 0
_version_minor = 1
_version_micro = 0
__version__ = "{0:d}.{1:d}.{2:d}".format(
_version_major, _version_minor, _version_micro)
|
"""Descrição de varias llinhas"""
""" Esse módul é usado para descrever um codigo qu funções especificas
levando em conta a usabilidade do usuário.
"""
variavel = 'valor'
def funcao():
return 1 |
def troca(i,j,lista):
if (i >= 0 and j >= 0) and (i <= (len(lista) - 1) and j <= (len(lista) - 1)):
aux = lista[i]
lista[i] = lista[j]
lista[j] = aux
return lista
def main():
n = int(input())
lista = []
for k in range(n):
lista.append(int(input()))
i = int(input(... |
velocidade = float(input('Digite a velocidade atual do carro: '))
multa = (velocidade - 80) * 7
if velocidade > 80:
print('Você excedeu o limite de velocidade que é de 80 KM/h')
print('Sua multa é de R$ {:.2f}'.format(multa))
else:
print('Dirija com segurança! ')
|
## У будинку кілька під'їздів. У кожному під'їзді однакову кількість квартир. Квартири нумеруються підряд, починаючи з одиниці. Чи може в деякому під'їзді перша квартира мати номер x, а остання - номер y?
## Формат введення
# Вводяться два натуральних числа x і y (x ≤ y), що не перевищують 10000.
## Формат виведення... |
# test
def addTwoNumbers(a, b):
sum = a + b
return sum
def addList(l1):
sum = 0
for i in l1:
sum += i
return sum
add = lambda x, y : x + y
num1 = 1
num2 = 2
print("The sum is ", addTwoNumbers(num1, num2))
numlist = (1, 2, 3)
print(add(10, 20))
print("The sum is ", addList(numlist)... |
#
# PySNMP MIB module MITEL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MITEL-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:02:47 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23... |
#!/usr/bin/python3
def print_matrix_integer(matrix=[[]]):
"prints a matrix of integers"
row_len = len(matrix)
col_len = len(matrix[0])
for i in range(row_len):
for j in range(col_len):
if j != col_len - 1:
print("{:d}".format(matrix[i][j]), end=' ')
else... |
def sum_of_squares(n):
total = 0
for i in range(n):
if i * i < n:
total += i * i
else:
break
return total
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = "Fireclaw the Fox"
__license__ = """
Simplified BSD (BSD 2-Clause) License.
See License.txt or http://opensource.org/licenses/BSD-2-Clause for more info
"""
|
_base_ = [
'../_base_/models/fcn_r50-d8.py', '../_base_/datasets/pascal_context.py',
'../_base_/default_runtime.py', '../_base_/schedules/schedule_40k.py'
]
model = dict(
decode_head=dict(num_classes=60),
auxiliary_head=dict(num_classes=60),
test_cfg=dict(mode='slide', crop_size=(480, 480), stride=(... |
pares = 0
numeros = (int(input('Digite um número: ')), int(input('Digite outro número: ')),
int(input('Digite mais um número: ')), int(input('Digite um último número: ')))
print(f'Você digitou os valores {numeros}')
print(f'O valor 9 apareceu {numeros.count(9)} vezes')
if numeros.count(3) == 0:
pri... |
_base_ = [
'../_base_/models/irrpwc.py',
'../_base_/datasets/flyingthings3d_subset_bi_with_occ_384x768.py',
'../_base_/schedules/schedule_s_fine_half.py',
'../_base_/default_runtime.py'
]
custom_hooks = [dict(type='EMAHook')]
data = dict(
train_dataloader=dict(
samples_per_gpu=1, workers_p... |
class Solution:
def isAlienSorted(self, words, order):
lookup = {c: i for i, c in enumerate(order)}
for i in range(len(words) - 1):
word1 = words[i]
word2 = words[i + 1]
for j in range(min(len(word1), len(word2))):
if word1[j] != word2[j]:
... |
#!/usr/bin/python
# sorting.py
items = { "coins": 7, "pens": 3, "cups": 2,
"bags": 1, "bottles": 4, "books": 5 }
for key in sorted(items.keys()):
print ("%s: %s" % (key, items[key]))
print ("####### #######")
for key in sorted(items.keys(), reverse=True):
print ("%s: %s" % (key, items[key]))
|
# variants
model_type = 'SepDisc'
runner = 'SepDiscRunner01'
lambda_img = 0.001
lambda_lidar = 0.001
src_acc_threshold = 0.6
tgt_acc_threshold = 0.6
img_disc = dict(type='FCDiscriminatorCE', in_dim=64)
img_opt = dict(type='Adam', lr=0.0002, weight_decay=0.001)
lidar_disc = dict(type='FCDiscriminatorCE', in_dim=64)
lid... |
def debug(x):
print(x)
### Notebook Magics
# %matplotlib inline
def juptyerConfig(pd, max_columns=500, max_rows = 500, float_format = '{:,.6f}', max_info_rows = 1000, max_categories = 500):
pd.options.display.max_columns = 500
pd.options.display.max_rows = 500
pd.options.display.float_format = float_f... |
# Scores old stuff
#
# Helper functions
#
# FIXME: use ticks instead, teams are either up for the whole tick or down for the whole tick
def _get_uptime_for_team(team_id, cursor):
"""Calculate the uptime for a team.
The uptime is normalized to 0 to 100. An uptime of 100 means the team was
online for the ent... |
# Copyright 2008-2012 Nokia Siemens Networks Oyj
#
# 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... |
"""
PASSENGERS
"""
numPassengers = 435
passenger_arriving = (
(2, 1, 1, 0, 1, 0, 0, 1, 2, 1, 1, 0), # 0
(1, 5, 1, 0, 0, 0, 2, 2, 0, 1, 0, 0), # 1
(1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0), # 2
(0, 2, 1, 1, 1, 0, 3, 2, 1, 0, 0, 0), # 3
(0, 1, 1, 1, 0, 0, 4, 1, 0, 0, 0, 0), # 4
(1, 0, 0, 1, 0, 0, 1, 3, 0, 1, 0, ... |
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
class ZookeeperBenchmark(MavenPackage):
"""It is designed to measure the per-request latency of a ZooKeeper
ensem... |
n = [ 1 ] + [ 50 ] * 10 + [ 1 ]
with open('8.in', 'r') as f:
totn, m, k, op = [ int(x) for x in f.readline().split() ]
for i in range(m):
f.readline()
for i, v in enumerate(n):
with open('p%d.in' % i, 'w') as o:
o.write('%d 0 %d 2\n' % (v, k))
for j in range(v):
... |
# Configuration file for ipython-console.
c = get_config()
#------------------------------------------------------------------------------
# ZMQTerminalIPythonApp configuration
#------------------------------------------------------------------------------
# ZMQTerminalIPythonApp will inherit config from: TerminalIP... |
"""Constants for the WLED integration."""
# Integration domain
DOMAIN = "wled"
# Attributes
ATTR_COLOR_PRIMARY = "color_primary"
ATTR_DURATION = "duration"
ATTR_FADE = "fade"
ATTR_INTENSITY = "intensity"
ATTR_LED_COUNT = "led_count"
ATTR_MAX_POWER = "max_power"
ATTR_ON = "on"
ATTR_PALETTE = "palette"
ATTR_PLAYLIST = ... |
"""Wrapper macro around parcel cli"""
load("@aspect_bazel_lib//lib:utils.bzl", "path_to_workspace_root")
load("@npm//parcel-bundler:index.bzl", _parcel = "parcel")
def parcel(name, entry_html, data = [], **kwargs):
"""Wrapper macro around parcel cli"""
_parcel(
name = name,
args = [
... |
def fib(n):
'''Takes in a number n, and returns the nth fibonacci number, starting with: 1, 1, 2, 3, 5,...'''
if n <= 1:
return n
else:
return fib(n - 1) + fib(n - 2)
|
class Column(object):
def __init__(self, name, dataType):
self._number = 0
self._name = name
self._dataType = dataType
self._length = None
self._default = None
self._notNull = False
self._unique = False
self._constraint = None
self._check = []
... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def middleNode(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return Non... |
""" author:
name : Do Viet Chinh
personal email: dovietchinh1998@mgail.com
personal facebook: https://www.facebook.com/profile.php?id=100005935236259
VNOpenAI team: vnopenai@gmail.com
via team :
date:
26.3.2021
""" |
# Definisikan class Karyawan
class Karyawan:
def __init__(self, nama, usia, pendapatan, insentif_lembur):
self.nama = nama
self.usia = usia
self.pendapatan = pendapatan
self.pendapatan_tambahan = 0
self.insentif_lembur = insentif_lembur
def lembur(self):
self.pend... |
# Faça um programa que leia um numero real e imprima
num_real = float(input('Entre com um numero real: '))
print(f'O numero real digitado foi: {num_real}')
|
TEMPLATE = """import numpy as np
import unittest
from {name}.algorithm.research_algorithm import {name_upper}Estimator
class Test{name_upper}Estimator(unittest.TestCase):
def test_predict(self):
multiplier = 2
input_data = np.random.random([1, 2])
expected_result = input_data * multiplie... |
"""A module for defining WORKSPACE dependencies required for rules_foreign_cc"""
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
load(
"//foreign_cc/private/shell_toolchain/toolchains:ws_defs.bzl",
shell_toolchain_workspace_ini... |
class Solution:
def wordSquares(self, words):
"""
:type words: List[str]
:rtype: List[List[str]]
"""
n = len(words[0])
pres = collections.defaultdict(list)
for word in words:
for i in range(n):
pres[word[:i]].append(word)
de... |
#!/usr/bin/env python
# encoding: utf-8
name = "Non Atom Centered Platts Groups"
shortDesc = ""
longDesc = """
"""
entry(
index = -3,
label = "R",
group =
"""
1 * R u0
""",
solute = None,
shortDesc = """""",
longDesc =
"""
""",
)
entry(
index = -2,
label = "CO",
group =
"""
1 ... |
def permutations(arr):
arr1 = arr.copy()
print(" ".join(arr1), end=" ")
count = len(arr1)
for x in range(len(arr)):
tmp = []
for i in arr:
for k in arr1:
if i not in k:
tmp.append(k + i)
count += 1
p... |
#!/bin/pypy3
with open("be2.txt", "r") as f: #beolvasás
seged=f.readlines()
be=[]
for sor in seged: #mátrixba szétszedés
asor = sor.split("\n")[0]
be.append(asor.split("\t"))
sordiff=[]
for i in range(len(be)):
for j in range(len(be[i])):
be[i][j]=int(be[i][j]) #konvertálás intre
min=be[i][0]
max=be[i... |
class AvailableCashError(Exception):
def __init__(self, available_amount, requested_amount):
error_message = (
'There is not enough available cash in the account. ' +
'Amount available is {available_amount}, amount requested is {requested_amount}. ' +
'\nPlease add funds ... |
# --------------
##File path for the file
file_path
#Code starts here
def read_file(path):
f=open(path,'r')
sentence=f.readline()
f.close()
return sentence
sample_message=read_file(file_path)
print(sample_message)
# --------------
#Code starts here
file_path_1
file_path_2
def fus... |
#
# Copyright SAS Institute
#
# 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... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
## Onera M6 configuration module for geoGen
#
# Adrien Crovato
def getParams():
p = {}
# Wing parameters (nP planforms for half-wing)
p['airfPath'] = '../airfoils' # path pointing the airfoils directory (relative to this config file)
p['airfName'] = ['one... |
# A function is a block of organized, reusable code that is used to perform a single, related action.
# Define a function.
def fun():
print("What's a Funtion ?")
# Functions with Arguments.
def funArg(arg1,arg2):
print(arg1," ",arg2)
# return(arg1," ",arg2)
#Functions that returns a value... |
# TASK 1
# Write a function called oops that explicitly raises an IndexError exception when called.
# Then write another function that calls oops inside a try/except statement to catch the error.
# What happens if you change oops to raise KeyError instead of IndexError?
def oops():
raise IndexError
try:
In... |
"""
Contains choice collections for model fields.
Add choices here instead of writing them in models.py.
"""
# Menu Item
MENU_ITEM_CHOICES = (("VEGETARIAN", "Vegetarian"), ("ALL", "All"))
MENU_ITEM_CATEGORY = (
("CHINESE", "Chinese Food"),
("SOUTH INDIAN", "South Indian Food"),
("FAST FOOD", "Fast ... |
# Frames Per Second
FPS = 60
# SCREEN
SCREEN_COLUMNS_NUMBER = 6
SCREEN_ROWS_NUMBER = 7
SCREEN_COLUMN_SIZE = 96
SCREEN_ROW_SIZE = 96
SCREEN_WIDTH = SCREEN_COLUMNS_NUMBER * SCREEN_COLUMN_SIZE
SCREEN_HEIGHT = SCREEN_ROWS_NUMBER * SCREEN_ROW_SIZE
# Colors for display.
COLOR_WHITE = (255, 255, 255)
CO... |
número = int(input('Digite um número qualquer: '))
if número % 2 == 0:
print('O número {} é PAR'.format(número))
else:
print('O número {} é ÍMPAR'.format(número))
|
def deny(blacklist):
"""
Decorates a handler to filter out a blacklist of commands.
The decorated handler will not be called if message.command is in the
blacklist:
@deny(['A', 'B'])
def handle_everything_except_a_and_b(client, message):
pass
Single-item blacklists may... |
class Linked_List():
def __init__(self, head):
self.head = head
class Node():
def __init__(self, data):
self.data = data
self.next = None
# O(N) space and O(N) time
def partition_linked_list(linked_list, partition):
less_than = []
greater_than_or_equal = []
next_one = linke... |
# -*- coding: utf-8 -*-
# See LICENSE file for full copyright and licensing details.
{
'name': 'Library Management system odoo',
'version': "10.0.1.0.6",
'author': "David Kimolo",
'category': 'School Management',
'website': '',
'license': "AGPL-3",
'summary': """A Module For Library Managem... |
"""
回溯算法,会提示超时因为时间复杂度为2的N次方
class Solution:
def climbStairs(self, n: int) -> int:
return self.go(n,0)
def go(self,n,cur) -> int:
if cur == n:
return 1
if cur > n:
return 0
return self.go(n,cur + 1) + self.go(n,cur + 2)
"""
"""
从起点递推到终点
"""
class Solu... |
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# External libraries
# Markdown
'markdownx',
# Bootstrap
'bootstrap4',
# Our apps
'... |
#!/usr/bin/python
# Copyright (c) 2010 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""PyAuto Errors."""
class JSONInterfaceError(RuntimeError):
"""Represent an error in the JSON ipc interface."""
pass
class NTPT... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
************************************************
@Time : 2019-06-13 01:11
@Author : zxp
@Project : AlgorithmAndDataStructure
@File : IgnoreErroAndNotRelative.py
@Description: ==================================
忽略错误文件,忽略没有对应Gt的图像,转而读取下一行
@license: (C) Copyrigh... |
class Sorting:
@staticmethod
def insertion_sort(arr):
for i in range(1, len(arr)):
curr = arr[i]
j = i - 1
while j >= 0 and curr < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = curr
return arr
if __name__ == "__m... |
# coding: utf-8
# (C) Copyright IBM Corp. 2018, 2019.
#
# 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... |
HERO = {'B': 'Batman', 'J': 'Joker', 'R': 'Robin'}
OUTPUT = '{}: {}'.format
class BatmanQuotes(object):
@staticmethod
def get_quote(quotes, hero):
for i, a in enumerate(hero):
if i == 0:
hero = HERO[a]
elif a.isdigit():
quotes = quotes[int(a)]
... |
numBlanks = 0
golden = ["Emptiness", "fear", "mountain"]
newLines = []
with open('fill-blanks.txt', 'r') as f:
for line in f:
if '...' in line:
blank = input("Fill the blank in " + line)
if blank == golden[numBlanks]:
newLine = line.replace("...", blank)
e... |
"""
6974. Long Division
작성자: xCrypt0r
언어: Python 3
사용 메모리: 29,088 KB
소요 시간: 72 ms
해결 날짜: 2020년 11월 26일
"""
def main():
n = int(input())
for _ in range(n):
a, b = map(int, [input(), input()])
print(a // b)
print(a % b)
print()
if __name__ == '__main__':
main() |
print('-' * 30)
print('GERADOR DE TABUADA COM WHILE')
print('-' * 30, '\n')
cont = 0
while True:
tabuada = int(input('Digite um número: '))
if tabuada < 0:
break
while cont <= 10:
print(f'{tabuada} x {cont} = {tabuada * cont}')
cont += 1
cont = 0
print('-' * 30)
print('Obr... |
array = [116, 176382, 94, 325, 3476, 4, 2542, 9, 21, 56, 322, 322]
print(array)
SENTINEL = 10**12
def merge(array, left, mid, right):
L = array[left:mid]
R = array[mid:right]
L.append(SENTINEL)
R.append(SENTINEL)
i = j = 0
for k in range(left, right):
if L[i] <= R[j]:
arr... |
ACTIONS = ["Attribution", "CommericalUse", "DerivativeWorks", "Distribution", "Notice", "Reproduction", "ShareAlike", "Sharing", "SourceCode", "acceptTracking", "adHocShare", "aggregate", "annotate", "anonymize", "append", "appendTo", "archive", "attachPolicy", "attachSource", "attribute", "commercialize", "compensate"... |
_base_ = [
'../_base_/models/regnet/regnetx_400mf.py',
'../_base_/datasets/imagenet_bs32.py',
'../_base_/schedules/imagenet_bs1024_coslr.py',
'../_base_/default_runtime.py'
]
# Precise BN hook will update the bn stats, so this hook should be executed
# before CheckpointHook, which has priority of 'NORM... |
cars = ['audi', 'bmw', 'subaru', 'toyoto']
#使用if判断
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car)
#多个判断条件 if xx ==xx and xx == xx
#只有要一个满足使用 if xx ==xx or xx == xx
#检查特定值是否包含在列表中 in 'xx' in xxList
#检查特定值是否不包含在列表中 not in | if user not in bannedUsers
car = 'subaru'
print("Is car... |
###########################################################################
#
# Copyright 2020 Google LLC
#
# 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
#
# https://www.apache.org/l... |
with open("input") as file:
lines = [line.split(" ") for line in file.read().strip().split("\n")]
register_names = set([line[0] for line in lines])
registers = {}
for name in register_names:
registers[name] = 0
operations = {
"dec": lambda r,v: r-v,
"inc": lambda r,v: r+v }
... |
# Source: https://github.com/kenshohara/3D-ResNets-PyTorch/blob/master/mean.py
def get_mean(norm_value=255, dataset='activitynet'):
# Below values are in RGB order
assert dataset in ['activitynet', 'kinetics', 'ucf101']
if dataset == 'activitynet':
return [114.7748/norm_value, 107.7354/norm_value... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"say_hello": "00_core.ipynb",
"say_bye": "00_core.ipynb",
"optimize_bayes_param": "01_bayes_opt.ipynb",
"ReadTabBatchIdentity": "02_tab_ae.ipynb",
"TabularPandasIdentity": ... |
C = "C"
CPP = "Cpp"
CSHARP = "CSharp"
GO = "Go"
JAVA = "Java"
JAVASCRIPT = "JavaScript"
OBJC = "ObjC"
PYTHON = "Python" # synonym for PYTHON3
PYTHON2 = "Python2"
PYTHON3 = "Python3"
RUST = "Rust"
SWIFT = "Swift"
def supported():
"""Returns the supported languages.
Returns:
the list of supported languag... |
class Student:
# Konstruktor może przyjąć argumenty
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
self.promoted = False
student = Student()
# Obiekty możemy przekazywać jako argumenty do funkcji
def print_student(student):
prin... |
"""
Build rule for open source tf.text libraries.
"""
def py_tf_text_library(
name,
srcs = [],
deps = [],
visibility = None,
cc_op_defs = [],
cc_op_kernels = []):
"""Creates build rules for TF.Text ops as shared libraries.
Defines three targets:
<name>
... |
# Sander Viirmaa
# 19.12.2018
# Ülesanne 08 - 02
class auto:
mark = ' '
aasta = 0
hind = 0
värv = ' '
kiirus = 0
def __init__(self, x, y, z, q, w):
self.mark = x
self.aasta = y
self.hind = z
self.kiirus = q
self.varv = w
def lisa... |
list_of_numbers_as_strings = input().split(", ")
for index in range(len(list_of_numbers_as_strings)):
number = int(list_of_numbers_as_strings[index])
if number == 0:
list_of_numbers_as_strings.remove(str(0))
list_of_numbers_as_strings.append(str(0))
print(list_of_numbers_as_strings)
|
##
# Copyright (c) 2006-2018 Apple Inc. 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 l... |
"""
Provide friendlier Kotlin rule exports.
"""
load(
"@io_bazel_rules_kotlin//kotlin:kotlin.bzl",
_kt_jvm_binary = "kt_jvm_binary",
_kt_jvm_library = "kt_jvm_library",
)
kt_jvm_library = _kt_jvm_library
kt_jvm_binary = _kt_jvm_binary
|
def query(self, sql, *args):
'''Mixin method for the XXXBase class.
conn should be a cm.db.Connection instance.'''
conn = self._get_connection()
return conn.query(sql, *args)
def get_connection(self):
'''Mixin method for the XXXBase class.
Returns a cm.db.Connection instance.'''
raise 'No i... |
##Config file for lifetime_spyrelet.py in spyre/spyre/spyrelet/
# Device List
devices = {
'vna':[
'lantz.drivers.VNA_Keysight.E5071B',
['TCPIP0::A-E5071B-03400::inst0::INSTR'],
{}
],
'source':[
'lantz.drivers.mwsource.SynthNVPro',
['ASRL16::INSTR'],
{}
]
... |
height = int(input())
for i in range(1, height + 1):
for j in range(1,i+1):
if(i == height or j == 1 or i == j):
print(i,end=" ")
else:
print(end=" ")
print()
# Sample Input :- 5
# Output :-
# 1
# 2 2
# 3 3
# 4 4
# 5 5 5 5 5
|
# -*- coding:utf-8-*-
name = ["gyj","dzj","why","zz","wwb","zke","ljx","syb","yxd"]
print(name)
name.reverse()
print(name)
print(len(name))
|
"""
Exercise 08: Write a Python program to sort a list of elements
using quick sort algorithm.
"""
def quickSort(alist):
"""
Quick sort algrithm, In-place version.
"""
def partition(alist, left, right):
pivot = alist[right - 1]
i = left - 1
for j in range(left, right):
... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: sample
Desc :
Python操作PDF:
1. 读取内容使用slate 0.4.1(基于PDFMiner),只能用于Python2
2. 各种PDF操作,包括读取内容、合并、分割、旋转、提取页面等等使用PyPDF2
目前最好的做法是使用PDFMiner,安装之后:
pdf2txt.py -o pc.txt /home/mango/work/perfect.pdf
然后自己去分享pc.txt文件即可
"""
|
def flatten(seq):
r = []
for x in seq:
if type(x) == list:
r += flatten(x)
else:
r.append(x)
return r
seq = [1,[2,3],4]
seq = [1,[2,[5,6],3],4]
print(seq, '-->', flatten(seq))
|
# parsetab.py
# This file is automatically generated. Do not edit.
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'nonassocLESSMOREEQUALSTOMOREEQUALLESSEQUALNOTEQUALleftPLUSMINUSleftTIMESDIVIDEleftANDORrightUMINUSINT FLOAT PLUS MINUS TIMES DIVIDE EQUALS LPAREN RPAREN LCURLBRACKET RCURLBRACKET ID COMMENT ST... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by Hai-Tao Yu
# 26/09/2018
# https://y-research.github.io
"""Description
""" |
class Level:
def __init__(self, current_level=1, current_xp=0, level_up_base=30, level_up_factor=30):
#Original (self, current_level=1, current_xp=0, level_up_base=200, level_up_factor=150)
self.current_level = current_level
self.current_xp = current_xp
self.level_up_base = level_up_... |
version = 1
disable_existing_loggers = False
loggers = {
'sanic.root': {
'level': 'DEBUG',
'handlers': ['console', 'root_file'],
'propagate': True
},
'sanic.error': {
'level': 'ERROR',
'handlers': ['error_file'],
'propagate': True
},
'sanic.access': {... |
#Printing Stars in 'C' Shape !
'''
****
*
*
*
*
*
****
'''
for row in range(7):
for col in range(5):
if (col==0 and (row!=0 and row!=6)) or (row==0 or row==6) and (col>0):
print('*',end='')
else:
print(end=' ')
print() |
# Copyright (c) 2019 Kevin Weiss, for HAW Hamburg <kevin.weiss@haw-hamburg.de>
#
# This file is subject to the terms and conditions of the MIT License. See the
# file LICENSE in the top level directory for more details.
# SPDX-License-Identifier: MIT
"""packet init for BPH PAL
"""
|
# Copyright 2018, OpenCensus 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 applicable law or agreed to in w... |
def Main():
a = 1
b = 2
c = 3
e = 4
d = a + b - c * e
return d
|
# Parameters:
# MON_PERIOD : Number of seconds the temperature is read.
# MON_INTERVAL : Number of seconds the temperature is checked.
# TEMP_HIGH : Value in Celsius degree on that a warning e-mail is sent if temperature is above it.
# TEMP_CRITICAL : Value in Celsius degree on that the device is shutted down ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.