text stringlengths 38 1.54M |
|---|
# Copyright (c) 2016-2023 Kirill 'Kolyat' Kiselnikov
# This file is the part of chainsyn, released under modified MIT license
# See the file LICENSE.txt included in this distribution
"""Main module of chainsyn"""
import os
import datetime
import curses
import re
import config
from core import processing, tools
def... |
import threading
def funcao_da_thread():
print("Thread working")
if __name__ == "__main__":
thread1 = threading.Thread(target = funcao_da_thread, args = ())
thread1.start()
|
import pika
import json
class PikaClient(object):
def __init__(self, log, conf):
#self.io_loop = io_loop
self.connected = False
self.connecting = False
self.connection = None
self._channel = None
self.server_host = conf.get('amqp_ho... |
# visualization Config
config = {
"physical_gpu_id": 0,
"dtype": "fp32",
"num_classes": 2,
"data_type": "image", # option: image or video
"data_dir": "", # folder path where jpg/png/avi/mp4 is
"img_step": 1,
"ckpt_id": 400000,
"vis_result_dir": "vis",
}
|
# Generated by Django 3.1.5 on 2021-04-14 18:25
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('network', '0003_likes_post'),
]
operations = [
migrations.RenameField(
model_name='likes',
old_name='post',
new_... |
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 25 14:37:54 2019
@author: pabde
"""
import webbrowser
import requests
import bs4
import urllib
#Define your keyword of interest
keyword = "influenza"
#Define the string indicator for a PDF in the source code
PDFstring = "/track/pdf"
#Create empty global array to hold ... |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from torchvision.utils import make_grid
import torch
from Models.rawConvNet import Model
def visualizeKernels(path_weights='../weights/TL_best_weights.pt', use_trained_weights=True):
sns.set()
cmap="viridis"
example_mat = np.linsp... |
import json
from datetime import datetime
with open('Q3/invent_list.json') as json_read:
data = json.load(json_read)
# Items on meeting room
def item_meet_room():
room = 'Meeting Room'
item_list = []
for datas in data:
if datas['placement']['name'] == room:
item_list.append(datas[... |
from server.equipment import Equipment,Item
from server.character import Player
import server.constants as constants
import random
players = []
for i in range(0,100):
player = Player()
player.set_name(constants.names[random.randint(0,len(constants.names)-1)])
for j in range(0,100):
player.level_up... |
import datetime
import math
import re
from django.utils.html import strip_tags
def count_words(html_string):
#html_string =""" <h> This is word coutn </h> """
word_string = strip_tags(html_string)
matching_list = re.findall(r'\w',word_string)
count = len(matching_list) #here count the word
return count
def ... |
import os
import random
from bottle import route, run
from sayings import beginnings, subjects, verbs, actions, ends
def generate_message():
# return "Сегодня уже не вчера, ещё не завтра"
return ' '.join([
beginnings[random.randrange(8)],
subjects[random.randrange(8)],
verbs[random.randrange(8)], ... |
# -*- coding: utf-8 -*-
import requests
headers = headers = {
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36"
}
res = requests.get('https://www.job1001.com/SearchResult.php?page=37&&parentName=&key=®ion_1=®ion_2=®ion_3=&keytypes=&jtzw=%... |
from os.path import dirname, abspath
import os
import random
import shutil
class File_Manager:
dir_to_watch = dirname(dirname(abspath(__file__)))
def file_manage(self):
obj = os.scandir(self.dir_to_watch)
for entry in obj:
if entry.is_file():
print("file cr... |
import flask
from flask import request, jsonify, make_response
import random
import socket
import json
app = flask.Flask(__name__)
app.config["DEBUG"] = True
quotes = [
{'id': 0,
'quotation': 'It is not only what you do, but also the attitude you bring to it, that makes you a success.',
'author': 'Don S... |
# Copyright (c) Jeremías Casteglione <jrmsdev@gmail.com>
# See LICENSE file.
from bottle import response, HTTPError, request, HTTP_CODES
from _sadm import log
__all__ = ['init', 'error']
def _handler(code, error):
log.debug("handler %d" % code)
log.debug("%d - %s" % (error.status_code, error.status_line))
argsLe... |
#######Problema 3
#from functional import seq
list = [1, 21, 75, 39, 7, 2, 35, 3, 31, 7, 8]
if __name__ == '__main__':
#seq(list)\
# .filter(lambda x:x>4)
#Eliminarea elementelor mai mici decat 5
for a in list :
if a < 5:
list.remove(a)
print(list)
#... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 17 18:49:38 2018
@author: dell
"""
from tkinter import *
import qjbl
qjbl.bl()
def main2(x):
def fun1():
import main3x1
tl = Toplevel()
tl.title('圆锥滚子直线型')
main3x1.func1(x,tl)
def fun2():
import main3x... |
# The code is to implement filter() method
# filter(func, iter) method is used to filter/
# select same element in func & iter
# It returns same element in function and iteration
file_open = open("Advance Functions/filter_sample.txt", "r")
content = file_open.readlines()
friends_list = []
for name in content:
if ... |
class Author:
try:
def __init__ (self, name):
self.name = name
self.books = []#empty list is created to hold books
def publish(self, title):
self.books.append(title)#append () method adds title to book list
def __str__(self):
title = ', '.j... |
# Copyright (c) 2014, 2015 by California Institute of Technology
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice... |
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
# X-Data
N = 200
X = np.random.random(N)
# Geneation Y-data
sign = (- np.ones((N,)))**np.random.randint(2,size=N)
Y = np.sqrt(X) * sign
# Neural network: three hidden layers and ReLU activations
act = tf.keras.layers.ReLU()
nn_sv = tf.ke... |
#!/usr/bin/python
import argparse
from time import perf_counter
t_start = perf_counter()
import pandas as pd
def parquet2csv_io():
"""
routine that gets user inputs
"""
parser = argparse.ArgumentParser(description="""convert parquet files to csv""")
parser.add_argument("-i","--input", default='f... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 31 01:35:46 2018
@author: linux1107pc
"""
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import warnings
#warnings.filterwarnings("ignore")
from sklearn.cluster import DBSCAN
from WeaponLibrary import ... |
# coding: utf8
__author__ = 'kole0114'
import random
import string
from TeacherGolosProject.settings import MACHINE_IP
def create_pass():
token = "".join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for x in range(25))[1:10]
return token
def random_salt():
data=random.ra... |
import os
import numpy as np
from input_processing import data_transformation
symbols = ['alpha', 'beta', 'gamma', 'delta', 'epsilon']
data_path = os.path.abspath(__file__ + '/../../data')
def get_symbol(i):
return symbols[i]
def load_data():
X = 0
y = 0
for i, symbol in enumerate(symbols):
... |
class about_section:
opening_section = """Welcome to the Covid rules generator! We've created a cutting edge tool for devising hoops to
make people jump through, all in the name of pandemic prevention."""
content_qs = ["Have you had a surprise pandemic sprung on you, with only the best... |
"""
Object Tracking Algorithm for PiPlane Goggles
This algorithm works well in landscapes where PiPlane is one of the only objects in the sky, and works even better in low-lighting situations. It is
less robust in environments with multiple agents; however, this is not its intended use. The algorithm is very fast ... |
// https://leetcode.com/problems/largest-number
class Solution(object):
def largestNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
def compare(a,b):
return int(str(a)+str(b)) > int(str(b)+str(a))
for i in range(1,len(n... |
"""
@author: Alfons
@contact: alfons_xh@163.com
@file: WeiboDog.py
@time: 2019/6/24 下午10:41
@version: v1.0
"""
import os
import time
import datetime
import requests
import traceback
from collections import namedtuple
from Base.DogQueue import DogQueue
from Base.DogLogger import GetLogger
from Dogs import DbDog, Emai... |
# T = int(input())
T = 1
for _ in range(T):
inp = 'thisismytext text'
text, pattern = map(lambda x : list(x) , inp.split(' '))
starts = [i for i, x in enumerate(text) if x == pattern[0]]
deleted = 0
for start in starts:
index_text = start
index_pattern = 1
steps = 0
... |
'''
Test dropbox folder operations
'''
import posixpath
from .. import dropboxfile, dropboxfolder
class TestUpdateFolder:
def test_add_files(self, folder_instance, dropbox_file):
folder_instance.update()
assert isinstance(folder_instance.cursor, str)
assert isinstance(folder_instance.fli... |
import pika
import sys
import os
import json
import requests
SERVER_API_KEY = 'wWPBZb7rKryrXLABP62cu2S6WqfSxcaQ'
def get_callback_url(callback_url):
return callback_url + "/api/v1/outbound-calls"
def main():
credentials = pika.PlainCredentials('admin', 'admin')
parameters = pika.ConnectionParameters(
... |
# Program gathers data from a text file (worldserieswinners.txt) and stores the data into a dictionary. There will be two dictionaries where one dictionary will have team name's as a key and the year as the other key
def main():
inputFile = open("WorldSeriesWinners.txt","r");
dataFile = inputFile.readlines();
... |
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen('http://www.pythonscraping.com/pages/warandpeace.html')
bs_obj = BeautifulSoup(html)
name_list = bs_obj.findAll('span', {'class': 'green'})
for name in name_list:
print(name.get_text())
|
import sys
import os
import numpy as np
from scipy import optimize
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
from mpl_toolkits import mplot3d
current_path = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(current_path, '../../'))
from analytical.steady import... |
"""Data loader for Seq2Seq with buckets
Usage:
>>> data_dir = './data'
>>> buckets = [(5, 10), (10, 20), (20, 30), (30, 30)]
>>> data = Data(data_dir, buckets, convlen=2, batch_size=20)
Load 278468 lines
Load 3002 words
Load 63440 convs
>>> data.start_loaders(n=4)
# In each round, call data.get()
>>> a, x, mask = data... |
import json
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from nltk import word_tokenize
from nltk.stem import WordNetLemmatizer
from sklearn.data... |
import torch
import os
import json
import zipfile
import urllib.request
from torch.utils.data import Dataset
from survae.data import TrainValidTestLoader, DATA_PATH
from .vocab import Vocab
class EnWik8(TrainValidTestLoader):
def __init__(self, root=DATA_PATH, seq_len=256, download=True):
self.train = EnW... |
# -*- coding:utf-8 -*-
import logging
import os
import unittest
import hashlib
## 长期备份会产生一些重复文件,此代码遍历目标目录root,记录所有文件的[md5, 尺寸, 路径],并按尺寸降序排序
class FileInfoSpider(object):
def __init__(self, root):
self.root = root
self.data = [] # [[md5, size, path], *]
def calcMd5(self, filePath):
m... |
import math
def DistanceToPoint(position1, position2):
return math.sqrt(pow(abs(position1[0] - position2[0]), 2) + pow(abs(position1[1] - position2[1]), 2))
def DistanceToLine(position, line):
lP1, lP2, p = line[0], line[1], position
if not (lP1[0] == lP2[0] or lP1[1] == lP2[1]):
a = (lP1[1] - lP2... |
import matplotlib as mpl
import matplotlib.pyplot as plt
plt.style.use('classic') #we will change as we move forward
# ------- file: myplot.py ------
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x))
plt.plot(x, np.cos(x))
plt.show()
#if you run this py script, wind... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the maximumToys function below.
def maximumToys(prices, k):
items = 0
expenditure = 0
for price in sorted(prices):
expenditure += price
if(expenditure > k):
expenditure -= price
break... |
# txt = " Hellow world "
# x = txt.strip()
# print(txt)
# print(bool("abc"))
# print(bool(2))
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"color" : "red",
"machine" : "IBM",
"area" : 300,
"type " : "Lamborgini",
"Sit cover" : "black end ",
"road" : "High way",
"Disel" : "100lr"
}
... |
from model.stats import Stats, empty_stats
from presets import preset_stat_name_list, preset_reward_types, preset_reward_display_name
from renpy_functions import shuffle_list
class Reward:
def __init__(self, name, reward_type, stats=None, materials=0, rewards=None, obtainable=True, essential=False):
self.... |
from .GetTKK import getTKK
import time
import ctypes
import requests
class GoogleTranslate():
def __init__(self, sl='', tl='', domainnames=""):
"""
A python wrapped free and unlimited API for Google Translate.
:param sl:from Language
:param tl:to Language
:param domainn... |
import logging
from pylons import request, response, session, tmpl_context as c, url, config
from pylons.controllers.util import abort, redirect
from ppdi.lib.base import BaseController, render
from paste.deploy.converters import aslist
from ppdi.model.meta import Session
from ppdi.model import ModeratorPin, Partic... |
"""
navdoon.collector
-----------------
Define collectors, that collect Statsd requests and queue them to be
processed by the processor.
"""
import os
import socket
from socket import socket as SocketClass
from abc import abstractmethod, ABCMeta
from threading import Event
from navdoon.pystdlib.queue import Queue
from... |
# Generated by Django 2.0.6 on 2018-06-30 16:58
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cm', '0012_auto_20180630_1341'),
]
operations = [
migrations.AlterField(
model_name='party',
... |
"""Game Bug's Labirint."""
from random import randint, random
import pygame
import sys
import time
WIN_WIDTH = 1500
WIN_HEIGHT = 1000
WALL_WIDTH = 30
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
LOSE_TEXT_COLOR = (200, 20, 20)
START_TEXT_COLOR = (0, 139, 139)
WIN_TEXT_COLOR = START_T... |
"""
Find the pairs of numbers that add to k
"""
def sum(arr, k):
diff_dict = {item:k-item for item in arr}
for k, v in diff_dict.iteritems():
if diff_dict.get(v, False):
print k, diff_dict[k]
sum([1, 2, 3, 4, 1], 7)
|
import json
import random
import pprint
def get_random_period():
year = random.randint(1000, 2000)
return {
'from_date': {
'year': year,
'month': random.randint(1, 12),
'day': random.randint(1, 28),
'comment': ''
},
'to_date': {
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-04 14:54
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('hugs', '0004_auto_20170204_1445'),
]
operations = [
migrations.RemoveField(
... |
# Generated by Django 2.1.5 on 2019-08-30 17:21
import django.contrib.postgres.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dota_chat', '0005_auto_20190830_1720'),
]
operations = [
migrations.AlterField(
model_name... |
a = [True, True]
b = [True, False]
c = [False, False]
print(all(a)) # True
print(all(b)) # False
print(all(c)) # False
print()
print(any(a)) # True
print(any(b)) # True
print(any(c)) # False
|
def solution(rows, columns, queries):
answer = []
matrix = []
for i in range(1, rows * columns + 1): # 초기 행렬 초기화
matrix.append(i)
for a, b, c, d in queries:
small = 10000 # 최솟값 체크
temp = [[], [],... |
'''
python file to dump messages to a json file that can be analysed
must run in container/virtual machine with ros installed
Create rosbag file with rosbag record -a
'''
import ros
import json
import rosbag
from std_msgs.msg import Int32, String
bag = rosbag.Bag('/udacity/CarND-TrackMasters-Capstone/data/2017-11-12... |
from django.shortcuts import render
from mycinema.models import Members
from django.db.models import Max
# Create your views here.
def JoinFunc(request):
return render(request, 'joinwithbgposter.html')
def JoinokFunc(request):
if request.method == "POST":
Members(
#id = Members.objects.al... |
from PyObjCTools.TestSupport import TestCase
import objc
import WebKit
class TestWebScriptObjectHelper(WebKit.NSObject):
@classmethod
def webScriptNameForSelector_(self, sel):
return 1
@classmethod
def isSelectorExcludedFromWebScript_(self, sel):
return 1
@classmethod
def web... |
import re
s = "psychoanalytic [ psychoanalysis: ] psychoanalytic"
patten=r'(\w+)\s+(.+)'
a = re.findall(patten,s)
print(a) |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import os
import numpy as np
import os.path as osp
import lmdb
import io
import torch
from torch.utils.data import Dataset
class JsonDataset(Dataset):
"""Auto Car Json Dataset"""
def __init__(self, ... |
import pandas as pd
import plotly.express as px
import seaborn as sns
import matplotlib.pyplot as plt
import plotly.graph_objects as go
import pyarrow
colnames = ["BidderId", "name", "day", "budget", "value", "bid", "utility", "payment", "rank"]
df = pd.read_feather('trail_data.feather')
def plot_all_bidding_profile... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Created by PyCharm.
File Name: LinuxBashShellScriptForOps:clean-old-backups-with-given-directory.py
Version: 0.0.1
Author: Guodong
Author Email: dgdenterprise@gmail.com
URL: https://github.com/DingGuod... |
import cv2
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
import torchvision.transforms as transforms
from nltk.translate.bleu_score import corpus_bleu
from torch import nn
from torch.nn.utils.rnn import pack_padded_sequence
from datasets import *
from utils import *
from models import ... |
# -*- coding: utf-8 -*-
from .__module__ import Module, dependency, source
from .python import Python
from .tensorflow import Tensorflow
from .pyopenpose import Pyopenpose
from .openpose import Openpose
from .keras import Keras
@dependency(Python, Tensorflow, Pyopenpose, Openpose, Keras)
@source('apt')
class Custom_D... |
import FWCore.ParameterSet.Config as cms
from PhysicsTools.PatAlgos.patTemplate_cfg import *
process = cms.Process("PAT")
process.load("PhysicsTools.PatAlgos.patSequences_cff")
process.load("FWCore.MessageLogger.MessageLogger_cfi")
process.load('Configuration.StandardSequences.Services_cff')
process.options = cms... |
"""
http://www.statsmodels.org/0.6.1/examples/notebooks/generated/wls.html
Date: 2018-04-07
"""
from __future__ import print_function
import numpy as np
from scipy import stats
import statsmodels.api as sm
import matplotlib.pyplot as plt
from statsmodels.sandbox.regression.predstd import wls_prediction_std
... |
from sys import argv
from random import random
from math import sqrt
from itertools import count, islice
IN_FILE = argv[1]
OUT_FILE = 'out.txt'
num_tests = 0
tests = []
jamcoins = []
with open (IN_FILE, 'r') as r:
for i, line in enumerate(r):
if not i:
num_tests = int(line.rstr... |
def compareTriplets(a, b):
score = []
a_score = b_score = 0
for i in range(len(a)):
if a[i] > b[i]:
a_score += 1
elif b[i] > a[i]:
b_score += 1
score = [a_score, b_score]
return score
a = [5, 7, 7]
b = [3, 6, 10]
print(compareTriplets(a, b))
|
lista = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def cuadrado(n):
return n ** 2
l2 = map(cuadrado, lista)
print l2
|
#!/usr/bin/python
import re
import os
import sys
import subprocess
import shutil
import optparse
import logging
'''
This program is used to install one off patches, e.g. timezone patches, openssl patches, etc.
It is mainly intended for those one off security patches that need to be updated/installed
in between OS p... |
###Shorthand for accessing lexical data and texts####
from nltk.corpus import gutenberg
gutenberg.fileids()
macbeth = gutenberg.words('shakespeare-hamlet.txt'
#practicing for loops - averaging out results for each book
for fileid in gutenberg.fileids():
num_chars = len(gutenberg.raw(fileid)) #this counts space charct... |
from django.db import models
# Create your models here.
class Tree(models.Model):
treeId=models.AutoField(primary_key=True)
class TreeImplementation(models.Model):
valId=models.AutoField(primary_key=True)
parent_id=models.IntegerField(default=None,null=True)
value=models.IntegerField()
tree=mode... |
ans = 0
def dfs(graph1, graph2, vis, x, y):
global ans
if x == 1:
for i in range(len(graph1[y])):
v = graph1[y][i]
if vis[v] == 0: ans += 1
vis[v] = 1
dfs(graph1, graph2, vis, x, v)
if x == 0:
for i in range(len(graph2[y])):
v = gr... |
__author__ = 'lataman'
import utilities
class scheme(object):
def __init__(self):
self.dict = {}
def add(self,id, alg):
if not utilities.hasValue(id):
return
if id in self.dict:
self.dict[id].append(alg)
else:
self.dict[id] = [alg]
def g... |
import numpy
import csv
state_data = {}
with open('state_data.csv', 'r') as state_data_csv:
state_data_csv_reader = csv.DictReader(state_data_csv)
for entry in state_data_csv_reader:
if entry["year"] not in state_data:
state_data[entry["year"]] = {}
if entry["name"] not in state_dat... |
#' -----
#' objetivos: corredores
#' autor: mauricio vancine
#' data: 16-10-2020
#' -----
# iniciar o python
python3
# importar bibliotecas
import os
import grass.script as gs
# addons
# gs.run_command("g.extension", extension = "r.area", operation = "add")
# bamges -------------------------------------------------... |
import sys
import pytest
import distutils.spawn
import schema_salad.validate
from cwltool.main import main
from .util import (get_data, get_main_output, needs_singularity,
working_directory)
sys.argv = ['']
@needs_singularity
def test_singularity_workflow(tmpdir):
with working_directory(st... |
import statistics
import requests
def coinbase_price():
url = 'https://api.coinbase.com/v2/exchange-rates?currency=eth'
response = requests.get(url)
response.raise_for_status()
return response.json()['data']['rates']['USDC']
def etherscan_price():
with open('./etherscan-api-token.txt') as fp:
... |
from multiprocessing import Process
import multiprocessing
import time
def job1(dict):
while True:
print('job1 is doing, dict = %s' % (str(dict)))
dict['job1'] = 'doing'
time.sleep(3)
def job2(dict):
while True:
print('job2 is doing, dict = %s' % (str(dict)))
dict['job2'] = 'doing'
time.sleep(5)
def m... |
# Uses python3
# Problem Description
# Task: The goal in this code problem is to implement the binary search algorithm.
# Input Format.
# The first line of the input contains an integer n and a sequence a 0 < a 1 < . . . < a n−1
# The next line contains an integer k and k.
# Constraints. 1 ≤ n, k ≤ 10 4 ; 1 ≤ a i ≤... |
from flask import Flask, jsonify, request
from flask_pymongo import PyMongo
app = Flask(__name__)
###Flask2db連線設定###
app.config['MONGO_DBNAME'] = '591'
app.config['MONGO_URI'] = "mongodb://localhost:27017/591"
app.config['JSON_AS_ASCII'] = False
mongo = PyMongo(app)
goods = mongo.db.Housessss
####- 【男生可承租】且【位於新北】的租... |
#!/usr/bin/python
import json,os,argparse
import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve, auc
import numpy as np
#from tensorflow.keras.models import load_model
import pandas as pd
from textwrap import wrap
parser = argparse.ArgumentParser(description = "Finds the aggregate AUROC")
parser.add_ar... |
def calculate_tax(kwargs):
"""
Author:Mbuvi
Function to calculate tax for various earnings
Params: kwargs-a dictionary containing name,amount pair for employees
Return type:d-dictionary containing name,tax pair for each name in kwargs
"""
if type(kwargs)==type({}):
d={}
for key,... |
from googleapiclient.discovery import build
import httplib2
from oauth2client.client import SignedJwtAssertionCredentials
# -*- coding: utf-8 -*-
__author__ = 'bryan'
import logging
import os
script_path = os.path.dirname(os.path.abspath(__file__))
#
# Enable Google API Logging level
# Docs: https://developers.goog... |
import collections
import os
from jinja2 import Template
import pytest
import yaml
import ocs.defaults
import ocsci
HERE = os.path.abspath(os.path.dirname(__file__))
OCSCI_DEFAULT_CONFIG = os.path.join(
HERE, "../conf/ocsci/default_config.yaml"
)
def get_param(param, arguments, default=None):
"""
Get ... |
from django.utils.translation import ugettext_lazy as _
from model_utils import Choices
# 业务码
BUSINESS_STATE = (
(0, 'ok', _('OK')),
(1, 'failure', _('Failure')),
)
BUSINESS_STATE_CHOICES = Choices(*BUSINESS_STATE)
|
from google.appengine.ext import db, blobstore
from google.appengine.api import files
from google.appengine.api.images import get_serving_url
from django.http import HttpResponse
class BlobModel(db.Model):
'''
Superclass for models that store a blobfile
'''
image = blobstore.BlobReferenceProperty()
... |
from selenium import webdriver
import random
import time
import pyautogui
from caine_mort.secrets import *
driver = None
v_list = [i for i in range(1, 4000)]
while True:
try:
driver = webdriver.Chrome(PATH)
idx = random.randint(0, len(v_list))
problem_idx = v_list[idx]
driver.... |
import os
import argparse
import torch
import cv2
import logging
import numpy as np
from net_dvc import *
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.utils.data as data
from torch.utils.data import DataLoader
import sys
import math
i... |
# encoding=utf-8
import requests
class Download:
"""
1. 高效爬取
2. 常见反反爬虫手段
3. 数据量的问题:并发, 分布式
"""
def __init__(self):
pass
@staticmethod
def get(url, headers={}):
html = requests.get(url, headers=headers)
return html.text
@staticmethod
def post(url, dat... |
from rest_framework import mixins, viewsets
from ..exceptions import Conflict
from ..models import Comment
from ..permissions import CommentPermissions
from ..serializers import CommentSerializer
# Comments can only be listed and created via a project
class CommentViewSet(mixins.RetrieveModelMixin,
... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from config.template_middleware import TemplateResponse
from tekton import router
from gaecookie.decorator import no_csrf
from formula1_app import facade
from routes.formula1s.admin import new, edit
def delete(_handler, formula1_id):
... |
"""Class definition for performing outlier detection on spectra."""
from functools import partial
from stdatamodels.jwst import datamodels
from jwst.datamodels import ModelContainer
from ..resample import resample_spec, resample_utils
from .outlier_detection import OutlierDetection
import logging
log = logging.getL... |
# 06-02
# ポアソン分布
#
import math
avg = 2.5
def prob(x):
return math.exp(-avg) * math.pow(avg, x) / math.factorial(x)
print("x=0~4の確率を求める")
sum = 0
for x in range(0, 5):
p = prob(x)
print("x=",x,"prob=",p)
sum += p
print("x>=5の確率は", (1 - sum))
import pylab as pl
print("ポアソン分布をプロットする")
probs = []
for... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
import plotting
z_disribution = lambda x: (x - x.mean()) / x.std() # works as a map function or in list comprehension
norm = lambda x: ( x - x.min() ) / ... |
"""Utility helper functions."""
from rudra.utils.validation import check_url_alive
from urllib.parse import urljoin
from rudra import logger
from sys import argv
from json import loads
GITHUB_CONTENT_BASEURL = 'https://raw.githubusercontent.com'
def get_github_repo_info(repo_url):
"""Get the github repository i... |
#!/usr/bin/env python3
from tensorforce.execution import Runner
RUNNER = Runner(
agent='agent.json',
environment=dict(environment='gym', level='CartPole', visualize=True),
max_episode_timesteps=500
)
if __name__ == '__main__':
RUNNER.run(num_episodes=300) |
from jellyfish import Jellyfish
def combine_crap(piece1=1, piece2=2):
return piece1 + piece2
if __name__ == "__main__":
# result = requests.get(url="https://leagueoflegends.fandom.com/wiki/Lulu")
# print(result.text)
# print(combine_crap(5))
# print(combine_crap(piece2=5))
banded_damo = jel... |
from main_app.forms import FeedingForm
from main_app.models import Pup, Toy, Photo
from django.shortcuts import redirect, render
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.views.generic import ListView, DetailView
from django.contrib.auth.views import LoginView
from django.cont... |
"""
Copyright © 2019 ground0state. All rights reserved.
"""
import numpy as np
from scipy.stats import f
class HotelingT2():
def __init__(self):
self.mean_val = None
self.cov_val_inv = None
self.M = None
self.N = None
def fit(self, X):
self.N, self.M = X.shape
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.