text stringlengths 38 1.54M |
|---|
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import pdb
evolutions = np.load('soft_evolution.npy')
font = {'family' : 'normal',
'size' : 30}
matplotlib.rc('font', **font)
for ev in evolutions:
plt.plot(ev[:, 0], ev[:, 1], color='orange', alpha=0.5, linewidth=4)
plt.xlim([0,100... |
import sys
import time
import IceRayCpp
import engine
import image
import room
import surface
import light
import rendering
def light_make( P_light ):
blocked = IceRayCpp.LightObstruct()
blocked.light( P_light['this'] )
return { 'this': blocked, '0': P_light }
import geometry
f... |
# -*- coding: utf-8 -*-
import os
import pathlib
from .Decorators import Decorators
from ...Exceptions import StoryscriptError
def safe_path(story, path):
"""
safe_path resolves a path completely (../../a/../b) completely
and returns an absolute path which can be used safely by prepending
the story's... |
# -*- coding: utf-8 -*-
from tccli.services.chdfs.chdfs_client import register_arg
from tccli.services.chdfs.chdfs_client import get_actions_info
from tccli.services.chdfs.chdfs_client import AVAILABLE_VERSION_LIST
|
import os
import yaml
import logging
from lxml import html
from tempfile import mkstemp
from krauler import Krauler
from aleph.crawlers.crawler import Crawler
log = logging.getLogger(__name__)
class AlephKrauler(Krauler):
USER_AGENT = 'aleph/web'
def __init__(self, crawler, source, config):
self.c... |
# coding: utf-8
"""
GNBR Knowledge Beacon API
This is the GNBR Knowledge Beacon web service application programming interface (API). # noqa: E501
OpenAPI spec version: 1.2.0
Contact: srensi@stanford.edu
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
Bugscan = 'https://www.bugscan.net/'
import six
if six.PY3:
import imp
import os
DIR, _ = os.path.split(__file__)
common = imp.load_compiled("common", os.path.join(DIR, "common3.pyc"))
from common import *
else:
from common2 import *
import comm... |
from PyQt5 import QtWidgets
class Options(QtWidgets.QTabWidget):
def __init__(self, parent=None):
super(QtWidgets.QTabWidget, self).__init__(parent)
self.parent = parent
self.resize(850, 250)
self.move(50, 375)
calibration_options = QtWidgets.QWidget()
matching_opt... |
# -*- coding: utf-8 -*-
from django.contrib import messages
from django.http import JsonResponse
def error_handler(request, message, redirect):
print(message)
messages.error(request, message)
return redirect
def json_error_handler(reason):
return JsonResponse({"success": False, "reason": reason})
|
# Given an array, A, of N integers, print A's elements in reverse order as a single line of space-separated numbers.
N = int(input())
#arr = input().split()
arr = list(map(int, input().rstrip().split()))
# Print the array in reverse using one of the following methods:
# 1. Using 'Array reversal with [::-1]
print(' '... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
# -*- encoding:utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.core.management.base import BaseCommand
from djrill.exceptions import MandrillAPIError
from idlecars import email
from owner_crm.tests.sample_merge_vars import merge_vars
class Command(BaseCommand):
help... |
__author__ = 'Patricio Cerda, Joaquin Moreno y Pedro Zepeda'
import os
import copy
import random
from time import time
# Correcciones finales mediante testeo intensivo.
### DPLL BASICO ###
def DPLL(alpha, recorrido):
global eleccion, show
if alpha == '':
recorrido.sort()
if show: print('La... |
#!/usr/bin/env python
# 到环境变量中查找python
# 文件要想运行,需要指定解释器
# 设置settings.py为环境变量
import sys
sys.path.insert(0, '../')
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "meiduo_mall.settings")
import django
django.setup()
# 编写代码:查询所有的商品,生成静态页面
from goods.models import SKU
from celery_tasks.html.tasks import g... |
import os
import dffml
import github
@dffml.op(
inputs={
"url": dffml.Definition(name="github.repo.url", primitive="string"),
},
outputs={
"owner": dffml.Definition(
name="github.org.owner_name", primitive="string"
),
"project": dffml.Definition(
na... |
__author__ = 'Brad'
from HttpServer.httpServer import httpServer
from DatabaseManagementCode.dataFileUploaderClass import DataFileUploader
from DatabaseManagementCode.configFileUploaderClass import ConfigFileUploader
from DatabaseManagementCode.eventFileUploaderClass import EventFileUpl... |
import dosyalama1 as dos
dos.alanlar = ["Uzunluk","Cins","Sayı"]
dos.adres = "olcum.csv"
import random as rnd
liste = []
for i in range(10000):
line = f"{rnd.randrange(0,1000,10)};{rnd.randrange(0,5)};{rnd.randrange(0,100,5)}\n"
liste = dos.OtomatikYeniKayit(liste,line)
dos.dosyaKayit(liste)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 7 17:10:28 2020
@author: alex
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import os
import numpy as np
import math
from sklearn import linear_model, datasets
from sklearn.metrics import mean_squared_error, r2_score
impor... |
import Problem
from Maze import Maze
from Operator import Operator
from Tree import Tree
import OperatorType
class GottaCatchEmAll:
def __init__(self, initial_state, maze, operators):
self.initial_state = initial_state
self.maze = maze
self.operators = operators
def goal_test(self, n... |
# coding: utf-8
# file name: multi_thread.py
# python version: 2.7
# author: wu ming ming
# description: study of multi thread
import threading
from multiprocessing import Process, Queue
import time
import os
# """
# When you use python manage.py runserver Django start two processes, one for the actual development se... |
import proto
class UrlHTML(proto.Message):
url = proto.Field(proto.STRING, number=1)
raw = proto.Field(proto.STRING, number=2)
class UrlsMessage(proto.Message):
urls = proto.RepeatedField(proto.STRING, number=1)
|
import collections
import operator
def day6a_solver(lines, character_selector=lambda ft: ft.most_common(1)[0][0]):
# count the frequency of each character in every position of our input
msglen = len(lines[0])
freq_tables = [collections.Counter() for i in range(msglen)]
for line in lines:
asser... |
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('register/login/', views.login, name = 'login'),
path('register/', views.register, name = 'register'),
path('register/logout/', views.logoutUser, name = 'logout'... |
"""
Functions for loading each main data file, creating the file from cached pages if necessary.
"""
from classes import SuperScraper, KedamaScraper, MarketScraper
from datetime import datetime
import utils, os
async def merge_auctions():
# get data
if not os.path.exists(utils.SUPER_EQUIP_FILE):
_,s_data= await S... |
import networkx as nx
import matplotlib.pyplot as plt
import tabulate as tab
class TaskNode:
def __init__(self, time=0, adj_list=None) -> None:
"""
Constructor from TaskNode
:param time: time it takes to complete a task
:param adj_list: list of nodes adjacent to the nodes
"... |
import sys
from PyQt5 import QtWidgets as qw
from Draw_v3 import DrawWidget
class MainWindow(qw.QMainWindow):
def __init__(self):
super().__init__()
#qw.QMainWindow.__init__(self) # why not?
# set Window to screen height/2 and width/2
self.setMinimumHeight(qw.QDesktopWidget().heig... |
from election.votingutils import *
from . import rule_names
def count_in_plurality(ballots):
"""
:param ballots: 2D list of lists. Each list contains the preference order of candidates.
:return: A list of winners
"""
score_board = init_score_board(ballots[0])
for preference_order in ballots:
... |
N = 100010
n = int(input())
q = list(map(int, input().split()))
q = sorted(q)
res = 0
for i in range(n):
res += abs(q[i] - q[n//2])
print(res)
|
from django.shortcuts import render
from store.models import Product
def home(request):
products = Product.objects.all().filter(is_available=True)
print("************************************************************")
print(products)
print(products.query)
print(type(products))
#print(type(n... |
from django.test import TestCase
from advertisements import urls
from rest_framework.test import APIClient
from advertisements.models import *
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
import json
from advertisements.serializers import AdvertisementSerializer
clas... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.FileItem import FileItem
from alipay.aop.api.constant.ParamConstants import *
class AlipayCommerceEcEnterpriseAuthApplyRequest(object):
def __init__(self, biz_model=None):
self._biz_model = biz_model
self._enterprise... |
#Non project imports
from django.utils.safestring import mark_safe
from django.forms import ModelForm
#Project imports
from .models import GuildProfileModel
class UpdateGuildProfileModelForm(ModelForm):
class Meta():
model = GuildProfileModel
fields = ['GuildProfileBio', 'GuildProfileImage', 'Guil... |
from typing import Tuple, List
from lvmagp.images import Image
class GuideCalc:
"""Base class for guide series helper classes."""
async def reference_target(self, images: List[Image]) -> None:
"""Analyse given images.
"""
raise NotImplementedError
async def find_offset(self, imag... |
from django.contrib import admin
from django.conf.urls import url
from django.conf.urls import include
from .views import(
PostListAPIView
)
# from social_django.urls import extra
# from login.views import complete
urlpatterns = [
url(r'^$', PostListAPIView.as_view(), name='list'),
] |
# Copyright (c) 2019. Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
# Generated by Django 3.2.4 on 2021-08-05 20:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('LK', '0003_auto_20210805_1957'),
]
operations = [
migrations.AlterModelOptions(
name='news',
options={'ordering': ['... |
# coding:utf-8
import unittest
from datadiff.tools import assert_equal
import vyattaconfparser as vparser
class TestBackupOspfRoutesEdgemax(unittest.TestCase):
def test_basic_parse_works_a1(self, dos_line_endings=False):
s = """
interfaces {
ethernet eth0 {
address 1... |
# coding=utf-8
import win32com.client
import os
from scenario_classes import ScenarioClass
class ExcelInput(object):
def __init__(self, description):
self.description_of_scenario = description
def excel_write(self):
# open excel file
excel_app = win32com.client.Dispatch("Excel.Applica... |
from get_token import *
class MyTestCase(unittest.TestCase):
"""阅读进度"""
def setUp(self):
self.book_id = 129337698467840
self.chapter_id = 397
self.cmd_id = 7064986742885395
self.option_id = 1565674662000
def test_vote(self):
"""用户投票"""
data = {
"... |
def get_is_eligible(subscription_plan, header):
pricing_eligibility = {
"free": [
"2008",
],
"basic": [
"2008", "totals"
],
"standard": [str(year) for year in range(1981, 2009)] + ["totals"],
"business": [str(year) for year in range(1981, 20... |
from time import *
# 导入time模块
# 质数优化
# 优化前 10000 4.394584894180298秒
# 100000 491.8559818267822秒
# 优化一 10000 0.5091140270233154秒
# 100000 41.997756242752075秒
# 优化二 10000 0.061048269271850586秒
# 100000 0.6928699016571045秒
begin = time()
# 100以内的数
i = 2
while i < 100000 :
# 默认为质数
flag = True
... |
def print_backwards(*args, end='', **kwargs):
print(kwargs)
#kwargs.pop('end', None) - removing from dictonary
for word in args[::-1]:
print(word[::-1], end=' ', **kwargs)
print_backwards("hello", "take", "me", "to", "your", "leader", end='\n')
# ** - unpacks a dictionary (instead of defining default paramets a... |
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
import pymysql
import logging
logger = logging... |
import networkx as nx
import planarity_test
import math
import copy
def thickness(g):
return thickness_bisection(g)
""""
Thickness merge algoritme:
Hieronder is het eerste algoritme dat wij hebben bedacht voor het bepalen van de thickness. De intuitie van dit
algoritme is om een volledige partitie van de edges t... |
import numpy as np
class SymmetrizeWfn:
@staticmethod
def swap_two_atoms(cds, dws, atm_1,atm_2):
"""Given two atoms, return a copy of the walkers in which the two atoms are swapped"""
cop = np.copy(cds)
cop[:,[atm_1, atm_2]] = cop[:,[atm_2, atm_1]]
tot_cds = np.concatenate((cds,... |
from django.contrib import admin
from listApp.models import Categories
# Register your models here.
admin.site.register(Categories)
|
import pandas as pd
df = pd.DataFrame()
nombreMascunin =''
nombreFeminin =''
annee=''
sexe=''
tranche=''
valeur1=0
valeur2=0
i = 0
data = pd.read_csv('populationpartrancheagesexe20082017.csv', delimiter=',')
file = open('test.txt', 'a')
tab = []
for index, row in data.iterrows():
print(row[... |
from django.db import models
from uuid import uuid4
from django.contrib.auth.models import User
class UserAddon(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
uuid = models.UUIDField(default=uuid4, editable=False, unique=True)
valid = models.DateTimeField(blank=True, null=True)... |
from app.model.ActionCode import ActionCode
from app.model.StatusCode import StatusCode
# ActionCode = ActionCode
# StatusCode = StatusCode
|
#!/usr/bin/python
import sys
firstLine = sys.stdin.readline().strip()
tmp = firstLine.split(' ')
if len(tmp) != 0 :
prevUsersPosts = tmp[1:]
prevCount = len(prevUsersPosts)
prevUser = tmp[0]
maxUsersPosts = tmp[1:]
maxCount = len(maxUsersPosts)
maxUser = tmp[0]
for line in sys.stdin:
line = line.strip(... |
"""
Django settings for socion project.
Generated by 'django-admin startproject' using Django 2.2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
from... |
"""
Command line interface for working with webhooks
"""
from typing import Dict, List
from uuid import UUID
import typer
from rich.table import Table
from prefect.cli._types import PrefectTyper
from prefect.cli._utilities import exit_with_error
from prefect.cli.cloud import cloud_app, confirm_logged_in
from prefect... |
from scriptgenerator import *
from plotutils import *
import sys
sys.path.insert(0, 'limittools')
from limittools import renameHistos
from limittools import addPseudoData
path='/nfs/dust/cms/user/kelmorab/treesMEMblr'
pathDB='/nfs/dust/cms/user/kelmorab/trees0108/'
name='bdtplots_parrallel_test'
#mcweight='(2.54*Weig... |
# coding:utf-8
"""
检测特定网口的ipv6地址是否包含在其它网口设置的地址中
此脚本提供给PHP使用
执行命令有以下两种方式:
@param: {ipv6} 单个ipv6地址
@param: {netport}: 目标端口
python -m utils.check_ipv6 {ipv6} {netport}
python -m /usr/local/bluedon/utils/check_ipv6 {ipv6} {netport}
"""
import sys
sys.path.append('/usr/local/bluedon')
from netaddr import IP... |
#!/usr/bin/env python
import sys
__outputTemplate = 'Case #{0}: {1}\n'
__forever = 'INSOMNIA'
__max = 1000
def getLastNumber(n):
if n == 0:
return __forever
seen = [False] * 10
i = 0
while i < __max and not all(seen):
i += 1
current = n * i
for x in str(current):
... |
def main():
list = []
top = -1
#testttttttttt
while 1 :
print "\n1.Add 2.Remove 3.Display 4.Sort [by name]\n"
option = raw_input()
if option == '':
exit()
else :
if option == '1':
print "Enter the item(s)"
while 1:
item = raw_input()
if(item!=''):
list.append(item)
else:
... |
#!/usr/bin/python3
values = open('01.in', 'r').readlines()
module_masses = [int(x) for x in values]
result = sum([x//3 - 2 for x in module_masses])
print(result) |
import os
import sys
import shutil
import asyncio
from .shared import get_yaml_dict, rel_to_cwd, verb_msg, compat_event_loop
def write_sources_file():
"""Write a sources.yaml file to current working dir."""
file_content = (
"schemes: "
"https://github.com/chriskempson/base16-schemes-source.git... |
from time import sleep
from random import randrange
class Character(object):
def __init__(self):
self.stats = {'health' : 100.0,
'attack power' : 1.0,
'defense' : 1.0,
}
self.actions = {}
self.level = 1
def take_damage(damage):
self.stats["health"] -= damage
if self.stats["health"] <... |
from bg_atlasapi.list_atlases import utils, descriptors
def lateralise_atlas_image(
atlas, hemispheres, left_hemisphere_value=1, right_hemisphere_value=2
):
atlas_left = atlas[hemispheres == left_hemisphere_value]
atlas_right = atlas[hemispheres == right_hemisphere_value]
return atlas_left, atlas_righ... |
#!/usr/bin/python
"""
" @section DESCRIPTION
" Field class for representing data in a field format
"""
import numpy as np
from operator import mul
from rf_helper import outer_product, gaussian_field, smooth_reg_l
from scipy import sparse
class Field(object):
"""Field class representing data in field format"""
... |
# -*- coding utf-8 -*-
""" -This Crawler+Scraper requests the URL (data.gov.ie - Met Éireann)) and fetches the content of the file containing historical readings of weather condition"""
""" -The time is reported in UTC which is then converted to ISO 8601 format with UTC offset"""
""" -The available data is formatted, a... |
class BankAccount:
# don't forget to add some default values for these parameters!
accounts = []
def __init__(self, int_rate, balance = 0):
self.int_rate = int_rate
self.balance = balance
BankAccount.accounts.append(self)
def deposit(self, amount):
self.balance += amount... |
def next_id(arr):
total = 0
count = 0
b = sorted(arr)[-1]
print sorted(arr)
for i in range(0, b+1):
count = count + i
for i in arr:
total = total + i
if len(arr) == 0:
print 0
elif (total != count):
diff = count - total
... |
from django.urls import path , include
from .views import welcome ,register
from django.contrib.auth import views as auth_views
urlpatterns = [
path("", welcome, name="welcome"),
path('accounts/', include("django.contrib.auth.urls")),
path("register/", register, name="register"),
]
|
import feedparser
import requests
import re
import db
from bs4 import BeautifulSoup
import tvtime
rss_link = "feed://ilcorsaronero.unblocker.cc/rsscat.php?cat=15"
def get_list():
l = tvtime.get_show_list()
return create_match_list(l)
def check_rss():
feed = feedparser.parse(rss_link)
feed = feed.e... |
import asyncio
import time
from unittest import TestCase
import motor
class Test(TestCase):
max = 90
motor1 = motor.Motor([24, 25, 8, 7], 1, max)
def test_constructor_valid(self):
pins = [24, 25, 8, 7]
ratio = 1
motor2 = motor.Motor(pins, ratio, self.max)
self.assertTrue(m... |
import unittest
import warnings
from datasets.utils import experimental
@experimental
def dummy_function():
return "success"
class TestExperimentalFlag(unittest.TestCase):
def test_experimental_warning(self):
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always"... |
"""
Provides functionality to launch a web browser on the host machine.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/browser/
"""
DOMAIN = "browser"
SERVICE_BROWSE_URL = "browse_url"
def setup(hass, config):
"""
Listen for browse_url events... |
# -*- coding: utf-8 -*-
import logging
import wcwidth
from vindauga.constants.command_codes import (wnNoNumber,
cmClose, cmZoom)
from vindauga.constants.drag_flags import dmDragMove, dmDragGrow
from vindauga.constants.window_flags import wfMove, wfGrow, wfClose, wfZoom
fr... |
from scipy.io import loadmat
import numpy
mnist = loadmat('mnist-original.loadmat')
mnist_data = mnist['data'].T
mnist_label = mnist['label'][0]
print (mnist)
print(mnist_data)
print(mnist_label) |
class Site(object):
def __init__(self, login_url, credentials, login_button_css,
login_confirm_css, username_id='username', password_id='password'):
self.login_url = login_url
self.credentials = credentials
self.username_id = username_id
self.password_id = password_... |
from boto.s3.connection import S3Connection
AWS_KEY = 'KEY'
AWS_SECRET = 'SECRET_KEY'
aws_connection = S3Connection(AWS_KEY, AWS_SECRET)
bucket = aws_connection.get_bucket('bucket_name')
for file_key in bucket.list():
print file_key.name |
import mrtparse
import radix
import logging
from typing import List
class PrefixASPath:
def __init__(self, filename:str):
self.reader = mrtparse.Reader(filename)
def __iter__(self):
return self
def __next__(self):
for m in self.reader:
mrt = m.mrt
pref... |
num = int(input('Insira um valor: '))
dobro = num * 2
trilo = num * 3
raizQuadrada = num ** (1 / 2)
print('O dobro do valor digitado é: {}, o triplo {}, e a raiz quadrada é: {}'.format(dobro, trilo, raizQuadrada))
|
""" ###1 create a class charecter in the game:
it will have attributes like name, gender, class, armor, magic item, weapon,health
##2
classes will be (barbarian, wizard, ninja)
create a class for each.
##3
barbarian will have:
weapon: ax
armor : leather
health : 80
##4
wizard will have
weapon: wand
armor : robe
h... |
from svgwrite import Drawing
from webbrowser import get
from xml.dom import minidom
from os import listdir
import struct
import imghdr
def mm(pos):
return '%fmm' % (pos)
def get_image_size(fname):
'''Determine the image type of fhandle and return its size.
from draco'''
with open(fname, 'rb') as fhan... |
"""
Queries Microsoft Academic Knowledge API with Fields of Study (paper keywords) and stores the responses locally.
The pickle file is a list of JSONs where every JSON object is the API response corresponding to a paper. Every
pickle contains a maximum of 1,000 objects (that's the maximum number of papers we can retr... |
from fastapi import FastAPI
from fastapi.exceptions import HTTPException
from fastapi.params import Header
from linebot.exceptions import InvalidSignatureError
from starlette.requests import Request
from starlette.status import HTTP_200_OK
from app.event_handler import handler
router = FastAPI()
@router.post("/webh... |
# Generated by Django 2.2.7 on 2019-11-17 22:02
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name='Course',
fields=[
... |
import urllib.request
import json
import datetime
class AvanzaScraper(object):
def __init__(self):
self.url = None
self.fond = None
self.fond_id = None
self.fond_name = None
self.beg = None
self.end = None
self.purl = "https://www.avanza.se/_cqbe/fund/chart/... |
import numpy as np
from collections import defaultdict
import random
matrix_file = open("train_data/output_matrix_number.txt")
label_file = open("train_data/output_label_number.txt")
label_dict = defaultdict()
classes = ["O", "B-LOC", "B-PER", "B-ORG", "B-TOUR", "I-ORG", "I-PER", "I-TOUR", "I-LOC", "B-PRO", "I-PRO"]... |
# Generated by Django 2.2 on 2021-01-30 14:32
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('m2m_app', '0019_auto_20210130_1631'),
]
operations = [
migrations.AlterModelOptions(
name='order',
options={'ordering': ['date... |
from flask import Flask, jsonify, request, Response
from flask_pymongo import PyMongo, ObjectId
from bson import json_util
from bson.objectid import ObjectId
import json
from werkzeug.security import generate_password_hash, check_password_hash
app = Flask(__name__)
app.secret_key = 'myawesomesecretkey'
app.config['... |
class InvalidUsage(Exception):
"""
An exception indicating a user error.
"""
def __init__(self, message, status_code=400):
self.message = message
self.status_code = status_code
def to_dict(self):
return dict(message=self.message) |
from flask import Flask
from flask_cors import CORS
import os,logging
app = Flask(__name__)
app.secret_key = 'qwertyuiopasdfghjklzxcvbnm123456'#os.urandom(24)
gunicorn_logger = logging.getLogger('gunicorn.error')
app.logger.handlers = gunicorn_logger.handlers
app.logger.setLevel(gunicorn_logger.level)
CORS(app)
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
import from 50b745c1d18d5c4b01d9d00e406b5fdaab3515ea @ KamLearn
Compute various statistics between estimated and correct classes in binary
cases
"""
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
#=======... |
#Mateusz Proc
#nr 45123
# Informatyka N1 GR. 20C
#bilbioteki użyte w programie
import math as m
import numpy as np
import matplotlib.pyplot as plt
####################################################################################################################################################
############... |
import copy
import heapq
import time
from lab1.TP1.a_star.fastest_path_estimation import fastest_path_estimation
from lab1.TP1.read_graph import read_graph
from lab1.TP1.a_star.solution import Solution
places_test = [0, 5, 13, 16, 6, 9, 20]
# sol = Solution(places_test, read_graph())
# final_sol = fastest_path_esti... |
from random import randint
options = ['Rock', 'Paper', 'Scissors']
winnerMap = {"00" : -1, "01" : 1, "02": 0, "10": 1, "11": -1, "12": 2, "20": 0, "21": 2, "22": -1}
player = ""
while len(player) < 1:
computer = options[randint(0,2)]
player = input("Rock, Paper or Scissors?: ")
if player == "q": break
if pla... |
from itertools import dropwhile, islice
from itertools import permutations, combinations
from itertools import combinations_with_replacement
def parser(filename):
with open(filename, 'rt') as f:
for lineno, line in enumerate(f, 1):
print(lineno, line)
fields = line.split()
... |
def selection_sort(list):
for i in range(len(list)-1):
min = i
for j in range(i + 1, len(list)):
if list[j] > list[min]:
min = j
list[i], list[min] = list[min], list[i]
return list
print(selection_sort([3, 6, 9, 1, 10, 4]))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# =============================================================================
# Ural Hostname Name Getter Unit Tests
# =============================================================================
from ural.get_hostname import get_hostname, get_hostname_prefixes
SUBDOMAI... |
from flask import current_app
def add_to_index(index, model):
if not current_app.elasticsearch:
return
payload = {}
for field in model.__searchable__:
payload[field] = getattr(model, field)
current_app.elasticsearch.index(index=index, doc_type=index,
id=model.id, # Use SQLAlchem... |
from urllib.parse import urlsplit, urlunsplit, urlencode
from django import template
from django.http import QueryDict
register = template.Library()
@register.simple_tag
def url_add_query(url, **kwargs):
"""
Lets you append a querystring to a url.
If the querystring argument is already present it will b... |
import model
# Training
options = model.parser.parse_args([
"--log-dir", "exp1",
"--training-data", "uk_iu-ud-train.conllu",
"--dev-data", "uk_iu-ud-dev.conllu",
"--num-epochs", "20",
"--vocab-save", "exp1/vocab.pkl",
"--settings-save", "exp1/settings.pkl",
"--params-save", "exp1/params.bin",
"--debug"
])
mode... |
#!/usr/bin/env python
import ez_setup
ez_setup.use_setuptools()
import os
import sys
from setuptools import setup, find_packages
if sys.platform != 'win32':
expect = 'pexpect>=4.0.1'
else:
expect = 'winpexpect'
setup(name='pyco',
version='0.3.0',
description='python library for network devices c... |
from keras.layers import Conv2D, UpSampling2D, InputLayer
from keras.callbacks import TensorBoard
from keras.models import Sequential
from keras.preprocessing.image import ImageDataGenerator
from skimage.color import rgb2lab, lab2rgb, rgb2gray, gray2rgb, rgb2hsv, hsv2rgb
from skimage.io import imsave
import numpy as... |
from copy import deepcopy
from statistics import median, stdev
from config import default_weight_func
class Block:
def __init__(self, word_list, middle_index, radius):
start = max(0, middle_index - radius)
end = min(len(word_list), middle_index + radius+1)
self.before_wing = word_list[s... |
# -*- coding: utf-8 -*-
import requests
import json
def post_token(api_url='https://exmail.qq.com:/cgi-bin/token'):
"""
更新/获取腾讯的Token
"""
agent_secret = 'NiOmcvhOfJfX99UU1086ZReDlcgS4FzlY4nAADqslBMsxwqk9GyY-LPOI0ROpv-w'
agent_id = 'shinezonetest'
print 'agent_id:', agent_id
print 'agent_se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.