text stringlengths 8 6.05M |
|---|
# 桶子演算法
"""
桶子排序法 (Bucket Sort) 想法很簡單,其實就是準備幾個桶子,將要排序的資料分類丟至指定的桶子中,
再依序將桶子裡的東西取出。有點類似資源回收的概念啦~
O(M + N)
"""
# 題目: 將資料 (分數) 由小到達排序
data = [89, 34, 23, 78, 67, 100, 66, 29, 79, 55, 78, 88, 92, 96, 96, 23]
# 結果: data = [23, 23, 29, 34, 55, 66, 67, 78, 78, 79, 88, 89, 92, 96, 96, 100]
def bucket_sort(data):
# 1. 生成桶... |
from PIL import Image, ImageDraw, ImageFont
import numpy as np
def create_DB():
# generate char imgs:
from PIL import Image, ImageDraw, ImageFont
IMG_WIDTH = 10
IMG_HEIGHT = 15
fnt = ImageFont.truetype('arial.ttf', 15)
chars = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o... |
import os
import csv
from itertools import chain
with open('cloudwatch_logs.csv', 'r') as f:
reader = csv.reader(f)
security_groups = list(reader)
for sg in security_groups:
print("\nChanging retention on Log Group: {}".format(str(sg)[2:-2]))
os.system("aws ec2 delete-security-group --group-id {}".for... |
# Original
bool1 = True;
store1 = 0;
store2 = 0;
store3 = 0;
store4 = 0;
list1 = []
while(bool1 == True):
keys = input("Directions in ^ (North) or v (South) or < (East) or > (West): ")
if(keys == "^"):
store1 += 1
print("store1", store1)
list1.append("store1")
elif(keys == ">"):
... |
#!/usr/bin/python
# EA to check for Safari's opening "safe" files on download
import CoreFoundation
domain = 'com.apple.Safari'
key = 'AutoOpenSafeDownloads'
key_value = CoreFoundation.CFPreferencesCopyAppValue(key, domain)
if key_value == 0:
print "<result>Disabled</result>"
else:
print "<result>Enabled</... |
import numpy
from xversion.model import *
'''
每次都会给一整棵树,所以
'''
class Painter(object):
start_point = numpy.array([0, 0, 0])
base_vector = numpy.array([0, 0, 10])
tree_string = ''
n = 0
def __init__(self, tree):
self.tree = tree
self.tree_string = tree.axiom
# Every time this ... |
from src.abcnn.graph import Graph
from src.abcnn import args
import tensorflow as tf
import os
import numpy as np
import pandas as pd
from src.utils import singleton
import logging
import logging.config
from src.config import AbcnnConfig
@singleton
class AbcnnModel:
def __init__(self):
self.model = Graph(T... |
#!/usr/bin/python3
import sys
a = 1
while a < 26:
for i in sys.argv[1]:
ch = ord(i) + a
if ch > 122:
ch -= 26
print(chr(ch), end="")
print('')
a += 1
|
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
count = 0
mem = 0
f = open("data.txt", 'r')
g = open("output2.txt", 'w')
for line in f:
count = count + 1
splitline = line.split()
print splitline
if splitline:
if is_number(splitline[0]... |
from django.shortcuts import render
def home_page(request):
context ={
"title": "Hello World!",
"welcome": "Welcome to the homepage",
"premium_content": "YEAHHH"
}
# print(request.session.get('first_name', 'Unknown'))
return render(request, "home_page.html", context)
def abou... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import pytest
from pants.base.specs import (
AddressLiteralSpec,
AncestorGlobSpec,
DirGlobSpec,
DirLiteralSpec,
RawSpecsWithoutFile... |
# Copyright 2018 Davide Spadini
#
# 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... |
import matplotlib.pyplot as plt
import numpy as np
def f(x, y):
return x**2 + y**2 / 4
x = np.linspace(-5, 5, 300)
y = np.linspace(-5, 5, 300)
xmesh, ymesh = np.meshgrid(x, y)
z = f(xmesh, ymesh)
colors = ["0.1", "0.3", "0.5", "0.7"]
levels = [1, 2, 3, 4, 5]
plt.contourf(x, y, z, colors=colors, levels=levels)
pl... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from nrf24 import NRF24
import time
from time import gmtime, strftime
import MySQLdb
import xml.dom.minidom
import sys
verbose = 0
if len(sys.argv) > 1:
if sys.argv[1] == "-v":
verbose = 1
else:
print "Argument non reconnu ! -v pour verbose"
... |
import numpy as np
import glob
def getAllInDir(dir_filename):
if not dir_filename[-1] =="/":
dir_filename+="/"
all_files = glob.glob("{}*".format(dir_filename))
return all_files
def safe_crop_ltbr(image, x1, y1, x2, y2):
"""
Returns a crop of an image based on the image and an [left, top, ... |
# SCREEN SETTINGS
WIDTH = 720
HEIGHT = 500
BACKGROUND = (76, 175, 80)
PADDLE_COLOR = (255, 255, 255)
# GAME SETTINGS
FPS = 60
#PADDLE1
PADDLE_WIDTH = 25
PADDLE_HEIGHT = 80
PADDLE_SPEED = 10
#BALL1
BALL_WIDTH = 20
BALL_HEIGHT = 20
BALL_COLOR = (255, 255, 255)
|
$ chomod +x test1.py
$ ./test1.py |
def factorialfun(number):
factorial = 1
while number > 0:
factorial = factorial * number
number = number - 1
return factorial
|
#!/usr/bin/python3
import validate
import wave_generator
years = [2018,2019,2020,2021,2022,2023,2024,2025]
marks = []
ymap = []
for y in years:
temp = wave_generator.generate_markers(y)
marks.extend(temp)
for i in range(len(temp)):
ymap.append(y)
print(len(marks))
vald = validate.val(marks)... |
# from . import kitti_dataset
# from . import nuscenes_dataset
from .import lyft_dataset
|
# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import os.path
from dataclasses import dataclass
from typing import Iterable
from pants.backend.javascript import nodejs_project_environment
from pants.... |
def decodeMorse(morse_code):
output = []
for x in morse_code.split(" "):
output.append(" ")
for i in x.split(" "):
if len(i)>0: output.append(MORSE_CODE[i])
return "".join(output).lstrip()
'''
In this kata you have to write a simple Morse code decoder. While the Morse code
i... |
import pickletools
def protocol_version(file_object):
maxproto = -1
for opcode, arg, pos in pickletools.genops(file_object):
maxproto = max(maxproto, opcode.proto)
return maxproto
|
from django.contrib import admin
from models import Item, Label, Category, Subcategory, BagCount, Setting
class ItemAdmin(admin.ModelAdmin):
pass
admin.site.register(Item, ItemAdmin)
class LabelAdmin(admin.ModelAdmin):
pass
admin.site.register(Label, LabelAdmin)
class CategoryAdmin(admin.ModelAdmin):
pas... |
import os
import json
from functools import lru_cache
SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
CONF_FILE_PATH = os.path.normpath(os.path.join(SCRIPT_DIR, "config.json"))
@lru_cache(maxsize=None)
def get_config():
with open(CONF_FILE_PATH, "r") as fp:
... |
from datetime import datetime
from dateutil.relativedelta import relativedelta
from time import mktime
import time
import requests
import pandas as pd
import config
import os
try:
previous_data = pd.read_csv(os.path.join(config.DATADIR, "last_month_tracks.csv"))
except FileNotFoundError:
# 1 month ago
las... |
# Generated by Django 2.2.11 on 2021-08-24 11:42
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('users', '0043_auto_20210824_1534'),
('facility', '0271_auto_20210815_1617'),
]
operations = [
migr... |
#encoding: utf-8
import random
import sys
if len(sys.argv) != 2 :
print 'Args: número'
sys.exit(1)
veces = int(float(sys.argv[1]))
media = 100
sigma = 20
indice0 = media - 3*sigma
indice1 = media + 3*sigma
print "# ", indice0, indice1
amplitud = indice1-indice0 + 1
varreglo = [0]*amplitud
i=0
while i < veces:
... |
#!/usr/bin/env python3
from certCheck import CertCheck
from loadEnv import load as loadEnvVariables
from printSubprocessStdout import printSubprocessStdout
from subprocess import check_output
def relative(subpath='', useCwd=False):
import os
basePath = os.getcwd() if useCwd else os.path.dirname(os.path.abspath(__fil... |
from django.http import HttpResponse,JsonResponse
from django.shortcuts import render,redirect
from datetime import datetime
from django.views.generic import View
from django.contrib.auth.models import User, Group, auth
from django.contrib import messages
from rest_framework import viewsets
from rest_framework import p... |
from entity.response_wrapper import Response
|
from resourse import db
class Teacher(db.Model):
__tablename__ = 'teacher'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(255), nullable=True)
password = db.Column(db.String(255), nullable=True)
e_mail = db.Column(db.String(255))
create_time = db.Column(db.DateTime)
... |
def letter_count(s):
outut ={}
for i in s:
outut[i] = s.count(i)
return outut
|
import unittest
from Pyskell.Language.TypeClasses import *
from Pyskell.Language.EnumList import L
class ShowTest(unittest.TestCase):
def setUp(self):
self.int_test = 1
self.float_test = 1.1
self.string_test = "some string"
self.list_test = [1, 2, 3]
self.set_test = {1, 1, ... |
import unittest
from katas.beta.vowel_shifting import vowel_shift
class VowelShiftTestCase(unittest.TestCase):
def test_is_none_1(self):
self.assertIsNone(vowel_shift(None, 0))
def test_equal_1(self):
self.assertEqual(vowel_shift('', 0), '')
def test_equal_2(self):
self.assertEq... |
import sys
import numpy as np
from dateutil import parser
import json
from prime_mcmc import ammcmc
from prime_posterior import logpost, logpost_negb, logpost_poisson
from prime_utils import runningAvg, compute_error_weight
def main(setupfile):
r"""
Driver script to run MCMC for parameter infer... |
import argparse
def _add_common_args(arg_parser):
arg_parser.add_argument('--config', type=str)
# Input
arg_parser.add_argument('--types_path', type=str, help="Path to type specifications")
# Preprocessing
arg_parser.add_argument('--tokenizer_path', type=str, help="Path to tokenizer")
arg_pa... |
import turtle
import math
bob = turtle.Turtle()
bob.speed(10)
#making the fibonaccis sequence
def fib(n):
if n == 0: return 1
if n == 1: return 1
else: return fib(n-1) + fib(n-2)
#making fibonacci squares
def make_square(n):
for i in range(6):
bob.forward(n)
bob.left(90)
bob.ri... |
from django.http import HttpResponse
from django.core import serializers
import tushare as ts
import json
from pandas import DataFrame
def get_price_data(request):
stockCode = getRequestParameter(request, 'stockcode')
beginDate = getRequestParameter(request, 'begindate')
endDate = getRequestPar... |
import utils
import os
import time
import torch
import torch.utils.data
import torchvision.transforms as transforms
import skimage.color as skcolor
import skimage.io as skio
import skimage.filters as skfilters
import skimage.feature as skfeature
import numpy as np
from tqdm import tqdm
from utils import normalize, ... |
#!/usr/bin/env python
'''
Custom operations to check annotations
'''
#####################
# IMPORT OPERATIONS #
#####################
import GenerationOps as GnOps
import GlobalVariables as GlobVars
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore")
from Bio.Seq import Seq
f... |
# Generated by Django 2.1.7 on 2019-04-16 06:12
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0025_share_date_posted'),
]
operations = [
migrations.AlterModelOptions(
name='post',
options={'verbose_name': 'Post... |
from snake import Snake
from food import Food
from scoreboard import Scoreboard
from turtle import Turtle
import time
snake = Snake()
food = Food()
score = Scoreboard()
flag = 1
snake.screen.listen()
snake.screen.onkey(fun=snake.up,key="Up")
snake.screen.onkey(fun=snake.down,key="Down")
snake.screen.onkey(fun=snake... |
from battle.battlemenu.BattleOption import BattleOptions
from battle.round.RoundAction import RoundAction
from battle.battleeffect.RegularAttack import RegularAttack
# Represents just a regular attack:
class AttackOption(BattleOptions):
def __init__(self, fighter, targets):
super().__init__("Attack", fi... |
import pickle
import numpy as np
from data import TextData
from train import TextTrain
with open('../data/mailContent_list_1000.pickle', 'rb') as file:
content_list = pickle.load(file)
# random.seed(1234)
# pickle.dump(random.sample(content_list,1000), open('mailContent_list_1000.pickle', 'wb'))
with open(... |
import random
from scipy.stats.distributions import norm, triang
import pyDOE
class Lhs(object):
"""
Generate a latin-hypercube design
Parameters
----------
sampling_dist: string
Models of distributions: uniform, normal, triang
Example
-------
A 1-factor design with uniform di... |
import numpy as np
import control
from rrt_star import RRT_star
# see spec for RRT_star
# A_fn and B_fn take state, control and return matrix
# Q and R are matrices
# update_fn takes state, control and returns a new state
class LQR_RRT_star(RRT_star):
def __init__(self, s_init, s_goal, bounds, obstacles, A_fn, B_f... |
from matplotlib import pyplot as plt
import datetime
def plot_errors(generator, disriminator, display):
file_name = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")+'.png'
# plt.title("Final Model Training Losses vs Epochs")
plt.xlabel("Epoch")
plt.ylabel("Error")
plt.plot(generator,'b',label='... |
"""Yaml CLI formatter."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from treadmill import yamlwrapper as yaml
def format(obj): # pylint: disable=W0622
"""Returns yaml representation of the object."""
... |
from django.conf.urls import url
from DPMAPI import views
urlpatterns = [
url('', views.weibullAnalysis),
url('WeibullAnalysis/', views.weibullAnalysis)
]
|
from kmeans import K_Means
from knn import KNN_test
from trees import DT_train_binary, DT_test_binary, DT_train_binary_best
import numpy as np
import random
import math
def main():
#K-NN Data
X_train = np.array([[1,5],[2,6],[2,7],[3,7],[3,8],[4,8],[5,1],[5,9],[6,2],[7,2],[7,3],[8,3],[8,4],[9,5]])
Y_train = np.arr... |
peso = float (input ("Digite o seu peso: "))
print("Seu peso é: ", peso)
altura = float (input ("Digite sua altura: "))
print("Sua altura é: ", altura)
imc = peso/(altura*altura)
print("Seu IMC é: ",imc)
|
from datetime import datetime
from django.shortcuts import render
def now(request):
now = datetime.now()
h = str(now.hour)
if len(h) == 1:
h = "0" + h
m = str(now.minute)
if len(m) == 1:
m = "0" + m
s = str(now.second)
if len(s) == 1:
s = "0" + s
now_str = h + ":" + m + ":" + s
return r... |
import airsim
import os
from shutil import copy2
airsim_dir = os.path.dirname(airsim.__file__)
file_path = os.path.realpath(__file__)
dir_path = os.path.dirname(file_path)
print(airsim_dir)
copy2(os.path.join(dir_path, "client.py"), airsim_dir)
copy2(os.path.join(dir_path, "types.py"), airsim_dir)
|
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import dataclasses
import itertools
import logging
import re
from dataclasses import dataclass
from pathlib import Path, PurePath
from textwrap import d... |
#!/usr/bin/env python
"""
v0.1 This retrieves TCP related data files, weka .models, etc... which
are required to run as a TCP task client / ipengine client.
"""
import os, sys
import ingest_tools
ingest_tools_pars = ingest_tools.pars
if __name__ == '__main__':
local_scratch_dirpath = os.path.expand... |
from django.conf.urls import url
from book import views
urlpatterns = [
url(r'^$',views.showbook_view),
url(r'^showbook/(\d+)',views.showbook_view),
url(r'^booktype/',views.booktype_view),
url(r'^addbooktype',views.addbooktype_view),
url(r'^changebooktype/(\d+)',views.changebooktype_view),
url(... |
if __name__ == '__main__':
file = open("day12.txt", "r")
moves = []
ship_x_coord = 0
ship_y_coord = 0
waypoint_x_coord = 10
waypoint_y_coord = 1
facing = 90
for line in file:
moves.append(line.strip("\n"))
for individual_move in moves:
action = individual_move[:1]
... |
from security import export_key, generate_keys
# Check if we have locally stored keys or generate new ones
def check_key(keyfile):
try:
key = open(keyfile, 'r')
except Exception:
return None
else:
return key
def main():
if check_key('private_key.pem') is None or \
... |
#input exercise
print("adinizi giriniz:")
x=input()
|
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import itertools
import logging
from pants.backend.java.target_types import JavaFieldSet, JavaGeneratorFieldSet
from pants.backend.kotlin.compile.kotlin... |
from mrsimulator import MRSimulator, SameKeyGroup, PairMultiset
def map(key, value):
return key, value
def reduce(key, group: SameKeyGroup):
sum = 0
for k,v in group:
sum += v
return 1, sum
if __name__ == '__main__':
raw_data = range(0,1000)
pairs = PairMultiset([(1,v) for v in raw_d... |
player1_run = int(input("enter the run scored by player 1 in 60 balls: "))
player2_run = int(input("enter the run scored by player 2 in 60 balls: "))
player3_run = int(input("enter the run scored by player 3 in 60 balls: "))
strikerate1 = player1_run * 100 / 60
strikerate2 = player2_run * 100 / 60
strikerate3 = player3... |
# -*- coding: utf-8; -*-
from collections import namedtuple
from pubsub import pub
import ConfigParser
import logging
import os.path
import sys
logger = logging.getLogger("platakart.core")
from pygame.time import Clock
import pygame
import pygame.event
import pygame.font
import pygame.joystick
from pytmx.util_pygame... |
from studentdata.student import Student
from studentdata.club import Club
from studentdata.supervisor import Supervisor
from studentdata.city import City
name = "name1 name2"
status = "status"
city = City(name="city")
supervisor = Supervisor(name="super")
clubs = [Club("Chess"), Club("Fencing")]
def test_cityPop():
... |
#! /usr/bin/env python
import sys
import copy
import rospy
import moveit_commander
import moveit_msgs.msg
import geometry_msgs.msg
import rospy
from std_msgs.msg import Int16
moveit_commander.roscpp_initialize(sys.argv)
rospy.init_node('move_group_python_interface_tutorial', anonymous=True)
pub = rospy.Publisher('grip... |
# noinspection PyUnusedLocal
# skus = unicode string
def calculate_offers(bill, item, quantity, offers):
bill = bill.copy()
for offer, price in offers:
bill[item]['offers'].append(
{'items': quantity / offer, 'price': price}
)
quantity = quantity % offer
return bill, ... |
print([i for i in range (50)]) |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
# Poskrapeovat iba jazyk - slovensky
class BookItem(scrapy.Item):
# define the fields for your item here like:
id = scrapy.Field()
title = s... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from poseidon.providers.interface import ProviderInterface
from poseidon.acl.interface import ACLInterface
from poseidon.watchdog.networkbench import NetworkBench
from ..base.handlers import BaseHandler
from ..privilege import req... |
# -*- coding:utf-8 -*-
import json
import os
import re
import urllib.request
from PIL import Image
import colorsys
import math
import time
from functools import cmp_to_key
from sklearn.cluster import KMeans
from collections import Counter
import cv2 # for resizing image
from colorthief import ColorThief
from colormat... |
from django.db import models
from django.db.models.query import QuerySet
from django.utils.translation import ugettext_lazy as _
from django.core.validators import MinValueValidator
from teams.models import Team
class PlayerMixin(object):
pass
class PlayerQuerySet(QuerySet, PlayerMixin):
pass
class Playe... |
a,b,c,x,y = map(int,input().split())
p = [
2 * c * x + b * max(y-x, 0),
2 * c * y + a * max(x-y, 0),
a * x + b * y
]
print(min(p)) |
import os
import pandas as pd
from PIL import Image, ImageDraw
import numpy as np
"""LABEL GENERATION"""
labels = pd.read_csv("WashingtonOBRace/corners.csv", delimiter = ',', names=['image_name', 'x_top_left', 'y_top_left',
'x_top_right', ... |
import numpy as np
import lasagne
from numpy.random import RandomState
import theano
import theano.tensor as T
from braindecode.veganlasagne.layers import get_input_shape
def create_descent_function(layer, wanted_activation, learning_rate=0.1,
input_cost=None, n_trials=1, seed=983748374,
... |
# import sbol3
# import labop
# import labop.type_inference
#
#
# # Pre-declare the ProtocolTyping class to avoid circularity with labop.type_inference
# class ProtocolTyping:
# pass
#
# primitive_type_inference_functions = {} # dictionary of identity : function for typing primitives
#
#
# # When there is no outpu... |
# 多重继承
# 搜索方式:从左到右,广度优先
class P1:
def foo(self):
print("P1中的foo")
def bar(self):
print("P1中的bar")
class P2:
def foo(self):
print("P2中的foo")
def bar(self):
print("P2中的bar")
class C1(P1):
def foo(self):
print("C1中的foo")
class C2(P2):
def bar(self):
... |
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict.values():
print(x)
*
**
***
****
***
**
*
n=6
6/2 = 3
n*n/2
for i=0 to 6
if(i<=3){
for (j=0;j<i+1;);
print()
j++
}else{
}
|
# The "if...elif...else"-statement
# If the numer is positive, we print an appropriate message
num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
num = -1
if num > 0:
print(num, "is a positive number.")
print("This also is always printed.")
# If else
num = ... |
"""
This module implements :class:`ImageSequence`, a 3D array.
:class:`ImageSequence` inherits from :class:`basesignal.BaseSignal` which
derives from :class:`BaseNeo`, and from :class:`quantites.Quantity`which
in turn inherits from :class:`numpy.array`.
Inheritance from :class:`numpy.array` is explained here:
http://... |
"""
default rig setup
main module
"""
import maya.cmds as mc
from rigLib.base import control
from rigLib.base import module
from rigLib.rig import spine
from rigLib.rig import neck
from rigLib.rig import ikChain
from rigLib.rig import leg
from rigLib.utils import joint
from . import defaultDeform
from . import project... |
#!/usr/bin/env python
import time, unittest, os, sys
from selenium import webdriver
from main.page.desktop_v3.login.pe_login import *
from main.page.desktop_v3.login.pe_logout import *
from main.page.desktop_v3.shop.pe_shop import *
from main.page.desktop_v3.product.pe_product import *
from main.page.desktop_v3.tx.pe_... |
from collections import Counter
import pandas as pd
import numpy as np
import math
import sys
import os
# THIS FUNCTION PROVIDES AN ALTERNATE DISTANCE METRIC TO SILHOUETTE
# SCORE.
#=========1=========2=========3=========4=========5=========6=========7=
#=========1=========2=========3=========4=========5=========6... |
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import os
import copy
import io
import operator
import prettyplotlib as ppl
import random
import cPickle as pickle
import pdb
import matplotlib
matplotlib.use('Agg')
matplotlib.rc('pdf', fonttype=42)
import matplotlib.pyplot as plt
try:
impo... |
__author__ = 'korhammer'
import pandas as pd
import h5py
import numpy as np
from os import listdir
from os.path import join, isfile, isdir
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import misc
class Evaluation:
def __init__(self, allocate=50000):
self.results = pd.DataFr... |
#!/usr/bin/python
# Libraries
from PIL import Image, ImageTk
from math import sqrt, floor, ceil, sin, cos, tan, atan2, radians, degrees
from random import random, randint
import numpy
from time import time
from sys import maxint
# ======= solid colors =======
WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)
GRE... |
import random, string, os
import host
from Time import Time
class Power:
# ----------------------------------------------------------------------
def __init__(self, game, name, type = None):
vars(self).update(locals())
self.reinit()
# ----------------------------------------------------------------------
def... |
data = 'From stephen.marquard@uct.ac.za Sat jan 5'
atposition = data.find('@')
print(atposition)
spaceposition = data.find(' ', atposition)
print(spaceposition)
host = data[atposition+1:spaceposition]
print(host)
|
# from tables.proxies import proxies
import json
_DEFAULT_DICT = {'http': 'http://103.207.4.170:60570', 'https': 'https://103.207.4.170:60570',
'ftp_proxy': 'ftp://103.207.4.170:60570'}
_proxies = []
ips = open('tables/proxies.txt', 'r').readlines()
ports = open('tables/ports.txt', 'r').readlines()
ip... |
"""Create a brute-force winner determination mechanism for XOR-bids based combinatorial
auctions. As input, your mechanism should take XOR-bids from a set of agents, and should
then output an allocation as well as the social welfare obtained.
Example:
3 agents with bids:
- a: 3 xor a, b: 100 xor c: 4
- a, b: 2 xor d: ... |
# Generated by Django 3.0.4 on 2020-04-22 05:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('apps', '0009_auto_20200419_1505'),
]
operations = [
migrations.AddField(
model_name='section',
name='sequence',
... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from utils import init
import numpy as np
import math
import sys
import datetime
def print_now(cmd):
time_now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print('%s %s' % (time_now, cmd))
sys.stdout.flush()
class NoisyLinear(nn... |
import math
from typing import Any, List
import torch
from torch import nn
from torch.nn.functional import pad
def init_weights_xavier_(network, activation="tanh"):
"""
Initializes the layers of a given network with random values.
Bias layers will be filled with zeros.
Parameters
----------
... |
import pygame,enteties
class Projectil(enteties.Entetie):
frames={}
def __init__(self, position, side_left,tipo,movment,time=100):
super(Projectil, self).__init__(None, position)
self.movement = movment
self.frame_index = 0
self.frame_on = "ball"
self.rect=Projectil.... |
#! encoding=utf-8
# Creation Date: 2018-03-27 21:19:29
# Created By: Heyi Tang
import json
import os
def json2f(data, f):
if isinstance(data, set):
data = list(data)
with open(f, "w") as fout:
json.dump(data, fout, indent = 2)
def f2json(f):
with open(f) as fin:
data = json.load(... |
# 作业:用代码模拟博客园系统
# 项目分析
## 一. 首先程序启动,页面显示下面内容供用户选择
'''
1. 请登录
2. 请注册
3. 进入文章页面
4. 进入评论页面
5. 进入日记页面
6. 进入收藏页面
7. 注销账号
8. 退出整个程序
'''
## 二.必须实现的功能
'''
1.注册功能要求
a.用户名、密码要记录在文件中
b.用户名要求:只能含有字母或者数字,不能含有特殊字符并且确保用户明唯一
c.密码要求:长度要在 6~14 个字符之间
d.超过三册登陆还未成功则退出整个程序
2.登陆功能要求
a.用户输入用户名、密码进行登陆验证
b.登录成功后,才可以访问 3... |
import cmath
from cmath import exp, pi, sin, cos
import numpy as np
import matplotlib.pyplot as plt
def FFT(A):
N = len(A)
if N == 1:
return A
else:
Wn = exp(2*pi*1j/N)
W = 1
A_even = []
A_odd = []
for i in range(0, N):
if i%2 == 0:
A_even.append(A[i]... |
import unittest
from katas.kyu_7.triangular_treasure import triangular
class TriangularTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(triangular(0), 0)
def test_equals_2(self):
self.assertEqual(triangular(2), 3)
def test_equals_3(self):
self.assertEqual(tri... |
from Bio.PDB import * |
from flask import Flask
from flask import jsonify
import mysql.connector
from util import db_util
from util import youtube_util
from util import ssl_util
app = Flask(__name__)
@app.route("/")
def hello_world():
return "Hello, World!"
@app.route("/api/get/<key>", methods=["GET"])
def api_get(key):
return key... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.