text stringlengths 38 1.54M |
|---|
import hashlib
import sys
#Number of elements in hash table
if len(sys.argv) != 2 :
print "Required format: <python> <program> <size of hash table>"
sys.exit(0)
if int(sys.argv[1]) <= 0:
print "Required format: <python> <program> <size of hash table>"
sys.exit(0)
N=int(sys.argv[1])
F=[hashlib.md5, h... |
import configparser
import os.path
import sqlite3
from os import path
from sqlite3 import Error
def create_connection(db_file):
"""Create connection to SQLite database.
Args:
db_file (str): Name of database to connect to.
Returns:
Connection object: Connection to SQLite database.
""... |
from django.conf.urls import url,include
from . import views
app_name = "accounting"
apiv1 = [
# url(r'^helpers/',include(hpatterns)),
]
urlpatterns = [
url(r'^income$',views.AppIncome.as_view()),
url(r'^expenses$',views.AppExpenses.as_view()),
url(r'^apiv1/',include(apiv1)),
]
|
# coding: utf-8
from django.conf import settings
import os
import shutil
def get_test_tmp_dir():
return settings.TMP_ROOT + '/test'
def create_test_tmp_dir():
path = get_test_tmp_dir()
if not os.path.isdir(path):
os.mkdir(path)
def delete_test_tmp_dir():
path = get_test_tmp_dir()
if os... |
D = int(input())#D=365
c = list(map(int, input().split()))#0<=c<=100
s = [list(map(int, input().split())) for _ in range(D)]#0<=s<=20000
t = [int(input()) for _ in range(D)]
v = []
last = [0] * 26
value = 0
for d in range(D):
type = t[d]
value += s[d][type - 1]
last[type - 1] = d + 1
fo... |
#!/usr/bin/env python
import httplib
import sys
import os
def GetStockPriceFromYahoo(stockid):
yahoo = httplib.HTTPConnection('tw.stock.yahoo.com')
req = "/q/q?s=" + str(stockid)
# print req
yahoo.request("GET", req)
resp1 = yahoo.getresponse()
#print resp1.status, resp1.reason
data1 = resp1... |
# Generated by Django 2.1.7 on 2019-04-09 13:26
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Invoice',
fiel... |
#!/usr/bin/env python
"""Tests for low-level flows."""
from absl import app
from grr_response_client.client_actions import standard
from grr_response_client.client_actions import tempfiles
from grr_response_core.lib.rdfvalues import chipsec_types as rdf_chipsec_types
from grr_response_server import data_store
from gr... |
import logging
import os
import time
import requests
from dotenv import load_dotenv
from telegram import Bot
load_dotenv()
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s %(levelname)s %(name)s %(message)s",
)
logger = logging.getLogger(__name__)
PRAKTIKUM_TOKEN = os.getenv("PRAKTIKUM_TOKEN")... |
from django.core.management import BaseCommand
from django.conf import settings
from seedsource_core.django.seedsource.models import SeedZone
from tempfile import mkdtemp
import os
import subprocess
import json
import shutil
class Command(BaseCommand):
help = 'Facilitates converting of vector data into vector til... |
import math
t = int(input())
for _ in range(t):
a1, a2, a3, c1, c2, c3 = [int(x) for x in input().strip().split(" ")]
if (a1 > a2 and c1 > c2) or (a1 == a2 and c1 == c2) or (a1 < a2 and c1 < c2):
if (a1 > a3 and c1 > c3) or (a1 == a3 and c1 == c3) or (a1 < a3 and c1 < c3):
if (a2 > a3 and ... |
#! /usr/bin/python
# src: https://www.pythonforengineers.com/audio-and-digital-signal-processingdsp-in-python/
import numpy as np
import wave
import struct
import matplotlib.pyplot as plt
# frequency is the number of times a wave repeats a second
frequency = 1000
noisy_freq = 50
num_samples = 48000
# the sampling rate... |
def num_splits(s, d):
"""Return the number of ways in which s can be partitioned into two
sublists that have sums within d of each other.
>>> num_splits([1, 5, 4], 0) # splits to [1, 4] and [5]
1
>>> num_splits([6, 1, 3], 1) # no split possible
0
>>> num_splits([-2, 1, 3], 2) # [-2, 3], [... |
"""max()
The max() function takes any number of arguments and returns the largest one.
("Largest" can have odd definitions here, so it's best to use max() on integers and
floats, where the results are straightforward, and not on other objects, like strings.)
For example, max(1,2,3) will return 3 (the largest number in... |
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
import re
import sys
import subprocess
def usage():
return " ".join(["usage:", sys.argv[0], "<公車站名> <路線 0:去程/1:返程 ...>"])
if __name__ == '__main__':
if len(sys.argv) < 4:
print(usage())
sys.exit(1)
stop_name = sys.argv[1] # '中國電視公司'
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
readme = open('README.rst').read()
history = open('HISTORY.rst').read()
setup(
name='django-kb',
version='0.2.0',
description='Simple knowledge base made with django',
long_description=readme + '\n\n' + history,... |
from django import template
register = template.Library()
@register.inclusion_tag('likes/inclusion_tags/print_links.html', takes_context=True)
def print_like_link(context, obj):
"""
prints the link using the inclusion template
"""
request = context["request"]
from likes.models import Like
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 9 11:51:20 2013
@author: svenni
"""
from pylab import *
from scipy.ndimage.morphology import binary_closing
from scipy.ndimage import measurements
from percolation import clusterNumberDensity
L = 1024
Lx = L
Ly = L
nSamples = 100
nPVals = 12
pc = 0.59275
maxBinA... |
import random
def simulate(p, i, n):
k=1
position = i
samplePath = [i]
while k < n:
if random.random()<p:
position+=1
else:
position-=1
samplePath.append(position)
k+=1
return samplePath
print(simulate(0.5,0,10))
simulate(0.3,6,10)
|
# Generated by Django 3.0.5 on 2021-05-04 09:19
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('user', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='quser',
name='address',
),
migr... |
import posixpath
from django.urls.base import reverse
import diary
import logging
from .forms import InquiryForm, DiaryCreateForm
from django.urls import reverse_lazy
from django.views import generic
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from .models import Diary... |
import igraph as ig
import argparse, os
parser = argparse.ArgumentParser(description='Finds communities within the IMGpedia Graph')
parser.add_argument('input_graph', type=str, help='the lgl file of the graph')
parser.add_argument('output_folder', type=str, help='the folder for the output')
args = parser.par... |
#file import of which returns list of cursed tweets
from django.shortcuts import render, HttpResponse
from django.http import JsonResponse
import json
import pickle
import os
import pandas as pd
from pathlib import Path
import tweepy
import re
BASE_DIR = Path(__file__).resolve().parent.parent
Pkl_Filename = os.path.j... |
import json
import requests
def zbx_load_auth_from_file(auth_file):
"""Загрузка учетных данных Zabbix-сервера из JSON-файла, используя которые будет получен токен."""
with open(auth_file, 'r', encoding='utf-8') as af:
auth_data = json.load(af)
auth_data["url"] = auth_data["protocol"].lower() +... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 12 18:32:11 2020
@author: Dell
"""
import gzip
import numpy as np
def train_labels(path):
# Getting the labels
f = gzip.open(path,'r')
f.read(8)
labels = []
try:
for i in range(60000):
buf = f.read(1)
l = np.frombu... |
from vtk import *
from .AbstractMesh import AbstractMesh
class PolygonSet(AbstractMesh):
MAX_VERTS = 500
def __init__(self):
AbstractMesh.__init__(self)
self._currentVertex = 0
self._points = vtkPoints()
self._lines = vtkCellArray()
self._polygons = vtkCellArray()
... |
plik = open('dane_obrazki.txt')
data = plik.read().splitlines()
obrazki = []
obrazek = []
i = 0
while i < len(data):
if len(data[i]) != 0:
obrazek.append(data[i])
if len(data[i]) == 20:
obrazki.append(obrazek)
obrazek = []
i+=1
poprawne = 0
naprawialne = 0
nienaprawialne = 0
max_ble... |
#!/usr/local/bin/python3
# Filename : quadraticEquation.py
# author by : Lexi
# 二次方程式 ax**2 + bx + c = 0
# a、b、c 用户提供,为实数,a ≠ 0
# 导入 cmath模块
import cmath
a = float(input('输入 a:'))
b = float(input('输入 b:'))
c = float(input('输入 c:'))
# 计算
d = (b**2) - (4*a*c)
# 两种求解方式
sol1 = (-b-cmath.sqrt(d))... |
#macro to open up the .root file
#NOW IN PYTHON
#include <iostream>
#include <iomanip>
#include <stdlib.h>
#include <cmath>
#include <time.h>
#include "TFile.h"
#include "TTree.h"
#include "TCanvas.h"
#include "TH1.h"
#int main(){
def openpb():
TFile *f = TFile::Open("pbfile.root");
if (f == 0):
cout << "E... |
from django.urls import path
from . import views
from django.contrib.auth.views import LogoutView
urlpatterns = [
path('', views.ProfileView.as_view(), name='profile'),
path('login/', views.LoginView.as_view(), name='login'),
path('reg/', views.RegistrationView.as_view(), name='reg'),
path('logout/', L... |
from flask import Flask
from flask import request
from fanfic_downloader import FanficDownloader
# import password
from email_sender import EmailSender
import sys
import os
import threading
from rq import Queue
from worker import conn
import downloader
import password
app = Flask(__name__)
q = Queue(connection=conn)
... |
from typing import *
from proxy.ProxyConnection import ProxyConnection
import asyncio
class GameConnection(ProxyConnection):
"""
Specialised ProxyConnection for `GameServer`s
"""
__slots__ = ('state')
def __init__(self, server: 'servers.game.GameServer.GameServer',
st... |
import os, sys
from shutil import copyfile
args = sys.argv
unitType = ""
tempChannel = 0
def checkInputs():
#print("updateWebsiteSettings.py:checkInputs()")
if len(args) == 4:
channel = args[1]
inputType = args[2]
value = args[3]
#print(channel)
#print(inputType)
... |
# Generated by Django 2.0.5 on 2018-07-27 09:53
from django.db import migrations, models
import utils.storage
class Migration(migrations.Migration):
dependencies = [
('Users', '0012_auto_20180727_1752'),
]
operations = [
migrations.AlterField(
model_name='userprofile',
... |
import numpy as np
import uncertainties.unumpy as unp
from uncertainties import ufloat
from scipy.stats import sem
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
N=np.genfromtxt("data/indium.csv",delimiter=",",unpack=True)
t=np.arange(1,16,1)
t=t*240
null=223/900*240
#nullerr=np.sqrt(null)
N0=N
N... |
import os
import nsml
from nsml import DATASET_PATH
from tokenizer import CharTokenizer
from collections import Counter
from data_loader import read_strings
def bind_nsml(vocab_noisy, vocab_unlabeled, vocab_clean, vocab_total):
def save(path, **kwargs):
with open(os.path.join(path, 'vocab_noisy.txt'), 'w'... |
"""Routes WSGI Middleware"""
import re
import logging
from webob import Request
from routes.base import request_config
from routes.util import URLGenerator
log = logging.getLogger('routes.middleware')
class RoutesMiddleware(object):
"""Routing middleware that handles resolving the PATH_INFO in
addition to ... |
#!/usr/bin/env python
# Programmer: Navraj Chohan <nlake44@gmail.com>
import os
import sys
import unittest
from cassandra.cluster import Cluster
from flexmock import flexmock
sys.path.append(os.path.join(os.path.dirname(__file__), "../../../AppServer"))
from google.appengine.api import api_base_pb
from google.appe... |
from sys import argv
script, user_name = argv
prompt = '> '
print "Hi %s, I'm the %s script." %(user_name, script)
print "I'd like to ask you a few questions"
print "Do you like me %s?" % user_name
likes = raw_input (prompt)
print "Where do you live %s?" % user_name
lives = raw_input (prompt)
print ... |
# _tp : tige polaire
# _m : miroir
# alpha : angle d'inclinaison du miroir
# _p : hauteur du centre de rotation virtuel des pivots rcc
# _mt : moteur, actionneur
# _eq : tige equatoriale
#_s : support
#_ts : tige superieur des contrepoids
#_cp : contrepoids
#_ti : tige inferieur des contrepoids
#%%
import ma... |
#!/usr/bin/env python
import datetime
import glob
import numpy as np
import mygis as myio
from bunch import Bunch
def stats(data):
"""Calculate the rate of melt from peak to 0
Assumes that data starts at peak and decreases from there
Takes the first point data dips below peak as the onset of melt
... |
import pandas as pd
from fbprophet import Prophet
import streamlit as st
st.title('株価の時系列予測')
st.subheader('株価データの読み込み(6758:Sony)')
df = pd.read_csv("/Users/io/Desktop/prophet/stockdata/6758_2015_2020.csv", encoding = 'utf-8', names=['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Adj Close'], skiprows=[0, 1])
st... |
# spark enabled CNN with locality
from pyspark.sql import SparkSession
import os
import numpy as np
from time import time
from spark.conv import ConvolutionLayer
from spark.relu import ReLULayer
from spark.pool import PoolingLayer
from spark.fc import FCLayer
from spark.utils import *
from spark.spark_cnn import SparkC... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from time import sleep, time
import datetime
import unittest
from Nurse_A.Scenario.web_scenario import WEB
from Nurse_A.Ext_unittest.Testcase import Case
from Nurse_A.Scenario.android_scenario import ANDROID
from Nurse_A.Settings import keycode, constant, data, setup, mobil... |
#!/usr/bin/env python
import httplib2
#import datetime
import time
import os
import selenium
import json
import boto3
import requests
from dateutil.parser import parse
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
from selenium.webdriver... |
#These methods are based on Garrelt's IDL routines
from .. import const
from .. import conv
import numpy as np
import os
from .. import files
from temperature import calc_dt
from .. import utils
def freq_axis(z_low, output_slices, box_length_slices=256, box_length_mpc = conv.LB):
''' Make a frequency axis vector wit... |
from django.test import TestCase
from django.test import Client
from django.urls import reverse
from tests.factories.gbe_factories import ProfileFactory
from tests.contexts import StaffAreaContext
from tests.functions.gbe_functions import (
grant_privilege,
login_as,
setup_admin_w_privs,
)
from gbe.models i... |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
from matplotlib.patheffects import withStroke
from itertools import combinations
from inv2xyz import get_offsets
from array_response import get_array_response
import ipywidgets as widgets
out = widgets.Output()
class A... |
import grok
from zope.interface import Interface
from zope.component import getMultiAdapter
from zope.viewlet.interfaces import IContentProvider
from uvc.layout.interfaces import IPageTop
grok.templatedir('templates')
class SpotMenuViewlet(grok.Viewlet):
grok.viewletmanager(IPageTop)
grok.context(Interface... |
# -*- coding: utf-8 -*-
#
# This file is part of DO-MPC
#
# DO-MPC: An environment for the easy, modular and efficient implementation of
# robust nonlinear model predictive control
#
# The MIT License (MIT)
#
# Copyright (c) 2014-2015 Sergio Lucia, Alexandru Tatulea-Codrean, Sebastian En... |
# -*- coding=UTF-8 -*-
"""Viewer control. """
from __future__ import absolute_import, division, print_function, unicode_literals
import nuke
TYPE_CHECKING = False
if TYPE_CHECKING:
from .. import _types
class ActiveViewerService(object):
def _node(self):
v = nuke.activeViewer()
if v:
... |
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.OUT)
GPIO.setup(24, GPIO.IN,pull_up_down=GPIO.PUD_UP)
GPIO.setwarnings(False)
flag = 0
while 1:
GPIO.output(23, GPIO.HIGH)
time.sleep(0.5)
print GPIO.input(24)
if GPIO.input(24) != 0 and flag == 0:
print "ERROR: Lamp b... |
# Given two bit strings of length n, find the bitwise AND,
# bitwise OR, and bitwise XOR of these strings.
def AND(strA, strB):
result = ''
n = len(strA)
for i in range(0, n):
if(strA[i] == '1' and strB[i] == '1'):
result += '1'
else:
result += '0'
ret... |
#!/usr/bin/env python
'''
Copyright (C) 2006 Georg Wiora, xorx@quarkbox.de
Copyright (C) 2006 Johan Engelen, johan@shouraizou.nl
Copyright (C) 2005 Aaron Spike, aaron@ekips.org
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the... |
# Tachyon - Fast Multi-Threaded Web Discovery Tool
# Copyright (c) 2011 Gabriel Tremblay - initnull hat gmail.com
#
# GNU General Public Licence (GPL)
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Found... |
"""
Authentication Handler interface
"""
__author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2015 VMware, Inc. All rights reserved. -- VMware Confidential' # pylint: disable=line-too-long
class AuthenticationHandler(object):
"""
The AuthenticationHandler interface is used to verify the authentication
... |
from typing import List
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
'''
螺旋矩阵 II: 给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix
思路: 循环的方式, 依次给 i*i的正方形的上边、右边、下边、左边设置值,
'''
ret = [[0 for i in range(n)] for j in range(n)]
star... |
import pygame as pg
import time
# calculates the placement for the bomb the player places
# so that the bomb will be centered and not stuck inside of a wall.
def get_bomb_spot(origin_x, origin_y):
x = (int(origin_x/64)*64) + 32 - 10
y = (int(origin_y/64)*64) + 32 - 10
return x, y
class Player:
def _... |
import xlrd
s=xlrd.open_workbook('students.py')
sh = s.sheet_by_index(0)
cell=sh.cell(0,0)
print cell
|
import numpy as np
import pandas as pd
import os
for dirname, _, filenames in os.walk('/input'):
for filename in filenames:
print(os.path.join(dirname, filename))
df = pd.read_csv('/kaggle/input/beer-consumption-sao-paulo/Consumo_cerveja.csv')
df=df.rename(columns={"Temperatura Media (C)": "Temp median... |
from bs4 import BeautifulSoup as BS
with open('index.htm', 'r', encoding='utf-8') as f:
text_original = f.read()
soup = BS(text_original, 'html.parser')
print(soup.span.string)
|
from flask import Flask, render_template, request
from handler import proxy
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/video/<string:vid>.<any(jpg,webp):ext>")
def image(vid, ext):
return proxy.image(vid, ext)
@app.route("/video/api/v3/videos")
def... |
import boto3
def create_keypair():
outfile = open('ec2-keypair.pem','w')
key_pair = ec2.create_key_pair(KeyName='ec2-keypair')
KeyPairOut = str(key_pair.key_material)
print(KeyPairOut)
outfile.write(KeyPairOut)
def create_instances_and_show_ip():
ec2 = boto3.resource('ec2')
response... |
import socket
import threading
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
SERVER = 'localhost'
def pscan(port):
try:
s.connect((SERVER, port))
print(f'{port} is open')
return True
except:
print(f'No luck here at {port}')
return False
threads = list()
for x... |
# Generated by Django 2.2.10 on 2020-02-20 16:41
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import simple_history.models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AU... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 8 01:02:00 2021
@author: leonl42
Unit test for the character length feature
"""
import unittest
import pandas as pd
from scripts.feature_extraction.feature_character_length import FeatureCharacterLength
from scripts.util import COLUMN_TWEET
from ... |
from django.urls import path, re_path
from . import views
app_name = 'visacheck'
urlpatterns = [
path('visacheck/', views.visacheck, name='visacheck'),
path('visacheck/success', views.success, name='success'),
]
|
# -*- coding: utf-8 -*-
##
#@author Victor Cominotti
#@brief publish in a queue
import pika
import os
from S4_queues_tools import *
#how many messages publish
n_message = 1000
## publish data with amqp protocol
#@param args : arguments wanted, see S4_queues_tools for the list
#@param value : value of arguments, see... |
import requests
from bs4 import BeautifulSoup
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36'}
for i in range(1,11):
#因为一页只有25个电影简介,所以需要10页
href='https://movie.douban.com/top250?start='+str((i-1)*25)+'&f... |
#!/usr/bin/env python3
from scrapy.selector import HtmlXPathSelector
from scrapy.spiders import Spider
from scrapy.http import Request
from scrapy.crawler import CrawlerProcess
from scrapy.linkextractors import LinkExtractor
import os
import argparse
parser = argparse.ArgumentParser(description='web crawler')
parser.... |
import numpy as np
from PIL import Image
def color_to_char(pixel_color, c: str) -> list:
new_arr = []
for line in pixel_color:
row = []
for i in line:
if i == 0:
row.append(' ')
else:
row.append(c)
new_arr.append(row)
return... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
#ENV_NAME = 'CartPole-v1'
ENV_NAME = 'MountainCar-v0'
#ENV_NAME = 'Alien-v0'
#ENV_NAME = 'Pendulum-v0'
import gym
env = gym.make(ENV_NAME)
env.reset()
for _ in range(1000):
env.render()
env.step(env.action_space.s... |
'''
Take the number 192 and multiply it by each of 1, 2, and 3:
192 × 1 = 192
192 × 2 = 384
192 × 3 = 576
By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3)
The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4,... |
from os import path
from smtplib import SMTP_SSL
from _datetime import datetime
from base64 import b64encode, b64decode
from subprocess import Popen, PIPE
'''umgehe noconsole error bei convert durch pyinstaller'''
def cmd(command):
process = Popen(command, stdout=PIPE, stdin=PIPE, stderr=PIPE)
ip = process.com... |
import random
async def cmd_8ball(message, args):
responses = ["Yep!", "Of course.", "Absolutely!", "Eh, ask again.", "Unsure", "What? No!", "I don't think so.", "Probably a bad idea."]
response = random.choice(responses)
random_embed = discord.Embed(
title = "**8ball**",
description = r... |
# -*- encoding: utf-8 -*-
from __future__ import print_function
import numpy as np
import sys
from collections import defaultdict
from joblib import Parallel, delayed
import cPickle as pkl
from nn.utils.io_utils import serialize_to_file, deserialize_from_file
import dill
from nn.utils.io_utils import serialize_to_file
... |
#!/usr/bin/env python
# coding=utf-8
import Queue
class Node:
"A Node in the Binary Tree"
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def addLeft(self, N):
self.left = N
def addRight(self, N):
self.right = N
def breathFirs... |
# This is an example feature definition file
import os
import pandas as pd
from datetime import timedelta, datetime
from feast import (
Entity,
FeatureView,
Field,
FileSource,
RequestSource,
ValueType,
)
from feast.on_demand_feature_view import on_demand_feature_view
from feast.types import Flo... |
from contextlib import suppress
from typing import Any, Callable, Optional
from starlite import WebSocket
from starlite.exceptions import SerializationException, WebSocketDisconnect
from strawberry.schema import BaseSchema
from strawberry.subscriptions import GRAPHQL_WS_PROTOCOL
from strawberry.subscriptions.protocols... |
import os
import nose.tools
import numpy as np
import skeletonization.skeleton.io_tools as io_tools
from tempfile import TemporaryDirectory
def test_module_dir():
d = io_tools.module_dir()
assert d.endswith('skeleton'), d
def test_module_relative_path():
nose.tools.assert_equals(
io_tools.modu... |
'''
Function:
Implementation of SemanticFPN
Author:
Zhenchao Jin
'''
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
from ..base import FPN, BaseSegmentor
from ...backbones import BuildActivation, BuildNormalization
'''SemanticFPN'''
class SemanticFPN(BaseSegmentor):
... |
#导入paramiko包
import paramiko
#导入StringIO模块
from io import StringIO
'''
Paramiko包含两个核心组件:SSHClient和SFTPClient。
SSHClient的作用类似于Linux的ssh命令,是对SSH会话的封装,该类封装了传输(Transport),通道(Channel)及SFTPClient建立的方法(open_sftp),通常用于执行远程命令。
SFTPClient的作用类似与Linux的sftp命令,是对SFTP客户端的封装,用以实现远程文件操作,如文件上传、下载、修改文件权限等操作。
'''
'''
Paramiko中... |
import os
import shutil
import numpy as np
import cv2 as cv
from mxnet.tools import im2rec
root_path = './train_dir/'
train_ds_path = './valid_ds'
test_ds_path = './test_ds'
valid_ds_path = './train_ds'
def show(label, image_file):
image_path = os.path.join(root_path, label, image_file)
image = cv.imread(i... |
x = {'a':30, 'b':20, 'c':50}
for i in x: # x에서 key만 가져온다
print(i)
print('================')
for i in x:
print(i, ":", x[i])
print('================')
for i in x.keys(): # x에서 key만 갖고 온다
print(i, ":", x[i])
print('================')
for i in x.values(): # x에서 key만 갖고 온다
print(i)
print('==... |
# Модуль ввода данных
def get_input():
EF1 = float(input("введите значения жесткостей элементов: " + "\n" + "EF1 = "))
EF2 = float(input("EF2 = "))
EF3 = float(input("EF3 = "))
C1 = float(input("введите значения жесткостей пружин: " + "\n" + "C1 = "))
C2 = float(input("C2 = "))
F1 = float(input(... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
''' Phase Correlation based image matching and registration libraries
'''
__author__ = "Yoshi Ri"
__copyright__ = "Copyright 2017, The University of Tokyo"
__credits__ = ["Yoshi Ri"]
__license__ = "BSD"
__version__ = "1.0.1"
__maintainer__ = "Yoshi Ri"
__email__ = "yoshiyoshide... |
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
# class NestedInteger:
# def isInteger(self) -> bool:
# """
# @return True if this NestedInteger holds a single integer, rather than a nested list.
# ""... |
'''
Simulate rounds of Rock, Paper, Scissors
'''
from abc import ABC, abstractmethod
import getopt
import random
import sys
import os
import matplotlib.pyplot as plt
import argparser as ap
_ROCK = 0
_SCISSOR = 1
_PAPER = 2
_RAND = 0
_SEQ = 1
_HIST = 2
_FREQ = 3
_OTP = 4
class Player():
'''
Class representi... |
# file: longestSubstring.py
# author: Marc Kennedy
# Program that prints the longest substring of s in which the letters occur in
# alphabetical order.
def longestSubstring(s):
'''(str) -> None
Finds the longest substring of s in which the letters occur in alphabetical
order.
>>> longestSubstring('zyxw... |
from mulTwoFractions import mulTwoFractions
def divTwoFractions(n1,d1,n2,d2):
r1 = n1 * d2
r2 = n2 * d1
return (r1,r2)
|
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import os
import scipy
from scipy import stats
import statsmodels.formula.api as smfrmla
import statsmodels.api as sm
import xml.etree.ElementTree as ET
import statsmodels.sandbox.stats.multicomp as multicomp
import glob
from s... |
a = (True or (2 == 1 + 2)) == True
print(a)
print(2==1 + 2)
print(False * 6)
print(False == 0)
print(4 == 7)
print(2 < 3 > 1, 2 < 3 == 5)
print("_________\n")
print(True == True != False)
print(1 < 2 < 3 < 4 < 5)
print ((1 < 2 < 3) and (4 < 5))
print(1 < 2 < 4 < 3 < 5)
print( (1 < 2 < 4) and (3 < 5)) |
import logging
import glob
import numpy as np
import argparse
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
# from keras.optimizers import RMSprop
from keras import optimizers as opt
from keras.layers.normalization i... |
# pdteco3.py
# An implementation of the core TECO functionality
# in Python.
# This code is released to the public domain.
# "Share and enjoy....." ;)
from yeanpypa import *
import sys, math, curses, curses.ascii, string, os
|
import json
import uvicorn
from aiohttp import ClientSession
from examples.central_system.routers.v16.provisioning_router import (
router as v16_provisioning_router,
)
from examples.central_system.routers.v201.provisioning_router import (
router as v201_provisioning_router,
)
from ocpp_asgi.app import ASGIApp... |
# -*- coding: utf-8 -*-
import scrapy
from ..items import SamplescraperItem
class QuotesSpider(scrapy.Spider):
name = "quotes"
allowed_domains = ["quotes.toscrape.com"]
start_urls = ['http://quotes.toscrape.com/']
def parse(self, response):
items = SamplescraperItem()
for q in respons... |
# Generated by Django 3.1.3 on 2020-11-28 20:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('instaladores', '0004_merge_20201128_1647'),
]
operations = [
migrations.AlterField(
model_name='instaladores',
name=... |
from django.test import TestCase
from .views import is_public_holiday, get_business_seconds
import datetime
class BusinessSeconds(TestCase):
def test_is_public_holiday(self):
"""Tests that a given date is a public holiday"""
self.assertEqual(is_public_holiday(2021-1-1), True)
def test_get_bu... |
from django import template
register = template.Library()
## Builtin
from urllib import parse
@register.simple_tag(takes_context = True)
def url_replace(context,**kwargs):
query = context['request'].GET.dict()
query.update(kwargs)
return parse.urlencode(query) |
import unittest
import os
import configparser
import serial
import time
import socket
import queue
from datetime import datetime
class BaseCommunicator():
def write(self, items):
raise NotImplementedError()
def read(self):
raise NotImplementedError()
def close(self):
raise NotImp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.