text stringlengths 38 1.54M |
|---|
import libfoolang
ctx = libfoolang.AnalysisContext()
foo = ctx.get_from_file('foo.txt')
assert foo.root.is_a(libfoolang.HasExamplePresent)
print(foo.root.p_prop)
print('Done.')
|
import hashlib
import numpy as np
from utils.myPrint import PRINT_blue
from utils.myPrint import PRINT_red
def check(data1, data2, name1 = 'data1', name2 = 'data2'):
"""
function:
to check the data is equal or not.
parameters:
data1: numpy.ndarray, must, first data.
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 12 15:49:29 2019
@author: skondaveeti
Each roll is equally likely, so it will show 1,2,3,4,5,6 with equal probability. Thus their average of 3.5 is the expected payoff.
Now let's suppose we have 2 rolls. If on the first roll, I roll a 6, I would n... |
from pyspark.sql import SparkSession
from pyspark.sql.functions import window, column, desc, col
import time
if __name__ == "__main__":
spark = SparkSession.builder.master("local").appName("structured-streaming").getOrCreate()
spark.conf.set("spark.sql.shuffle.partitions", "1")
data_path = "/home/jameslin... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-u
"""
Purpose : Exceptions for our pythons wrapper
"""
class NotValidEmail(Exception):
""" The email is not valid """
pass
class BreachNotFound(Exception):
""" The breach Name is not found """
pass
class UnvalidParameters(Exception):
pass
|
__author__ = 'Eidan Wasser'
from Utils import Config
from selenium.webdriver.common.by import By
from selenium.common.exceptions import ElementNotVisibleException, NoSuchWindowException
import unittest, time
class GooglePlus(unittest.TestCase):
def test(self):
driver = Config.get_driver()
google = ... |
# Copyright 2014-2022 Scalyr Inc.
#
# 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 writin... |
def tri_area(width,height):
return width*height*1/2
def box_area(width,height):
return width*height
def print_area(width,height):
print("가로 : ",width," 세로 : ",height," 삼각형의 넓이 : ",tri_area(width,height))
print("가로 : ",width," 세로 : ",height," 사각형의 넓이 : ",box_area(width,height))
if ... |
class MainPage:
type = "Page"
def __init__(self, topic = None, name = None, icon="home"):
self.topic = topic
self.name = name
self.icon = icon
class Device:
type = "Device"
def __init__(self, topic = None, name = None, icon="zap"):
self.topic = topic
self.na... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
from django.utils.timezone import utc
from django.conf import settings
import uuid
class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operati... |
# This files contains your custom actions which can be used to run
# custom Python code.
#
# See this guide on how to implement these action:
# https://rasa.com/docs/rasa/custom-actions
# This is a simple example for a custom action which utters "Hello World!"
from time import strftime
from typing import Any, Text, ... |
def sum_sfarot(num):
print((num//100)+(num//10%10)+(num%10))
sum_sfarot(int(input("enter number in 3 numbers: "))) |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 9 17:12:47 2020
@author: anish pratheepkumar
code to run the quadcopter model autonomously on a track using trained CNN model
"""
#import essential libraries
import sim
import sys
#import os
#import matplotlib.pyplot as plt
import cv2
import numpy as np
import time
from... |
#Code to find sum and average of elements in list anf to multiply all elements in list
def sumAndAvg(lst):
sum=0
avg=0
mul1=1
for i in lst:
sum+=i
mul1*=i
avg=sum/len(lst)
print("Sum of elements in list is {}".format(sum))
print("Average of elements in list is {}".forma... |
print("Hello, Themyscira!")
# This is a comment that won't be interpreted as a command.
# Associate the variable diana with the value "Wonder Woman 1984"
diana="Wonder Woman 1984"
# Print a message with the true identity of Diana
print("I believe Diana is actually "+diana)
# Define a power (fucntion) to chant a phrase
... |
#!/usr/bin/python
import sys, os, string, re
#******************************
# check that the patch numbers are in order
# August 30, 2006
# Annette Roll (help from Mike Harris)
##########################################
# function to determine missing patches
def getMissingPatches(num_patches, s_patches):
# for eac... |
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
from matplotlib import ticker
from matplotlib.ticker import MaxNLocator,MultipleLocator, FormatStrFormatter, FuncFormatter, ScalarFormatter
import matplotlib as mpl
from matplotlib import cm
def... |
import random
try:
min_value = int(input('Enter the minimum value of the die: '))
max_value = int(input('Enter the maximum value of the die: '))
except:
print('Imput invalid program will revert to default.')
min_value = 1
max_value = 20
again = True
while again:
print(random.ran... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 20:14:57 2020
@author: Pinar
@description: creating figs for NeurIPS
"""
import gym
import random
import string
import os
import numpy as np
from diabetes import *
from constants import *
from gym.envs.registration import register
register(
... |
def count_consonants(str):
count = 0
str2 = str.lower()
for i in range(0, len(str2)):
if str2[i] in 'qwrtpsdfghjklzxcvbnm':
count = count + 1
return count
|
debug_level = "all"
def log(message,type="TEMP"):
#print("logging..."+type)
if (type == 'temp' or type == 't') and (debug_level =="all" or debug_level == 'temp'):
print("\ntest value: "+message+"----------\n")
elif type == 'debug' or type == 'd' and (debug_level =="all" or debug_level == 'debug' or... |
import numpy as np
from api import *
import tensorflow as tf
import math
def sigmoid(z):
s = 1.0 / (1.0 + np.exp(-1.0*z))
return s
def relu(z):
for i in range(len(z)):
z[i] = max(0,z[i])
return z
def iterate_nn(input):
for i in range(len(weights)):
if i == 0:
h = relu(... |
class Solution:
def tribonacci(self, n: int) -> int:
x = 0
y = 1
z = 1
if n == 0:
return x
elif n == 1:
return y
elif n == 2:
return z
for i in range(3, n+1):
tmp = x + y + z
x, y, z = y, z, tmp
... |
import numpy as np
import ctypes
from scipy.sparse import coo_matrix, csr_matrix, csc_matrix
import test_math
m = int(1e1)
n = int(9e0)
nz = int(.25*m*n)
nthreads = 4
np.random.seed(123)
X = np.random.gamma(1,1, size=(m,n))
X[np.random.randint(m, size=nz), np.random.randint(n, size=nz)] = 0
all_NA_row = (X == 0).sum(... |
import secrets
from typing import Any, Dict, List, Optional, Union
from pydantic import AnyHttpUrl, BaseSettings, EmailStr, HttpUrl, PostgresDsn, validator
class Settings(BaseSettings):
API_V1_STR: str = "/api/v1"
class Config:
case_sensitive = True
settings = Settings()
|
# -*- coding: utf-8 -*-
# coding:utf-8
__author__ = 'lancelrq'
import json
from wejudge.core import *
from wejudge.utils import *
from wejudge.utils import tools
from wejudge import const
import apps.oauth2.libs as libs
import apps.education.libs as EduLibs
from django.http.response import HttpResponseRedirect
def a... |
#!/usr/bin/env python
# -*-coding:utf-8 -*-
##*************************************************************************************************************
##*************************************************************************************************************
## ** 文件名称: init_hive_database.py
## ** 功能描述: 数... |
#!/usr/bin/env python
# # -*- coding: utf-8 -*-
#!/usr/bin/env python
import pickle as pickle
import glob, os
import numpy as np
import argparse
import time
import seaborn as sns
import matplotlib
#matplotlib.use('Agg')
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import pandas as pd
import s... |
#!/usr/bin/env python
# ----------------------------------------------------------------------- #
# Copyright 2017, Gregor von Laszewski, Indiana University #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); you ... |
from collections import deque
import numpy as np
class ExperienceMemory(object):
def __init__(self, max_memory_length, history = 4):
self.history = history
self.state_memory = np.zeros([max_memory_length, 84, 84, self.history], dtype=np.uint8)#deque(maxlen=max_memory_length)
... |
#!/bin/env python
# pylint: disable=invalid-name
"""This module contains the Atom class"""
PERIODIC_TABLE = {
1: {'symbol': 'H'},
2: {'symbol': 'He'},
3: {'symbol': 'Li'},
4: {'symbol': 'Be'},
5: {'symbol': 'B'},
6: {'symbol': 'C'},
7: {'symbol': 'N'},
8: {'symbol': 'O'},
9: {'symb... |
import sys
import unittest
import tests.mockanki
from unittest.mock import patch, call, Mock, MagicMock
from ankiscript.addin import Addin
sys.modules['anki'] = MagicMock()
sys.modules['anki.httpclient'] = MagicMock()
import anki.httpclient
class AddinTest(unittest.TestCase):
@patch('ankiscript.add... |
seq_1 = 'ATCACAGT'
seq_2 = 'GACGCACG'
for i in reversed(range(len(seq_1)+1)):
for j in range(num_substrings(len(seq_1), i))
# seq_1[j:j+1] defines the common
seq_1[j:j+i]
if seq_1[i:j+i] in seq_2:
return seq_1[i:j+i]
n = range(len(seq_1)+1)
m = reversed(range(len(seq_1)+1))
... |
import unittest
from hdlConvertor import ParseException
from hdlConvertor.language import Language
from hdlConvertor import hdlAst
from tests.basic_tc import BasicTC, parseFile as _parseFile
def parseFile(fname):
return _parseFile(fname, Language.VHDL)
class VhdlConversionTC(BasicTC):
def test_dump_mux(s... |
class Out_put_vis():
def plot_fig(self,input1,pred,n):
plt.figure(1)
t=np.arange(1,10000,1)
p=input1.shape[0]
l=min(t.shape[0],pred.shape[0])
plt.plot(t[:p],input1[:p,0,0],'b--',t[:l],pred[:l,0,0], 'r--')
plt.savefig('C:/Users/Pranesh/Desktop/share/open_1'+n+... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
# import matplotlib.pyplot as plt
# from scipy.stats import norm
import scipy.stats as st
from mpmath import mp
mp.dps = 30
# ###########################################DATOS#########################
# muestra #1
S0 = ... |
friends = ["Tim", "Sasa", "Casey", "Craig", "Gigot"]
print(friends[2:4]) # prints friends[2] and friends[3], but not [4]
print(friends[1:]) # prints from friends[1] to the end of the list (all but friends[0]).
print(friends[:4]) # prints from the start of the list and prints friends[0] thru friends[3], but not f... |
# ##################################################################################################
# Copyright (c) 2020 - Fundação CERTI
# All rights reserved.
# ##################################################################################################
import numpy
import rasterio as rio
import pytest
from q... |
import random
from math import exp
from agent.agent import Agent
class ReinforcementLearning(Agent):
type = "RL"
'''
q(state, action)
The states are:
Each combination of owning stocks: 2 exp 10 stocks
The actions are:
3 for each stock: buy, sell
10 stocks
... |
# encoding=utf-8
__author__ = 'xiaowang'
__date__ = '17/2/16'
from itertools import *
# natuals = count(1, 2)
# for n in natuals:
# print n
# cs = cycle('ABC')
# for c in cs:
# print c
# ns = repeat('A', 10)
# x = [n for n in ns]
# print x
# natuals = count(1)
# ns = takewhile(lambda x:x<=10, natuals)
# l... |
from django.contrib import admin
from .models import Order,OrderDetails
admin.site.register(Order)
admin.site.register(OrderDetails) |
'''
字符串匹配和搜索
'''
import re
if __name__ == "__main__":
text1 = '11/27/2012'
text2 = 'Nov 27, 2012'
datepat = re.compile(r'\d+/\d+/\d+')
if datepat.match(text1):
print("match text1")
if datepat.match(text2):
print("match text2")
text = 'Today is 11/27/2012. PyCon starts 3/13/20... |
import json
from typing import List, Dict
import stanza
from tqdm import tqdm
import numpy as np
from data_processing.class_defs import SquadExample, SquadMultiQAExample, RepeatQExample, RepeatQFeature
from data_processing.dataset import Dataset
from defs import UNKNOWN_TOKEN
class RepeatQDataset:
def __init__(... |
class ventaDetalle:
def __init__(self,pro,pre,cant):
self.producto=pro
self.precio=pre
self.cantidad=cant |
# -*- coding: utf-8 -*-
from PyQt4 import QtGui
import sys
sys.path.append('../Controladores')
from main_controller import *
class MainWindows(QtGui.QWidget):
def __init__(self):
super(MainWindows, self).__init__()
self.controlador = MainControlador(self)
self.init_ui()
def init_ui(s... |
#!/usr/bin/env python
"""
Copyright (C) 2022 Andy Piltser-Cowan <awc34@cornell.edu>.
Released under Creative Commons Attribution-Sharealike License 4.0
Available at https://creativecommons.org/licenses/by-sa/4.0/
Contact the author if a different license is desired.
This should be considered alpha-quality software, ... |
#!/usr/bin/env python
import re
import urllib2
import crawler
url = "http://en.wikipedia.org/wiki/List_of_venture_capital_firms"
web_page = urllib2.urlopen(url)
#print web_page
vc_dict = dict()
crawler.crawl(url, vc_dict)
working_dict = vc_dict['http://en.wikipedia.org/wiki/List_of_venture_capital_firms']
#retri... |
# Generated by Django 2.2.4 on 2020-12-17 03:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app_fav_books', '0002_book'),
]
operations = [
migrations.AddField(
model_name='book',
name='description',
... |
import numpy as np
from scipy.cluster.hierarchy import dendrogram, linkage
from matplotlib import pyplot as plt
import math
x_points = [2,2,8,5,7,6,1,4]
y_points = [10,5,4,8,5,4,2,9]
# x_points = [0.4,0.22,0.35,0.26,0.08,0.45]
# y_points = [0.53,0.38,0.32,0.19,0.41,0.3]
points = np.array([x_points,y_points])
def get... |
# -*- coding: UTF-8 -*-
from . import bp_2DVectors
from flask import render_template
@bp_2DVectors.route('/',methods=['GET'])
def index():
return render_template('2DVectors/index.html')
@bp_2DVectors.route('/2DVectorsRep',methods=['GET'])
def VectorsRep2D():
return render_template('2DVectors/2DVectorsRep.html... |
#!/usr/bin/env python
from collections import namedtuple
from .quaternion import Quaternion
class Point(namedtuple('Point', ('x', 'y', 'z'))):
def __new__(cls, x=0, y=0, z=0):
return super(Point, cls).__new__(cls, x, y, z)
def rotate(self, q: Quaternion):
ix = q.w * self.x + q.y * self.z - q... |
"""
Util classes for HTTP/REST
"""
__author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2017 VMware, Inc. All rights reserved. -- VMware Confidential' # pylint: disable=line-too-long
# pylint: disable=C0103
class HTTPStatusCodes(object):
"""
Constants for HTTP status codes
"""
HTTP_200_OK = 200
... |
# create plots
import matplotlib.pyplot as plt
from datetime import datetime
# dictionary for conversion of variables (velicina)
prevodnik = {
'kumulativni_pocet_nakazenych': 'Kumulativní počet nakažených',
'kumulativni_pocet_vylecenych': 'Kumulatnvní počet vyléčených',
'kumulativn... |
from django.db import models
from datetime import datetime,timezone;
import string;
import random;
def getPromoCode():
'''
generate alphanumercial string used as promo code
'''
alpha_numeric=string.ascii_letters + string.digits;
random_code=''.join(random.choice(alpha_numeric) fo... |
import socket
import sys
import select
import getpass
import getopt
import time
#Klient TCP
try:
opts, ar = getopt.getopt(sys.argv[1:], 'p:s:l:i')
except getopt.GetoptError as ge:
print(repr(ge))
sys.exit()
value = ''
port = int(55500)
serwer = 'localhost'
pseudonim = getpass.getuser()
wyl_wys = 1
if l... |
import datetime
render = 0
pin = 0
starttime = 0
def initsc(renderA, pinA, starttimeA):
global render
global pin
global starttime
render = renderA
pin = pinA
starttime= starttimeA
def digitalRead(pinno):
global pin
if(pinno > 13):
return(bool(vars(pin)['pinA'+str(pinno-14)].st))... |
# coding: utf-8
from enum import Enum
from six import string_types, iteritems
from bitmovin_api_sdk.common.poscheck import poscheck_model
class DolbyVisionMetadataSource(Enum):
INPUT_STREAM = "INPUT_STREAM"
EMBEDDED = "EMBEDDED"
|
class Basic:
@staticmethod
def pesquisar(id_client):
import sqlite3
conexao = sqlite3.connect('dadosCliente.bd')
cursor = conexao.cursor()
cursor.execute('''
select * from Cliente inner join Endereco on Cliente.id_endereco = Endereco.id_endereco where id_cliente... |
from numpy import *
x = input("insira a string:")
y = x[0]
z = x[-1]
a = len(x)
b = x.lower()
c = x.upper()
d = x * 500
print(y)
print(z)
print(a)
print(b)
print(c)
print(d)
|
def add_submission(user: str, language: str, points: int, results: dict):
if user not in results['users']:
results['users'][user] = []
if language not in results['submissions']:
results['submissions'][l] = 0
results['users'][user].append(points)
results['submissions'][l] += 1
retur... |
notes = [100, 50, 10, 5, 2, 1]
t = int(input())
for test in range(t):
n = int(input())
count = 0
for note in notes:
while n >= note:
n -= note
count += 1
print(count) |
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(rc={"figure.figsize" : (12, 8)})
def plot_history(history) :
hist = pd.DataFrame(history.history)
hist["epoch"] = history.epoch
plt.figure()
plt.xlabel("Epoch")
plt.ylabel(... |
#! /usr/bin/env python3
# -*- coding:utf-8 -*-
# Importando as Bibliotecas
from bs4 import BeautifulSoup
import urllib.request
import os
import time
import re
import json
import csv
class SmartWatcher(): # Classe com o Robô Web Crawler
def __init__(self):
while True: # Chamada da função principal, que ap... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn import preprocessing
from sklearn.metrics import silhouette_samples, silhouette_score
import matplotlib.cm as cm
from sklearn.cluster import KMeans, AgglomerativeClustering, FeatureAgglomeration, MeanShift, Spectra... |
import os
import os.path
import numpy as np
import cv2
from PIL import Image
import matplotlib.pyplot as plt
from torchvision import datasets, transforms
from base import BaseDataLoader
from torch.utils.data import Dataset
import torch
path_to_img = "C:/Users/10138/Documents/yottacloud/code/water-meter-detect/data/... |
import os
import sys
import re
import shlex
GCC_DRIVER_LINE = re.compile('^Driving:')
POSIX_STATIC_EXT = re.compile('\S+\.a')
POSIX_LIB_FLAGS = re.compile('-l\S+')
def is_output_verbose(out):
for line in out.splitlines():
if not GCC_DRIVER_LINE.search(line):
if POSIX_STATIC_EXT.search(line) or... |
# Faça um Programa que leia três números e mostre o maior deles.
a = float(input('Informar o 1° número: '))
b = float(input('Informar o 2° número: '))
c = float(input('Informar o 3° número: '))
if b > a:
print(b)
elif c > a:
print(c)
else:
print(a)
|
from random import choice
from random import randint
import csv
def Utili():
BT = ['Miser','Geek','Generous']
GT = ['Choosy','Normal','Desperate']
GFT= ['Essential','Luxury','Utility']
Boy = [('B'+str(i),randint(2,20),randint(44,120),randint(100,300),randint(1,16),choice(BT))for i in range(1,51)]
G... |
from torch import nn
from torch.nn import MaxPool2d
from torch.nn.modules.conv import Conv2d
from torch.nn.modules.activation import Sigmoid, ReLU
def dcn_vgg(input_channels):
model = nn.Sequential(
Conv2d(input_channels, 64, kernel_size=(3, 3), padding=0),
ReLU(),
Conv2d(64, 64, kernel_... |
# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/
#
# 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, modi... |
import pytest
from zig.main_components import Graph
class TestDomElements:
#test passing of attributes to DomElement works
def test_div_creation(self):
test_id = "123"
test_figure = "figure"
test_section = []
# HOW TO TEST ALL attributes efficiently?
graph = Graph... |
consumer_key = 'xgkA30ZnNtxpx5rZ4M2ZeADyt'
consumer_secret = 'xUiCmURo5NVXYVeNrL2pvO8br4B355zGBWrAwOCfa1L1yweZtE'
access_token = '1184086168608088064-jPANfIKR0OsxoubRlO6t8RhdyJ7LCf'
access_secret = 'PhgH1FVI2Gkg2JFYchlcuS2PHz0Y6XGpjD1ifIbUpP932'
|
import webbrowser
class Movie():
# Class for symbolize a movie
def __init__(self, title, poster_url, trailer_url):
"""
Initialize a Movie object
title = a string of the movie title
poster_url = a string containing a URL to a poster image
trailer_url = a str... |
#!/usr/bin/python3
import RPi.GPIO as GPIO
import pigpio
import time
servo = 2
# more info at http://abyz.me.uk/rpi/pigpio/python.html#set_servo_pulsewidth
pwm = pigpio.pi()
pwm.set_mode(servo, pigpio.OUTPUT)
pwm.set_PWM_frequency( servo, 50 )
while 1:
for i in range(500, 2500, 50):
print( "{} deg".fo... |
# Generated by Django 3.1.6 on 2021-03-19 05:28
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('Feedback_Management_System', '0013_auto_20210319_1107'),
]
operations = [
migrations.RemoveField(
... |
import h5py
import numpy as np
import os
import matplotlib.pyplot as plt
import math
import affine
import h5py
import argparse
import sklearn
from sklearn.cluster import KMeans
from sklearn.mixture import GaussianMixture as GMM
from sklearn.decomposition import PCA
import pickle
import pandas as pd
pars... |
from sgmon.log import get_logger
import requests
from requests.exceptions import RequestException
logger = get_logger(__name__)
class HTTPClientError(Exception):
pass
def handle_exception(func):
"""
Decorator to catch exception
"""
def wrapped(*args, **kwargs):
try:
return ... |
from odoo import models, fields, api
import logging
_logger = logging.getLogger(__name__)
class DocumentRejection(models.TransientModel):
_name = 'document.rejection'
_description = "Reject Documents"
document_id = fields.Many2one(
'document.management', string="Document", readonly="True")
no... |
import cv2
import numpy as np
img = cv2.imread('images/Frog.jpg')
new_img = np.zeros(img.shape, dtype='uint8')
# Нахождение контуров объекта
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img = cv2.GaussianBlur(img, (5, 5), 0)
img = cv2.Canny(img, 100, 140)
con, hir = cv2.findContours(img, cv2.RETR_LIST, cv2.CHAIN_APP... |
#iput fom sys aruments
import sys
x=sys.argv[1]
y=sys.argv[2]
print("sys.argv[1]=",sys.argv[0])
print("x=",x)
print("y=",y)
print("sum= ",x+y)
|
import multiprocessing as mp
from threading import Thread
from common.constants import SCENE_GRID_BLOCK_WIDTH, SCENE_GRID_BLOCK_HEIGHT, SCENE_WIDTH, SCENE_HEIGHT
from common.enums.climb_state import ClimbState
from common.enums.collision_control_methods import CCMethods
from common.enums.direction import Direction
fro... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
chromedriver = 'C:/Users/jinyoung/Pictures/Crawling/janjaemi/chromedriver'
driver = webdriver.Chrome(chromedriver)
driver.get('https://python.org')
# title에 Python이 없으면 에러를 발생
assert "Python" in driver.title
# <input id="id-se... |
import boto3
import os
region = 'eu-west-1'
ec2 = boto3.client('ec2', region_name=region)
def handler(event, context):
print(event)
start_event_arn=os.environ["START_EVENT_ARN"]
stop_event_arn=os.environ["STOP_EVENT_ARN"]
event_arn=event["resources"][0]
if event_arn==stop_event_arn:
filters... |
import pytest
from parso.grammar import load_grammar
from parso import utils
def test_load_inexisting_grammar():
# This version shouldn't be out for a while, but if we ever do, wow!
with pytest.raises(NotImplementedError):
load_grammar(version='15.8')
# The same is true for very old grammars (even... |
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('./data/bok_statistics_CD_2.csv', header=0, index_col=0)
print(df.head(), '\n')
df['CD_rate'].plot(kind='hist')
df['change'].plot(kind='hist')
plt.show() |
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
from numpy.random import randn
from pandas import Series, DataFrame
import scipy
from scipy import stats
address='mtcars.csv'
cars=pd.read_csv(address)
cars.columns=['car_name','mpg','cyl','disp','hp','drat',
'wt','qsec','vs','am... |
def is_pangram(sentence):
alphabet = range(97, 123)
for index in alphabet:
if chr(index) not in sentence.lower():
return False
return True
|
# Generated by Django 2.1 on 2019-01-29 17:39
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Customer',
fields=[
('id', models.AutoField(a... |
from django.core.mail import send_mail
from django.utils import timezone
from swatusers.models import UserTask
from subprocess import check_call
from swatluu import geotools
import numpy as np
import os
import shutil
env = os.environ.copy()
env['PATH'] = '{0}{1}{2}'.format('/usr/local/bin', os.pathsep, env['PATH'])
... |
#!/usr/bin/python
import sys
import csv
inputlist= sys.argv
inputlist.pop(0)
for filename in inputlist:
f = open(filename, 'r')
reader = csv.reader(f, delimiter='\t', quotechar=None, doublequote=False)
out = open(filename[:-4] + "onecol.vcf", 'w')
outcsv = csv.writer(out, delimiter='\t', quotech... |
def duplicate_count(text):
text = text.lower()
print text
from sets import Set
ls = list(text)
st = Set(ls)
greater = []
for i in st:
if ls.count(i) > 1:
greater.append(i)
return len(greater)
|
# -*- coding: utf-8 -*-
from unittest import mock
from oauthlib.oauth2 import TokenExpiredError
from wbia.utils import call_houston
def disabled_test_call_houston(request):
client_patch = mock.patch('wbia.utils.BackendApplicationClient')
BackendApplicationClient = client_patch.start()
request.addfinaliz... |
import os
import sys
PROJECT_DIR = os.path.abspath(os.path.dirname(__file__))
PARENT_DIR = os.path.join(PROJECT_DIR, os.pardir)
sys.path.append(PARENT_DIR)
sys.path.append(PROJECT_DIR)
MONGO_DB = os.getenv('MONGO_DB') or 'instance_db'
MONGO_URL = os.getenv('MONGO_URL') or 'mongodb://127.0.0.1:27017/instance_db'
SM... |
from django.db import models
from django.conf import settings
from .constants import WidthChoices
class Comment(models.Model):
name = models.CharField(max_length=100)
content = models.TextField()
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('-created',)
def _... |
import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(-5,5,100)
print ('type(x) = ',type(x),' len = ', len(x) )
plt.plot(x,np.sin(x)) # on utilise la fonction sinus de Numpy
plt.ylabel('fonction sinus')
plt.xlabel("l'axe des abcisses")
plt.grid()
plt.show()
|
# -*- coding: utf-8 -*-
from flask.ext.wtf import Form
from wtforms import (
StringField,
PasswordField,
TextAreaField
)
from wtforms import validators
from wtforms.fields.html5 import EmailField
class AcademyForm(Form):
academy_name = StringField(
u'학원이름',
[validators.data_required... |
import numpy as np
import torch
from torch import nn
from sklearn.metrics import r2_score
import scipy
import matplotlib.pylab as plt
def mape_error(y_pred, y_true):
# y_pred=y_pred[:len(y_true)]
y_true, y_pred = np.array(y_true), np.array(y_pred)
return np.mean(np.abs((y_true - y_pred) / y_true))
# ===... |
#!/usr/bin/python
# Copyright (C) 2017-2020 Alex Manuskin
#
# 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 Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This pr... |
"""This class defines a device that measures the angle of a radio transmission comes from"""
from math import asin, sqrt, pow
C = 299792458
class Radiogoniometer:
def __init__(self, probes=None):
"""Constructor"""
if probes:
self.probes = probes
else:
self.probes... |
from __future__ import print_function
try:
import time
import os
import sys
import pickle
import argparse
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from plots import plot_bar_probs
from plots import plot_confusion_matrix
from plots import... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.