text stringlengths 8 6.05M |
|---|
from selene import browser
def password_recovery():
browser.open_url('https://pf-client-api.partnerearning.com')
browser.element('a.nav-general__login-link:nth-child(1)').click()
browser.element('.popup-authorization__forgot-link').click()
browser.element('.popup-block__form > div:nth-child(1) > input:... |
import pygame
pygame.init()
pygame.mixer.music.load('04. Djimetta - Tudo Ou Nada (feat. Bander).mp3')
pygame.mixer.music.play()
pygame.event.wait() |
import json
from collections import namedtuple
class Serializer(object):
def to_json(self):
return json.dumps(self, default=lambda o: o.__dict__,
sort_keys=True, indent=4)
@staticmethod
def from_json(json_data):
return json.loads(json_data, object_hook=Serializer... |
from heapq import *
n, k = map(int, input().strip().split(' '))
h = list(map(int, input().strip().split(' ')))
heapify(h)
ans = 0
while len(h) >= 2 and h[0] < k:
least = heappop(h)
heappushpop(h, least + (h[0] * 2))
ans += 1
if h[0] < k:
print(-1)
else:
print(ans) |
from enum import Enum
class DateMode(Enum):
DAILY = 'B'
WEEKLY = 'W'
MONTHLY = 'BM'
YEARLY = 'BY'
|
import pyodbc
import json
import os
from flask import Flask
from flask import request
from flask import make_response
from urllib.request import urlopen
app = Flask(__name__)
class Menu:
def __init__(self):
self.urlMenu = "https://www.mealgaadi.in/Meal_API/products_api.php?query=product_category... |
import sys
import platform
from selenium import webdriver
from tests.test_login import LoginTest
from tests.test_adding_new_employees import AddingNewEmployeesTest
from tests.test_clock_in import ClockInClockOutTest
from modules.logs_module import WriteLogs
default_parameters = {'base_url': ['', None],
... |
#!/usr/bin/env python3
deck = [4]*9
deck.append(16)
sd = sum(deck)
p = [x/sd for x in deck]
# Dealer hits soft 17
hit_soft_17 = True
def dealer_p(total, ace, cards):
outcomes = [0.0]*22
if (total > 21):
# Dealer busts
outcomes[0] = 1.0
elif (total >= 17):
... |
#! /usr/bin/env python
import argparse
import os
import re
def parse_args():
parser = argparse.ArgumentParser(description="Submit c3i one-off job(s)")
parser.add_argument(
"feedstocks",
nargs="+",
help="Feedstock(s) to submit as a one-off job(s)")
parser.add_argument(
"--p... |
class seq():
seqarr = ""
def isValidLetter(self, ch):
return(ch.isalpha())
def __init__(self, seqarr):
for ch in seqarr:
if( not (self.isValidLetter(ch))):
raise ValueError("illegal argument")
else:
self.seqarr = seqarr
def seqLength(self):
return len(seqarr)
def getSeq(self):
return seqar... |
import os
from reorg import cli
def test_whats_dir_target(monkeypatch):
monkeypatch.setenv("PWD", "/foo")
assert "/foo/reorged" == cli.whats_dir_target(None)
assert "/bar/reorged" == cli.whats_dir_target("/bar")
def test_prepare_dir_target(tmpdir):
target_dir = cli.whats_dir_target(str(tmpdir))
p... |
import os.path
import math
from os import path
allNames =[
"lizard",
"shiftHappens",
"erato",
"cubes",
"sponza",
"daviaRock",
"rungholt",
"breakfast",
"sanMiguel",
"amazonLumberyardInterior",
"amazonLumberyardExterior",
"amazonLumberyardCombinedExterior",
"gallery",
]
# 0 = lizard
# 1 = shift happens
# 2 ... |
from discord.ext import commands
import discord
import random
import datetime
import cogs._json
import cogs._utils
class Events(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_member_join(self, member):
try:
if self.bot.muted_users[m... |
import torch
import ocnn
bn_momentum, bn_eps = 0.01, 0.001
class OctreeConvBnRelu(torch.nn.Module):
def __init__(self, depth, channel_in, channel_out, kernel_size=[3], stride=1):
super(OctreeConvBnRelu, self).__init__()
self.conv = ocnn.OctreeConv(depth, channel_in, channel_out, kernel_size, stride)
se... |
"""
TICCLAT testing helper functions.
"""
from pathlib import Path
from itertools import chain
import nltk.data
from nltk import word_tokenize
import pandas
def load_test_db_data(dbsession):
"""
Insert mock data into database.
"""
files = (Path(__file__).parent / 'db_data').glob('./*.tsv')
dbse... |
import threading
import time
import random
import sys
import socket
rsListenPort = sys.argv[1]
rsListenPort = int(rsListenPort)
#djdjdjd
def sendData(value,sock):
sock.send(value.encode('utf-8'))
def file_to_dict(fileName):
f = open(fileName, "r")
lst = []
dic = {}
for line in f:
fo... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from openravepy import *
env = Environment() # create openrave environment
env.SetViewer('qtcoin') # attach viewer (optional)
env.Load('data/lab1.env.xml') # load a simple scene
robot = env.GetRobots()[0] # get the first robot
with env: # lock the environment since robot will ... |
import torch
import math
import torch.nn as nn
import torch.nn.functional as F
class SFIModel_gating(nn.Module):
def __init__(self,hparams,vocab):
super().__init__()
self.name = hparams['name']
self.cdd_size = (hparams['npratio'] + 1) if hparams['npratio'] > 0 else 1
self.batch_siz... |
#!/usr/lib/python
# NYUAD SVM Project Preprocessor
# AI - Fall 2013
# Written by Lingliang Zhang
# A very simple Python preprocessor script that normalizes ARFF formatted
# data. It counts the number of instances in each class, determines the
# minimum. It then takes a random subset of each class of the minimum size.... |
# Generated by Django 2.0.5 on 2018-07-11 15:22
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('api', '0012_part_meta'),
]
operations = [
migrations.CreateModel(
name='Set',
field... |
# def table(nb):
# i = 0
# while i < 10: # tant que i est strictement inferieure à 10.
# print(i + 1, "*",nb,"=",(i+1)*nb)
# i += 1 #on incremente i de 1 à chaque tour
# table(2)
# version avec le choix du chiffre multipliant x
def table(nb,max):
i=0
while i < max:
print(i + 1... |
from django.contrib.auth import (login as auth_login, authenticate)
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
from django.http import HttpResponseRedirect
from django.urls import reverse
from .models import DataSchema, DataSet, Field
from .forms import Fiel... |
from django.db import models
from LandingPage.models import Course
# Create your models here.
class CorporatesTalks(models.Model):
name=models.CharField(max_length=50)
email=models.EmailField(max_length=100)
organization=models.CharField(max_length=250)
course= models.ForeignKey(Course,related_name='co... |
#!/usr/bin/python
#\file crop_img.py
#\brief Crop an image.
#\author Akihiko Yamaguchi, info@akihikoy.net
#\version 0.1
#\date Jun.15, 2021
import numpy as np
import cv2
import sys,os
if __name__=='__main__':
file_in= sys.argv[1]
img= cv2.imread(file_in)
print 'Input image shape:',img.shape
x,y,w,h=... |
from rest_framework import serializers
from .models import StepUser, StepUserHistory
class StepUserHistorySerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = StepUserHistory
class StepUserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = StepUser
... |
from django.contrib import admin
from .models import Profile, Role
# Register your models here.
admin.site.register(Profile)
admin.site.register(Role)
|
'''
Your goal in this kata is to implement a difference function, which subtracts one list from another and returns the result.
It should remove all values from list a, which are present in list b.
array_diff([1,2],[1]) == [2]
If a value is present in b, all of its occurrences must be removed from the other:
array_d... |
#_*_coding:utf-8_*_
from apps.online_user.models import OnlineUser, OnlineUserSerializer
from django.shortcuts import get_object_or_404, render
from rest_framework.response import Response
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.authentication impo... |
# for gmail
EMAIL_USE_TLS = True
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'vlad120403@gmail.com'
EMAIL_HOST_PASSWORD = ''
EMAIL_PORT = 587 |
from django.conf import settings
from django.contrib.auth import logout
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from django.shortcuts import redirect, render_to_response
from django.template import RequestContext
import ... |
# -*- coding: UTF-8 -*-
__author__ = 'Aaron zh'
from function import *
import json
from django.db import connection, transaction
global current_time
current_time = time.strftime('%Y-%m-%d', time.localtime(time.time()))
reload(sys)
sys.setdefaultencoding("utf-8")
from ..businessRule.actions import *
class MyThread(ob... |
# 1. web server under construction
# 2. other than get is invalid request response with error code
# 3. /index.html, match contents.
# 4. list of directory with files and folders. (html template for printing)
# 5. Handling threads
# 1. /scripts/file.py, check for the output
# 2. /file.py, other than scripts folder
# 3... |
import matplotlib.pyplot as plt
import numpy as np
def plot_surface(clf,X,y,h=.02):
fig = plt.figure(figsize=[6,6])
x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h)... |
import codecs
import datetime
import mimetypes
import re
import os
import json
from typing import Dict, Any, List, Union, Optional, Tuple, Type
from django.shortcuts import redirect, render
from .exceptions import ParamNotFoundError, ValueOutOfRangeError, RequestValidationError, \
InvalidParamFormatError, ObjectN... |
#!/usr/bin/python3
"""main.py: Read a file and create linked lists of word size containing no repeating words
"""
import string
from linked_list import LinkedList
from node import Node
def main():
"""main: Opens up a text file and creates linked lists of words
"""
with open('paragraph.txt') as file:
... |
contador1 = 1
contador2 = 1
while contador1 <= 9:
print('-'*12)
while contador2 <= 10:
print('{} x {:2} = {}'.format(contador1, contador2, contador1 * contador2))
contador2 += 1
contador2 = 1
contador1 += 1
|
import os
import os.path
config_file_name = 'config_file.cfg'
PATH = '.svds/config/config_file.cfg'
if ( os.path.isfile(PATH) ):
print("true")
else:
print("false") |
import bcrypt, sys
import pymongo
from pymongo import MongoClient
from pymongo import errors
import gridfs
class Database(object):
def __init__(self):
try:
self.client = MongoClient()
self.movies = self.client.xray.movies
self.shots = self.client.xray.shots
self.actors = self.client.xray.actors
self... |
"""
smorest_sfs.modules.codes.resource
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
编码的资源模块
"""
from typing import Any, Dict
from flask.views import MethodView
from smorest_sfs.modules.auth import PERMISSIONS
from smorest_sfs.modules.auth.decorators import doc_login_required, permission_required
from . imp... |
#!/usr/bin/env python3
import sys
sys.path.insert(0, '..')
import random
import earthquake.catalog as catalog
import models.model as model
import gaModel.parallelGAModelP_AVR as parallelGAModelP_AVR
import time
import numpy as np
def createRealModelSCwithP_AVR(
year, region, qntYears=5, withMag=True, save=True):
... |
#!/usr/bin/python3
import sqlalchemy
#TODO {time:[food1, food2...]}
class FoodType():
milk = 'молочные продукты'
fruit = 'фрукты'
meat = 'мясо'
fish = 'рыба'
vegetable = 'овощи'
nut = 'орехи'
fastfood = 'фастфуд'
water = 'вода'
drink = 'напитки'
alco = 'алкогольные напитки'
... |
# -*- coding:gb18030 -*-
# -*- coding:utf-8 -*-
from appium import webdriver
from time import sleep, ctime
def appium_start():
desired_caps = {"platformName": "Android",
"deviceName": "127.0.0.1:62001",
"platformVersion": "4.4.2",
# apk°üĆū
... |
def getFunc(multiplier):
def getMultiplications(l):
return [multiplier*i for i in l]
return getMultiplications
funcs = []
for multiplier in range(4):
funcs.append(getFunc(multiplier))
l = [10, 20, 30, 40, 50]
for f in funcs:
print(f(l)) |
h1,m1=map(int,input().split())
h2,m2=map(int,input().split())
hrs=h1-h2
mins=m1-m2
print(abs(hrs),abs(mins),end=" ")
|
# _*_coding:utf-8_*_
# Author : Leo
# Time : 17/12/2018
import requests
import json
import sys
class Translation:
def __init__(self, query):
# set the translation page
self.post_url = "https://fanyi.baidu.com/basetrans"
# simulate a mobile user
self.header = {
"U... |
# University project of a TechFarm where I should use binary search to find cows in a specific list and know if it was milked or not and also if it is on the list:
cows = [100, 101, 102, 103, 104, 105]
milkedCow = {100: 'Milked', 101: 'Not Milked', 102: 'Milked', 103: 'Milked', 104: 'Milked', 105: 'Milked'}
searchCo... |
import urllib2, json, re
from bs4 import BeautifulSoup
def weather_by_name(city):
"""requests the weather data for city from the openweathermap api
Args:
city: A string containing a valid city name.
Returns:
Json of weather data.
"""
key = "4a2a82ee8a8dec7dc93d7bf8e048a6bc"
... |
import re, sys
import pdf
if len(sys.argv) != 2:
print 'Syntax: ' + sys.argv[0] + ' filename'
exit()
emailregex = r'\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b'
pdffilename = sys.argv[1]
m = pdf.convert_pdf_to_txt(pdffilename)
res = m.split()
#for r in res:
# print r
emails = set()
for line in res:
m ... |
import sqlite3, hashlib, binascii, os, stdiomask, time, sys, pprint
from tabulate import tabulate
from datetime import datetime
from colorama import init, Fore, Back, Style
def sqlConnect():
conn = sqlite3.connect("mail.db", timeout=10)
cursor = conn.cursor()
# conn.set_trace_callback(print) # отладка ... |
import json
import time
import urllib.request
import datetime
import sys
import logging
logging.basicConfig(level=logging.DEBUG)
from kafka import KafkaProducer
# Run this program
# python3 analyze.py 2016-12-01
# python3 analyze.py 2016-12-01 2016-12-31
# python3 analyze.py 2018-01-01 2018-12-31
# Example call of ... |
"""
back.app.models.json
This module aims at converting models in a json format.
"""
class JsonModel(object):
"""
This module aims at converting models in a json format.
Methods
-------
as_dict()
Convert a model that inherit from JsonModel in a json format
"""
def as_dict... |
n = int (input ())
A = []
for i in range (n):
A.append (list ('0' * n))
for i in range (n):
A [i][n - i - 1] = 1
for j in range (n):
if n - j < i + 1:
A [i][j] = 2
for i in range (n):
for j in range (n):
print (A [i][j], end = ' ')
if j == n - 1:
print () |
class MyException(Exception):
def __init__(self,arg):
self.msg=arg
def check(dict):
for k,v in dict.items():
print("Name = {} balance = {}".format(k,v))
if (v<2000):
raise MyException("balance amount less in {}".format(k))
bank={"raj":500,"sanju":450... |
import traceback
import asyncio
import http3
import json
import sys
import os
class RetryError(Exception):
pass
class retry():
def __init__(self, f):
self.f = f
async def _handle_function(self, func, selfF, *args, **kwargs):
tb = 'None found if you get this in the stack + error section contac... |
import example
print example.fact(3) |
import pytest
from pytest import mark
from time import sleep
@mark.flaky(reruns=3)
def test_snippets(browser):
browser.visit('/snippets')
browser.wait_for_js_variable('initFormSnippets')
browser.execute_script("""
initFormSnippets(document.querySelector('.formcode-snippets'));
""")
asser... |
from library.imapclient.imapclient import IMAPClient
from app.email.model import EmailModel
from app.core import settings
import email
import os
import smtplib
import time
class EmailController:
'''
Email controller
@todo: create mark message as read function
'''
client = None
''' IMAP client library'''
model ... |
import dyspatch
def test_version():
assert "." in dyspatch.__version__
assert len(dyspatch.__version__) >= 5
|
from django.contrib import admin
from .models import Event
class EventAdmin(admin.ModelAdmin):
list_display = ['name', 'is_published', 'start_date', 'end_date', 'location']
exclude = ('date_created',)
admin.site.register(Event, EventAdmin)
|
n = int(input())
odd_sum = 0
even_sum = 0
for i in range(0, n):
num = int(input())
if i % 2 == 0:
even_sum += num
else:
odd_sum += num
if odd_sum == even_sum:
print("Yes")
print("Sum = {0}".format(odd_sum))
else:
print("No")
print("Diff = {0}".format(abs(odd_sum - even_su... |
import yaml
import pandas as pd
import os
from autumn.projects.covid_19.vaccine_optimisation.vaccine_opti import initialise_opti_object
from autumn.settings import BASE_PATH
def load_decision_vars(file_name):
file_path = os.path.join(
BASE_PATH, "apps", "covid_19", "vaccine_optimisation", "optimal_plans... |
class GeneralizeStorageLocationException(Exception):
pass
class UninitializedStorageLocationException(Exception):
pass
|
"""
Auth provider that authenticates against django.contrib.auth.
This is currently half-assed and assumes that django.settings.configure() has
already been called by the time that DjangoAuth.authenticate gets called, and
that the database is set up correctly, etc.
By default, this only authenticates users who are is... |
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('listings/', include('listings.urls')),
path('send_mail/', views.send_email, name='send_mail'),
] |
from django.contrib.auth.models import User
from django import forms
class UserForm(forms.ModelForm):
username = forms.CharField(label='帳號')
password = forms.CharField(label='密碼', widget=forms.PasswordInput)
password2 = forms.CharField(label='確認密碼', widget=forms.PasswordInput)
first_name = forms.CharF... |
import numpy as np
import random
import copy
import util
import itertools
class Simple_Cycles():
# the epsilon value we use
epsilon = 0.01
# runs the iterative algorithm for this of iterations
iterations = 2000
# the threshold for the convergence limit = 10^-7
convergence_threshold = 0.000000... |
# Is The Number Less Than Or Equal To Zero
def lessThanZero(input):
if(input <= 0):
return "Yes less than or equal to zero"
else:
return "Not less than zero"
print(lessThanZero(0)) |
# Copyright 2010-2011 OpenStack Foundation
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
#
# 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/licens... |
import tensorflow as tf
from matplotlib import pyplot as plt
import numpy as np
import matplotlib.image as mpimg
from random import randint
import sys
infile_i = open("images.npy", "rb")
infile_l = open("labels.npy", "rb")
emo = [np.load(infile_i), np.load(infile_l)]
randomize = np.arange(len(emo[0]))
np.random.shuff... |
#-*- coding:utf8 -*-
import time
import json
import datetime
from django.db import models
from shopback.signals import user_logged_in
from shopapp.jingdong import apis
import logging
logger = logging.getLogger('django.request')
class JDShop(models.Model):
shop_id = models.CharField(max_length=32,primary_k... |
import sys
def solve(fences):
stack = []
ret = 0
# stack = [(idx, value)]
for cur, v in enumerate(fences):
new_idx = cur
while stack and stack[-1][1] >= v:
ret = max(ret, stack[-1][1] * (cur - stack[-1][0]))
new_idx = stack.pop()[0]
stack.append((new_idx,... |
# Generated by Django 3.1 on 2020-09-14 22:03
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('user', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Projec... |
import sys
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
torch.manual_seed(1)
class BiLSTM_CRF(nn.Module):
def __init__(self, vocab_size, tag_to_ix, embedding_dim, hidden_dim):
super(BiLSTM_CRF, self).__init__()
self.vocab_size = vocab_size
self.embedd... |
# -*- coding: UTF-8 -*-
from flask import Blueprint, url_for, render_template as flask_render_template, request, make_response, g, send_from_directory, redirect, session
from werkzeug.contrib.atom import AtomFeed
from fypress.folder import Folder
from fypress.post import Post, GuestCommentForm, LoggedCommentForm, S... |
from django.conf import settings
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic.edit import FormView
from zenpy import Zenpy
from zenpy.lib.api_objects import CustomField, Ticket, User as ZendeskUser
from .forms import RequestAccessForm
class AccessDeniedView(Form... |
#!/usr/bin/python3
""" create a new class Scuare """
from models.rectangle import Rectangle
class Square(Rectangle):
""" new class
Args:
Rectangle (class): Inheritance: from Base Class
"""
def __init__(self, size, x=0, y=0, id=None):
""" constructor
Args:
... |
"""Brain Even game logic."""
from random import randint
from typing import Tuple
MIN_NUMBER = 0
MAX_NUMBER = 100
DESCRIPTION = 'Answer "yes" if number even otherwise answer "no".'
def get_task() -> Tuple[str, str]:
"""
Generate new question and right answer for even game.
Returns:
dict: dict w... |
# Generated by Django 2.2.5 on 2019-09-30 21:10
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
('afriventapp', '0001_initial'),
migrations.swappable... |
#!/usr/bin/env python3
##############################
# Data Thread section
##############################
import logging
import os
from time import sleep
from threading import Thread
from datetime import datetime
from serial import Serial, SerialException, SerialTimeoutException, STOPBITS_ONE, EIGHTBITS, PARITY_NONE... |
contents = open('rosalind_1a.txt', 'r')
text,k = contents.readlines()
d = {}
highest_score = 0
for i in range(int(k), len(text)):
k_mer = text[i-int(k):i]
if k_mer in d:
d[k_mer] += 1
if d[k_mer] > highest_score:
highest_score = d[k_mer]
else:
d[text[i-int(k):i]] = 1
to_print = []
for... |
# Generated by Django 3.0.7 on 2020-08-06 13:18
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('Inventario', '0009_auto_20200806_0814'),
]
operations = [
migrations.RemoveField(
model_name='entry',
name='provider',
... |
import tensorflow as tf
import matplotlib.pyplot as plt
import requests
import csv
import os
import numpy as np
from tensorflow.python.framework import ops
## load data
## name of data file
birth_weight_file = 'birth_weight.csv'
#birthdata_url = 'https://github.com/nfmcclure/tensorflow_cookbook/raw/master/01_Introdu... |
import numpy as np
def hm_estimator(vqsamp, targ=None):
vq = np.sort(vqsamp, kind='mergesort')
if targ is not None:
ft = lambda h: targ(h)
else:
ft = lambda h: custom_target(h, 0, 0, 5)
M = len(vqsamp)
vh = [(1./M)*(0.5 + j) for j in range(M)]
vt = np.array([float(ft(hi)) for... |
# hack script to get around the OS X tkinter threading limitation
# works on Python 2 and 3
import sys
try:
import tkinter
except:
import Tkinter as tkinter
try:
from tkinter import filedialog
except:
import tkFileDialog as filedialog
root = tkinter.Tk()
root.withdraw()
root.overrideredirect(True)
root.geomet... |
#!/usr/bin/env python3
"""https://snlp2020.github.io/a5/
Course: Statistical Language processing - SS2020
Assignment: A5
Author: Jinghua Xu
Description: experiment with ANNs
Honor Code: I pledge that this program represents my own work.
"""
import random
import numpy as np
from sklearn... |
#!/usr/bin/env python
from the_window import GameWindow
from screens import level_from_file
import pyglet
def go():
window = GameWindow()
window.thescreen = level_from_file.GameplayScreen(window, "one")
window.unpause()
pyglet.app.run()
if __name__ == "__main__":
go()
|
# -*- coding: utf-8 -*-
import scrapy
import time
from movie.items import LeetcodeItem
class MeijuSpider(scrapy.Spider):
# name = 'meiju'
# allowed_domains = ['meijutt.com']
# start_urls = ['http://www.meijutt.com/new100.html']
#
# def parse(self, response):
# movies = response.xpath('//ul... |
class AlreadyExistsError(Exception):
""" Raised if a product of an onboarding process exists already. """
|
import numpy as np
from scipy import sparse, stats, linalg
from project.esn.utils import mydataclass, pre_proc_args, force_2dim
import pickle as pic
''' generator for scipy and np matrix '''
def generate_smatrix(m, n, density=1, bound=0.5, **kwargs):
"""generate a sparse matrix in the CSR format (Compressed Spars... |
import os
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
from torch.utils.data import DataLoader
from tqdm import tqdm
import numpy as np
from tensorboardX import SummaryWriter
import sys
import time
import json
from qanet.tvqanet import TVQANet
from tvqa_dataset import TVQADataset, pad_coll... |
import os
import csv
from enum import Enum
class Column(Enum):
timestamp = 0
location = 1
classtime = 2
open_seats = 3
taken_seats = 4
is_full = 5
IS_FULL = 'is_full'
TOTAL_SLOTS = 'total_slots'
summary = {}
with open(os.getcwd() + '/classes.csv', 'r') as csvfile:
for row in reversed(list... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
def simple_ann():
import cv2
import numpy as np
ann = cv2.ml.ANN_MLP_create()
# 设置相应的层数为 9-5-9
ann.setLayerSizes(np.array([9,5,9],dtype=np.uint8))
# 使用反向传播算法进行权重修正
ann.setTrainMethod(cv2.ml.ANN_MLP_BACKPROP)
ann.train(np.array([[1.2,1.3,1.9,2.2,2.3,2.9,3.0,3.2,3.3... |
import pandas as pd
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.rcParams['agg.path.chunksize'] = 20000
print 'reading data'
df = pd.read_csv('data.csv')
col_list = list(df.columns)
col_list.remove('y')
col_list.remove('id')
df['count_null'] = df.isnull... |
""" Interfaces
"""
from zope.interface import Interface
from zope import schema
from zope.i18nmessageid import MessageFactory
_ = MessageFactory("edw")
class IDataCube(Interface):
"""Description of the Example Type"""
# -*- schema definition goes here -*-
class IDataCubeSettings(Interface):
""" Setting... |
class Node(object):
"""Node for singly linked list."""
def __init__(self, val, next=None):
self.value = val
self.next = next
def __str__(self):
return str(self.value)
class LinkedList(object):
"""Singly linked list."""
def __init__(self):
self.first = self.last = No... |
def publish_sensor(project_id, topic_id,data,origin='python-sample',username='gcp'):
""""
description: send data to pubsub topic
arguments:
project_id (str): name of GCP project ID
topic_id (str): name of pubsub topic
data (str): data you want to upload
origin (str): name of ... |
from datetime import datetime
def take_time(func):
def wrapper(*args, **kwargs):
start = datetime.now()
result = func(*args, **kwargs)
print(func.__name__, 'duration', datetime.now() - start)
return result
return wrapper
|
# --------------------------------------------- #
# Imports #
# --------------------------------------------- #
from collections import OrderedDict
import pyfftw, mrcfile, itertools
import numpy as np
# --------------------------------------------- #
# Fourier transf... |
from rv.modules import Behavior as B
from rv.modules import Module
from rv.modules.base.lfo import BaseLfo
class Lfo(BaseLfo, Module):
behaviors = {B.sends_audio}
|
# -*- coding: utf-8 -*-
from irc3.testing import BotTestCase
from irc3.testing import MagicMock
from irc3.testing import asyncio
import datetime
import tempfile
import shutil
import os
def hook(entries):
return []
class Hook:
def __init__(self, bot):
pass
def __call__(self, entries):
r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.