text stringlengths 8 6.05M |
|---|
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
train_data = pd.read_csv('train.csv')
test_data = pd.read_csv('test.csv')
Y = train_data["Survived"]
features = ["Pclass", "Sex", "SibSp", "Parch"]
X = pd... |
import os
import re
import numpy as np
import torch
from torch import autograd
from torch.autograd import Variable
import codecs
import numpy as np
import matplotlib.pyplot as plt
import random
import sys
import torch.nn.functional as F
import math
import torch.nn as nn
import sys
sys.path.append('/home/rjzhen/anaconda... |
#!/usr/bin/python
import datetime
import logging, time
def check_dates(start_date, end_date):
accepted_formats = ["%Y-%m-%d", "%Y-%m-%dT%H:%M",
"%Y-%m-%dT%H:%M:%S",
"%Y-%m-%dT%H:%M:%S.%f",
"%Y-%m-%dT%H:%M:%S.%fZ" ]
for f in accepted_formats:
try: start = datetime.datetime.strp... |
import random
import string
random.seed(1234)
def get_random_string(length=5):
return ''.join(random.choice(string.ascii_lowercase) for _ in range(length))
def get_random_line(min_str_len, max_str_len, num_columns):
return [
get_random_string(random.randint(min_str_len, max_str_len))
for _... |
#!/usr/bin/env python
import socket
import sys
host = ''
port =
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((host, port))
s.shutdown(2)
up = True
except:
up = False
s.close()
if up:
print "success"
sys.exit(0)
else:
print "connection failure"
sys.exit(2)
|
import KratosMultiphysics as Kratos
import KratosMultiphysics.RANSApplication as KratosRANS
def Factory(settings, Model):
if (not isinstance(settings, Kratos.Parameters)):
raise Exception(
"expected input shall be a Parameters object, encapsulating a json string"
)
if (not isinstan... |
import torch.optim as optim
import torch.nn as nn
def optimizer_SGD(lr=0.001, momentum=0.9, net):
return optimizer = optim.SGD(net.parameters(), lr, momentum) |
"""domain_manage URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Cl... |
from elasticsearch import Elasticsearch
host = 'http://localhost:9200'
es = Elasticsearch([host])
es.indices.create(index='reliability')
|
from django import forms
from .models import *
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title', 'text','extra','insert')
class ResultsPage(forms.ModelForm):
class Meta:
model = Post
fields = ('text','title')
class BloodSampleForm(forms.ModelForm):... |
f = open('L3/text.txt')
for line in f.readlines():
print(line)
|
import json
# Enter your keys/secrets as strings in the following fields
credentials = {}
credentials['CONSUMER_KEY'] = "Kel08xM3PPXMpuAkXU2CmGNAb"
credentials['CONSUMER_SECRET'] = "YbQMuZg2Bg22s0Ct0CJTaTe2Eop2xopNWiLrIlpj8IJkpcRSEZ"
credentials['ACCESS_TOKEN'] ="1050020587203125248-TpDsgXR2BSVESMMdVopVSOEsfZN2b5"
cre... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from todo_app.models import Task
# Register your models here.
admin.site.register(Task) |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('course_selection', '0004_auto_20141124_1148'),
]
operations = [
migrations.CreateModel(
name='Enrollment',
... |
# Generated by Django 2.1.3 on 2018-12-17 16:49
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Author',
... |
/Users/rasmuslevinsson/anaconda3/lib/python3.6/re.py |
from django.contrib import admin
from pizzariaApp.models import Pizza, Topping
admin.site.register(Pizza)
admin.site.register(Topping)
|
# coding:utf-8
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.common.exceptions import *
from selenium.webdriver.support.select import Select
class Base():
def __init__(self, driver):
self.driver =... |
import cv2
import numpy as np
import dlib
from facialLandmarksDetection import *
print('import Success!!')
def generateEyeRegion(landmarks,eyeIndices):
"""
Input : 68 facial landmark points, Indices of left or right eyes.
Output : region covering respective eye, whose indices have been provided.
"""
... |
from django.test import override_settings
class TestAPIStatusView:
@override_settings(VERSION='TESTCASE')
def test_works(self, client):
resp = client.get('/api/v2/status/')
assert resp.status_code == 200
assert resp.json() == {
'data': {
'id': '1',
... |
import itertools
import logging
import os
import sys
import warnings
from contextlib import contextmanager
from contextlib import suppress
from decimal import Decimal
from enum import Enum
import hydra
import joblib
import numpy as np
import pandas as pd
import scipy
import tensorflow as tf
from questions.utils impor... |
#String methods
quote = "I think there is a world market for mabye five computers."
print(quote)
print(quote.upper())
print(quote.title())
print(quote.lower())
print(quote.replace("five","millions of"))
print(quote)
input("\n\nPress the enter key to exit")
|
# Generated by Django 3.2.3 on 2021-05-15 12:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('App', '0004_auto_20210515_1316'),
]
operations = [
migrations.AlterField(
model_name='audiobook',
name='duration',
... |
# Memorization of two 50-bit binary patterns per episode, with LSTMs. Takes a very long time to learn the task, and even then imperfectly. 2050 neurons (fewer neurons = worse performance).
#
#
# Copyright (c) 2018 Uber Technologies, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not ... |
from rest_framework import serializers
class Detailserializers(serializers.Serializer):
name = serializers.CharField(max_length=30)
fname = serializers.CharField(max_length=40)
age = serializers.IntegerField()
address = serializers.CharField(max_length=40)
city = serializers.CharField(max_length=4... |
import numpy as np
import matplotlib.pyplot as plt
y = 0.2 * np.power(X, 3) - np.square(X) - 3 * X - 10 + np.random.randn(np.shape(X)[0])
#y = 10 * X * np.sin(X) + np.random.randn(np.shape(X)[0])
X = np.linspace(-5, 10, 4)
print(X)
print(X[:, np.newaxis])
pass
def plot_train_data(X, y):
fig = plt.figure(figsiz... |
"""
------------------------------------
@Time : 2020/9/15 14:43
@Auth : chai
@File : home_page_data.py
@IDE : PyCharm
------------------------------------
"""
class HomePageData(object):
"""选择菜单功能
现在没做断言判断,因为没有界面统一的位置标记,等有了再断言"""
menu_select = [
("recommend", "お困り事"),
("collaboration", ... |
import math
import numpy as np
import modern_robotics as mr
pi = math.pi
print("\n------ Question 1 ------")
density = 5600
rad_cyl = 0.02
len_cyl = 0.2
rad_sph = 0.1
mass_cyl = density * pi * len_cyl * rad_cyl**2
print("\nMass of Cylinder: ", mass_cyl, sep='')
Ixx_cyl = mass_cyl * (3 * rad_cyl**2 + ... |
#!/usr/bin/env python3
from ev3dev2.motor import LargeMotor, OUTPUT_A, OUTPUT_D, SpeedPercent
from ev3dev2.sensor import INPUT_4
from ev3dev2.sensor.lego import UltrasonicSensor
import socket
import time, os
import subprocess
# HOST = '192.168.0.7'
HOST = '192.168.137.1'
PORT = 12345
client_socket = sock... |
# coding: utf-8
from __future__ import print_function
import os
import tensorflow.contrib.keras as kr
import torch
from torch import nn
from cnews_loader import read_category, read_vocab
from model import TextRNN
from torch.autograd import Variable
import numpy as np
try:
bool(type(unicode))
except NameError:
... |
N, K = map( int, input().split())
L = [0]*K
for n in range(1,N+1):
L[n%K] += 1
ans = 0
for a in range(1,N+1):
if (2*a)%K == 0:
ans += L[(K-a)%K]**2
print(ans)
|
# Complete the countApplesAndOranges function below.
def countApplesAndOranges(s, t, a, b, apples, oranges):
TA = 0
TO = 0
for i in range(len(apples)):
apples[i] += a
if apples[i] >= s and apples[i] <= t:
TA += 1
print(TA)
for j in range(len(oranges)):
oranges[j] ... |
import pytest
from icalendar import Calendar, Event, Parameters, vCalAddress
import unittest
import icalendar
import re
@pytest.mark.parametrize('parameter, expected', [
# Simple parameter:value pair
(Parameters(parameter1='Value1'), b'PARAMETER1=Value1'),
# Parameter with list of values must be separated... |
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import Vacancy
from rest_framework import generics
from .serializers import (
VacancySerializer,
VacancyCreateSerializer,
)
from django.db import IntegrityError
from info.models import Skills
from accounts.models ... |
import sys
class Account(object):
__slots__ = [ 'name', '_balance', 'min_balance', 'transactions', 'index' ]
def __init__(self, name):
self.name = name
self._balance = 0
self.min_balance = 0
self.transactions = []
self.index = 0
def __iter__(self):
return ... |
# Generated by Django 2.2.2 on 2019-07-01 13:25
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('debt', '0002_creditline_account_holder'),
]
operations = [
migrations.RemoveField(
model_name='creditline',
name='holder',
... |
# this script is used to make the stock relations which is used to label news
import xlrd
import re
import functools
import pandas as pd
xls_path = r'/Users/wangfeihong/Desktop/Dynamic-Financial-News-Collection-and-Analysis/data/us_stocks.xls'
dict_path = r'/Users/wangfeihong/Desktop/Dynamic-Financial-News-Collection... |
#!/usr/bin/env python
# encoding: utf-8
"""
conf.py
"""
import sys
import os
sys.path.append(os.path.abspath(os.curdir))
from pyflix.Netflix import *
import flixdohickey.secretkey as secretkey
APP_NAME = 'FlixDohickey'
API_KEY = 'g2wcttragfgx37fv54qxpjqw'
API_SECRET = secretkey.get_api_secret()
CALLBACK = ''
... |
# run_grtrans_3D.py
# runs grtrans on koral simulation images at very high resolution
# these will take a long time!
import grtrans_batch as gr
import numpy as np
import sys
import os
import subprocess
import time
import astropy.io.fits as fits
import scipy.ndimage.interpolation as interpolation
####################... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-10-15 23:29
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('travelapp', '0001_initial'),
]
operations = [
... |
'''
Combine already-calculated dispersions in various ways.
Things to investigate:
* Compare Mississippi and Atchafalaya
* Compare months
* Compare years
'''
import numpy as np
import pdb
from matplotlib.mlab import find
import netCDF4 as netCDF
from scipy import ndimage
import time
from glob import glob
import tra... |
import requests
import json
import configparser as cfg
class telegram_chatbot():
def __init__(self, config):
self.token = self.read_token_from_config_file(config)
self.base = f"https://api.telegram.org/bot{self.token}"
def get_updates(self, offset=None):
url = self.base + "/getUpdates... |
from django.db import models
#Parameters model containing nutrients and other molecules from Wastes
class Parameters(models.Model):
#has a name
name = models.CharField(max_length=128, unique=True)
#has a unit
unit = models.CharField(max_length=128)
#has a type
type = models.CharField(max_length... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 8 10:08:30 2020
@author: saurabh
"""
import subprocess
def PingIP(str):
process=subprocess.Popen(str,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
for line in process.stdout:
print(line)
res.append(line)
errcode = process... |
# sys 모듈로 입력 인수 주기
import sys
args = sys.argv[1:]
for i in args:
print(i)
# sys 모듈의 argv 는 명령창에서 입력한 인수들을 의미한다.
# 즉 , sys1.py aaa bbb ccc << 와 같이 입력했다면 argc[0]는 파일이름인 sys1.py가 되고 argv[1] 부터는 뒤에 따라오는
# 인수들이 차례로 argv의 요소가 된다.
# sys1.py << argv[0] , aaa << argv[1] , bbb << argv[2] , ccc << argv[3]
|
import re
from onegov.activity import BookingCollection, InvoiceCollection
from onegov.core.orm import Base
from onegov.core.orm.mixins import ContentMixin, TimestampMixin
from onegov.core.orm.types import UUID, UTCDateTime
from onegov.feriennet import _
from onegov.feriennet.collections import VacationActivityCollect... |
from .projects import BaseProjectModelRoute
from .serializers import SampleSerializer
from portia_orm.models import Sample
class SampleRoute(BaseProjectModelRoute):
lookup_url_kwarg = 'sample_id'
default_model = Sample
def perform_create(self, serializer):
self.project.spiders # preload spiders
... |
import logging
import pprint
import os
import collections
import multiprocessing
import wandb
from action_recognition.utils import setup_logging
from action_recognition.experiment import ExperimentConfig, run_experiment
from action_recognition.evaluate.evaluate_video import expand_nested_str_dict
from action_recognit... |
def test_qr_code_view(client):
assert client.get('/qrcode?payload=hello').content_type == 'image/png'
assert client.get('/qrcode?img_format=jpeg').content_type == 'image/jpeg'
assert client.get('/qrcode?img_format=gif').content_type == 'image/gif'
assert client.get('/qrcode?encoding=base64').content_ty... |
from flask_wtf import FlaskForm
from wtforms import StringField, TextAreaField, SubmitField, SelectField, RadioField
from wtforms.validators import DataRequired
from flask_wtf.file import FileField, FileRequired, FileAllowed
class NewsForm_mysql(FlaskForm):
""" 新闻表单 """
title = StringField(label='新闻标题', valid... |
RANGE_STOP = eval(input("RANGE STOP > "))
n = list(range(1, RANGE_STOP+1, 1))[::-1] # Create and then reverse the array, so it's completly unsorted
def recursive_iterationSort(arr, length):
if length <= 1:
return
recursive_iterationSort(arr, length-1)
last = arr[length-1]
j = length-2
... |
# Generated by Django 3.0.1 on 2020-01-29 18:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('eica', '0005_boletacompra_responsable'),
]
operations = [
migrations.AddField(
model_name='boletacompra',
name='vali... |
#!/usr/bin/env python
#coding: utf-8
import unittest
from mock import Mock
from pyinotify import WatchManager
from picman_sync import PicmanSync
class TestPicmanSync(unittest.TestCase):
def setUp(self):
pass
def test_have_a_watcher_manager(self):
picman_sync = PicmanSync()
self.asser... |
# Generated by Django 3.2.3 on 2021-06-15 07:17
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='About',
fields=[
('id', models.AutoField(au... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
快速得到一个表中的行数, 或是选中的数据的行数。
结论: 使用 ``SELECT COUNT(*) FROM (SELECT column_name FROM test)``
"""
import time
import sqlite3
connect = sqlite3.connect(":memory:")
cursor = connect.cursor()
# Create Table
cursor.execute("CREATE TABLE test (id INTEGER)")
# Insert Test Dat... |
""" Advent of Code Day 10 - Balance Bots"""
import re
with open('input.txt') as f:
instructions = [line.strip() for line in f.readlines()]
target_1 = 61
target_2 = 17
comp_bot = None
outputs = {}
bots = {}
while instructions:
to_delete = []
for row, instruction in enumerate(instructions):
bot_re... |
import os, json
from random import randint, random
from pandas import DataFrame, read_csv
from faker import Factory
from .updateYear import RolloverYear
# Parses data from commissions and residuals files
# Makes commissions and residuals fake
# Stored faked data will be used to match to CarrierStatistics data
class... |
from .stage import PipelineStage
import os
import yaml
import copy
import collections
import string
import numpy as np
class SafeFormatter(string.Formatter):
"""
This helper class from http://stackoverflow.com/questions/17215400/python-format-string-unused-named-arguments
means that we can keep the {} plac... |
import cv2 as cv
import sys
img_color = cv.imread("../sample/test.jpg", cv.IMREAD_COLOR)
if img_color is None:
print("이미지 파일을 읽을 수 없습니다.")
sys.exit(1)
img_gray = cv.cvtColor(img_color, cv.COLOR_BGR2GRAY)
retval, img_binary = cv.threshold(img_gray, 127, 255, cv.THRESH_BINARY)
img_result = cv.hconcat([img_... |
import time
import pyautogui
for i in list(range(4))[::-1]:
print(i + 1)
time.sleep(1)
while True:
print('down')
pyautogui.keyDown('s')
time.sleep(3)
print('up')
pyautogui.keyDown('w')
time.sleep(3)
|
""" -------------------------------------------------------------------------------------------------------------------
ITEC 136: Homework 09 - 02
Provide different code snippets for
each of the following complexities.
O(n2)
O(n)
O(1)
O( nlog(n) )
O( log(n) )
@author: Dani Hooven
@version: 11/06/2020
... |
#!/usr/bin/python3
"""Provides an empty class 'Rectangle' to represent a rectangle"""
class Rectangle():
"""Empty definition of a class to represent a rectangle"""
|
words = [
'abruptly',
'absurd',
'abyss',
'affix',
'askew',
'avenue',
'awkward',
'axiom',
'azure',
'bagpipes',
'bandwagon',
'banjo',
'bayou',
'beekeeper',
'bikini',
'blitz',
'blizzard',
'boggle',
'bookworm',
'boxcar',
'boxful',
'buck... |
# pylint: disable=redefined-outer-name,protected-access
import pytest
from rlib.string_stream import StringStream
from som.compiler.ast.method_generation_context import MethodGenerationContext
from som.compiler.ast.parser import Parser
from som.compiler.ast.variable import Argument
from som.compiler.class_generation_c... |
num = int(input())
character = chr(num)
print(character)
|
import asyncio
import time
import redis
import aredis
redis_pool = aredis.ConnectionPool(
host='192.168.170.132',
port=6379,
db=1
)
def aredis_cli():
return aredis.StrictRedis(
connection_pool=redis_pool,
decode_responses=True, # 自动解码
)
TYPE1_NUM = 3
class TaskModel():
d... |
# Generated by Django 2.2.6 on 2019-10-12 07:31
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('csvintegration', '0002_auto_20191011_2317'),
]
operations = [
migrations.RenameField(
model_name='carreer',
old_name='unives... |
""""Argo Workflow base builder for building OCI image using Kaniko"""
from kubeflow.kubeflow import ci
from kubeflow.testing import argo_build_util
class Builder(ci.workflow_utils.ArgoTestBuilder):
def __init__(self, name=None, namespace=None, bucket=None,
test_target_name=None, **kwargs):
... |
import numpy as np
from sys import platform
import os
def unpacknbits(arr, nbit, axis=-1):
'''unpack numbers to bits.'''
nd = np.ndim(arr)
if axis < 0:
axis = nd + axis
return (((arr & (1 << np.arange(nbit - 1, -1, -1)).reshape([-1] + [1] * (nd - axis - 1)))) > 0).astype('int8')
def packnbits... |
import sys
import xbmc
import xbmcgui
import xbmcplugin
import xbmcaddon
from resources.lib.url_resolver import StreamcloudResolver
from resources.lib.items.directory_item import DirectoryItem
from resources.lib.items.action_item import ActionItem
from resources.lib.items.video_item import VideoItem
from resources.lib ... |
class Stack(object):
def __init__(self, alist):
self.alist = alist
def push(self, param):
self.alist.append(param)
return param
def pop(self):
if len(self.alist) > 0:
result = self.alist[len(self.alist) - 1]
self.alist = self.alist[:len(self.alist)-1... |
from django.contrib import admin
from wiki.models import Article
admin.site.register(Article) |
#Conversor de medidas: Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros.
n1 = float(input('Digite o valor em metros: '))
cent = n1 * 100
mili = n1 * 1000
print('O valor em centimetros é {:.0f} cm e o valor em milimentros é {:.0f} mm'. format(cent, mili))
|
from selenium import webdriver
import random
import time
def click_timeout_button():
chromedriver_path = "C:/Users/chris/OneDrive/Documents/github/web-scrapers/chromedriver"
driver = webdriver.Chrome(chromedriver_path)
driver.get("http://www.quibids.com/en/category-12-vouchers-and-limit-busters/")
start_time = t... |
#!/usr/bin/python3
from sys import argv
from os.path import isdir, exists
from os import listdir, makedirs, system
from pipes import quote
import numpy as np
import scipy.io.wavfile as wav
import tensorflow as tf
class Configuration(object):
dataset_directory = None
model_iterations = None
sampling_frequ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-11-10 08:11
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('carto', '0050_auto_20171110_0911'),
]
operations =... |
# coding: utf-8
def num_of_1(num):
count = 0
while num:
num = num & (num - 1)
count += 1
return count
if __name__ == '__main__':
print(num_of_1(-1))
|
# print(type(False)) # bool
# print(1 > 3) # False
# print(1 == 1) # True
# Can give None data type if initially undefined
b = None |
"""
Python Wechaty - https://github.com/wechaty/python-wechaty
Authors: Huan LI (李卓桓) <https://github.com/huan>
Jingjing WU (吴京京) <https://github.com/wj-Mcat>
2020-now @ Copyright Wechaty
Licensed under the Apache License, Version 2.0 (the 'License');
you may not use this file except in compliance wit... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# The above lines tell the shell to use python as interpreter when the
# script is called directly, and that this file uses utf-8 encoding,
# because of the country specific letter in my surname.
"""
Name: Program 9 "Most Frequent Character"
Author: Martin Bo Kristensen Gr... |
'''
Which Archimedean is Best?
Extreme Value copulas formulas are based on Genest 2009
References
----------
Genest, C., 2009. Rank-based inference for bivariate extreme-value
copulas. The Annals of Statistics, 37(5), pp.2990-3022.
'''
import numpy as np
from scipy.special import expm1
def copula_bv_indep(u, v)... |
import serial
import sys
import Adafruit_DHT
import firebase
import time
from uuid import uuid4
import datetime
# Parse command line parameters.
sensor_args = { '11': Adafruit_DHT.DHT11,
'22': Adafruit_DHT.DHT22,
'2302': Adafruit_DHT.AM2302 }
# Serial instance for reading arduino sensor... |
#!/usr/bin/env python
import subprocess
import sys
import re
counters = ['\Memory\Available MBytes',
'\Memory\Pages/sec',
'\PhysicalDisk(_Total)\% Disk Time',
'\PhysicalDisk(_Total)\Current Disk Queue Length',
'\PhysicalDisk(_Total)\Disk Transfers/sec',
'\Phy... |
"""
Removes games older than a day from the mongo db from a Raspberry Pi
command to run: python purge_day_old_games.py
"""
import os
import datetime as dt
from pymongo import MongoClient
DATABASE_URL1 = os.environ.get('DATABASE_URL1')
client = MongoClient(DATABASE_URL1)
def remove_game(game_id: str):
"""
All... |
#######################################################################
#
# User Interface Helper Functions
#
#######################################################################
import time
import winsound
def wait_for_keypress():
"""Type x + ENTER To break loop"""
while True:
k = input()
i... |
from twisted.internet import protocol, reactor
class Knock(protocol.Protocol):
def dataReceived(self, data):
print("Client:{}".format(data))
if data.startswith("Knock knock".encode('utf-8')):
response = "Who's there?"
else:
response = data + " who?".encode('utf-8')
... |
import urllib.request
import re
def main(page):
url = 'http://jandan.net/ooxx/page-%d#comments' % page
req = urllib.request.Request(url)
# req.add_header("User-Agent", "Mozallia")
response = urllib.request.urlopen(url)
html = response.read().decode("utf-8")
print(html)
links = re.... |
#!/usr/bin/env python
# Authors: Chris Wilks (original) and Ben Langmead (modifications)
# Date: 7/3/2018
# License: MIT
"""sradbv2q
Usage:
sradbv2q query [<SRP>,<SRR>]... [options]
sradbv2q query-file <file> [options]
Options:
--delay Seconds to sleep between requests [default: 1].
--l... |
import unittest
from conans.test.utils.tools import TestClient
import os
from conans.util.files import load
class NewTest(unittest.TestCase):
def new_test(self):
client = TestClient()
client.run('new MyPackage/1.3@myuser/testing -t')
root = client.current_folder
self.assertTrue(os... |
# Generated by Django 2.2 on 2019-04-26 02:24
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('onlclass', '0039_auto_20190426_1116'),
]
operations = [
migrations.AlterField(
model_name='inquir... |
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('Paint')
self.setWindowIcon(QIcon('Images/Paint.png'))
self.setMaximumSize(860, 720)
self... |
from django.core.management.base import BaseCommand, CommandError
from csp_observer.models import Session
from csp_observer import settings as app_settings
from django.utils import timezone
from datetime import timedelta
class Command(BaseCommand):
help = 'Deletes old session data from the database'
def add_a... |
from AbstractGeometricObject import GeometricObject
class Rectangle(GeometricObject):
def __init__(self, width = 1, height = 1): # Construct a circle object
super().__init__()
self.__width = width
self.__height = height
def getWidth(self):
return self.__width
def setWidth(... |
import sync
import data_access
import time
import importers.txt_importer as txt
import importers.pdf_importer as pdf
import importers.doc_importer as doc
import logging
logging.basicConfig(format='%(levelname)s\t%(message)s', level=logging.DEBUG)
data_accessor = data_access.MySQLDataAccessor()
POLLING_DELAY = 10
wh... |
import matplotlib
#%matplotlib inline
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import sys
sys.path.append('waveglow/')
import numpy as np
import torch
import time
from hparams import create_hparams
from model import Tacotron2
from layers import TacotronSTFT, STFT
from audio_processing import griffin_lim... |
from typing import Union
from pydantic import BaseModel
from rest_framework import serializers
class PromoCodeBase(BaseModel):
group_name: Union[int, str]
class PromoCodeData(PromoCodeBase):
promo_codes: list
class PromoCodeRequest(PromoCodeBase):
promo_codes_amount: int
class PromoCodeRequestBody(... |
# 3rd Script to be run.
# We now have a dataset of 400 buses.
# We will create a new dataset. Each row of the dataset will correspond to a single bus id start and stop location and timestamp.
# Final dataset columns are ['s_lat','s_long','s_time','e_lat','e_long','e_time'].
import pandas as pd
import random
import gc
... |
"""Utility functions and classes for perceptron algorithms."""
import numpy as np
def generate_teacher(N, clamped):
"""Create a teacher perceptron w_opt.
Create a random teacher perceptron w_opt and normalize it such that:
|w|^2 = N <==> |w| = sqrt(N)
"""
if clamped:
N += 1
w_opt ... |
import foolbox
import tensorflow as tf
import numpy as np
import sys
labels = [
"airplane",
"automobile",
"bird",
"cat",
"deer",
"dog",
"frog",
"horse",
"ship",
"truck"
]
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()
img_size = (32, 32, 3)
batch_size = 1
input_layer = tf.pla... |
from .models import Avaliacao, Comentario
from django.shortcuts import render, get_object_or_404, redirect
from .funcoes import get_avaliacoes_context
def avaliar_item(request, tipo_item, item_id):
context = {}
if tipo_item not in ('filme', 'livro', 'serie'):
return redirect('/')
context.update(get... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.