text stringlengths 38 1.54M |
|---|
import sys
import pygame
from pygame.sprite import Group
from common.Settings import Settings
from common.ship import Ship
from common.zidan import Zidan
from common.wxr import Wxr
def check_event(ship,setvar,screen,zidans):
"""捕捉键盘和鼠标事件"""
for event in pygame.event.get():
if event.type == pygame.QU... |
import cv2
cam = cv2.VideoCapture(0)
fourcc = cv2.VideoWrite_fourcc(*'XVID')
out = cv2.VideoWrite('my_cam_vis.avi',fourcc, 20.0, (640, 480))
while True:
ret, img = cam.read()
cv2.imshow('my_cma', img)
out.write(img)
if cv2.waitKey(10) == 27:
break
cam.release()
out.release()
cv2.destroyAllWindo... |
#!/usr/bin/env python3
# ============================================================================
# File: featprint
# Author: Erik Johannes Husom
# Created: 2019-12-05
# ----------------------------------------------------------------------------
# Description:
# Save feature importance as numpy arrays.
# ==... |
#!/home/linus/PycharmProjects/flask/bin/python2.7
import os,unittest
from flaskr.models import User,Post,Comment,Like
from config import basedir
from flaskr import app,db
from flaskr.appviews import uniqueMail
from datetime import datetime,timedelta
class TestCase(unittest.TestCase):
def setUp(self):
app.co... |
# Generated by Django 2.0 on 2020-03-08 07:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('account', '0011_headman'),
]
operations = [
migrations.AddField(
model_name='headman',
name='group',
field... |
from django.contrib import admin
from .models import Employee
# Register your models here.
@admin.register(Employee)
class EmployeeAdmin(admin.ModelAdmin):
list_display = ('employee_ID','first_name','last_name','email','contact','address','manager_ID','department_ID','hire_date','is_active')
|
import math
class Health_Kit():
def __init__(self,x_position,starting_point, health, velocity):
self.x_position = x_position
self.y_position = starting_point
self.starting_point = starting_point
self.health = health
self.velocity = velocity
self.frequency = ... |
from __future__ import absolute_import
# Copyright (c) 2010-2019 openpyexcel
from .worksheet import Worksheet
|
def readStyle():
with open('src/style.qss', 'r', encoding='UTF-8') as style:
return style.read() |
import flask
import json
from schemainspect import get_inspector
from sqlalchemy.ext.declarative import declarative_base
from sqlbag import Base
Model = declarative_base(cls=Base)
def selectables(s):
i = get_inspector(s)
names = [_.name for _ in (i.selectables.values())]
return names
class Response(fl... |
# -*- coding: utf-8 -*-
import threading
import ali_speech
from ali_speech.callbacks import SpeechSynthesizerCallback
from ali_speech.constant import TTSFormat
from ali_speech.constant import TTSSampleRate
class MyCallback(SpeechSynthesizerCallback):
# 参数name用于指定保存音频的文件
def __init__(self, name):
self._... |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 4 14:33:36 2018
@author: bramv
"""
import numpy as np
import matplotlib.pyplot as plt
import calendar
import calculate_geostrophic_wind as gw
import read_cabauw_data as r
import settings as s
year = 2016
for i in range(11, 12):
months = [i-1, i] if i > 1 else [12, ... |
# Generated by Django 3.2 on 2021-04-30 07:41
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('courses', '0016_auto_20210430_1540'),
]
operations = [
migrations.AddField(
model_name='test',
... |
CODE_DIR = 'C:/Users/mmall/Documents/github/repler/src/'
SAVE_DIR = 'C:/Users/mmall/Documents/uni/columbia/multiclassification/saves/'
import os, sys, re
import pickle
sys.path.append(CODE_DIR)
import torch
import torch.nn as nn
import torchvision
import torch.optim as optim
import numpy as np
import matplotlib.pypl... |
import datetime
import flask_testing
from sqlalchemy import desc
from monolith.app import create_app
from monolith.database import Story, User, db, ReactionCatalogue, Counter
from monolith.forms import LoginForm, StoryForm
from monolith.urls import *
class TestTemplateStories(flask_testing.TestCase):
app = None... |
# Generated by Django 2.1.7 on 2019-03-22 20:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('equipaments', '0008_clients_date'),
]
operations = [
migrations.AddField(
model_name='clients',
name='planos',
... |
#!/usr/bin/Python
# -*- coding: utf-8 -*-
import uiautomator2 as ut2
ip_list =['10.2.8.138:7912','10.2.8.113:7912','10.2.8.34:7912']
url = 'http://10.0.4.14:9257/dev/android_cn/'
#apkName = 'snqz_banshu_0.0.0.008_1711071629.apk'
apkName ='snqz_test_0.0.0.013_1801241755.apk'
pack_name = ['com.jingmo.snqz','com.snqz.unio... |
#!/usr/bin/env python
import collections
import socket
import struct
import sys
import json
import time
MCAST_ADDR = "224.1.1.1"
MCAST_PORT = 5008
MULTICAST_TTL = 8
PAUSE = 0
PLAY = 1
JUMPTO = 2
GOTOURL = 3
if sys.platform == "win32":
import os, msvcrt
msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
msv... |
from lib.base import BaseGithubAction
from lib.formatters import repo_to_dict
__all__ = [
'GetRepoAction'
]
class GetRepoAction(BaseGithubAction):
def run(self, user, repo, base_url):
if base_url == None:
self._reset(user)
else:
self._reset(user+'|'+base_url)
u... |
from ..main import utils
def test_mac_os():
os = 'mac_os'
res = utils.get_user_details(os)
assert res['name'] == 'Chris'
assert res['surname'] == 'Mipi'
def test_windows():
os = 'windows'
res = utils.get_user_details(os)
assert res['name'] == 'Makhabane'
assert res['surname'] == 'M... |
number = 3
tries = 0
guess = int(input("Guess a number"))
for tries in range (0, 2):
if number > guess:
guess = int(input("Guess higher"))
elif number < guess:
guess = int(input("Guess lower"))
print ("the correct number is 3")
|
# declare tuple of names and print
nametuple = ("Joe", "Sally", "Liam", "Robert", "Emma", "Isabella")
print("Contents of nametuple is: ", nametuple)
# tuple items can be accessed via [] operator
# note that index in [] is zero based
print("Tuple element at index 1: ", nametuple[1])
# index to access tuple can be nega... |
USAGE="""
Creates the heuristic hybrid index given a threshold argument.
"""
import pandas as pd
import numpy as np
import argparse, os, logging, sys
import dev_capacity_calculation_module
if os.getenv('USERNAME') =='ywang':
M_DIR = 'M:\\Data\\Urban\\BAUS\\PBA50\\Draft_Blueprint\\Base z... |
while True:
try:
list_num = int(input())
list_ = input().split()
sort_ = int(input())
lise_new = list_[:list_num]
if sort_:
list_ = sorted(list_,reverse=True)
else:
list_ = sorted(list_)
print(" ".join(list_))
except:
... |
import proxmox_api
import rpyc
import ec2_functions
import sys
import getpass
import multiprocessing
class EC2Service(rpyc.Service):
def on_connect(self, conn):
# code that runs when a connection is created
# (to init the service, if needed)
pass
def on_disconnect(self, conn):
... |
#Q1
olympics=( 'Beijing', 'London', 'Rio', 'Tokyo')
#Q2
tuples_lst = [('Beijing', 'China', 2008), ('London', 'England', 2012), ('Rio', 'Brazil', 2016, 'Current'), ('Tokyo', 'Japan', 2020, 'Future')]
country=[]
for list in tuples_lst:
country.append(list[1])
#Q3
olymp = ('Rio', 'Brazil', 2016)
cit... |
import cv2
import numpy as np
class NeuralNet:
SIGMOID, TANH = 0, 1
activation_map = [staticmethod.sigmoid_activation, staticmethod.tanh_activation]
'''For now, I assume all the hidden layers have the same amount of neurons (n_hidden)'''
def __init__(self, n_hidden_layers=1, n_input=2, n_output=2,
... |
str = "sumit sudalkar"
print(str.capitalize())
str1 = "PYTHON NEED MORE PRACTICE"
a = str1.casefold()
print(a)
str2 = "It is example of count, count the number of string"
b = str2.count("count")
print(b)
str3 = "Align"
c = str3.center(30)
print(c)
str4 = "Working on Python"
x = str4.encode()
print(... |
# Generated by Django 3.1.4 on 2021-11-12 08:25
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('Quiz', '0002_host_create... |
import os
from abc import ABC, abstractmethod
class base_sanitizer():
def __init__(self, ql):
self.ql = ql
@property
@staticmethod
@abstractmethod
def NAME():
pass
@abstractmethod
def enable(self):
pass
def verbose_abort(self):
self.ql.os.emu_error()
... |
#from .alexnet import AlexNet
#from .lenet import LeNet5
#from .mobilenet_v2 import MobileNetV2
#from .mobilenet_v3 import MobileNetv3
#from .regnet import RegNet
#from .resnest import ResNeSt
#from .resnet import ResNet, ResNetV1d
#from .resnet_cifar import ResNet_CIFAR
#from .resnext import ResNeXt
#from .seresnet im... |
#!/usr/bin/env python3
# -*- coding:UTF-8 -*-
import sys
sys.path.append("../common/") # 将其他模块路径添加到系统搜索路径
import numpy as np
import tensorflow as tf
import time
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.exceptions import NotFittedError
from sklearn.metrics import accuracy_score, f1_score
from... |
import smbus
i2c_bus = smbus.SMBus(1)
DEVICE_ADDRESS = 0x08
DISABLE = 2147483647
ENABLE = 2147483646
def send_step(n):
i2c_bus.write_block_data(DEVICE_ADDRESS, 0x00, list(n.to_bytes(4, byteorder='big')))
def step_enable(enable):
send_step(enable*ENABLE or DISABLE)
def main():
step_enable(False)
... |
from django.db import models
from django.utils import timezone
class Note(models.Model):
class Meta:
ordering = ['must_complete_before']
author = models.ForeignKey('auth.User')
task = models.CharField(max_length=40)
create_date = models.DateTimeField(default=timezone.now)
must_complete_bef... |
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from subprocess import call
import pyrebase, json, requests
@csrf_exempt
def echo(req):
fileUrl = str(req.POST['fileUrl'])
config = {
"apiKey": "AIzaSyDCUr8ng_lqfuwHEzOTE-yF2mbarPpBm5M",
"authDomain": "boba-eecca.fireb... |
import abc
class Base(abc.ABC):
@classmethod
@abc.abstractmethod
def factory(cls, *args):
return cls()
@staticmethod
@abc.abstractmethod
def const_behavior():
return 'Should never reach here'
class Implementation(Base):
def do_something(self):
pass
@classm... |
"""
In this problem, median is defind below:
the median of a set S of n integers = the ceil(n / 2)-th smallest element in S
Task is to find the median in any arrays.
Naive algorithm: O(nlogn)
Median of the medians algorithm: O(n)
"""
from math import ceil
def select(arr, k):
if not arr or k < 0 or k >= len(ar... |
from rookcore import web_server
from rookcore.reactive import *
from . import web_server_common
class MyHandler(web_server.Handler, web_server_common.ServerIface):
async def run(self, websocket):
await self.run_rpc(websocket, root_obj=self)
@classmethod
def get_user_code(self):
return [
... |
from __future__ import absolute_import
# /////////////////////////////////////////////////////////////////////////////
# Bundle property O-R mapping classes
# see Conf() docstring
# /////////////////////////////////////////////////////////////////////////////
import splunk
import splunk.auth as auth
import splunk.en... |
from django.db import models
# Create your models here.
# as classes serão criadas aqui
# code first - fazer o código primeiro e depois gerar o bd em uma aplicação
# python utiliza o code first
# o models é a herança de tudo que tem de Model no django
class Pessoa(models.Model):
nome = models.CharField(
... |
s=input("请输入字符串");
sub="abba"#sub="bob";
start=0;
len_sub=len(sub);
num=0;
len_s=len(s);
while(start+len_sub-1<len_s):
num+=s.count(sub,start,start+len_sub);
start+=1;
print("Number of times bob occurs is:")
print(num);
|
class NumberGuesser:
def guess(self, leftOver):
for a in range(1, 9999):
bList = self.getPossibleB(a)
for b in bList:
if a > b:
c = a - b
c = str(c)
while '0' in c:
c = self.removeDigit(c, '0')
valid = True
for x in leftOver:
if x != '0':
if x in c:
c = s... |
from django.contrib import admin
from SmartSuperHero.models import Doctor, Patient, GenericQuestion, Question, Report
# Register your models here.
admin.site.register(Doctor)
admin.site.register(Patient)
admin.site.register(GenericQuestion)
admin.site.register(Question)
admin.site.register(Report) |
# lista = []
# n = int(input())
# input_strings = input("Numerele tale:")
# input_strings = input_strings.split()
# for i in range(len(input_strings)):
# lista.append(int(input_strings[i]))
# quick sort -> algoritm divide et impera
# alegi un pivot si pui numerele mai mici decat pivotul in stanga si pe cele ma... |
# Imports
import random
import numpy as np
from sklearn.metrics import confusion_matrix, auc
def one_hot_dna(seq, exp_len):
'''
One-hot encodes DNA sequence data.
Parameters
----------
seq : list
Input list of DNA sequences (str).
exp_len : int
Expected length of output se... |
from django.contrib import admin
from .models import user_mailcompose_tb,user_mailsave_tb,contacts_tb,user_hobby
# Register your models here.
admin.site.register(user_mailcompose_tb)
admin.site.register(user_mailsave_tb)
admin.site.register(contacts_tb)
admin.site.register(user_hobby) |
import scrapy
import time
import datetime
import re
import json
from REI.scraper import get_ajax_url
from REI.scraper import get_price_history
from bs4 import BeautifulSoup
from REI.crawl import gen_urls
from random import randint
from scrapy.http.request import Request
from scrapy.contrib.spiders import CrawlSpider, R... |
from django.shortcuts import render,render_to_response
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from .forms import loginUser, registerUser
from django.contrib.auth.models import User,Group
from django.contrib.auth import logout
from django.core.exceptions import Ob... |
import logging
import json
from datetime import datetime
from moxie.core.service import Service
from moxie.core.kv import kv_store
from moxie_food.domain import Meal
logger = logging.getLogger(__name__)
KEY_MEAL = 'meals'
KEY_UPDATED = 'last_updated'
class FoodService(Service):
def __init__(self, providers=... |
from abstractcomponent import AbstractComponent
from b_text_block import BTextBlock
from ..gui_settings import *
from ...settings import *
class THeroHud(AbstractComponent):
def __init__(self,x,y,hero):
AbstractComponent.__init__(self,x,y,100,1000)
self.hero = hero
self._build_hud()
d... |
import cv2
import numpy as np
import matplotlib.pylab as plt
from tkinter import *
from tkinter import filedialog
root = Tk()
img1 = cv2.imread(filedialog.askopenfilename(title='multi-select images',
initialdir='C:/Users/',
filetypes=(('jpg files... |
import numpy as np
from sklearn import neighbors
from sklearn.preprocessing import MinMaxScaler
import pandas as pd
import os
class PredictionModel:
def __init__(self):
cur_dir = os.path.abspath(__file__)
cur_dir = os.path.dirname(cur_dir)
data = pd.read_csv(f'{cur_dir}/data.csv')
... |
from rest_framework.permissions import BasePermission
class UsersPermission(BasePermission):
# Listado de usuarios: solo lo puede ver un usuario administrador (y por lo tanto autenticado)
# Creación de usuarios: cualquier usuario
# Detalle de usuario: los admin puede ver cualquier usuario, usuarios auten... |
from django.contrib import admin
import os
import time
from images.models import Video, Album, TFModel
from images.tasks import new_model
# Register your models here.
def close_album(modeladmin, request, queryset):
queryset.update(status='c')
def open_album(modeladmin, request, queryset):
queryset.update(stat... |
from typing import Iterator, Iterable, Tuple, Sized, Union
from elasticsearch import Elasticsearch
from collections import OrderedDict
import math
import numpy as np
import gzip
import json
import csv
def read_json(data_file: str) -> Iterator:
"""read_json reads the content of a JSON-line format file, which has a... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
key_value_list = []
def output_value(jsons, key):
"""
通过参数key,在jsons中进行匹配并输出该key对应的value
:param jsons: 需要解析的json串
:param key: 需要查找的key
:return:
"""
key_value = ""
key_value_list1 = [1,2,3]
if isinstance(jsons, dict):
for json_resul... |
# Yunlu Ma ID: 28072206
import tkinter
import get_point
import P5_logic
import set_dialogs
class Start_game:
# This Class used to build the first root window with a button of "Start Game"
# and run the game
def __init__(self):
# The __init__() fuction builds the tk... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-05-13 12:23
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependen... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import netCDF4
__author__ = 'kmu'
"""
Retrieve data from netcdf files from thredds.met.no or \hdata\grid.
"""
def _nc_info(nc_data):
print('### DIMENSIONS ###')
print(nc_data.dimensions)
for k in nc_data.dimensions.keys():
print("-\... |
# coding=utf-8
# Copyright 2020 The TF-Agents Authors.
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
"""Models and database functions for project"""
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import joinedload
import datetime
# This is the connection to the PostgreSQL database; we're getting this through
# the Flask-SQLAlchemy helper library. On this, we can find the `session`
# object, where we do ... |
import torch.nn as tn
import torch.nn.functional as tnf
import torch.utils.data as tud
import torch.utils.data.dataloader as tuddl
import torch.utils.data.dataset as tudds
import torch.autograd.variable as tav
import torchvision
import torchvision.transforms as tvt
class SiameseNetwork(tn.Module):
def __init__(se... |
#basket에서 인형을 삭제할지 판단하는 함
def determinator(answer, basket):
if(basket[-1] == basket[-2]):
basket.pop()
basket.pop()
answer += 2
return answer
else:
return answer
#각각의 칸에서 가장 높은 곳에 있는 인형을 찾는 함수
def find_top(board, m):
for height in range(len(board)):
if board... |
import linecache
def client_id():
file = open('id.txt', 'r')
second_line = linecache.getline('id.txt', 1)
actual_line = second_line.strip()
file.close()
return actual_line
def secret_id():
file = open('id.txt', 'r')
second_line = linecache.getline('id.txt', 2)
actual_line = s... |
from hed.schema.hed_schema_constants import HedKey
import copy
class HedTag:
""" A single HED tag.
Notes:
- HedTag is a smart class in that it keeps track of its original value and positioning
as well as pointers to the relevant HED schema information, if relevant.
"""
def __init_... |
import turtle
def circle():
while turtle.heading() < 359:
turtle.forward(1)
turtle.left(1)
turtle.left(1)
def poly(r, teta):
n = 360 / teta
while n > 0:
n = n - 1
turtle.forward(r)
turtle.left(teta)
n = 10
while n > 0:
n = n - 1
poly(10, 30)
turtle.... |
import requests
from bs4 import BeautifulSoup
import matplotlib.pyplot as plt
import time
URL = 'https://www.gismeteo.ru/'
plt.ion()
fig, ax = plt.subplots()
temp_data = []
time_data = []
start_time = time.time()
first_time = True
while (1):
if (time.time() - start_time >= 60 or first_time):
first_time = False
... |
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.PROTECT)
text = models.CharField(max_length=400, blank=True, null=False)
image = models.ImageField(upload_to='images/')
created_a... |
#Guessing Game
import random
game_over = False
SECRET = random.randint(1,100)
#
modes = {"easy":10,"hard":5}
print(SECRET)
print('Welcome to the Guessing Game')
MODE_CHOICE = input("'easy' or 'hard'? :").lower()
remaining_guesses = modes[MODE_CHOICE]
print('Guess the right number between 1-100 to win')
def guess():
... |
from django.apps import AppConfig
class IntraTypeDataConfig(AppConfig):
name = 'intra_type_data'
|
import importlib
import os
import pickle
from pytracking.evaluation.environment import env_settings
class Tracker:
"""Wraps the tracker for evaluation and running purposes.
args:
name: Name of tracking method.
parameter_name: Name of parameter file.
run_id: The run id.
"""
def... |
#
# Comparison between different number of grid points in mesh
#
import pybamm
from tec_reduced_model.set_parameters import set_thermal_parameters
pybamm.set_logging_level("INFO")
# Define TDFN with a lumped themral model
model = pybamm.lithium_ion.DFN(
options={
"thermal": "lumped",
"dimensiona... |
import datetime
from pychesscom.clients.base_client import BaseClient
from pychesscom.utils.response import Response
from pychesscom.utils.route import Route
class Player:
"""
Class for handling endpoints of player information.
Args:
client(BaseClient): HTTP client for API requests
"""
d... |
#coding:utf-8
from struct import pack,unpack
import numpy as np
class MecanumBase():
def __init__(self):
self.dir=[]
self.v=0
self.av=0
self.t1=0
self.t2=0
def __encode__(self,vel,angle,angle_v,angle_vd):
if vel<0: vel = 0
vel = int(ve... |
#Addison, due to limitations in my knowledge, we have to settle with this display class. All this does is give a specific entry from the nested "allTime" list.
#The class requires three variables: the huge nested list from the calInputClass, which will be unpacked.
#The week number, starting from 0, and the weekday n... |
from django.db import models
from apps.users.models import *
from django.shortcuts import reverse
from apps.users.models import Student
class Status(models.Model):
title=models.CharField(max_length=100);
slug=models.SlugField(max_length=255)
def __str__(self):
return self.title
#relation containg... |
'''
q1
with语句适用于对资源进行访问的场合,确保不管使用过程中是否发生异常都会执行必要的"清理"工作
主要用于释放资源
比如说:文件适用后的自动关闭;线程中锁的自动获取和释放
'''
f = open('files/readme.txt','r')
data = f.read()
print(data)
f.close()
'''
这么写存在两个问题:
1、没有关闭文件
2、即使关闭了文件,但在关闭之前如果抛出异常,仍然会无法关闭文件
'''
f = open('files/readme.txt','r')
try:
data = f.read()
except:
print('抛出异常')
# 防止了第... |
from aws_lambda_typing.events import SNSEvent
def test_sns_event() -> None:
event: SNSEvent = {
"Records": [
{
"EventVersion": "1.0",
"EventSubscriptionArn": "arn:aws:sns:us-east-2:123456789012:sns-lambda:21be56ed-a058-49f5-8c98-aedd2564c486", # noqa: E501
... |
import numpy as np
import pandas as pd
from collections import deque
import matplotlib
# matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
def len_reg(x,y):
n = len(x)
sigma_x = np.sum(x)
sigma_xsq = np.sum(x ** 2)
sigma_y = np.sum(y)
sigma_xy = np.sum(x * y)
A = np.array([[n, sigma_x], [s... |
from GameObject import GameObject
import pygame
class Hole(GameObject):
def init():
#Loading and scaling player image
Hole.image = pygame.image.load('images/mousehole.png').convert_alpha()
#Using the super (gameobject) init and update
def __init__(self, x, y, rows):
self.ro... |
import numpy as np
import cv2
from train import train
from sklearn.neighbors import NearestNeighbors
COLORS = np.random.random_integers(0, high=255, size=(100, 3))
def foot(rect):
x, y, w, h = rect
pad_w, pad_h = int(0.15*w), int(0.05*h)
return (x+w/2,y+h-pad_h)
def draw_map(img, circles):
r = 10
for circle in ... |
# Author Emily Wang
#!/usr/bin/env python
# coding: utf-8
#import anal_util from ajustador/FrontNeuroinf
import sys
import os
import numpy as np
import pandas as pd
import glob
import scipy
import sklearn as sc
#import the random forest classifier method
from sklearn.ensemble import RandomForestClassifier
from sklearn... |
# project/api/views.py
from flask import Blueprint, jsonify, request
from project.api.models import User, Kanji, Entry, Reading, ReadingInfo, Meaning
from project import db
from sqlalchemy import exc
users_blueprint = Blueprint('users', __name__)
@users_blueprint.route('/ping', methods=['GET'])
def ping_pong():
... |
#!/usr/bin/env python3
#
# A mobility class for Levy walk.
# Copyright (c) 2011-2015, Hiroyuki Ohsaki.
# All rights reserved.
#
# Id: LevyWalk.pm,v 1.11 2015/12/09 14:45:23 ohsaki Exp $
#
import random
import math
from dtnsim.mobility.rwp import RandomWaypoint
from vector import Vector as V
def pareto(scale, shape):... |
from bottle import route, run, template
import requests
import os
from subprocess import Popen
# startup react-markup-server
Popen('npm start >& react-markup-service.log', shell=True,
stdin=None,
stdout=None,
... |
# from code_challenges.linkedList.linked_list import *
class Node:
def __init__(self,value):
self.value = value
self.next = None
class LinkedList:
def __init__(self, head = None):
self.head = head
def append(self,value):
currnet = self.head
prev = None
... |
from source.attribute_grouper import AttributeGrouper
from source.dataframe_splitter import DataframeSplitter
from source.dataframe_monthwise_splitter import DataframeMonthwiseSplitter
from source.month_attribute_grouper import MonthAttributeGrouper
def generate_attribute_grouper_data():
attribute_grouper = Attri... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
def upload_handler(instance, filename):
return 'upload_license{}/{}'.format(instance.user.id, filename)
class UploadLicense(models.Model):
file = models.ImageField(upload_to='upload_license/')
|
# Ghiro - Copyright (C) 2013-2016 Ghiro Developers.
# This file is part of Ghiro.
# See the file 'docs/LICENSE.txt' for license terms.
from django.db.models import Q
from hashes.models import List
from lib.analyzer.base import BaseProcessingModule
try:
import hashlib
IS_HASH = True
except ImportError:
IS... |
import atexit
import json
import logging
import os
from datetime import datetime
from typing import Any, Dict, List, Optional
from apscheduler.schedulers.background import BackgroundScheduler
from flask import Flask, request
from flask_login import LoginManager, current_user, login_required
from webargs import fields
... |
import re
import discord
import asyncio
import tokens
from phonetic import phonetic
client = discord.Client()
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
@client.event
async def on_message(message):
if message.content.st... |
matrix = []
def is_valid(r, c, matrix):
n = len(matrix)
return 0 <= r < n and 0 <= c < n
for _ in range(8):
line = [x for x in input().split()]
matrix.append(line)
directions = {
'up':[-1,0],
'down': [1, 0],
'right':[0, 1],
'left': [0, -1],
'upleft':[-1, -1],
'... |
fish_name = ['selmon roe','red bream',
'egg roll','shimp','kimbab', 'tuna']
fish_price = [1000,3000,1000,2000,1000,5000]
price = 0
for i in range(len(fish_name)):
price += fish_price[i]
print("Total price is",price)
fp = 0
price = 0
for fp in fish_price:
price += fp
print("Total price is",price) ... |
bl_info = {
"name": "Retopology",
"author": "Nikhil Sridhar",
"version": (2, 5, 2),
"blender": (2,80,0),
"location": "View3D > Sideshelf > Retopology",
"description": "Remesh/Retopologize",
"warning": "",
"wiki_url":... |
from picas.documents import Document, Task
from picas.util import seconds
from nose.tools import assert_equals, assert_raises, assert_true
''' @author Joris Borgdorff '''
test_id = 'mydoc'
test_other_id = 'myotherdoc'
def test_create():
doc = Document({'_id': test_id})
assert_equals(doc.id, test_id)
as... |
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
current_r, current_c, current_d = map(int, input().split())
dx = [-1, 0, 1, 0] # 북, 동, 남, 서
dy = [0, 1, 0, -1]
board = []
for i in range(n):
board.append(list(map(int, input().split())))
visited = [[0] * m for i in range(n)] # 청소기가 청소한 곳 ... |
# Binary Search Tree Checker
# Write a function to check that a binary tree is a valid binary search tree.
# class BinaryTreeNode:
#
# def __init__(self, value):
# self.value = value
# self.left = None
# self.right = None
#
# def insert_left(self, value):
# self.left = BinaryT... |
#
# test_http
#
# Copyright (c) 2011-2021 Akinori Hattori <hattya@gmail.com>
#
# SPDX-License-Identifier: MIT
#
import ayame
from ayame import http
from base import AyameTestCase
class HTTPTestCase(AyameTestCase):
def assertStatus(self, st, code, reason, superclass=None):
self.assertEqual(st.code, c... |
def sum_double(a,b):
if a==b:
return 2*(a+b)
return a+b
print sum_double(1,2)
print sum_double(3,2)
print sum_double(2,2)
print sum_double(3,3)
|
import json
import logging
import requests
from EntityLoader import LoadContext, Loading
from github_loading import GithubLoadBehaviour
class SimplePageableBehaviour(GithubLoadBehaviour):
def __init__(self,
_token: str,
per_page: int,
_logger: logging.Logger,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.