text stringlengths 38 1.54M |
|---|
import os
import pytesseract
from PIL import Image
from collections import defaultdict
pytesseract.pytesseract.tesseract_cmd = r"D://Tesseract-OCR/tesseract.exe"
def get_threshold(image):
pixel_dict = defaultdict(int)
rows, cols = image.size
for i in range(rows):
for j in range(cols):
... |
from golem import actions
from golem.webdriver.extended_webelement import ExtendedRemoteWebElement
from golem.webdriver.extended_webelement import ExtendedFirefoxWebElement
description = 'Verify that the webdriver.find method can find a web element by xpath positional arg'
def test(data):
actions.navigate(data.... |
from math import floor, sqrt
# Beatty's sequence with sqrt(2)
# General form would be for n wanted instances
# sum of floor(sqrt(2)*k) for k to n
# Even more general
# S(a, n) where a is the irrational and n is the amount of inputs
# S(a,n) = summation k=1 to n floor(a*k)
# https://mathworld.wolfram.com/BeattySequenc... |
from django.urls import path
from .views import ticket_list
app_name = 'support_ticket'
urlpatterns = [
path('', ticket_list, name='ticket_list')
] |
import tensorflow as tf
xNode = [784, 500, 10]
xLayer = ['layer1', 'layer2']
input_node = xNode[0]
output_node = xNode[-1]
def get_weight_variable(shape, regularizer):
weights = tf.get_variable("weights", shape, initializer=tf.truncated_normal_initializer(stddev=0.1))
if regularizer != None:
tf.add_... |
from golem import actions
from golem.core.exceptions import ElementNotDisplayed
description = 'Verify webdriver.find throws error when time is out and element is still not displayed'
def test(data):
actions.navigate(data.env.url+'dynamic-elements/?delay=5')
browser = actions.get_browser()
actions.step('F... |
import matplotlib.pyplot as plt
import random
arquivo = open("base.csv","r", encoding = "utf8")
arq = arquivo.readlines()
tp = 0.25
zn = 1.96
splits = 5
classificacao = []
itens = []
for linha in arq:
t = linha.split(";")
citacao = t[0]
clas = t[1].rstrip('\n')
itens.append(citacao)
classificacao... |
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
# In[2]:
#import json file
purchasedata = "purchase_data.json"
purchasedataDF = pd.read_json(purchasedata)
#purchasedataDF.head()
# Player Count
# Total Number of Players
# In[3]:
# take value counts on SN and print the len to get total player co... |
from random import choice
import unittest
from _base import StructureTestsBase
from part_1_ADT.queues import Deque
from part_1_ADT.dynamic_array import DynamicArray
class DequeTestsBase(StructureTestsBase):
_TEST_CLS = Deque
_ARRAY_CLS = DynamicArray
_FILL_METHOD = 'add_tail'
def check_items_after_... |
#导入工具
import requests
res = requests.get("http://www.bcactc.com/home/gcxx/now_sgzbgg.aspx")
res.text
#lxml是一个专门用于解析xml语言的库
from lxml import etree
response = etree.HTML(res.text)
values = response.xpath('//div[@style="float:right"]/text()[1]')[0].strip()
|
#!/usr/bin/env python
from functools import reduce
def tree_count(m, slope_x, slope_y):
trees = 0
x = slope_x
for y in range(slope_y, len(m), slope_y):
if m[y][x] == '#':
trees += 1
x = (x + slope_x) % len(m[y])
return trees
def main(m):
trees = reduce(
lambda ... |
import tensorflow as tf
import numpy as np
from matplotlib import pyplot as plt
import math
# this function adds noise per channel with gaussian distribution
def add_gaussian_noise(img,mean,variance,scale):
# get dimensions and set the noise size
height, width, channel = img.shape[0],img.shape[1],img.shape[... |
"""
This file is part of the everest project.
See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.
Created on Apr 11, 2013.
"""
import pytest
from everest.constants import CARDINALITIES
from everest.constants import CARDINALITY_CONSTANTS
from everest.constants import Cardinality
__docformat_... |
""" Challenge 168 Task 1 LK Python """
from sympy import isprime
def generate_perrin_primes(n: int) -> list:
"""
Generate all primes up to n using the Perrin sequence.
"""
perrin_sequence = [3, 0, 2]
perrin_primes: dict = {}
while len(perrin_primes.keys()) < n:
next_number = perrin... |
from django.contrib.auth import get_user_model
from rest_framework import mixins, viewsets, status
from rest_framework.generics import get_object_or_404
from rest_framework.response import Response
from rest_framework_simplejwt.tokens import RefreshToken
from api_auth.serializers import (AuthenticationSerializer,
... |
# origin: profilehooks 1.6 (http://pypi.python.org/pypi/profilehooks) :
'''
Copyright (c) 2004--2012 Marius Gedminas <marius@pov.lt>
Copyright (c) 2007 Hanno Schlichting
Copyright (c) 2008 Florian Schulze
Released under the MIT licence since December 2006:
Permission is hereby granted, free of charge, to any pers... |
#Amber Evans
#9-26-2020
#program 5-10
#This program demonstrates what happens when you
#change the value of a parameter.
def main():
value =99
print(f'The value is {value}.')
change_me (value)
print (f'Back in main the value is {value}.')
def change_me(arg):
print('I am changing the value.')
a... |
def add_poly(p1, p2):
d = {}
for i,j in p1 :
if j not in d :d[j] = i
else : d[j] += i
for i,j in p2 :
if j not in d :d[j] = i
else : d[j] += i
return [(i[1],i[0]) for i in sorted(list(d.items()))[::-1] if i[1] != 0]
def mult_poly(p1, p2):
d = {}
for i,j in p1:
... |
from pathlib import Path
from scisort import scisort_keygen
from scitree import scitree
tree = ["data", "README.md", "scripts", "installation.R", "requirements.txt", "tests"]
tree_expected = [
"README.md",
"installation.R",
"requirements.txt",
"data",
"scripts",
"tests",
]
def test_keygen(... |
#
# Uses the emacsclient feature to allow editing a string
# We should reverse engineer the emacs lisp (looks fairly easy)
# to skip the file completely
#
import commands
import os
import pwd
def edit(astring):
filename = os.path.join('/tmp', pwd.getpwuid(os.getuid())[0]+'-emacsclient')
f = open(filename,'w')
f... |
# coding: utf-8
# In[16]:
from imutils import face_utils
import numpy as np
import imutils
import argparse
import dlib
import cv2
import random
from PIL import Image
# import the necessary packages
from imutils.face_utils import FaceAligner
from imutils.face_utils import rect_to_bb
import argparse
import imutils
imp... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Usage:
show-image-meta <file>
show-image-meta [-h | --help | --version]
Options:
-v --version show the version
-h --help show the help
--debug enable debugging
'''
import docopt
import os
import sys
from PIL import Ima... |
import elie
import random
from utils import debug
class Escape(Exception):
pass
def test_pos(subgrid, pos):
x,y = pos
return subgrid[x][y] == 0
def mark_random(preferred_pos, subgrid, morpion):
debug("caca")
something_marked = False
checked = set()
nice_pos = set()
pos = None
w... |
# Copyright 2018-2023 Xanadu Quantum Technologies 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... |
from django.conf import settings
from django.contrib.sites.models import Site
def debug(context):
return {'DEBUG': settings.DEBUG}
def site_name(context):
current_site = Site.objects.get_current()
return {
'SITE_URL':current_site.domain
} |
import pytest
from calcul_droite import *
from units import *
#TODO : case pour l'hemisphère sud
def test_calc_declinaison_for_days():
to_be_tested = [
# year, month, day, result
(2020, 4, 13, (pytest.approx(179.8637*degrees), pytest.approx(9.135786*degrees))),
(1998, 3, 4, (pytest.approx(... |
"""
Method :meth:`detector_factory` in :class:`PyDetector` returns instance of the detector data accessor
=====================================================================================================
Method detector_factory(src,env) switches between detector data access objects depending on source paramete... |
import random
def generate_answer():
answer = random.sample(range(0,9),4)
if answer[0] == 0:
answer.reverse()
return int(''.join(str(e) for e in answer))
def calculate_bulls(answer, user_answer):
count=0
answer = list(str(answer))
user_answer = list(str(user_answer))
for i in range(4):
if answer[i] == use... |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from pandasql import sqldf
import copy
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import confusion_matrix
import itertools
##########... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Original created on Sun Jul 31 13:10:33 2016
Original code is in from /bfast/python/bfast.py
That code was running complete n all.
This version created on Thu Oct 6 13:10:33 2016.
The first change here is that I'm removing main() and
adapting bast() so that it can be ... |
import pysam
import re
import gzip
import os
import sys
__author__ = "Noah Ollikainen, Charlotte A Lai, Peter Chovanec"
class Position:
"""This class represents a genomic position, with type of nucleic acid (DNA)
Methods:
- to_string(): Returns a string representation of this position in the form
"... |
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Game(models.Model):
title = models.CharField(max_length=200, unique=True)
publisher = models.CharField(max_length=200)
genre = models.CharField(max_length=200)
year = votes = models.IntegerField(d... |
import os
import numpy as np
import matplotlib.pyplot as plt
from glob import glob
from skimage import measure
import ersa_utils
# get test data
gammas = [2.5, 1, 2.5]
sample_id = 3
data_dir = r'/media/ei-edl01/data/aemo/samples/0584007740{}0_01'.format(sample_id)
files = sorted(glob(os.path.join(data_dir, 'TILES', '*... |
def findChar(list, char):
newList = []
for i in list:
if char in i:
newList.append(i)
return print(newList)
word_list = ['hello','world','my','name','is','Anna']
char = "a"
findChar(word_list, char) |
graph = {
'A' : ['D'],
'B' : ['C','D'],
'C' : ['B'],
'D' : ['A','B']
}
def dfs(graph, node, visited):
if node not in visited:
visited.append(node)
for n in graph[node]:
dfs(graph, n, visited)
return visited
visited = dfs(graph,'A', [])
print(visited) |
from Utilities.ImageFormats import ImageFormats
import validators
def get_file_name(url):
list = url.split("/")
name = list[len(list)-1]
return name
def get_file_extension(name):
list = name.split(".")
ext = list[len(list) - 1]
return ext
def is_image(url):
name = get_file_name(url)
... |
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import render
from .models import Article
# Create your views here.
def index(request):
articles = Article.objects.order_by('-created_at')[:2]
return render(request , 'index.html' , {
'title' : 'Articles Pa... |
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", reshape=False, one_hot=True)
X = tf.placeholder(tf.float32, [None, 28, 28, 1])
Y_ = tf.placeholder(tf.float32, [None, 10])
W = tf.Variable(tf.zeros([784,... |
from linkedlist import LinkedList
class LL(LinkedList):
def __init__(self):
super().__init__()
def undupe(self):
buffer = set()
n = self.head
if n:
buffer.add(n.data)
else:
return
while n.next:
if n.next.data not in buffer:
... |
"""
Determination of the echo top height from radar PPI data using the
Lakshmanan et al. (2013). method
@title: echotop
@author: Valentin Louf <valentin.louf@monash.edu>
@copyright: Valentin Louf (2018-2019)
@institution: Monash University
@reference: Lakshmanan et al. (2013), "An Improved Method for Estimating Radar
... |
import socket
import datetime
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as so:
so.sendto(b"", ("127.0.0.1", 123))
time, _ = so.recvfrom(254)
l_time = time.decode("utf-8")
r_time = datetime.datetime.now()
print(f"Действительное время: {r_time}")
print(f"Время от сервера: {l_time}... |
from django.forms import ModelForm
from .models import ShippingAddress
class CheckoutForm(ModelForm):
class Meta:
exclude = ('customer', 'order', 'completed')
model = ShippingAddress
def save(self, user, order):
shipping_address = ShippingAddress.objects.create(
customer=u... |
from __future__ import annotations
import time
from random import randint
from element import Element
import pongaccelerated as pong
from pyg import Screen, load_and_scale, load_texture, TEXTURE_ROUTES, LOG_ROUTES
from pygcontext import PygContext
from pygtext import Text
from unsafe_vector import V, Vector
class D... |
"""Tests for functions inside visual_shopping_image_utils."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
import tf_testing_utils
import visual_shopping_image_utils as image_utils
class VisualShoppingImageUt... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from collections import Counter
def main():
c = Counter()
for line in sys.stdin:
label, prediction, _ = line.split('\t')
pair = (label, prediction)
if pair == ('+1', '+1'):
c['TP'] += 1
elif pair == ('+1', '-... |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 4 10:04:31 2019
@author: quinn.ramsay
"""
import datetime
from detectors import PredictionDetector
from video_analysis import VideoAnalyzer
def get_image_path(relative_path):
return "images/" + relative_path
def get_video_path(relative_path):
... |
# -*- coding: utf-8 -*-
# Scrapy settings for huaban project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
# http://scrapy.readthedocs.org/en/latest/... |
from django.contrib.auth.models import User
from django.db import models
from taggit.managers import TaggableManager
class Project(models.Model):
title = models.CharField(max_length=20)
description = models.TextField()
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(a... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author: H.L. TIAN 2017
#import DroNECore
import DroNECore.PyIncident as PI
import NEON
import json
class NeonRPCCronIncident(PI.PyCronIncident):
def __init__(self, name, cron = 0, repeatable = False):
super(NeonRPCCronIncident, self).__init__(name, cron, rep... |
from io import BytesIO
from celery import task
from dotenv import load_dotenv
import os
import weasyprint
from django.template.loader import render_to_string
from django.core.mail import EmailMessage
from django.conf import settings
from orders.models import Order
@task
def payment_completed(order_id):
order = Ord... |
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import matplotlib.pyplot as plt
# load data
(x_train, _), _ = keras.datasets.mnist.load_data()
x_train = x_train.astype('float32').reshape((-1, 28, 28, 1)) / 255.
# build with tf
encoder_input = keras.Input... |
#!usr/bin/python3
import unittest
import experiment as exp
from rdflib import Graph
import datetime
import time
# import rdflib
class Test(unittest.TestCase):
def setUp(self):
self.g = Graph()
self.g.parse("../graph/for_test_graph.ttl", format="turtle")
self.mashup = "http://www.programm... |
n1 = int(input('Digite o primeiro numero: '))
n2 = int(input('Digite o segundo numero: '))
if n1 > n2:
print(n1, 'e maior que ', n2)
elif n2 > n1:
print(n2, 'e maior que ', n1)
else:
print('Os numeros sao iguais')
|
from .home import Index
from .login import Login, logout
from .signup import Signup
from .cart import Cart
from .checkout import CheckOut
from .order import OrderView
|
import jwt,json
from sqlalchemy import desc,func
from sqlalchemy.orm import Session,sessionmaker
from app.config.models import Account,SystemLog,Parking,Trx_Data,Lane,Einvoice_Number_Data,Garage
from app.services.exceptions import UserNotExistError,AuthenticationError
from app.services.systemlog_service import S... |
import h5py
import os
import tensorflow as tf
from numpy.random import RandomState
import numpy as np
MODEL_SAVE_PATH = "model/"
MODEL_NAME = "model.ckpt"
INPUT_NODE_NUM = 10
f = h5py.File('route_prediction.h5','r')
data = f['data'][:]
#print(data[3])
x = tf.placeholder(tf.float32, shape = (None,INPUT_NODE_NUM), n... |
from flask import Flask, jsonify
from flask_pymongo import PyMongo
app = Flask(__name__)
app.config["MONGO_URI"] = "mongodb://localhost:27017/obsco"
mongo = PyMongo(app)
@app.route('/users/<int:userId>', methods=['GET'])
def get_user(name = '', userId = -1):
users = mongo.db.users
results = []
#N... |
def bfs():
q=[(s,0)];v=[s]
while len(q):
n,c=q.pop(0)
if n==e:return c
for i in range(1,l+1):
if i not in v and m[n][i]:q.append((i,c+1));v.append(i)
return 0
for t in range(int(input())):
l,k=map(int,input().split());m=[[0]*(l+1)for _ in range(l+1)]
for i in rang... |
"""
============================
Author:柠檬班-木森
Time:2020/2/7 20:py26_32day
E-mail:3247119728@qq.com
Company:湖南零檬信息技术有限公司
============================
"""
"""
封装的需求:
1、读取数据
2、写入数据
封装目的:
1、提高代码的重用率
封装的时候有哪些数据需要参数化?
1、excel文件名
2、表单名
"""
import openpyxl
class R... |
from unittest.mock import MagicMock, patch
import pytest
from UM.Scene.SceneNode import SceneNode
from cura.Machines.Models.MultiBuildPlateModel import MultiBuildPlateModel
from cura.Scene.CuraSceneController import CuraSceneController
from cura.UI.ObjectsModel import ObjectsModel
@pytest.fixture
def objects_model(... |
import argparse
import os
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import PIL
import scipy.io
import scipy.misc
import tensorflow as tf
from keras import backend as K
from keras.layers import Conv2D, Input, Lambda
from keras.models import Model, load_model
from matplotlib.pyplot import im... |
import webbrowser
name = input("What is your name?")
print("Hi {0}! I am your artificial friend Harvey!".format(name))
continueForward = input("""Would you like to continue forward?
Type yes or no: """)
def quizShow():
return webbrowser.open("https://docs.google.com/presentation/d/1rXtEToGUqqhEYTYEE2oIt7rV... |
# Copyright 2019 Huawei Technologies Co., Ltd
#
# 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... |
import requests
from .models import Character, Episode, Location
def generate_request(url, params={}):
response = requests.get(url, params=params)
if response.status_code == 200:
return response.json()
def get_episodes():
response1 = generate_request('https://integracion-rick-morty-api.herokuap... |
#!/usr/bin/python
# Uptime over 4 hours by percent
import requests
r = requests.get('https://p.datadoghq.com/screen/shared_batch_update/1xfifX-a17f211ecb')
percent = "{:.2%}".format(r.json()["responses"]["4"][0]['value'] / 100.)
print percent
|
import copy
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.init import xavier_uniform_
from torch.nn.utils.rnn import pad_sequence
from models.decoder import TransformerDecoder
from models.encoder import Bert, TransformerEncoder, PositionalEncoding
from models.generator... |
from enum import Enum
from app.main.util.exception.FileException import UnknownFileTypeException
class FileType(Enum):
Document = 0
Photo = 1
@staticmethod
def from_string(string_file_type):
if not FileType.__dict__.__contains__(string_file_type):
raise UnknownFileTypeException(s... |
#!/usr/bin/env python
# -*- coding: utf-8
# Copyright 2017-2019 The FIAAS Authors
#
# 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
#
# Unle... |
import os
import random
from django.db import models
from django.db.models import Count
def get_filename_ext(filepath):
# /..../helloworld.jpg
#helloworld.jpg
base_name = os.path.basename(filepath)
#helloworld-> name
#jpg --> ext
name, ext = os.path.splitext(base_name)
return name, ext
... |
from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render
from .utils import get_org_units, get_data_el, get_geojson, get_analytics, get_geojson_4
def org_view(request):
if 'q' in request.GET:
q = request.GET['q']
org_units = get_org_units(query... |
import discord
from discord.ext import commands
import random
class __8ball(commands.Cog, name='8ball'):
def __init__(self, bot):
self.bot = bot
self.response = ['Yes', 'No']
@commands.command(name='8ball',description="Answers a yes or no question",usage='<question>')
async def _8ball(self,ctx,*,question=None... |
import os
import pytest
from .. import create_app
@pytest.fixture
def client():
"""Create and configure a new app instance for each test."""
os.environ['FLASK_ENV'] = "Testing"
app = create_app()
ctx = app.app_context()
ctx.push()
client = app.test_client()
yield client
|
from django.shortcuts import render, redirect,render_to_response
from .forms import *
from django.contrib.auth import authenticate
def login(request):
loginuser=LoginForm()
if request.method == "POST":
loginpost = LoginForm(request.POST)
if loginpost.is_valid():
user = authenticate... |
#!/usr/bin/env python3
from sys import stdin, stdout, stderr, argv
from re import compile
def abort_compilation(message):
stderr.write('%s\n\n' % message)
stderr.write('Aborting compilation.\n')
quit(1)
def parse_rd(line, args):
if len(args) != 1:
abort_compilation('line %d: wrong argument ... |
from django.contrib import admin
from .models import Alunos, Turmas, Estrelas
# Register your models here.
class Aluno(admin.ModelAdmin):
list_display = ['nome', 'turma']
search_fields = []
class Turma(admin.ModelAdmin):
list_display = ['turma']
search_fields = []
class Estrela(admin.ModelAdmin):
... |
import numpy as np
import pandas as pd
print('Hello World!')
df = pd.read_csv('../git_test_moved.csv')
print(df.head())
df['Food'] = ['P', 'G', 'F', 'A']
df.to_csv('../git_update.csv')
print(df.head()) |
import matplotlib.pyplot as plt
import networkx as nx
class Drawer(object):
def __init__(self, file_name='graph.png'):
self.graph = nx.Graph()
self.file_name = file_name
def draw_deep_graph(self):
options = {
'node_color': '#FF0000', # цвет узла
'node_size': 5... |
#!/usr/bin/python
import dbus, flimflam
flim = flimflam.FlimFlam(dbus.SystemBus())
for service in flim.GetObjectList("Service"):
properties = service.GetProperties(utf8_strings = True)
print "[ %s ]" % (service.object_path)
for key in properties.keys():
print " %s = %s" % \
(key,... |
import keg_mail.content as content
class TestEmailContent(object):
def test_content_is_dedented(self):
text = """
stuff
thing
"""
cont = content.EmailContent(text, text)
assert cont.text == "stuff\nthing"
assert cont.html == "stuff\nthing"
def test_con... |
#! /usr/bin/env python
import sys
import os
cflags = os.environ.get("CFLAGS", "")
os.environ["CFLAGS"] = cflags + " -fno-strict-aliasing"
from distutils.core import setup, Extension
setup(name="pysubnettree",
version="0.19", # Filled in automatically.
author_email="info@bro-ids.org",
license="BSD",
... |
import FWCore.ParameterSet.Config as cms
nEvtLumi = 4
nEvtRun = 2*nEvtLumi
nRuns = 64
nStreams = 4
nEvt = nRuns*nEvtRun
process = cms.Process("TESTSTREAMMODULES")
import FWCore.Framework.test.cmsExceptionsFatalOption_cff
process.options = cms.untracked.PSet(
numberOfStreams = cms.untracked.uint32(nStreams),
... |
import re
def prepare_text(text):
text = text.replace('\t', ' ').replace('\n', ' ')
text = re.sub(r' +', ' ', text)
text = text.strip(' ')
return text
def split_into_sentences(text):
sentences = []
parts = re.split(r'([\.\?\!]) \s*(?![^()]*\))', text)
for i in range(len(parts))[::2]:
... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class BlstmCNNModel(nn.Module):
def __init__(self, sentence_length, vocab_size, embedding_dim, output_size, kernel_dim=32, lstm_dim=32, dropout=0.2, bn_momentum=0.2):
super(BlstmCNNModel, self).__init__()
# 1 input image channel, 6... |
import os
import time
import requests
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import e... |
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from DMS.ipredictor.models import HoltWintersI, HybridI, LSTMI, HoltI, HoltWinters, HybridIPoints, ANN, ANNI
from DMS.ipredictor import tools
if __name__ == "__main__":
# Seed switch
np.random.seed(36)
file =... |
from sllist import SkipiNode as Node
class SkipiList:
"""
This class represents a special kind of a doubly-linked list
called a SkipiList. A SkipiList is composed of Nodes (SkipiNode from
sllist).cIn addition to the data, each Node has one pointer to the
next Node in the list, and another pointer t... |
# Copyright 2017, Google Inc. 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 required by applicable law or ... |
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
import time
import random
from selenium.webdriver.common.keys import Keys
import sys
pchars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
uchars = '123567890'
def gen():
print('''What email ... |
import numpy as np
import scipy.sparse as sp
import numpy as np
from time import time
class Dataset(object):
'''
Loading the data file
trainMatrix: load rating records as sparse matrix for class Data
trianList: load rating records as list to speed up user's feature retrieval
... |
import time
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))
screen.fill((255, 0, 0))
start_time = time.time()
seconds = 4
WOW123 = True
while WOW123:
screen.fill((255, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
WOW123 = False
... |
import re
from MainUserRegistration.UserRegistrationException import UserException
class UserRegistration:
FIRST_NAME_PATTERN = r'^[A-Z][a-z]{3,}$'
LAST_NAME_PATTERN = r'^[A-Z][a-z]{3,}$'
EMAIL_PATTERN = r'^[0-9a-zA-Z]+([._+-][0-9a-zA-Z]+)*[@][0-9A-Za-z]+([.][a-zA-Z]{2,4})*$'
PHONE_NUMBER_PATTERN = r... |
import jieba
import re
f=open("test.txt","r")
content=f.read()
content=re.sub(re.compile('\n+'),"",content)
# content=content.replace(",","")
# content=content.replace("。","")
# print(content)
seg_list = jieba.cut(content, cut_all=True)
print("Full Mode: " + "/ ".join(seg_list)) # 全模式
# for item in seg_list:
# pr... |
'''Solution for Exercise "Correlation" in Chapter 11 '''
# author: Thomas Haslwanter, date: Sept-2015
import numpy as np
import pandas as pd
from scipy import stats
import matplotlib.pyplot as plt
import seaborn as sns
def getModelData(show=True):
''' Get the data from an Excel-file '''
# First, define ... |
class Vecter3:
def __init__(self, x=0, y=0, z=0):
self.X = x
self.Y = y
self.Z = z
def __add__(self, n):
r = Vecter3()
r.X = self.X + n.X
r.Y = self.Y + n.Y
r.Z = self.Z + n.Z
return r
def __sub__(self, n):
r = Vecter3()
r.X =... |
#The GUI draft (COMMENT OUT FOR NOW)
#fonts
from tkinter import *
from tkinter import messagebox
from tkinter import font
#hTimes10 = (family="Times",size=10,weight="bold")
top = Tk()
top.geometry("400x400")
#Function for Commands
def printchoice(e):
output = E.curselection()
print(output)
def PlaySong():
msg = m... |
import torch
import meshzoo
def generate_2D_mesh(H, W):
_, faces = meshzoo.rectangle(
xmin = -1., xmax = 1.,
ymin = -1., ymax = 1.,
nx = W, ny = H,
zigzag=True)
x = torch.arange(0, W, 1).float().cuda()
y = torch.arange(0, H, 1).float().cuda()
xx = x.repeat(H, 1)
y... |
import functions
import csv
import os
import numpy as np
# Functions
macd = functions.get_macd # 3 random variables
ema = functions.get_ema # 2 random variables
rsi = functions.get_rsi # 1 random variable
timestamp = []
# Import prices of each stock
with open('prices.csv') as g:
reader = csv.reader(... |
# Make an array of translated impact forces: translated_force_b
translated_force_b = force_b - np.mean(force_b) + 0.55
# Take bootstrap replicates of Frog B's translated impact forces: bs_replicates
bs_replicates = draw_bs_reps(translated_force_b, np.mean, 10000)
# Compute fraction of replicates that are less than th... |
import time
print("Ingrese su peso")
p=input()
print("Ingrese su altura")
a=input()
mc=p/(a^2)
print("Su masa corporal es " + mc)
time.sleep(5)
|
from setuptools import find_packages, setup
setup(
name="harvester",
version="1.0",
packages=find_packages(),
include_package_data=True,
install_requires=["click", "sickle", "smart_open"],
entry_points={
"console_scripts": [
"oai=harvester.cli:main",
]
},
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.