text stringlengths 38 1.54M |
|---|
Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> # Number System Conversion
>>>
>>> bin(25)
'0b11001'
>>> # bin converts decimal to binary system
>>> # This is how you convert
>>> # Divide... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.tsa.api import ExponentialSmoothing, SimpleExpSmoothing, Holt
from sklearn.metrics import mean_squared_error
from math import sqrt
#Importing data
#df = pd.read_csv('CreditCardAuthorization.csv')
#Printing head
#df.head()
#Print... |
def openOrSenior(data):
return ["Senior" if person[0] >= 55 and person[1] > 7 else "Open" for person in data]
|
# Problem promt:
# Reverse the digits of an integer
def reverse(num):
sign = 1
if num < 0:
sign = -1
num = str(abs(num))
num = num[::-1]
num = sign * int(num)
if num > 2147483647 or num < -2147483647:
return 0
return num
# test cases
print reverse(0)
print reverse(-63482)
print reverse(112345123452345)
p... |
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*
import RPi.GPIO as GPIO
import time
from datetime import datetime
from PIL import Image
import pygame
from pygame.locals import *
import os
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)
pygame.init()
screen = pygame.display.set_mode((0,0),pyga... |
import os
import numpy as np
import pandas as pd
import argparse
import progressbar
parser = argparse.ArgumentParser(description='Code to preprocess data from the eICU database')
parser.add_argument('--path', help='Path to eICU database', required=True, type=str)
args = parser.parse_args()
assert len(args.path) > 0... |
from cotton.scm import Git
from fabric import api as fab
from fabric.api import env
class BroadGit(Git):
def git(self, *commands):
with fab.prefix(". /broad/tools/scripts/useuse && use Git-1.7"):
with fab.prefix("umask 0002"):
super(BroadGit, self).git(*commands)
|
from matplotlib import pyplot
from openpyxl import load_workbook
wb = load_workbook('C:\\Users\\p.mykhailyk\\Seafile\\p4ne_training\\data_analysis_lab.xlsx')
sheet_data = wb['Data']
sheet_A = sheet_data['A'][1:]
sheet_B = sheet_data['B'][1:]
def getV(x): return x.value
A_V = list(map(getV,sheet_data['A'][1:]))
B... |
# -*- coding: utf-8 -*-
from django.test import TestCase
from Instanssi.kompomaatti.models import Entry
VALID_YOUTUBE_URLS = [
# must handle various protocols and hostnames in the video URL
"http://www.youtube.com/v/asdf123456",
"https://www.youtube.com/v/asdf123456/",
"//www.youtube.com/v/asdf123456... |
import sys # to accept the files from a command line argument as stream
import string # to use the punctuation to remove punctuations from the file
def guess(model, doc):
""" This function guesses the genre of a given document.
It uses sum of polarities to classify the document to its correct genre.
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable=W0102
from __future__ import (division, absolute_import, print_function,
unicode_literals)
# memoization
# python object, keys will be the arg to fn, value will be the resturn value
def fib(n, memo={}):
if n in memo:
... |
import local_learning.models.loopy.factory.leaves as leaves
import local_learning.models.loopy.factory.operators as operators
import local_learning
debug_exceptions = local_learning.debug_exceptions
def indent_code_block(code_block):
return '\n'.join(' ' + line for line in code_block.splitlines())
class Ren... |
from __future__ import print_function
import io
import os
os.remove('./data.txt')
for entry in os.scandir('./clean'):
with io.open(entry, 'r') as f:
file = f.read()
new_path = './data.txt'
new_lyrics_file = open(new_path, 'a+')
new_lyrics_file.write(file)
new_lyrics_file.close()
|
thisdict={
"brand":"ford",
"model":"mustang",
"year":1966}
if "model" in thisdict:
print("YES, It's in thisdict")
thisdict={
"brand":"ford",
"model":"mustang",
"year":1966}
print(len(thisdict))
thisdict={
"brand":"ford",
"model":"mustang",
"year":1966}
... |
#!/usr/bin/python3
import numpy as np
class ScrapBooker:
@staticmethod
def crop(array, dimensions, position=(0, 0)):
p = position
d = tuple(i if i < j else j for i, j, in zip(dimensions, array.shape))
if any(True for i, j in zip(d, dimensions) if dimensions > d):
print("Di... |
class Gel:
"""The Gel object defines a swelling gel.
Notes
-----
This object can be accessed by:
.. code-block:: python
import material
mdb.models[name].materials[name].gel
import odbMaterial
session.odbs[name].materials[name].gel
The table data for this objec... |
from sklearn.base import BaseEstimator, TransformerMixin
import numpy as np
import pandas as pd
class first_sums(BaseEstimator, TransformerMixin):
"""
a general class for creating a machine learning step in the machine learning pipeline
"""
def __init__(self):
pass
def fit(self, X, y=None)... |
#class Solution:
# def beautySum(self, s: str) -> int:
def beautySum(s):
if len(s) <= 2:
return 0
# Now assured that len(s) >= 3.
somme = 0
for head in range(len(s) - 2):
statistics = {s[head]: 1}
if s[head+1] in statistics:
statistics[s[head+1]] += 1
... |
import unittest
from ho600_ltd_libraries.utils.tests import *
if __name__ == '__main__':
unittest.main()
|
import matplotlib.pyplot as plt
import pygad as pg
import numpy as np
import h5py
import caesar
ssfr_lim = -1.5
n_lim = 1000
model = 'm50n512'
snap = '151'
wind = 's50j7k'
plot_dir = './all_pygad_plots/'
factor = 10.
softening = pg.UnitArr([0., 0., 0., 0., 0.25, 0.], 'ckpc h_0**-1')
xaxis = [0, 1, 2]
yaxis = [1, 2, ... |
# Make a calculator that does +, -, *, and /, however, alerting if the special "ZeroDivisionError" or any errors occur.
import sys
def InputFunction():
try:
FirstNumber = float(input("What is the first number? "))
SecondNumber = float(input("What is the second number? "))
Operation = input("... |
# -*- coding: utf-8 -*-
"""WSGI server."""
import argparse
import sys
from flask import Flask, request, jsonify
from flask_cors import CORS
from werkzeug.exceptions import BadRequest, NotFound, InternalServerError
from .columns import list_columns, update_column
from .datasets import list_datasets, create_dataset, ge... |
"""MixtapeServeur URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
C... |
# Copyright (c) SkyTruth
# Author: Egil Moeller <egil@skytruth.org>
# Parts of the code reused from loaddata.py and dumpdata.py from Django
# Copyright (c) Django Software Foundation and individual contributors.
# All rights reserved.
# Redistribution and use in source and binary forms, with or without modification,... |
import sys
from string import punctuation
def sort(tup):
return tup[1]
vowels = {
'a': 0,
'e': 0,
'i': 0,
'o': 0,
'u': 0
}
for line in sys.stdin:
line = line.strip().split()
for word in line:
word = word.strip(punctuation).lower()
if not word:
continue
for letter in word:
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 9 18:39:16 2019
@author: Alex
"""
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import confusion_matrix, accuracy... |
# This implementation of Lanczos interpolation is just too slow to run
# import matplotlib
# matplotlib.use('Agg')
import sys
import os
from glob import glob
import numpy as np
import fitsio
import astropy.io.fits as fits
import fitsio
from desitarget.targetmask import desi_mask
from desitarget.geomask import match
# ... |
from os import sys, path
from importlib import import_module
def getSettings(environment: str, defaultConfig: dict):
'''
getSettings function import the environment config given by argument
when our application is run.
@environment: string
@defaultConfig: dictionary contains applic... |
# Generated by Django 2.2.7 on 2019-11-25 10:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hipeac", "0046_hipeac_hipeacpartner"),
]
operations = [
migrations.AddField(model_name="hipeac", name="visible", field=models.BooleanField(d... |
__author__ = 'lotso'
from scrapy import cmdline
# cmdline.execute("scrapy crawl asusMBspider -o asusMB.json".split())
cmdline.execute("scrapy shell http://www.asus.com/Motherboards/Intel_Platform_Products/".split())
|
print("Enter the string:")
string= str(input())
print("You entered:",string)
l= len(string)
palin=True
for i in range(0,l):
if i==l:
pal= True
elif string[i]==string[l-1-i]:
pal= True
else:
palin= False
print("mismatch at",i,l-i)
if palin== False:
print("it is not apalind... |
# This file loads all the configfiles from ~/.config/qutebrowser/config.d/
## Documentation:
## qute://help/configuring.html
## qute://help/settings.html
import os
config = config # noqa
CONF_DIR = os.path.expanduser("~/.config/qutebrowser/config.d/")
for file in os.listdir(CONF_DIR):
if file.endswith(".p... |
from urllib2 import urlopen
from json import load,dumps
import re
from random import sample
from multiprocessing import Pool
def splitpgraph(pgraph):
return re.split('\w{5,}\. ',pgraph)
def getFacts(subject, num_titles=3, num_sentences=27):
subject = re.sub(' ','_',subject) # put input into wiki format i.e. '... |
from django.shortcuts import render, render_to_response
from decimal import Decimal
# Create your views here.
def home_view(request):
num_a = request.GET.get("num_a")
function = request.GET.get("function")
num_b = request.GET.get("num_b")
context = perform_function(num_a, function, num_b)
return ... |
import tornado.web
import json
import logging
from Crypto.CommonEvclide import CommonEvclide
async def Evclide(a, b):
return CommonEvclide(a, b)
class EvclideHandler(tornado.web.RequestHandler):
async def post(self):
body = self.request.body.decode("UTF8")
message = json.loads(body)
lo... |
#! /usr/bin/env python
# encoding:utf-8
def merge(list1,list2):
return dict(zip(list1,list2))
if __name__ == "__main__":
list1 = [1,2,3]
list2 = ['abc','def','ghi']
print merge(list1,list2)
|
"""
Simple task list.
"""
def new(tasklist, task):
"""Add new task"""
tasklist.append(task)
def remove_by_num(tasklist, tasknum):
"""Remove by number"""
if tasknum > 0 and tasknum <= len(tasklist):
tasklist.pop(tasknum - 1)
def remove_by_name(tasklist, taskname):
"""Remove by name"""
if... |
import io
import sys
def parse_group(stream):
abc = 256*[0]
count = 0
while True:
str = stream.readline()
if str == "": return None
if str == "\n": break
for q in str.strip(): abc[ord(q)] += 1
count += 1
sum = 0
for elt in abc:
if elt == count: sum += 1
return sum
sum = 0
stream = open(sys.argv... |
#
# [273] Integer to English Words
#
# https://leetcode.com/problems/integer-to-english-words/description/
#
# algorithms
# Hard (22.95%)
# Total Accepted: 66.7K
# Total Submissions: 289.2K
# Testcase Example: '123'
#
# Convert a non-negative integer to its english words representation. Given
# input is guaranteed ... |
'''
终止程序并给出错误信息
'''
import sys
if __name__ == "__main__":
sys.stderr.write("It failed!\n")
raise SystemExit(1)
print("hhaha") |
import random
import matplotlib.pyplot as plt
import matplotlib.lines as lines
import sys
import copy
def cost_calculation(A,B):
Ax = list(A)[0]
Ay = list(A)[1]
Bx = list(B)[0]
By = list(B)[1]
distance = ((Ax-Bx) ** 2 + (Ay-By)**2)**.5
return distance
def a_star_search(ocean_edges, start, end)... |
from sysconfig import get_platform
from setuptools import setup, Extension
with open('README.rst') as fd:
long_description = fd.read()
classifiers = [
'Development Status :: 5 - Production/Stable',
'Environment :: Win32 (MS Windows)',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',... |
s=set({1,2,3})
p=set({4,5,6})
print(p)
'''s.add(1)
s.add(2)
s.add(3)'''
s1=s.union({1,2,3})
print(s,s1)
print(s.isdisjoint(p))
s.union()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (... |
from flask import (
Flask, Response, render_template, request, g, abort, make_response
)
from mock import patch, MagicMock
from openc2 import Command, Response as OpenC2Response
from libcloud.compute.base import NodeImage, NodeSize, Node
from libcloud.compute.types import Provider
from libcloud.compute.providers imp... |
from django.core.management.base import BaseCommand
from PiControl.models import Schedule
import rollbar
from django.conf import settings
class Command(BaseCommand):
help = 'cron for schedule'
def handle(self, *args, **options):
rollbar.init(settings.ROLLBAR['access_token'])
schedules = Sche... |
"for"
for i in ["dubian","gomez",3]:
print("hola",end=" ")
for i in "cosas que pasan ":
print("hola",end=" ")
email = False
for i in "dubian@cosasquepasan":
if i == "@":
email=True
if email:
print("es correcto")
else:
print("no es correcto")
email2 = True
mi_i = input("introduce tu ... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class AutoItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
price = scrapy.Field()
mileage = scrap... |
path = r'C:\Users\admin\Desktop\TestData.properties'
with open(path, 'r', encoding='UTF-8') as f:
li = f.readlines()
with open(path, 'w', encoding='UTF-8') as w:
for line in li:
if line.startswith('en_us.common.common.connectbrowser.url.value'):
w.write('en_us.common.common.connectbrowser.u... |
import tensorflow as tf
import model.layer as layers
import util.operation as op
from model.attr_net import Attr_Net
from model.senti_net import Senti_Net
class Joint_Net(object):
def __init__(self, config):
self.graph = tf.Graph()
self.config = config
self.A_Net = Attr_Net(self.config)
... |
from cryptography.fernet import Fernet
key = Fernet.generate_key()
file = open("encryption_key.txt", 'wb')
file.write(key)
file.close() |
vec = []
with open("sorted.txt", "r") as infile:
for line in infile:
words = line.split()
vec.append(words[0])
dic = {}
out = []
with open("processed.tsv", "r") as infile, open("vectors.tsv", "w") as outfile:
count = 1
for line in infile:
for entry in vec:
d... |
from ... import api as Z
class Layer(object):
"""
Object that pairs a tensor transformation with the state it uses.
"""
def __init__(self, x_sigs=None, y_sigs=None):
if x_sigs is None:
xsnd = None
else:
assert isinstance(x_sigs, list)
xsnds = []
... |
import spotipy
import spotipy.util as util
def Spotify_Client(path):
with open(path, "r") as f:
username, client_id, client_secret = [x.strip() for x in f]
redirect_uri = "http://localhost:8000"
scope = "playlist-read-private playlist-read-collaborative user-read-recently-played user-library-read u... |
from dal import autocomplete
from django.db.models import Q
from django.shortcuts import render
from django.utils import six
from django.utils.decorators import method_decorator
from django.views import generic
from django.views.decorators.cache import never_cache
from .models import DocumentTemplate
from .forms impor... |
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as charts
import numpy as numpy
import itertools as tools
def plot_learning_curves(train_losses, valid_losses, train_accuracies, valid_accuracies):
graph, labels = charts.subplots(1, 2, figsize = (20, 10))
labels[0].set_title('Loss Curves')
label... |
from rest_framework import mixins
from rest_framework.generics import GenericAPIView
# not used anymore. just use an existing API view and add the required mixin to add functionality
class CreateOrDestroyView(mixins.CreateModelMixin,
mixins.DestroyModelMixin,
Generi... |
#!/usr/bin/python3
import os
import argparse
import time
import urllib.request
import email.mime.text
import socket
import getpass
import subprocess
def lookup_mac_vendor(mac_address):
result = ""
if mac_address:
for i in range(3):
vendor = None
try:
# Only firs... |
from enum import Enum
from typing import List
from pydantic import BaseModel
class MoveFileStrategy(str, Enum):
"""Strategy available for file move"""
OVERWRITE = 'overwrite'
RENAME = 'rename'
class MoveFileRequest(BaseModel):
"""Request data for file move"""
files: List[str]
destination: str... |
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_bcrypt import Bcrypt
from sqlalchemy import text
import base64
import uuid
from datetime import datetime
from sqlalchemy import create_engine
from sqlalchemy.sql import text
app = Flask(__name... |
from typing import List, Union, NamedTuple
from .dictionary import ZMachineDictionary
from .data_structures import ZWord, ZByte
class WordAndOffset(NamedTuple):
word: str
offset: int
next_offset: int
def _next_word(memory: memoryview, word_separators: List[int], offset: int) -> Union[None, WordAndOffse... |
import json
from .recipe_class import Recipe
# Receives request from frontend, returns list of ingredients
def process_incoming_data(request):
# Get data from request (a list of strings = ingredients)
data_in = json.loads(request.body) # the body of the request is a list of ingredients (list of strings)
... |
import urllib.request
url = 'http://cirtec.ranepa.ru/Word2Vec/fixes.raw.txt'
response = urllib.request.urlopen(url)
data = response.read() # a `bytes` object
with open('../initial_data/Word2Vec__fixes.raw.txt', 'wb') as f:
f.write(data)
|
#!/usr/bin/env python2
if __name__ == '__main__':
import ctypes
import sys
if sys.platform.startswith('linux'):
try:
x11 = ctypes.cdll.LoadLibrary('libX11.so')
x11.XInitThreads()
except:
print "Warning: failed to XInitThreads()"
import os
import sys
sys.... |
from __future__ import with_statement
from pyaspell import Aspell
from util.net import isurl
from common.spelling.dicts import MakeDigsbyDict
from common.filetransfer import ManualFileTransfer
from common import profile, pref
from common.notifications import fire
objget = object.__getattribute__
import wx, os
import... |
import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
from kvv_processor.model.weather import Weather
Base = declarative_base()
class DatabaseWeather(Base):
__tablename__ = 'Weather'
id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
temp = sqlalchemy.Column(sqlalchemy.DECIM... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 13 13:40:52 2019
@author: domin
"""
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import axes3d
#used to plot the Bloch sphere
phi = np.linspace(0, np.pi, 20)
theta = np.linspace(0, 2 * np.pi, 30)
blochX = np.outer(np.sin(... |
import torch
import torch.nn as nn
from transformers import BertModel
class TextClassificationModel(nn.Module):
def __init__(self, rnn_dim, rnn_num_layer, im_dim, que_dim, key_dim, deep, num_class):
super(TextClassificationModel, self).__init__()
self.dropout = nn.Dropout(0.2)
self.rnn = ... |
import requests
import logging
logging.getLogger("requests").setLevel(logging.DEBUG)
rq = requests.Session()
resp = rq.get('http://127.0.0.1:8085/foo')
assert('/foo' in resp.text)
assert('/bar' not in resp.text)
print(resp)
resp = rq.get('http://127.0.0.1:8085/bar', timeout=2)
assert('/bar' in resp.text)
assert('/foo'... |
import calendar
def main():
date = input("Enter a date formatted as dd/mm/rrrr: ")
date_list = date.split('/')
day = date_list[0]
month = int(date_list[1])
month_full_name = calendar.month_name[month]
year = date_list[2]
print(f'{day} {month_full_name} {year}')
main()
|
# Generated by Django 3.1.10 on 2021-07-30 09:15
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("editorial", "0018_add_help_text"),
]
operations = [
migrations.DeleteModel(
name="EditorialPageSubjectPlacement",
),
]
|
#!bin/python3
size = int(input().strip())
Arr = [int(arrItem) for arrItem in input().strip().split(' ')]
e = Arr[len(Arr) - 1]
tempIndex = 0
#print(Arr, len(Arr), e)
#Finds where the location we want to put two at.
for i in range(size-1):
if e > Arr[i] and e < Arr[i+1]:
tempIndex = i+1
#print... |
__all__ = ()
from re import compile as re_compile, escape as re_escape, I as re_ignore_case, U as re_unicode
from scarletio import LOOP_TIME, Task
from hata import KOKORO, DiscordException, ERROR_CODES, InviteTargetType, Embed, ICON_TYPE_NONE, elapsed_time, \
Permission, Emoji
from hata.ext.slash import abort
fro... |
from rest_framework import mixins, parsers, permissions, viewsets
from rest_framework.settings import api_settings
from ..models import Boxart, Brand, ModelKit, Scale
from .filters import BrandFilter, ModelKitFilter, ScaleFilter
from .serializers import (
BoxartSerializer,
BrandSerializer,
CreateModelKitSe... |
# Uses python3
import sys
if __name__ == "__main__":
input = sys.stdin.read()
a, b = map(int, input.split())
numerator = max(a, b)
denominator = min(a, b)
while not denominator == 0:
x = denominator
denominator = numerator % denominator
numerator = x
print((a*b) // nu... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 4 11:31:10 2018
@author: IkerVazquezlopez
"""
import sys
import pickle
import cv2
import gc
def obj_in_list(obj, loaded_list):
for e in loaded_list:
if obj.getID() == e[0]:
return True
return False
#%% MAIN METHOD
... |
from django.urls import path
from case_admin.views import common, case, comment, tag, user, question
app_name = "case_admin"
urlpatterns = [
path("users/", user.view_admin_user, name='users'),
path("users/review", user.view_admin_user_review, name='users_review'),
path("users/<int:user_id>", user.api_adm... |
import math
from Classifiers.custom_layers import FBetaLoss, HyperedgePoolingLayer
from Classifiers.base_model import BaseModel
import numpy as np
import torch
import torch.nn.functional as F
from tqdm import tqdm
# pylint: disable=no-member
class HGNNConvolution(torch.nn.Module):
"""Hypergraph convolution laye... |
""" ------------------------------- Check Permutation -------------------------------------
Given two strings, S and T, check if they are permutations of each other. Return true or false.
Permutation means - length of both the strings should same and should contain same set of characters.
Order of characters doesn't ... |
import re
import string
def translation(s):
k = re.search('(AUG([ACGU]{3,3})+?)(UGA|UAA|UAG)', s)
codons = re.findall(r'...', k.group(1))
protein = ''
genetic_code = {'UUU': 'F', 'UUC': 'F', 'UUA': 'L', 'UUG': 'L', 'CUU': 'L', 'CUC': 'L', 'CUA': 'L', 'CUG': 'L',
'AUU': 'I', 'A... |
import argparse
import pickle
import os
import sys
import random
random.seed(50)
src_dir = '/hpf/projects/brudno/marta/mimic_rs_collection/rs_sorted_alpha_cleaned/'
dest_dir = '/hpf/projects/brudno/marta/mimic_rs_collection/cuis_rs_20190315/'
def load_terms():
# src_file = '/hpf/projects/brudno/marta/mimic_rs_col... |
class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
print(self.restaurant_name.title() + " is a(n) " + self.cuisine_type + " restaurant.")
def open_restaurant(... |
# Assignment-3
'''
author : teja
date : 10/8/2018
module 11
'''
def is_valid_word(word_test, hand_word, word_list):
"""
Returns True if word is in the wordList and is entirely
composed of letters in the hand. Otherwise, returns False.
"""
count = 0
word_test = list(word_test)
for i_1 in wor... |
import pdb
import time
import pickle
import traceback
def get_num():
index = 0
with open('d:/bimbo/train.csv', 'r') as file:
line = file.readline()
while line:
index += 1
line = file.readline()
print index
def get_data():
with open('d:/bimbo/train.csv', 'r')... |
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot = True)
# one_hot means that from the 10 outputs only one will be selected at a time
n_nodes_hl1 = 500
n_nodes_hl2 = 500
n_nodes_hl3 = 500
n_classes = 10
batch_size = 100
x = tf.... |
"""Test the serialize function of Schema."""
import mock
import argo
@mock.patch.object(argo.Attr, 'serialize')
def test_schema_calls_attr(attr_serialize):
"""Test that schema serialize calls attr serialize with the correct value."""
class S(argo.Schema):
"""Test schema."""
key = argo.Attr... |
from pandas import read_csv
from pandas import DataFrame
import pandas as pd
import time
# fix random seed for reproducibility
#numpy.random.seed(7)
db_type = "lstm5"
update_type = 'a'
month = '09'
day = '01'
date = month+'-'+day
num_epochs=5000
batch=2
num_experiments = 1
error_scores = list()
announcement_times = ... |
"""empty message
Revision ID: d4bc619881c2
Revises: c9c770549430
Create Date: 2019-02-17 16:02:46.249427
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'd4bc619881c2'
down_revision = 'c9c770549430'
branch_labels = None
depends_on = None
def upgrade():
# ... |
import cv2
import os
from scipy import stats
from math import *
import numpy as np
import pandas as pd
def CannyThreshold(lowThreshold, ori_img, gray):
# 阈值自适应二值化
detected_edges = cv2.GaussianBlur(gray, (3, 3), 0)
detected_edges = cv2.Canny(detected_edges, lowThreshold, lowThreshold * ratio, apertureSize=... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from get_data import get_kalman_data_10, get_data_10
from wave_filter import wave_mix
from wave_detect import wave_double
from setting import get_thh
from wave_filter import after_kalman
from get_feature import fourier_transform
if __name__ == '__... |
import facebook
import os
import shutil
import requests
import simplejson
import yaml
from datetime import datetime
from dateutil import parser
from quik import FileLoader
import youtube_dl
import cgi
# This downloads all the content and build pages for all the posts.
# A second file called "indexer.py" will generat... |
import random
from os.path import exists
import numpy as np
import json
TRIES = 1000
CLUSTER_TRIES = 100
class World_generator():
def generate_world(self, args):
# prepare world parameters
path = args['path']['default'] if 'path' in args else '.\_data\generated_worlds'
if not 'name' in a... |
class Solution:
# O(n) time, O(n) space
def findErrorNums(self, nums: List[int]) -> List[int]:
s=set()
for num in nums:
if num not in s:
s.add(num)
else:
num1=num
for i in range(1,len(nums)+1):
if i in s:
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 17 16:12:10 2019
@author: Anthony
"""
# From the ashes of version 5 version 6 returns anew.
# I'm starting to make enough changes in the formatting that a new version number is in order
# Nothing fundamentally has changed, it's just significantly prettier
###... |
print("dasdasda")
zmienna = 1
print(zmienna)
zmienna2 = zmienna*0.5
print(zmienna2)
rzeczywista = float(35)
print(rzeczywista)
x=4.3
print(x)
print("%20f"%x)
print(x)
a,b =5,10
print(a)
print(b)
print(a+b)
napis = "To jest liczba parzysta"
if isinstance(a, int):
print( "%d %s" %(a, napis))
# else:
# print(a ... |
from keras.layers import Input, Dense
from keras.datasets import mnist
from keras.models import Model
import matplotlib.pyplot as plt
# Model configuration
img_width, img_height = 28, 28
initial_dimension = img_width * img_height
# Load MNIST dataset
(input_train, target_train), (input_test, target_test) = mn... |
# Copyright 2011 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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 ... |
import cloudconvert
api = cloudconvert.Api(
'NrtpV6kD5BdVxJ2R20eBqgCHK6heTjEMxtWSWENeZ9HdKUj5Ew3aCpodMCPPwLeH')
process = api.convert({
'inputformat': 'md',
'outputformat': 'rst',
'input': 'upload',
'file': open('./mytest.md', 'rb')
})
process.wait() # wait until conversion finished
p... |
from django.contrib import admin
from .models import *
from unittester.models import UnitTest
class ApplicationAdmin(admin.ModelAdmin):
list_display = ('order', 'name',)
class TestSectionAdmin(admin.ModelAdmin):
list_display = ('order', 'name', 'app')
list_filter = ('app',)
class UnitTestInline(admin... |
import unittest
from tax import calc_tax
class TestCalcTax(unittest.TestCase):
def test_calc_tax_with_ten_percent(self):
self.assertEqual(10, calc_tax(100, 0.1))
def test_calc_tax_with_fourteen_percent_with_almost_equal(self):
self.assertAlmostEqual(14, calc_tax(100, 0.14))
def test_cal... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.