text stringlengths 38 1.54M |
|---|
import unittest
from bricklane_platform.models.payments import Payment, CardPayment, BankPayment
from ..fixture import get_path
from bricklane_platform.services.payment_processor import PaymentProcessor
def create_stub_payment(mock_is_successful):
payment = CardPayment()
payment.is_successful = lambda: mock_... |
import bs4, requests, pyperclip
url = pyperclip.paste()
productData = []
def geteMAGData(productUrl):
res = requests.get(productUrl)
try :
res.raise_for_status()
except requests.exceptions.HTTPError:
print('Service Unavailable from URL: ' + productUrl + '\n\n')
soup = bs... |
#Amy Doan ID:1895125
# When inputing month, it must be spelled correctly to avoid errors
month_list = {"January" : "1", "February" : "2", "March" : "3", "April" : "4", "May" : "5", "June" : "6", "July" : "7", "August" : "8", "September" : "9", "October" : "10", "November" : "11", "December" : "12"} # List of the month
... |
from django.conf.urls import url
from . import views
urlpatterns = [
# Analysis App
url(r'^network/(?P<group_pk>\d+)/$',
views.group_network, name='group-network'),
# Longitudinal user F in Group
url(r'^analysis/group/(?P<group_pk>\d+)/user/(?P<user_pk>\d+)/$',
views.analysis_group_us... |
import timeit
from timeit import default_timer as timer
from torchvision.utils import save_image
import torch
metrics = []
class Test:
def __init__(self, model, data_loader, criterion, metric, device):
self.model = model
self.data_loader = data_loader
self.criterion = criterion
sel... |
import os
import sys
import string
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from keras.models import Model
from keras.layers import Dense, Embedding, Input, LSTM
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.optimizers ... |
"""
******************************************************************************
* Purpose: Program To Implement DQueue to check Palindrome Checker.
*
* @author: Manjunath Mugali
* @version: 3.7
* @since: 23-01-2019
*
*******************************************************************************
"""
import re
fro... |
N=int(input()) #x ranges from 1 to N
#print(num)
k=300
i=1
max=N
min=0
for i in range (0,k):
if i==0:
y=1
print(y)
character=input()
if(character=='L'):
s='evenlie'
else:
s='oddlie'
elif s=='oddlie':
y=int((max+min)/2)
print(... |
import FWCore.ParameterSet.Config as cms
from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer
l1tcsctpg = DQMEDAnalyzer('L1TCSCTPG',
disableROOToutput = cms.untracked.bool(True),
csctpgSource = cms.InputTag("muonCSCDigis","MuonCSCCorrelatedLCTDigi"),
verbose = cms.untracked.bool(False),
DQMStore = ... |
import tweepy
def authenticate_user():
try:
consumer_key="hhYq78kZ6VkAp4Q4pXzuKCOkA"
consumer_secret="A468W3FnFd9WcL2PXYeRO0iLWnu90761HkKHijXRXqmgtR1bpk"
access_token="374363728-BCe1rusHWiVPBHDCQ5RoketbfaNePuHXTeJja7W6"
access_token_secret="cMyNaQwVzxtXKqSG0jjlI1H6avEoMbvZ36pB7Zr5dPEN0"
auth = tweepy.OAuth... |
def apply(L, f):
"""
Applies function given by f to each element in L
Parameters
----------
L : list containing the operands
f : the function
Returns
-------
result: resulting list
"""
result = []
for i in range(len(L)):
result.append(f(L[i]))
return result
L = [1, -2, -5, 6.2]
print... |
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
# Make sure that caffe is on the python path:
caffe_root = '/work/personal/caffe/' # this file is expected to be in {caffe_root}/examples
import sys
sys.path.insert(0, caffe_root + 'python')
import caffe
def vis_square(data):
"""Take an a... |
import os
from app import app, db, lm
from flask import Flask, render_template, request, flash, session, redirect, url_for, send_from_directory, g
from forms import ContactForm, SignupForm, SigninForm
from flask.ext.mail import Message, Mail
from flask.ext.login import current_user
from models import db, User
import fa... |
import pygame
from pygame.locals import *
import sys
class Display():
def __init__(self, wait):
self.screen = pygame.display.set_mode((700, 502))
self.clock = pygame.time.Clock()
self.wait = wait
def print(self, array, highlights):
self.screen.fill((0, 0, 0))
bar_s... |
from sacrerouge.metrics.decomposed_rouge.categorizers.categorizer import Categorizer, TupleCategorizer
from sacrerouge.metrics.decomposed_rouge.categorizers.dep import DependencyCategorizer, DependencyVerbRelationsCategorizer
from sacrerouge.metrics.decomposed_rouge.categorizers.ner import NERCategorizer
from sacreroug... |
import os
import re
import random
import hashlib
import hmac
from string import letters
from operator import is_not
from functools import partial
from random import randint
from time import sleep
from datetime import date
from protorpc import messages
import webapp2
import jinja2
from google.appengine.ext import db... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2019-11-07 21:16
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('MainAPP', '0046_additionalcalculations_scale'),
]
operations = [
... |
# author: Rebecca Ramnauth
# last update: 4 March 2020
from datetime import datetime
import json
import matplotlib.pyplot as plt
import numpy as np
def reaction_rate(items, sender):
other_last_sent = 0
reaction_sum = 0
for item in items[1:]:
if item.get('sender_name') != sender:
... |
from scrapy.http import FormRequest
from scrapy.spider import Spider
from scrapy.utils.response import open_in_browser
import scrapy
class Post_Spider(Spider):
name = "Post"
allowed_domains = ["github.com"]
start_urls = ["https://github.com/login"]
def parse(self, response):
token = response... |
import pickle
import socket
import sys
import logging
import threading
import time
import random
import Queue
class LeaderElection():
def __init__(self,mlist,elect_queue):
#super(master_node, self).__init__()
# Election messages are sent over below port
self.ehost = ''
self.eport... |
name = input('Please, write your name:')
while True:
operator = input(f'{name.capitalize()} Виберіть операцію з +; -; *; /; //; %; **; round; square of number or/'
f'if your want exit please push 0:')
if operator == '+':
number1 = (input('Please, write first digit:'))
number... |
import torch
import torch.nn as nn
import torch.nn.functional as F
def conv3x3x3(in_planes, out_planes, stride):
# 3x3x3 convolution with padding
return nn.Conv3d(
in_planes,
out_planes,
kernel_size=3,
stride=stride,
padding=1)
def upconv3x3x3(in_planes, out_planes, stri... |
import pandas as pd
from tqdm import tqdm
from magics_with_UCM_region import choose_region
def print_to_csv_age(recommender1, recommender2, filename):
target_file = pd.read_csv('dataset/data_target_users_test.csv')
range_target_users = list(target_file["user_id"])
cold_file = pd.read_csv('myFiles/coldUser... |
# Copyright (C) 2021, RTE (http://www.rte-france.com)
# SPDX-License-Identifier: Apache-2.0
from vm_manager.vm_manager import (
list_vms,
start,
stop,
create,
clone,
remove,
enable_vm,
disable_vm,
is_enabled,
status,
create_snapshot,
remove_snapshot,
list_snapshots,
... |
import numpy as np
import theano
import theano.tensor as T
from .initialization import random_init, create_shared
from .initialization import ReLU, tanh, linear, sigmoid
from .basic import Layer, RecurrentLayer
class IterAttentionLayer(Layer):
def __init__(self, n_in, n_out):
self.n_in = n_in
sel... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 17 20:19:11 2021
@author: UBTOHTS
"""
import sys
from PyQt5 import QtWidgets
import pandas as pd
import sqlite3
from sqlite3 import OperationalError
import os
from main import MainWindow
class lectable(MainWindow):
def outputshown(self, x):
self... |
# Написать произвольную анкеты, и вывести полученные данные
name_input = input('Введите имя тут: ')
print(f'Привет, {name_input}!') |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'YiJing.ui'
#
# Created by: PyQt5 UI code generator 5.15.1
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui... |
# External module imports
import RPi.GPIO as GPIO
import time
import sys
if len(sys.argv) != 3:
print "incorrect number of args"
exit()
# Pin Definitons:
pin = int(sys.argv[1])
state = (GPIO.HIGH if sys.argv[2] == "on" else GPIO.LOW)
print "setting %d to %s" %(pin, sys.argv[2])
print pin
print state
# Pin ... |
import os
from math import prod
from typing import List, Tuple
from solutions.python.common.files import read_lines, INPUTS_FOLDER
from solutions.python.common.timing import timer
@timer
def multiply_tree_counts_for_several_slopes(area_map: List[str], slopes: List[Tuple[int, int]]) -> int:
return prod(count_tree... |
def genTest():
yield 1
yield 2
yield 3
def genFib():
Fib_1=1 #Fib(n-1)
Fib_2=0 #Fib(n-2)
while True:
#Fib_n=Fib(n-1)+Fib(n-2)
next=Fib_1 +Fib_2
yield next
Fib_1=next
Fib_2=Fib_1
def allCombo(items):
n=len(items)
for i in range (3**... |
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
#%%
app = dash.Dash()
elements = [
dcc.Input(id='my-id',value='Initial Text',type='text'),
html.Div(id='my-div',style={'border':'2px blue solid'})
]
app.layout=html.D... |
import jwt
from flask import jsonify, request
import urls.basic_urls as bu
from models import Car, app, db, Rent, User
from schema import RentSchema
@app.route("/rent", methods=['POST'])
def create_rent():
auth_token = request.args.get('access_token')
try:
keys = bu.decode_auth_token(auth_token)
... |
''' Rotate an array of size n by d elements '''
'''
Algorithm:
Consider arr = [1, 2, 3, 4, 5, 6, 7]
n = 7, d = 2
A = [1, 2] (arr[0] - arr[d-1])
B = [3, 4, 5, 6, 7] (arr[d] - arr[n-1])
Rotate A and B:
Thus,
Ar = [2, 1] and Br = [7, 6, 5, 4, 3]
ArB = [2, 1, 3, 4, 5, 6, 7]
(ArBr)r... |
# 定义函数
# args不定长参数 适用场景:不确定是否有参数,也不确定参数的个数
print("666")
print("44444")
def good_job(salary, bonus, subsidy=4000, *args,**kwargs):
sum1 = salary + bonus + subsidy
for num in args:
sum1 += num
# print(sum1)
# print('参数kwargs为:{}'.format(kwargs))
# 把**kwargs传入的参值与sum1相加求和 ,可以循环遍历
for i in... |
# -*- coding: utf-8 -*-
import benzina.native
import gc
import numpy as np
import torch
import torch.utils.data
from torch.utils.data.dataloader import default_collate
from contextlib import suppress
from . import operations as ops
class Data... |
import math
def solve(n):
if n == 0:
return "INSOMNIA"
seen = set()
for i in range(1, 100):
newn = str(i * n)
for char in newn:
seen.add(char)
if len(seen) == 10:
return newn
return "INSOMNIA"
name = "storage/emulated/0/codejam/A-large"
fi = open(name + ".in", "r")
... |
import os.path
from data.base_dataset import BaseDataset, get_transform
import torch.nn.functional as F
from PIL import Image
import pandas as pd
import numpy as np
import torch
class KeyDataset(BaseDataset):
def initialize(self, opt):
self.opt = opt
self.root = opt.dataroot
if opt.phase =... |
import matplotlib.pyplot as plt
from numpy import cos, arange
t = arange(0, 5.0, 0.01)
x = arange(0, 5.0, 0.01)
plt.plot(t, cos(x**2)/x)
plt.show()
|
import argparse
import numpy as np
import sys
import json
import models
import torch
import torch.nn as nn
from torchvision import transforms
import torch.nn.functional as F
import base
from torch.utils.data import DataLoader, Dataset
import os
from tqdm import tqdm
import PIL
import nibabel as nib
from utils.metrics i... |
from threading import Thread
import os
from queue import Queue
def returnName(name):
print(name)
if __name__ == '__main__':
numThreads = os.cpu_count()
threads = []
for i in range(numThreads):
t = Thread(target=returnName, args=("Bruce Wayne",))
threads.append(t)
for t in threads:
t.start()
for t in th... |
from django.db import models
from django.contrib.auth.models import User
from user.models import Department
# class Comment(models.Model):
# content_object = models.ForeignKey(Homework, on_delete=models.DO_NOTHING)
#
# text = models.TextField()
# comment_time = models.DateTimeField(auto_now_add=True)
# ... |
import os
import argparse
import random
import numpy as np
from utils.misc import get_datetime, str2bool
from utils.file import copy, prepare_dirs, write_record
from tqdm import tqdm
celeba_attr_names = [
'新双颊胡须', '柳叶眉', '吸引人', '眼袋', '秃头',
'刘海', '大嘴唇', '大鼻子', '黑发', '金发',
'模糊', '棕发', '浓眉', '圆胖', '双下巴',
... |
from django.core.management.base import BaseCommand
import os
import logging
import numpy as np
from acacia.meetnet.models import Well
logger = logging.getLogger(__name__)
class Command(BaseCommand):
args = ''
help = 'check raw data for QC3'
def handle(self, *args, **options):
baros = {}
w... |
import pandas as pd
import numpy as np
from app.users_orm import Users, add_user, users_get_all
from app.posts_orm import Posts, add_post
from app.groups_orm import Groups, add_group, groups_get_all
from app.user_subscribes_to_group_orm import UserSubscribes_toGroup, add_user_subscriptions
from app import db
from sqlal... |
import boto3
import time
import sys
profile=sys.argv[1]
region_session = boto3.Session(region_name='us-east-1', profile_name=profile)
r = region_session.client('ec2')
regions = [region['RegionName'] for region in r.describe_regions()['Regions']]
def checkVolumes(region):
volume_session = boto3.Session(region_na... |
import numpy as np
import urllib.request
# url with dataset
url = "http://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data"
# download the file
raw_data = urllib.request.urlopen(url)
# load the CSV file as a numpy matrix
dataset = np.loadtxt(raw_data, delimiter="... |
from django.contrib import admin
# Register your models here.
from .models import Tutor, Tutee
#admin.site.register(Tutor)
#admin.site.register(Tutee)
# Define the admin class
class TutorAdmin(admin.ModelAdmin):
list_display = ('name', 'email', 'mobile_no', 'subjects', 'grade', 'timeslot', 'days')
list_filt... |
import urllib2
import time
import datetime
stocks_to_pull = ['AAPL', 'GOOG', 'MSFT', 'CMG', 'AMZN', 'EBAY', 'TSLA']
def pullDataPart3(stock):
try:
path = 'C:\Users\B40904\Documents\Personal\PythonFinanceCharts\\'
file_line = path+stock+'.txt'
url_to_visit = 'http://chartapi.finan... |
from re import findall
class Date(object):
def __init__(self, year = 0, month = 0, day = 0, hour = 0, minute = 0):
self.__year = year
self.__month = month
self.__day = day
self.__hour = hour
self.__minute = minute
@property
def year(self):
return self.__year
... |
# setuptools script
# Use `python setup.py sdist` to compile to dist/
import setuptools
with open('README.md', 'r', encoding='utf-8') as fh:
long_description = fh.read()
setuptools.setup(
name='demuxfb',
# Date of Facebook 'Download Your Information' data archive creation this
# is built against.
... |
#!/usr/bin/python3
# -*- config:utf-8 -*-
import bs4
import datetime
import requests
import re
import yaml
with open('config.yaml',) as fh:
c = yaml.load(fh.read(), Loader=yaml.FullLoader)
s = requests.Session()
r = s.get(url=c['url'])
b = bs4.BeautifulSoup(r.text, 'html5lib')
f = b.select_one('form#new_user')... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 29 10:04:58 2019
@author: seth
"""
from LSTMClass import LSTMClass as LSTMPrediction
from ProphetClass import ProhetClass as ProhetPrediction
import matplotlib.pyplot as plt
from matplotlib import rcParams
from gather_data import get_data
import nu... |
from django.db import models
from django.contrib.auth.models import User
from django.http import JsonResponse
class Response():
"""
Handle API Responses
"""
def __init__(self, data, status_code=200, message=None):
self.data = data
self.status_code = status_code
def get_obj(self):
... |
import random
import config as Cg
import csv
from copy import deepcopy
import os
def genRuns(low,
num_blocks,
num_study_items):
random.shuffle(low)
exp = {"study": None,
"test": None}
study = []
lure = []
for i in range(num_blocks):
for y in range(num_... |
# -*- coding: utf-8 -*-
"""Main module."""
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""doc for _main.py - """
import logging
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)
import sys
import argparse
import re
import os
import subprocess
import distutils.sysconfig as sysconfig
fr... |
"""drafts.py
Implements drafts behavior for dexterity types"""
import zope.interface
from plone.app.drafts.interfaces import IDraft, IDrafting
from plone.z3cformbuttonoverrides.interfaces import IButtonAndHandlerSubscriber
#Custom Behavior Button Marker Interfaces
class IDraftAutoSaveBehavior(zope.interface.Inte... |
from flask import Flask, request
from flask_restful import Resource, Api
from flask_cors import CORS
import scrapy
app = Flask(__name__)
CORS(app)
api = Api(app)
class DominiosIgnorados(Resource):
def post(self):
try:
dados = request.get_json()
x = scrapy.addDominiosIgnorados(da... |
#Input: [[10,20],[30,200],[400,50],[30,20]]
#Output: 110
# Explanation:
# The first person goes to city A for a cost of 10.
# The second person goes to city A for a cost of 30.
# The third person goes to city B for a cost of 50.
# The fourth person goes to city B for a cost of 20.
# The total minimum cost is 10 + 30 +... |
import unittest
import os
import requests
os.environ["CONFIG_PATH"] = "bg_agg.config.TestingConfig"
from bg_agg import app, models
from bg_agg.database import Base, engine, session
class TestApp(unittest.TestCase):
def setUp(self):
self.client = app.test_client()
# Set up the tables in the datab... |
class Solution(object):
def __init__(self):
self.ans = []
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
alpha = {"2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz"}
def dfs... |
import joblib
import numpy as np
import random
from Agents import modelFreeAgent
from Agents.Collections import ExperienceReplay
from Agents.Collections.TransitionFrame import TransitionFrame
class DeepQ(modelFreeAgent.ModelFreeAgent):
displayName = 'Deep Q'
newParameters = [modelFreeAgent.ModelFreeAgent.Para... |
# hithere.py
name = input("What is your name?")
second = input("What about your second name")
lastname = input ("Whats your last name?")
print("Hello there!")
print(name + " "+ second + " " + lastname)
|
# copied from elastic/ansible-elasticsearch
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
def filter_reserved(users_role={}):
reserved = []
for user_role, details in list(users_role.items()):
if (
"metadata" in details
and "_reserved" in... |
from flask import render_template,redirect,session
from app.models import *
from . import main
import functools
import hashlib
#密码加密
def setPassword(password):
md5 = hashlib.md5()
md5.update(password.encode())
result = md5.hexdigest()
return result
from flask import request
@main.route("/register/",m... |
diccionario ={"España": "Madrid", "Portugal": "Lisboa", "Francia": "Paris"}
#creamos un bucle que recorra las claves y valores del diccionario a la vez y vamos guardando cada pasado
#la clave en pais, y el valor en ciudad
for pais, ciudad in diccionario.items():
respuesta = input(print("Cual es la capital de ", pai... |
#!/usr/bin/env python3
#
#
# Diamond Hunt Marketplace Analyzer
# Author: Samuel Pua (kahkin@gmail.com)
#
##############################################
import json
import requests
import numpy
import sys
from statsmodels.stats.weightstats import DescrStatsW
from collections import OrderedDict
from operator import ite... |
import common
result_file = open("results.json", "a")
#CFI
# micro-snake
protection_time = common.measure_protection_time(["./compile.sh", "inputs/snake.bc", "CFI-build/snake", "snake_sens_list.txt"])
print('CFI snake protection time ' + str(protection_time))
runtime_overhead = common.measure_runtime_overhead(["pyth... |
import numpy as np
EXP = 'exponential'
GAU = 'gaussian'
def exp_vario(h,a=1.0,sill=1.0):
return sill * (1.0 - (np.exp((-h/a))))
def gauss_vario(h,a=1.0,sill=1.0):
return sill * (1.0 - (np.exp((-h**2)/(a**2))))
def dist(p1,p2):
return ((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2)**0.5
class mfgrid():
de... |
"""
This module sets up the meetups model and all it's functionality
"""
import os
from flask import jsonify
from app.api.v2.models.base_model import BaseModel, AuthenticationRequired
class Meetup(BaseModel):
def __init__(self, meetup={}, database=os.getenv('FLASK_DATABASE_URI')):
self.base_model = Bas... |
"""Add chinook models
Revision ID: 13d5b7bf4214
Revises: b7f884f5fc23
Create Date: 2020-06-17 22:23:58.202580
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '13d5b7bf4214'
down_revision = 'b7f884f5fc23'
branch_labels = None
depends_on = None
def upgrade():
... |
# _*_ coding: utf-8 _*_
from loop import Loop
from channel import Channel, Socket
class Client(object):
def __init__(self, addr, coder=None):
self.sock = Socket()
self.addr = addr
self.loop = Loop()
self.ch = Channel(self.sock, self.loop, coder)
self.ch.set_read_callback(s... |
from errors import *
from tools import *
tls_mode = "normal"
tls_ciphers_v12_paranoid = (
"ECDHE-RSA-CHACHA20-POLY1305",
"ECDHE-RSA-AES256-GCM-SHA384",
"ECDHE-RSA-AES128-GCM-SHA256",
"ECDHE-RSA-AES256-SHA384",
"ECDHE-RSA-AES128-SHA256",
)
tls_ciphers_v12_normal = (
"ECDHE-RSA-CHACHA20-POLY13... |
print("Enter the data to list:")
l=[int(x) for x in input().split()]
print(l)
small=l[0]
large=l[0]
for i in range(0,len(l)):
if(l[i]<small):
small=l[i]
else:
large=l[i]
print("The smallest number is:",small)
print("The lagrest number is:",large) |
def fuel(start):
current = start // 3 - 2
while current > 0:
yield current
current = current // 3 - 2
with open("input1") as f:
lines = f.readlines()
result = 0
for mass in lines:
result += sum(fuel(int(mass)))
print(result) |
#컴퓨팅 사고력 카피체크_프로그램
import glob
import chardet
import difflib
import os
import sys
from multiprocessing.pool import ThreadPool
import multiprocessing
# class for unionfind
class disjointSet:
def __init__(self):
self.elements = {}
def makeSet(self, x):
if x not in self.elements:
self... |
import numpy as np
def lumpy_backround(dim=(64, 64), nbar=200, dc=10, lump_function="GaussLmp", pars=(1, 10),
discretize_lumps_positions=False, rng=None):
"""
: param dim: Output image dimensions. Can be 2D tuple or int (will convert it to a square image)
: param nbar: Mean number of l... |
import Information_Retrieval as IR
from tkinter.filedialog import askopenfilename
from PIL import Image
from tkinter import messagebox
import os
try:
# Python2
import Tkinter as tk
except ImportError:
# Python3
import tkinter as tk
window = tk.Tk()
window.eval('tk::PlaceWindow %s center' % window.winf... |
__all__ = ()
from scarletio import RichAttributeErrorBaseType
CATEGORIES = {}
class TriviaCategory(RichAttributeErrorBaseType):
"""
Represents a trivia category.
Attributes
----------
id : `int`
The category's identifier.
items : `tuple` of ``TriviaItem``
Possibilities ... |
#!/bin/python3
import sys
N = int(input().strip())
L=[]
for a0 in range(N):
firstName,emailID = input().strip().split(' ')
firstName,emailID = [str(firstName),str(emailID)]
if emailID.find('@gmail.com')!=-1 :
L.append(firstName)
L.sort()
for tmp in L:
print(tmp)
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-01-19 23:29
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0087_auto_20170120_0201'),
]
operations = [
mig... |
from Prac_06.guitar import Guitar
def main():
list_of_guitars = []
print("My Guitars!")
name = input("Name: ")
while name != "":
year = int(input("Year: "))
cost = float(input("Cost: $"))
guitar_to_add = Guitar(name, year, cost)
list_of_guitars.append(guitar_to_add)
... |
from Purchase import Purchase
class Splitter:
def split_request(self, post_body):
print(post_body)
catagories = post_body.decode("utf-8").split("&")
phones = catagories[0].replace('+', ' ')[catagories[0].index("=") + 1:].split("%2C")
phone_lines = catagories[1][catagories[1].index(... |
#coding:utf8
import os
import json
import sys
import re
import MySQLdb
import time
reload(sys)
from jobs import utils
from jobs.majorposition import get_position
import codecs
sys.setdefaultencoding('utf8')
import pdb
start = time.clock()
# postdct = get_position.get_pos()
def get_position_meta():
... |
from structlog import get_logger
logger = get_logger()
class Manage:
def __init__(self, config, engine):
self._config = config
self._engine = engine
def drop(self):
db_connection = self._config['uri']
db_schema = self._config['schema']
# fix-up the postgres schema:
... |
#! /usr/bin/env python3
"""Firmware implementing echoing line inputs."""
import sys
def main():
"""Print some header and echo the output."""
print("Starting RIOT Ctrl")
print("This example will echo")
while True:
print(input())
if __name__ == "__main__":
sys.exit(main())
|
#!/usr/bin/python3
# coding: utf-8
"""
Programme : fichierCsv.py version : 1.0
Auteur : H. Dugast
Date : 02-05-2017
Matériel utilisé : ordinateur sous windows (avec wing ide par exemple)
Fonctionnement programme :
Manipulation de données dans un fichier au format CSV
"""
import os
import csv
import time
pathFich ... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# To run in terminal
# $ cd /home/james/Documents/Edoc/3Nohtyp/Python_By_Example/Example_051
# $ python3 Example_051.py
# $ python3 Example_051.py <Input.txt >Output.txt
"""
Python by Example: Learning to Program in 150 Challenges by Nichola Lacey
051
Using the song “10 gre... |
from django.db import models
import datetime
# Create your models here.
class Bucket(models.Model):
name = models.CharField("Bucket Name", max_length=200)
datetime = models.DateTimeField("Date TIme", default=datetime.datetime.now())
def __str__(self):
return self.name
class Todo(models.Model):
... |
# -*- coding: utf-8 -*-
from apollo.factory import create_celery_app
celery = create_celery_app()
from apollo.formsframework.tasks import update_submissions
from apollo.messaging.tasks import send_messages, send_email
from apollo.participants.tasks import import_participants
from apollo.locations.tasks import import_... |
# -*- coding: utf-8 -*-
# Created on Mon Jul 17 2018 15:35:57
# Author: WuLC
# EMail: liangchaowu5@gmail.com
class Solution(object):
def binaryGap(self, N):
"""
:type N: int
:rtype: int
"""
result = 0
pre, curr = -1, 0
while N:
if (N&1) == 1:
... |
"""
Time Based Key-Value Store
Create a time based key-value store class TimeMap, that supports two operations.
1. set(string key, string value, int timestamp)
Stores the key and value, along with the given timestamp.
2. get(string key, int timestamp)
Returns a value such that set(key, value, timestamp_prev) w... |
import tensorflow as tf
import vectorize_graph
import numpy
import random
tf.set_random_seed(7)
# Parameters
learning_rate = 0.001
training_epochs = 100
#batch_size = 100
display_step = 1
# Network Parameters
n_hidden_1 = 3 # 1st layer number of features
n_hidden_2 = 3 # 2nd layer number of features
n_input = 5 # MNI... |
from controller.DisciplineController import DisciplineController
from controller.GradeController import GradeController
from controller.StudentController import StudentController
from domain.Discipline import Discipline
from domain.Grade import Grade
from domain.Student import Student
from repository.DisciplineRe... |
#!/usr/bin/env python3
import os
import pandas as pd
import xlsxwriter
def save(result, x):
"""
This function saves the results(concatenated dataframes) into an Excel file.
:param result: concatenated dataframes
:param x: number of dataframes
"""
filename = 'New %s files.xlsx' % x
writer ... |
import os
import sys
import re
from collections import defaultdict, deque
def breadth_search(graph, start):
visited, queue = set(), deque(start)
while queue:
vertex = queue.popleft()
if vertex not in visited:
visited.add(vertex)
queue.extend(graph[vertex])
p... |
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
import pandas as pd
import plotly.graph_objs as go
from dash.dependencies import Input, Output
import dash_table
from webapp import app
import ctransforms
df = ctransforms.df
layout = html.Div(
... |
for i in range(1,21):
if i % 2 == 0:
print(i,"on paarisarv")
else:
print(i,"on paaritu arv") |
# bbc-text.csv
import csv
import tensorflow as tf
from tensorflow.keras import layers, Input, regularizers
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
import tensorflow_datasets as tfds
import numpy as np
import matplotlib.pyplot as mpplot... |
# -*- coding:utf-8 -*-
from typing import List
class Solution:
def PredictTheWinner(self, nums: List[int]) -> bool:
nums_len = len(nums)
if nums_len == 0 or nums_len == 1: return True
# dp[i][j]表示nums从i到j中, 先手比后手多的数值
dp = [[0 for j in range(nums_len)] for i in range(nums_len)]
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.