text stringlengths 38 1.54M |
|---|
import KNN
import gzip
import pickle
import TestBase
def main():
#path = r'C:\Users\mdhal\Desktop\Fall 2018\Machine Learning\Project\Compressed\reviews_Musical_Instruments_5.json.gz'
path = r'C:\Users\mdhal\Desktop\Fall 2018\Machine Learning\Project\Compressed\reviews_Books_5.json.gz'
num_tests = 2000
... |
import random
from army_factory import ArmyFactory
from constants import STRATEGIES
class Battlefield:
def __init__(self, num_armies):
self._armies = []
for i in range(num_armies):
self._armies.append(ArmyFactory.create(random.choice(STRATEGIES)))
def start(self):
print("... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
''' Optimizer classes for parameters optimization.
'''
import numpy as np
from simpleflow.base import compute_gradients, DEFAULT_GRAPH
from functools import partial
class Optimizer(object):
"""
优化器
"""
def __init__(self):
self.output_value = None
... |
fname = input('Enter the file name: ')
try:
fhand = open(fname)
except:
print('File can not be opened:',fname)
quit()
count = 0
for line in fhand:
if line.startswith('s'):
count = count + 1
print('There were ',count, 'lines starts with s in',fname)
|
from __future__ import division
#/usr/bin/env python
# -*- coding: utf-8 -*-
#
# exclude duplicates in same line and sort to ensure one word is always before other
#
# look: https://stackoverflow.com/questions/21297740/how-to-find-set-of-most-frequently-occurring-word-pairs-in-a-file-using-python
#
# Copyright ... |
import csv
import matplotlib.pyplot as plt
import numpy as np
import time
import os
import sqlite3
import requests
class alvian:
#Buat Manggil semua aja .
def MataBatin(self):
self.nomor()
self.nama()
self.uang()
self.Matplotlib()
self.cobaWhile()
self.CobaTabel... |
from django.apps import AppConfig
class InformationSourcesConfig(AppConfig):
name = 'information_sources'
|
import gtk
from gobject import timeout_add, source_remove
class EscapeObject(object): pass
class FeedbackPopup(object):
def __init__(self):
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.set_property('allow-shrink', True)
self.window.props.skip_pager_hint = True
self.w... |
class ProcessControlBlock:
def __init__(self, pid, resources, status, ready_list, pcb_parent, priority):
self.pid = pid
self.resources = resources,
self.status = status
self.ready_list = ready_list
self.pcb_parent = pcb_parent
self.pcb_children = []
self.prior... |
# -*- coding: utf-8 -*-
"""
This module provides the miscellaneous utility functions required by kousen.gl.
"""
from OpenGL import GL
from OpenGL import GLU
from PySide import QtCore
from PySide import QtGui
class Scope(object):
"""
Scope provides a context manager base interface for various OpenGL operations.... |
import unittest, SpatialBasedQuadTree
from SpatialBasedQuadTree import SpatialQuadTree2D
from QuadTestItem import TestItem
from random import randint
runPerformanceTests = False
class Tester(unittest.TestCase):
def test_GetItemXY(self):
q = getBaseSpatialTree()
intendedX = 10
intendedY = ... |
"""Ebuild Tests."""
import copy
import logging
import os
import unittest
import unittest.mock
from typing import Any, Callable, Dict, Tuple
from etest.ebuild import Ebuild
from etest_test.fixtures_test import FIXTURES_DIRECTORY
from etest_test.fixtures_test.ebuilds_test import EBUILDS
logger = logging.getLogger(__nam... |
__author__ = 'alonabas'
from priority_dict import *
from RoutingTable import *
class RouterInterface:
def __init__(self, ip, mask, mac):
temp_ip = str(ip).split('.')
temp_mask = str(mask).split('.')
temp_network = [int(part1) & int(part2) for part1, part2 in zip(temp_ip, temp_mask)]
... |
# -*- coding: utf-8 -*-
import time
import random
from pathlib import Path
from datetime import datetime, timedelta
from airflow import DAG
from airflow.operators.python import PythonOperator
from airflow.utils.dates import days_ago
HOME = Path.home()
LOG_FILE = Path(HOME, "airflow", "sanhe-test-log.txt")
def step1... |
f = open("Arduino/script.py", "w")
print("James amazing compiler")
print("report any bugs plz")
print("Ver 1.1")
print("current support: Arduino ('pins') and LCD")
indent = 0
indentA = 0
i = 0
lcdneed = False
#pin.disable([rs, en, d4, d5, d6, d7])
array = ['from time import sleep\nfrom functions import *\nLED_BUILTIN ... |
from typing import Union
from goerr.colors import colors
class Msg:
"""
Class to handle the messages
"""
def fatal(self, i: Union[int, None] = None) -> str:
"""
Returns a fatal error message
"""
head = "[" + colors.red("\033[1mfatal error") + "]"
if i is not No... |
import numpy as np
from math import sqrt
from collections import Counter
from Utils.AccuracyFunction import accuracy_score
class KNNClassfier:
#初始化分类器
def __init__(self,k):
assert 1 <= k , "K must be >= 1!"
self.k = k
#私有成员变量加下划线
self._X_train = None
self._y_train = None... |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 7 01:43:15 2020
@author: Aalaap Nair & Shanmugha Balan
"""
import csv
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
import imageio as io
# Get the lines from the file to a processed list
def process_file(file_de... |
import pickle as pk
class Archiver:
def ZipData(self, data):
pass
def UnZipData(self, data):
pass
def Zip(self, data):
data = self.ZipData(data)
data = pk.dumps(data)
return data
def UnZip(self, data):
data = pk.loads(data)
data = self.UnZipData... |
#coding:utf-8
"""
@file: IEEE_download.py
@author: lyn
@contact: tonylu716@gmail.com
@python: 3.3
@editor: PyCharm
@create: 2016-08-31 14:43
@description:
专门为IEEE出版社的pdf下载模块
"""
import sys,os
up_level_N = 2
SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.ex... |
from pwn import *
from pprint import pprint
context.binary = "./main.elf"
context.bits = 64
context.arch = "amd64"
elf = ELF("./main.elf")
io = process("./main.elf")
print(io.recvline().decode("utf-8"))
payload = cyclic(345, n=8)
io.sendline(payload)
io.wait_for_close()
core = Core("./core")
fault_address = enhex... |
import numpy as np
def trapz(func,a,b,N):
func = lambda x: x**4 - 2*x + 1
h = (b-a)/N
k = np.arange(1,N)
It = h*(0.5*func(a) + 0.5*func(b) + func(a+k*h).sum())
return It
def simps(func,a,b,N):
func = lambda x: x**4 - 2*x + 1
h = (b-a)/N
k1 = np.arange(1,N/2+1)
k2 = np.arange(1,N/... |
import math
import numpy as np
import copy
import torch
LARGEPRIME = 2**61-1
cache = {}
#import line_profiler
#import atexit
#profile = line_profiler.LineProfiler()
#atexit.register(profile.print_stats)
class CSVec(object):
""" Count Sketch of a vector
Treating a vector as a stream of tokens with associate... |
students = ['Ivan', 'Masha', 'Sasha']
for student in students:
print('Hello,' + student + '!')
# Доступ происходит с помощью инднксов
students = ['Ivan', 'Masha', 'Sasha']
#Длина списка: len(students)
# Доступ к эл.списка осуществляется как и к строкам
#так же берем и отрицательные индексы
students[-1] 'Sas... |
from tests.UAT.page_models.book import Book
# The Cart constant page contains all the web locator for the cart page
# The ID for add to cart button
ADD_TO_CART_BUTTON_ID = "add-to-cart-button"
# The id for the cart icon picture located on the top of the page
CART_ICON_ID = "nav-cart"
# The dropdown ID for quantity ... |
# Generated by Django 3.1 on 2020-08-23 04:56
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Item',
fields=[
('id', models.AutoField(auto_... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
@Author : Ven
@Date : 2020/12/10
"""
INPUT = []
with open("2020-10.data") as f:
for i in f.read().split("\n"):
INPUT.append(int(i))
INPUT.append(0)
INPUT.append(max(INPUT) + 3)
INPUT.sort()
print(INPUT)
VAR_1 = ""
for i in range(0, len(INPUT) - 1):
VAR_1 ... |
import os
import errno
from torchvision.datasets.utils import download_url, extract_archive
class DataSetDownloader:
def __init__(self, root_dir, dataset_title, download=False):
"""
Parameters:
root_dir: root directory of data set
dataset_title: title of datase... |
import sys, os
from pyprojroot import here
root = here(project_files=[".here"])
sys.path.append(str(here()))
from typing import Dict, Optional, Union, Any
from collections import namedtuple
import pathlib
import argparse
import pandas as pd
from tqdm import tqdm
import numpy as np
import time
import joblib
import xar... |
"""
Documents Model Unittests
Copyright (c) 2018 Qualcomm Technologies, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the
limitations in the disclaimer below) provided that the following conditions are met:
* Redistributio... |
#!/usr/bin/env python3
import json
from statistics import stdev
from sys import argv
from datetime import datetime
from pymongo import MongoClient
def consume(source='apple--2018-09-03T13-11-54.json'):
# open connection
client = MongoClient('localhost', 27017)
db = client.hw2
# load + insert
with... |
from rank.util import purge
def main(_in, _out):
title = _in.read()
from rank.collect.movie import get_comments
for comment in get_comments(title.strip()):
_out.write("| {0}\n".format(purge(comment)))
if __name__ == "__main__":
import sys
main(sys.stdin, sys.stdout)
|
rom django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
def send_welcome_email(name, receiver):
pass |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayFundTransIcrowdTagModifyModel(object):
def __init__(self):
self._mobile = None
self._scene_code = None
self._tag_code = None
self._tag_value = None
s... |
import pandas as pd
import os
from sklearn.model_selection import train_test_split
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def train_val_split(trainx_path, trainy_path, trainpx_path,
trainpy_path,valx_path, valy_path):
trainx = pd.read_csv(trainx_path, e... |
#!/usr/bin/env python
import re
import sys
import array
import ROOT
ROOT.gROOT.SetBatch(True)
ROOT.PyConfig.IgnoreCommandLineOptions = True
colors = [
ROOT.kBlue,
ROOT.kRed+1,
ROOT.kBlack
]
def findBounds(x, ys, xmin=None, ymin=None, xmax=None, ymax=None):
if xmin is None:
xmin = min(x)
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 27 12:12:41 2019
@author: dori
"""
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import sys
sys.path.append('..')
from READ import slice_data
from READ import read_variables
from statistic import hist_and_plot
from air_prop... |
import os
import boto3
for i in ec2.instances.all():
if i.state['Name'] == 'stopped':
i.start()
print("Instance started: ", instance[0].id)
|
import unittest
def split_on_dash(string):
return string.split('-')
class TestSplitOnDash(unittest.TestCase):
def test(self):
self.assertEqual(split_on_dash('hi-hi'), ['hi', 'hi'])
if __name__ == '__main__':
unittest.main()
|
import random
anagramma = ('корова','правило','конфета',)
# случайным образом выбираем из последовательности одно слово
word = random.choice(anagramma)
correct = word
# создаем анаграмму выбранного слова, в которой буквы будут расставлены хаотично
mixed = ""
while word:
position = random.randrange(len(word))
m... |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 24 17:10:58 2020
@author: 59654
"""
import requests
import json
import pandas as pd
import re
from bs4 import BeautifulSoup
def geturl(month):
m = '%02d'%month
url = "http://tianqi.2345.com/t/wea_history/js/2020"+m+"/58457_2020"+m+".js"
retu... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the workbook function below.
def workbook(n, k, arr):
page_no = 1
count = 0
for i in arr:
com_pg = i//k
prob_last = i%k
idx = 1
for _ in range(com_pg):
if page_no in range(idx, id... |
import configparser
# CONFIG
config = configparser.ConfigParser()
config.read('dwh.cfg')
# DROP TABLES
staging_events_table_drop = "DROP TABLE IF EXISTS staging_events"
staging_songs_table_drop = "DROP TABLE IF EXISTS staging_songs"
songplay_table_drop = "DROP TABLE IF EXISTS songplays"
user_table_drop = "DROP TAB... |
"""Example of using hangups to receive chat messages.
Uses the high-level hangups API.
"""
import re
from datetime import datetime as dt
from datetime import timedelta as td
import volatile.memory as mem
import dynadb.db as db
def check_site_sensor(site_code):
""" Returns names of sensors (rain, tilt, soms, pi... |
from io import BytesIO
from urllib.parse import urlparse
import logging
import requests
from lxml import etree
from readability import Document
from kermes_infra.messages import AddArticleMessage, ArticleFetchCompleteMessage
from kermes_infra.models import Article, RelatedContent
from kermes_infra.queues import SQSPr... |
import math
import numpy as np
import cv2
import random
import colorsys
coco = ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
'elephant',... |
import mysql.connector
import tkinter as tk
from mysql.connector import Error
from tkinter import *
from _curses import COLOR_BLACK
class loginFrame(tk.Frame):
global connection
# global password
# frame.bg = COLOR_BLACK
def __init__(self, parent, controller):
tk.Frame.__init__(self, ... |
'''This file is a test file of a 3-body simulation. It takes input from a binary data file and plots the positions of two satellites around the Earth.
'''
import matplotlib.pyplot as plt
import numpy as np
import Simulation
#Load in the data file
Data = np.load("ThreeBodyTest.npy", allow_pickle=True)
earth_x = [item... |
import os
from flask import Flask
import blinker as _
from ddtrace import tracer
from ddtrace.contrib.flask import TraceMiddleware
import logging
import sys
# Have flask use stdout as the logger
main_logger = logging.getLogger()
main_logger.setLevel(logging.DEBUG)
c = logging.StreamHandler(sys.stdout)
formatter = l... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or d... |
# coding=utf-8
"""
pygame-menu
https://github.com/ppizarror/pygame-menu
SCROLLAREA
ScrollArea class to manage scrolling in menu.
License:
-------------------------------------------------------------------------------
The MIT License (MIT)
Copyright 2017-2020 Pablo Pizarro R. @ppizarror
Permission is hereby granted,... |
from flask_wtf import FlaskForm
from wtforms import SubmitField, RadioField, StringField, validators
class ShowRecords(FlaskForm):
record_list = RadioField("Список записів: ", coerce=int)
back = SubmitField('<- Назад')
delete = SubmitField('Видалити')
add = SubmitField('Додати')
update = Su... |
import os
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import sys
def density_plot(result_sizes):
# Density Plot with Rug Plot
sns.distplot(result_sizes, hist=True, kde=True, rug=True,
color='darkblue',
kde_kws={'linewidth': 2},... |
a=input().split(' ')
s=[]
w=[]
n=[]
e=[]
k=0
l=[]# To store the directions.
l1=[]# To strore the attacking strength.
for i in range(0,len(a)): # The loop is to extract the directions along with attacking strenth.
if a[1]=='1$':#Checks whether the input starts with day 1.
if a[i]=='W' or a[i]=='E' ... |
# !/usr/bin/env python
# coding=utf-8
# author: sunnywalden@gmail.com
import qiniu
import os
import requests
import sys
BASE_DIR = os.path.abspath(os.path.join(os.getcwd(), ".."))
sys.path.append(BASE_DIR)
from utils.get_logger import Log
from conf import config
from utils.fonts_scanner import get_fonts_from_local
... |
try:
from functools import wraps
except ImportError:
from django.utils.functional import wraps # Python 2.4 fallback.
from django.utils.decorators import available_attrs
from django.contrib import messages
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.decorators import login_requ... |
my_file = open('hairpin.fa', 'r')
lines = my_file.readlines()
y = ''
fileText = ""
text = []
for line in lines:
if line.rstrip("\r\n"):
if line.rstrip("\r\n").find(">") == 0:
if text:
fileText = fileText + ''.join(text)
fileText = fileText + "\n"
fileT... |
# Generated by Django 2.2.17 on 2021-03-10 19:38
from django.db import migrations, models
import django.db.models.deletion
def create_event_host_to_sponsor(apps, schema_editor):
"""Copy event.host to event.sponsor for existing events."""
Event = apps.get_model("workshops", "Event")
Event.objects.exclude(... |
import wave
import math
import struct
import subprocess
import thread
import sys
from Phonemes import Phonemes
from Syllables import Syllables
class SimpleSynthesizer(object):
SPACERS = {
" ": 0.2,
",": 0.4,
".": 0.6}
ACCENT_FACTOR = 2.0
PHONEMES_PATHS = ["synteza_mowy/p1/fonemy2016", "synteza_mowy/p1/fon... |
#! /usr/bin/env python2.7
T=int(raw_input())
NJ=raw_input().split()
N=int(NJ[0])
J=int(NJ[1])
DivMax=212 # the max div to check
PrimeList=range(2,DivMax)
# for optimization, we build a list of primes less then DivMax
for i in range(4,DivMax):
if i %2==0 :
PrimeList.pop(PrimeList.index(i))
continue
j=3
while j... |
import os
import os.path
import sys
from sys import platform
sys.path.append(os.path.join(os.getcwd(), "Measures"))
import numpy as np
import pandas as pd
from collections import defaultdict
from sklearn.utils import check_random_state
from sklearn.utils.validation import check_array
import timeit
import... |
import requests
import urllib.parse
from flask import redirect, render_template, request, session
from functools import wraps
def lookup(symbol):
# Contact API
try:
response = requests.get(f"https://api.iextrading.com/1.0/stock/{urllib.parse.quote_plus(symbol)}/quote")
response.raise_fo... |
import Hierarchical_clustering
import Second_Hierarchical_clustering
import Get_feature
for data_number in range(4,5):
for t1 in range(9,10):
t1=t1*0.5
Hierarchical_clustering.frist_Hierarchical(t1,data_number)
for t2 in range(6,7):
t2=t2*0.5
Second_Hierarchical_clu... |
import pickle
# Define some variables that will be put into pickle
Album = ( "Rammstain",
"Mutter",
1991,
( (1, "Mutter"),
(2, "Moskau"),
(3, "Herzlich")))
var_num = 14356
var_str = "Test string to pickle"
with open("vars.pickle", "wb") as vars_pickled:
pic... |
import scipy.optimize as op
f = lambda x: x**2 - 1e8* x + 1
x1 = op.fsolve(f, x0 = 0)
x2 = op.fsolve(f, x0 = 1e9) |
# FileName : pyTime_practice.py
# Author : Adil
# DateTime : 2018/7/27 16:17
# SoftWare : PyCharm
import time
# python中时间日期格式化符号:
# %y 两位数的年份表示(00-99)
# %Y 四位数的年份表示(000-9999)
# %m 月份(01-12)
# %d 月内中的一天(0-31)
# %H 24小时制小时数(0-23)
# %I 12小时制小时数(01-12)
# %M 分钟数(00=59)
# %S 秒(00-59)
#
# %a 本地简化星期名称
# %A 本地完整星期名称
# %b... |
# 将字符串str01,改为str02,变化的历程写在列表中,要求历程中的字符串必须出现在字典my_dict中
my_dict = {"hot": 1, "dot": 1, "dog": 1, "lot": 1, "log": 1, "cog": 1}
# def change_str(str01,str02):
|
from rest_framework.response import Response
from rest_framework import generics
from rest_framework import mixins
from blog.serializer import PostSerializer, CommentSerializer
from blog.models import Post, Comment
class GenericPostView(generics.GenericAPIView, mixins.ListModelMixin, mixins.CreateModelMixin,
... |
from PIL import Image
import numpy as np
from base_pic import BasePic
from base_file import BaseFile
class Stegan:
def __init__(self, pic, file):
self.pic = pic
self.file = file
self.pic_array = self.pic.bin_array
self.file_array = self.file.binary_array
self.pic_msb_array ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('profile_management', '0002_auto_20160122_0639'),
('resume_management', '0002_auto_20160122_0632'),
]
operations = [
... |
import urllib.request
import xmltodict, json
#import pygrib
import numpy as np
import pandas as pd
from datetime import datetime
import time
# Query to extract parameter forecasts for one particular place (point)
#
# http://data.fmi.fi/fmi-apikey/f96cb70b-64d1-4bbc-9044-283f62a8c734/wfs?
# request=getFeature&storedq... |
#Deletrear letra por letra el nombre de cada uno (Pedir ingresar el nombre)
nombre = ""
for x in nombre:
print(x) |
# -*- coding: utf-8 -*-
"""
REST API serving a simple Titanic survival predictor
"""
import pandas as pd
from flask import request
from flask_restful import Resource
from app import app, api
from model import PassengerSchema
from predictor import serialized_prediction
__author__ = "Felipe Aguirre Martinez"
__email... |
import io
from flask import Blueprint, jsonify
from flask import request
from common import util
from common.api import require_root
from common.api import require_user
from mediation import MediationConfig
from mediation import data_query
from mediation.data_receiver import DataInsertor
dataAPI = Blueprint('data_ap... |
from time import sleep
import requests
import pandas as pd
import matplotlib.pyplot as plt
from config import password
from date_handler import date_id_sequence, to_string
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, Float, func, create_engine, ForeignKey, tex... |
# 逻辑回归
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import precision_score, recall_score
# Read data from `.txt` file
def read_from_txt(filePath):
f = open(filePath)
line = f.readline()
data_list = []
while... |
"""
This file contains the implementation of the Typofinder class.
Use this class to find typos in a file based on a dictionary.
"""
import logging
from src.utils import get_words
logging.basicConfig(format='[%(asctime)s][%(levelname)8s][%(name)s]: %(message)s')
_root_log = logging.getLogger("typofinder")
_log = _ro... |
import re
import urllib.request
from pathlib import Path
from django.core.management import BaseCommand
from django.db.models.signals import post_save
from django.utils import timezone
from pybb.models import Post, Topic
from pybb.signals import post_saved
from notifications.models import create_pybb_post_notificati... |
from flask import Flask, render_template, url_for, request, redirect, session
import pymongo
from pymongo import MongoClient
from bson.objectid import ObjectId
from mongoengine import *
import requests
import re
client = MongoClient("mongodb+srv://teama7:ee461lteama7@mongodbcluster.bs58o.gcp.mongodb.net/BGDB?retryWrit... |
import re
from builtins import range
def camel_to_under(name):
"""
Converts camel-case string to lowercase string separated by underscores.
Written by epost (http://stackoverflow.com/questions/1175208).
:param name: String to be converted
:return: new String with camel-case converted to lowercas... |
# import necessary libraries
import json
from flask import (
Flask,
render_template,
jsonify,
request)
from flask_sqlalchemy import SQLAlchemy
#################################################
# Flask Setup
#################################################
app = Flask(__name__)
######################... |
import math
x = 1
x = 1.1
x = 1 + 2j # complex number
print(10 + 3)
print(10 - 3)
print(10 * 3)
print(10 / 3)
print(10 // 3)
print(10 % 3)
print(10 ** 3)
x = 10
x = x + 3
x += 3
print(x)
print(round(2.9))
print(abs(-2.4))
print(math.ceil(2.2))
x = int(input("x: "))
y = x + 1
print(y)
print(type(y))
# False value... |
from flask import Flask
from flask import request
app = Flask(__name__)
@app.route('/', methods=['GET','POST'])
def serve_part2():
# get request arguments
user_id = request.args.get('userid')
n = request.args.get('n')
# input validations
if user_id is None:
return "user id is invalid"
... |
"""
This module contains functions that validate neural networks for predicting device performance,
based on tabular data and m2py labels
"""
import os
import sys
import numpy as np
import torch
import torch.nn as nn
module_path = os.path.abspath(os.path.join('./'))
if module_path not in sys.path:
sys.path.appen... |
'''Write a python function find_smallest_number() which accepts a number n and returns the smallest number having n divisors.
Handle the possible errors in the code written inside the function.
Sample Input Expected Output
16 120
'''
def find_divisors(num):
divisors=[]
for i in range(1, num+1):
... |
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
os.environ["CUDA_VISIBLE_DEVICES"] = '0'
from library import *
def seed_all(seed=2020):
np.random.seed(seed)
tf.random.set_seed(seed)
seed_all()
#########################################################
#########################################################
... |
# Generated by Django 3.0.2 on 2020-03-19 19:47
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
... |
from jsonpickle import encode as json_encode
from requests import post as http_post, get as http_get
from Client.Logger import logger
class Shipper(object):
"""
Responsible for sending hardware_objects_lib.Computer objects
to the centralized server which handles these data.
"""
def __init__(self, host, port, ti... |
import os
import pytest
import sys
import ray
@pytest.mark.parametrize(
"call_ray_start_with_external_redis", [
"6379",
"6379,6380",
"6379,6380,6381",
],
indirect=True)
def test_using_hostnames(call_ray_start_with_external_redis):
ray.init(address="127.0.0.1:6379", _redis_pass... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
创建一个模块,包含一个阶乘函数f1(n)、一个列表删值函数f2(lst,x),一个等差数列求和函数f3(a,d,n)
'''
#阶乘 从1开始乘
def factorial(n):
result = 1
for x in range(1, n+1):
result *= x
print('%d的阶乘为:%d' %(n, result))
#列表删值函数 入参为:list,想删的值
def remove_lst(lst, x):
# for i in lst:
# ... |
'''
Created on Dec 21, 2012
@author: dough
'''
import unittest
from mock import MagicMock
from recording_schedule import *
from time import time
from source import Source
class TestRecordingSchedule(unittest.TestCase):
def setUp(self):
self._source = Source("dummy source")
self.rec_sch = Recordi... |
#
# Outputer utils
#
# Copyright (c) 2020, Arm Limited. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
import os
import builtins
import abc
import collections as co
import itertools as it
import string
import io
import re
from ..glue import Inherit
OUTPUTS = co.OrderedDict()
def output(cls):
asser... |
#-*- coding:utf-8 -*-
'''
Created on 2015年11月29日
@author: LeoBrilliant
'''
#-*- coding:utf-8 -*-
'''
Created on 2015年11月25日
@author: LeoBrilliant
#获取大盘指数历史行情
'''
import DBAccess.MySQLdb.MySQLAccess as msql
import tushare as ts
from datetime import datetime
#连接数据库,当前参数为地址、用户、密码(可控)、数据库
#db... |
import asyncio
from tornado import websocket
# define a coroutine
async def custom_coroutine():
print("opening a websocket to localhost:8000/test")
await asyncio.sleep(1)
ws= await websocket.websocket_connect("ws://localhost:8000/test")
print("trying to read an open websocket")
await asyncio.slee... |
import time
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def handle_ajax(request):
"""
接受ajax请求,并给以响应
:param request:
:return:
"""
time.sleep(10)
name = request.POST.get("name")
age = request.POST.get("age")
print(name,age)
... |
import unittest
from tests.test_python_generator.utils import PythonGeneratorUtils
class ListTestCase(PythonGeneratorUtils):
save_output_files: bool = False
def test_list(self):
import tests.test_python_generator.py.list as doc
jsg = 'l {e:@string*}'
test_cases = [
'{"e"... |
# -*- coding: utf-8 -*-
__author__ = 'oscar@outliers.es'
# Twitter lib used for user lookup + streaming: https://github.com/sixohsix/twitter [easy_install twitter]
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import pprint
import json
import traceback
import s... |
ages = [('Joe', 9), ('Samantha', 45), ('Methuselah', 969)]
# for (name, age) in ages:
# print('XXXX'.format(XXXX))
|
#!/usr/bin/python2.7
import RPi.GPIO as GPIO
import subprocess as SP
screenState = "/home/pi/pi-tablet_retropie/assets/currentDisplayMode"
GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
try:
GPIO.wait_for_edge(23, GPIO.FALLING)
stateFile = open(screenState, 'r')
state = stateFile... |
# pylint: disable=unused-wildcard-import
from utils import *
p1, p2 = inp_groups()
p1 = ints(p1[1:])
p2 = ints(p2[1:])
while p1 and p2:
c1, c2 = p1.pop(0), p2.pop(0)
if c1 > c2:
w = p1
else:
w = p2
w.append(max(c1, c2))
w.append(min(c1, c2))
print(w)
def score(w):
w = w[::-1... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.