text
stringlengths
8
6.05M
from django import template from apps.characters.models import Character register = template.Library() @register.filter def is_alive(user): if user.character_set.filter(alive=True): return True else: return False @register.filter def humanize_time(secs): mins, secs = divmod(secs, 60) ...
import unittest import basecrm from basecrm.test.testutils import BaseTestCase from decimal import * from basecrm.coercion import Coercion class TestCoercion(BaseTestCase): def test_to_decimal(self): self.assertEqual(Coercion.to_decimal(0), Decimal(0)) self.assertEqual(Coercion.to_decimal("0"), D...
from datetime import timedelta from django.conf import settings from rest_framework.settings import APISettings, api_settings USER_SETTINGS = getattr(settings, 'AUTH_TOKEN_SETTING', None) DEFAULTS = { 'HASH_ALGORITHM': 'HS256', 'JWT_SECRET_KEY': settings.SECRET_KEY, 'AUTH_TOKEN_CHARACTER_LENGTH': 64, ...
from django.urls import path from . import views urlpatterns = [ path('',views.index,name = 'index'), path('contact',views.contact, name = 'contact'), path('about',views.about,name = 'about'), path('pricing',views.pricing,name = 'pricing'), path('service',views.service,name = 'service'), path('blog',views.blog,n...
from .lnetwork_plugin import LNetworkPlugin from .models import * from .schedule_record_lan_traffic import ScheduleRecordLANTraffic from . import lnetwork_api
# coding:utf-8 from __future__ import absolute_import, unicode_literals from sanic.blueprints import Blueprint from . import spider, other __author__ = "golden" __date__ = '2018/6/25' bp = Blueprint(__name__, '/api/') bp.add_route(spider.SpidersApi.as_view(), '<project:[A-z]+>/spiders/') bp.add_route(spider.ProjectsA...
# This programs calculates the minimum fixed monthly payment needed in order to # pay off a credit card balance within 12 months. def calculatePayment(balance, annualInterestRate, numOfMonths = 12): '''(number, float, int) => float Raises AssertionError Returns the minimum fixed monthly payment needed in order...
# -*- coding: utf-8 -*- # Generated by Django 1.11.22 on 2019-08-06 17:00 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('course', '0020_badge_criteria'), ] operations = [ migrations.AddField( ...
'''earth.py: get the clouds + earth image May 2014 -- Mendez http://flatplanet.sourceforge.net/maps/night.html http://flatplanet.sourceforge.net/maps/natural.html http://wiki.birth-online.de/know-how/software/linux/xplanet http://www.fourmilab.ch/fourmilog/archives/Monthly/2005/2005-05.html http://mathematica.stack...
import unittest from katas.beta.how_much_hex_is_the_fish import fisHex class FisHexTestCase(unittest.TestCase): def test_equal_1(self): self.assertEqual(fisHex('redlionfish'), 12) def test_equal_2(self): self.assertEqual(fisHex('pufferfish'), 1) def test_equal_3(self): self.asse...
from rest_framework import serializers from rest_framework.exceptions import APIException from clasificador.models import ClassifierModel from gerente.datatxt_helpers import Datatxt import simplejson as json from pruebas.models import BaseTestResult class DataTXTErrors(APIException): status_code = 504 defaul...
# Generated by Django 2.2 on 2019-10-19 17:16 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0008_pedidos_finalizado'), ] operations = [ migrations.AddField( model_name='carro', name='activo', ...
""" Localiza el número mas pequeño de una serie de números introducidos por el usuario """ numeros_usuario = [] comprobacion= "" while len(numeros_usuario) < 10: while not comprobacion.isdigit(): comprobacion=(input("Dime un número: ")) numeros_usuario.append(comprobacion) comprobacion="" numero_...
import io import sys import unittest from logic.parking import Parking class TestParking(unittest.TestCase): def setUp(self): self.parking_obj = Parking() self.parking_obj2 = Parking() self.parking_obj2.create_parking_lot(2) self.parking_obj2.park("MH14GN5463", "blue") sel...
# 백화점 고객의 구매 데이터 import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.preprocessing import StandardScaler, RobustScaler,MinMaxScaler from sklearn.metrics import roc_curve, roc_auc_score from sklearn.ensemble import RandomForestClassifier from sklearn.tree imp...
def to_n_bits(input, input_bits = 8, output_bits = 5): """ Convert an array of N-bits integer into an array of N'-bits integers """ carry = 0 bits_count = 0 output = [] for number in input: carry = carry << input_bits carry += number bits_count += input_bits ...
import z import zen import dask_help import csv import util from sortedcontainers import SortedSet def lowSale(): z.getStocks.devoverride = "ITOT" dask_help.convertToDask.directory = "history" dask_help.createRollingData.dir = "historyCalculated" savedlow = dict() sorts = SortedSet() for a...
# coding: utf-8 """ To use this backend, 1. create /var/opt/mallet/{tool,data} 2. download mallet to /var/opt/mallet/tool 3. put dictionary file to /var/opt/mallet/data """ def retrain(data): """ /var/opt/mallet/ |- tool/ |- data/ |- dictionary |- 11397283704/ |...
from django.contrib import admin from .models import * # Register your models here. def created_by(obj): return "%s" % obj.created_by.username @admin.register(NewsText) class NewsTextAdmin(admin.ModelAdmin): list_display = ('title', 'created_at', created_by) @admin.register(Happening) class HappeningAdmi...
from panda3d.core import LineSegs, Vec4, Point3, TextNode, Vec3 # Widget that shows which direction the camera is looking in the 3D viewport. class ViewportGizmo: def __init__(self, vp): self.vp = vp axes = self.vp.getGizmoAxes() self.np = self.vp.a2dBottomLeft.attachNewNode("viewAxisWidg...
#!/usr/bin/env python # -*- coding: utf-8 -*- import NaoCreator.SpeechToText.nao_listen as Nl from NaoCreator.setting import * def test_naolisten(): Setting.naoSpeech.say("Test d'une reponse courte !") Setting.naoSpeech.say("Test de se que tu ma dit {}".format(Nl.nao_listen())) if __name__ == '__main__': ...
from marshmallow import Schema, fields from bitcoin_acks.data_schemas.project_schema import ProjectCardsSchema class AuthorSchema(Schema): avatarUrl = fields.Url() login = fields.Str() url = fields.Url() class CommentSchema(Schema): author = fields.Nested(AuthorSchema, allow_none=True) bodyText...
from marshmallow_sqlalchemy import ModelSchema, ModelSchemaOpts from models import * from marshmallow import fields, Schema from db import db from marshmallow_util import AppModelConverter from marshmallow_sqlalchemy import field_for class BaseOpts(ModelSchemaOpts): def __init__(self, meta, *args, **kwargs): ...
""" Script to get the energy and hittime distribution of the prompt signal of preselected events of atmospheric NC neutrino background that are simulated with JUNO detector simulation. 1. read only the preselected events (preselection done with script preselection_detsim_user.py and saved in folder /h...
from goods.models import Good from django.forms import ModelForm class GoodForm(ModelForm): class Meta: model = Good fields = ["name", "category", "description", "content", "price", "price_acc", "in_stock", "featured", "image"]
from django.db import models from .utils import constants from .utils.models import CreationModificationDateMixin from datetime import time # Create your models here. class Lote(CreationModificationDateMixin): """ Modelo que representa un lote """ lote_nro = models.PositiveIntegerField(help_text="I...
"""Upgrades Class.""" from fmcapi.api_objects.apiclasstemplate import APIClassTemplate from fmcapi.api_objects.device_services.devicerecords import DeviceRecords from .upgradepackages import UpgradePackages import logging class Upgrades(APIClassTemplate): """ The Upgrades Object in the FMC. NOTE: This ...
#%% import attr from typing import Dict, List import gzip import argparse import json from collections import defaultdict from typing import DefaultDict, Set, Optional, Tuple #%% @attr.s class TrecRunEntry(object): query_id = attr.ib(type=str) para_id = attr.ib(type=str) score = attr.ib(type=float) ran...
#!/usr/bin/python # Copyright 2014 Google. # # 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 agreed to...
#!/usr/bin/env python3 # coding: utf-8 from .app import run if __name__ == '__main__': run()
from pylab import * from numpy import * from PIL import Image import harris import imresize im1 = array(Image.open("C://Users//HASEE//Desktop//crans_1_small.jpg").convert("L")) im2 = array(Image.open("C://Users//HASEE//Desktop//crans_2_small.jpg").convert("L")) # 调整大小加快匹配速度 im1 = imresize(im1,(im1.shape[1]//2,im1.s...
# Copyright 2021 DAI Foundation # # 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 agreed to in writing,...
""" client.py --------- Helper methods for performing HTTP calls. Wrapper around requests module. """ import requests import base64 # declare constants here DEFAULT_TIMEOUT = 30 # in seconds CREDS_FILE = "C:\Creds\creds.txt" def get_creds(filename): """ Read credentials from a file. Format is...
# Generated by Django 2.0.3 on 2019-07-25 05:40 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('orders', '0004_auto_20190724_1829'), ] operations = [ migrations.CreateModel( name='Dinner_Plat...
import sqlite3 import shutil from datetime import datetime import os from os import listdir import csv from logger import App_Logger class DbOperation: """ This class shall be used for handling all the SQL operations and Data Type Validation. Written By: Durgesh Kumar Version: 1.0...
# coding: utf-8 """ Copyright 2016 SmartBear Software 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 applica...
name = "soan"
#!/bin/env python #_*_coding:utf-8_*_ #Author:swht #E-mail:qingbo.song@gmail.com #Date:2015.11.24 #Version:V0.0.1 import shoplogin import banklogin import linecache import time import random moneynum = 0 #获取文件的行数 # def countnum(filename): # count = 0 # thefile = open(filename, 'rb') # while True: # buffer = ...
from threading import Thread, Event import time def countdown(n: int, started_evt: Event): print('countdown starting') started_evt.set() while n > 0: print('T-minus', n) n -= 1 time.sleep(5) started_evt=Event() print("Launching countdown") t=Thread(target=countdown,args=(10,start...
import os from scikits.samplerate import resample import pandas as pd import numpy as np import logging from copy import deepcopy from braindecode.datasets.pylearn import DenseDesignMatrixWrapper import lasagne import theano from zipfile import ZipFile from zipfile import ZIP_DEFLATED import StringIO from braindecode.v...
""" Routes and views for the flask application. """ from datetime import datetime from flask import Flask,render_template, request from globalsuperstore import app import tweepy import time import os from textblob import TextBlob import pandas as pd @app.route('/') @app.route('/home') def home(): """Renders the ...
import pickle import numpy as np import os from datetime import datetime def get_pickle_file_content(full_path_pickle_file): pickle_file = open(full_path_pickle_file,'rb') pickle_list = pickle.load(pickle_file, encoding='latin1') pickle_file.close() return pickle_list def get_ret_type_dict(pick...
from typing import KeysView, Dict from datetime import datetime, timedelta import logging from threading import Timer, Lock from ..fleet import member_info from ...storage.database import CrestFleet, FleetTime, Character, FleetTimeLastTracked, FleetTimeByHull from ...base import db from ..swagger.eve.fleet.models impor...
notes = range(25) notes_names = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"] modes = range(7) modes_names = ["Ionian", "Dorian", "Phrygian", "Lydian", "Mixolydian", "Aeolian", "Locrian"] scales = [0, 2, 4, 5, 7, 9, 11, 12, 14, 16, 17, 19, 21, 23, 24] chords = { "maj" : [0, 4, 7], "min" : [0, 3, ...
__author__ = 'shannonjaeger' from Exceptions import * import csv class Member(object): def __init__(self, imis, first_name=None, last_name=None, active=False, dates_selected=[]): try: assert(isinstance(imis, int)) self.imis = imis except: self.imis = int(imis)...
p = (4, 5) x, y = p print x print y data = ['ACME', 50, 91.1, (2016, 05, 16)] name, shares, price, date = data print name print shares print price print date name, shares, price, (year, month, day) = data print name print shares print price print year print month print day s = 'hello' a, b, c, d, e = s print a, b, c...
#!/usr/bin/env python # coding: utf-8 # In[24]: import numpy as np from numpy import linalg as la import pandas as pd from scipy import stats from scipy.special import logsumexp from sklearn.mixture import GaussianMixture from sklearn.model_selection import KFold import math from scipy.stats import multivariate_norm...
from models import RequestItem from django.http import HttpResponse class StoreRequestMiddleware(object): """ This middleware is saving every request object to database """ current_request = None def process_request(self, request): self.current_request = RequestItem.objects.create( ...
# -*- coding: utf-8 -*- #num=int(input()) #if (num % 4 ==0) and not(num % 100 == 0): # if (num % 4 == 0) or (num % 400 == 0): # print(num,"is a leap year.") #else: # print(num,"is not a leap year.") #year=int(input()) #if year % 4 == 0: # if year % 400 ==0: # print(year,"is a leap year.") #elif ...
# 排序函数 # 重要的是reverse属性 a = [1, 99, 6, 8, 44, -58, -11, -33] print(sorted(a, key=abs)) print(sorted(a, reverse=True)) b = ['Lisa', 'Bob', 'Adam', 'Bart'] print(sorted(b)) # 全部忽略首字母大小写 print(sorted(b, key=str.lower)) x = (1,) print(list(x)[0])
import numpy as np import tensorflow as tf import tensorflow_probability as tfp tfd = tfp.distributions class MixturePrior(object): def __init__(self, pi, sigma1, sigma2): self.mu, self.pi, self.sigma1, self.sigma2 = (np.float32(v) for v in (0.0, pi, sigma1, sigma2)) self.dist = tfd.MixtureSameFami...
while True: try: d = int(input()) except: break print(sum([(i*d)**2*d for i in range(600//d)]))
# This is a sample Python script. # Press Shift+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. from tkinter import * import os import shutil from tkinter import messagebox root=Tk() def compare_file(file1...
from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.select import Select import time driver=webdriver.Chrome() driver.get("file:///C:/Users/%E5%9C%9F%E8%B1%86/Desktop/%E6%96%B0%E5%BB%BA%E6%96%87%E6%9C%AC%E6%96%87%E6%A1%A3%20(8).html") '''mouse...
#!/usr/bin/env python """ This returns whether or not a PDB file contains all of the require backbone heavy atoms: ' CA ', ' CB ', ' C ', ' N ', ' O ' """ import sys res_types = (['ALA', 'ARG', 'ASN', 'ASP', 'CYS', 'GLU', 'GLN', ...
#!/usr/bin/env python import urllib2, os, subprocess, shutil, time, re from sys import argv, exit from distutils.version import LooseVersion script, log_file = argv class install(object): def __init__(self): self.app_name = "Dropbox" self.the_app = self.app_name + ".app" self.info_file = ...
names = ["andy", "sue", "pete"] for name in names: name.capitalize() names = [name.capitalize() for name in ("andy", "sue", "pete")] assert names == ["Andy", "Sue", "Pete"] some_names = [name for name in names if name[0] != "S"] assert some_names == ["Andy", "Pete"] some_names.append(sum([num for num in range...
html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a href="http://example.com/l...
#!/usr/bin/env python3 # Created by: Liam Csiffary # Created on: May 21, 2021 # This program calculates the factorial of the users number # main function def main(): # vars user_num = input("what is the number: ") # make sure the users num can be an integer try: user_num = int(user_num) ...
def get_middle(s): q, r = divmod(len(s), 2) return s[q - (1 if not r else 0):q + 1]
from gym.envs.registration import register # Env registration # ========================== register( 'ObjectDetection-v0', entry_point='rl_od.envs.rl_od:rl_od' )
def main(): pyksi = input ("Pelaaja 1, syötä valintasi (K/P/S): ") pkaksi = input("Pelaaja 2, syötä valintasi (K/P/S): ") if pyksi == "K" and pkaksi == "K": print ("Tuli tasapeli.") elif pyksi == "P" and pkaksi == "P": print ("Tuli tasapeli.") elif pyksi == "S" and pkaksi == "...
"""Base for all node resource services. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import abc import collections import errno import glob import io import logging import os import socket import struct import ...
import turtle screen = turtle.Screen() image = "rock.gif" screen.register_shape(image) turtle.shape(image) screen.bgcolor("lightblue") move_speed = 10 turn_speed = 10 def forward(): turtle.forward(move_speed) def backward(): turtle.backward(move_speed) def left(): turtle.left(turn_speed) def right(): ...
from charm.schemes.grpsig.groupsig_bgls04 import ShortSig as BGLS04 from charm.schemes.grpsig.groupsig_bgls04_var import ShortSig as BGLS04_Var from charm.toolbox.pairinggroup import PairingGroup import unittest debug = False class BGLS04Test(unittest.TestCase): def testBGLS04(self): groupObj = PairingGro...
import cv2 import numpy as np class VideoHelper(object): """ This class will help us to duel with operations related with videos such as open/close, read/write video and also we can use this helper to get attributes of the video """ def __init__(self, config): # video in self.v...
import cv2 from streamlit_webrtc import VideoTransformerBase, webrtc_streamer webrtc_streamer(key="example")
""" TensorFlow integration. Importing this module registers the TensorFlow backend with `phiml.math`. Without this, TensorFlow tensors cannot be handled by `phiml.math` functions. To make TensorFlow the default backend, import `phi.tf.flow`. """ from phiml.backend.tensorflow import TENSORFLOW __all__ = [key for key ...
import time import math import datetime from influxdb import InfluxDBClient from threading import Event, Thread, Timer from multiprocessing import Queue import serial import socket import sys from dbSetting import * # Create a UDP socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Bind the socket to the...
# -*- coding: utf-8 -*- # One Statement per Line from datetime import datetime with open('test.txt', 'w') as f: f.write('Today is ') f.write(datetime.now().strftime('%Y-%m-%d')) with open('test.txt', 'r') as f: s = f.read() print('open for read...') print(s) with open('test.txt', 'rb') as f: ...
from bottle import request from .app import app from .app.auth import sign_in @app.post("/api/signin") def post_sign_in(db): email = request.POST.get("email") password = request.POST.get("password") return sign_in(db, email, password)
# number conversion # zio800 # decimal to binary def nc10_2(num10): num2 = [] while num10 / 2 != 0: num2.append(str(num10 % 2)) num10 = num10 // 2 num2.reverse() ans = int(''.join(num2)) print('binary = ', ans) # decimal to octal def nc10_8(num10): num8 = [] ...
from flask_restful import Resource, reqparse from models.user import Usermodel from flask_jwt import jwt_required import json import logging log = logging.getLogger(__name__) class User(Resource): parser = reqparse.RequestParser() parser.add_argument('username', required=True, type=str, help='This f...
import argparse import re import glob import os import numpy as np import matplotlib.pyplot as plt import sys args = dict() data = dict() origDir = os.getcwd() #plt.style.use('ggplot') ## plt.style.use('grayscale') ## plt.style.use('fivethirtyeight') #print plt.style.available numInst = re.compile('Number of Instru...
from apps.users.models import UserProfile, UserToken from apps.jobs.models import Jobs from apps.users import handler as user_handler import serializers from django.http import Http404, HttpResponse from ipware.ip import get_real_ip, get_ip from libs.sparrow_handler import Sparrow from rest_framework.views import...
""" 合同视图模块 """ # pylint: disable=invalid-name, too-few-public-methods from datetime import datetime from flask import render_template, redirect, url_for, flash, make_response, request from flask_login import login_required, current_user from flask_moment import Moment import pytz from sqlalchemy import and_, or_, not_ ...
from django.core.exceptions import ObjectDoesNotExist from django.utils.timezone import localdate from rest_framework import serializers from rest_framework.exceptions import ValidationError from ..models import Menu, Option class OptionSerializer(serializers.ModelSerializer): class Meta: model = Option ...
from view import View view = View()
import time import pandas as pd import numpy as np # PLEASE USE THE GIVEN FUNCTION NAME, DO NOT CHANGE IT def read_csv(filepath): ''' TODO : This function needs to be completed. Read the events.csv and mortality_events.csv files. Variables returned from this function are passed as input to the metric...
import requests from bs4 import BeautifulSoup import pandas as pd #封装成函数 def get_page_content(request_url): #得到页面内容 headers={'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36'} html=requests.get(request_url,headers=headers,...
import keras.models def biard_net(in_shape, n_classes): return keras.models.Sequential([ keras.layers.Conv2D(filters=64, kernel_size=(5, 5), padding="same", input_shape=in_shape, activation='relu'), keras.layers.Conv2D(filters=64, kernel_size=(5, 5), padding="same", input_shape=in_shape, activatio...
from django.contrib import admin from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin from .models import * class SearchIssue(admin.ModelAdmin): search_fields = ["title"] class SearchNewsEvents(admin.ModelAdmin): search_fields = ["title"] class SearchPeople(admin.Model...
#!/usr/bin/env python from twisted.application import service from consider import server master = server.MasterService() application = service.Application("consider-server") master.setServiceParent(application)
#for qaudratic equation of these form ax^2 + bx +c=0 #import complex math module import cmath #using the integer and input text a= int(input("a =")) b= int(input("b = ")) c= int(input("c = ")) # to calculate the discriminant d = (b**2) - (4*a*c) # find two solutions x1 = (-b-cmath.sqrt(d))/(2*a) x2 = (-b+cmath.sqrt(d)...
# Generated by Django 2.0.7 on 2018-09-14 14:31 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('TraverMsg', '0002_auto_20180914_1419'), ] operations = [ migrations.RemoveField( model_name='travermsg', name='end_c...
from __future__ import absolute_import from numbers import Number from plotly import exceptions, optional_imports from plotly.figure_factory import utils from plotly.graph_objs import graph_objs from plotly.tools import make_subplots pd = optional_imports.get_module('pandas') np = optional_imports.get_module('numpy'...
import pytesseract from PIL import Image,ImageDraw #pytesseract.pytesseract.tesseract_cmd = 'F:/Tesseract-OCR/tesseract.exe' #C:\\Users\\Administrator\\Desktop\\企业雷达\\百度信用公司图标\\getCapImg.jpg #F:\\baiduimg\\0ERuBLlQ_imges.png #F:\\yzm\\1412260-20180701125834481-1681474414.png img = Image.open('F:\\yzm\\txtimg.png') img...
from django.db import models from catalog.managers import TLEManager class TLE(models.Model): class Meta: verbose_name = "Two Line Element" verbose_name_plural = "Two Line Elements" first_line = models.CharField( max_length=70, null=True ) second_line = models.CharFiel...
#!/usr/bin/env python """ billy.py Compare models using CROW features w/ those using bilinear features !! Need to clean up the ordering """ import os import sys import bcolz import numpy as np import pandas as pd from sklearn.decomposition import PCA from sklearn.svm import LinearSVC from sklea...
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations from textwrap import dedent import pytest from pants.backend.go import target_type_rules from pants.backend.go.goals import check from pants.backend.g...
from sklearn.datasets import make_moons from sklearn.cluster import KMeans from matplotlib.pylab import plt x, y = make_moons(200, noise=.05, random_state=0) print(x, y) labels = KMeans(2, random_state=0).fit_predict(x) plt.scatter(x[:,0], x[:,1], c=labels, s=50, cmap='viridis') plt.show()
# deps.py -- Portage dependency resolution functions # Copyright 2003-2012 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 __all__ = [ 'Atom', 'best_match_to_list', 'cpvequal', 'dep_getcpv', 'dep_getkey', 'dep_getslot', 'dep_getusedeps', 'dep_opconvert', 'flatten', 'get_operato...
#If the bill was $150.00, split between 5 people, with 12% tip. #Each person should pay (150.00 / 5) * 1.12 = 33.6 #Format the result to 2 decimal places = 33.60 #Tip: There are 2 ways to round a number. You might have to do some Googling to solve this.💪 #HINT 1: https://www.google.com/search?q=how+to+round+number+to...
from flask import current_app from werkzeug.local import LocalProxy from werkzeug.utils import import_string def import_shop_object(key): shop = current_app.config['SHOP_ID'] shop_settings = current_app.config['SHOPS'][shop] return import_string(shop_settings[key]) def get_order_class(): key = 'orde...
import numpy as np import random from utils import * from math import sqrt class replay_buffer: def init(self): self.n = 0 self.data = [] self.s = [] self.a = [] self.r = [] self.s2 = [] self.d = [] self.i_episode = [] self.ban = [] ...
#!/usr/bin/env python # encoding: utf-8 import urllib import logging from tornado.gen import coroutine from tornado.httpclient import AsyncHTTPClient from settings import ALERT_VOICE_API, ALERT_VOICE_TOKEN @coroutine def sender(mobiles, content): mobile = ','.join(map(str, mobiles)) logging.info("tel will ...
from fashion.models import Researcher from django import forms from mongodbforms import DocumentForm,EmbeddedDocumentForm, CharField class ResearcherForm(DocumentForm): lattes_ids = CharField() class Meta: model = Researcher class LoadIDForm(forms.Form): lattes_ids = CharField(widget=forms.Textarea) start_year...
""" Problem Statement Джеймс раздобыл любовное письмо, которое его друг Гарри написал своей девуш- ке. Будучи шутником, Джеймс решил изменить его. Он превратил все слова в палинд- ромы. В каждом слове он изменял буквы только на меньшие, например, 'd' он мог превратить в 'c' и это считалось одной операцией. ( ...
# https://www.hackerrank.com/contests/june-world-codesprint/challenges/minimum-distances import itertools def difference(a_pair): x, y = a_pair return abs(x-y) def list_duplicates(source, item): return [index_x for index_x, x in enumerate(source) if x == item] def min_dist(A): min_dist_list = [] ...
# 水题 grades = [] N = int(input()) minv, maxv = 101, -1 s = 0 for _ in range(N): t = int(input()) minv = min(t, minv) maxv = max(t, maxv) s += t print(maxv) print(minv) print("%.2f"%(s/N))