text
stringlengths
8
6.05M
#!/usr/bin/env python3 import sys nums = {} highest = 0 for line in sys.stdin: parts = line.strip().split() source = int(parts[0]) targets = {int(v) for v in parts[2:]} nums[source] = targets if source > highest: highest = source counts = {0: 0} dists = {0: 0} for i in range(101, highest ...
import pygame NEGRO=[0,0,0] VERDE=[0,255,0] ROJO=[255,0,0] AZUL=[0,0,255] BLANCO = [255,255,255] def escalamiento(ptoPvte,puntos,tamanoEscala): x=0 y=0 puntosFinal = [] for value in puntos: x=value[0]-ptoPvte[0] x=x*tamanoEscala x=x+ptoPvte[0] y=value[1]-ptoPvte[1] ...
"""Treadmill docker runtime.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from .runtime import DockerRuntime __all__ = [ 'DockerRuntime' ]
# Author: Christian Brodbeck <christianbrodbeck@nyu.edu> from _eeg_systems import predefined_connectivity
import os import click from pprint import pprint import logging from treadmill.infra import constants, connection, vpc, subnet from treadmill.infra.setup import ipa, ldap, node, cell from treadmill.infra.utils import mutually_exclusive_option, cli_callbacks from treadmill.infra.utils import security_group from treadmi...
from django.core.management.commands.runserver import BaseRunserverCommand class Command(BaseRunserverCommand): help = "Starts a lightweight Web server for development without automatically serving static files."
__author__ = 'Hanzhiyun' print(3+7) print(type(3+7)) print(2-1) print("this is a chunk of text") print(type("this is a chunk of text"))
class Solution(object): def firstBadVersion(self, n): """ https://leetcode.com/problems/first-bad-version/ isBadVersion is already given. just needed to binary search to find the solution. """ low = 1 high = n if isBadVersion(1): ...
from src.util.Logging import info from src.layout.PlannedGraph import PlannedGraph import src.plan.GraphUtils as GraphUtils import networkx as nx from difflib import SequenceMatcher from collections import OrderedDict import random def LCS(str1, str2): seqMatch = SequenceMatcher(None, str1, str2) match = seqM...
# coding=utf-8 user = raw_input('Enter login name:') # Enter login name:root print 'Your login is:', user print 3 ** 2 pystr = 'python' import sys print pystr[1:] aList = [1, 2, 3, 4] print aList print aList[2:], if 2 <= 4: print 'this is using if' counter = 0 while counter < 3: print 'loop#%d' % (coun...
## ## connect the object detections in multiple video frames ## obtained by a pretrained object detector ## ## Author: Abhishek Dutta <adutta@robots.ox.ac.uk> ## Date: 10 Dec. 2018 ## import threading import os import csv import json # for debug import cv2 import numpy as np import math import urllib.request #...
from mongoengine import * from flask_mongoengine import MongoEngine db = MongoEngine() class OneImage(db.EmbeddedDocument): element = db.ImageField(thumbnail_size=(100, 100, True)) def get_el(self): return self.element.name class UserV(db.Document): second_name = db.StringField(required=True, ...
# Flask from flask import Flask, redirect, url_for, request, render_template, Response, jsonify, redirect from model1 import imgg, pimgg import base64 import json import time # Declare a flask app app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': img = reque...
# -*- coding: utf-8 -*- class Solution: def capitalizeTitle(self, title: str) -> str: return " ".join( word.capitalize() if len(word) > 2 else word.lower() for word in title.split() ) if __name__ == "__main__": solution = Solution() assert "Capitalize The Title" ...
from django.shortcuts import render, redirect # the index function is called when root is visited # CONTROLLER!! def index(request): print ("*" * 100 ) return render(request, "vinmyMVC/index.html") # response = "Hello, I am your first request!" # return HttpResponse(response) def show(re...
import os from typing import Dict from be.model import table from be.model import tuple from be.model import user import sqlite3 as sqlite class Store: tables: Dict[str, table.Table] database: str def __init__(self): self.database = "be.db" self.tables = dict() self.create("User")...
#NumPy intro import os """ NumPy is a pythin library for woriking with arrays it stands for numerical python It used as lists are slow to use pretty much so this is faster an array object is created called an ndarray To start you need to install numpy if you dont have in the cmd linw call pip install numpy """ "T...
# -*- python -*- # Assignment: Find Characters # Write a program that: # Takes: # - a list of strings # - a string containing a single character # Produces: # - prints a new list of all the strings containing that character. # Here's an example: # input l1 = ['hello','world','my','name','is','Anna'] c...
from celery import shared_task from lxml import etree as et import requests from .models import CurrencyMap from django.core.exceptions import FieldDoesNotExist CURRENCY_STORAGE_URL = "https://www.cbr-xml-daily.ru/daily.xml" @shared_task def sample_task(): print("The sample task just ran.") @shared_task def up...
from django.shortcuts import render from rest_framework import viewsets,generics from rest_framework.response import Response from .models import Head_content from .serializers import HeadContentSerializer # Create your views here. class HeadTabarViewSet(viewsets.ViewSet): def list(self, request): quer...
import roomba import time init_serial() start_data() stop() end_data() set_mode(0)
# coding=utf-8 """ 最长不含重复字符的子字符串 请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。假设字符串中只包含从’a’到’z’的字符。例如,在字符串中”arabcacfr”,最长非重复子字符串为”acfr”,长度为4。 """ class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ last_appear_dict = {} max_leng...
from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import json import smtplib from tornado.template import Loader, os from logging import Logger from core import Data class MailPublisher(object): def __init__(self, logger, db, config_path): """ @type db: Data ...
# Copyright (c) 2021 kamyu. All rights reserved. # # Google Code Jam 2021 Qualification Round - Problem E. Cheating Detection # https://codingcompetitions.withgoogle.com/codejam/round/000000000043580a/00000000006d1155 # # Time: O(S * Q + SlogS + QlogQ) # Space: O(S + Q) # # Difference with neighbors in easiest and har...
c=input() a=c//2 print(a)
# -*- coding: utf-8 -*- """ Created on Mon Jan 04 12:21:33 2016 An implementation of Sequential T-test Analysis of Regime Shifts as described in the paper: "A sequential algorithm for testing climate regime shifts" S.N. Rodionov Geophys. Rev. Ltrs. V31 N9 May 2004 @author: kristencutler """ impo...
# add = lambda x, y : x + y def double(x): return x * 2 sequence = [1, 3, 5, 9] doubled = [double(x) for x in sequence] doubled = map(double, sequence) doubled = list(map(lambda x: x * 2, sequence)) print(doubled)
# Generated by Django 3.1.6 on 2021-02-08 04:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main_app', '0012_auto_20210208_0405'), ] operations = [ migrations.AlterField( model_name='profile', name='photo', ...
from db import db class TutorModel(db.Model): __tablename__ = "tutors" id = db.Column(db.Integer, primary_key=True) #unique full name name = db.Column(db.String(32)) first_name = db.Column(db.String(32)) last_name = db.Column(db.String(32)) email = db.Column(db.String(32)) subject = db...
import logging import os import json import uuid from datetime import datetime from shapely.geometry.point import Point from shapely.wkt import loads import pandas as pd import numpy as np from geopy.distance import vincenty # redis from redis_client import RedisClient import pickle from vibebot import EventBot fro...
# class Coordinates(object): # def __init__(self, x, y): # self.x = x # self.y = y # def __str__(self, x, y): # return '<' + str(self.x) + '+' + str(self.y) + '>' # point1 = Coordinates(5,5) # point2 = Coordinates(6,6) # origin = Coordinates(0,0) # print(origin) class Dog...
#!/usr/bin/python # This is used as a setup for servers! from distutils.core import setup import socket setup(name='pykonverse', description='chat client/server', author='nulltf, originally created by russjr08', author_email='jayitinc@jayitstudios.com', url='jayitstudios.com', ) class default: port = 1337 hos...
def add_to_dict(name, bid,): auction_dict[name] = bid auction_finished = 0 auction_dict = {} while auction_finished == False: print("Welcome to the secret auction program\n") name_input = input('What is your name? ').lower() bid_input = input('What is your bid? $') decision_input = input('Are ther...
# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import json from pants.backend.terraform.goals.deploy import DeployTerraformFieldSet from pants.backend.terraform.testutil import rule_runner_with_auto_...
__author__ = "Narwhale" def loop_merge_sort(l1, l2): temp = [] while len(l1) > 0 and len(l2) > 0: if l1[0] < l2[0]: temp.append(l1.pop(0)) else: temp.append(l2.pop(0)) temp.extend(l1) temp.extend(l2) return temp l1 = [1,3,5,7,9] l2 = [2,4,6,8,10,14,15,78] ...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns class KinematicsDataAdjuster: def __init__(self, data_frame): self.data_frame = data_frame def column_adjuster(self, keep_cols, new_column_names): self.data_frame = self.data_frame[keep_cols] ...
# A high-level class for easily conducting # convergence scans. ################################################## import numpy as np from . import DREAMIO from . import runiface from DREAM.DREAMSettings import DREAMSettings from DREAM.DREAMOutput import DREAMOutput class ConvergenceScan: def __init__(self, s...
from keras.preprocessing.image import ImageDataGenerator import keras.applications as keras_applications import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np from sklearn.metrics import classification_report, confusion_matrix import pandas as pd import sys from timeit import defau...
from db import db class PlanetImage(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) img_ref = db.Column(db.String, nullable=False) description = db.Column(db.String, nullable=True) task_id = db.Column(db.BigInteger, db.ForeignKey('task.id'), nullable=True) task = db.re...
import time from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Chrome() # 隐式等待10s driver.implicitly_wait(10) # 服务大厅地址 url = "https://ehall.jlu.edu.cn/jlu_portal/index" driver.get(url) # 登录 driver.find_element_by_id("username").send_keys("用户名") driver.fin...
def newfile(): fout = open('running-config.cfg') fin = open('newconfigfile.cfg','w+') l = [] l1 = [] book = fout.read() line = book.split() for i in range(len(line)): if '192.' in line[i]: line[i] = line[i].replace('192.','10.') if '172.' in line[i]: line[i] = line[i].replace('172.','10.') if '255...
import sys from decimal import * getcontext().prec = 25 def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) class Queue: def __init__(self): self.l = [] def put(self, n): if (n == 0): return self for i in range(0, len(self.l)): if self.l[i]...
from . import models from . import controllers from . import wizard from odoo import api, fields, SUPERUSER_ID def add_book_hook(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) book_data1 = { 'name': 'Java Course', 'pages': 98, 'date_release': fields.Date.today() } ...
#! /usr/bin/env python #coding:utf-8 import sys import os import re import urllib2 import urllib import requests import cookielib import getpass import json from bs4 import BeautifulSoup import socket socket.setdefaulttimeout(100.0) ## 这段代码是用于解决中文报错的问题 reload(sys) sys.setdefaultencoding("utf8") ##########...
from sklearn import preprocessing from clustering import * import pandas as pd import numpy as np import cPickle as pickle def get_ratings(df): n_labels = len(df.label.unique()) athlete_ids = np.array(sorted(df.athlete_id.unique())) n_athletes = len(athlete_ids) ath_labels = df.groupby(['athlete_id', '...
#----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from __future__ import print_function, absolute_import import os from IPython.nbconvert.preprocessors.base import Preprocessor #---------------------...
from django.views.generic import TemplateView class IndexView(TemplateView): template_name = "index.html" def get_context_data(self): ctxt = super().get_context_data() ctxt["username"] = "phuoclv" return ctxt class AboutView(TemplateView): template_name = "about.html" ...
import scrapy import datetime import re class ShoesSpider(scrapy.Spider): name = 'Shoes' allowed_domains = ['www.wildberries.ru'] start_urls = ['http://www.wildberries.ru'] pages_count = 6 cookie = {'__region': '64_75_4_38_30_33_70_1_22_31_66_40_71_69_80_48_68', '__store': '11926...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for `eust` package.""" import pytest from click.testing import CliRunner import tempfile import shutil import eust from eust import cli @pytest.fixture def temp_repo(request): temp_dir = tempfile.mkdtemp() def fin(): shutil.rmtree(temp_dir) ...
import numpy as np from sklearn.cross_validation import LeaveOneOut, KFold X = np.array([[0., 0.], [1., 1.], [-1., -1.], [2., 2.]]) Y = np.array([0, 1, 0, 1]) loo = LeaveOneOut(len(Y)) print "Leave-One-Out indices" for train, test in loo: print("%s %s" % (train, test)) kf = KFold(len(Y), n_folds=2) print "Kfold i...
############################################################################### # В інтервалі від 1 до 10 визначити числа # • парні, які діляться на 2, # • непарні, які діляться на 3, # • числа, які не діляться на 2 та 3. for x in range(1,11): if x % 2 == 0: print(f"{x} ділиться націло на 2") if x...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from .ligne import Ligne L211_loyer_brut = Ligne(211, "loyer brut") L221_frais_administration = Ligne(221, "frais d'administration") L222_autre_frais_gestion = Ligne(222, "autre frais de gestion") L223_prime_assurance = Ligne(223, "Prime d'assurance") L224_tra...
from __future__ import print_function import sys from os.path import join as oj import torch import torch.nn as nn import torch.optim as optim # pytorch stuff import torch.utils.data as data import torchvision.models as tv_models from torch.autograd import Variable # set up data sys.path.insert(1, oj(sys.path[0], '....
# -*- coding: utf-8 -*- cin=input().strip().split(' ') m,n,s=map(int,cin) user={} cnt=0 for i in range(m): cin=input().strip() if i >= s-1: if cnt%n ==0: if cin not in user: print(cin) user[cin]=cin else: cnt-=1 cnt += 1 if...
with open("day7input.txt", "r") as f: input_data = f.read() progdict = {} for line in input_data.split("\n"): print(line) arrow = line.find('>') if arrow > 0: children = line[arrow+2:].split(', ') print(children) parent = line[:arrow-2].split()[0] if parent not in progdict: progdict[parent] = N...
class AStarPlanner(object): def __init__(self, planning_env, visualize): self.planning_env = planning_env self.visualize = visualize self.nodes = dict() def Plan(self, start_config, goal_config): plan = [] # TODO: Here you will implement the AStar planne...
# huff_functions.py # Contains functions for building huffman trees import heapq as hq import bitstring as bs # Build forest of nodes of form (frequency, index, left child, right child) def build_forest(freqs): forest = [] for node in freqs: hq.heappush(forest, ((freqs[node],node,None,None))) retu...
from lib.multi import Threader from lib.auth import * import lib.execption as err import lib.action as YT import lib.cli as cli import threading import signal cli.banner() action = cli.ask_action() threader = Threader(cli.ask_threads()) # accounts_path = cli.ask_accounts_file() accounts_path = 'examples/...
from setuptools import setup from setuptools import find_packages requires = [ 'pyramid', 'asgiref', 'uvicorn[watchgodreload]', 'watchdog', 'pyramid_mako', 'zope.interface', 'zope.sqlalchemy', 'zope.deprecation', 'SQLAlchemy', 'transaction', 'filelock', 'importlib-metad...
# coding: utf-8 import itchat from itchat.content import TEXT from yabot.monitors.ya import YaMonitor from yabot.monitors.vote import VoteMonitor class WechatBot(object): def __init__(self): self.chatroom_uin_monitors = {} self.member_uin_monitors = {} @classmethod def init(cls): ...
#!/usr/bin/python ans = 1 for _ in range(7830457): ans *= 2 ans %= 10000000000 ans *= 28433 ans %= 10000000000 ans += 1 print(ans)
a=[1,2,3] b=[4,5,6] print(a+b)
import torch import torch.nn as nn class PropConv(nn.Module): def __init__(self, in_features, out_features=1, K=10, bias=False): super().__init__() assert out_features == 1, "'out_features' must be 1" self.in_features = in...
from spack import * import sys,os sys.path.append(os.path.join(os.path.dirname(__file__), '../../common')) from scrampackage import write_scram_toolfile class HeppdtToolfile(Package): url = 'file://' + os.path.dirname(__file__) + '/../../common/junk.xml' version('1.0', '68841b7dcbd130afd7d236afe8fd5b949f0176...
# pi-funcs.py # File containing useful functions # function to remap one range to another def remap(value, fromLow, fromHigh, toLow, toHigh): # get how wide each range is fromRange = fromHigh - fromLow toRange = toHigh - toLow # convert low range into a 0-1 range valueNew = flo...
import sys import math def stripped_lines(filename): with open(filename) as f: for line in f.readlines(): yield line.strip() def parse_file(filename): lines = [line for line in stripped_lines(filename)] available_time = int(lines[0]) buses = [None if bus == 'x' else int(bus) for ...
#!/usr/bin/env python3 # if user.get('user_id') and user.get('is_superuser'): # -*- coding: utf-8 -*- __version__ = '1.0.1' create_traceable_object_type_element_query = """ INSERT INTO public.traceable_object_type AS tobt (name, active, deleted) VALUES ($1, $2, FALSE) RETURNING *; """
import pygame class Wallnut(pygame.sprite.Sprite): def __init__(self): super(Wallnut, self).__init__() self.image = pygame.image.load('resources/images/wall_nut/WallNut_00.png').convert_alpha() self.images = [pygame.image.load('resources/images/wall_nut/WallNut_{:02d}.png'.format(i)).conve...
from .getTRMM_PF import getTRMM_PF from .getGPM_PF import getGPM_PF
# KVM-based Discoverable Cloudlet (KD-Cloudlet) # Copyright (c) 2015 Carnegie Mellon University. # All Rights Reserved. # # THIS SOFTWARE IS PROVIDED "AS IS," WITH NO WARRANTIES WHATSOEVER. CARNEGIE MELLON UNIVERSITY EXPRESSLY DISCLAIMS TO THE FULLEST EXTENT PERMITTEDBY LAW ALL EXPRESS, IMPLIED, AND STATUTORY WARRANTIE...
#!/usr/bin/env python """ from Foundation import * from ScriptingBridge import * word = SBApplication.applicationWithBundleIdentifier_('com.microsoft.word') #word.activate() #the_count = word.__getattribute__('recentFiles') #the_count = word.countNumberedItems_numberType_level_('recentFiles', 1, 1) print the_count #...
import sys import copy from .utils import con_dimension, cursor class ConsoleDriver: def __init__(self, **kwargs): self.specialCharacterMode = kwargs.get('specialCharacterMode', False) self.ignoreOverflow = kwargs.get('ignoreOverflow', False) self.historyLength = kwargs.get('historyLength', 10) sel...
import numpy as np import matplotlib.pylab as plt from mpl_toolkits.mplot3d import Axes3D def _numerical_gradient_no_batch(f, x): h = 1e-4 # 0.0001 grad = np.zeros_like(x) for idx in range(x.size): tmp_val = x[idx] x[idx] = float(tmp_val) + h fxh1 = f(x) # f(x+h) ...
from urllib.request import Request, urlopen from bs4 import BeautifulSoup import math ''' REQUIREMENTS: python3 urllib.request bs4 math AUTHOR: Javo ''' target = "https://example.com" max_groups = 200 members_per_page = 10000 user_agent = "Mozilla/5.0 (X11; U; Linux i686) Gecko/...
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import logging import sys from dataclasses import dataclass from pants.base.exiter import PANTS_FAILED_EXIT_CODE, PANTS_SUCCEEDED_EXIT_CODE, ExitCode f...
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^register/$', views.UserFormView.as_view(), name='register'), url(r'^login/$', views. login_view, name='login'), url(r'^logout/$', views.logout_view, name='logout'), url(r'^eintraege/$', ...
import sqlite3 import unittest import final_proj_4_14 as proj class TestTables(unittest.TestCase): def testRestaurant(self): try: conn = sqlite3.connect('food_event.db') cur = conn.cursor() except Error as e: print(e) sql1 = ''' SELECT COUNT(*),...
#!/usr/bin/env python # coding: utf-8 # ### Welcome to Hiro's Calculator # # This calculator will contain simple function for mathematical operations # In[4]: from sklearn.base import BaseEstimator import sklearn.metrics import numpy as np import sklearn.metrics from sklearn.datasets import fetch_openml class Dum...
"""This module contains simple helper functions """ from __future__ import print_function import torch import numpy as np from PIL import Image import os from matplotlib.colors import hsv_to_rgb from torchvision import transforms def resize_flow(flow, new_shape): _, _, h, w = flow.shape new_h, new_w = new_sha...
import requests from time import sleep import datetime import hashlib import hmac import json import requests API_HOST = 'https://api.bitkub.com' API_KEY = '8a0b8f4649d9c8c4858181ee286c6714' API_SECRET = b'c4e815924288b34c32d942a4cb29a624' mycoins = ['THB_ADA'] def checkPrice(): response = requests.get(API_HOST + '...
from flask import Flask, render_template from flask_wtf import FlaskForm from wtforms import StringField, Form, BooleanField, PasswordField, validators from wtforms.validators import DataRequired app = Flask(__name__) @app.route('/') def index(): return render_template("index.html") @app.route('/login') ...
# Generated by Django 2.1.7 on 2019-04-20 11:11 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('amazon', '0012_auto_20190420_1634'), ] operations = [ migrations.DeleteModel( name='accessories', ), migrations.DeleteMo...
from selenium import webdriver import unittest import json class APITest(unittest.TestCase): def setUp(self): self.browser = webdriver.Firefox() def tearDown(self): self.browser.quit() def is_correct_json(self, string): """ Check if the string is a well formed json ...
import os import pickle import numpy as np from keras import callbacks from keras import optimizers from keras import regularizers from keras.utils import np_utils from keras import layers from keras import models from keras.preprocessing.image import ImageDataGenerator from keras.callbacks import LearningRateScheduler...
import logging from os import path from utils import send_mail, setup_logging from uploaders import UploaderFuse, UploaderScp, UploaderSshFs from backuper import Backuper from filedeleter import filedeleter import configparser def worker(backuper, configuration, uploader=None): lines_start = 0 message = "" ...
# -*- coding: utf-8 -*- """ Author: Yili Yu Date: December 7 2015 Description: this module contains unit-testing for test_grades and data_setup functions """ import unittest from unittest import TestCase from hw10functions import * class CommandTest(TestCase): def test_data_setup(self): data = da...
#!/usr/bin/python3 def somme(n): S=0 sgn=-1 for k in range(1,n+1): S+=sgn/(k*k) sgn=-sgn return(S) def produit(n): P=1 for k in range(1,n): P=P*((k-n)/(k+n)) return(P) def maxi_c(L): x=L[0] y=L[1] maxi=abs(x-y) for i in range(2,len(L)): x=y ...
# -*- coding: utf-8 -*- from app.models import Poll from app.notifications import notify_via_email, Events from app.utils import session, http from web import config import web class View: @session.login_required def GET(self, poll_id): # Loads the poll poll = Poll....
# views.py import imdb from django.contrib.auth import logout from django.shortcuts import render,redirect from django.http import HttpResponse, HttpResponseRedirect from .models import MoviesToWatch, Movie from .wp_model import get_recommendation, get_details, searchMovie, genreSearch # Create your views here. def i...
#!/usr/bin/env python """ VolumeShaders.py: This module provides a python wrapper for the GLSL Volume Raycasting shader as well as an an interface object for initializing and modifying uniform values on the fly. """ __author__ = "John McDermott" __email__ = "JFMcDermott428@gmail.com" __version__ = "1....
import sys from time import sleep import pygame from bullet import Bullet from ku import Ku def check_keydown_events(event, ai_settings, screen, cha, bullets, stats): """Respond to key presses.""" if event.key == pygame.K_RIGHT: cha.moving_right = True elif event.key == pygame.K_LEFT: cha.m...
""" This file is part of the private API. Please do not refer to any variables defined here directly as they will be removed on future versions without warning. """ # This will eventually be replaced with a call at torchvision.datasets.info("imagenet").categories _IMAGENET_CATEGORIES = [ "tench", "goldfish", ...
import sys import string # swaps freq and word so that we have (word freq) f = open("C:/Users/Daway Chou-Ren/Documents/REU/linguistics/all.num.txt", 'r') output = open("C:/Users/Daway Chou-Ren/Documents/REU/linguistics/all_num_swapped.txt", 'w') sum_freqs = 0; for line in f.readlines(): line = line.lowe...
import os import sys root = os.path.dirname(__file__) sys.path.insert(0, os.path.join(root, 'site-packages')) os.environ.setdefault("DJANGO_SETTINGS_MODULE" , "iexam.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() def app(environ, start_response): status = '200 ...
from datetime import datetime,date,timedelta import statistics import networkx as nx from itertools import combinations from feature_tools import get_statistical_results_of_list import pickle def get_average_age_difference_in_retweets(tweets): my_age = datetime.strptime(tweets[0]['user']['created_at'],'%a %b %d %H...
import os import math import csv def gen_curve(filename: str): with open(filename, 'w', newline='') as fs: writer = csv.writer(fs) for i in range(630): x = i / 100.0 writer.writerow([x, math.cos(x), math.sin(x)]) def gen_state(filename: str): with open(filename, 'w', ...
# -*- coding: utf-8 -*- import os import shutil from tqdm import tqdm from PIL import Image import numpy as np import re import hashlib import piexif MAX_NUM_IMAGES_PER_CLASS = 2 ** 27 - 1 def move_fungi(old_dir, new_dir, validation_percentage, testing_percentage): if not os.path.exists(new_dir): os.mk...
#!/usr/bin/env python # -*- coding:utf-8 -*- """ 通过使用浏览器的“审查元素”功能,其中的 network 可以查看网页在请求数据时发送和接收了哪些数据 GET:从服务器请求获取数据 POST:向指定服务器提交被处理的数据 """ import urllib.request import urllib.parse import json # url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule' url = 'http://fanyi.youdao.com/translate?sma...
from graphviz import Digraph from hashlib import md5 def dictToGraph(j, echo=True, coFilter=[]): """ A quick and dirty function to convert JSON into a Digraph. """ g = Digraph(format='png') g.graph_attr['rankdir'] = 'LR' for clusteroperator in j.get('items'): coname = clusteroperator['m...
# Dom Parise - 4/13/14 # participant model # import math,time from random import random from datetime import datetime,timedelta,date from threading import Timer,Thread from database import Database from textmessenger import TextMessenger # -ln(RND)/p hours def poisson(p): return -( math.log(random()) / p ) db = ...