text stringlengths 38 1.54M |
|---|
import sys
import timeit
# The general idea is to get the set of points (relative to the central port) that each wire goes through.
# Then, get the intersection of the sets and iterate through that to find the closest point to the central port.
# With this attempt, I calculate the endpoints for each wire line and use ... |
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from .models import PromotionArticle
class PromotionListView(ListView):
model = PromotionArticle
paginate_by = 20
template_name = 'promotions/list/list.html'
def get_queryset(self):
return Promot... |
from flask import Flask, render_template, redirect ,request,url_for
from wtforms import StringField, BooleanField
from wtforms.validators import Length, InputRequired
from flask_wtf import FlaskForm
from bson import ObjectId
from flask_pymongo import MongoClient
from flask_bootstrap import Bootstrap
# creates a Flask ... |
__author__ = 'Todd.Hay'
# -------------------------------------------------------------------------------
# Name: SoundPlayer
# Purpose:
#
# Author: Todd.Hay
# Email: Todd.Hay@noaa.gov
#
# Created: Apr 04, 2016
# License: MIT
#-----------------------------------------------------------------... |
# coding:utf-8
import pandas as pd
import numpy as np
import os
#读取文件
PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))#获取项目根目录
path = os.path.join(PROJECT_ROOT,"课程负面评价.xlsx") #文件路径
df = pd.read_excel(path)#读取xlsx文件内容
print (df.shape)
print (df)
print ('------')
grouped = df.groupby(['sku','课程标题'])
array = n... |
import sys
r = sys.stdin.readline
def solution():
countryNum, answerIdx = map(int, r().rstrip().split())
country = []
rank = 1
countryCount = 1
for _ in range(countryNum):
country.append(list(map(int, r().rstrip().split())))
country = sorted(country, key=lambda x:(x[1], x[2], x[3... |
#!/usr/bin/python3
# Copyright 2020 Intel Corporation
#
# 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... |
import torch
from torch import nn
from torch.nn import functional as F
import numpy as np
from transformer.module import Encoder
class Relevance(nn.Module):
def __init__(self, space_dims, hidden_dims, relevance_dims):
super(Relevance, self).__init__()
self.gru = nn.GRU(space_dims, hidden_dims, bat... |
from django.contrib.auth.models import User, Group
from django.contrib import admin
from .site import admin_site
from .. import models
class UserAdmin(admin.ModelAdmin):
list_display = ['first_name', 'last_name', 'email', 'username']
search_fields = ('first_name', 'last_name', 'email', 'username')
class Me... |
#Snake
import pygame
import random
pygame.init()
#SCREEN
WIDTH=800
HEIGHT=600
screen=pygame.display.set_mode((WIDTH,HEIGHT))
#COLORS
WHITE=(255,255,255)
RED=(255,0,0)
BLUE=(0,0,255)
GREEN=(0,255,0)
BLACK=(0,0,0)
#CLASS FOR SNAKE
class Snake:
def __init__(self,x,y):
self.size=1
self.elements=[[x,... |
class ScraperException(Exception):
pass
class LogicError(ScraperException):
pass
class RollBack(Exception):
pass
class ParseError(Exception):
pass
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'gui.ui'
#
# Created: Mon May 19 22:42:29 2014
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeE... |
import os
import requests
from bs4 import BeautifulSoup, Comment
from datetime import datetime
from lxml import html
from collections import defaultdict
import re
class SkatteFunnParser:
def __init__(self,url, name, notes):
self.url = url
self.title = "SkatteFunn"
self.header = {'user-agent': 'Mozilla/5.0 (X1... |
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from .models import Report
from .forms import ReportForm
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render
def index(request):
return HttpResponse("HELLO WORLD")
def me(req... |
# coding: utf-8
# In[18]:
# imports
import pandas as pd
import statsmodels.formula.api as smf
import numpy as np
# allow plots to appear directly in the notebook
get_ipython().magic(u'matplotlib inline')
# In[19]:
# read data into a DataFrame
data = pd.read_csv("http://archive.ics.uci.edu/ml/machine-learning-dat... |
import tkinter as tk
form = tk.Tk()
form.title("RadioButton")
form.geometry("500x450")
x = tk.StringVar()
def kontrol():
if x.get() == "1":
print("buton1")
elif x.get() == "2":
print("buton2")
else:
print("buton2 ve buton1")
buton = tk.Button(form, text="tıkla",... |
import random
import numpy as np
import math
import time
import numpy
from otsu import otsu, fast_ostu
class GWO:
def __init__(self, image):
self.image= image
# self.N = N
self.Max_iter=1000
self.lb=-100
self.ub=100
self.dim=1
self.SearchAgents_no=5
... |
from rest_framework import routers
from tests.django_rest_framework_api.api import (
AuthorViewSet, PostViewSet)
router = routers.SimpleRouter()
router.register(r'post', PostViewSet)
router.register(r'writer', AuthorViewSet)
|
#Hector Jose Sosa Castro ,Matricula:2019-7889
n =(input("Introduce una frase para verificar si es diptongo:"))
if n.find('ia')!=-1:
print("Esta palabra es un diptongo")
elif n.find('au')!=-1:
print("Esta palabra es un diptongo")
elif n.find('ei')!=-1:
print("Esta palabra es un diptongo")
elif n.find('eu')!=... |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 06 12:10:47 2017
@author: Malumbo
The directory keeps track of connected processes and provides a simple discovery mechanism.
When a new process starts, it registers itself with the directory and fetches connection info
about other processes of interest.
The connection ... |
import matplotlib.pyplot as plt
import matplotlib.pyplot as mpl
Duplex = []
Lightning = []
payments = []
i = 4
with open('Results//DuplexMessages.txt', 'r') as f:
for line in f:
line, none0, none1 = line.partition(".")
try:
if i == 4:
Duplex.append(int(line))
... |
def main():
numdecimal=int(input("Ingrese un numero decimal (maximo 5 cifras):"))
num1=numdecimal //8
nu1=numdecimal-num1*8
num2=num1 //8
nu2=num1-num2*8
num3=num2 //8
nu3=num2 - num3*8
num4=num3 //8
nu4= num3 -num4*8
print("Numero en octal: ",nu1,nu2,nu3... |
import argparse
import logging
import os
import en_core_web_lg
import spacy
from spacy.matcher.matcher import Matcher
from spacy.symbols import nsubj, VERB
from spacy_readability import Readability
ADJECTIVE = 'adjective'
VERB = "verb"
ADVERB = 'adverb'
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 4 13:21:39 2020
@author: Rabia Tüylek
"""
import cv2
import numpy as np
import os
os.environ['OPENCV_VIDEOIO_PRIORITY_MSMF'] = "0"
#%% Recording Video
live_camera = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter("o... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020, 04, 14, 05, 40
# @Author : Allen Zhang
# @File : ~/a2g-wordsbook/main/new_words.py
# Usage:
# Default Constant Values:
WORD_CONFIDENCE = 1 # Define the word of threshold AWS Transcribe predicted confidence to choose
NEW_WORDS_FILENAME = "./words/new... |
#!/usr/bin/env python2.5
"""
#######################################################################
#
# Copyright (c) Stoke, Inc.
# All Rights Reserved.
#
# This code is confidential and proprietary to Stoke, Inc. and may only
# be used under a license from Stoke.
#
####################################################... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: Alex Wang
import src.alex_misc.hex2bin as hex2bin
# Set logger
from src.alex_misc.alex_logging import create_logger
log_frame = create_logger(logger_name=__name__, fmt='%(message)s')
class Frame(object):
def __init__(self, capture_file_path):
"""
Frame l... |
dict = {'a':50,'b':50,'c':50,'d':40, 'e':100,'f':20}
max=0
smax=0
thmax=0
l=[]
for i in dict:
if dict[i]>max:
max=dict[i]
max_key=i
for j in dict:
if dict[j]<max:
if dict[j]>smax:
smax=dict[j]
smax_key=j
for k in dict:
if dict[k]<max:
if dict[k]<smax:
... |
from .views import IndexHandler, LoginHandler
url_patterns = [
(r'/users/', IndexHandler),
(r'/users/login', LoginHandler)
] |
"""The enemy for the game"""
import random
import numpy as np
import pygame
from sprite.sprite_library import Collider
from sprite.health import Health, HealthBar
from utils import image_load, rot_matrix
from sprite.bullets import LinearBullet, BouncingBullet, BombBullet
class AttackPattern:
"""An attack patte... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import asyncio
import pytest
from abot.util import iterator_merge
async def three_yields():
yield 1
yield 2
yield 3
async def exception_yield():
yield 1
raise Exception()
@pytest.mark.asyncio
asy... |
from __future__ import absolute_import
import unittest
from agms.configuration import Configuration
from agms.transaction import Transaction
class RemoteTransactionTest(unittest.TestCase):
def setUp(self):
Configuration.configure('agmsdevdemo', 'nX1m*xa9Id', None, None, 'requests')
self.transacti... |
import re, logging
from django.conf import settings
from django.core.handlers.wsgi import STATUS_CODE_TEXT
req_handler = logging.FileHandler(settings.HOME_DIR + '/logs/requests.log')
req_handler.setLevel(logging.INFO)
formatter = logging.Formatter('[%(asctime)s] %(message)s')
req_handler.setFormatter(formatter)
req... |
import xml.etree.ElementTree as ET
class Person(object):
def __init__(self, first_name = None, last_name = None):
self.first_name = first_name
self.last_name = last_name
def name(self):
return(self.first_name + " " + self.last_name)
@classmethod
def getAll(self):
... |
import sys
import json
def main():
sent_file = open(sys.argv[1])
tweet_file = open(sys.argv[2])
#TODO: Implement
afinnfile = open('./data/AFINN-111.txt','r')
scores = {}
sentiment_scores = {}
i=0
j=0
for line in afinnfile:
term, score = line.split("\t")
scores[term] = float(score)
for line in tweet_file:... |
# Adopted from https://github.com/allenai/allennlp under Apache Licence 2.0.
# Changed the packaging.
from typing import List, Set, Tuple, Dict
import numpy
def decode_mst(
energy: numpy.ndarray, length: int, has_labels: bool = True
) -> Tuple[numpy.ndarray, numpy.ndarray]:
"""Note: Counter to typical in... |
#!/usr/bin/env python
from __future__ import print_function
import argparse
import sys
from apiclient.discovery import build
import google.auth
from google.auth import iam
from google.auth.transport import requests
from google.oauth2 import service_account
TOKEN_URI = 'https://accounts.google.com/o/oauth2/token'
... |
# sreesaibaba
import pymongo
class Db:
def __init__(self):
"""
"""
self.client = pymongo.MongoClient('mongodb://localhost:27017')
self.db = self.client.data
self.fm_users = self.db.fmusers
def view_fm_users(self):
"""
"""
results = []
c... |
#!/usr/bin/python
class Singleton(object):
_state = {}
def __new__(cls, *arg, **kw):
#print cls.__class__ #type
if not cls._state.has_key(cls):
cls._state[cls] = super(Singleton, cls).__new__(cls, *arg, **kw)
#print "+++",cls._state[cls].__class__ #Singleton
retur... |
import sched
import time
from decimal import Decimal
from binance.websockets import BinanceSocketManager
from datetime import datetime
class OrderBookService(object):
def __init__(self, client, base, quote, callback, name):
self.binance_client = client
self.buffer = []
self.recovere... |
#!/usr/bin/python
import math
from .Support_Files import constants as consts
from .Support_Files import extmath
sea = 0
high = 6
class atmosphere:
def __init__(self):
self.__Teff = 0.5 # Transmission efficiency
self.__lambdaref = 1e-6 # Reference wavelenght
self.__thetaref... |
"""
String constants for usage in QCCT
"""
stUnknown = "Unknown"
stHead = "HEAD"
stBody = "BODY"
stAir = "AIR"
stWater = "WATER"
stTungsten = "TUNGSTEN"
stTeflon = "TEFLON"
|
import numpy as np
# Normalises training data for better training
class FeatureNormalise:
"""Normalises data using mean std normalisation
Usage:
Call function batchData to train on data.
After whole data is received call fit and transform
"""
def __init__(self, n_features):
sel... |
#%%
from bs4 import BeautifulSoup
import requests
from time import time
#%%
def find_title(head):
title = head.find('meta', {'property' : "og:title"})
if title != None:
return(title['content'])
title = head.find('meta', {'name' : "twitter:title"})
if title != None:
return(title['cont... |
import six
def utf8bytes(maybe_text):
if maybe_text is None:
return
if isinstance(maybe_text, six.binary_type):
return maybe_text
return maybe_text.encode('utf-8')
def utf8text(maybe_bytes, errors='strict'):
if maybe_bytes is None:
return
if isinstance(maybe_bytes, six.te... |
# Import the library
import requests
def main():
# Get the API endpoint
URL = "https://api.chucknorris.io/jokes/random"
# Store the result here
result = requests.get(url = URL)
# Convert the result to json format
json_data = result.json()
json_joke_value = json_data["value"]
# Displa... |
#Originally project from here https://github.com/fogleman/Poker
#New authors: Abraham Ludlam and Hezekiah Pilli
#This code evaluates poker hands for 5 and 7 card poker. We added the functionality of 3 player 7 card poker and providing a UI for the user to interact with to run the evaluation functions as much as they ... |
import unittest
from tests.test_common import create_css_file
from icon_font_to_png import load_css
class TestLoadCSS(unittest.TestCase):
def test_common_prefix(self):
css_file = create_css_file(
".foo-bar:before { content: '\\f001' }\n"
".foo-xyzzy:before { content: '\\f002' }\n"... |
from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
import datetime #for checking renewal date range.
class addEventForm(forms.Form):
event = forms.CharField(help_text="Enter the event title")
date = forms.DateField(help_text="Ent... |
# f=open("w3_Q11.txt","w")
# a=f.write("hey \ni am muskan\ni am from utter pradesh")
# print(a)
# f.close()
# #size of file
def remove_newlines(fname):
flist = open(fname).readlines()
print(flist)
# return [s.rstrip('\n') for s in flist]
print(remove_newlines("w3_Q11.txt"))
|
#!/usr/bin/python
# ex:set fileencoding=utf-8:
from __future__ import unicode_literals
import django_filters
from django import forms
class HasValueFilter(django_filters.Filter):
field_class = forms.NullBooleanField
def filter(self, qs, value):
if value is not None:
lookup = '%s__isnull... |
삼성전자 = 50000
총평가금액 = 삼성전자*10
print(총평가금액)
시가총액 = 298000000000000
현재가 = 5000
PER =15.79
print(시가총액, type(시가총액))
print(현재가,type(현재가))
print(PER, type(PER))
s = "hello"
t = "python"
print(s+"!", t)
print(2+2*3)
a ="132"
print(type(a))
num_str ="720" #형변환
num_int =int(num_str)
print(num_int, type(num_int))
num = 100
n... |
n, k = map(int, input().split())
# k = max(1, k)
arr = list(map(int, input().split()))
prefix = [10 ** 18] * n
ind = [10 ** 18] * n
for i in range(n):
if i == 0:
prefix[i] = arr[i]
ind[i] = 0
continue
if prefix[i - 1] < arr[i]:
prefix[i] = arr[i]
ind[i] = i
else:
... |
# project/api/exercises/exercises.py
from sqlalchemy import exc
from flask import Blueprint, jsonify, request
from project import db
from project.api.utils import authenticate
from project.api.exercises.models import Exercise
exercises_blueprint = Blueprint('exercises', __name__)
@exercises_blueprint.route('/exe... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
Copyright 2017-2019 Baidu 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... |
from utils.vector import Vector
from utils.progress import show_progress
DIRECTIONS = [
Vector(0, -1), # UP
Vector(1, 0), # RIGHT
Vector(0, 1), # DOWN
Vector(-1, 0) # LEFT
]
def read_input():
return [
list(line.rstrip())
for line in open('input.txt')
]
def grid_to_di... |
# analyzes twitter comments
import nltk
positive_words = []
negative_words = []
class Analyzer():
"""Implements sentiment analysis."""
def __init__(self, positives, negatives):
"""Initialize Analyzer."""
self.positives = positives
self.negatives = negatives
with open(positi... |
from tkinter import *
import tkinter as tk
import tkinter.font as tkFont
from tkinter import ttk
from tkcalendar import Calendar,DateEntry
from ttkthemes import ThemedStyle
from functools import partial
import pandas as pd
import mysql.connector
import numpy as np
from table_class import *
#from db_class imp... |
class Vector2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector2D(self.x + other.x , self.y + other.y)
def __sub__(self, other):
return Vector2D(self.x - other.x , self.y - other.y)
def __eq__(self, other):
return self.x ... |
import socket
import click
import struct
import pathlib
import numpy as np
from liveplotter import LivePlotter
import matplotlib.pyplot as plt
import matplotlib.animation as animation
@click.command(context_settings=dict(help_option_names=['-h', '--help']))
@click.option('-l', '--localip', type=click.STRING, default='... |
# Script Tarea 1
import numpy as np
from math import factorial
from matplotlib import pyplot as plt
import os
# Pregunta 3
print("Pregunta 3")
print(1**np.inf)
print(2**np.inf)
print(np.e ** np.inf)
print(np.e ** -np.inf)
# print(np.sign(np.nan))
# print(np.sign(-np.nan))
print(np.nan**0)
print(np.inf**0)
print(1**np.n... |
from os import listdir
import pandas as pd
import logging
import pickle
def find_csv_filenames(path_to_dir, suffix=".csv"):
"""Find Names of CSV files
Args:
path_to_dir (string): Path to the directory
suffix (str, optional): Extension to use. Defaults to ".csv".
Returns:
List of ... |
# dirstate.py - working directory tracking for mercurial
#
# Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
import errno
from node import nullid
from i18n import _
import scmutil... |
import tensorflow as tf
class RoiClassifier(tf.keras.models.Model):
def __init__(self, num_classes, **kwargs):
super().__init__(**kwargs)
self.flatten = tf.keras.layers.Flatten(name='flatten')
self.fc1 = tf.keras.layers.Dense(4096, activation='relu', name='fc1')
self.do1 = tf.keras.l... |
''' This document contains my code for the PHYS 479 Leapfrog techniques, Classical
Harmonic Oscillators and 3-body simulations assignment which is divided into two parts.
The first part (Question 1) involves simulating a classical harmonic oscillator using
a Leapfrog technique. The second part (Question 2) uses th... |
def main():
print('jsak')
print('SECOND')
print('hjka')
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 9 08:17:28 2019
@author: dhersch1
"""
## Import necessary modules
import pandas as pd
import os
import matplotlib.pyplot as plt
import datetime
from tkinter import filedialog
from tkinter import *
root = Tk()
root.filename = filedialog.askopenfilenam... |
"""
@file
@brief description of a blog post
"""
import datetime
from textwrap import dedent
import jinja2
from pyquickhelper.loghelper.convert_helper import str2datetime
class BlogPost:
"""
A blog post.
::
<item>
<title>Raw food</title>
<link>http://www.xavierdupre.fr/bl... |
import sqlite3
cardsToIncludeFile = open('foundIds.txt', "r")
cardsToInclude = []
for everyLine in cardsToIncludeFile.readlines():
cardsToInclude.append(everyLine.replace('\n', ""))
cardDatabase = sqlite3.connect('cards.cdb')
cursor = cardDatabase.cursor()
cursor.execute('SELECT * FROM datas')
datas = cursor.fetch... |
# coding: utf-8
# @author octopoulo <polluxyz@gmail.com>
# @version 2020-08-29
"""
Inspect JS files
"""
import os
import re
import sys
from time import time
BASE = os.path.dirname(__file__)
if BASE not in sys.path:
sys.path.append(BASE)
from commoner import read_text_safe
BASE = os.path.dirname(os.path.dirnam... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_pddbserver
----------------------------------
Tests for all the bottle server-related methods from the `pddb` module.
"""
import os
import sys
import json
import unittest2
from pddb import PandasDatabase
class TestPandasDatabaseServerMethods(unittest2.TestCase... |
from PIL import Image, ImageOps
import glob, os
# im1 = Image.open('stone_var0.bmp')
# im2 = Image.open('dg_var0.png')
#
# mask = Image.open('mask_round.bmp')
#
# small_mask_2 = mask.crop((33, 0, 66+33, 64+0)).convert('L')
# small_mask_1 = mask.crop((99, 0, 66+99, 64+0)).convert('L')
#
#
# # inv masks:
# small_mask_1... |
#!/usr/bin/python3
#The count() method returns the number of occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.
#str.count(sub, start= 0,end=len(string))
str = "this is string example....wow!!!"
sub = 'i'
print ("str.count('i') : ", str.count(... |
import requests
def uam_func_sync(request,*args):
try:
requests.get(args[0]+'/functions_sync/?prj_name='+args[1]+'&client_name='+args[2]+'&prj_uid=' + str(request.user.id) + '&func_module='+args[3]+'&func_page='+args[4])
except Exception as e:
print(e)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Daniel Berenberg
"""
simple_decryption core library. Contains cipher helper functions and
Cipher class hierarchy
"""
import string
import random
from collections import Counter
from .utils import cache_pickle, chunks
__all__ = ["SubstitutionCipher","AbstractCip... |
from cs50 import get_int
from math import floor
# Prompt user for positive int
def main():
while True:
card_number = get_int("Card Number: ")
if card_number > 0:
break
return card_number
# Check the legnth of CC number
i = int(card_number * 1)
counter = 0
... |
from .models import Summoner
from request_maker.utils import make_request
def get_challengers():
challenger_data = make_request('league/v4/challengerleagues/by-queue/RANKED_SOLO_5x5', None)
for player in challenger_data['entries']:
try:
summoner = Summoner.objects.get(summonerName=player['summonerName'])
exce... |
# https://leetcode.com/problems/sliding-puzzle/
# 773. Sliding Puzzle
# History:
# Google
# 1.
# Apr 29, 2019
# 2.
# Mar 17, 2020
# 3.
# May 8, 2020
# On a 2x3 board, there are 5 tiles represented by the integers 1 through 5,
# and an empty square represented by 0.
#
# A move consists of choosing 0 and a 4-directiona... |
#!/usr/local/bin/python3
"""
Created on Mon May 20 2019
@author: Xiao Zhang
@id: 78369457
"""
from GenericHashClass import *
class LinearProbing(GenericHashClass):
label = "Linear Probing"
def __init__(self):
GenericHashClass.__init__(self)
self.N = 9887
def set(self, key):
index... |
#!/usr/bin/python -tt
#Make it a bit more like python3:
from __future__ import absolute_import
from __future__ import print_function
import coverage
import os
import shutil
import sys
import unittest
def main():
major, minor, micro, releaselevel, serial = sys.version_info
if major == 2 and minor < 7:
... |
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
from sklearn.svm import SVC
iris = load_iris()
logreg = LogisticRegression()
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target,
... |
import sys
import sqlite3 as sq
conn=sq.connect("test.db")
cur=conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS phone_book(name text,number INTEGER)")
cur.execute("SELECT * FROM phone_book")
r=cur.fetchall()
def add():
call=(sys.argv[2],sys.argv[3])
for search in r:
if sys.argv[2] in search:
... |
#Este programa determina cual es el numero maximo de tres numeros dados
a = int(input('Dame el primer numero: '))
b = int(input('Dame el segundo numero: '))
c = int(input('Dame el tercer numero: '))
if a > b:
if a > c:
maximo = a
else:
maximo = c
else:
if b > c:
maximo = b
else:
if c > a:
if c > b:
... |
from gevent import monkey, pool
monkey.patch_all()
import requests
from BeautifulSoup import BeautifulSoup as BS
# Scrapes from the Coinwarz site
# Get the index
def get_main():
req = requests.get("http://www.coinwarz.com/cryptocurrency/coins")
c = req.content
a = BS(c)
coins = a.findAll("div", {"cla... |
import numpy as np
from numpy.random import seed
seed(1)
from numpy import array
import pandas as pd
import datetime
from datetime import datetime
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
import tensorflow as tf
tf.ran... |
"""
Thompson sampling example
"""
import numpy as np
from arm import BernoulliArm, GaussianArm
from bandit import StaticBandit, LinearInterpolationBandit
from strategy import ThompsonBernoulli, ThompsonGaussianKnownSigma
if __name__ == '__main__':
np.random.seed(0)
# Bernoulli
bernoulli_bandit = Stati... |
import ast
import io
import tokenize
from typing import Optional, Union
import astor
from astor.string_repr import pretty_string
from flynt.exceptions import ConversionRefused
from flynt.linting.fstr_lint import FstrInliner
from flynt.utils.format import QuoteTypes, set_quote_type
def nicer_pretty_string(
s,
... |
#Данные для создания клиента
api_id = 6262981
api_hash = 'a354281220e0be50000c7c90b3434f9e'
api_client = 'me_parser'
channels = ['parser_test1']
# 'EUC_market' |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# FileName : util.py
# Author : Feather.et.ELF <fledna@qq.com>
# Created : Thu Jun 14 20:23:14 2012 by Feather.et.ELF
# Copyright : Feather Workshop (c) 2012
# Description : description
# Time-stamp: <2012-06-14 20:54:34 andelf>
import getpass
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 18 13:36:33 2019
@author: michael.schulte
"""
import gym
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
env = gym.make('FrozenLake-v0')
alpha = 0.2
alpha_decay = .99999
GAMMA = .9
epsilon = 0.5
eps_decay = .999
EPISODES ... |
from django.shortcuts import render, redirect
from django.views.generic import View, TemplateView
from django.http import Http404
from django.http import HttpResponse
from .forms import *
from .models import *
from django.core.files.storage import default_storage
# Create your views here.
class CustomerIndexView(View... |
import os
import sys
import scipy.io
import scipy.misc
import matplotlib.pyplot as plt
from matplotlib.pyplot import imshow
from PIL import Image
import numpy as np
import tensorflow as tf
class CONFIG:
IMAGE_WIDTH = 224
IMAGE_HEIGHT = 224
COLOR_CHANNELS = 3
NOISE_RATIO = 0.6
def gen... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
from scipy.optimize import fsolve
#%%
# Functions
def dTlm_F(Tsat,To,Ti):
num = (Tsat-To) - (Tsat-Ti)
dom = np.log((Tsat-To) / (Tsat-Ti))
return num/dom
def mu_w(T):
A = -52.843
B = 3703.6
C = 5.866
D = -5.879e-29
... |
import pyaudio
import webrtcvad
import queue
import threading
import numpy as np
import math
import wave
import matplotlib.pyplot as plt
from scipy.io import wavfile
import sys
import collections
class WebRTCVAD:
def __init__(self, sample_rate=16000, level=0):
"""
Args:
sample_rate: au... |
import numpy as np
from .HHMMtoDec import HHMMtoDec
from .DateJoin import DateJoin
import datetime
def DatetimetoDate(dt):
'''
Convert datetime objects to dates and times
Inputs
======
dt : datetime
Array of datetimes
Returns
=======
Date : int
Date array in the format yyyymmdd
ut : float
Time array ... |
# Filename: gtd_action_rows.py
# Author: Darren Hart <darren@dvhart.com>
# Description: Actionable gtd objects for use in datastores
#
# 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; eit... |
# Copyright (C) 2011 Lukas Lalinsky
# Distributed under the MIT license, see the LICENSE file for details.
import logging
from acoustid.handler import Handler, Response
from acoustid.data.track import lookup_mbids
from acoustid.data.musicbrainz import lookup_metadata
from acoustid.data.submission import insert_submiss... |
import cs_grading.comparison_tools as comp
import cs_grading.executable_tools as exe
import cs_grading.io_tools as sysio
import cs_grading.logging_tools as log
import cs_grading.result_tools as res
####################################################################################################
# Purpose: Runs exec... |
print "Starting analyzing..."
UNAFFECTED_FILES = []
AFFECTED_FILES = []
# Mappings from human ID to another mapping of position to variant.
unaffected_variant_info = {}
affected_variant_info = {}
print "Checkpoint 1"
# Populate data structure of unaffected children.
for unaffected_file in UNAFFECTED_FILES:
unaffe... |
from abc import ABC, abstractmethod
import os, sys
import numpy as np
import time, random, threading, sys
import multiprocessing
from graph import *
import constants
lock = threading.Lock()
graph_train = None
graph_test = None
graph_train_number = 0
graph_test_number = 0
test_end = False
class Agent(ABC):
@a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.