text stringlengths 8 6.05M |
|---|
Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> import turtle
>>> t=turtle.Turtle()
>>> t.pensize(5)
>>> t.shape("fish")
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module... |
import os
def helpPath():
'''
Returns the directory of the help files
'''
instDir = os.path.abspath(__file__) # path to this file
instDir = os.path.dirname(instDir) # take off file name (path to help)
return(instDir)
|
'''
The following JSON template shows what is sent as the payload:
{
"serialNumber": "GXXXXXXXXXXXXXXXXX",
"batteryVoltage": "xxmV",
"clickType": "SINGLE" | "DOUBLE" | "LONG"
}
A "LONG" clickType is sent if the first press lasts longer than 1.5 seconds.
"SINGLE" and "DOUBLE" clickType payloads are sent fo... |
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 19 00:34:09 2020
@author: anwar
"""
def get_stats(class_list):
new_stats = []
for elt in class_list:
new_stats.append([elt[0], elt[1], avg(elf[1])])
return new_stats
def avg(grades):
return sum(grades)/len(grades) |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import urllib2
from bs4 import BeautifulSoup
import re
f = open("/Users/zhoufengting/Desktop/possession1.txt","r")
lines = f.readlines()
for line in lines:
url = line
request = urllib2.urlopen(url)
response = request.read()
soup = BeautifulSoup(response,"html.parser")
... |
"""
MFreq w/ Atom Counter & f(Col_)
"""
import numpy as np
import scipy.stats as sts
import matplotlib.pyplot as plt
import scipy.constants as sc
import scipy.special as scp
import timeit
start = timeit.default_timer()
ymot = 0.004 # Radius of Col Atoms
G = 38.11e6 # See ln 96
Xi... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from textwrap import dedent
import pytest
from pants.backend.helm.resolve import fetch
from pants.backend.helm.resolve.artifacts import HelmArtifact, ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
from PyQt4 import QtGui, QtCore
from django_packer import *
from django_frame_main import *
class FormWidget(QtGui.QWidget):
def __init__(self, parent):
super(FormWidget, self).__init__(parent)
self.django_simulator = ''
... |
from django.shortcuts import render
from django.views.generic import View
import fredboardChords as gs
import random
class ChordsPage(View):
def get(self, request, *args, **kwargs):
add = gs.create_svg('CM7', 'drop2_inv1_strS1', 1)
add = add.create()
svg1 = ''.join(add)
title = 'C ... |
from django.conf import settings
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from tos.models import TermsOfService, UserAgreement, has_user_agreed_latest_tos
class TestViews(TestCase):
def setUp(self):
# User that has agreed to TOS
... |
"""
Examen Parcial 4
Carrillo Medina Alexis Adrian (CMAA)
Nombre del programa: Parcial4.py
"""
#----- Seccion de bibliotecas
import numpy as np
import matplotlib.pyplot as plt
# scipy es utilizado unicamente para la comprobacion
import scipy.integrate as integrate
#----- Codigo
# La validacion se encuentra en el... |
# Generated by Django 3.1.1 on 2020-10-10 11:35
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Permission',
fields=[
('id', models.AutoFie... |
"""
剑指 Offer 10-2. 青蛙跳台阶问题
一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶。求该青蛙跳上一个 n 级的台阶总共有多少种跳法。
"""
from functools import lru_cache
# 显然也是个递归,这个可以反着想,比方说上第n级台阶,其实就是上第n-1个台阶的方法种类再迈一步,其实就是n-1个台阶那么多种,或者n-2个台阶那么多种类再上一步。
# 递归的东西应该仔细思考一下,再简单也要思考一下,细思极恐。
@lru_cache()
def numWays(n):
if n == 0:
return 1
elif n == 1:
return 1
elif... |
#!/usr/bin/env python
# detections_refinement.py: Node for online refinement of detections (BirdNet 1 only)
import sys
import rospy
import datetime
import math
import numpy as np
from numpy.linalg import inv
import cv2
import tf
import message_filters
from sensor_msgs.msg import Image, CameraInfo, PointCloud2
from pe... |
import math
def perfect_num(start, end):
perfectNums = []
s, e = int(math.sqrt(start)), int(math.sqrt(end))+1
for i in range(s, e):
if i*i >= start and i*i <= end:
perfectNums.append(i*i)
if len(perfectNums) == 0:
print(-1)
return
print(sum(perfectNums))
... |
#display the output
print("New Python File")
print("edit")
|
# individual network settings for each actor + critic pair
# see networkforall for details
from networkforall import Actor, Critic
from utilities import hard_update, gumbel_softmax, onehot_from_logits
from torch.optim import Adam
import torch
import numpy as np
# add OU noise for exploration
from OUNoise import OUNoi... |
#!/usr/bin/env python
# coding: utf-8
# <b> Create and print a numpy 1-d array containing 21 decimal numbers that starts at 5 and end at 10. Calculate and print the min, max and avarage value of this 1-d array. <b>
# In[1]:
import numpy as np
# In[2]:
my_array = np.linspace(5,10,21)
print(my_array)
# In[6]:
... |
import kvt
import torch
import torch.nn as nn
import torch.nn.functional as F
def dice_loss(input, target):
smooth = 1.0
input = torch.sigmoid(input)
if input.dim() == 4:
B, C, H, W = input.size()
iflat = input.view(B * C, -1)
tflat = target.view(B * C, -1)
else:
asser... |
import os, shutil, glob
def recursive_copy_files(source_path, destination_path, override=False):
"""
Recursive copies files from source to destination directory.
:param source_path: source directory
:param destination_path: destination directory
:param override if True all files will be overridden otherwise sk... |
import camera
if __name__ == "__main__":
camera.capture_single_image()
|
from base.DeepRecommender import DeepRecommender
import tensorflow as tf
from math import sqrt
from tensorflow import set_random_seed
from collections import defaultdict
import random
set_random_seed(2)
class LightGCN(DeepRecommender):
def __init__(self,conf,trainingSet=None,testSet=None,fold='[1]'):
sup... |
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QSlider, QPushButton, QLabel
from PyQt5.QtWidgets import QFileDialog
from PyQt5.QtGui import QPixmap, QColor, QPainter
from PIL import Image
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(s... |
# This is on the handle_file branch.
import sys
# Must have at least one value.
if len(sys.argv) == 1:
print 'Error: No arguments given.'
exit()
# Calculate sum of command-line arguments.
n = 0
sum = 0
for num in open(sys.argv[1]):
sum += float(num)
n += 1
print sum / n
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-10-11 07:37
from __future__ import unicode_literals
from django.db import migrations
from elections.constants import ELECTION_TYPES
def add_initial_election_types(apps, schema_editor):
ElectionType = apps.get_model("elections", "ElectionType")
Elec... |
def oddTuples(aTup):
'''
:param aTup:a tuple
:return:tuple,every other element of aTup
'''
b = ()
length = len(aTup)
return aTup[0:length:2]
Tup = ('I', 'am', 'a', 'test', 'tuple')
print oddTuples(Tup)
|
# 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 law or agreed to in writin... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the countApplesAndOranges function below.
def countApplesAndOranges(s, t, a, b, apples, oranges):
myApple = calculateTheArr(apples,a)
myOranges = calculateTheArr(oranges, b)
m1 = detectionAppleOrOrangeByLimit(myApple,s,t)
... |
import time
list_1=[1, 5, 8, 3]
x=int(input("Please enter the number you want to check in the list :"))
time.sleep(1)
print("Checking ... ")
time.sleep(1)
if (x in list_1):
print(x,"is there in the list")
else:
print(x,"is not there in the list")
|
#!/usr/bin/env python
import os
top = '.'
out = 'build'
def options(opt):
opt.add_option('--double', action='store_true', default=False, help='Double precision instead of float')
if os.name != 'nt':
opt.load('compiler_c')
else:
opt.load('msvc')
def configure(conf):
conf.env.DOUBLE = c... |
from django.apps import AppConfig
class AndelaSocialsConfig(AppConfig):
name = 'andela_socials'
|
"""Kerberos related CLI tools.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import click
from treadmill import cli
def init():
"""Return top level command handler."""
@click.group(cls=cli.make_comma... |
import numpy as np
import pandas as pd
from modules import metrics
# a. Regressão Linear Univariada - Método Analítico
class LRAnalyticalMethod():
def __init__(self):
pass
def fit(self, X, y):
# Número de observações
n = len(X)
# Média do X e do y
mean_x, mean_y = n... |
# exceptions.py
class DataFormatError(Exception):
'''Exception that is raised when provided time series data file or header file does not conform to required formatting.
'''
def __init__(self,value):
self.value = value
def __str__(self):
return str(self.value)
class TimeSeriesFileNameError(Exception):
'... |
from django.apps import AppConfig
class BooksliceConfig(AppConfig):
name = 'bookSlice'
|
'''
About: -Recieve family data in CSV format, save data about each family member and output a print version of the family tree
-Names can be added individually as well
Family Tree Print Output:
Parent
Child (Parent to Sub-Child)
Sub-Child
Child
Note: doesn't handle duplicate names, could gen... |
import datetime
from functools import reduce
from django.contrib.auth.views import login as contrib_login
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.db.models import Sum, Case, When, F, Q, In... |
import re
A = input()
A = A.replace('6', '9')
N = []
for i in range(ord('0'), ord('9')):
N.append(len(re.findall(chr(i), A)))
N.append(len(re.findall('9', A)) / 2)
N.sort(reverse=True)
if N[0] % 1 == 0:
print(int(N[0]))
else:
print(int(N[0]+1))
# Done
|
""" importing modules and functions from flask
"""
from flask import Flask, render_template, request, session, make_response, redirect
import os #for cryptographic functions
from models.bucketlist import Bucketlist
from models.user import User
import uuid
app = Flask(__name__)
Users = {}
app.secret_key = os.urandom(... |
#!/usr/bin/env python
"""
Check that alls functions are documented.
"""
import os
import sys
ERROR = False
ROOT = os.path.dirname(os.path.dirname(os.path.abspath((__file__))))
def error(message):
print(message)
global ERROR
ERROR = True
def all_functions():
functions = []
for (root, _, pathes) ... |
"scope.py"
a = 1
n = 1
def f(n):
print 'In f, a =', a, 'and n =', n, vars()
f(10)
print vars()
|
class SystemItem:
def __init__(self, name, parent):
self.name = name
self.parent = parent
class Directory(SystemItem):
def __init__(self, name, parent):
super().__init__(name, parent)
self.children = []
def mkdir(self, name):
self.children.append(name)
retur... |
# YOu cannot alert the data in a tuple
daysOfTheWeek=("Monday","Tuesday","Wednesday","Thursday","Fri","Sat","Sun")
print(type(daysOfTheWeek))
print(len(daysOfTheWeek))
print(daysOfTheWeek[4])
print(daysOfTheWeek.count('y'))
print(daysOfTheWeek[-6])
man= " Daset",67
print(type(man))
|
#!/usr/bin/env python
# encoding: utf-8
"""
app.py
Created by yang.zhou on 2012-08-28.
Copyright (c) 2012 zhouyang.me. All rights reserved.
"""
import logging
import os.path
import json
import tornado
import pylibmc
#import motor
import tornado.options
from tornado import httpserver
from tornado import ioloop
from to... |
# Generated by Django 2.2.1 on 2019-06-16 22:58
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('questi', '0004_auto_20190617_0054'),
]
operations = [
migrations.AddField(
model_name='prof',
... |
import wx
import cv2
import pymysql
from model.dbconnect import *
from props.InputProp import *
from form.MainList import *
from form.ConnectDialog import *
from form.FlexList import *
from form.EditForm import *
from MenuForm import * |
mark = int(input("Enter your mark: "))
print(mark % 2)
if mark % 2 == 0:
print("Even!")
else:
print("Odd!") |
"""
Copyright 1999 Illinois Institute of Technology
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, modify, merge, publis... |
import networkx as nx
import csv
import random
class node_preprocess:
def __init__(self, fp, G):
self.fp = fp
self.G = G
def getGraph(self):
fp = self.fp
G = self.G
with open(fp) as file:
csv_file = csv.reader(file, delimiter=',')
for row in csv_... |
from .sbvat import SBVAT
from .obvat import OBVAT |
'''
Created on Oct 9, 2012
@author: christian
'''
import os
import re
import tempfile
import numpy as np
__all__ = ['MarkerFile']
def fix_ptb_eeg_events(raw):
"""Fix events from a vmrk file recorded with psychtoolbox/stim tracker
Parameters
----------
raw : RawBrainVision
MNE-Python objec... |
operation = raw_input("Would you like to add, subtract, mutiply, or divide?")
number1 = int(raw_input("Enter the first number"))
number2 = int(raw_input("Enter the second number"))
if operation == "add":
answer = number1 + number2
elif operation == "subtract":
answer = number1 - number2
elif operation == "multi... |
#!/usr/bin/python3
from flask import Flask, request, jsonify
from flask_restful import Resource, Api, reqparse
from dbconnection import connect
from Queries import ALL_BOOKS, SPECIFIC_BOOK, INSERT_BOOK, UPDATE_BOOK
from Queries import DELETE_BOOK, ALL_AUTHORS, SPECIFIC_AUTHOR
book_post = reqparse.RequestParser()
book_... |
import json
import boto3
import datetime
dynamodb = boto3.resource('dynamodb')
some_table = dynamodb.Table('audio-details')
def lambda_handler(event, context):
time_stamp = str(datetime.datetime.now().year)+str(datetime.datetime.now().month)+str(datetime.datetime.now().day) + \
str(datetime.datetime.now(... |
import pyglet
window = pyglet.window.Window()
label = pyglet.text.Label("hello")
@window.event
def on_draw():
window.clear()
label.draw()
pyglet.app.run()
|
import pickle
import bson
ARMORS_PATH = '../WebScrapper/obj/armors/'
WEAPONS_PATH = '../WebScrapper/obj/weapons/'
MONSTERS_PATH = '../WebScrapper/obj/monsters/'
DECORATIONS_PATH = '../WebScrapper/obj/decorations/'
SKILLS_PATH = '../WebScrapper/obj/skills/'
ITEMS_PATH = '../WebScrapper/obj/items/'
def read_armor_file... |
class SelectionSort(object):
def sort(self, data):
if data is None:
raise TypeError('Dados não podem ser None')
if len(data) < 2:
return data
if data == []:
return False
self.max_num(data)
return data
def max_num(self,... |
import numpy as np
dt = 1.
sigma = 0.05
# goal = np.array([0.,5.])
# obstacle = np.array([2.5,2.5])
# obstacle_r = 0.5
num_steps = 5
R = 1. #0.25
def dynamics(state,action,rng):
# act = np.clip(action,-1.,1.) ## Saturate
nxt_state = state + action*R
nxt_state += np.random.randn()*0.01
# nxt_state += rng.multivari... |
# -*- coding: utf-8 -*-
from .database import Database as db
from .command import Command, CommandError, authorise
from .context import Context
from .client import bot, ratelimit
from . import language
from .utils import get_next_arg
from . import converters
from .interaction import (ButtonController, BasePager, NamedP... |
from django.db import models
# Create your models here.
class Ingredient(models.Model):
title = models.CharField(max_length=256)
def __str__(self):
return self.title
def __unicode__(self):
return self.title
pass
class Measure(models.Model):
title = models.CharField(max_length... |
# Generated by Django 2.2.10 on 2020-02-15 01:45
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('confession', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='confession',
old_name='hunter',
... |
"""Helper functions for Jinja2 templates.
This file is loaded by jingo and must be named helpers.py
"""
from django.conf import settings
from django.utils.six.moves.urllib_parse import urlencode
from django_jinja import library
from jinja2 import contextfunction, Markup
from ..views import can_create, can_refresh
@... |
from django.contrib.auth import get_user_model
from rest_framework import authentication
User = get_user_model()
class DevAuthentication(authentication.BasicAuthentication):
def authenticate(self, request):
qs = User.objects.all()
if qs:
user = qs.order_by('?').first()
ret... |
import datetime
from datetime import datetime
class longFrame(object):
def __init__(self):
self._start = 0x68
self._stop = 0x16
self._L = 0x00
self._C = 0x00
self._A = 0x00
self._CI = 0x00
def setField(self,L,C,A,CI):
self._L = L
self._C = C
... |
#!/usr/bin/env python
from beta import beta_reduce
# 1.11 Chapter Exercises
# Normal Form or diverge?
exercises_b = r"""
(\x.xxx)
(\z.zz)(\y.yy)
(\x.xxx)z
"""
# Beta Reduce
# example 6 modified so that first term doesn't shadow free var
# example 7 modified so that first term doesn't shadow free var
exercises_c = r"... |
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread('./images/test_hough.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 灰度图像
# 实行canny边缘检测
edges = cv2.Canny(gray, 50, 200)
plt.subplot(121)
plt.imshow(edges, 'gray')
plt.xticks([])
plt.yticks([])
# hough变换直线检测
lines = cv2.HoughLines(e... |
import time
import socket
CLIENT_PORT = 10001 #Do not change this, hardcoded in the client.py file
server_address = 0
clientSockets = []
# Will make remote client with ip 'ip' start sending data
def start(ip, session_id):
global CLIENT_PORT
global clientSockets
setup_flag = 1
#Check if connection... |
# 异常检测
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(context='notebook', style="white", palette=sns.color_palette("RdBu"))
import numpy as np
import pandas as pd
import scipy.io as sio
from scipy import stats
from sklearn.model_selection import train_test_split
from sklearn.metrics import f1_score, c... |
array = [-2, 4, -3, 4, 6, 6, 3, -2]
indexes_for_poping = []
for i in range(len(array)):
for j in range(i + 1, len(array)):
if array[i] == array[j]:
indexes_for_poping.append(j)
indexes_for_poping.sort(reverse=True)
for i in indexes_for_poping:
array.pop(i)
print('New array is ', arr... |
import tensorflow as tf
x = [1, 2, 3]
y = [1, 2, 3]
learning_rate = 0.1
w = tf.Variable(10.)
b = tf.Variable(10.)
for i in range(10):
# GradientDescentOptimizer -> GradientTape
with tf.GradientTape() as tape:
hx = w * x
cost = tf.reduce_mean(tf.square(hx - y))
# cost-function function... |
import model.ChakeList as mo
import json
data = {'sex':1,'age':2,'alchol':1.1}
def test(data):
print(data['sex']+data['age'])
return data
test(data)
|
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 7 20:19:36 2018
@author: user
字串資料取代
"""
f_name = input()
str_old = input()
str_new = input()
with open(f_name,"r",encoding="utf-8") as fd:
data=fd.read()
print("=== Before the replacement")
print(data)
data=data.replace(str_old,str_new)
print("=== After the repla... |
# @see https://adventofcode.com/2015/day/9
import re
from itertools import permutations
def parse(s: str):
r = re.match(r'([a-zA-Z]+) to ([a-zA-Z]+) = ([\d]+)', s.strip())
return (r[1], r[2]), int(r[3])
def find_dist(a: str, b:str, c: dict):
return c[(a, b)] if (a, b) in c else c[(b, a)]
def calc_route_dist(... |
from emails import send_simple_message
if __name__ == '__main__':
send_simple_message('eldalai@gmail.com', 'MegaChess', 'hola mundo')
|
# Exercício 10.5 - Livro
class Televisao:
def __init__(self, min=2, max=14):
self.ligada = False
self.canal = min
self.minimo = min
self.maximo = max
self.tamanho = 0
self.marca = ''
def avanca(self):
print('Muda canal!')
if self.minimo <= self.ca... |
def wrapper_decorator(func):
def wrapper(*args, **kwargs):
return u"<p>" + func(*args, **wkargs) + u"</p>"
return wrapper
|
from rest_framework.generics import GenericAPIView, ListAPIView, CreateAPIView
from rest_framework.permissions import IsAuthenticated
from .models import Level, LevelPackage
from .serializers import LevelDetailedRetrieveSerializer, PackageSimpleRetrieveSerializer, UserPackageDetailSerializer, \
UserPackageCreateSe... |
# Generated by Django 3.0.3 on 2020-05-10 06:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0003_user_phone'),
]
operations = [
migrations.AlterField(
model_name='user',
name='phone',
fie... |
msg="please input two words:(Enter 'q' to exit)"
while True:
print(msg)
try:
first=input("please input your first number?\n")
if first =='q':
break
first=int(first)
second=input("please input your second number?\n")
if second =='q':
break... |
import numpy as np
from glumpy import app, gloo, gl, glm
vertex=""" uniform vec2 viewport;
uniform mat4 model, view, projection;
uniform float antialias, thickness, linelength;
attribute vec3 prev, curr, next;
attribute vec2 uv;
varying vec2 v_uv;
varying vec3 v_no... |
# -*- coding: utf-8 -*-
from typing import List
class Solution:
def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
return [candy + extraCandies >= max(candies) for candy in candies]
if __name__ == "__main__":
solution = Solution()
assert [True, True, True, False, T... |
import math
from typing import cast, Iterator, List, Optional, Sized, Union
import torch
import torch.distributed as dist
from torch.utils.data import Sampler
from torchvision.datasets.video_utils import VideoClips
class DistributedSampler(Sampler):
"""
Extension of DistributedSampler, as discussed in
ht... |
#!/usr/bin/env python
from __future__ import print_function
import rospy
# import gazebo_msgs.msg
from gazebo_msgs.srv import GetJointProperties
from gazebo_msgs.srv import ApplyJointEffort
import os
#This function will send the joint values with /gazebo/apply_joint_effort
class PD_Controller:
def __init__(self, j... |
from django.http import Http404
from django.shortcuts import get_object_or_404
from django.views import generic
from django.utils import timezone
from ..models import Question
class DetailView(generic.DetailView):
model = Question
template_name = 'polls/detail.html'
# 템플릿에서 참조하는 객체 이름
context_object_n... |
#! -*- coding:utf8 -*-
import os
import sys
import json
reload(sys)
sys.setdefaultencoding("utf-8")
from gensqlalorm.config import get_db_config
from db_connect import DBConnectionPool
from db_executor import DBExecutor
db_connection_pool = None
db_executor = None
def init():
global db_connection_pool
glo... |
# 正確な四捨五入
from decimal import Decimal, ROUND_HALF_UP
num = 123.456
digit = 0.1
round_num = Decimal(str(num)).quantize(Decimal(str(digit)), rounding=ROUND_HALF_UP)
print(round_num)
# 自作の四捨五入関数
import math
def my_round(num, digit):
p = 10 ** digit
s = math.copysign(1, num)
return (s * num * p * 2 + 1) /... |
# -*- coding: utf-8 -*-
'''测试LEGB搜索规则, local --enclosed -- global -- built in '''
#定义全局变量str --str在内建函数(built in)中是将对象转换为字符串
str = 'global str'
#定义测试的嵌套函数
def outer():
#定义enclosed层的变量str
str = 'outer str'
#定义内层函数
def inner():
#定义内存本地变量
str = 'inner str'
print(str)
#调用内层... |
# analysis of a simple investment strategy on historical stock market data
import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize as opt
date, cpi, val = np.loadtxt('sp500.dat', unpack=True)
# normalize stock market values for convenience
val /= 90.0
val0 = 1.32*np.exp(0.06395*(date - 1871))
ratio... |
import os
import pickle
HOST = "0.0.0.0"
class PATHS:
SERVER_CERT = os.path.join(os.path.dirname(__file__),'resources/server.crt')
SERVER_KEY = os.path.join(os.path.dirname(__file__),'resources/server.key')
CLIENT_CERT = os.path.join(os.path.dirname(__file__),'resources/client.crt')
class DATABASE:... |
import numpy as np
import cv2
from queue import MyQueue
import util
import logging
class Engine():
def __init__(self,capForGoal,capForRecording):
self.capGoal = capForGoal
self.capRec = capForRecording
self.limit = 5*20 # 5 means before sec
self.storePrev = MyQueue(limit=self.limit)
self.storeN... |
# coding=utf-8
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -----------------------------------------------------... |
y=int(input())
for j in range(y):
print("Hello")
|
import urllib.request as req
url='https://www.bbc.com/news'
request=req.Request(url, headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'})
with req.urlopen(request) as response:
data=response.read().decode()
#print(data)
i... |
from setuptools import setup, find_packages
setup(
name="matchingmarkeets",
version="0.1.0",
license='BSD-3',
description='Matching Market Simulations',
author='Matt Ranger',
url='https://github.com/QuantEcon/MatchingMarkets.py',
packages=find_packages(),
keywords=['graph', 'network', '... |
from rest_framework.response import Response
from .serializers import StudentSerializer
from .models import Student
from rest_framework import viewsets
class StudentView(viewsets.Viewset):
def list(self, request):
queryset = Student.objects.all()
serializer = StudentSerializer(queryset, many=True)
return Respo... |
"""
*********************************************************************
This file is part of:
The Acorn Project
https://wwww.twistedfields.com/research
*********************************************************************
Copyright (c) 2019-2021 Taylor Alexande... |
from Engine.Player.player import Player
from Engine.Elements.bag import Bag
from Engine.Elements.board import Board
from Engine.Elements.center import Center
from Engine.Elements.discard import Discard
from Engine.Elements.factory import Factory
PlayerCount = int
default_bag = {
0: 20,
1: 20,
2: 20,
3:... |
#!/usr/bin/env python3
import sys
import re
from itertools import product
from util.aoc import file_to_day
from util.input import load_data
def main(test=False):
data = load_data(file_to_day(__file__), test)[0]
r = re.compile(r"((-?[\d]+)..(-?[\d]+))")
m = r.findall(data)
sx, ex, sy, ey = tuple(
... |
class Solution:
def pivotArray(self, nums: List[int], pivot: int) -> List[int]:
less, great, equal = [], [], []
for item in nums:
if item < pivot:
less.append(item)
elif item > pivot:
great.append(item)
else:
equal.a... |
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
import numpy as np
import math
color = [(1, 0, 0), (0, 1, 0), (0, 1, 1), (0, 0, 1)] # colors for plots
def get_data(filename):
return np.loadtxt("dataSets/" + filename + ".txt")
def plot_data(text=""):
# plot colored points
ax = pl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.