text
stringlengths
38
1.54M
import unittest import json import logging import lxc_ui_agent import lxc import lxc.test.helpers logger = logging.getLogger(__name__) class TestContainersAPI(unittest.TestCase): def setUp(self): self.app = lxc_ui_agent.app.test_client() self.app.testing = True token = "test-Token" ...
from main import main import timeit import tracemalloc #t = timeit.Timer("main(\"asdasda\", 2)", "from main import main") #print(t.timeit(1)) #tracemalloc.start() try: main(screen_name="asdasda", limit=2) except Exception as e: print(str(e)) #print("Current: %d, Peak %d" % tracemalloc.get_traced_memory())
import json import pickle import random import sys import math from rtree_node import node from anytree import RenderTree import Rtree_depth import resource curid = 1 # Stores id of root during insertion rootid = 0 dimen = 0 def calcM(): """ Function to calculate M value for R tree""" global dimen pagesiz...
""" App config """ from django.apps import AppConfig class ManifestStorageConfig(AppConfig): """ App Config """ name = "manifest_storage"
from tkinter import * tk = Tk() '''v = IntVar()#测试 c = Checkbutton(tk,text ="test",variable = v) c.pack() d = Label(tk,textvariable = v) d.pack() mainloop()''' FOOTBALL= ['莱奥.梅西','C罗','小罗'] soccer=[] for football in FOOTBALL: soccer.append(IntVar()) print(soccer.append(IntVar())) b = Checkbutton(tk,text = f...
# Generated by Django 2.2.7 on 2019-11-27 15:04 import datetime from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('rental', '0004_auto_20191127_1459'), ] operations = [ migrations.AlterField( mo...
def solve(L): ret = 0 for element in L: ret += element[1] % element[0] return ret n = int(input()) L = [] for i in range(n): students, apples = map(int, input().split()) L.append((students, apples)) print(solve(L))
import gym env = gym.make('FrozenLake-v0') print(env.action_space) print(env.observation_space) score = 0 for _ in range(1000): env.reset() # obs, rew, done, info = env.step(1) # obs, rew, done, info = env.step(1) # obs, rew, done, info = env.step(2) # obs, rew, done, info = env.step(2) # obs,...
import pytest import os from PIL import Image from algorithm.Meteocr import * from algorithm.character_recognition_adapters import MeteocrAdapter, TesseractAdapter class TestMetetocr: @staticmethod @pytest.mark.parametrize( "img_path", ['yourbudget/tests/static/a.png', 'yourbudget/tests/static...
"""A Note wrapper class""" class Note: """A Note wrapper class""" def __init__(self, anki, note): self.a = anki self.n = note self.model_name = note.model()['name'] self.fields = [x for x, y in self.n.items()] self.suspended = any([c.queue == -1 for c in self.n.cards()...
import json from MyThread import MyThread from Request import ServerRequest import select class ClientCommunicator(MyThread): """ The class represents a thread that is currently communicating with a specific client. Thread is necessary for the accept command, which may block the whole server. ...
l=[666] N=int(input()) i=1665 while True: if "666" in str(i): l.append(i) if len(l)==N: break i+=1 print(l[N-1])
import MyConnector FootballLeagueList = [21, 284, 17, 9, 12, 37, 36, 39, 35, 31, 34, 8, 11, 40, 33, 23, 157, 29, 150, 16, 25, 60, 61, 4, 358] def GetFootballTeams(): AllTeamList = [] for leagueCode in FootballLeagueList: url = 'http://info.nowscore.com/jsData/teamInfo/team%d.js?version=20181111141201'...
#!/bin/python3 import math import os import random import re import sys def chocolateFeast(n, c, m): # Get the total chocolates Bobby can buy with the initial money chocolates = n // c wrappers = chocolates # While you can still convert your wrappers to chocolates while wrappers >= m: # ...
import os import numpy as np import itertools as it import matplotlib.pyplot as plt import math from sklearn.datasets import fetch_mldata from scipy import spatial from collections import Counter """ returns a list of most common values in an input list output size is as number of elements sharing the max count value...
import boto3 import json # TODO: Change the table name TABLE_NAME = None def handler(event, context): """ Get the last 10 entries from the forecast table :param event: HTTP request details (not used) :param context: Lambda context details (not used) :return: A list of up to ten of the most recen...
# Generated by Django 3.1 on 2020-08-29 17:13 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mainapp', '0026_report'), ] operations = [ migrations.AddField( model_name='report', name='iduser', field=...
''' Distributed coordination Python implementation of group formation, communications, leader election, consensus and action coordination. Created on Feb 23, 2019 Author: riaps ''' import time import logging import struct import collections import traceback import random import string import ipaddress # import ctyp...
import random from components.deck import Deck class Shoe(object): # How many cards to print before a line break happens. linebreak_index = 10 def __init__(self, n_decks=None): """Initialization.""" self.cards = [] for _ in range(n_decks): cards = Deck().cards ...
n, letters = int(input()), input() numbers = [ord(letter) - 96 for letter in letters] nm_sum = 0 for i in range(n): nm_sum += numbers[i]*(31**i) print(nm_sum % 1234567891)
from django.urls import reverse from users.permissions import check_viewing_rights_admin from .forms import * from django.contrib import messages from django.contrib.auth.decorators import (login_required,user_passes_test) from django.shortcuts import render, redirect,get_object_or_404 from users.forms import DivErrorL...
# Copyright 1999 by Jeffrey Chang. All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. import os from Bio import Fasta from Bio import Alphabet def title_to_ids(title): """Func...
class Proc: def __init__(self, code): self.code = code def call(self, *args): return eval(self.code, dict(zip(self.code.co_varnames, args))) def proc(func): return Proc(func) def puts(*args): for x in args: print x if not args: print class BasicObject: pass
#!/usr/bin/python3 import os import sys import subprocess # This is only backwards compat now; main source is fstab boot_label = "I586CON_BOOT" cfgdir = "/etc/i586con/" def sub(*args, **kwargs): p = subprocess.run(*args, **kwargs) if p.returncode != 0: return False if p.stdout is not None: ...
# Generated by Django 2.2.12 on 2020-06-07 10:13 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('games', '0004_resultcluster_results'), ] operations = [ migrations.AlterField( model_name='res...
# Copyright 2015 Johannes Grassler <johannes@btw23.de> # # 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...
from enum import Enum class SimulationType(Enum): HighSpread = 1 LowSpread = 2 ClearingHouse = 3 ClearingHouseLowSpread = 4 Basel = 5 BaselBenchmark = 6 DepositInsurance = 7 DepositInsuranceBenchmark = 8 class BankSizeDistribution(Enum): Vanilla = 1 LogNormal = 2 class Inte...
from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.applications import VGG16 from tensorflow.keras.layers import AveragePooling2D from tensorflow.keras.layers import Dropout from tensorflow.keras.layers import Flatten from tensorflow.keras.layers import Dense from tensorflow.keras...
s = {'사과','오렌지','딸기','사과','딸기'} print(len(s)) # set의 내용을 비워준다. s.clear() print(len(s)) s.add('오징어') s.add('오징어') s.add('오징어') s.add('꼴뚜기') s.add('꼴뚜기') print(len(s)) print(s) s.remove('꼴뚜기') # .remove 는 없는걸 지우겠다고하면 오류남 s.discard('aaa') # .discard 도 remove처럼 지우는 메소드인데, 없는걸 지워도 오류안난다. try : s.remove('bbbb') except ...
# -*- coding: UTF-8 -*- # Copyright 2012 Rumma & Ko Ltd # License: GNU Affero General Public License v3 (see file COPYING for details) """ code changes must be documented in *one central place per developer*, not per module. """ import os import datetime from django.conf import settings from lino.utils import i2d, i...
from django.conf.urls import patterns, url from django.conf import settings from django.contrib.staticfiles.urls import staticfiles_urlpatterns from .views import index_view, login_view, words_view, words_del_view, translations_view, translation_add_view urlpatterns = patterns('', url(r'^$', index_view, name='in...
# -*- coding: utf-8 -*- # @Time : 2018/4/1 20:58 # @Author : mdl # @Email : 1271737949@qq.com # @File : numerical_practice.py # @Software: PyCharm import random '''数值类型练习''' #使用循环和算数运算,生成0到20的偶数 def even_num(): for i in range(0,21): if i%2==0: print(i,"是偶数") continue #使用...
#!/usr/bin/python import numpy as np NW_tt = 5*10**8 # number of W bosons with single lepton trigger # 10**4 for 20 MeV # 10**5 for 6 MeV # BR ~10**-3
from typing import Callable from db_module import db_init from telegram_bot import main as tg_main from vk_bot import main as vk_main from multiprocessing import Process def try_wrapper(func): def wrapper(*args, **kwargs): while True: try: func(*args, **kwargs) exc...
from random import shuffle class MosaicModel: def __init__(self, randomly=0, resolution=(2048, 2048)): self.randomly = randomly self.resolution = resolution self.img_urls = [] def add_images(self, images_str): self.img_urls = images_str.split(',') if self.randomly == ...
#! C:\Python38-32\python.exe -u import cgi, cgitb, re, encryptionlib as enc, os, mysql.connector as mysql, datetime as date from connectlib import connect_db # mysql account verification code # mysql candidate validation code def valid_amt(amt): """ Checks if a valid donation amout was entered """ ...
__author__="congcong wang" import pickle import shutil import time from sklearn.metrics.pairwise import cosine_similarity from sentence_transformers import SentenceTransformer from tqdm import tqdm import nltk import os import logging logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=loggin...
from package_ref import * def parse_vendor_yml(file_type_descriptor, data): references = [] lines = data.split('\n') vendors = False path = "" for line in lines: if line == '': continue if line.startwith("vendors:"): vendors = True elif line[0] != '-...
# Find an element in a list using binary search. def find(orderedList, elementToFind): startIndex = 0 endIndex = len(orderedList) - 1 found = False while startIndex <= endIndex and not found: middleIndex = (startIndex + endIndex) // 2 if orderedList[middleIndex] == elementToFind: ...
import pandas as pd import math '''Calculating Z-value and P-value based on the values of Spearman Rank coefficient computed in previous step ( StatisticalComputations.py) and it will create two files for each time window; one for z-Values and one for p-Values''' # # Tasks performed in the program # # method z...
import requests import os from dotenv import load_dotenv, find_dotenv BASE_URL = 'https://api.genius.com/search' BASE_LINK_URL = 'https://genius.com' load_dotenv(find_dotenv()) def get_lyrics(song_name): song_name.replace(' ', '%20') # %20 is the space character for the get request # try using params. I...
#! /usr/bin/python import MDAnalysis.coordinates.DCD import MDAnalysis.coordinates.DCD as dcd from numpy import * x=dcd.DCDReader('mdtest_flexible_yes.dcd') #unit cell paramters at frame 1 x[1].dimensions #number of frames frames=len(x) n=zeros((frames,6)) #array of unit cell parameters for all frames for ts in ran...
from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class RegisterForm(UserCreationForm): username = forms.CharField( label="帳號", widget=forms.TextInput(attrs={'class': 'form-control'}) ) email = forms.EmailField( ...
from gi.repository import Gdk as gdk ######################## ### ### MODES ### ######################## class VIG_Modes(object): """Holds info on all the modes""" def __init__(self): object.__setattr__(self, 'info', { 'command': 'Command Mode', 'visual': 'Visua...
import sys import os import json from Pre_process import read_csv,etl_preprocess from app import app from flask import Flask, flash, request, redirect, render_template from werkzeug.utils import secure_filename ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif','csv']) def allowed_file(fi...
# 练习: # 1. 用字符串 * 运算符打印三角形 # 要求输入一个整数,此整数代表最长的一行星离左侧的字节数 # 如: # 请输入离左侧的距离: 3 # 打印如下: # * # *** # ***** # ******* n = int(input('请输入离左侧的距离: ')) print(' ' * n + ' *') print(' ' * n + ' ***') print(' ' * n + ' *****') print(' ' * n + '*******')
from curie_calculator import clean_all, input_reader input_folder, _, _, _ = input_reader() clean_all(input_folder)
# Instant Messenger Bot import pyautogui # Messenger was my preffered chat platform m = pyautogui.getWindowsWithTitle('messenger - google chrome') m[0].activate() # Insert name of friends friends = ['friend A', 'friend B'] def send_message(name): pyautogui.click((306, 133)) pyautogui.sleep(1) pyautogui...
from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.views.generic import TemplateView from django.views.generic import RedirectView from django.core.urlresolvers import reverse_lazy from django.contrib import admin import portal.views impor...
###### Test steps ######## # Sign in # Navigate to Org page # CRUD rooms # Log out ########################## from atexit import register import time, sys, random, pickle, string from datetime import datetime from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.commo...
import sys sys.path.insert(0, '../tracking') from tracking.prepro_seq import * from utils.calculator import * def eval_center_pixel(gt_list, res_list): avg_dist = 0. for i in range(len(gt_list)): gt_center = np.array( [int(gt_list[i][0]) + int(int(gt_list[i][2]) / 2), int(gt_list[i][1]) +...
import csv import glob import os from lambdatrader.candlestick_stores.cachingstore import ChunkCachingCandlestickStore from lambdatrader.exchanges.enums import POLONIEX from lambdatrader.models.candlestick import Candlestick from lambdatrader.utilities.utils import pair_from, get_project_directory files = glob.glob(o...
import sys import time def change_money_recursive(amount, coins): if amount <= 0: return 0 n_change = (1 << 31) for coin in coins: if amount - coin >= 0: n_change = min(n_change, 1 + change_money_recursive(amount-coin, coins)) return n_change def change_money_dp( amount, C...
r""" This script tries to evaluate the importance of different connections of a single convolution layer """ import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1' os.environ['CUDA_VISIBLE_DEVICES'] = '0' import math import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim import dataset_factory...
# Напишите простой калькулятор, который считывает с пользовательского # ввода три строки: первое число, второе число и операцию, после чего # применяет операцию к введённым числам ("первое число" "операция" "второе # число") и выводит результат на экран. # Поддерживаемые операции: +, -, /, *, mod, pow, div, где # mod...
import time import serial import math as m import VtkPointCloud as v import sys import vtk import csv from numpy import random,genfromtxt,size from PyQt4 import QtCore, QtGui from vtk.qt4.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor import display import threading import time from PyQt4.QtCore import QT...
# David Curry # Gradient Descent using SciKit - Machine Learning import pylab as pl import numpy as np from sklearn import datasets, linear_model print '---> Importing the Dataset' data = np.loadtxt('mlclass-ex1-005/mlclass-ex1/ex1data1.txt', delimiter=',') x = data[:, 0] y = data[:, 1] # Create linear regression o...
from itertools import permutations t = input() for j in range(0,t): s = raw_input() li = [] b = len(s) for i in range(0,b): li.append(s[i]) p = permutations(li) k = p.next() k2 = p.next() if(not k2): print 'no answer' print '\n' else: li2 = [ w for w in k2] print ''.join(li2) print '\n'
import requests from bs4 import BeautifulSoup # Set the URL you want to webscrape from url = 'https://en.wikipedia.org/wiki/Google' # Connect to the URL response = requests.get(url) # Parse HTML and save to BeautifulSoup object¶ soup = BeautifulSoup(response.text, "html.parser") # finding text content text = soup.f...
from Fluxonium_hamiltonians.Single_small_junction import relaxation_rate_qp_array as r_qp_array from Fluxonium_hamiltonians.Single_small_junction import relaxation_rate_cap as r_cap from Fluxonium_hamiltonians.Single_small_junction import relaxation_rate_cap_chain1 as r_cap_chain1 import numpy as np from matplotlib im...
# We need to tell Python that we want to use certain features so it can # get them ready for us # "sys" contains things that help us read user input and print things to the screen # "math" contains things to help with advanced mathematical operations (beyond addition, subtraction, division, etc) import math # Our prog...
# -*- coding: utf-8 -*- """ Created on Mon Apr 22 22:10:12 2019 @author: mqureshi """ # -*- coding: utf-8 -*- """ Created on Mon Apr 22 14:14:07 2019 @author: mqureshi """ import os import pandas as pd from plug_load import load_file_plug import matplotlib.pyplot as plt import matplotlib.dates as matdates os.syste...
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 import sys sys.path.append("build") import MatterSim # import csv import numpy as np import math import base64 import logging import json import random import networkx as nx import utils from utils_data import load...
class student: def __init__(self,name,id,age): self.name=name self.id=id self.age=age s1=student('Rajesh',1,20) s2=student('Ramesh',2,21) print(getattr(s1,'name')) print(getattr(s2,'name')) delattr(s1,"id") # it is used to delete a attribute for particular object print(hasattr(s1,"age")) pri...
from typing import List import random class Helper(): def generate_random_list(self, low: int, high: int, length: int) -> List[int]: """Generates and returns an unordered list of random numbers. Args: low (int): The lowest possible number generated. high (int): The highest...
# -*- coding: utf-8 -*- import unittest from binascii import unhexlify from mnemonic.mnemonic import Mnemonic import os from ton_client.client import TonlibClientFutures proj_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..') class ClientKeyingTestCase(unittest.TestCase): keystore = os.path...
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-09-18 00:07 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('p2preview', '0002_auto_20170910_1429'), ] operatio...
mystery_state = "Georgia" #You may modify the lines of code above, but don't move them! #When you Submit your code, we'll change these lines to #assign different values to the variables. #It's snowing! # #The variable above holds the name of the state that you're #in (hypothetically). Complete the code below so that ...
from _functools import reduce def generate(coins): if len(coins) == 0: return ['0', '1'] result = [] for coin in coins: result.append(coin + '1') result.append(coin + '0') return result def getDivisor(n): d = set(reduce(list.__add__, ([i, n // i] for i in rang...
#label: rejection sampling difficulty: medium """ 思路: 利用已有的随机函数rand7将等概率空间扩大,然后从大的等概率空间中取小范围的数。 rand7 - 1的范围是0 ~ 6,每个数出现概率相等,为1/7 (rand7 - 1 ) * 7 的结果是[0, 7, 14, 21, 28, 35, 42],每个数字出现的概率相等,为1/7 所以 tmp = (rand7()-1)*7 + rand7()-1,得到的数字刚好能均匀覆盖0 ~ 48, 0 ~ 48 就是得到的大的等概率空间, 取0~39这一部分出来,返回%10 +1的结果就是rand10的答案, 如果tmp...
#!/usr/bin/python3 import sys import shutil if len(sys.argv) == 1: print("This script sets up the mini demo for the rasterizer.") print("The following demos are supported: \nbase, lines, attributes, depth, view, blend, animation") else: shutil.copyfile("extra/attributes_" + str(sys.argv[1]) + ".h","attrib...
#!/usr/bin/env python3 # Name: Eric Mockler (emockler) ''' Read a DNA string from user input and return a collapsed substring of embedded Ns to: {count}. Example: input: AaNNNNNNGTC output: AA{6}GTC Any lower case letters are converted to uppercase ''' class DNAstring (str): def length (self):...
# Copyright (c) SenseTime Research. All rights reserved. from random import choice from string import ascii_uppercase from torch.utils.data import DataLoader from torchvision.transforms import transforms import os from pti.pti_configs import global_config, paths_config import wandb from pti.training.coaches.multi_id_...
from django.conf.urls import url, include from django.urls import path from rest_framework.routers import DefaultRouter from . import views router = DefaultRouter() router.register('order', views.OrderViewSet) router.register('categories', views.CategoriesViewSet) router.register('dish', views.DishViewSet) urlpatt...
from .linear_val_func import LinearVF from .quadratic_val_func import QuadraticVF from .linear_time_varying_val_func import LinearTimeVaryingVF from .quadratic_time_varying_val_func import QuadraticTimeVaryingVF
import datetime import os import time import xlsxwriter from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.firefox.options import Options import globals def execute(): script_name = os.path.basename(__file__) print(script_name + " : " + "Launching W3C CSS Validation Service...
#! -*- coding:utf-8 -*- import torch import torch.nn.functional as F class LeNet_5(torch.nn.Module): def __init__(self): super(LeNet_5, self).__init__() self.conv1 = torch.nn.Conv2d(in_channels=3, out_channels=16, kernel_size=5, stride=1, bias=False) self.conv1_relu = torch.nn.ReLU(inpla...
import keras from keras.layers import Dense, Bidirectional, GRU, Dropout, Lambda from run import parse_args from utils import PRF, print_metrics from Models.BaseModel import BaseModel def difference(x): return x[0] - x[1] def no_change(input_shape): return input_shape[0] class LiuModel1(BaseModel): d...
# 연습문제 6-8 def biggest(lst): """리스트 하나를 매개변수로 전달받아 리스트에서 가장 큰 요소를 반환한다.""" # 가장 큰 요소를 저장하기 위한 변수 biggest_element = lst[0] # 변수의 초깃값으로 리스트의 첫번째 요소를 넣어 둔다. # 리스트의 첫번째 요소를 제외한 모든 요소를 순회한다. for element in lst[1:]: # 가장 큰 요소로 저장해 둔 요소보다 현재 요소가 더 크다면, if biggest_element < elemen...
#!/usr/bin/env python __author__ = "Bernd Gewehr" # import python libraries import signal import time import sys import RPi.GPIO as GPIO # import libraries import lib_mqtt as MQTT DEBUG = False #DEBUG = True print 'GPIO daemon starting' MQTT_TOPIC_IN = "/Gartenwasser/#" MQTT_TOPIC = "/Gartenwasser" MQTT_QOS = 0 ...
import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F # TODO: Use Transposed Convolution for upsampling # https://towardsdatascience.com/up-sampling-with-transposed-convolution-9ae4f2df52d0 class FCNN(nn.Module): def __init__(self, num_classes=2): super(FCNN, self...
import time import random from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains from .tools import check_func_args def sub_form(args, browse...
import pandas as pd import os import time import sqlite3 from time import sleep from requests_html import HTMLSession from pathos.pools import ProcessPool class WebscraperJs: def __init__(self, input_file, output_file='results.sqlite', chunk_size=200, n_cpu=8): self.input_file = input_fi...
import os basedir = os.path.abspath(os.path.dirname(__file__)) #SQLALCHEMY_DATABASE_URI = 'postgresql://flask:flask@localhost/flask' SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'db/app.db') SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository') SQLALCHEMY_TRACK_MODIFICATIONS = False apius...
#DAY 5 How about a nice game of chess? import hashlib def findPassword(id): password = '' count = 0 for _ in range(0,8): hashhex = '' while hashhex[0:5] != '00000': hashhex = hashlib.md5(bytes(id+str(count), 'utf-8')).hexdigest() count += 1 password+=hashhex...
#!/usr/bin/env python3 import logging from typing import Dict from telegram import ReplyKeyboardMarkup, Update, ReplyKeyboardRemove from telegram.ext import ( Updater, CommandHandler, MessageHandler, Filters, ConversationHandler, CallbackContext, ) import requests from datetime import date # ...
# Generated by Django 2.2.5 on 2019-09-24 12:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('catalog', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='book', name='summery', ), ...
def add(x, y): out = x + y return out c = add(134, 221) print c def sayhello(): print "Hello Python!" sayhello() def addnums(nums): out = 0 for x in nums: out = add(out, x) return out nums = [1, 2, 3, 4, 5, 6, 7] print addnums(nums)
print("What's your name?") name = input('insert your name: ') print('Hello', name,'!!!') print('How old are you?') age = int(input('insert you age: ')) print('You will have', age + 1, 'years next year')
import numpy as np import matplotlib.pyplot as plt from scipy import signal import seaborn as sns sns.set_context('poster') class Plant: def __init__(self, c, m, k): self.c = c self.m = m self.k = k def u(self, t): u_ = 4.0*np.abs(signal.sawtooth(t*np.sqrt(2)))+10.0*np.sin(t)...
# -*- coding: utf-8 -*- """Constants for PyKEEN.""" from pathlib import Path import pystow __all__ = [ 'PYKEEN_HOME', 'PYKEEN_DATASETS', 'PYKEEN_BENCHMARKS', 'PYKEEN_EXPERIMENTS', 'PYKEEN_CHECKPOINTS', 'PYKEEN_LOGS', ] #: A manager around the PyKEEN data folder. It defaults to ``~/.data/pyk...
import sys from ics import Calendar import requests from PySide2 import QtCore, QtGui, QtWidgets, QtDataVisualization url = 'https://learningsuite.byu.edu/iCalFeed/ical.php?courseID=bgN1BtkiKZZg' class Backend: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.cal = Calen...
xa = float(input("abscissa do ponto A: ")) ya = float(input("ordenada do ponto A: ")) xb = float(input("abscissa do ponto B: ")) yb = float(input("ordenada do ponto B: ")) xm = (xb + xa)/2 ym = (yb + ya)/2 print(round(xm, 1)) print(round(ym, 1))
#!/usr/bin/env python import argparse from PlistModifier import PlistModifier from SharedWorkspace import SharedWorkspace from XcodeProject import XcodeProject import os if __name__ == "__main__": # Command line arguments ##################### commandLineParser = argparse.ArgumentParser() commandLineParser...
from django.contrib import admin from .models import Server class ServerAdmin(admin.ModelAdmin): list_display = ('name', 'ip',) admin.site.register(Server, ServerAdmin)
import cv2 import numpy as np import skimage import random as r cv2 = cv2.cv2 # # GENERATE BLANK IMAGE # def generateBackgroundImage(we, he): # return 204 * np.ones(shape=[he, we, 3], dtype=np.uint8) # final_image = cv2.imread("./final/1.jpg") # print(final_image.shape) # final_image_resized = cv2.resize(final_...
def verbose_on(*args, **kwargs): """ dumb wrapper for print, see verbose_off and verbose """ print(*args, **kwargs) def verbose_off(*args, **kwargs): """ dummy function provides alternative to verbose_off """ _ = args, kwargs # dumb way of doing optional verbose output, see verbose...
''' Created on Jun 20, 2014 @author: Jake ''' import xml.etree.ElementTree as ET from nltk.featstruct import FeatStruct # class Terminal: # def __init__(self,name,features): # self.name = name # self.features = features # def toString(self): # s = '' # s += self.name + ' --> {'...
log_filename = "" dump_filename = "" html_dir = "" port = 0 connection_no = 0 hostname = "" vt_delay = 0
# %load q03_get_toss_win_count/build.py #Default Imports import numpy as np ipl_matches_array =np.genfromtxt('data/ipl_matches_small.csv', dtype= np.str , skip_header=1, delimiter=',') #Your Solution def get_toss_win_count(a): mi=ipl_matches_array[ipl_matches_array[:,5]== a] return len(np.unique(mi[:,0])) ge...