text stringlengths 38 1.54M |
|---|
from abc import ABC
from typing import *
class AbstractBank(ABC):
def reload(self):
raise NotImplementedError
def save(self):
raise NotImplementedError
T = TypeVar('T')
K = TypeVar('K')
V = TypeVar('V')
class AbstractStorage(MutableMapping[K, V], Generic[K, V, T], ABC):
def set_value(self,... |
import numpy as np
from scipy.stats import chisquare
import pandas as pd
import csv
import re
import os
def normalize_text(text):
text = text.lower()
text = re.sub("[^A-Za-z0-9\s]", "", text)
return text
def normalize_values(text):
text = re.sub("[^A-Za-z0-9\s]", "", text)
try:
text = in... |
import sys,os
import numpy as np
import sklearn
import csv
from util import *
from weka.classifiers import Classifier
from weka.core.converters import Loader
import weka.core.jvm as jvm
if not jvm.started:
jvm.start()
"""
http://www.cs.waikato.ac.nz/ml/weka/mooc/dataminingwithweka/transcripts/Transcript3-5.txt
M... |
import logging
from fileinput import filename
from pathlib import Path
import click
from gammapy.scripts.download import progress_download
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
BASE_URL = "https://github.com/gammapy/gammapy-data/raw/v1.0/"
PATH = Path(__file__).parent.parent
PATH... |
# from __future__ import unicode_literals, print_function, division
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from data_util.config import Config
from numpy import random
from data_util.logging import logger
import numpy ... |
import pickle
import numpy as np
from agent_code.big_bertha_v1.parameters import (BATCH_SIZE,
EXPERIENCE_BUFFER_SIZE_MAX,
STATE_SHAPE)
class ExperienceBuffer(object):
def __init__(self):
self.size = EXPERIEN... |
#!/usr/bin/env python
import sys
import shutil
import json
#constant names in template
AWARD_TYPE_STR = "typeOfAward"
RECIPIENT_NAME_STR = "awardeeName"
AWARD_DATE_STR = "awardedDate"
USER_NAME_STR = "authorizerName"
SIGNATURE_NAME_STR = "signatureFileName"
def templateSwitch(number):
constDict = {
0: AWARD_TYPE_... |
#Euler Problem 1 test
import unittest
import problem1
class TestProblem1(unittest.TestCase):
def test_multiples_of_3_and_5(self):
self.assertEqual(problem1.sum_multiples_of_3_and_5(2), 0)
self.assertEqual(problem1.sum_multiples_of_3_and_5(3), 0)
self.assertEqual(problem1.sum... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'loginLayout.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets, uic
from PyQt5.QtWidgets import QMessageBox
#from reglay impor... |
# !/usr/bin/env python
# coding=utf-8
import sqlite3
import sys
import os
import tushare as ts
try:
# 打开数据库连接
db = sqlite3.connect('stock.db')
except:
print('Error when Connecting to DB.')
sys.exit()
cursor = db.cursor()
'''
stockList=['600895','603982','300097','603505','600759']
for code in stockList:... |
import datetime
import logging
from rest_framework import status
from rest_framework.generics import ListAPIView, ListCreateAPIView,\
RetrieveUpdateDestroyAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from jogs.managers.jog_manager import JogManager
fr... |
class Solution(object):
lowIndex = 0
maxLen = 0
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
for i in range(len(s)):
self.extendPalindrome(s, i, i)
self.extendPalindrome(s, i, i + 1)
return s[self.lowIndex: self.low... |
#!/usr/bin/env python
import yaml
import sys
def make_verilog_wrapper(yamlData, outStream):
# Initial sanity checking
if "module_name" not in yamlData:
print >> sys.stderr, "'module_name' key not found, aborting"
return
if "wrapper_name" not in yamlData:
print >> sys.stderr, "'wrapper_name' key not found. Ab... |
import End_Game
import MUSIC_GAME_FINAL
import MUSIC_GAME_FINAL2
import SCORE_DISPLAY
import End_Game
import Def
import Control
#SONG_INFO = ['GUEST', 1700, 25, 'VIRUS.ogg', 'VIRUS', 22000, 1, 1, 5, 50, 'white',99999999,8,51010]
SONG_INFO = ['jack', 4500, 'HELL', 85, 537600, 281, 10, 1000, 'VIRUS.ogg', 'VIRUS',... |
def comp(x, y):
l = len(x)
c = 0
for i in x:
if x[i] == y[i]:
c += 1
if c == l:
return True
return False
n, m = input().split()
n = int(n)
m = int(m)
di = dict()
for i in range(m):
di[str(i + 1)] = False
x = input().split()
x.__delitem__(0)
for i ... |
from tkinter import *
class menuApp:
def __init__(self,master):
self.master = master
self.backFrame = Canvas(master,bg='black',height=700,width=1000)
self.backFrame.pack()
master = Tk()
master.geometry('1000x700')
Menu = menuApp(master)
mainloop()
|
# -*- coding: utf-8 -*-
# @Author: yancz1989
# @Date: 2016-05-12 11:37:37
# @Last Modified by: yancz1989
# @Last Modified time: 2016-05-12 11:37:37
|
import glob
from subprocess import Popen, PIPE
import os
pdfs = ['/Volumes/JetDrive/pdfs/0070001000.pdf']
def parse_pdf(path):
with open(path, 'rb') as fp:
ps2ascii = Popen(['ps2ascii'], stdin=PIPE, stdout=PIPE,
stderr=PIPE, shell=True)
ps2ascii.stdin.write(fp.read())
ps2... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
import scrapy
class Thesis(scrapy.Item):
title = scrapy.Field()
author = scrapy.Field()
advisor = scrapy.Field()
yearpub = scrapy.Field()
publish... |
# While statement demo
import sys
def demo1():
while True:
print("Who are you?")
name = input()
if name != "Joe":
continue
print("Hello, Joe. What's the password?")
password = input()
if password == "swordfish":
break
print("Access grante... |
import tensorflow as tf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import datetime
# Get data
data = pd.read_csv('data/train.csv', encoding='utf-8')
data = data.drop(['Id', 'Alley'], axis=1)
data_categoric = data.select_dtypes(include=['... |
import json
import sys
if __name__ == "__main__" :
if len(sys.argv) < 2 :
print("To few arguments.\nFormat : plot.py json_file");
exit(0);
data = json.load(open(sys.argv[1]));
print("HOT")
for entry in data :
print(entry['hot_keys']);
print("WARM")
for entry i... |
from urllib.parse import parse_qs
class HTTPRequest:
def __init__(self, scope: dict, body: bytes) -> None:
self.method = scope['method']
self.path = scope['path']
self.query = parse_qs(scope['query_string'], encoding="utf-8")
self.query = { key.decode(): [value.decode() for value i... |
"""Test the output-spaces parser."""
from collections import OrderedDict
import pytest
from .. import utils as u
TEST_TEMPLATES = (
'MNI152NLin2009cAsym',
'MNIInfant',
'MNI152NLin6Asym',
)
def test_output_spaces(monkeypatch):
"""Check the --output-spaces argument parser."""
with monkeypatch.cont... |
# this is a script to calculate the derivation of a polynom with non negativ exponents
# input = raw_input()
input = {
0 : 9,
1 : 2,
2 : 4,
4 : 7,
}
output = {}
def nDerive(input):
for x in input:
if x < 0:
print "only non-negativ exponents allowed"
return False
elif x == 0:
y = 0
else:
y = x -... |
# -*- encoding: utf-8 -*-
from django import forms
from libs.default.core import BaseForm
from modules.entidade.models import entidade
from modules.entidade.formularios import MENSAGENS_ERROS
from modules.honorario.models import Contrato, Proventos
from modules.servico.models import Plano
class FormContrato(forms.F... |
import os
import csv
import random
import pandas as pd
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
'''ADD ALL GENES FROM 108 GENBANK FILES INTO LIST.
PULL THE ONES CORRESPONDING TO EACH ORTHOGROUP AND EXPORT IN ONE FASTA.
ALL NEGATIVES GO TO ANOTHER FASTA.'''
photorhab... |
import numpy as np
class warehouse:
def __init__(self):
try:
self.vehicles = np.load('database.npy', allow_pickle=True).item()
except FileNotFoundError:
self.vehicles = {}
try:
self.places = list(np.load('places.npy', allow_pickle=True))
except Fil... |
'''Exercise 3: Write a program that reads a file and prints the letters in decreasing order of frequency. Your program should convert all the input to lower case and only count the letters a-z. Your program should not count spaces, digits, punctuation, or anything other than the letters a-z. Find text samples from seve... |
from django.db import models
from django.apps import apps
from django.utils.timezone import datetime, make_aware, timedelta
from core.constants import (HarvestStages, HARVEST_STAGE_CHOICES, REPOSITORY_CHOICES, DeletePolicies,
DELETE_POLICY_CHOICES)
from core.models.datatypes.dataset import ... |
#!/usr/bin/env python
import itertools
import json
import os
from senti.rand import *
def write_data(in_path, out_path, labels):
with open(out_path, 'w') as out_sr:
for label_name, label in labels.items():
file_names = os.listdir(os.path.join(in_path, label_name))
file_names.sort... |
from django.utils.encoding import force_str
from django.utils.functional import Promise
from sphinx.util.inspect import object_description
def list_or_tuple(obj):
return isinstance(obj, (tuple, list))
def lazy_repr(obj):
if list_or_tuple(obj):
values = []
for item in obj:
values... |
#!/usr/bin/python
#Using Gradient Descent calculate aT and b in loss function for Binary Classification
trainingSetX = []
trainingSetY = []
length = 0
#initialize data for our program
def init_data():
global trainingSetX,trainingSetY,length
for line in list(map(lambda x:x.strip(),open("perceptron.data").readl... |
import sys
class Employee:
def __init__(self):
self.num = 0
self.salary = 0
self.name = ''
self.next = None
findword = 0
namedata = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
data = [[1001, 22222], [1002, 23451], [1003, 32456], [1004, 45678], [1005, 43214], [1006, 23332], [1007, 25552... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django_services import admin
from ..service.parameter import ParameterService
from ..forms.parameter import ParameterForm
class ParameterAdmin(admin.DjangoServicesAdmin):
form = ParameterForm
service_class = ParameterService... |
"""url_shortener URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class... |
'''
https://docs.python.org/3/library/concurrent.futures.html
'''
import time
import shutil
import requests
import math
import concurrent.futures
from concurrent.futures import Executor, ThreadPoolExecutor, ProcessPoolExecutor
def sample_test():
with ThreadPoolExecutor(max_workers=1) as executor:
future ... |
nums = [7, 3, 4, 2, 8, 5]
def bubbleSort(arr):
switched = True
while switched:
switched = False
for i, num in enumerate(arr):
if i >= 1:
if num < arr[i - 1]:
temp = num
arr[i] = arr[i - 1]
arr[i - 1] = temp
switched = True
return arr
print(bubbleSort... |
import torch
import torch.nn as nn
from torchvision import models
import numpy as np
from blocks import ResidualBlock, DownSamplingBlock, Block
from attention import SelfAttention
class AttentionDiscriminator(nn.Module):
def __init__(self, image_channels = 3, features = [64, 128, 256, 512]):
super().__in... |
from copy import deepcopy
def de_replace(d, ab):
m[d] = mm[d]
def replace(d, ab):
global W
m[d] = [ab] * W
def dfs(cnt, start):
global D, W, K, result
if cnt >= result:
return
if check():
if cnt < result:
result = cnt
return
for i in range(start + 1,... |
#!/usr/bin/python3
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 9000
sock.connect((host, port))
msg = sock.recv(1024)
sock.close()
print(msg.decode('ascii'))
|
from workfront.objects.generic_object_param_value import WFParamValuesObject
import workfront.objects.portfolio
from workfront.objects.codes import WFObjCode
def create_new(wf, params={}):
'''
:param params: dict of details for new project (must have: name,
portfolioID)
:return: Object of the new prog... |
from models.relations.learns import Learns_Relation
from models.course.courses import Course
from models.relations.student_group_relation import StudentGroupRelation
from models.relations.group_course_relation import GroupCourseRelation
from models.user.students import Student
from models.user.users import User
from mo... |
import attr
import service_configs
import shortuuid
@attr.s()
class Contact(object):
name = attr.ib()
service_names = attr.ib()
key = attr.ib()
image = attr.ib(default='')
def to_dict(self):
return {
'name': self.name,
'image': self.image,
'key': self.ke... |
import re
import json
pattern = '[鄉|市|鎮|區]'
theater_info_slots = [ 'theater_address', 'theater_phone', 'theater_website' ]
def read_loc():
filename = './raw_data/loc.dict'
dic = {}
with open(filename, 'r') as f:
for row in f:
row = row.strip().split(' ')
key = row[0]
... |
import base64
from captcha.image import ImageCaptcha
from django.conf import settings
from django.utils.crypto import get_random_string
def generate_captcha():
return settings.CAPTCHA \
if hasattr(settings, 'CAPTCHA') \
else get_random_string(length=4)
def encode_captcha_image_base64(captcha: s... |
"""
Environment for Behave Testing
"""
import os
from behave import *
from selenium import webdriver
BASE_URL = os.getenv('BASE_URL', 'http://localhost:5000')
def before_all(context):
""" Executed once before all tests """
# Set headless chrome options
options = webdriver.ChromeOptions()
options.binar... |
from torch.nn import Module
import torch
import torch.nn.functional as F
class FeedForward(Module):
def __init__(self,
d_model: int,
d_hidden: int = 512):
super(FeedForward, self).__init__()
self.linear_1 = torch.nn.Linear(d_model, d_hidden)
sel... |
# -*- coding: utf-8 -*-
#
# @reference:
# https://api.slack.com/incoming-webhooks
# https://api.slack.com/tools/block-kit-builder
# https://yq.aliyun.com/articles/64921
#
"""
{
"push_data": {
"digest": "sha256:14bf0c9f45293f4783bd75e51ea68689103k89da6e51db75ef30b8564fe8d3cc",
"pushed_at": "201... |
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Survey(models.Model):
STATUS_CHOICES = [
("Active", "Active"),
("Closed", "Closed"),
]
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=... |
# from __future__ import absolute_import
#
# from itdtool.celeryapp import app
# # from lxml import etree
# # import xmltodict
# import sys
# # from passlib.hash import md5_crypt
# from django.conf import settings
#
#
#
# # @app.task
# def get_query_params_id(id):
#
# from itdtool.models import QueryParameters
# ... |
from django.shortcuts import render
from .models import Property, Category
from .forms import ReserveForm
from django.db.models import Q
def property_list(request):
property_list = Property.objects.all()
template = 'property/list.html'
address_query = request.GET.get('q')
property_type = request.GET.g... |
#use with python3
import shlex, subprocess
import paramiko
import os
import time
import yaml
from mapping import Testbed_Tools
t = Testbed_Tools()
dir_path = os.path.dirname(os.path.realpath(__file__))
pid_host = []
with open("config.yaml", "r") as ymlfile:
mapping_yaml = yaml.safe_load(ymlfile)
def convert... |
people = []
for T in range(int(input())):
w, h = map(int, input().split(' '))
people.append((w, h))
for i in people:
cnt = 1
for j in people:
if i[0] != j[0] and i[1] != j[0]:
if i[0] < j[0] and i[1] < j[1]:
cnt += 1
print(cnt, end = ' ') |
# --------------------------------------------------------
# Tensorflow Faster R-CNN
# Licensed under The MIT License [see LICENSE for details]
# Written by Zheqi He, Xinlei Chen, based on code from Ross Girshick
# --------------------------------------------------------
from __future__ import absolute_import
from __fu... |
import abc
class RequestData(metaclass=abc.ABCMeta):
"""请求信息"""
pass
class FriendRequestData(RequestData):
"""加好友请求"""
def __init__(self, user_id, comment):
self.user_id: str = user_id
self.comment: str = comment
class JoinGroupRequestData(RequestData):
"""加群请求 - 自己是管理员"""
... |
"""
A collection of prime-number related functions
"""
import math
import itertools as it
def nth(iterable, n, default=None):
from itertools import islice
"Returns the nth item or a default value"
return next(islice(iterable, n, None), default)
def erat3( ):
D = { 9: 3, 25: 5 }
yield 2
yiel... |
import consistihash.hasher
from consistihash.hasher import long_hash, short_hash
def new(**kwargs):
return hasher.Balancer(**kwargs)
|
#!/usr/bin/python
"""
this file is used to shift all files in current directory with extension .jpg
to the folder s3_files
"""
import os
import shutil
# make sure that these directories exist
path='/home/ec2-user/MajorProject/ec2_files/'
dir_src = '/home/ec2-user/'
dir_dst = path+"s3_files/"
for file in os.listdir(... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class ParticipantInfoDTO(object):
def __init__(self):
self._name = None
self._participant_id = None
self._participant_id_type = None
@property
def name(self):
r... |
import tkinter
"""
Variables de control:
IntVar()
DoubleVar()
StringVar()
BooleanVar()
"""
ventana = tkinter.Tk()
ventana.geometry("250x250")
x = tkinter.IntVar()
x.set(value=1) # marcar la opcion uno por defecto
def actualizar_valor(valor):
# pintamos el valor del radiobutton en un label
val... |
from rest_framework.test import APITestCase
from django.test import TestCase
from django.contrib.auth import get_user_model
from django.urls import reverse
from .models import Community, Membership
from .extauth import community_membership_extauth
from dpauth.models import Username
class CommunityJoinTests(APITestC... |
import numpy as np
import matplotlib.pyplot as plt
X = np.array([[5,3],
[10,15],
[15,12],
[24,10],
[30,30],
[85,70],
[71,80],
[60,78],
[70,55],
[80,91],])
print(X)
from sklearn.cluster import AgglomerativeClustering
cl=AgglomerativeClustering(n_clusters=4,affinity="eu... |
import numpy as np
def local_ls(x, y, k, center=None, const=True):
"""
Desc: Execute the Local weighted least square linear regression
Parameters:
x: A matrix contain explanatory variables. m row and n col means m observation and n features.
y: A column vector contain dependent variabl... |
import sys
import signal
from threading import Thread, Lock, Condition
import socket
import pickle
import datetime
import time
import random
import signal
import Queue as Q
import copy
# Dictionary of port and socket for each node
client_connections = {}
go_go_go = False
count = 0
min_delay = 0
max_delay = 0
cv = Co... |
# -*- coding: utf-8 -*-
"""
@Time : 2020/7/13 14:36
@Author : QDY
@FileName: 567. 字符串的排列_滑动窗口.py
给定两个字符串 s1 和 s2,写一个函数来判断 s2 是否包含 s1 的排列。
换句话说,第一个字符串的排列之一是第二个字符串的子串。
示例1:
输入: s1 = "ab" s2 = "eidbaooo"
输出: True
解释: s2 包含 s1 的排列之一 ("ba").
示例2:
输入: s1= "ab" s2 = "eidboaoo"
输出:... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import math
var = dir(math)
print 'math = ',var
import cmath
var1 = dir(cmath)
print 'cmath = ',var1
print cmath.sqrt(-1),cmath.sqrt(9),cmath.sin(1),cmath.log10(100)
import random
list = [111,'sfdf','aaa',444]
random.shuffle(list)
print list
print random.choice(range(1,100))
... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution(object):
def verticalOrder(self, root):
"""
:type root: TreeNode
:rtype: Lis... |
from flaskr.auth.login import Login
from flaskr.auth.logout import Logout
from flaskr.auth.register import Register
__all__ = [
'Login',
'Logout',
'Register',
]
|
from setuptools import setup, Extension
from torch.utils import cpp_extension
from torch.utils.cpp_extension import BuildExtension, CUDAExtension, CppExtension
setup(name='cpp_extensions',
ext_modules=[
CUDAExtension(name='plugins',
sources=['bindings.cpp'],
... |
class Solution(object):
def partitionLabels(self, S):
"""
:type S: str
:rtype: List[int]
"""
d={}
for i in S:
if i in d:
d[i]+=1
else:
d[i] = 1
ans = []
while True:
l = len(d)
curmin_key = min(d)
... |
# count = 0
# while count < 10:
# # print(count<=10)
# print("Count on", count)
# #count = count+1
# count +=1
#
# print("Tultiin kymppiin")
#
#
while True:
syote = input("Anna syöte>")
if syote =='q':
print("lopetetaan")
break
# exit(0)
print("antamasi syöte:",sy... |
t=int(input())
for i in range(t):
n,m=map(int,input().split(" "))
if((n*m)%2==0):
print('Yes')
else:
print('No')
|
import keras
from pathlib import Path
import cv2
import numpy as np
import random
class DataGenerator(keras.utils.Sequence):
def __init__(self, path, batch_size, input_size, permutations=False):
self.index = 0 # Indicates the current input
self.paths, self.x_paths, self.y_paths = self.loadPaths(p... |
from bokeh.plotting import figure
from bokeh.io import export_png
import numpy as np
from scipy.stats import norm
f=np.vectorize(lambda x: 0 if x<-20 or x>100 else 1)
x=np.linspace(-40,120,100)
y=f(x)/120
f=figure(title='Prior distribution on temperature',toolbar_location=None)
f.line(x,y,line_width=3)
export_png(f,f... |
import argparse
import json
import requests
import io
import os
import sys
CROMWELL_SERVER_URL = 'http://{ip}:{port}'
API_VERSION = 'v1'
QUERY = 'query'
SUBMIT = 'submit'
ABORT = 'abort'
# These parameters are unlikely to change often unless Cromwell spec changes.
DEFAULT_CONFIG = {
'submit_endpoint' : '/api/w... |
import numpy as np
from sklearn import preprocessing
from datetime import datetime
import sys
def readentry(line):
temp = line.rstrip().split(",")
return float(temp[1]), float(temp[2]), float(temp[3]), float(temp[4])
def gettime(line):
temp = [int(i) for i in line.split(" ")[0].split("-")+line.split(" ")[... |
import tkinter as tk
import requests
from AppLogic import AppLogic, HTTPBearerAuth
import requests
class CreatePage(tk.Frame):
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
tk.Label(self, text="Name: ").grid(row=0, column=0)
self.name_entry = tk.Entry(self)
... |
from statistics import mean
from scipy import stats
Estimate=[15,51,5,45,455,42,424,654,245,456,999,888,777,55,44,66,22,44,885,456,951,753,159,852,789,654,123,369,258,147,305]
Estimate.sort()
m=stats.trim_mean(Estimate,0.1)
print(m) |
def solution(stairs, index=0):
if index == len(stairs):
return 0
curr_sum = 0
for i in range(index):
if stairs[i] < stairs[index]:
curr_sum += stairs[i]
return curr_sum + solution(stairs, index + 1)
t = int(input())
for _ in range(t):
n = int(input())
stairs = lis... |
#!/usr/bin/env python3
import argparse
import glob as gb
import json
import logging
import os
import os.path as op
import re
import readline
import shutil
import socket
import subprocess
import sys
import tempfile
import time
import traceback
from cmd import Cmd
from contextlib import contextmanager
from datetime impo... |
import numpy as np
import pandas as pd
from pandas import DataFrame
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier,RandomForestRegressor,AdaBoostClassifier,AdaBoostRegressor
from sklearn.linear_model import LogisticRegressio... |
# Basic libs
import pickle
# PLY and OFF reader and MAT
import scipy.io as sio
from utils.off import *
# OS functions
from os.path import exists, join
# Subsampling extension
import cpp_wrappers.cpp_subsampling.grid_subsampling as cpp_subsampling
def downsample_data(dataset, subsampling_parameter):
"""
Sub... |
#!/usr/bin/env python3
# This program reads in a csv file of temp data and creates a plot.
# Usage:
# ./plottempdata.py kaittempdata konktempdata outfilename
import sys
import csv
import numpy as np
import matplotlib.pyplot as plt
def gettempdata(filename):
mjd = []
temp = []
temperr = []
with open(s... |
import os
from typing import Callable
import functools
import yaml
import httpx
async def server_lookup_flag(server_url, application_identity, flag_name):
async with httpx.AsyncClient() as client:
# TODO: Something about auth
url = f"{server_url}/{application_identity}/flags/{flag_name}"
... |
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as st
# 产生10000个服从标准正态分布的随机数
w = np.random.standard_normal(10000)
figure = plt.figure()
plt.plot(w,linestyle="-")
#plt.show()
# 绘制直方图
figure = plt.figure()
plt.hist(w,bins=100, density=True)
# 绘制(-3,3)范围内的标准正态分布曲线
dist = st.norm(loc=0,scale=1)
x ... |
# -*- coding: utf-8 -*-
from setuptools import setup
import powerbi_push_datasets
setup(name='powerbi-push-datasets',
version=powerbi_push_datasets.__version__,
description='Power BI Push Datasets Mgmt',
long_description=powerbi_push_datasets.__doc__,
keywords=("PowerBI", "Push", "Datasets", "... |
'''Train DNNs via PyTorch.'''
import torch
import torch.nn as nn
from torch.utils.tensorboard import SummaryWriter
import torch.optim as optim
import torch.backends.cudnn as cudnn
from torchsummary import summary
from typing import Tuple, Any, Dict
import copy
import numpy as np
import json
import os
import argparse
fr... |
a = float(input("digite o coeficiente a: "))
b = float(input("digite o coeficiente b: "))
raio = float(input("digite o raio : "))
if(a > 0):
if(b > 0):
print("Superiores")
if(b < 0) :
print("Inferiores")
if(a < 0):
if(b > 0):
print("Superiores")
if(b < 0):
print("Inferiores") |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... |
"""
author: Yernat M. Assylbekov
email: yernat.assylbekov@gmail.com
date: 08/10/2020
"""
import numpy as np
import tensorflow as tf
from model import Generator, Critic, loss_generator, loss_critic, create_generator, create_critic
from utils import read_preprocess_images, print_save_images
from IPython import display
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-05-01 18:31
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('app', '0023_merge_20180501_1157'),
]
operations =... |
#!python
"""
Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
Triangle Tn=n(n+1)/2 1, 3, 6, 10, 15, ...
Pentagonal Pn=n(3n−1)/2 1, 5, 12, 22, 35, ...
Hexagonal Hn=n(2n−1) 1, 6, 15, 28, 45, ...
It can be verified that T285 = P165 = H143 = 40755.
Find the next triangle nu... |
# my_vector
class Vec2:
x = 0.0
y = 0.0
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
msg = "(" + str(self.x) + "," + str(self.y) + ")"
return msg
def __add__(self, other):
return Vec2(self.x + other.x, self.y + other.y)
... |
import logging
from client.commands.command import Command
from client.utils.discord_embed import error_embed, success_embed, informational_embed
VALID_COMMANDS = ["setprefix"]
class SetPrefix(Command):
def __init__(self):
super().__init__(VALID_COMMANDS)
async def execute(self, message_dispatch... |
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from rest_framework_simplejwt.tokens import RefreshToken
from .models import GeoLocation
from django.contrib.auth.models import User
class GetAllGeoLocationsTest(APITestCase):
def setUp(self):
s... |
name = "Hilary"
country = "USA"
age = 35
hourly_wage = 100
satisfied = True
daily_wage = hourly_wage * 8
print("The new employee is " + name + " and she is " + str(age)+ ". Her daily wage is " + str(daily_wage) + ".")
print(f"Satisfied: {satisfied}") |
import flask, json
from domino.core import log
class Response:
def __init__(self, application, request):
self.application = application
self.request = request
self.account_id = self.request.args.get('account_id')
def get(self, name):
return self.request.args.get(name)... |
# -*- coding: utf-8 -*-
import scrapy
from scrapy import Spider,Request
import json
from zhihuuser.items import UserItem
#1.选定开始人
#2.开始人的关注列表,和粉丝列表
#3.获取列表用户信息,性别。。介绍
#4.获取开始人的粉丝的关注列表(循环往复)
class ZhihuSpider(Spider,Request):
name = 'zhihu'
allowed_domains = ['www.zhihu.com']
start_urls = ['http://www.zhih... |
#IST 440 Penn State Abington
#Professor: Joseph Oakes
#Fall 2016
#Controller.py
#Author: Nirav,Jacky,Mo
# displayTemp.py reads the tempertaure from the sensor which is attached to raspberry pi and sends the data to client
# via Bluetooth Socket connection.It also read the outside temperature and humidity through a API... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.