content stringlengths 5 1.05M |
|---|
class LabelSettings(object):
@property
def INSTALLED_APPS(self):
return super().INSTALLED_APPS + ['labels']
default = LabelSettings
|
import math
import numpy
import pyaudio
"""Note table
Key: Note Value: # of half steps
"""
NOTES_TABLE = {'Bb': 1, 'B': 2,
'C': 3, 'C#': 4,
'D': 5, 'Eb': 6,
'E': 7, 'F': 8,
'F#': 9, 'G': 10,
'Ab': 11}
BASE_FREQ = 440
def get_note(note, bas... |
# coding: utf-8
import math
import os
import random
import string
import sys
import time
PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(PROJECT_DIR)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
import django
django.setup()
from django.conf import sett... |
from .dispatch.rules import bot
from .framework.bot import ABCBotLabeler, Bot, BotBlueprint, BotLabeler, bot_run_multibot
from .tools.dev_tools.mini_types.bot import MessageMin
Message = MessageMin
Blueprint = BotBlueprint
rules = bot
|
from django.apps import AppConfig
class CodeanalysisConfig(AppConfig):
name = 'codeAnalysis'
|
"""
Insertion Sort
Always keep sorted in the sublist of lower positions. Each new item is then `inserted` back into
the previous sublist.
The insertion step looks like bubble sort, if the item located at `i` is smaller than the one before,
then exchange, until to a proper position.
[5, 1, 3, 2] -... |
import os
import secrets
from flask import render_template, url_for, redirect, request, Response
from palette.forms import ImageForm
from palette import app
from kmeans import get_colors
def save_picture(form_picture):
random_hex = secrets.token_hex(8)
_, f_ext = os.path.splitext(form_picture.filename)
pi... |
from django.template import Library, Node
register = Library()
class DumpNode(Node):
def render(self, context):
# for v in context.dicts[7]: print vars(context.get(v))
# import ipdb; ipdb.set_trace()
return ''
@register.tag
def dump_context(parser, token):
return DumpNode()
dump_conte... |
import dataclasses
import typing
import module3
@dataclasses.dataclass()
class Bar:
def is_in_foo(self, foo: module3.Foo):
return self in foo.bars
|
#!/usr/bin/env python3
from time import time
def find_pythagorean_triplet(n):
""" Find a Pythagorean triplet a^2+b^2=c^2 for which a+b+c=`n`. """
for c in range(n - 2, 0, -1):
for a in range(n - c - 1, 0, -1):
b = n - c - a
# Check if a,b,c form a valid Pythagorean triplet.
... |
# Generated by Django 3.0.1 on 2020-07-02 20:15
from django.conf import settings
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
... |
# coding: utf-8
import unittest
from unittest import mock
import numpy as np
from spectrum import marple_data
from hrv.classical import (time_domain, frequency_domain, _auc, _poincare,
_nn50, _pnn50, _calc_pburg_psd)
from hrv.io import read_from_text
from hrv.rri import RRi
from tests.test... |
from libs.config import alias, color
from libs.myapp import send, delay_send, is_windows, has_env, get_system_code, base64_encode
from libs.functions.webshell_plugins.old_socks import *
from threading import Thread
from time import sleep
def get_python(port):
return get_php_old_socks() % port
@alias(True, _type... |
from TurtleBop.models.guild import * |
import random
import numpy as np
import pandas as pd
import pytest
from privacy_budget import PrivacyBudget
from privacy_budget_tracker import MomentPrivacyBudgetTracker
from private_machine_learning import private_SGD
from utils import check_absolute_error
@pytest.fixture
def data():
np.random.seed(1)
x = ... |
# coding: utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import tensorflow as tf
class Recorder(object):
"""To save training processes, inspired by Nematus"""
def load_from_json(self, file_name):
tf.logging.info("Loadin... |
from django.db import models
from django.contrib.auth.models import User
class File(models.Model):
title = models.CharField(max_length=255, blank=True)
hash_val = models.CharField(max_length=200)
uploaded_at = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, on_delete=models.CASC... |
"""
A means of running standalone commands with a shared set of options.
"""
from __future__ import print_function
from __future__ import absolute_import
#-----------------------------------------------------------------------------
# Copyright (c) 2013, yt Development Team.
#
# Distributed under the terms of the M... |
from sqlalchemy import func
from sqlalchemy import types as sqltypes
from sqlalchemy.types import UserDefinedType
from sqlalchemy.sql import operators
class MolComparator(UserDefinedType.Comparator):
def hassubstruct(self, other):
return self.operate(
operators.custom_op('@>'), other, result_t... |
import FWCore.ParameterSet.Config as cms
process = cms.Process("OWNPARTICLES")
process.load("FWCore.MessageService.MessageLogger_cfi")
process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(100) )
process.source = cms.Source("PoolSource",
fileNames = cms.untracked.vstring('file:/user/geisler/RelVal... |
import scrapy
class LbcSpider(scrapy.Spider):
name = "lbc"
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.36 Safari/535.7'}
start_urls = ['https://www.leboncoin.fr/ventes_immobilieres/offres/ile_de_france']
def parse(self, response):... |
import cmazure.storage.account
import cmazure.storage.common
import cmazure.common
from cmazure.credentials import AzureCredentials
def test_create():
creds = AzureCredentials.make_from_environment()
storage_client = cmazure.storage.common.make_storage_client(creds)
resource_client = cmazure.common.make_... |
# SPDX-License-Identifier: Apache-2.0
#
# Copyright (C) 2015, ARM Limited and contributors.
#
# 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
#
# ... |
import zipfile
import io
import requests
def _get_zip(url):
"""Retrieve zipfile using http request.
zipfiles
Parameters
----------
url : type
Description of parameter `url`.
Returns
-------
zipfile.ZipFile
Usage:
>>> zip = _get_zip('https://www.bls.gov/oes/special.... |
# import asyncio
import logging
import pathlib
# import re
# import httpx
logger = logging.getLogger(__name__)
class Tag:
@staticmethod
def tag(tag, content, **attrs):
attr_line = ''.join(f' {attr}="{v}"' for attr, v in attrs.items())
return f'<{tag}{attr_line}>{content}</{tag}>'
@stati... |
# -*- coding: utf-8 -*-
#
# This class was auto-generated from the API references found at
# https://epayments-api.developer-ingenico.com/s2sapi/v1/
#
from ingenico.connect.sdk.data_object import DataObject
from ingenico.connect.sdk.domain.definitions.lodging_charge import LodgingCharge
from ingenico.connect.sdk.domain... |
import os
os.environ['TF_KERAS'] = '1'
import numpy as np
from skimage.filters import gaussian
if os.environ.get('TF_KERAS'):
from classification_models.tfkeras import Classifiers
class DummyModel:
def __init__(self):
pass
def predict(self, image: np.ndarray, sigma: float = 3.0) -> np.ndarray:
... |
# -*- coding: utf-8 -*-
"""
Utilities for ROSES 2021
Adapted from (https://github.com/bgoutorbe/seismic-noise-tomography)
"""
import numpy as np
import itertools as it
import scipy
import pygmt
import xarray as xr
from . import psutils
from .pstomo import Grid
def make_G(paths, grid, v0):
"""
Makes the matr... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class Attention(nn.Module):
def __init__(self):
super(Attention, self).__init__()
self.L = 500
self.D = 128
self.embeddingDimension = 120
self.K = 1
self.attention = nn.Sequential(
nn.Li... |
from src.util import resource_path, data_path
from kivy.config import Config
Config.set('kivy', 'log_dir', data_path(''))
import kivy.resources
kivy.resources.resource_add_path(resource_path('src/ui'))
from src.ui.kivy.KivyPlyerGui import RSS2VidApp
RSS2VidApp().run()
|
"""
testing a trained model for scheduling,
and comparing its performance with the
size-aware whittle index heuristic.
To test a control policy, uncomment the code corresponding to an algorithm.
"""
import os
import torch
import random
import operator
import itertools
import numpy as np
import pandas as pd
import ... |
import os
from common.utils import run, expect_retcode
def run_test(sut, verbose, debug):
this_dir = os.path.dirname(os.path.abspath(__file__))
args = '-h'.split()
proc, out = run(sut, args, this_dir, 3, verbose, debug)
expect_retcode(proc, 0, out, verbose, debug)
|
import mediacloud, datetime, logging
logging.basicConfig(filename='electionCount.log', format='%(levelname)s:%(message)s', level=logging.DEBUG)
class ElectionCount:
def __init__(self, key):
#Intitalise function with actual key value
self.key = key
logging.info('Accessing MediaCloud')
self.mc = mediacloud.ap... |
class WalkNavigation:
jump_height = None
mouse_speed = None
teleport_time = None
use_gravity = None
use_mouse_reverse = None
view_height = None
walk_speed = None
walk_speed_factor = None
|
from time import time
import fibonacci as pf
import cFibonacci as cf
n = 1000000
t1 = time()
pf.ifib(n)
t2 = time()
cf.ifib(n)
t3 = time()
print
print "n=" + str(n)
print "Iterative fibonacci time in Python: " + str(t2-t1)
print "Iterative fibonacci time in C: " + str(t3-t2)
print "C/Python ratio: " + ... |
from setuptools import setup, find_packages
setup(name="Qelos Core",
description="qelos-core",
author="Sum-Ting Wong",
author_email="sumting@wo.ng",
install_requires=[],
packages=["qelos_core"],
)
|
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 7 20:14:28 2021
@author: punti
"""
print("Hello World") |
n = int(input())
for i in range(1, n + 1):
print(i) |
# ex028 é a v1.0 do jogo. Fazer várias tentativas até acertar o número que o computador 'pensou'
# número int entre 0 e 10
from random import randint
pc = randint(0, 10)
print('''Sou seu computador,...
Acabei de pensar em um número entre 0 e 10.
Será que você consegue acertar com menos de 4 tentativas?''')
acertou = F... |
from flask import Flask, abort
import json
import socket, sys
app = Flask(__name__)
PORT = 7555
MAX = 65535
temp= []
@app.route('/node', methods=['GET'])
def semua():
return json.dumps(temp)
@app.route('/node/<int:node_id>', methods=['GET'])
def satu(node_id):
node = None
for n in temp :
if n["id"... |
from django.conf import settings
from django.urls import include, re_path
from django.conf.urls.static import static
from django.contrib import admin
from testproject import views
urlpatterns = [
re_path(r'^admin/', admin.site.urls),
re_path(r'^$', views.TestView.as_view(), name='home'),
re_path(r'^groups... |
#!/usr/bin/env python
"""
Neighboring WBEM agents.
"""
import sys
import logging
import lib_util
import lib_wbem
import lib_common
import lib_credentials
from lib_properties import pc
from sources_types import neighborhood as survol_neighborhood
# Similar to portal_wbem.py except that:
# - This script uses SLP.
# -... |
import os
import shutil
import tensorflow as tf
from tensorflow import keras
from logs import logDecorator as lD
import jsonref
import numpy as np
import pickle
from tqdm import tqdm
import PIL
import matplotlib.pyplot as plt
config = jsonref.load(open('../config/config.json'))
logBase = config['logging']... |
#!venv/bin/python
import re
import os
import sys
SUBS = [
('AsyncIteratorByteStream', 'IteratorByteStream'),
('AsyncIterator', 'Iterator'),
('AutoBackend', 'SyncBackend'),
('Async([A-Z][A-Za-z0-9_]*)', r'Sync\2'),
('async def', 'def'),
('async with', 'with'),
('async for', 'for'),
('awa... |
# Copyright (C) 2020 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""
Add 2 new roles for scoping objects
Create Date: 2018-10-23 11:02:28.166523
"""
# disable Invalid constant name pylint warning for mandatory Alembic variables.
# pylint: disable=invalid-name
import dat... |
# -*- coding: utf-8 -*-
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import random
import string
import logging
from copy import deepcopy
# Import Salt Testing libs
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.unit import skipIf, TestCase
f... |
#!/usr/bin/env python3
import os
from app.models import Player
from app.resources import GamePlay
import argparse
def get_team():
"""
Initializes the squad: the list of players in the order they are
expected to bat.
Uses the Player model to create each batsman with their given
scoring probabiliti... |
import sys
from typing import List
input = sys.stdin.readline
# def solution(N: int, nums: List[int]):
# __cache__ = [[0, 0] for _ in range(N)]
# __cache__[0] = [nums[0], nums[0]]
# for i in range(1, N):
# __prev__ = 0
# for j in range(i - 1, -1, -1):
# if nums[j] < nums[i]:
... |
from redis_admin.compat import url as redis_admin_url, get_library
Library = get_library()
register = Library()
@register.tag
def url(parser, token):
return redis_admin_url(parser, token)
|
'''Glyph'''
from importlib import reload
import zDogPy.shape
reload(zDogPy.shape)
from zDogPy.shape import Shape
def makePath(glyph, closed=True):
path = []
for ci, c in enumerate(glyph.contours):
if closed:
pt0 = c[-1][-1]
cmd = { 'move' : {'x': pt0.x, 'y': pt0.y } }
... |
somaidade = 0
maioridadehomem = 0
totmulher20 = 0
nomevelho = ''
for dados in range(1, 5):
print('----- {}ª PESSOA -----'.format(dados))
nome = str(input('Nome: ')).strip()
idade = int(input('Idade: '))
sexo = str(input('Sexo [M/F]: ')).strip()
somaidade += idade
if dados == 1 and sexo... |
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
#
# Copyright © 2022 Christos Pavlatos, George Rassias, Christos Andrikos,
# Evangelos Makris, Aggelos Kolaitis
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the “Software”), to deal in
# the Software without rest... |
from rest_api import db
from datetime import datetime
# attachment for tracking logs / user posts, many to one
class AttachmentModel(db.Model):
__tablename__ = "attachments"
id = db.Column(db.Integer, primary_key=True)
attachment_name = db.Column(db.String(200), nullable=False, unique=True)
# need i... |
price = int(input("Give me the price of this place! "))
rent = int(input("and what's the rent per week? "))
bodyC = int(input("and the body corporate per quarter? "))
RatesLand = int(input("What do the land rates look like per quarter? "))
RatesWater = int(input("Finally, I'll need the water rates per quarter? ")... |
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'seminar-roulette.settings')
import django
django.setup()
from backend.models import *
import csv
import os
import random
import pandas as pd
import numpy as np
import math
from django.utils import timezone
from scipy.sparse.linalg import svds
class Recomme... |
# LeetCode 888. Fair Candy Swap `E`
# 1sk | 92% | 7'
# A~0v06
class Solution:
def fairCandySwap(self, A: List[int], B: List[int]) -> List[int]:
setB = set(B)
dif = (sum(B)-sum(A)) // 2
for a in A:
if a + dif in setB:
return [a, a+dif]
|
# -*- coding: utf-8 -*-
"""
Tests for tipfy.appengine.db
"""
import unittest
import hashlib
from google.appengine.ext import db
from google.appengine.api import datastore_errors
from werkzeug.exceptions import NotFound
from tipfy.appengine import db as ext_db
import test_utils
class FooModel(db.Model):
na... |
from typing import Optional
from pydantic import BaseModel
class Query(BaseModel):
shop_url: str
api_secret: str |
import numpy as np
import cv2
from matplotlib import pyplot as plt
cap = cv2.VideoCapture('Night Drive - 2689.mp4')
count = 0
while(cap.isOpened()):
count += 1
if count < 100:
continue
ret, frame = cap.read()
plt.imshow(cv2.cvtColor(frame,cv2.COLOR_BGR2RGB))
plt.show()
H, S, V = c... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
#!/usr/bin/env python
from django.apps import AppConfig
class DjangoMakeSuperUserConfig(AppConfig):
name = 'django_makesuperuser'
|
#!/usr/local/bin/python3.5
# Copyright (c) 2017 David Preece, All rights reserved.
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INC... |
# implementation of iWare-E for PAWS
# Lily Xu
# May 2019
import sys
import time
import pickle
import pandas as pd
import numpy as np
from scipy.optimize import minimize
from sklearn import metrics
from sklearn.model_selection import train_test_split, StratifiedKFold
from sklearn.preprocessing import StandardScaler... |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
"""
Go through `001_basic_usage.py` before running this example. We will re-use
the same computation: x*y and z+w for x in [1, 2, 3], y = 2, z = 4,
w in [5, 6] in an experiment called BasicUsage.
Suppose you have done your experiment (say running `001_basic_usage.py`) and... |
from html.parser import HTMLParser
class CardParser(HTMLParser):
inside_p = False
text = ''
def clear(self):
self.text = ''
self.inside_p = False
def handle_starttag(self, tag, attrs):
# print("Start tag:", tag)
if tag == "p":
self.inside_p = True
... |
import os
import sys
import time
from argparse import SUPPRESS, ArgumentParser
from dodo_commands import CommandError, Dodo
from dodo_commands.dependencies.get import plumbum
from dodo_commands.framework.choice_picker import ChoicePicker
from dodo_commands.framework.util import exe_exists
tmux = plumbum.cmd.tmux
de... |
import marshal
exec(marshal.loads(b'\xe3\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00@\x00\x00\x00s\xda\x00\x00\x00d\x00d\x01l\x00Z\x00d\x00d\x01l\x01Z\x01d\x00d\x01l\x02Z\x02d\x00d\x02l\x03m\x04Z\x05\x01\x00d\x00d\x03l\x06m\x07Z\x07\x01\x00d\x00d\x04l\x08m\x08Z\x08\x01\x00d\x00d\x05l... |
# Copyright 2021 Google LLC
#
# 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, ... |
from weather import Weather
weather = Weather(verbose=1)
region = weather.getRegion() # 支持的所有地区
cities = weather.getCity() # 支持的所有城市
support = weather.getRegionCity(region='巴西') # 支持的巴西的城市
result = weather.getWeather(city='广州') # 查询广州的天气
print('支持的地区数', len(region))
print('支持的城市数', len(cities))
print('支持的... |
import pandas as pd
from TemporalFeatureFactory import TemporalFeatureFactory, temporal_driver
from utils.misc_utils import connect_rds
###
# DEFINE SETTINGS TO CREATE TEMPORAL FEATURES
###
time_granularity = '60min'
start_date = '2016-01-01'
end_date = '2018-02-01'
conn = connect_rds()
schema_name = 'features_tem... |
import datetime
from unittest import mock
from django.urls import reverse
from api.organisations.enums import OrganisationDocumentType
from test_helpers.clients import DataTestClient
class OrganisationDocumentViewTests(DataTestClient):
def create_document_on_organisation(self, name):
url = reverse("orga... |
from PIL import Image
from io import BytesIO
import aiohttp
import discord
import logging
import os
import secrets
import subprocess
from redbot.core import commands, checks, Config
from redbot.core.data_manager import cog_data_path
log = logging.getLogger("red.aikaterna.antiphoneclapper")
class AntiPhoneClapper(co... |
import FWCore.ParameterSet.Config as cms
process = cms.Process("DCRec")
process.load("Configuration.StandardSequences.MagneticField_cff")
#process.load("Configuration.StandardSequences.Geometry_cff") # Depreciated
process.load("Configuration.Geometry.GeometryIdeal_cff")
process.load("Configuration.EventCont... |
import json
from typing import cast, List
from fhir.resources.claim import Claim
from fhir.resources.claim import ClaimItem
from fhir.resources.address import Address
from fhir.resources.organization import Organization
from schema.insight_engine_response import InsightEngineResponse, Insight, InsightType, Trace
def... |
#!/usr/bin/python
# Classification (U)
"""Program: argparser_arg_parse2.py
Description: Integration testing of arg_parse2 in
gen_class.ArgParser class.
Usage:
test/integration/gen_class/argparser_arg_parse2.py
Arguments:
"""
# Libraries and Global Variables
# Standard
import sys
imp... |
from queue import Queue
"""Script to find the first non-repeating string in a stream.
This module reads a file called stream.txt to create a stream of strings. As a string is received, return the first
non-repeating string in the stream.
Example:
$ python nonrepeating.py
Todo:
* Add input argument for ... |
from django.urls import path
from . import views
urlpatterns = [
path(route='login' , view=views.LoginView.as_view() , name='login_page') ,
path(route='logout' , view=views.LogoutView.as_view() , name='logout_page') ,
path(route='register' , view=views.RegisterView.as_view() , name='register_page') ,
... |
from flask import request, make_response, render_template
from flask.views import MethodView
from flask_cas import login_required
from common_functions import display_access_control_error
from catCas import validate_professor
import gbmodel
class MissingStudentException(Exception):
"""
We raise this exception... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import pygame
import pygame.freetype
import pygame.gfxdraw
import pygame.locals
from glitchygames.engine import GameEngine
from glitchygames.sprites import BitmappySprite
from glitchygames.scenes import Scene
LOG = logging.getLogger('game')
LOG.setLevel(lo... |
# Copyright 2021 Toyota Research Institute. All rights reserved.
import numpy as np
from camviz.objects.object import Object
class BBox2D(Object):
"""
Bounding Box 2D draw class
Parameters
----------
points : np.array
List of points for the bounding box dimension (left, top, right, bot... |
# --------------
# Code starts here
class_1=['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio']
class_2=['Hilary Mason','Carla Gentry','Corinna Cortes']
new_class=class_1+class_2
print(new_class)
new_class.append('Peter Warden')
print(new_class)
new_class.remove('Carla Gentry')
print(new_class)
# Code... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
# Export this package's modules as members:
from .default_kms_key import *
from .encryption_by_default import *
from .get_default_kms_k... |
import cv2
def main():
#cv2.namedWindow('show',0)
#cv2.resizeWindow('show',640,360)
vc = cv2.VideoCapture(0) #웹캠 읽기
#vc = cv2.VideoCapture('./images/video2.mp4') #원하는 동영상을 읽기
vlen = int(vc.get(cv2.CAP_PROP_FRAME_COUNT)) #동영상이 갖고 있는 정보를 vc의 get() 함수로 읽기
print (vlen) # 웹캠은 video length 가 0 입... |
from .awd_lstm import *
from .transformer import *
__all__ = [*awd_lstm.__all__, *transformer.__all__]
|
from django.test import TestCase
from django.db import models
from django.core import mail
from django.contrib.auth import get_user_model
from ..models import Blog, Post, Subscription, Feed
class BlogModelTest(TestCase):
fixtures = ['initial_data.json']
def test_author_label(self):
blog = Blog.objec... |
class UserResourceMixin(object):
"""Methods for managing User resources."""
def create_user(self, **attributes):
"""Create a user.
>>> user = yola.create_user(
name='John',
surname='Smith',
email='johnsmith@example.com',
partner_id='WL_PARTNER_ID... |
import pickle
import sys
import time
import numpy as np
import torch
from fvcore.nn import FlopCountAnalysis
import xnas.core.config as config
import xnas.logger.logging as logging
from xnas.core.config import cfg
from xnas.core.builder import setup_env, space_builder, optimizer_builder
import xnas.algorithms.RMINAS.... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 5 13:03:17 2017
@author: mschull
"""
from __future__ import division, print_function, absolute_import
__author__ = 'jwely'
__all__ = ["landsat_metadata"]
# standard imports
import os.path
import numpy as np
import logging
from .utils import Raste... |
'''
Copyright (c) 2019, Ameer Haj Ali (UC Berkeley), and Intel Corporation
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
... |
infile=open('alienin.txt','r')
n,w=map(int,infile.readline().split())
list1=[]
for i in range(n):
p=int(infile.readline())
list1.append(p)
i,j=0,0
index=0
currentp=0
answer=0
while i<n:
while index<w and j<n:
index=(list1[j]-list1[i])
if index<w:
currentp+=1
... |
import json
from player_stats_url import stats_url, top_50_url
class PriceData:
def __init__(self, web_object):
print('Getting player price change data...')
self.web_object = web_object
self.price_data_url = self.find_price_data_url()
self.player_price_data = self.get_player_price... |
# Copyright 2014 PerfKitBenchmarker Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
class Skier:
def __init__(self, length, age, style):
self.length = length
self.age = age
self.style = style
classic = 'classic'
freestyle = 'freestyle'
_MAX_SUPPORTED_CLASSIC_SKI_LENGTH = 207
def calculate_ski_length(skier):
if skier.age <= 4:
return _calculate_baby_sk... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from yandex.cloud.cdn.v1 import origin_pb2 as yandex_dot_cloud_dot_cdn_dot_v1_dot_origin__pb2
from yandex.cloud.cdn.v1 import origin_service_pb2 as yandex_dot_cl... |
# 2021 June 4 14:44
# The solution is based on a rather magical algorithm called:
# Reservoir Sampling
# Naturally, we'd think of traversing over the entire linked-list, and get to
# know the enire length. Random sample and then traverse again to get the
# element. Or else store the elements in a list. But these mak... |
from .inlined_async import Async
def add(x, y):
return x+y
def test():
r = yield Async(add, (2, 3))
print(r)
r = yield Async(add, ('youm3sh'))
print(r)
for n in range(10):
r = yield Async(add, (n, n))
print(r)
# My work done now deploy it Manish
print('Goodbye')
|
"""
=============
Маршрутизация
=============
Модуль routing отвечает за маршрутизацию запросов от пользователя в приложении.
Маршруты разбиты на файлы по функциям:
fakeDataRoutes - генерация фейковых данных
plansRoutes - работа с планами
profileRoutes - работа с профилями
registrationRoutes - авторизац... |
#!/usr/bin/env python3
# This program plots a three dimensional graph representing a runner's
# performance vs time and length of run. Input is an activity file downloaded
# from connect.garmin.com.
# FIXME: Runs.load() excludes runs whose distance and pace fall outside
# a given range. See "Exclude outliers" comment b... |
from django.shortcuts import render
import pyrebase
# Create your views here.
firebaseConfig = {
"apiKey": "AIzaSyDEwWVDdZlXARcUrLvgEfn-goXpgpKf1nU",
"authDomain": "e-voting-f8fd3.firebaseapp.com",
"databaseURL": "https://e-voting-f8fd3-default-rtdb.asia-southeast1.firebasedatabase.app",
"projectId": "e-voting... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.