text stringlengths 8 6.05M |
|---|
### Chapter 7: Python 101 :Jimmy Moore ###
# Ex. 7.1
file = raw_input ('Enter a file name: ')
try:
fhand = open(file)
except:
print 'Cannot open file : ', file
exit()
for line in fhand:
line = line.rstrip()
print line.upper()
# Ex. 7.2
file = raw_input ('Enter a file name: ')
try:
fhand =... |
import math
grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
def print_grades(grades):
for grade in grades:
print grade
def grades_sum(grades):
total = 0
for grade in grades:
total += grade
return total
def grades_average(grades):
sum_of_grades = grades_sum... |
# -*- coding: utf-8 -*-
import unittest
from django.test.testcases import TestCase, override_settings
from mock import patch, Mock, MagicMock, call
from stretch import stretch_app
from stretch.tests.base import get_connection
from example.models import Foo
from example.stretch_indices import FooIndex
def setUpModul... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponse
from adafruit_motorkit import MotorKit
from adafruit_motor import stepper
import time
import subprocess
RESPONSE_STRING = "Welcome back!"
RUN_CMD = "sudo p... |
from django.shortcuts import render, HttpResponse
from web_app.models import *
from web_app.serializers import *
from rest_framework.views import APIView
from django.http import JsonResponse
# Create your views here.
def index(request):
return HttpResponse('你好')
# http://127.0.0.1:8000/news/?id=1
def news_conten... |
__author__ = 'Bill'
import graphlab as gl
import math
## Load training data
train = gl.load_sframe("/Users/Bill/Dropbox/cs151/ctr/full_train_data")
train.remove_column("hour")
train.remove_column("id")
train["click"] = train["click"].astype(int)
subset = train[1:100]
print train.groupby("click", {'count': gl.aggrega... |
#criar um arquivo e armazenar um registro
nome = input("Digite o nome: ")
idade = input("Digite a idade: ")
cpf = input("Digite o CPF: ")
registro = '\n' + nome + ';' + idade + ';' + cpf + ';'
with open('registro.txt','a+') as f:
f.write(registro)
exit()
cpf = input('Digite o cpf: ')
with open('arquivo_pessoa.jso... |
from turtle import Turtle,Screen
import time
UP = 90
DOWN = 270
LEFT = 180
RIGHT = 0
class Snake:
def __init__(self):
self.screen = Screen()
self.snake = [Turtle(shape="circle") for _ in range(3)]
self.screen.bgcolor("black")
self.screen.setup(width=600,height=600)
self.sc... |
#!python3
"""
Implementation of a directed Graph Class
"""
from graphs.vertex import Vertex
class Digraph:
def __init__(self):
"""
Initializes a graph object with an empty dictionary.
self.edge_list -> List of the edges
self.num_verticies -> Number of verticies
self.num_edg... |
import selenium.webdriver as webdriver
from constants import driver_path
def has_digits(input_str):
return any(char.isdigit() for char in input_str)
def start_headless_driver():
options = webdriver.ChromeOptions()
options.add_argument('headless')
return webdriver.Chrome(executable_path=driver_path, ... |
import base64
#encoding=utf-8
data="我爱你中国"
data=data.encode("utf-8")
data_b64=base64.b64encode(data)
data2=str(data_b64,'utf-8')
# print("data:",data)
# print("type:",type(data))
# print("data_b64",data_b64)
# print("tpye2:",type(data_b64))
# print("data2:",data2)
# print("tpye3:",type(data2))
#解密 data2
data2=data2.en... |
from datetime import date
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from rest_framework import serializers
from .models import Profile,TermsConditionsText,TermsConditions
from hrr.fitbit_aa import belowaerobic_aerobic_anaerobic
class UserSerializer(serializers.ModelS... |
from appium_auto.three.page.base_page import BasePage
from py_test.pytest_shuju_qudong.page.market import Market
class Search(BasePage):
def search(self, value):
self._param["value"]=value
self.steps("../page/search.yaml")
return Market(self._driver) |
from helper import helper
from score import score
import random as rm
import math as m
import sys
import copy
import time
import matplotlib.pyplot as plt
import numpy as np
''' Survival of the Fittest algorithm'''
def populationBased(populationSize, mel, mir):
'''
A population based optimization algorithm based on g... |
#!/usr/bin/python3
'''
Creation, Updating, Deleting functions from Flask application
'''
import models
from models import storage
from app import application
from flask import render_template, flash, redirect, url_for, request, session
from flask import jsonify, abort
from app.forms import CreateTrip
from flask_log... |
#!/usr/bin/python3
"""
Copyright (c) 2015, Joshua Saxe
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of con... |
MAX_RANK = 15000
PER_PAGE = 25
TYPES = dict(
designers='designer',
publishers='publisher',
artists='artist',
mechanics='mechanic',
)
WAR_RANK = 500 |
#! /usr/bin/python
# coding=utf-8
import time
import select
import sys
import os
import RPi.GPIO as GPIO
import numpy as np
import picamera
import picamera.array
import matplotlib.pyplot as plt
import time
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import math
import os
from car impo... |
from memoize import memoized
def is_complete(csp, assignment):
w, h, horiz_constr, vert_constr = csp
return len(assignment) == h
@memoized
def order_domain_values(csp, var):
w, h, horiz_constr, vert_constr = csp
# calculate the possible lengths and movements
# generate the numbers by moving sequ... |
from setuptools import setup, Extension
def readme():
with open('README.md') as f:
return f.read()
PACKAGES = ['cornichon']
PACKAGE_DATA = {
'.': ['README.md']
}
# import distutils.sysconfig
setup(name='cornichon',
version='0.1',
description='A way to save the data of a class in pytho... |
class Solution:
# https://leetcode.com/problems/reverse-integer/discuss/4220/Simple-Python-solution-56ms
# https://leetcode.com/problems/reverse-integer/discuss/4055/Golfing-in-Python
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
def sign(x): return x and (... |
__author__ = "Narwhale"
import socket
client = socket.socket()
client.connect(('localhost',10000))
while True:
mag = input('>>>>:')
if not mag:
break
client.send(mag.encode(encoding='utf-8'))
data = client.recv(1024)
print(data)
|
#!/usr/bin/env python
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="onglai-classify-homologues",
version="1.0.0",
author="Adelene Lai",
author_email="adelene.lai@uni.lu",
maintainer="Adelene Lai",
maintainer_email="adelene.lai@un... |
"""Abstract base class for MSSM calculation."""
import json
import logging
import math
import pathlib
from typing import List, Optional
import simsusy.mssm.library
from simsusy.mssm.input import MSSMInput
logger = logging.getLogger(__name__)
class AbsSMParameters:
"""
The abstract version of the Standard M... |
print('='*30)
print('Sequeência de Fibonacci')
print('-' *30)
n = int(input('Digite quantos termos você deseja? '))
t1 = 0
t2 = 1
c=3
print(' {} -> {} ->'.format(t1, t2), end='')
while c <= n:
t3 = t1+t2
print(' ->{}'.format(t3), end='')
t1 = t2
t2 = t3
c = c+1
print(' -> FIM!')
|
# -*- coding: utf-8 -*-
import unittest
from datetime import datetime
from flask import Flask
from flaskext.mongokit import MongoKit, BSONObjectIdConverter, \
Document, Database, Collection
from werkzeug.exceptions import BadRequest
from bson import ObjectId
class BlogPost(Document):
... |
import numpy as np
import cv2
def contour():
img = cv2.imread('images/star.jpg')
imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thr = cv2.threshold(imgray, 127, 255, 0)
_, contours, _ = cv2.findContours(thr, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnt = contours[0]
hull = cv2.convexHull... |
# -*- coding: utf-8 -*-
import re
from colormath.color_objects import sRGBColor, LabColor
from colormath.color_conversions import convert_color
from colormath.color_diff import delta_e_cie2000
from pycolorname.color_system import ColorSystem
class CalPrint(ColorSystem):
def __init__(self, *args, **kwargs):
... |
from script.base_api.api_operation_app.memberships import *
from script.base_api.api_operation_app.pay import *
from script.base_api.api_operation_app.versionInfo import *
from script.base_api.api_operation_app.employee import *
from script.base_api.api_operation_app.public import *
from script.base_api.api_operat... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__license__ = ''
__version__ = '1.0.1'
get_timezone_list_query = """
SELECT *
FROM public.time_zone AS tmz
WHERE tmz.deleted is FALSE
AND (
$1::VARCHAR is NULL OR
tmz.name ILIKE $1::VARCHAR || '%' OR
tmz.name ILIKE '%' || $1::VARCHAR || '... |
import string
import random
def gen():
s1 = string.ascii_uppercase
s2 = string.ascii_lowercase
s3 = string.digits
s4 = string.punctuation
passlength = int(input("Enter the password length\n"))
s = [] # Created a empty list
s.extend(list(s1))
s.extend(list(s2))
s.e... |
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2013-2015 Marcos Organizador de Negocios SRL http://marcos.do
# Write by Eneldo Serrata (eneldo@marcos.do)
#
##############################################################################
from... |
from flask import render_template, redirect, url_for, flash, get_flashed_messages
from market import app
from market.forms import RegisterForm
from market.models import U2Message
app_styles = {}
base_style = "body { background-color: purple; color: white }"
app_styles['base'] = base_style
@app.route('/')
@app.route('... |
# This file is part of beets.
# Copyright 2016, Fabrice Laporte.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy,... |
from gala import imio
import h5py
import numpy as np
from skimage._shared._tempfile import temporary_file
def test_cremi_roundtrip():
raw_image = np.random.randint(256, size=(5, 100, 100), dtype=np.uint8)
labels = np.random.randint(4096, size=raw_image.shape, dtype=np.uint64)
for ax in range(labels.ndim):... |
# Create your views here.
from django.http import HttpResponse
from django.template import Context, loader
from django.http import Http404,HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404,render
from storefront.models import Store,StoreAdmin ... |
from django.contrib import admin
# Register your models here.
from tags.models import TagTeacher, TagOpening, ViewTeacherUnique, ViewOpening, FavTeacher, FavOpening, ViewTeacherRecord, ViewTeacherNonUnique, SearchWordTeacherRecord, BlockUser
class SearchWordTeacherRecordAdmin(admin.ModelAdmin):
list_display = ['__u... |
#WAP to print all the even numbers upto a given number
n=input('Enter end point of even numbers :')
count=0
for i in range(0,n-1,2):
i=i+2
print i,
count=count+i
print""
print count
|
#!/usr/bin/env python
#
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
import argparse as arg
import pandas as pd
import numpy as np
import xlwings as xw
import os
import shutil
import time
#parser = arg.ArgumentParser()
#parser.add_argument("-g", default="total", help="machine group")
#args = parser.parse_args()
smonth = "2017.09"
stable = "行为规范表"
sfolder = smonth + "月"... |
import os
import pickle
import numpy as np
import pandas as pd
from functools import reduce
import config as cfg
import utils
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-spy", type=str, help="Path to the raw SPY data file", required=True)
parser.add_argument("-dia", type=str, help="Path t... |
VERSION = (1, 3, 1)
from .decorators import job
from .queues import enqueue, get_connection, get_queue, get_scheduler
from .workers import get_worker
|
# -*- coding: utf-8 -*-
from functools import reduce
def str2float(s):
def fn(x, y):
return x * 10 + y
n = s.index('.') #区分字符串'.'的位置
s1 = map(int, s[:n])
s2 = map(int, s[n+1:]) #小数点前后分别处理
no = 0.1**len(s[n+1:]) #小数位
return reduce(fn, s1) + reduce(fn, s2) * no
print('str2float(\'123.4... |
"""
Check for statements that pertain to personal, rather than profession, life.
Letters for women are more likely to discuss personal life.
Goal: Develop code that can read text for terms related to personal life like
family, children, etc. If the text includes personal life details; return a
summary that directs th... |
#! python3
"""
Have the user enter a username and password.
Repeat this until both the username and password match the
following:
username: admin
password: 12345
(2 marks)
inputs:
str (username)
str (password)
outputs:
Access granted
Access denied
"""
username = str(input("Enter a username ")).strip()
password = str... |
# Python 2.7
import logging
import json
import socket
import subprocess
import os
from httplib import HTTPConnection
STATE = dict(Yellow="PORT11=0:NC PORT12=128:NC PORT13=0:NC",
Red="PORT11=0:NC PORT12=0:NC PORT13=128:NC",
Green="PORT11=128:NC PORT12=0:NC PORT13=0:NC",
Off="PO... |
from django.http import HttpResponse
class AppMaintainanceMiddleware(object):
def __init__(self,get_response):
self.get_response=get_response
def __call__(self,request):
return HttpResponse('<h1> currently application is under maintainance! <p style="color:red;">please try again later.!</p> th... |
test_str = "Hey, I'm a string, and I have a lot of characters...cool!"
print (test_str)
print ("String length:", len(test_str)) |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015 Niklas Rosenstein
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy,... |
import numpy as np
from . import process_image as module
def test_get_ROI_statistics():
# fmt: off
mock_ROI = np.array([
[[1, 10, 100], [2, 20, 200]],
[[3, 30, 300], [4, 40, 400]]
])
# fmt: on
actual = module.get_ROI_statistics(mock_ROI)
expected = {
"r_msorm": 2.5,
... |
# -*- coding: utf-8 -*-
# author: kiven
import os
DEBUG = True
TIME_ZONE = 'Asia/Shanghai'
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, '../omsBackend.db'),
}
}
# 开启lda... |
#!/usr/bin/env python3
import pwn
"""
Idea:
1. Need to delete the two instances by sending "3\n"
2. Need to feed in data through a file ./uaf <length> <file-with-length-data> and by sending "2\n"
such that the virtual table will point to a table containg the function named 'give_shell'.
But do we need to know a... |
class Solution(object):
def findDiagonalOrder(self, matrix):
if not matrix or not matrix[0]:
return []
result = []
N = len(matrix)
M = len(matrix[0])
#Iterate over heads
for d in range(M + N - 1):
inter = []
if d < M:
... |
../numpy/stats.py |
import numpy as np
from sklearn import linear_model
import pickle
import definitions
import os
from wsdm.ts.features import word2VecFeature
from wsdm.ts.helpers.regression import regression_utils
def get_data_and_labels(inputType):
if inputType == definitions.TYPE_NATIONALITY:
filename = os.path.join(defi... |
import dash_bootstrap_components as dbc
breadcrumb = dbc.Breadcrumb(
items=[
{"label": "Docs", "href": "/docs", "external_link": True},
{
"label": "Components",
"href": "/docs/components",
"external_link": True,
},
{"label": "Breadcrumb", "active"... |
from backpack.core.derivatives.batchnorm1d import BatchNorm1dDerivatives
from .base import GradBaseModule
class GradBatchNorm1d(GradBaseModule):
def __init__(self):
super().__init__(
derivatives=BatchNorm1dDerivatives(), params=["bias", "weight"]
)
|
#!/usr/bin/env python
import cProfile
import uproot
import awkward as ak
import pandas as pd
import argparse
import fastjet as fj
import fjext
import tqdm
class ALICEDataConfig:
event_tree_name = "PWGHF_TreeCreator/tree_event_char"
track_tree_name = "PWGHF_TreeCreator/tree_Particle"
def __init__(self) -> None:
... |
import typing
from typing import TYPE_CHECKING
if TYPE_CHECKING: # pragma: no cover
from kerasltisubmission import AnyIDType
class KerasLTISubmissionBaseException(Exception):
pass
class KerasLTISubmissionBadModelException(KerasLTISubmissionBaseException):
pass
class KerasLTISubmissionInputException(... |
#!/usr/bin/env python
# coding=utf-8
# Jesus Tordesillas, jtorde@mit.edu
# date: July 2020
import math
import os
import sys
import time
import rospy
from snapstack_msgs.msg import State
import subprocess
import rostopic
def waitUntilRoscoreIsRunning():
# https://github.com/ros-visualization/rqt_robot_plugins/blo... |
"""URLs for bcauth."""
from django.conf.urls import patterns, url
bcauth_urlpatterns = patterns(
'bcauth.views',
url(r'^accounts/$', 'account', name='account_base'),
url(r'^accounts/profile/$', 'profile', name='account_profile'),
)
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2019-04-08 12:37
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('apple', '0005_auto_20190408_1229'),
]
operations = [
migrations.RemoveField(
... |
import socket
import struct
import binascii
import random
while True:
role = str(input("server/client? [s/c]: "))
if role == 'c' or role == 's':
break
while True:
reports = input("reports? [y/n]: ")
if reports == 'y' or reports == 'n':
break
if role == 'c':
s = socket.socket(socke... |
# Functions needed for training models
from __future__ import unicode_literals, print_function, division
from io import open
import unicodedata
import string
import re
import random
from random import shuffle
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch import optim
import torch.n... |
import numpy as np
import pandas as pd
import os
from io import StringIO
import matplotlib.pyplot as plt
from collections import Counter
cwd = os.getcwd()
print(cwd)
path = "/Users/janmichaelaustria/Documents/Data Sets"
os.chdir(path)
cwd = os.getcwd()
print(cwd)
celebrities = pd.read_csv("celebrity_deaths_4.csv"... |
# -*- coding: utf-8 -*-
from app.utils import formatting
from formalchemy import FieldSet
from formalchemy.fields import Field
from formalchemy.tables import Grid
import datetime
import operator
def create_generic_date_field(name, attr_getter, dt_format, today_by_default=True):
""" Instanciates a generi... |
# Generated by Django 2.2.2 on 2019-06-04 11:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('DBCalls', '0002_auto_20190604_1054'),
]
operations = [
migrations.AlterField(
model_name='collection',
name='colID',... |
import random
from sdfbuilder.math import Vector3
from revolve.util import Time
from revolve.angle import Robot as RvRobot
class Robot(RvRobot):
"""
Class to manage a single robot
"""
def __init__(self, conf, name, tree, robot, position, time, battery_level=0.0, parents=None):
"""
:p... |
import os
from email.mime.image import MIMEImage
from django import forms
from django.conf import settings
from django.contrib.auth import authenticate, get_user_model, login
from django.contrib.auth.forms import PasswordResetForm as DjangoPasswordResetForm
from django.core.mail import EmailMultiAlternatives
from djan... |
import requests
import pandas as pd
# 데이터 포맷팅
pd.options.display.float_format = '{:,.2f}'.format
pd.set_option('mode.chained_assignment', None)
# url: 서버 주소
url = 'http://data.krx.co.kr/comm/bldAttendant/getJsonData.cmd'
# header: 브라우저 정보
headers = {
'User-Agent': 'Mozilla/5.0',
'Origin': 'http://data.krx.co.... |
from pathlib import Path
p = (Path(__file__).parent)/ "testingstuff.py"
with open(p) as f:
print(f.readlines())
with p.open() as f:
print(f.readlines()) |
fin=open('outputname.txt','r')
fout=open('outhypo.txt','w')
lines=fin.readlines()
nums='0123456789'
for line in lines:
linechange=line[20:]
if linechange[30]=='\t':
linechange=linechange[0:29]+'0'+linechange[29:]
#line=linechange
if len(linechange)>33:
... |
from django.test import TestCase
from django.utils.html import escape
from lists.models import Item, List
from lists.forms import (
DUPLICATE_ITEM_ERROR, EMPTY_ITEM_ERROR,
ExistingListItemForm, ItemForm,
)
# Create your tests here.
class HomePageTest(TestCase):
"""Home page test"""
def test_uses_home... |
import numpy as np
def dcg_at_k(r,k):
r = np.asfarray(r)[:k]
if r.size:
return np.sum( np.subtract(np.power(2,r),1)/np.log2(np.arange(2,r.size+2)))
return 0.
def ndcg_at_k(r,k):
idcg = dcg_at_k( sorted(r,reverse=True),k)
if not idcg:
return 0.
dcg = dcg_at_k(r,k)
return dcg/i... |
"""
Module containing Debug Methods and sites.
This Module should only be loaded in debug Mode.
"""
from flask.app import Flask
from . import root # noqa
from . import routes # noqa
def register_debug_routes(app: Flask):
"""Register the debug routes blueprint with the flask app."""
if not app.config["DEBU... |
#!/usr/bin/python
from typing import TYPE_CHECKING
import pygame
from glm import ivec2
from pygame.surface import SurfaceType
from game.base.script import Script
from game.base.signal import Signal, SlotList
from game.constants import *
from os import path
from game.util import *
if TYPE_CHECKING:
from game.bas... |
'''
imputationflask.secrets
-------------------
Gets secrets from google cloud secret manager. Relies on proper IAM
'''
from google.cloud import secretmanager
def csrf_key(config):
client = secretmanager.SecretManagerServiceClient()
name = client.secret_version_path(
config['PROJECT_NAME'], config[... |
########################
####### BRIDGE #########
########################
# This acts as a bridge between the services and the launcher for the application
import argparse as arg
import sys
from . import logo
from . import recommendation
from . import index_data
from . import searchp
from . import preprocess
from . ... |
# Generated by Django 3.0.6 on 2020-06-02 19:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('LaF', '0011_auto_20200603_0026'),
]
operations = [
migrations.AlterField(
model_name='lost',
name='image',
... |
#!/usr/bin/python
# # -*- coding: utf8 -*-
import re
# reading and decoding input files
#textFile = ["/home/darya/work/lingvo_data/sample2.txt"]
textFile = ["/home/darya/work/lingvo_data/Rasshifrovki_125-147.txt",
"/home/darya/work/lingvo_data/Rasshifrovki_do_I99.txt",
"/home/darya/wor... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 12 23:49:52 2018
@author: koyyk_000
"""
#given S
#
#for i=1:3
#
# split S into S_train (80%) and S_test (20%)
#
# train Classifier 1 using S_train with cross-validation, report Classifier 1's cross-validation errors (S_train) and test error (S_test)
#... |
import logging
from six.moves import input
from django.core.management import BaseCommand, CommandError, call_command
from elasticsearch_dsl import connections
from stretch import stretch_app
class Command(BaseCommand):
"""
Update Elasticsearch Documents
"""
can_import_settings = True
def add_... |
from gym_SnakeGame.envs.SnakeGame import SnakeGameEnv
|
#!/usr/bin/python3
import os
import requests
import configparser
class Venmo:
def __init__(self):
self.session = requests.session()
self.username = None
self.phone_number = None
self.name = None
self.access_token = None
self.balance = None
self.id = None
... |
class store(object):
def __init__(self, products, location, owner):
self.products = products
self.location = location
self.owner = owner
def add_product(self, new_product):
self.products.append(new_product)
return self
def remove_product(self, remove_product... |
from rest_framework import serializers
from .models import Payment
class CategorySerializer(serializers.Serializer):
name = serializers.CharField(max_length=64)
description = serializers.CharField(max_length=1024)
url = serializers.CharField(max_length=64)
image = serializers.FileField()
class Compe... |
###
### Copyright (C) 2018-2019 Intel Corporation
###
### SPDX-License-Identifier: BSD-3-Clause
###
from ....lib import *
from ..util import *
from .encoder import EncoderTest
class MPEG2EncoderTest(EncoderTest):
def before(self):
vars(self).update(
codec = "mpeg2",
ffenc = "mpeg2_vaapi",
... |
import sys
tmp = sys.argv[1:]
from random import randint as rint
N = int(tmp[0])
Xmin = -rint(1, N*100)
Xmax = rint(1,N*100)
Ymin = -rint(1,N*100)
Ymax = rint(1,N*100)
filename = "test"
f = open(filename, "w+")
f.write(str(N) + '\n')
for i in range(N):
x = rint(Xmin, Xmax)
y = rint(Ymin, Ymax)
f.write(str(x) + '... |
from peewee import DateTimeField, BooleanField, ForeignKeyField
from model.BaseModel import BaseModel
from model.Mentor import Mentor
class InterviewSlot(BaseModel):
start_time = DateTimeField()
end_time = DateTimeField()
reserved = BooleanField()
mentor = ForeignKeyField(Mentor, related_name='interv... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn import datasets
from sklearn import svm
from sklearn.semi_supervised import label_propagation
from sklearn import decomposition
from sklearn import metrics
train = pd.read_csv("C:/Users/ASUS/Des... |
# -*- coding: utf-8 -*-
"""
Boxy Theme Presets
"""
import sublime
import sublime_plugin
from collections import OrderedDict
NO_SELECTION = -1
PREFERENCES = 'Preferences.sublime-settings'
OPTIONS = [
'theme_accent_blue',
'theme_accent_cyan',
'theme_accent_green',
'theme_accent_lime',
'theme_accent_orange',
'th... |
import autodisc as ad
from autodisc.cppn.selfconnectiongenome import SelfConnectionGenome
import neat
import copy
import random
class TwoDMatrixCCPNNEATEvolution:
@staticmethod
def default_config():
def_config = ad.Config()
def_config.neat_config_file = 'neat.cfg'
def_config.matrix_siz... |
from rest_framework import serializers
from film.models import origin
class originSerializers(serializers.ModelSerializer):
class Meta:
model = origin
fields = '__all__'
class originOnSerializers(serializers.ModelSerializer):
class Meta:
model = origin
fields = ['name']
|
"""
This module will manage Command Line Interface (CLI) for gpio-monitor.
It will parse argument and build a configuration reference for gpio-monitor.
For more information about argparse, see https://docs.python.org/3/library/argparse.html
"""
import argparse
class Config: # pylint: disable=too-few-public-methods
... |
from django.apps import AppConfig
class MusicrunConfig(AppConfig):
name = 'musicRun'
|
import math
a = 1
b = 1
if a == b:
print ('1 through 10')
a = 11
while a > 1:
a = a - 1
print(a)
def factorial(a):
b = a
while b > 1:
b = b - 1
a = a * b
return a
print(factorial(11))
def nchoosek(n,k):
f = factorial(n)/(factorial(n-k)*factorial(k))
return f
pr... |
from manta import note_from_pad, OFF, AMBER, RED, pad_from_note
class MantaSeqState(object):
def __init__(self, manta_seq):
self.manta_seq = manta_seq
def process_step_press(self, step_num):
pass
def process_step_release(self, step_num):
pass
def process_shift_press(self):
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 12 19:19:35 2015
@author: LIght
"""
from sklearn.decomposition import ProjectedGradientNMF
import utility
import numpy as np
import pandas as pd
##use of NMF
class NMF:
@staticmethod
def groupMovieGenre(user_item_matrix,item_df):
genre_num = 50
... |
import controller
import model # See how update_all should pass on a reference to this module
#Use the reference to this module to pass it to update methods
from ball import Ball
from floater import Floater
from blackhole import Black_Hole
from pulsator import Pulsator
from hunter import Hunter
from spec... |
def mintot(triangle):
n = len(triangle)
if n == 1:
return triangle[0][0]
if n == 2:
arr = triangle[1]
if arr[0] < arr[1]:
return triangle[0][0] + arr[0]
else:
return triangle[0][0] + arr[1]
elif n > 2:
bob1 = []
bob2 = []
fo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.