text
stringlengths
38
1.54M
import requests import json import zipfile import re def startDownload(project_id): print('downloading project: ' + str(project_id)) # try: resp = requests.get( 'https://cdn.projects.scratch.mit.edu/internalapi/project/' + str(project_id) + '/get/') project = resp.json() p...
# -*- coding: utf-8 -*- """ Created on Sun Aug 14 10:36:06 2016 @author: Luciano """ import numpy as np import matplotlib.pyplot as plt from scipy import ndimage as ndi from PIL import Image import scipy.signal import tifffile from skimage import io def importData(cameraFrameFile, darkFrameFile): img = Im...
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-12-10 19:15 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('music_choreo_app', '0002_auto_20171210_1853'), ] operations = [ migrations.Al...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function from pyoselm.core import OSELMClassifier, OSELMRegressor from sklearn.datasets import load_digits, make_regression from sklearn.metrics import confusion_matrix import numpy as np import time import random import sys def make_batch...
priority = { "+" : 1, "-" : 1, "/" : 2, "X" : 2, "^" : 3, "(" : 0, ")" : 0, } def isFloat(number): try: float(number) return True except: return False def infixToPost(inExpr): global priority postExpr, opStack = [], [] for token in list(inExpr.strip().split()): if isFloat(token): postExpr.appe...
locators = { 'title': '//*[@id="site-name"]/a', 'username_title': '//*[@id="login-form"]/div[1]/label', 'username_field': '//*[@id="id_username"]', 'password_title': '//*[@id="login-form"]/div[2]/label', 'password_field': '//*[@id="id_password"]', 'login_button': '//*[@id="login-form"]/div[3]/input', }
import PySide.QtGui as QtGui import PySide.QtCore as QtCore import Ui_MainWindow import GameWorld class MainWindow(QtGui.QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow.Ui_MainWindow() self.ui.setupUi(self) scene = GameWorld...
from torch import nn import torchvision.models as models from torchvision.models.resnet import Bottleneck from torch.hub import load_state_dict_from_url class MedNet(models.ResNet): """ Simple transfer learning for a medical image task instead of CIFAR """ def __init__(self, num_classes): super(MedNet...
# -*- coding: utf-8 -*- # by Part!zanes 2017 import re import requests from log import Log from config import Config as cfg class hdapi(object): cfg.initializeConfig() hdLog = Log("hdLog") hdUrl = cfg.getHdUrl() @staticmethod def postQuickReply(ticket_id, reply, status, openbot): secretKe...
from tkinter import Canvas, BOTH from automata import Automata from canvasGrid import CanvasGrid class AutomataCanvas(Canvas): def __init__(self, frame=None, data=None, automata=None, width=0, height=0): if frame == None: raise ValueError('ERROR: no frame') super().__init__( frame, ...
import cv2 for dogNUM in range(4000): dogPic="dogs/dog."+str(dogNUM+1)+".jpg" img=cv2.imread(dogPic) imgResize=cv2.resize(img,(32,32)) dogPic2="DataSet_CAT_DOG/dogs/dog."+str(dogNUM)+"resized.jpg" cv2.imwrite(dogPic2,imgResize) for catNUM in range(4000): catPic="cats/cat."+str(catNUM+1)+".jpg"...
import numpy as np import json import tensorflow as tf from config import Config from utils import * import sys import os class imdb_classifier(object): def __init__(self, config, session, x_train, y_train, x_test, y_test, train_length, test_lentgh): self.config = config self.embedding_size = config...
class Point: def __init__(self, orientation, position, timestamp): self.orientation = orientation self.position = position self.timestamp = timestamp class Orientation: def __init__(self, w, x, y, z): self.w = w self.x = x self.y = y self.z = z class P...
def zero_matrix(matrix): zero_cols = [] count = 0 for row in matrix: has_zero = False count = 0 for column in row: if column == 0: zero_cols.append(count) has_zero = True count += 1 if(has_zero...
from ast import Call from hashlib import sha256 from random import randint from shellshock.parse import Parseable, parse class AssignType(Parseable): @classmethod def parse(cls, obj): assign_target = obj.targets[0].id cls._known_vars.add(assign_target) if isinstance(obj.value, Call) a...
import asyncio import logging from abc import ABCMeta from types import MappingProxyType from typing import Any, Callable, Mapping, Optional from . import decorators from .abc import AbstractRoute, AbstractWebSocket log = logging.getLogger("wsrpc") # noinspection PyUnresolvedReferences class RouteMeta(ABCMeta): ...
''' This code is based on the Matryoshka [1] repository [2] and was modified accordingly: [1] https://arxiv.org/abs/1804.10975 [2] https://bitbucket.org/visinf/projects-2018-matryoshka/src/master/ Copyright (c) 2018, Visual Inference Lab @TU Darmstadt ''' import os import json from collections impor...
# Made with python3 # (C) @FayasNoushad # Copyright permission under MIT License # All rights reserved by FayasNoushad # License -> https://github.com/FayasNoushad/Info-Bot/blob/main/LICENSE import os from pyrogram import Client, filters from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton FayasNoush...
# Generated by Django 3.0.5 on 2020-05-04 03:38 import django.contrib.postgres.indexes import django.contrib.postgres.search from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('questions', '0004_auto_20200503_0713'), ] operations = [ migrat...
# Copyright 2019 Yelp 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 writing, so...
import sys, os from collections import deque from skimage.segmentation import slic from skimage.morphology import remove_small_objects, disk, remove_small_holes, binary_dilation from skimage.future.graph import rag_mean_color, cut_normalized from multiprocess import Pool sys.path.append(os.path.join(os.environ['REPO_D...
#! /usr/bin/env python import argparse import json import os import cv2 from frontend import YOLO from utils import draw_boxes os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"] = "0" argparser = argparse.ArgumentParser( description='Infer the localization of nucleus using YOLO_v...
from flask import Blueprint, jsonify, request, abort, make_response from services import userService from auth import requiresAdmin from utils.mail import sendMail mail = Blueprint("mail", __name__, url_prefix="/mail") @mail.route("/<id>", methods=["POST"]) @requiresAdmin def sendMailToId(id): if request.is_json...
#!/usr/bin/env python # coding=utf-8 """ Copyright (C) 2019 * Ltd. All rights reserved. Editor : PyCharm File name : buttom.py Author : Charles zhang Created date: 2020/6/7 12:16 Description : """ import pygame.font class Button: def __init__(self, setting, screen, ms...
from django.contrib import admin # Register your models here. from .models import Run, Manufacturer, Shoe class ManufacturerAdmin(admin.ModelAdmin): fields = ("name",) list_display = ["name",] # list_display_links = ["name",] # list_editable = ["name",] # list_filter = ["name",] search_fileds = [...
# -*- coding: utf-8 -*- """ Created on Wed Nov 4 16:32:03 2020 @author: DELL """ import pandas as pd import numpy as np data1 = pd.read_csv('ReaderInformation.csv'); data2 = pd.read_csv('ReaderRentRecode.csv'); #观察数据 print(data1.info()) print(data2.info()) data3 = pd.merge(data1,data2,on='num') da...
import traceback import asyncio from nats.aio.client import Client as NATS #from nats.aio.errors import ErrConnectionClosed, ErrTimeout, ErrNoServers # python3 implementation of NATS python client async def nats(server, subject, msg, loop): """ NATS client implemented via asyncio python3 implementation, s...
def find_first_k_missing_positive(nums, k): missingNumbers = [] i = 0 while i < len(nums): j = nums[i] - 1 if j >= 0 and j < len(nums) and nums[j] != nums[i]: nums[i], nums[j] = nums[j], nums[i] else: i += 1 extraNumbers = set() for index, num in ...
class worldlist: #====================================================================================# #=================== Liste des mots auquel le bot réagit (Début) ====================# #====================================================================================# liste_Kaamelott = ['Kaamelott', 'k...
#!/usr/bin/python class Feature: def __init__(self,name,path,time,cost,label,location,box): self.name = name self.path = path self.time = time self.cost = cost self.label = label self.location = location self.box_location = box
from django.urls import path from .views import * urlpatterns = [ path('', OrderView.as_view(), name='order'), path('login/', LoginLogoutView.as_view(), name='login'), path('orders/', Order_List.as_view(), name='list'), path('detail/<int:pk>', Order_Detail.as_view(), name='detail'), path('detail/<in...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 30 11:10:49 2019 @author: jason @E-mail: jasoncoding13@gmail.com @Github: jasoncoding13 """ import matplotlib.pyplot as plt import numpy as np import os import pandas as pd from collections import Counter from sklearn.cluster import KMeans from skl...
# coding:utf-8 import cv2 as cv import os import sys __all__ = ['PictureUtil'] class PictureUtil(object): def __init__(self): pass @staticmethod def get_picture_part(image, coordinate): return image[coordinate['y1']: coordinate['y2'], coordinate['x1']: coordinate['x2']] @staticmeth...
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_bcrypt import Bcrypt from flask_login import LoginManager app = Flask(__name__) app.config['SECRET_KEY'] = 'secretkey' #Put A Better Secret Key app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///site.db' db = SQLAlchemy(app) bcrypt = Bcrypt(app)...
# encoding: UTF-8 from vnpy.trader import vtConstant from .oandaGateway import OandaGateway gatewayClass = OandaGateway gatewayName = 'OANDA' gatewayDisplayName = 'OANDA' gatewayType = vtConstant.GATEWAYTYPE_INTERNATIONAL gatewayQryEnabled = False
def start(): print("there are two doors ") print("select any door left or right") answer = input("<").lower() if "f" in answer: bear_room() elif "r" in answer: monster_room() else: game_over("don't you know how type!!") def bear_room(): print("your in b...
import os s = 'javac -cp ".:lucene-6.6.0/*" -g src/*.java -d bin/' os.system(s) test = "HW1-Test" for i in range(0, 30): testcase = i filetowrite = ['test.param', "my{1}-{0}.teIn".format(testcase, test)] with open(filetowrite[0], 'w') as f: f.write("indexPath=[indexpath]\n") f.write( ...
import tensorflow as tf import os import glob import numpy as np os.environ['CUDA_VISIBLE_DEVICES'] = '1' def make_single_dataset(image_size=[256, 128], tfrecords_path="./mars/mars_validation_00000-of-00001.tfrecord", shuffle_buffer_size=2000, repeat=True, train=True): """ Input: image_size: size of input imag...
#!/usr/bin/python for prj in [ 1,2,3,4,5,6,7]: print "drop database if exists net_stat_%02d; "%(prj) print "create database net_stat_%02d CHARACTER SET 'utf8' COLLATE 'utf8_general_ci'; "%(prj) print "use net_stat_%02d; "%(prj) for i in range(4): for j in range(10): if i in [0,1]: ...
#!/usr/bin/python3 #encoding=utf-8 import time import random import RPi.GPIO as GPIO class MyGPIO(): init_count = 0 mode = GPIO.BCM def __init__(self, idx, init_with_output, init_with_high=False): self.idx = idx if idx is None: return if MyGPIO.init_count == 0: ...
#AIM:Compute EMIs for a loan using the numpy or scipy libraries. import numpy as np # assume annual interest of 7.5% def calc_interest(interest ,years , loan_value ): annual_rate = interest/100.0 monthly_rate = annual_rate/12 number_month = years * 12 monthly_pay = abs(np.pmt(monthly_rate, number_month, loa...
#!/usr/bin/python # -*- coding: UTF-8 -*- # author: Carl time:2020/9/14 dic = { 'python': 95, 'java': 99, 'c': 100 } # 1.字典的长度是多少 # 2.请修改'java' 这个key对应的value值为98 # 3.删除 c 这个key ======>> 重点看看 # 4.增加一个key-value对,key值为 php, value是90 # 5.获取所有的key值,存储在列表里 # 6.获取所有的value值,存储在列表里 # 7.判断 javascript 是否在字典中...
r""" .. autofunction:: openpnm.models.phases.thermal_conductivity.water .. autofunction:: openpnm.models.phases.thermal_conductivity.chung .. autofunction:: openpnm.models.phases.thermal_conductivity.sato """ import scipy as sp def water(target, temperature='pore.temperature', salinity='pore.salinity'): r""" ...
from __future__ import absolute_import from __future__ import division, print_function, unicode_literals from sumy.parsers.plaintext import PlaintextParser from sumy.nlp.tokenizers import Tokenizer # from sumy.summarizers.lsa import LsaSummarizer as Summarizer # from sumy.summarizers.lex_rank import LexRankSummarizer a...
""" @author: shoo Wang @contact: wangsuoo@foxmail.com @file: demo02.py @time: 2020/5/6 0006 """ import requests as rq from bs4 import BeautifulSoup as Bs import pandas as pd import numpy as np # 获取数据,就是通过访问网页,把他的html源代码拿过来 def getData(resLoc): rp = rq.get(resLoc) rp.encoding = 'utf-8' return rp.text # 最...
# -*- coding: utf-8 -*- from django.contrib import admin from django import forms from nested_inline.admin import NestedStackedInline, NestedModelAdmin from .models import ProgramInterface, ProgramArgument, ProgramArgumentField, Program, ReferenceDescriptor, \ ProgramVersion from .utils import get_customer_availa...
# Generated by Django 2.0.7 on 2018-08-12 12:52 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('cowapp', '0004_delete_monthlyweatherbycity'), ] operations = [ migrations.AlterField( model_name='s...
from trawler.browsers.base import BrowserBase class BrowseStackOverFlow(BrowserBase): """ Does the browsing tasks on stackoverflow.com Usage: from trawler.browsers.stackoverflow import BrowseStackoverFlow stack = BrowseStackoverFlow(kw="invaana", max_page=1) stack.search() ...
import random import matplotlib.pyplot as plt def normal_initialization(population_size, val_range): population = [] for i in range(population_size): population.append(random.randint(val_range[0], val_range[1])) return population def special_initialization(population_size, val_range, segments): ...
def Fabs(a): if a<0: return -a else: return a def solve(listB, listG): res=0; cntb=0 while cntb<len(listB): cntg=0 while cntg<len(listG): if Fabs(listB[cntb]-listG[cntg])<=1: res+=1 listG[cntg]=10000 li...
__author__ = "Arnaud Girardin &Alexandre Laplante-Turpin& Antoine Delbast" import csv class Map: def __init__(self, path): self.map = [] self.startingPoint =[] self.numRow = 0 self.numCol = 0 self.generateMapFromFile(path) def generateMapFromFile(self, path): ...
#!/usr/bin/python import sys import socket import os def load_file(file): f=open(file,'r') out = f.read() return out def receive(client): output='' while True: msg=client.recv(2048).decode('utf-8') if(msg==None): break output += msg if(output[...
class Solution(object): def treeToDoublyList(self, root): if not root: return root first = None last = None def convert(node): nonlocal first, last if not node: return node convert(node.left) if last: ...
# Generated by Django 3.1.7 on 2021-04-03 07:36 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('college', '0004_auto_20210403_0212'), ] operations = [ migrations.RemoveField( model_name='depa...
from django.shortcuts import render from . import models # Create your views here. def articles_list(request): article = models.Article.objects.all().order_by('date') arg = {'art':article} return render(request,'articles/articleslist.html',arg)
import numpy as np import pandas as pd import pytest from tti_explorer import Case, Contacts from tti_explorer.scenario import get_monte_carlo_factors, run_scenario, STATS_KEYS, scale_results, results_table from tti_explorer.strategies import registry, RETURN_KEYS def test_get_monte_carlo_factors(): monte_carlo_...
import traceback from muddery.common.utils.singleton import Singleton from muddery.common.utils.password import hash_password, make_salt from muddery.worldeditor.settings import SETTINGS from muddery.server.database.worlddata_db import WorldDataDB from muddery.worldeditor.database.worldeditor_db import WorldEditorDB f...
# Copyright (c) 2009-2014 Stefan Marr <http://www.stefan-marr.de/> # # 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, cop...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Oct 28 15:03:04 2022 @author: Dartoon """ import numpy as np import astropy.io.fits as pyfits import matplotlib.pyplot as plt import glob import pickle import copy run_folder = 'stage3_all/' #!!! filt = 'F356W' files = glob.glob(run_folder+'fit_mate...
print("====Apuração de Votos - Melhor dia para Lives====") segunda = int(input("Insira os votos da Segunda-feira: ")) # variável dia terca = int(input("Insira os votos da Terça-feira: ")) # variável dia quarta = int(input("Insira os votos da Quarta-feira: ")) # variável dia quinta = int(input("Insira os votos da...
from abc import abstractmethod from contextlib import suppress from os import unlink from pathlib import Path from typing import Union from google.cloud import bigquery from google.cloud.bigquery.table import RowIterator, _EmptyRowIterator from pandas import DataFrame, read_feather class AbstractRepository: @abs...
import os from operator import itemgetter, attrgetter def month_to_second(month_str): if (month_str == "January"): return 1 if (month_str == "February"): return 2 if (month_str == 'March'): return 3 if (month_str == 'April'): return 4 if (month_str == 'May'): return 5 if (month_str == ...
def calculateTotalPrice(articlePrice: int, n=9): cgst_sgst = articlePrice * (n/100) totalPrice = articlePrice + cgst_sgst return totalPrice print(calculateTotalPrice(105))
#_*_coding:utf-8_*_ __author__ = 'Jorden Hai' from sqlalchemy import create_engine,Table from sqlalchemy.orm import sessionmaker from conf import settings # engine = create_engine(settings.DB_CONN) # engine = create_engine(settings.DB_CONN,echo=True) #创建与数据库的会话session class ,注意,这里返回给session的是个class,不是实例 SessionCls...
#!/usr/bin/env python #---------------------------------------------------------------------- # Description: # Author: Carsten Richter <carsten.richter@esrf.fr> # Created at: Sa 6. Mai 16:04:24 CEST 2017 # Computer: lid01gpu1. # System: Linux 3.16.0-4-amd64 on x86_64 #---------------------------------------------------...
from os import path def read_file(filename): file_path = path.join(path.dirname(__file__), filename) f_obj = open(file_path, "r") fie_content = f_obj.readlines() f_obj.close() return fie_content def get_str_digits(string): result = ''.join(char for char in string if char.isdigit()) retu...
#Programmers - 비밀지도 def solution(n, arr1, arr2): answer = [] a,b = [], [] for i in arr1: temp = str(bin(i).replace('0b','')) if len(temp) == n: a.append(temp) else: a.append('0'*(n-len(temp))+temp) for i in arr2: temp = str(bin(i).replace('0b','')...
import json import requests from pathlib import Path with open('api_key.json') as f: API_KEY = json.load(f)['API_KEY'] # Get 300 featured tracks r = requests.get('https://freemusicarchive.org/featured.json', data={'api_key': API_KEY}) tracks = r.json()['aTracks'] for track in tracks[:90]: fi...
from marsim import rescue_line rescue_line.init() robot = rescue_line.Robot() # robot = rescue_line.Robot(x=0.4, y=0.3, angle=0) robot.addSensor(0.01, 0.14) # add one sensor rescue_line.start() # run simulation (optional) while True: s1 = robot.readSensors("gray")[0] # get information from first sensor u = (s1 -...
from tkinter import END from tkinter.filedialog import * def decimalToRoman (self): self.root.title("Task 20") self.file = None string_textarea = self.textArea.get(1.0, END) self.textArea.delete(1.0, END) number = int(string_textarea) num = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, ...
from django.contrib import admin from models import * from django.contrib.contenttypes import generic class ImageInline(admin.StackedInline): model = SentenceImage class OrderImageInline(admin.TabularInline): model = OrderImage class OrderAdmin(admin.ModelAdmin): list_display = ('title', 'sta...
import os from load_model import load_model_depth import os import time import cv2 from my_utils import load_cv os.environ['TF_CPP_MIN_LOG_LEVEL'] = '10' from keras.models import load_model from layers import BilinearUpSampling2D from utils import predict, display_images import json import numpy as np depthModel =...
import sqlalchemy as sa import sqlparse import argparse def main(sql_file_name, connection_string, schema=None): engine = sa.create_engine(connection_string) connection = engine.connect() with open(sql_file_name) as f: sql_txt = f.read() sql_statements = sqlparse.split(sql_txt) ...
"""Pylint plugin for py.test""" from __future__ import unicode_literals from __future__ import absolute_import from os.path import exists, join, dirname from six.moves.configparser import ( # pylint: disable=import-error ConfigParser, NoSectionError, NoOptionError ) from pylint import lint from pylint.con...
import pyttsx3 import datetime import speech_recognition as sr import wikipedia import smtplib import webbrowser as wb import os import pyautogui import psutil import pyjokes from covid import Covid from quotes import Quotes import pywhatkit as kit en=pyttsx3.init() #en.say("hello this is Jarvis") vo...
import asyncio import logging import unittest from aioradius import RadiusService, RadiusAuthProtocol, RadiusAccountingProtocol, \ RadiusResponseError, \ packet __author__ = 'aruisnov' logging.basicConfig( level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) class Fa...
# -*- coding: utf-8 -*- """ Created on Wed Aug 24 19:22:30 2016 @author: colinh """ from sys import argv import json from stream.twitch_stream import * from stream.config.universal_config import * import socket, threading import logging import sys logging.basicConfig() class StreamServer: def __init__(self, c...
class SharedData: spam = 42 # 数据属性,在顶层,为所有实例共享 class MixedNames: data = 'spam' # 类对象的属性,在实例继承变量名的类中 def __init__(self, value): # self返回的是调用主题,也就是实例对象,一个类有多个实例对象 self.data = value # 在实例对象中 def display(self): print(self.data, MixedNames.data) # 这两个display是不一样的 if __name__...
import torch import argparse import os import torch import torch.optim import numpy as np import argparse from torch.utils import data from ssdn.network import NoiseNetwork from ssdn.Discriminator import DiscriminatorLinear from lossfunction_dual import * from datasets.DenoisingDatasets import BenchmarkTrain, SIDD_VA...
import FWCore.ParameterSet.Config as cms l1tGTTFileReader = cms.EDProducer('GTTFileReader', files = cms.vstring("gttOutput_0.txt"), #, "gttOutput_1.txt"), format = cms.untracked.string("APx") )
#C:\Users\mzy\Desktop\机器学习\data\train import tensorflow as tf import random import os def image_deals1(train_file): # 读取原始文件 image_string = tf.io.read_file(train_file) # 读取原始文件 image_decoded = tf.image.decode_png(image_string) # 解码JPEG图片 image_decoded=randoc(image_decoded) image_decoded=...
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-08-01 21:37 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('login', '0002_user_pokes'), ] operations = [ migrations.RemoveField( mod...
import numpy as np import pandas as pd data = pd.read_csv('austin_crime.csv', names = ["address","census_tract","clearance_date","clearance_status","council_district_code","description","district","latitude","location","location_description","longitude","primary_type","timestamp","unique_key","x_coordinate","y_coordina...
"""Core appconfig""" from django.apps import AppConfig class CoreConfig(AppConfig): name = 'core'
estados = {"roraima","acre","amapa","amazonas","para","rondonia","tocantins"} a = raw_input() if a in estados: print("Regiao Norte") else: print("Outra regiao")
import random import pygame from pygame.locals import * from sys import exit print("Welcome to your new house!") print("To open the door press the 0 key") print("To have the sun, press the 1 key") print("To close the door and make it night time, press the 2 key") print("To open the windows, press the 3 key") print("To...
import mpl_toolkits.mplot3d.axes3d as p3 import matplotlib.pyplot as plt from scipy.integrate import odeint import numpy as np from matplotlib import animation fig = plt.figure() ax = p3.Axes3D(fig) N = 200 t = np.linspace(0, 10, N) def diff_func(s, t): x, v_x, y, v_y, z, v_z = s ml = 3 * g * z...
from flask import json from snakeeyes.blueprints.User.model import Employee from lib.tests import assert_result_is_dictionary DUMMY_ID = 1000 class TestModel(): def test_getall(self,client): result = Employee.getall() assert_result_is_dictionary(result,dict) def test_gettree(self,client): ...
# multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to http://ai.berkeley.e...
from django.db import models from musica.settings import MEDIA_ROOT from django.contrib.auth.models import User class perfil(models.Model): def get_ruta(self,filename): ruta_completa = "%s%s" %(MEDIA_ROOT,user.username) return ruta_completa user = models.OneToOneField(User,null=False,blank=False) foto = mode...
import gzip import json import re fname = "jawiki-country.json.gz" def get_UK_article(): with gzip.open(fname, "rt") as jsonfile: for line in jsonfile: line_json = json.loads(line) if line_json["title"] == "イギリス": return line_json["text"] raise ValueError("Not ...
import db, import_file PayrollRecord = import_file.import_file('PayrollRecord') def getPayrollRecords(): res = db.List("PayrollRecord") PayrollRecordList = [] for row in res: if row is not None: PayrollRecord = PayrollRecord.PayrollRecord( int(row[0]), int(row[1]), int(row[2]), int(row[3]), int(row[4])...
#!/usr/bin/env python # Requires urllib: pip3 install urllib3 from http.server import BaseHTTPRequestHandler, HTTPServer import requests # HTTPRequestHandler class class testHTTPServer_RequestHandler(BaseHTTPRequestHandler): def do_POST(self): length = int(self.headers['Content-Length']) print(se...
from prac_07.date import Date def main(): print("Current Date: ") date = Date(20, 9, 2017) print(str(date)) number_of_days = int(input("Enter the number of days you wish to add: ")) print("In {} days the date will be".format(number_of_days)) date.add_days(number_of_days) print(str(date)) m...
from lxml import etree import os from os.path import join path = 'Real_Masters_all' callnumbers = {} filecount = 0 for filename in os.listdir(path): filecount += 1 eachfile = 0 for filename in os.listdir(path): eachfile += 1 tree = etree.parse(join(path, filename)) callnumber = tree.xpath('//archdes...
def main(): # problem1() # problem2() def problem1(): nameList= [] userInput = "" while userInput.lower() != "quit": nameList.append(userInput) userInput = input("What are your favorite Pokeman? If you dont like Pokeman or just dont have anymore enter 'quit\n'") print(nameLis...
from utils import * from function2 import * from function3 import * def reduce_puzzle(values): """ Iterate eliminate() and only_choice(). If at some point, there is a box with no available values, return False. If the sudoku is solved, return the sudoku. If after an iteration of both functions, the sud...
from .litmus_database import Litmus from .color_space import CVC def search_main(word): search = {} if len(word) > 2: # 2글자 이하는 검색에서 제외 symbol = word[0] tag = word[1:] if symbol == '#': if is_hexa(tag): # 헥사코드인지 확인 - #시작 16진 7 숫자 (#FFFFFF) or 16진 6 숫자 (FFFFFF) ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 通过关键字搜索 rarbg.is 发布的资源,并获取第一个搜索结果的磁力链接, 再打开 Mac 上的 Transmission 添加到下载列表中。 如果没有搜索结果,一段时间后再请求搜索,直到添加下载后退出执行。 如果需要验证浏览器,获取新的Cookies再请求 """ __author__ = 'LGX95' import logging import os import random import re import subprocess import time import urllib.parse from date...
""" Code shared by LocalCKAN, RemoteCKAN and TestCKAN """ import json from ckanapi.errors import (CKANAPIError, NotAuthorized, NotFound, ValidationError, SearchQueryError, SearchError, SearchIndexError, ServerIncompatibleError) class ActionShortcut(object): """ ActionShortcut(foo).bar(baz=2) <=> foo....