text stringlengths 38 1.54M |
|---|
#!/bin/python
import sys
import json
print "Parsing Delay-estimation statistics ..."
# Read the stdin for the data.
for line in sys.stdin:
# Only handle the specific entires.
if (not "DELAY-ESTIMATOR-JSON:" in line) :
continue
# print line
chainDelay = json.loads(line[len("DELAY-ESTIMATOR-JSON:"):])
erro... |
import sys
_module = sys.modules[__name__]
del sys
core = _module
client = _module
config = _module
dataloader = _module
dataset = _module
evaluation = _module
federated = _module
metrics = _module
model = _module
schema = _module
server = _module
strategies = _module
base = _module
dga = _module
fedavg = _module
utils... |
#Ejercicio: Las Elecciones
# El programa primero recibe un número N , la cantidad de votos totales que se realizaron. Luego recibe N votos en formato string, cada uno consiste en el nombre del candidato seleccionado. El programa debe calcular el ganador e imprimir su nombre, para este ejemplo se asume que no hay emp... |
import sys
import socket
from itertools import product
import json
from string import ascii_letters, digits
import datetime
with open(r"C:\Users\javie\Downloads\logins.txt") as f:
logins = f.readlines()
logins = [x.strip() for x in logins]
ip_address = sys.argv[1]
port = int(sys.argv[2])
my_socket = socket.socke... |
# coding:utf-8
# File Name: plus_test
# Description :
# Author : micro
# Date: 2019/12/12
a_tuple = ("microease")
b_tuple = 24
c_tuple = a_tuple + str(b_tuple)
print(c_tuple)
|
from sklearn.utils import shuffle
def get_best_tokens_dummy(corpus, each_q):
pos = corpus[corpus['rate'] == 'positive']['content'].str.split(expand=True).stack().value_counts()
neg = corpus[corpus['rate'] == 'negative']['content'].str.split(expand=True).stack().value_counts()
best_tokens = pos.head(each_q... |
# -*- coding: utf-8 -*-
from mongoengine import *
from models.agent_model import Agent
# connect(db='sd',
# host='10.3.242.253',
# port=27017,
# username='sd',
# password='software_design'
# )
connect('software_db', host='localhost', port=27017)
class Task(Document):
"""S... |
import numpy as np
import scipy.sparse as sps
from collections import namedtuple
from sklearn.model_selection import KFold, ParameterGrid
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.linear_model import ElasticNet, Ridge, Lasso
from sklearn.base import BaseE... |
import numpy as np
from sknn.mlp import Classifier, Layer
from sknn.platform import gpu32
import sys
import logging
import pickle
import argparse
from sklearn.grid_search import GridSearchCV
from sklearn.metrics import classification_report
import matplotlib.pyplot as plt
import csv
parser = argparse.ArgumentParser(... |
# -*- coding: utf-8 -*-
import MySQLdb
class PyMysql:
conn = None
cur = None
def __init__(self, host='localhost', user='root', passwd='root',
db='bprest', port=3306):
self.host = host
self.user = user
self.passwd = passwd
self.db = db
self.port = ... |
""" Code is generated by ucloud-model, DO NOT EDIT IT. """
import typing
from ucloud.core.client import Client
from ucloud.services.sts.schemas import apis
class STSClient(Client):
def __init__(
self, config: dict, transport=None, middleware=None, logger=None
):
super(STSClient, self).__ini... |
# Generated by Django 2.1.3 on 2018-11-30 03:32
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='AirPlane',
fields=[
... |
# -*- coding:utf-8 -*-
x = "abc"
if x == "abc":
print("x and abc 是相等的")
else:
print("x and abc 是不相等的")
|
import json
import requests
import herogetAgent
requests.packages.urllib3.disable_warnings()
def main():
# 访问百度验证
baidu = "https://www.sohu.com/"
use_ip_proxy = []
ip_proxy_path = "./jsonfile/proxyipdata3.json"
# 加载数据
ip_proxy_datas = json.load(open(ip_proxy_path,"r"))
# pri... |
from django.urls import path
from . import views
from django.views.decorators.csrf import csrf_exempt
urlpatterns = [
path('filldata', views.FillData().as_view(), name = 'filldata'),
path('deldata', views.DelData().as_view(), name = 'deldata'),
path('getjson', views.GetJson().as_view(), name = 'getjson'),
... |
import os
import unittest
from parameterized import parameterized
from utils.emulator_launcher import CommandLineEmulatorLauncher
from utils.test_modes import TestModes
from utils.channel_access import ChannelAccess
from utils.ioc_launcher import get_default_ioc_dir, EPICS_TOP
from utils.testing import get_running_le... |
import pyaudio
cache = "cache/"
rate = 44100
channels = 1
format = pyaudio.paInt16
chunk = 1024
rec_seconds = 5 |
import json
import os
from collections import defaultdict
from src import model
class MutantOperator:
operators = {}
@classmethod
def reset_operators(cls):
cls.operators = {}
def __init__(self, adict):
self.name: str = adict["name"]
self.description: str = adict["description... |
from pyspark.sql import SparkSession
from pyspark.sql import Row
from pyspark.sql import functions as func
spark = SparkSession.builder.appName("FriendsByAge").getOrCreate()
lines = spark.read.option("header", "true").option("inferSchema", "true").csv("file:///scourse/fakefriends-header.csv")
# Select only age and n... |
""" MULTIVARIATE TIME SERIES SINGLE POINT FORECAST
----------------------------------------------
Implementation of a lstm recurrent neural network for multivariate time series forecasting of a single point in the future.
This script uses a weather time series dataset, which contains 14 features collected ... |
class Solution:
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# TODO: Challenge is to find a solution with O(1)
# space complexity and O(N) time complexity
# The following solution is O(N) for time and space
... |
from collections import deque
effects = deque([int(n) for n in input().split(", ")])
casings = deque([int(n) for n in input().split(", ")])
bombs_types = {40: {"name": "Datura Bombs", "quantity": 0},
60: {"name": "Cherry Bombs", "quantity": 0},
120: {"name": "Smoke Decoy Bombs", "quantity... |
from django.urls import path
from . import views
app_name = "account"
urlpatterns = [
path('login', views.acc_login, name="login"),
]
|
from django.conf.urls import *
from django.contrib import admin
from HelloWorld.view import hello
from HelloWorld.testdb import testdb
from HelloWorld import search
from HelloWorld import search2
admin.autodiscover()
urlpatterns = patterns(
"",
(r'^admin/', include(admin.site.urls)),
('^hello/$', hello),... |
########################### train.py #######################################
# This code implements the training procedure for the speech-to-image
# retrival model for spoken words and visual objects. To run the code,
# simply modify the data paths for the data and pretrain models to the
# right paths, copy and past... |
import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import socket
import os
IP = "127.0.0.1"
Port = 8051
class eventHandler(FileSystemEventHandler):
"""Logs all the events captured."""
def on_created(self, event):
... |
import subprocess
class SubprocessWrapper(object):
VERBOSE = False
def __init__(self, arguments, working_directory=None, require_out=False, require_log=False):
assert isinstance(arguments, list) or isinstance(arguments, str)
assert require_out != require_log or require_out is False
i... |
import tensorflow as tf
from models import BaseModel
class BertClassifier(BaseModel):
def __init__(self,
bert_config,
sequence_length,
num_classes,
initializer='glorot_uniform',
output='logits',
dropout_rate=0.1... |
def get_next_target(s):
start_link = s.find('<a href=')
start_quote = s.find('"',start_link)
end_quote = s.find('"',start_quote+1)
url = s[start_quote+1:end_quote]
return url , end_quote
print get_next_target('<a href= "www.hello.com" >') |
### copy from jianjin
import random
import os.path
import logging
import os
from copy import copy
import numpy as np
import h5py
import pandas as pd
from datetime import datetime
import time
logger = logging.getLogger(__name__)
def string2timestamp(strings, T=48):
timestamps = []
time_pe... |
# Teste seu código aos poucos. Não teste tudo no final, pois fica mais difícil de identificar erros.
# Ao testar sua solução, não se limite ao caso de exemplo. Teste as diversas possibilidades de saída
a=float(input("Lado 1: "))
b=float(input("Lado 2: "))
c=float(input("Lado 3: "))
print("Entradas:" , a,",",b,",",c)
if... |
# Copyright 2019 3YOURMIND GmbH
# 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 required by applicable law or agreed to in writing, soft... |
from collections import OrderedDict
from copy import deepcopy
import numpy as np
import torch
from torch import nn
from utils.io import make_path
class MLFeatures:
__RequiredTarget__: OrderedDict
__IgnoreSuffix__: str = '__'
_model_callbacks: nn.ModuleDict
_model_kwargs: OrderedDict
_model_type_... |
"""
Django settings sans boilerplate
"""
from .functions import emplace, setenv
__all__ = ['emplace', 'setenv']
|
import mysql.connector
from mysql.connector import Error
from openpyxl import load_workbook
from openpyxl.styles import Alignment, Protection, Font
#To load workbook
wb = load_workbook('./AugustReport/July2019IEAReport.xlsx')
print(wb.get_sheet_names())
anotherSheet = wb.active
# try:
# sheet = wb.get_sheet_by_n... |
import serial, sys, io, time
"""
Logger for iMax-B6, Turnigy Accucel-6 and similar 4-button chargers
by Andy Gock
CSV output in format:
time,minutes,voltage,current,charge
If using Windows:
Download wintee: http://code.google.com/p/wintee/
(allows logging to file AND viewing output at the same time)
Run (Win... |
def getPrimeFactorsDict(number):
current = number
checking = 2
factors = dict()
while checking <= current:
while current % checking == 0:
current = current / checking
factors[checking] = factors.get(checking, 0)+ 1
checking+=1
return factors
def getSmallestDi... |
import sys
from enum import Enum
class Acid(Enum):
NON_METAL = 'non-metal acid'
POLYATOMIC = 'polyatomic acid'
NOT_ACID = 'not an acid'
def name_acid(text: str) -> Acid:
hydro = text.startswith('hydro')
poly = text.endswith('ic')
if hydro and poly:
return Acid.NON_METAL
elif pol... |
#!/usr/bin/env python3.5
# -*- coding: utf-8 -*-
# @Time : 18-3-24 下午1:33
# @Author : 无敌小龙虾
# @File : GetNewsClass.py
# @Software: PyCharm
import re
import requests
from bs4 import BeautifulSoup
from lxml import etree
class GetNews:
def __init__(self):
self.headers = {
'Connection': ... |
# -*- coding: utf-8 -*-
"""
箱图
当我们的数据是num_subj*num_var,且有几个诊断组时,我们一般希望把var name作为x,把var value作为y,把诊断组作为hue
来做箱图,以便于观察每个var的组间差异。
此时,用于sns的特殊性,我们要将数据变换未长列的形式。
行数目为:num_subj*num_var。列数目=3,分别是hue,x以及y
input:
data_path=r'D:\others\彦鸽姐\final_data.xlsx'
x_location=np.arange(5,13,1)#筛选数据的列位置
未来改进:封装为类,增加可移植性
@a... |
# Databricks notebook source
# Select Libraries => Install New => Select Library Source = "Maven" => Coordinates => Search Packages => Select Maven Central => Search for the package required. Example: mysql-connector-java library => Select the version required => Install
# COMMAND ----------
# dbutils.widgets.removeA... |
import time
class StopWatch:
def __init__(self):
self.start_time = time.time() # record the first timestamp
self.end_time = -1
def start(self):
self.start_time = time.time()
self.end_time = -1
def stop(self):
self.end_time = time.time()
def elapsed_time(self)... |
n11,m1=map(int,input().split())
a1=[]
b1=[]
for i1 in range(n11):
a1.append(list(map(int,input().split())))
for i1 in range(n11):
for j1 in range(m1):
if a1[i1][j1]==0:
b1.append(i1)
b1.append(j1)
for i1 in range(0,len(b1),2):
for h1 in range(m1):
a[b[i1]][h1]=0
f... |
import glob
import json
import os
import sys
from uuid import uuid4
# Usage: python matview_sql_generator.py (from usaspending_api/database_scripts/matview_generator)
# ^--- Will clobber files in usaspending_api/database_scripts/matviews
'''
POSTGRES INDEX FORMAT
CREATE [ UNIQUE ] INDEX [ name ] ON table_n... |
#!/usr/bin/env python2.7
"""
Ted Satcher
CS 640
Fall 2012
Final Exam
File: problem4.py
This executable is for Problem 4 for the final exam.
It uses the Parzen window approach to calculate
an estimated density function from a collection
of sample patterns.
"""
from __future__ import print_function
import numpy as np
... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 30 15:48:13 2018
@author: brian
"""
import seaborn as sns
########Correlation Matrix
#Seaborn's heatmap version:
df3 = dfMaster
corr = df1.corr()
sns.heatmap(corr,
xticklabels=corr.columns.values,
yticklabels=corr.columns... |
# It turns out that 12 cm is the smallest length of wire that can be bent to form an integer sided right angle triangle in exactly one way, but there are many more examples.
# 12 cm: (3,4,5)
# 24 cm: (6,8,10)
# 30 cm: (5,12,13)
# 36 cm: (9,12,15)
# 40 cm: (8,15,17)
# 48 cm: (12,16,20)
# In contrast, some lengths of w... |
num=int(input("Enter the number"))
sum=0
for i in range(2,num+1):
sum=sum+(1/(i*i*i))
print("Sum of series is",sum) |
import numpy
import pandas
import ROOT
from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasRegressor
from sklearn.cross_validation import cross_val_score
#from sklearn.model_selection import cross_val_score
from sklearn.cross_validation import KFold
#from skle... |
import os
import time
import math
import proddog.changeset
import proddog.observer
observDirectory = '/var/local/www/hostname'
modifiedPeriod = 60*60*48
checkPeriod = 10*60
excludeExtensions = ['png', 'log']
observer = prodcontrol.observer.Observer(observDirectory, modifiedPeriod, excludeExtensions)
changeset = pr... |
#Python的循环有两种
#一种是for...in循环,依次把list或tuple中的每个元素迭代出来,看例子:
names = ['Michael', 'Bob', 'Tracy']
for name in names:
print(name)
#计算1-10的整数之和
sums = [1,2,3,4,5,6,7,8,9,10]
total = 0;
for sum in sums:
total +=sum;
pass;
print(total)
#如果要计算1-100的整数之和,从1写到100有点困难,
#幸好Python提供一个range()函数,可以生成一个整数序列,
#再通过list()函数可以转... |
from xml.dom import minidom
xmldoc = minidom.parse('4.xml')
reflist = xmldoc.getElementsByTagName('ref')
print reflist
print
print reflist[0].toxml()
print
print reflist[1].toxml()
|
# Copyright 2021 Google LLC
#
# 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 required by applicable law or agreed to in writing, ... |
class Script:
@staticmethod
def main():
int_months_0 = 1
int_months_1 = 2
int_months_2 = 3
int_months_3 = 4
int_months_4 = 5
int_months_5 = 6
int_months_6 = 7
int_months_7 = 8
int_months_8 = 9
int_months_9 = 10
int_months_10 = 11
int_months_11 = 12
index_four = int_months_4
last_value = i... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.10 on 2016-10-11 09:03
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('pjt_inventory', '0027_auto_20161011_1358'),
]
oper... |
# -*- coding: utf-8 -*-
"""
voicetools library
=====================
"""
__title__ = 'voicetools'
__version__ = '0.0.1'
__author__ = 'namco1992'
__license__ = 'Apache 2.0'
from voicetools.api import Wolfram, TuringRobot, BaiduVoice
from voicetools.clients import BaseClient
import voicetools.utils
from voicetools.exc... |
__author__ = 'CLH'
'''
Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create.
'''
class Solution(object):
def __init__(self):
self.S = []
self.answer = []
self.total_answ... |
import pdb
from models.beer import Beer
from models.brewer import Brewer
import repositories.brewer_repository as brewer_repository
import repositories.beer_repository as beer_repository
brewer_repository.delete_all()
beer_repository.delete_all()
brewer1 = Brewer('Fallen Brewing',
"Unrefined, Vegan f... |
# Text-based adventure game - Viet Hoang Cao
def game_over():
print("I'm sorry that you were defeated while this game has not been completed yet so fingers cross for you next time")
game_over()
def treasure_room_1(): # alone
print("After all, this game has almost came to an end. However, it is not ov... |
#Connection persistence strategy adapted from @vincent31337, Stack Overflow:
#https://stackoverflow.com/questions/55523299/best-practices-for-persistent-database-connections-in-python-when-using-flask
from flaskr.db import MoviebuffDB
from flaskr.cosmos import MoviebuffCosmos
from flaskr.mongo import MongoDB
db = Mo... |
from django.conf.urls import patterns, url
from places import views
urlpatterns = patterns('',
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>\d+)/$', views.PlaceDetailView.as_view(), name='place_detail'),
url(r'^creat_new_place/$', views.NewPlaceCreateView.as_view(), name='creat_new_... |
from selenium import webdriver
from bs4 import BeautifulSoup
import pandas as pd
from time import sleep
import re
import json
import requests
import sys
import datetime
arguments = sys.argv
# - TODO --
# - add command line arguments to choose what call is being searched for
# - process data
# - averages for the y... |
"""add_project
Revision ID: c0acc1e1a1b5
Revises: 675cea0bd5a0
Create Date: 2019-09-25 11:16:04.135133
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'c0acc1e1a1b5'
down_revision = '675cea0bd5a0'
branch_labels = None
depends_on = None
def upgrade():
# ##... |
# encoding: utf-8
import xlrd
import sys
from sheet import shm
args = {}
def export_single_book():
file_path = args.input
output_path = args.output
shm.add_work_book(file_path)
sheet_name_list = shm.get_sheet_name_list()
for sheet_name in sheet_name_list:
if shm.is_ref_sheet(sheet_nam... |
for tc in range(int(input())) :
n, k = list(map(int, input().split()))
result = 0
for i in range(1<<12) :
item = []
for j in range(12) :
if i & 1<<j :
item.append(j+1)
if sum(item) == k and len(item) == n :
result+=1
print(f'#{tc+1} {result... |
'''
extract communication cost between classes from workflow.csv
'''
import sys
import csv
METHODDict = dict() #dict[methodName] = methodID
CLASSDict = dict() #dict[className] = classID
CLASSID2NAMEDict = dict() #dict[classID] = className
METHODEdgeDict = dict() # dict[mid1][mid2] = edgeIndex
METHODEdgeList = list()... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 24 15:19:51 2018
@author: Brandon Croarkin
"""
from PIL import Image
import os
import re
#listing out the (x1, y1, x2, y2) coordinates of information on each of
#the different forms
image_coords_020209 = {'LastName':(.055*width,.168*height,.37*width,.205*h... |
from poc.classes.AuxISourceAnalyser import AuxISourceAnalyser
from poc.classes.AuxInterpretation import AuxInterpretation
from poc.classes.AuxContext import AuxContext
from poc.classes.ContextSignature import ContextSignature
class ContextTheoremLikeStatement:
@staticmethod
def start(i: AuxISourceAnalyser, pa... |
# coding: utf-8
# In[218]:
import numpy as np
#import matplotlib.pyplot as plt
from proteus import SpatialTools as st
import os
from proteus import Domain
def get_yz(filename):
data=st.getInfoFromSTL(str(filename))
x=data[0][0][0]
yz=[]
for i in range(len(data[0])):
if data[0][i][0] >= 0.99... |
"""
Author: Thomas.JR
THMS OPERATING SYSTEM
version: pre-alpha v.0.0.010
"""
#program functions
def help():
def git():
print("Welcome to System Helper. (VERSION: 0.00.1")
print("Use these commands to make guidelines:")
print(" /help.settings: To make guidelines for SETTINGS Program")
... |
# libray imports
import winsound
import numpy as np
from sklearn import manifold
# application imports.
from data_generator import generate_data_gausian_archimedean_spiral
from data_visualization import plot_data
def sound ( f, p, n ):
for i in range ( n ):
winsound.Beep ( f, p )
# Function: Ma... |
"""
Author: Marion Owera
Date Written: Feb 25, 2018
Description: Temporary sent_tokenizer lang to, may problema pa kasi dun sa tokenizer ni Jeremy.
"""
import re
import json
def sent_tokenize(inp,fh=False):
sym =r"([,\"\'])"
inp = re.sub(r"(\w+)"+sym+r"(\w+)"+sym+r"(\w+)",r"\1 \2 \3 \4 \5",inp)
inp = re.s... |
import sys
sys.path.insert(1, "../lua")
import Sym
class TestSym:
def testSym(self):
str = "aaaabbc"
sym = Sym.Sym(0, "symbols")
for i, x in enumerate(str):
sym.add(x)
mode = sym.mid()
entropy = sym.div()
entropy = (1000*entropy//1)/1000
print(" ... |
import numpy as np
from sklearn.datasets import load_boston
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
Dataset = []
d1 = [[2345,34,45],[3456,4,5],[4567,7,8],[5678, 23, 63]]
X = [[10,20,30],[2,3,4], [5,6,8]]
Y = [14565, 654, 765]
# X = np.array(X).reshape(-1,1)
X = np.... |
"""
MIT License
Copyright (c) 2020-2021 Dmitriy Trofimov
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, ... |
#### This code searches over subsets of streams and locations simultaneously
#### The search happens centered on every tract in the city, with a radius (defined below) of .01
#### Ideas for exploratory data analysis:
#### 1. Tweak this radius
#### 2. Leave out 50% of data (create a training dataset and a testing data... |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 3 15:02:25 2013
@author: team
"""
import hydro_wrapper
hydro_wrapper.change_param(12,9, 180, 1, 1, 1)
hydro_wrapper.change_data_time(12,12,14,2013,12,23,2013)
hydro_wrapper.timer(15600)
hydro_wrapper.runSELFE(12,10800)
|
from csv_comparison_package import Compare
from csv_comparison_package import Field
# TODO LEFT HERE
def check_for_identical_row(comparable_a: Compare, comparable_b: Compare):
"""
Sort both data frames
Both data frames must have the same indices
Get indices of one data frame
for each all the indic... |
#Python code to generate all anagrams of a word
def anagrams(word):
if len(word)==1:
return [word]
result=[]
for i in range(len(word)):
letter=word[i]
rest=word[0:i] + word[i+1:]
for tail in anagrams(rest):
result.append(letter + tail)
return result
def all_d... |
#-*- coding: UTF-8 -*-
from plone.directives import form
# Interface class; used to define content-type schema.
class Iormfolder(form.Schema):
"""
db map container
""" |
def greatest_common_divisor(m, n):
low = min(m, n)
high = max(m, n)
if low == 0:
return high
for divisor in reversed(xrange(1, low + 1)):
if low % divisor == 0 and high % divisor == 0:
return divisor
def test_greatest_common_divisor():
gcd = greatest_common_divisor
... |
"""Test the healthcheck feature."""
from asserts import assert_equal
from behave import given, then, when
from behave.runner import Context
@given("a healthy server")
def healthy_server(_context: Context) -> None:
"""Server should be healthy by default, so no step implementation needed."""
@when("a client chec... |
from django.test import TestCase
from django.contrib.auth import get_user_model
from django.core import exceptions
from core import models
from uuid import uuid4
class ModelTests(TestCase):
def test_create_user_with_email_successful(self):
""" Test creating a new user with an email is successful """
... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 3 14:21:59 2019
@author: Nelson
"""
# import libraries
import os
import cv2
import numpy as np
import sys
from math import pi
from skimage import morphology, measure
from skimage.filters import scharr
from scipy import ndimage
import math
import copy
imp... |
from kipoi.data import Dataset
from kipoiseq.transforms import ReorderedOneHot
from genome_tools import genomic_interval, genomic_interval_set, bed3_iterator
from genome_tools.helpers import open_file
from pyfaidx import Fasta
from footprint_tools import bamfile
from footprint_tools.modeling import bias, prediction
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Código
import pygame
pygame.init()
pygame.mixer.music.load('sunset.mp3')
pygame.mixer.music.play()
pygame.event.wait()
# Biblioteca
# print('{}'.format())
# variável = int(input(''))
# variável = float(input(''))
# variável = str(input(''))
# Instalando o pygame
... |
from typing import Tuple
def index_to_rowcol(index: int, width: int) -> Tuple[int, int]:
"""Translate 1D index to 2D index.
Parameters
----------
index : int
width : int
Width of target 2D matrix.
Returns
-------
Tuple[int, int]
Row / column indices for target 2D matr... |
import cv2
import pysift
import numpy as np
from numpy import float32
def warpTwoImages(img2, img1, H):
'''warp img2 to img1 with homograph H'''
print("=={}==".format(H))
h1,w1 = img1.shape[:2]
h2,w2 = img2.shape[:2]
pts1 = float32([[0,0],[0,h1],[w1,h1],[w1,0]]).reshape(-1,1,2)
print(pts1)
pts2 = float32([[0,0],... |
#!/usr/bin/python
# Imports
# System
import os
import sys
import time
# Image/Papirus
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from papirus import Papirus
# Socket for IP Address
import socket
# Fonts
hatdir = '/proc/device-tree/hat'
ipFont = '/usr/share/fonts/truetype/freefont/Free... |
import numpy as np
from numpy.random import randint
LIST_OF_CHARS = ['a','b','c','d','e','f','g','h','@','#','1','2','3','4','5','6','7', '8', '9', '0']
NUMBER_OF_LINES = 100000
#NUMBER_OF_LINES = 20
MAX_NUMBER = 1000000
random_ints = randint(0,MAX_NUMBER, randint(0,70))
def convert_number_to_word(n):
list_ch... |
import code.rule_simplification.CheckReplacementForFitting as CheckReplacementForFitting
def check(first_model, second_model, dict_tokens_info, config):
"""
Find if the first model is equivalent to the second
Author: Kulunchakov Andrei
"""
if CheckReplacementForFitting.check(first_model, second_... |
# (C) Copyright 1996- ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status as an intergovernmen... |
#본 코드는 Bismark CpG report 파일로부터 여러개의 sample을 position별로 통합하고 filtering 조건을 부여하여 유의미한 methylation정보를 통합하여 경향성을 파악하는 코드이다
#Output으로는 filtering 전, 후, ref Bed file로 부터 CpG site를 통합하여 값들을 나타낸 파일(Sum + Mean), Tendency file이 나온다
import sys
import time
import numpy as np
import argparse
parser = argparse.ArgumentParser(descr... |
class BigDict(object):
def __init__(self):
self.collection = dict()
def put(self, key, value):
if self.collection.__contains__(key):
old = self.collection.get(key)
self.collection[key] = old + ',' + value
else:
self.collection[key] = value
def... |
import cloudinary
cloudinary.config(
cloud_name="roadpadi",
api_key="842581262512282",
api_secret="U3yenMVfOLC33BcA1dWhzjs_VBE"
)
|
from rest_framework import urlpatterns
from .view.read_view import StoryViewset,CommentViewset
from .view.write_view import CreateStory,StoryDetail,CreateComment,CommentDetail
from rest_framework_nested import routers
from django.urls import path, include
router = routers.DefaultRouter()
router.register('stories',St... |
# coding: utf-8
__author__ = 'deff'
from scanner.base import BaseScanner
##动态信息
class DynamicScanner(BaseScanner):
def __init__(self):
super().__init__()
##可单独直接开始
def start(self):
return ""
# 做初始化操作
def init(self):
pass
# 扫描
def scan(self):
pass
#... |
import numpy as np
'''
characters of COVID-19
'''
t_eps = 5.2 #incubation period(day)
t_I = 14 #lasting of I(day)
t_Ia = 14 #lasting of Ia(day)
d = 0.15 #death rate
R_0 = 2.68 #basic reproduction number
Pa = 0.018 #proportion of Ia
r_L = 1.0
r_a = 0.6
'''
get parameters and covert them to values measur... |
import cv2
import os
import numpy as np
class FormTransform:
def __init__(self, max_features, good_match, is_debug=False):
self.max_features = max_features
self.good_match = good_match
self.is_debug = is_debug
if is_debug == True:
self.debug_path = os.path.join(os.pat... |
from django.db import models
# Create your models here.
class Acs(models.Model):
name = models.CharField(max_length=50, null=True, default=None)
target = models.PositiveIntegerField()
arrival = models.IntegerField(null=True, default=None)
class Alliance(models.Model):
ally_name = models.CharField(ma... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.