text stringlengths 38 1.54M |
|---|
from django.apps import AppConfig
class SupplementaryContentConfig(AppConfig):
name = "regcore.supplementary_content"
verbose_name = "Supplementary content for regulations"
|
m1=int(input())
m2=list(map(int,input().split()))
print(m2.index(min(m2))+1,end=" ")
print(m2.index(max(m2))+1)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def night_at_the_museum(s):
total = 0
last = 'a'
for c in s:
dist = abs(ord(last) - ord(c))
total += min(dist, 26 - dist)
last = c
return total
s = input()
ans = night_at_the_museum(s)
print(ans)
|
import os
import argparse
import sys
import json
import sqlite3
# TODO configure
def configure_query(delimiter=",",type="str", **kwargs) -> str:
pass
def get_config() -> dict:
print("Loading settings.json file")
path = f"{get_folder()}/settings.json"
if not os.path.isfile(path):
print("File ... |
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import pickle
import glob
from collections import defaultdict
from analysis import *
def load_metrics(path):
"""
This function loads metrics
"""
# load the data
seed_folders = glob.glob(f"{path}/*")
... |
import unittest
from configchecker import ConfigChecker
import os
import logging
import sys
from io import StringIO
logging.disable(logging.CRITICAL)
good_config = \
"[FirstSection]\n\
key_integer = 45 \n\
key_boolean = yes \n\
key_float = 23.2\n\
key_string = I am a string\n\
\n\
[SecondSection] \n\
User = hg \n\
\n... |
"""
Quicksort: One of the fastest sorting algorithm. Divide and conquer.
Select a pivot and place it in it's place in the array, then
recursively do the same for left and right partitions of the remaining array.
Time Complexity: O(n*log(n)) [O(n*n) - Worst case]
Space Complexity: O(log(n))
Inplace: Yes
Stable: ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 5 04:34:01 2020
@author: chetanya
"""
{
"sender_address": "",
"reciever_address":"",
"units":"",
"Ether":""
} |
#!/usr/bin/python
#
# Magicor
# Copyright 2006 Peter Gebauer. Licensed as Public Domain.
# (see LICENSE for more info)
import sys, os
def change_to_correct_path(): #taken from pygame wiki cookbook
import os, sys
exe_base_dir = os.path.abspath(os.path.dirname(sys.argv[0]))
os.chdir(exe_base_dir)
sy... |
#SMPAIR
for _ in range(int(input())):
n = int(input())
num = list(map(int,input().split()))
num.sort()
print(num[0] + num[1])
|
class classname:
def createname(self,name):
self.name=name
def displayname(self):
return self.name
def saying(self):
print "hello %s" %self.name
print classname
first=classname()
second=classname()
first.createname("chandan")
second.createname("kuiry")
print first.displayname()
print second.displayname()
firs... |
# @Author : Vector
# @Email : vectorztt@163.com
# @Time : 2019/5/30 17:09
# -----------------------------------------
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from conf.base_page import BasePage
from conf.decorator import teststep
class MedalPage(Bas... |
import os
import random
import string
from transliterate import detect_language
from transliterate import slugify as slugify_translit
from django.utils.text import slugify
def get_filename_ext(filepath):
base_name = os.path.basename(filepath)
name, ext = os.path.splitext(base_name)
return name, ext
de... |
#!/usr/bin/env python
# coding=utf-8
# Python Script
#
# Copyright © Manoel Vilela
#
#
from simulation import AntSimulation
matrix = AntSimulation.run()
print("Goodbye!") |
"""
Summary:
Libary of functions to create an the report.
"""
from . import meistertask_requests as meistertask
from datetime import datetime
from datetime import timedelta
from . import data_helper
import json
def calctime(starttime,endtime):
"""
Summary:
Calculates the difference between start time a... |
# Generated by Django 3.0.5 on 2020-11-09 11:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0051_auto_20201109_0622'),
]
operations = [
migrations.AddField(
model_name='attendance',
name='image',
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the OLE Compound File summary and document summary plugins."""
import unittest
from plaso.parsers.olecf_plugins import summary
from tests.parsers.olecf_plugins import test_lib
class TestSummaryInformationOLECFPlugin(test_lib.OLECFPluginTestCase):
"""Tes... |
def validation():
name = input("What is your name?")
print("Hello",name,",you are a beautiful fucking bastard.")
validation()
|
locators = {
'breadcrumbs': '//*[@id="container"]/div[2]',
'home': '//*[@id="container"]/div[2]/a[1]',
'authentication_and_authorization': '//*[@id="container"]/div[2]/a[2]',
'groups': '//*[@id="container"]/div[2]/a[3]',
'are_you_sure_headline': '//*[@id="content"]/h1',
'are_you_sure_question': '//*[@id="co... |
from typing import List
from bisect import bisect_right
class Solution:
def breakfastNumber_(self, staple: List[int], drinks: List[int], x: int) -> int:
# 暴力解法
res = 0
for i in staple:
for j in drinks:
if i + j <= x:
res += 1
... |
import numpy as np
from numpy import mat
#将各节点的有向图转换为概率转移矩阵
def probability_graph(w_ori_mat):
N = w_ori_mat.shape[0]
for i in range(N):
w_ori_mat[:,i] = w_ori_mat[:,i] / np.sum(w_ori_mat[:,i]) #这个sum函数用的好,直接的想法事用for循环,而这一个是用数学的方法,这种要总结
return w_ori_mat
def pangerank(w_ori_mat, iter_num, c_dampin... |
import random
def hangman(correct_word):
uniq = set()
wrong = set()
hint = "-" * len(correct_word) # hint =["-"] * len(correct_word)
chances = 8
while chances > 0:
print()
print(hint) ... |
from ctypes import addressof, create_string_buffer
from warnings import warn
import numpy as np
from pyvst import VstPlugin
from pyvst.vstwrap import VstTimeInfoFlags, VstTimeInfo, AudioMasterOpcodes
from pyvst.midi import midi_note_event, wrap_vst_events
# Class inspired from MrsWatson's audioClock
class Transport... |
import os
import pickle
from matplotlib.transforms import Bbox
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import wavfile
from tqdm import tqdm
from utils import get_spectrogram, plot_spectrogram
from scipy.ndimage import gaussian_filter
from skimage.filters import apply_hysteresis_threshold
from s... |
from datetime import date, datetime
from dateutil.rrule import MONTHLY, YEARLY
import pytest
from dashboard.libs.date_tools import (
get_workdays, get_workdays_list, get_bank_holidays, get_overlap,
parse_date, to_datetime, slice_time_window, dates_between,
financial_year_tuple, get_weekly_repeat_time_wind... |
def main():
score = float(input('Enter the test score: '))
if score < 60:
print('Your grade is F.')
elif score < 70:
print('Your grade is D.')
elif score < 80:
print('Your grade is C.')
elif score < 90:
print('Your grade is B.')
elif score >=90:
... |
import code
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("run_mlm_features")
import torch
import spacy
nlp = spacy.load('en_core_web_sm')
lemma_overrides = {
'it': ['it'],
"they/them": ['they', 'them'],
"oneself": ['himself', 'herself', 'itself', 'themselves', 'oursel... |
import pygame
class Cell:
def __init__(self, i, j, cell_size):
self.i = i
self.j = j
self.size = cell_size
self.number = 0
def draw(self, surface):
print("Rysuję")
# print(self.number, end="")
#pygame.draw.rect()
w, h = self.size... |
import pandas as pd
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
from sklearn import svm
# read data from csv
def read_data():
train = pd.read_csv('../input/train_features')
test = pd.read_csv('../input/test_features')
label = pd.read_csv('../input/train_label'... |
#!/usr/bin/env python
import unittest
from dominion import Card, Game, Piles, Player
###############################################################################
class Card_Den_of_Sin(Card.Card):
def __init__(self):
Card.Card.__init__(self)
self.cardtype = [Card.CardType.NIGHT, Card.CardType.D... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import gym
from itertools import count
import time
import matplotlib.pyplot as plt
R = np.loadtxt('return_per_episode_baseline.txt')
L1 = np.loadtxt('return_per_episode_decay_rate_30000.txt')
L2 = np.loadtxt('return_per_episode_deca... |
import logging
import threading
import time
from ast import literal_eval
from random import randint
from threading import Thread
import requests
from flask import Flask, request, jsonify, render_template
from tools.maths import rnd
from client.motors.v03 import Motor
from datetime import datetime
from client import h... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 15 11:05:38 2018
@author: CUHKSZ
"""
import time
#from collections import deque
from ina219 import INA219
from ina219 import DeviceRangeError
def sensor():
Shunt_OHMS = 0.1 # For this sensor it is 0.1 ohm
try:
print('Starting Current Sensor')
... |
"""list of common VLANs."""
def int_in_list(a_list):
"""Convert a_list elements to int type."""
counter = 0
for elem in a_list:
a_list[counter] = int(elem)
counter += 1
COMMAND1 = "switchport trunk allowed vlan 1,3,10,20,30,100"
COMMAND2 = "switchport trunk allowed vlan 1,3,100,200,300"
... |
# Return the sum of the numbers in the array, except ignore sections of numbers
# starting with a 6 and extending to the next 7 (every 6 will be followed by at
# least one 7). Return 0 for no numbers.
def sum67(nums):
sum = 0
add = True
for i in nums:
while add == True:
if i != 6:
... |
from lxml import html
import json
import requests
from time import sleep
def AdebooksParser(url, isbn, keyword):
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36'}
page = requests.get(url,headers=headers)
while Tru... |
from enum import Enum
from string import ascii_uppercase, ascii_lowercase
from typing import NamedTuple, Tuple, Generator
class CharacterType(Enum):
LOWERCASE = 'LOWERCASE'
UPPERCASE = 'UPPERCASE'
UNDERSCORE = 'UNDERSCORE'
DASH = 'DASH'
DOT = 'DOT'
SLASH = 'SLASH'
COMMA = 'COMMA'
OTHER... |
#
# Copyright (c) 2023 Airbyte, Inc., all rights reserved.
#
import pendulum
import pytest
import responses
from airbyte_cdk.models import SyncMode
from pytest import fixture
from source_orb.source import CreditsLedgerEntries, Customers, IncrementalOrbStream, OrbStream, Plans, Subscriptions, SubscriptionUsage
@fixt... |
#!/usr/bin/env python
from ListNode import ListNode, ListTestCase
head = ListTestCase(range(10)).head
ListTestCase.prettyPrint(head)
def reverse(head):
pre = None
p = head.next
while p != None:
tmp = p.next
p.next = pre
pre = p
p = tmp
head.next = pre
return head
... |
# train_model.py
import numpy as np
from alexnet import alexnet
WIDTH = 205 # 80
HEIGHT = 155 # 60
LR = 1e-3
EPOCHS = 8
MODEL_NAME = 'pyET2-car-{}-{}-{}-epochs.model'.format(LR, 'alexnetv2', EPOCHS)
model = alexnet(WIDTH, HEIGHT, LR)
print('Ready to load data, loading now: ')
train_data = np.load('shuffled_final.n... |
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets.samples_generator import make_blobs
data_dict= {}
sample_data= None
labels= None
NUM_EPOCHS= 100000
X_train= []
X_test= []
Y_train= []
Y_test= []
def create_data():
global data_dict, sample_data, labels, min_fval, max_fval
X0, labels = make_... |
from .utils import *
from .base_actuator import Actuator, HighLevelActuator
from .wheel_actuator import WheelActuator
from .communication_transmitter import CommunicationTransmitter
from .RF_transmitter import RF_Transmitter
from .led_actuator import LedActuator
from .joint_actuator import JointPositionActuator... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('firestation', '0018_assign_station_number'),
]
sql = """
BEGIN TRANSACTION;
-- If postgres supported negative lookbehind regexes, t... |
#
# Copyright 2016 iXsystems, Inc.
# All rights reserved
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted providing that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and th... |
# vim: ai ts=4 sts=4 et sw=4
from datetime import datetime
from django.db import models
from mwana.apps.locations.models import Location
from rapidsms.models import Contact
class SMSAlertLocation(models.Model):
"""
Manages facilities that can receive SMS alerts
"""
district = models.ForeignKey(Locati... |
__author__ = 'christopherrivera'
########################################################################################################################
# This contains functions classes for scrapping the web or parsing websites
#########################################################################################... |
import pygame
from pygame.locals import *
from EventManager import *
from Charactor import CharactorViewEntity
from Sprite import *
class PygameView:
def __init__(self, evManager):
self.evManager = evManager
#List every event for which this object listens
self.evManager.registerListener(self,[TickEvent,MapB... |
#coding=utf-8
__author__ = 'JinyouHU'
'''
使用属性tags设置item的tag
使用Canvas的方法gettags获取指定item的tags
'''
from Tkinter import *
root = Tk()
#创建一个Canvas,设置其背景色为白色
cv = Canvas(root, bg='green')
#使用tags指定一个tag('r1')
rt = cv.create_rectangle(10, 10, 110, 110,
tags=1
)
cv.pack()
print cv.gettags(r... |
import psycopg2
""" Convenience class that wraps a Postgres Database Connection. """
class Connection:
def __init__(self, host, dbname, user, password):
self.host = host
self.dbname = dbname
self.user = user
self.password = password
def connect(self):
self.conn = psyco... |
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Store, Base, InventoryItem, User, Category
engine = create_engine('sqlite:///store.db')
# Bind the engine to the metadata of the Base class so that the
# declaratives can be accessed through a DBSession inst... |
## Script for Exporting Briefcase contents to a text file
## Copies the Briefcase as a tar file
## Extracts The File "toc.xml" from the tar file (toc = table of contents)
## Parses "toc.xml" and writes each line to a text file
## Counts each parsed line and revisits the text file
## Writes number of line as final ... |
__author__ = 'sriram'
def get_prime_numbers(p1, p2):
primes = []
for num in range(p1, p2):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
primes.append(num)
return primes
def find_next_prime(a, b):
... |
from PIL import Image
__author__ = 'sss'
IMAGE_HEIGHT = 60
IMAGE_WIDTH = 160
if __name__ == '__main__':
image = Image.open("C:\\Users\sss\Desktop\\2907.jpg")
image = image.resize((IMAGE_WIDTH, IMAGE_HEIGHT)) #resize image with high-quality
image.save("C:\\Users\sss\Desktop\\bbb.png", 'png') |
import numpy as np
import math
from domains.environment import Environment
import copy
class SimpleEnv(Environment):
def __init__(self, branch, solution_path, printp=False):
self._branch = branch # branching factor
self._solution_path = solution_path # path to unique solution
self._path ... |
n=int(raw_input())
print("enter '0' for exist")
n=input("enter any character")
if n==0:
exit();
else:
if((n>='a' and n<='z') or (n>='A' and n<='z')):
print("Alphabet")
else:
print("Not")
|
class PlayerDto:
def __init__(self, server_id: int, player_id: int, inventory: list[str]=[],
coal_count: int=0, score: int=0):
self.server_id = server_id
self.player_id = player_id
self.inventory = inventory #list of items
self.coal_count = coal_count
self.score = len(inventory) |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
a=np.array([1,2,3])
# In[2]:
a
# In[3]:
a[0]
# In[4]:
a[2]
# In[10]:
import sys
# In[11]:
x=range(500)
# In[12]:
array=np.arange(500)
# In[13]:
print(sys.getsizeof(5)*len(x))
print(array.size*array.itemsize)
# In[14]:
a... |
import requests
url = 'http://httpbin.org/post'
files = {'file': open('post_file.txt', 'rb')}
r = requests.post(url, files=files)
print(r.text)
|
# elevator.py
import os
import logging
import argparse
import threading
import time
import random
import json
import paho.mqtt.client as mqtt
from typing import List
from cps_common.data import Passenger, PassengerEncoder, ElevatorData
class Floor:
def __init__(self, id: int):
self.floor: int = id
... |
from lib import common
def login():
print("登录功能")
common.logger('egon刚刚登陆了')
def register():
print("注册功能")
def witdraw():
print("提现功能")
def transfer():
print("转账功能")
func_dict={
'0':['登录',login()],
'1':['注册',register()],
'2':['提现',witdraw()],
'3':['转账',transfer()],
'5':['退出',... |
from typing import List
import random
class Layer:
def __init__(self, size: int):
self.size = size
self.neurons = [0.] * size
self.biases = [0.] * size
self.weights = []
class NeuralNetwork:
def __init__(self, learningRate: float, activation, derivative, sizes: List[int]):
... |
import logging
import pymysql
logger = logging.getLogger()
class PyMysqlBase(object):
"""建立单个 mysql 数据库连接的 python 封装"""
def __init__(self,
host='localhost',
port=3306,
user='user',
password='pwd',
db='db',
... |
from django.conf.urls import url
from .views import (ReportFormView, ProjectDetailView, ProjectListView, home, inner, temp)
urlpatterns=[
url(r'^$', home, name='home'),
url(r'^inner/$',inner,name='inner'),
url(r'^temp/$',temp,name='temp'),
url(r'^report-form/$', ReportFormView.as_view(), name='report-form'),
url(r... |
N = int(input())
visit = [[0]*N for _ in range(N)]
a = [list(map(int,list(input()))) for _ in range(N)]
# print(a)
# print(visit)
cnt = 0
dx = [1,-1,0,0]
dy = [0,0,1,-1]
def bfs(x, y, cnt):
queue = [[x,y]] # 이중배열
visit[x][y] = cnt
while queue:
current_node = queue.pop(0) # 0번째 인덱스인 리스트 하나가 나옴
... |
from sys import argv
# read WYSS section for how to run this
script, first, second, third = argv
print("The script is called:", script)
print("The first variable is:", first)
print("The second variable is:", second)
print("The third variable is:", third)
# What you should see
# WARNING! Pay attention! You... |
n = int(input())
ll = []
for i in range(n):
peo={}
temp = input().split()
n = int(temp[1])**2+int(temp[2])**2
peo[n] = temp[0]
ll.append(peo)
print(ll)
|
##### Part 1 #####
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.cross_validation import train_test_split
from sklearn import metrics
import statsmodels.formula.api as smf
# visualization
import seaborn as sns
import matplotlib.pyplot as plt
# 1. read in the yelp dataset
import p... |
user_input=input("ENTER STRING ")
print("OUTPUT")
#titlte first letter of each word will be capilta
print(user_input.title())
#capitalize first letter of string will be capital
print(user_input.capitalize())
#all letters will be capital
print(user_input.upper())
#OUTPUT
"""
ENTER STRING my name is mohd mazh... |
import pickle
from config import *
from Messages.Ack import Ack
from Messages.message_types import *
from utils.utils import *
class MessageHandler:
def __init__(self, msg, server_socket):
self.msg = msg
self.server_socket = server_socket
self.handle_message_scenario()
# here we send t... |
import matplotlib.pyplot as plt
import numpy as np
def A7(title, blue, green, brown, other):
y = [blue, green, brown, other]
x = [2, 4, 6, 8]
y_ticks = list(range(max(y)+2))
# Format y_ticks
def format_y_ticks():
if max(y) < 30:
y_even = []
for val in y_tick... |
from django.conf.urls import patterns, url
from rest_framework.urlpatterns import format_suffix_patterns
from rrdapi import views
urlpatterns = patterns('',
# url(r'^rrddata/$', 'rrddata_detail'),
url(r'^rrddata/$', views.RRDDataDetail.as_view()),
)
urlpatterns = format_suffix_patterns(urlpatterns)
|
import argparse
from src.data import CelebaData
from src.train import Trainer, Evaluation
from src.utils import load_checkpoint
from src.config import config
from src.net import VggNetwork
import torch
parser = argparse.ArgumentParser()
parser.add_argument("--epochs", help="Number of epochs to train", type=int, defa... |
import serial
import pyqtgraph as pg
import random
from PyQt5 import QtGui, QtWidgets,QtCore
from PyQt5.QtWidgets import QWidget, QApplication
from pyqtgraph.Qt import QtGui, QtWidgets,QtCore
from threading import Thread
'''
app = QtGui.QApplication([])
win = pg.GraphicsLayoutWidget(show=True, title="Basic plotting ex... |
# coding=utf-8
import math
import operator
import os
import datetime
#from numpy import *
class KnnUtil:
def __init__(self):
pass
def get_us(self,time_pointa,time_pointb):
return time_pointa.second*1000000+time_pointa.microsecond-time_pointb.second*1000000-time_pointb.microsecond
def dis... |
from node_position import NodePosition
def get_neighbor_coordinates(node_pos):
"""
Calculates node's neighbor's cartesian coordinates
:param node_pos: tuple containing node's coordinates
:return: neighbor coordinates as a dictionary
"""
x, y = node_pos
top = (x - 1, y)
bottom = (x + 1,... |
from flask import Flask, request, session, g, redirect, url_for, \
abort, render_template, flash, Response, send_from_directory
import time
from bluepy import btle
import logging
import server_settings
app = Flask(__name__)
app.config.from_object(__name__)
# WARNING: For some reason, setting Flask DEBUG=True caus... |
#!/usr/bin/env python
# coding: utf-8
# In[141]:
import os
import csv
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import requests
import json
from pprint import pprint
from stats import median
csvpath = os.path.join("Data", "city_codes.csv")
csvpath = os.path.join("Data", "majors_dates.cs... |
from typing import Protocol
class SessionManagerAdapter(Protocol):
async def get(self):
...
async def commit(self):
...
async def rollback(self):
...
async def close(self):
...
async def execute(self, *args, **kwargs):
...
|
from GUIControllerAttack import *
from GUImethods import *
def sshAttack(raiz):
'''
:param raiz: Se recibe la dirección de memoría de la interfáz gráfica de Tkinter
:return: No se devuelve nada, simplemente se llama a la función 'Controller' definida en 'GUIControllerAttack.py'
'''
attackWi... |
# 1423. Maximum Points You Can Obtain from Cards (Medium)
def maxScore(self, cardPoints: List[int], k: int) -> int:
n = len(cardPoints)
total = sum(cardPoints)
if n == k:
return total
rem = n - k
subArr = 0
maxSum = 0
for i in range(n):
if i < rem:
subArr += ... |
import subprocess
def get_firmware_url():
return 'https://github.com/makestack/esp8266-firmware/releases/download/v0.3.0/firmware.bin'
def install(serial, firmware_path):
subprocess.run(['esptool', '-v', '-cd', 'ck', '-cb', '115200',
'-cp', serial, '-ca', '0x00000', '-cf', firmware_path]... |
"""%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PARAMETERSPACE_AGNfitter.py
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
This script contains all functions used by the MCMC machinery to explore the parameter space
of AGNfitter.
It contains:
* Initializing a point on the parameter space
* Calculating the lik... |
# (0). 选择题库。
# 写这个程序,要用到requests模块。
# 先用requests下载链接,再用res.json()解析下载内容。
# 让用户选择想测的词库,输入数字编号,获取题库的代码。
# 提示:记得给input前面加一个int()来转换数据类型
import requests
link = requests.get('https://www.shanbay.com/api/v1/vocabtest/category/')
#先用requests下载链接。
js_link = link.json()
#解析下载得到的内容。
bianhao = int(input('''请输入你选择的词库编号,按Ente... |
import os
import pygame
import pygame.mixer
import random
import sys
#required
pygame.init();
#colors
white = (255,255,255)
#window size
X_MAX = 950
Y_MAX = 472
#position vars
background_x = 0
background_y = 0
mich_x = 75
mich_y = 100
block_init_y_top = 0
block_init_y_bottom = 375
ref_init_y_bottom = 300
win_screen_x... |
import mysql.connector
conexion = mysql.connector.connect(
host = 'cloud.eant.tech',
database = '',
user = '',
password = 'eantpass')
cursor = conexion.cursor()
sql = "SELECT nombre, apellido FROM alumnos where apellido like 'r%'"
cursor.execu... |
from urllib import request, parse
url = 'http://httpbin.org/post'
headers = {
'User-Agent ': 'Mozilla/4.0 (compatible; MSIE S. S; Windows NT)',
'Host':'httpbin.org'}
dict={'name':'Germey'}
data= bytes(parse.urlencode(dict), encoding='utf-8')
req = request.Request(url=url, data=data, headers=headers, method='POS... |
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 22 22:25:01 2020
@author: zeh0814
"""
def main(x, target):
import functools
import math
#比较字符串中使用('+','-','*','/')的总个数,输出个数较少的
def CompareLen(str1,str2):
sum1,sum2 = 0,0
for i in {'+','-','*','/'}:
sum1 = sum1 + str1.count(i)... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 15 17:31:41 2021
@author: alysonweidmann
"""
|
# -*- coding: utf8 -*-
# org.onap.vnfrqts/requirements
# ============LICENSE_START====================================================
# Copyright © 2018 AT&T Intellectual Property. All rights reserved.
#
# Unless otherwise specified, all software contained herein is licensed
# under the Apache License, Version 2.0 (th... |
# assignment_010: Building your own Data set from Google Images
# The task is to create an image dataset through Google Images, visualise the train and
# test sets.
# Your codes here..
|
from django.contrib import admin
from .models import Web_test
from django.contrib import messages
from web_test.views import WebTest
from product.models import Product
from django.urls import reverse
from django.utils.html import format_html
#<a href="/admin/product/product/2/change/">2</a>
@admin.register(Web_test... |
import argparse
import gym
import torch
from models.dqn_learning import DQN_net
from tensorboardX import SummaryWriter
def train(config, device, writer):
step_list = []
i_episode_list = []
env = gym.make(config.env)
env = env.unwrapped
config.action_space = env.action_space.n
config.state_s... |
#!/usr/bin/env python
# Copyright 2017, Tianwei Shen, HKUST.
# compute mAP score for overlap benchmark
import sys, os
sys.path.append('..')
from tools.common import read_list
def compute_overlap_ap(gt_list, res_list, d):
gt_size = len(gt_list)
old_recall = 0.0
old_precision = 1.0
ap = 0.0
interse... |
from input_algorithms.errors import BadSpecValue
from input_algorithms.dictobj import dictobj
from input_algorithms import spec_base as sb
from input_algorithms.meta import Meta
from delfick_error import DelfickError, ProgrammerError
from collections import defaultdict
from operator import itemgetter
from layerz impor... |
#!/usr/bin/env python
# encoding: utf-8
"""
@author: Wayne
@contact: wangye.hope@gmail.com
@software: PyCharm
@file: Largest Magic Square
@time: 2021/06/13 00:22
"""
from typing import *
class Solution:
def largestMagicSquare(self, grid: List[List[int]]) -> int:
rs = [[0] + list(accumulate(row)) for row... |
import unittest
import json
from tests.v2.basecases import TestBaseCase
class QuestionTestCase(TestBaseCase):
"""
test class for the question endpoint
"""
def test_user_posting_a_question_with_str(self):
"""Test user posting a question to no meetup"""
auth_token = self.user_login()
... |
from __future__ import annotations
from unittest.mock import patch
import pytest
from kombu import Connection
class test_get_manager:
@pytest.mark.masked_modules('pyrabbit')
def test_without_pyrabbit(self, mask_modules):
with pytest.raises(ImportError):
Connection('amqp://').get_manage... |
###JunctionArray
#Copyright 2005-2008 J. David Gladstone Institutes, San Francisco California
#Author Nathan Salomonis - nsalomonis@gmail.com
#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 Soft... |
fr = open('text.txt')
import json
# fw = open('text2.txt', 'w')
# fw.write('HELLO PIDOR!\n')
def getJSON(filePathAndName):
with open(filePathAndName, 'r') as json_data:
return json.load(json_data)
class Book:
def __init__(self, i, author, title, date, shellNumber):
self.id = i
self.title = title
s... |
"""
-------------------------------------------------------
Lab/Assignment Testing
-------------------------------------------------------
Author: Zehao Liu
ID: 193074000
Email: liux4000@mylaurier.ca
(Add a second set of Author/ID/Email if working in pairs)
__updated__ = '2020-05-18'
---------------------------... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.