text stringlengths 8 6.05M |
|---|
class Fly:
@staticmethod
def move(unit):
unit.position += 10
class Walk:
@staticmethod
def move(unit):
unit.position += 1
class Viking:
def __init__(self):
self.move_behavior = Walk()
self.position = 0
def move(self):
self.move_behavior.move(self)
|
import contextlib
import functools
import importlib
import inspect
import itertools
import os
import pathlib
import platform
import random
import shutil
import string
import struct
import tarfile
import unittest
import unittest.mock
import zipfile
from collections import defaultdict
from typing import Any, Callable, Di... |
# -*-coding:utf-8-*-
"""
归并排序算法
"""
import numpy as np
def create_array(a):
"""产生随机数组"""
return np.random.randint(0, 10, size=10)
"""方法1:对数组整体排序 """
def merge1(list1, list2):
ls = []
i = j = 0
while i < len(list1) and j < len(list2):
if list1[i] > list2[j]:
ls.append(list2... |
from django.urls import path
from .views import MyApiView, ReadUpdateView, ItemApiView, ReadUpdateItemView, ReadShopItemView
urlpatterns = [
path('', MyApiView.as_view(), name="myapiview"),
path('/<int:id>', ReadUpdateView.as_view(), name="readUpdate"),
path('/item', ItemApiView.as_view(), name="itemapivie... |
from django.contrib.auth.models import User
from rest_framework import generics
from rest_framework.views import APIView
from rest_framework.response import Response
from django.http import JsonResponse
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from garmin.serializers imp... |
"""268"""
import codecs
from sklearn import svm
from sklearn.externals import joblib
vectors = {}
with codecs.open('features', 'r', 'utf8') as reader:
for line in reader:
values = line.strip().split(' ')
word = values[0]
vector = map(float, values[1:])
vectors[word] = vector
topics... |
# -*- coding:utf8 -*-
import gspread
import httplib2
from .drive import get_file_list, get_credentials_from_file
from apiclient import discovery
from oauth2client.service_account import ServiceAccountCredentials
from . import healthservice_blueprint as healthservice
from sqlalchemy import create_engine, MetaData, Table... |
import requests
r = requests.get("https://stepic.org/media/attachments/course67/3.6.2/316.txt")
s = [i for i in r.text.splitlines()]
print(len(s)) |
from flask_wtf import FlaskForm
from ..models import User
from .. import db
from wtforms import StringField, DateField, SubmitField, TextAreaField, PasswordField,ValidationError, validators
from wtforms.validators import Required, Optional, Email, EqualTo
from wtforms import RadioField
class BlogForm(FlaskForm):
ti... |
try:
1 / 0
except Exception as E:
raise TypeError('Bad') from E # Explicitly chained exceptions
|
password="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
print("Goodbye, World!")
|
import json
from tqdm import tqdm
import pdb
from analysis.map_condition_phrases import read_embeddings
import numpy as np
import jsonlines
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import sent_tokenize
import os
import sys
import random
import re
import scipy.cluster.hierarchy as hcluster
from shutil... |
from ctypes import *
user32 = windll.LoadLibrary('user32.dll')
user32.LockWorkStation() |
#coding=utf-8
import os
from flask import Flask
import config
from flask_mongoengine import MongoEngine
from flask_bootstrap import Bootstrap
bootstrap = Bootstrap()
db = MongoEngine()
def create_app():
app = Flask(__name__)
app.config.from_object(config)
bootstrap.init_app(app)
db.init_app(app)
... |
#!/usr/bin/env python
REDIS_DB = 0
REDIS_PORT = 6379
REDIS_HOST = 'localhost'
SALT = 'retwitter'
r =None
|
# -*- coding: utf-8 -*-
#a=int(input())
#b=int(input())
#c=int(input())
#x1=0
#x2=0
#x1=(-1*b+(b**2-(4*a*c))**0.5)/2*a
#x1=(-1*b-(b**2-(4*a*c))**0.5)/2*a
#print(x1)
#print(x2)
def compute(a,b,c):
x1=0
x2=0
if((b**2-4*a*c)<0):
print("Your equation has no root.")
else:
x1=((-1)*b+(b**2... |
from tkinter import *
from tkinter import messagebox
root = Tk()
root.title("Tic-Tac-Toe")
w=17
h=4
global i
i=1
status = [-1,-2,-3,-4,-5,-6,-7,-8,-9]
def resetBoard():
global i
i=1
btn1 = Button(root, text="", width=w, height=h, command= lambda: clicked(1))
btn2 = Button(root, text="", width=w, height=h, comman... |
# Find the maximum total from top to bottom of the triangle below:
# Comments Section:
# - My first try was simply using a brute force algorithm but since there was said that existed
# a better algorithm I took some time to think about it. From the forum I found that this was exactly
# what we should aim to. It consis... |
from __future__ import absolute_import, unicode_literals
import logging
import requests
from requests import Response, RequestException
from django.conf import settings
from common_services.errors import *
try:
# Load Python3 urljoin
from urllib.parse import urljoin
except:
# If failed, load Python2.7 u... |
import json
import math
import requests
from recipes.models import Good, Pharmacy, Medicine
from recipes.serializers import PharmacySerializer, MedicineSerializer
def get_coordinates(address: str):
response = requests.get('https://geocode-maps.yandex.ru/1.x/?format=json&geocode={}'.format(address))
data = j... |
# Python script to create the index containing frame-number and timestamp
import os
import sys
import argparse
# PyAV - wrapper for FFMPEG
import av
# Local imports
def process(video_fname, imdb_key):
"""Generate the matidx file.
"""
if imdb_key is None:
movie_name = '.'.join(video_fname.split('/'... |
import os
import sys
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
path = '/backend'
if path not in sys.path:
sys.path.append(path)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
application = Cling(get_wsgi_application())
|
# IMPORTANT
#run in StanfordCoreNLP folder:
# java -mx4g -cp "*" edu.stanford.nlp.pipeline.StanfordCoreNLPServer
import os
import re
import logging as lo
from pycorenlp import StanfordCoreNLP
from gensim.models import word2vec
import sys
import pickle
import pandas as pd
import numpy as np
#Class that parses input sen... |
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import re
from typing import Callable
def assert_equal_with_printing(
expected, actual, uniform_formatter: Callable[[str], str] | None = None
):
... |
from flask import Flask, Response
from flask_accept import accept_fallback
from flask_restplus import Resource, Api
from flask_weasyprint import render_pdf, HTML
from config import Config
from formatter.report_formatter import ReportFormatter
from model.report import Report
from model.report import db
app = Flask(__n... |
class MyClass:
def __init__(self, firstname = "Vivek", lastname = "Khimani"):
self.name1 = firstname
self.name2 = lastname
def getName (self,age):
self.name2 = age
return self.name1
myObject = MyClass("Bhargav","Khimani")
print(myObject.name1)
print(myObject.n... |
import ROOT
ROOT.gROOT.SetBatch(True)
import json
from array import array
# choose which year's eta-phi ROOT files to make!
year2017 = False
year2018 = False
year2016 = True
# "Average" : 0.5485,
# "NonPixelProblemBarrel" : 0.5570,
# "EndCap" : 0.5205,
# "PixelProblemBarrel" : 0.3589
def fillH2( trigger, wp, dm, ... |
# Copyright (C) 2014 Yellow Feather Ltd
#
# The following terms apply to all files associated
# with the software unless explicitly disclaimed in individual files.
#
# The authors hereby grant permission to use, copy, modify, distribute,
# and license this software and its documentation for any purpose, provided
# that... |
import board
import neopixel
import time
pixels = neopixel.NeoPixel(board.D18, 20)
For i in range (14):
pixels[i] = (10,0,0)
|
import pytest
@pytest.mark.asyncio
async def test_exists(redis):
redis._redis.set('foo', 'bar')
redis._redis.set('baz', 'blub')
val = await redis.exists('blargh')
assert 0 == val
val = await redis.exists('foo')
assert 1 == val
val = await redis.exists('foo', 'baz')
assert 2 == val
... |
#14. Write a Python program that accepts a string and calculate the number of digits and letters. Go to the editor
#Sample Data : Python 3.2
#Expected Output :
#Letters 6
#Digits 2
s = input("Input a string: ")
d = 0
l = 0
limit = 0
while len(s) > limit:
if s[limit].isdigit():
d = d + 1
elif s[limit].isalpha... |
from __future__ import print_function
import sys
import os
import requests
import logging
import json
from os.path import dirname
from jsonschema import validate
import importlib
import pkgutil
from halocli.util import Util
logger = logging.getLogger(__name__)
logging.root.setLevel(logging.INFO)
class PluginError(E... |
# -*- coding=utf-8 -*-
from __future__ import unicode_literals
"""
Excel Reader
~~~~~~~~~~~~~
"""
import xlrd
from .base import cached_property, _missing
__all__ = ['ExcelReader']
class ExcelReader(object):
def __init__(self, filename=None, file_contents=None, file_point=None):
self.filename =... |
#!/usr/bin/env python
import rospy
from std_msgs.msg import Float64
import math
def main():
radius_pub = rospy.Publisher('radius', Float64, queue_size=10)
rospy.init_node('radius_pub_node', anonymous=True)
loop_rate = rospy.Rate(5)
radius = 1.0
PI = math.pi
angular_speed = 1.0
distance = ... |
for row in range(1,6):
for col in range(1,6):
if (col==1 and row!=1) or (col==5 and row!=1) or(( row==1 or row==3)and(col!=1)) and (col>1 and col<5):
print("0",end=" ")
else:
print(" ",end="")
print()
for row_b in range(1,6):
for col_b in range(1,6):
if col... |
# coding:utf-8
from __future__ import absolute_import, unicode_literals
__author__ = "golden"
__date__ = '2018/6/21'
from cleo import Command
class GreetCommand(Command):
"""
Greets someone
greet
{name? : Who do you want to greet?}
{--y|yell : If set, the task will yell in uppercase let... |
import unittest
from katas.beta.who_took_the_car_key import who_took_the_car_key
class WhoTookTheCarKeyTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(who_took_the_car_key(
['01000001', '01101100', '01100101', '01111000', '01100001',
'01101110', '01100100', ... |
#!/usr/bin/env python3
import pickle
with open('temp.txt', 'w') as ff:
ff.write('this is test file')
with open('temp.txt', 'r') as fr:
print(fr.read())
data1 = {'a': [1, 2.0, 3, 4+6j],
'b': ('string', u'Unicode string'),
'c': None}
selfref_list = [1, 2, 3]
selfref_list.append(selfref_list)
pr... |
import unittest
from src.card import Card
from src.card_game import CardGame
class TestCardGame(unittest.TestCase):
def setUp(self):
# Cards
self.card1 = Card("Hearts", 7)
self.card2 = Card("Spades", 2)
self.card3 = Card("Diamons", 1)
self.cards = [self.card1,... |
#Christopher Hansen
#Programming for Data Science with Python - Udacity
import time
import pandas as pd
import numpy as np
import datetime
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
months = ('january', 'february', 'march... |
from .disability import DisabilityObserver
from .mortality import MortalityObserver
from .risk import CategoricalRiskObserver
from .disease import DiseaseObserver
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 21 07:45:14 2018
@author: jeremy.meyer
"""
import pandas as pd
#Series. s.index are row names. Can mix variabule types
s = pd.Series([1,2,3,4,5,6])
s.index = ['label1', 'l2', 'l3', 'l4', 'l5', 'l6']
print(s)
#Subsetting
s[1]
s[:2] #First 2 elemen... |
data = ""
with open("1day5data.txt") as f:
data = f.read()
data = data.split("\n")
for i in range(0, len(data)):
data[i] = int(data[i])
def cycle(data):
i = 0
previ = 0
stillInLoop = True
steps = 0
while stillInLoop:
if i > (len(data) - 1):
break
previ = i
... |
"""
Various utils to retreive from database and export to file
"""
import config
from lib.Database import Database
import os
import shutil
from uuid import UUID
from dateutil.parser import parse as dateparse
import logging
import config
from lib.pymot.pymot import MOTEvaluation
from mpyx.F import EZ, As, By, F
fro... |
from django.db import models
# Create your models here.
class class10(models.Model):
name = models.CharField(max_length=30, blank=True)
class Meta:
db_table = '_App1_class10'
class class2(models.Model):
name = models.CharField(max_length=30, blank=True)
class Meta:
db_table = '_A... |
"""
剑指 Offer 39. 数组中出现次数超过一半的数字
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
"""
"""
一言不合暴力破解,走一遍就行了,记住用hash表来记住这个值。
"""
def majorityElement( nums: list) -> int:
hash = {}
for i in nums:
if i not in hash:
hash[i] = 1
else:
hash[i]+=1
for i in hash:
if hash[i] > len(nums)... |
#! /usr/bin/python
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
plt.rc('axes', titlesize=16) # fontsize of the axes title
plt.rc('axes', labelsize=16) # fontsize of the x and y labels
plt.rc('xtick', labelsize=12) # fontsize of the tick labels
plt.rc('ytick', labelsize=12) # fon... |
"""Generic operation class. """
class Operation(object):
languages = None
tasks = None
seed = 0
heavy = False
def __init__(self, seed=0, verbose=False):
self.seed = seed
self.verbose = verbose
if self.verbose:
print(f"Loading Operation {self.name()}")
@cla... |
#从摄像头中找到人脸,参考facerec_from_webcam_faster.py
#实时播放出来,打水印并把截图保存下来
import face_recognition
import cv2
video_capture = cv2.VideoCapture(0)
#找这些人脸
obama_image = face_recognition.load_image_file("obama.jpg")
obama_face_encoding = face_recognition.face_encodings(obama_image)[0]
lijiawei_image = face_recognition.load_image_fi... |
# テンプレートマッチング(NCC)のプログラム
# 参照URL = https://algorithm.joho.info/programming/python/opencv-template-matching-ncc-py/
# 域値を設定することで、その域値以上の検出結果を描画するプログラム
# ver1に追記する
# 回転処理を加えたプログラムを記述する(達成)
# このプログラムは、回転しても全体がきちんと映るように調整されています。
# ver2に追記
# 回転画像の黒以外の部分をテンプレートマッチングにかける(未達成)
# Q. 入力画像を回転させ、それに対してテンプレートマッチングを試すことで解決することはできな... |
from __future__ import print_function, absolute_import
import logging
import re
import json
import requests
import uuid
import time
import os
import argparse
import uuid
import datetime
import socket
import apache_beam as beam
from apache_beam.io import ReadFromText
from apache_beam.io import WriteToText
from apache_... |
from qcodes.instrument.visa import VisaInstrument
from qcodes.utils import validators as vals
import numpy as np
class Weinschel_8320(VisaInstrument):
'''
QCodes driver for the stepped attenuator
Weinschel is formerly known as Aeroflex/Weinschel
'''
def __init__(self, name, address, **kwargs):
... |
from channels.routing import route
from . import consumers
routes = [
route('websocket.connect', consumers.data_entry_connect, path='^(?P<game_id>\d+)/score/$'),
route('websocket.receive', consumers.data_entry_receive, path='^(?P<game_id>\d+)/score/$'),
route('websocket.disconnect', consumers.data_entry_... |
#!/usr/bin/python3
# pip3 install matplotlib
from matplotlib import pyplot as plt
import numpy as np
x,y=np.loadtxt('exm2.csv',unpack=True,delimiter=',')
plt.scatter(x,y,color='r',linewidth=10,label='today')
#add labels
plt.grid(True,color='k')
plt.title("My Chart")
plt.ylabel("y label")
plt.xlabel("x label")
pl... |
'''
Created on Feb 2, 2016
@author: henry
'''
# A program to print a multiplication
num = int (input("Display multiplication table of?" ))
# Loop to iterate 15 times
for i in range(1,16):
print(num, 'x',i,'=',num*i)
|
from model.models import GRUMultiTask
import os
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import TensorDataset, DataLoader
import defines as df
from time import gmtime, strftime
from datetime import datetime
from sklearn.metrics import f1_score
try:
import cPickle as pickle
except... |
from flask import jsonify, request, current_app, url_for
from . import api
from ..model import kPost, User, Permission
from .decorators import permission_required
from .errors import forbidden
@api.route('/post/<int:userId>', methods=['GET' ,'POST'])
def get_userPost(userId):
kPost_ = kPost()
userPost = kPos... |
l=[]
while (1):
print(" press 1 for add a person in a list\n press 2 for go in the room\n press 3 to exit ")
n=int(input(""))
if n==1:
name=input("")
l.append(name)
elif n==2:
if len(l)>0:
print(l.pop(0),", now its your turn ")
else:
print("Ther is no person in the list for interview")
elif n==3:
... |
import os
import funcy
import requests
from mixpanel import Mixpanel
from bs4 import BeautifulSoup
from telegraph import Telegraph
mp = Mixpanel(os.environ.get('mix_token'))
telegraph = Telegraph()
telegraph.create_account(short_name='1337')
accents = {
'uk': {'class': 'sound audio_play_button pron-uk i... |
from lib.list import List
def check_node_and_size(head, k):
if head == None:
return (None, 1)
(node, size) = check_node_and_size(head.next, k)
returned_node = head if (size == k) else node
return (returned_node, size + 1)
def find_kth_to_last_elem(items, k):
node = check_node_and_size(items.head, k)[... |
from rest_framework import serializers
from main_app.models import Movie, Profile
from django.contrib.auth.models import User
from rest_framework_simplejwt.tokens import RefreshToken
class MovieSerializer(serializers.ModelSerializer):
class Meta:
model = Movie
fields = [
'id',
... |
# KVM-based Discoverable Cloudlet (KD-Cloudlet)
# Copyright (c) 2015 Carnegie Mellon University.
# All Rights Reserved.
#
# THIS SOFTWARE IS PROVIDED "AS IS," WITH NO WARRANTIES WHATSOEVER. CARNEGIE MELLON UNIVERSITY EXPRESSLY DISCLAIMS TO THE FULLEST EXTENT PERMITTEDBY LAW ALL EXPRESS, IMPLIED, AND STATUTORY WARRANT... |
import random
from past.builtins import range
import numpy as np
class Candidate(object):
""" A candidate solutions to the Sudoku puzzle. """
def __init__(self, Nd, sqrtVal):
self.Nd = Nd
self.sqrtVal = sqrtVal
self.values = np.zeros((self.Nd, self.Nd))
self.fitness = None
... |
from django.conf.urls import url
from . import views
# URLs barril | lote | movimientos
urlpatterns = [
# Create object URLs
url(r'^lote/create/$', views.LoteCreate.as_view(), name='lote_create'),
url(r'^barril/create/$', views.BarrilCreate.as_view(),
name='barril_create'),
url(r'^movimiento/c... |
import sys
import csv
import tweepy
import matplotlib.pyplot as plt
import os
import json
from collections import Counter
from aylienapiclient import textapi
def getSentiment(subject):
filepath = os.path.dirname(os.path.realpath(__file__))
# print filepath
oldFilename = "eventdata_"+subject+'.jso... |
"""
Given an array of integers nums sorted in ascending order,
find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
"""
... |
import numpy as np
import open3d as o3d
from PyNomaly import loop
import time
# from numba import jit
class PointSet:
ply_=[]
len_=[]
tree_=[]
def __init__( self, path):
self.ply_ = o3d.io.read_point_cloud(path)
self.len_=len(self.ply_.points)
self.tree_=o3d.geometry.KDTreeFlann(self.... |
import torch
import time
import torch.nn as nn
from IPython import embed
from . import losses as losses_lib
class PrimedBackpropper(object):
def __init__(self, initial, final, initial_num_images):
self.initial = initial
self.final = final
self.initial_num_images = initial_num_images
... |
import unittest
import numpy.testing as testing
import numpy as np
import hpgeom as hpg
from numpy import random
import healsparse
class BuildMapsTestCase(unittest.TestCase):
def test_build_maps_single(self):
"""
Test building a map for a single-value field
"""
random.seed(seed=12... |
# -*- coding: utf-8 -*-
from insertion_sort.insertion_sort import InsertionSort
from selection_sort.selection_sort import SelectionSort
import time
import copy
import random
sizes = [
1000,
10000,
50000
]
for size in sizes:
# random generation of items to be sorted
items = ran... |
# coding: utf-8
import os
import requests
import json
from PIL import Image
from pymongo import MongoClient
from StringIO import StringIO
FLASK_BIND_PORT = int(os.environ.get('FLASK_BIND_PORT', '5000'))
mongodb_host = os.environ.get('MONGODB_HOST', 'localhost')
mongodb_port = int(os.environ.get('MONGODB_PORT', '2701... |
a = 1
b = 1
for i in range(100000000):
#print(b)
c = a
a = b + a
b = c
print(a) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 11 10:44:49 2018
This is Will's PSF notebook put into code so that I can understand what it does
@author: ppxee
"""
from __future__ import print_function, division
from astropy.io import fits
import numpy as np
import matplotlib.pyplot as plt
plt.... |
# heapq 이용해서 풀기 (최대 최소값 문제)
# 배운 부분: 따로 heap 설정한 리스트에 접근하여 값을 빼는 것이 아닌 값을 빼서 계산하고 다시 넣는 과정으로 진행
from heapq import *
def solution(n, works):
if sum(works) <= n:
return 0
answer = 0
works = [-i for i in works]
heapify(works)
for _ in range(n):
A = heappop(works)
A += 1
... |
from django.shortcuts import render, redirect, HttpResponse
from bbs.models import Comments, CommentsReply, UserInfo, User, Article, FriendShip
from notifications.models import Notification, NotificationQuerySet
from django.contrib.auth.views import login_required
from django.db import transaction
import json
@login_... |
import claripy
import hashlib
def findAns(ind):
possible = s.eval(x[ind], 17, extra_constraints=ext)
if ind > 15:
ruleAry.append(ext[:])
print 'add new ext'
return
for i in possible:
ext.append(x[ind] == i)
findAns(ind + 1)
ext.pop()
ruleAry = []
s = clari... |
# Copyright (c) 2015 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'make_global_settings': [
['LINK_wrapper', './check-ldflags.py'],
],
'targets': [
{
'target_name': 'test',
'type': 'executable',
... |
# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import logging
from typing import cast
from pants.base.specs import AddressLiteralSpec, FileLiteralSpec, RawSpecs, Specs
from pants.base.specs_parser import SpecsParser
from pants.core.ut... |
p1_total += 5 * (p1_table.count('Tempura') / 2)
p1_total += 10 * (p1_table.count('Sashimi') / 3)
p1_total += (p1_table.count('Dumpling') * (p1_table.count('Dumpling') + 1)) / 2
maki += p1_table.count('SingleMaki') + 2 * p1_table.count('DoubleMaki') + 3 * p1_table.count('TripleMaki')
p1_total += p1_table... |
from dotenv import load_dotenv
def load():
envFilePath = '/root/.env'
load_dotenv(envFilePath) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__version__ = '1.0.1'
import ujson
import time
from sanic.log import logger
# from decimal import Decimal
from sanic.request import Request
# from shapely.geometry import Point, LineString, Polygon
# NVL POINT IMPORTS
from .specification.get_nvl_position_specification i... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 14 21:41:41 2018
@author: bolof
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
dataset = pd.read_csv('Position_Salaries.csv')
# create your independent and dependent variables of X and y
X = dataset.iloc[:,1:2].values
... |
import logging
import Currency
from telegram.ext import *
from DBMS import *
from sms import SMS
import unidecode
from bot_info import *
# Enable logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)
logger = logging.getLogger(__name__)
# DBMS
database =... |
from si7021 import getTempC, getHumidity
print("***Test SI7021 Sensor***")
print ("Temperature in Celsius is : %.2f C" %getTempC())
print ("Relative Humidity is : %.2f %%" %getHumidity())
|
import tkinter
import tkinter as tk
from tkinter import *
from tkinter import messagebox
#Properties for the window/canvas
window = Tk()
window.title("Login Screen")
window.geometry("200x200")
#Creating the login screen
lbl = Label(window, text="Please Login to Continue", font=("Arial Bold", 10))
lbl.grid(c... |
# 一. 类型和运算
# 1 --简单的列出对象obj所包含的方法和名称, 返回一个字符串列表
# print(dir(obj))
# 查询obj.func的具体介绍和方法
# help(obj.func)
# 2--测试类型的三种方法
# L = list()
# if type(L) == type([]):
# print("L is list")
#
# if type(L) == list:
# print("L is list")
#
# if isinstance(L, list):
# print("L is list")
# 3--python数据类型: 哈希类型, 不哈希类型
... |
#!/usr/bin/env python
# coding: utf-8
# In[2]:
fruits = ['mango', 'kiwi', 'strawberry', 'guava', 'pineapple', 'mandarin orange']
numbers = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 17, 19, 23, 256, -8, -4, -2, 5, -9]
# Example for loop solution to add 1 to each number in the list
numbers_plus_one = []
for number in num... |
import imp
import json
import logging
import time
from slackclient import SlackClient
from .brain import Brain
from .listener import Listener
from .listener import ListenerType
from .message import Message
from .repl import EspressoConsole
from .user import User
from .plugin_api import PluginAPI
class Espresso(Plug... |
import asyncio
import time
from aiokafka import AIOKafkaConsumer, AIOKafkaClient
from aiokafka.conn import AIOKafkaConnection
from aiokafka.cluster import ClusterMetadata
from aiokafka.errors import ConnectionError
from kafka.errors import KafkaError
from typing import Dict
def is_connected(conns: Dict[str, AIOKafk... |
from django.urls import include, re_path
from rest_framework import routers
from .views import (
ElectionSubTypeViewSet,
ElectionTypeViewSet,
ElectionViewSet,
OrganisationViewSet,
)
class EERouter(routers.DefaultRouter):
def get_lookup_regex(self, viewset, lookup_prefix=""):
# we identify... |
import pandas as pd
import math
def selectData(df, newData):
for i, rowAux in newData.iterrows():
#Initialize counts for each column in each Category
countRating=0
countSize=0
countInstalls=0
for j, row in df.iterrows():
if rowAux['Category'] == row['Category']:
if math.isnan(row['Rating'])==False: ... |
"""
練習問題1
print(sum([1,2,3])/len([1,2,3]))
"""
"""
練習問題2
i = input()
score = int(i)
if score < 0:
print(0)
else:
print(score)
"""
"""
i = input()
score = int(i)
print(max(0,score))
print(min(100,score))
"""
"""
i = input()
score = int(i)
#print(max(0,score))
print(min(100,max(0,score)))
"""
"""
def plus1(a):
... |
#!/usr/bin/env python3
#
# This example shows how to set up a self-consistent fluid DREAM run,
# where no kinetic equations are solved, but the electric field and
# temperature are evolved self-consistently.
#
# Run as
#
# $ ./basic.py
#
# ###################################################################
import nu... |
def add(*args):
return round(sum(x/(c+1) for c,x in enumerate(args)))
'''
This kata is all about adding numbers.
You will create a function named add. It will return the sum of all the arguments.
Sounds easy, doesn't it?
Well Here's the Twist. The inputs will gradually decrease with their index as
parameter to... |
n = int(input())
scores = [int(x) for x in input().split()]
M = max(scores)
sum_new_scores = 0
for s in scores:
sum_new_scores += s / M * 100
print(sum_new_scores / n)
|
import torch
import torch.nn as nn
import torch.nn.functional as F
from model.classifier import GNNClassifier
class GAT(GNNClassifier):
def __init__(self, input_dim, hidden_dim, num_labels, num_layers, num_heads=2, merge='mean', dropout=0.6):
super().__init__(input_dim, hidden_dim, num_labels, num_layers)... |
# -*- coding: utf-8 -*-
"""
ytelapi
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
import jsonpickle
import dateutil.parser
from .controller_test_base import ControllerTestBase
from ..test_helper import TestHelper
from ytelapi.api_helper import APIHelper
... |
# cmds = {
# 'query_comm_temp_unit':':UNIT:TEMPERATURE?',
# 'set_comm_unit_f':':UNIT:TEMPERATURE F',
# 'set_comm_unit_c':':UNIT:TEMPERATURE C',
# 'query_temp_disp':':UNIT:TEMPERATURE:DISPLAY?',
# 'set_disp_unit_f':':UNIT:TEMPERATURE:DISPLAY F',
# 'set_disp_unit_c':':UNIT:TEMPERATURE:DISPLAY C',
... |
from django.views.generic import TemplateView
from generic.mixins import CategoryListMixin
class ContactsView(TemplateView, CategoryListMixin):
template_name = "contacts.html"
|
# TODO: Still need to write the parser
import macropy.activate
from language import *
from gen import *
from sympy import *
import shac
# This the the single dimension in "x" example artificially paced cell
# without any value for f(lambda).
ode1 = Ode(S("diff(x(t))+0.1*x(t)"), S("x(t)"), 0.0001, {})
ode2 = Ode(S... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.