text stringlengths 2 999k |
|---|
# coding: utf-8
"""
OpenAPI Petstore
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
"""
... |
from random import choices
from string import ascii_uppercase, digits
class Robot:
def __init__(self):
# When robots come off the factory floor, they have no name.
self._name = None
self._past_names = set()
@property
def name(self):
if self._name is None:
while... |
from django.contrib import admin
from .models import User, Exercise, Log, Set, Muscle, Routine
# Register your models here.
admin.site.register(User)
admin.site.register(Exercise)
admin.site.register(Log)
admin.site.register(Set)
admin.site.register(Muscle)
admin.site.register(Routine) |
from pydantic import BaseModel
from pydantic.fields import Field
from pydantic.networks import EmailStr
from typing import List, Optional
class User(BaseModel):
userID: int=Field(...)
name: Optional[str]
email: Optional[EmailStr]
username: str=Field(...)
password: str=Field(...)
listOfProjects:... |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# NOTICE FILE in the root directory of this source tree.
#
from logging import getLogger
import os
import torch
from .transformer import TransformerModel
logger = getLogger()
def che... |
# Dedicated to the public domain under CC0: https://creativecommons.org/publicdomain/zero/1.0/.
import inspect
import sys
from code import InteractiveInterpreter
from typing import ContextManager, List
from .io import errSL
from .typing import OptBaseExc, OptTraceback, OptTypeBaseExc
class Interpreter(InteractiveIn... |
from kivy.lang import Builder
from kivy.clock import Clock
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.carousel import Carousel
from kivy.uix.widget import Widget
from kivymd.theming import ThemableBehavior
from kivy.properties import NumericProperty, BooleanProperty, StringProperty, ListProperty
from kivy.... |
# coding: utf-8
"""
FlashArray REST API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 2.6
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re
import six
import typing
from .... |
#!/usr/bin/env python
import yaml # https://pyyaml.org/wiki/PyYAMLDocumentation
from deepdiff import DeepDiff # https://pypi.org/project/deepdiff/
import json
import os
import re
from pprint import pprint
import shutil
dns_1123_regex = re.compile('[a-z0-9]([-a-z0-9]*[a-z0-9])?')
def generate_filename(crd_diction... |
import os
import torch
import torch.distributed.autograd as dist_autograd
import torch.distributed.rpc as rpc
import torch.multiprocessing as mp
import torch.optim as optim
from torch.distributed.optim import DistributedOptimizer
import rnn
def _run_trainer():
r"""
The trainer creates a distributed RNNModel... |
# -*- coding: utf-8 -*-
"""Imaginary Interferometers."""
__author__ = "Aman Chokshi"
__date__ = "2021-06-13"
__cite__ = "https://github.com/amanchokshi"
import numpy as np
from numba import njit, prange
from scipy.constants import c
def read_layout(layout_path=None):
"""Read array layout from txt file.
An... |
#################################################################################################################
def make_patient_data(data):
first_visit = min(data.visit_date)
time_follow_up = data.visit_date - first_visit
time_follow_up = time_follow_up.tolist()
data = data.sort_values('visit_date' ... |
from setuptools import setup, find_packages
import os
# import sys
try: # for pip >=12
from pip._internal.req import parse_requirements
try:
from pip._internal import download
except ImportError: # for pip >= 20
from pip._internal.network import session as download
except ImportError: # ... |
import json
import yaml
import requests
import xml.etree.ElementTree as ET
VERSION = '2.2'
ENDPOINT_SALES = 'https://reportingitc-reporter.apple.com/reportservice/sales/v1'
ENDPOINT_FINANCE = 'https://reportingitc-reporter.apple.com/reportservice/finance/v1'
CONFIG_LOCATION = 'config.yaml'
class Reporter:
def __... |
#!/usr/bin/env python3
# Copyright (c) 2014-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Run regression test suite.
This module calls down into individual test cases via subprocess. It will
f... |
"""Vera tests."""
from unittest.mock import MagicMock
from pyvera import CATEGORY_CURTAIN, VeraCurtain
from homeassistant.core import HomeAssistant
from .common import ComponentFactory
async def test_cover(
hass: HomeAssistant, vera_component_factory: ComponentFactory
) -> None:
"""Test function."""
ve... |
from preprocessing import EnglishCorpus
from sumy.parsers.plaintext import PlaintextParser
from sumy.nlp.tokenizers import Tokenizer
from sumy.utils import get_stop_words
from sumy.summarizers.lex_rank import LexRankSummarizer
def summarize_sentences(sentences:str, language="english") -> list:
# Preparation sente... |
# Copyright 2014 ETH Zurich
# Copyright 2018 ETH Zurich, Anapaya Systems
#
# 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 b... |
# This file is Copyright 2003, 2006, 2007, 2009 Dean Hall.
#
# This file is part of the Python-on-a-Chip program.
# Python-on-a-Chip is free software: you can redistribute it and/or modify
# it under the terms of the GNU LESSER GENERAL PUBLIC LICENSE Version 2.1.
#
# Python-on-a-Chip is distributed in the hope that it ... |
from random import randint
import pygame
from time import sleep
from settings import *
import os
# from gameScreen import tilesHeight,tilesWide,width,height
class snakeEnemy:
def __init__(self, x, y, length):
image = pygame.image.load(os.path.join('assets', 'body.png'))
self.image = pygame.transfo... |
from .RayTracing import * |
# Copyright 2013 Locaweb.
# 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... |
import gym
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import torch
from gym import error, spaces, utils
from gym.spaces import Discrete, Box
from gym.utils import seeding
#from stable_baselines.common.env_checker import check_env
pathToGroundTruthMap = "./gridWorld_16x16.csv"
device = "cud... |
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import torchvision.models as models
from torch.autograd import Variable
import numpy as np
from model.utils.config import cfg
from model.rpn.rpn import _RPN
from model.roi_pooling.modules.roi_pool import... |
"""
Truncation.
Example usage
-------------
Simple distribution to start with::
>>> distribution = chaospy.Normal(0, 1)
>>> distribution.inv([0.9, 0.99, 0.999]).round(4)
array([1.2816, 2.3263, 3.0902])
Same distribution, but with a right-side truncation::
>>> right_trunc = chaospy.Trunc(chaospy.Nor... |
import time
import numpy as np
import scipy.io as sio
import h5py
from sklearn.datasets import load_svmlight_file
from sklearn.cluster import KMeans
print("reading")
f = h5py.File('/code/BIDMach/data/MNIST8M/all.mat','r')
t0 = time.time()
data = f.get('/all') # Get a certain dataset
X = np.array(data)
t1 = time.tim... |
from .city import City
class NewOrleans(City):
BASE_NAME = 'NewOrleans'
DATE_FORMAT = '%m/%d/%Y %H:%M:%S %p'
COLUMN_TRANSFORMS = {
'TimeArrive' : 'date_time',
'TimeCreate' : 'date_time',
'TimeClosed' : 'date_time',
}
USE_YEARS = [2014,2015,2016,2017,2018]
COL... |
import json
import pytest
from django.urls import reverse
@pytest.mark.parametrize(
"search,results,orga_results",
(("a", 0, 0), ("aa", 0, 0), ("aaa", 0, 0), ("Jane S", 1, 0),),
)
@pytest.mark.django_db
def test_user_typeahead(
orga_client, event, speaker, other_orga_user, search, results, orga_results
)... |
# -*- coding:utf-8 -*-
# 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, software
... |
from .esba_test import Agent, Model, Deep_Evolution_Strategy, load_model
|
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 28 13:39:54 2020
@author: Zeyu
"""
from data_gen import raw_data_checkout
# import numpy as np
# import matplotlib.pyplot as plt
import serial
import time
import pandas as pd
import seaborn as sns
import argparse
import os
COLUMNS = ['col',
'row1','row2','row... |
import io
import qrcode
from bit import PrivateKey
def make_keys():
key = PrivateKey()
code = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_M,
box_size=10,
border=4
)
code.add_data(f'bitcoin:{key.address}')
code.make(fit=True)
img = ... |
#!/usr/bin/env python3
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test multiple rpc user config option rpcauth
#
from test_framework.test_framework import BitcoinTest... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-01-11 22:05
from __future__ import unicode_literals
from django.db import migrations, models
import wagtail.core.blocks
import wagtail.core.fields
import wagtail.documents.blocks
import wagtail.images.blocks
class Migration(migrations.Migration):
depe... |
# Auto generated by generator.py. Delete this line if you make modification.
from scrapy.spiders import Rule
from scrapy.linkextractors import LinkExtractor
XPATH = {
'name' : "//div[@class='product-info']/form/h1[@class='mainbox-title']",
'price' : "//p[@class='actual-price']/span/span/span[1]",
'category... |
"""
Test that a variable watchpoint should only hit when in scope.
"""
from __future__ import print_function
import unittest2
import lldb
from lldbsuite.test.lldbtest import *
import lldbsuite.test.lldbutil as lldbutil
from lldbsuite.test.decorators import *
class WatchedVariableHitWhenInScopeTestCase(TestBase):
... |
# 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, software
# d... |
from linalg.matrices.square_matrix import SquareMatrix
from linalg.base.any_vector import AnyVector
from abc import ABC
from dataclasses import dataclass
__all__ = ['AnySystem']
@dataclass(frozen=True)
class AnySystem(ABC):
matrix: SquareMatrix
vector: AnyVector
@property
def n(self):
retur... |
from package_control import sys_path
sys_path.add_dependency(u'pygments')
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging as logging_
import sys
from typing import Optional
def init_logging(level: int = logging_.INFO, logger: Optional[logging_.Logg... |
import torch.nn as nn
import torch.utils.checkpoint as cp
from mmcv.cnn import (build_activation_layer, build_conv_layer,
build_norm_layer, constant_init, kaiming_init)
from mmcv.runner import load_checkpoint
from mmcv.utils.parrots_wrapper import _BatchNorm
from mmedit.utils import get_root_logg... |
"""Tools for generating QR codes. This module depends on the qrcode python library."""
import base64
from io import BytesIO
import xml.etree.ElementTree as ET
from django.utils.encoding import force_text
from django.utils.html import escape
from django.utils.safestring import mark_safe
from qr_code.qrcode.constants... |
from io import StringIO
from tempfile import mkstemp
import json
import unittest
import os
from molotov.util import resolve, expand_options, OptionError, set_var, get_var, _VARS
_HERE = os.path.dirname(__file__)
config = os.path.join(_HERE, "..", "..", "molotov.json")
class Args:
pass
class TestUtil(unittest.T... |
import time
import datetime
import numpy as np
import matplotlib.pyplot as plt
from flask import Flask, request, send_file, abort
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from hpcpm.api import log
from hpcpm.api.helpers.database import database
... |
"""
This file offers the methods to automatically retrieve the graph Novispirillum itersonii.
The graph is automatically retrieved from the STRING repository.
References
---------------------
Please cite the following if you use the data:
```bib
@article{szklarczyk2019string,
title={STRING v11: protein--protei... |
import datetime as dt
from airflow import DAG
from airflow.utils.trigger_rule import TriggerRule
import airflow.utils
from airflow.contrib.operators.kubernetes_pod_operator import KubernetesPodOperator
# from airflow.operators.python_operator import BranchPythonOperator
# from airflow.operators.dummy_operator import... |
import argparse
from pathlib import Path
from news_tls import utils, data, datewise, clust, summarizers, plugin
from pprint import pprint
from pymongo import MongoClient
import time
CONN = MongoClient("localhost")
DB = CONN["news-tls"]
COLLECTION = DB["log"]
def stats_and_save(timeline, args, topic):
taxo_distan... |
# coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
# -*- coding: utf-8 -*-
# Copyright 2013 Google Inc. 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 require... |
from .Auto_image_detector import Detector_single_image
__all__ = [
'Detector_single_image'
] |
#! /usr/bin/env python3
# -*- coding:utf8 -*-
#
# air.py
#
# This file is part of pyplanes, a software distributed under the MIT license.
# For any question, please contact mathieu@matael.org.
#
# Copyright (c) 2018 The pyplanes authors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# ... |
# -*- coding: utf-8 -*-
"""
py2/py3 compatibility.
compat.py
(c) Will Roberts 23 June, 2017
"""
from __future__ import absolute_import
import sys
PY2 = int(sys.version[0]) == 2
if PY2:
text_type = unicode # noqa
binary_type = str
string_types = (str, unicode) # noqa
unicode = unicode # noqa
... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 05 12:06:04 2016
@author: james
"""
import logging
import time
from datetime import datetime, timedelta
from fxprime import scripts
from fxprime import executor
from fxprime import settings
from fxprime import oandapy
class MyStreamer():
'''Finds the... |
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import tensorflow.contrib.slim as slim
flags = tf.app.flags
FLAGS = flags.FLAGS
def mynet(input, reuse=False):
with tf.name_scope("model"):
with tf.variable_scope("conv1") as scope:
net = tf.contrib.layers.conv2d(input, 32, [7, 7], activ... |
from latex2sympy import process_sympy
from sympy import *
import sys
import hashlib
import time
sys.path.append("..")
M = Matrix([[1, 2], [3, 4]])
v = Matrix([1, 2])
# sub settings
sub_settings_symbols = {}
sub_settings_symbols[Symbol('M' + hashlib.md5('M'.encode()).hexdigest(), real=True)] = M
sub_settings_symbols... |
#! /usr/local/bin/python3
# -*- coding: utf-8 -*-
import code_stat_collector
import sys
if __name__ == '__main__':
sys.exit(code_stat_collector.main()) |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------
# stm/configuration.py
#
# Holds configuration values.
# ----------------------------------------------------------------
# copyright (c) 2015 - Domen Ipavec
# Distributed under The MIT License, see LICENS... |
"""Config flow for Entidade Reguladora dos Serviços Energéticos integration."""
import logging
import homeassistant.helpers.config_validation as cv
import voluptuous as vol
from pyerse.comercializador import Comercializador
from pyerse.ciclos import Ciclo_Diario
from homeassistant.components.utility_meter.const impor... |
from __future__ import unicode_literals
from moto.core.responses import BaseResponse
from .models import autoscaling_backends
class AutoScalingResponse(BaseResponse):
@property
def autoscaling_backend(self):
return autoscaling_backends[self.region]
def create_launch_configuration(self):
... |
"""
face detection using vilola & jones method
run the detect_front_face function to see example
*** change the paths of resources according to your file location.
"""
import cv2
def detect_front_face(cascade_path, img_path):
faceCascade = cv2.CascadeClassifier(cascade_path)
img = cv2.imread(img_path)
i... |
import os
import re
import textwrap
import jinja2
from nmigen import tracer
from nmigen_soc.memory import MemoryMap
from nmigen.build.run import *
from .. import __version__, software
from ..periph import Peripheral
__all__ = ["socproperty", "SoC", "ConfigBuilder"]
def socproperty(cls, src_loc_at=0):
name =... |
from abc import ABCMeta, abstractmethod
class SemiAlgebraicObject(metaclass=ABCMeta):
@abstractmethod
def __repr__(self):
pass
@abstractmethod
def __eq__(self):
pass
@abstractmethod
def __mul__(self):
pass
@abstractmethod
def __pow__(self):
... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: aiExchangeMessages.proto
import sys
_b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x: x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import re... |
# We can improve this code. What if there are two characters
# that occur the same number of times? We would certainly want
# to know this:
myParagraph = "Hi, my name is Paul Vierthaler"
# Create a variable to store the most common character. Only
# this time, use a list:
mostCommonCharacter = []
mCCFreq = 0
for c... |
'''
import requests
r = requests.get('https://api.github.com/events')
print (r.text)
'''
import socket
import datetime
from flask import Flask
APP = Flask(__name__)
@APP.route("/")
def hello():
'''
hello
'''
return "Hello World! from " + socket.gethostname() + " @ " + str(datetime.datetime.now(... |
from django.conf import settings
from .. import register, Tags, Warning
W003 = Warning(
"You don't appear to be using Django's built-in "
"cross-site request forgery protection via the middleware "
"('django.middleware.csrf.CsrfViewMiddleware' is not in your "
"MIDDLEWARE_CLASSES). Enabling the middl... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright 2011-2020, Nigel Small
#
# 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
#
# Unle... |
#!/usr/bin/env python
# Copyright 2016 Rackspace Hosting Inc.
# 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/LICENS... |
import copy
import numpy as np
import scipy.linalg
import scipy.stats
import torch
from matplotlib import pyplot as plt
# from ray import tune
# from ray.tune.suggest import ConcurrencyLimiter
# from ray.tune.suggest.hyperopt import HyperOptSearch
# import tqdm
from torch import nn
from torch.nn import functional as ... |
import os
import time
import math
from pymol import cmd
from openbabel import openbabel
from urllib.error import HTTPError
from urllib.request import urlopen
from plip.basic import config
from plip.structure.preparation import PDBComplex
from plip.visualization.pymol import PyMOLVisualizer
__all__ = ['AttrDict', 'draw... |
# (C) Datadog, Inc. 2018-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import json
import logging
import os
import sys
from collections import defaultdict
from datetime import datetime
import mock
import pytest
import requests
from six import iteritems
from datadog_checks.b... |
"""mongoexport implemented as a python module.
'username' and 'password' for accessing target mongodb
can be stored as environment variables or in python
keyring.
Stored as environment variables:
export MONGOEXPORT_USERNAME=*****
export MONGOEXPORT_PASSWORD=*****
or in python keyring:
$ keyring set mongoexport use... |
# coding=utf-8
#! ./kt/bin/python
from flask_script import Manager, Shell
from flask_migrate import Migrate, MigrateCommand
from app import create_app, db
app = create_app(config_name='default')
migrate = Migrate(app, db)
def _make_context():
return dict(app=app, db=db)
manager = Manager(app)
manager.add_comman... |
#
# 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, software
# ... |
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from django_countries.fields import CountryField
from accounts.models import Proprietaire
# 1 ###################################... |
from . import simple
from . import theanode
from . import embedding
from . import combine
from . import containers
from . import activations
from . import upsample
from . import conv
from . import updates
from . import costs
from . import stochastic
from . import scan
from . import composite
from . import hyperparamete... |
"""Treadmill REST auth plugins."""
|
import six
import numpy as np
import flops_counter
import flops_counter.nn.functional as F
import flops_counter.nn as nn
class Conv_Block(nn.Module):
def __init__(self, in_channels, out_channels, kernel_sizes, strides=None, paddings=None, with_pool=True):
super(Conv_Block, self).__init__()
assert ... |
from setuptools import find_packages, setup
version = "1.16.0"
with open('README.rst') as file:
long_description = file.read()
setup(name='cloudinary',
version=version,
description="Python and Django SDK for Cloudinary",
long_description=long_description,
keywords='cloudinary image video ... |
"""
Testing that skewed axes properly work
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import itertools
import matplotlib.pyplot as plt
from matplotlib.testing.decorators import image_comparison
from matplotlib.axes import Axes
import matplotlib.tr... |
# django imports
from django.contrib.auth.decorators import permission_required
from django.http import HttpResponse
from django.template.loader import render_to_string
from django.template import RequestContext
from django.utils import simplejson
from django.utils.translation import ugettext_lazy as _
# lfs imports
f... |
import logging
from ..stubs.format_parser import FormatParser
l = logging.getLogger('angr.procedures.posix.syslog')
l.setLevel('INFO')
class syslog(FormatParser):
def run(self, priority):
fmt = self._parse(1)
formatted = fmt.replace(2, self.arg)
l.info("Syslog priority %s: %s", priority, ... |
"""ARM/NEON assembly emitter.
Used by code generators to produce ARM assembly with NEON simd code.
Provides tools for easier register management: named register variable
allocation/deallocation, and offers a more procedural/structured approach
to generating assembly.
TODO: right now neon emitter prints out assembly i... |
class DataFrame:
... |
import networkx as nx
import matplotlib.pyplot as plt
from classes.bfs import BfsTraverser
G = nx.Graph()
nodes = ["Karen", "J6", "Gitaru", "J1", "J4", "J7"]
G.add_nodes_from(nodes)
G.nodes() # confirm nodes
# Add Edges and their weights
G.add_edge("Karen", "J1", weight="2.8")
G.add_edge("Karen", "J6", we... |
# !/usr/bin/python
# -*- coding: utf-8 -*-
"""
@Desc : 最大约数 -- 不存在平方数的约数
"""
"""
暴力法
时间复杂度 O(n^1/2)
"""
import math
T = int(input())
for _ in range(T):
n = int(input())
a = int(math.sqrt(n))
for x in range(2, a + 1):
while n % (x * x) == 0:
n //= x
print(n)
|
# Copyright 2018 The TensorFlow 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 applica... |
# Copyright (c) 2010 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the ... |
import asyncio
import json
import logging
import re
from datetime import date, datetime, timedelta
from types import MappingProxyType
from typing import Optional, Any, Dict, Tuple, Union, List, Set, Mapping
import aiohttp
from dateutil.tz import gettz, tz
_LOGGER = logging.getLogger(__name__)
HistoryEntryDataType = ... |
"""Resource routes for the API."""
from api.endpoints.songs import (AverageDifficultyResource,
RatingMetricsResource, SongRatingResource,
SongSearchResource, SongsListResource)
def resource_routes(api):
"""Define the routes for the API."""
api.... |
import h5py
import xml.etree.ElementTree as et
from afqmctools.wavefunction.mol import read_qmcpack_wfn
def write_xml_input(qmc_in, hamil_file, wfn_file, id_name='qmc', series=0,
rng_seed=None, options=None):
"""Generate template input file from hamiltonian and wavefunction.
Parameters
... |
import pygame as pg
from collections import defaultdict
def schlage(von, stein):
schläge = defaultdict(list)
for n in richtungen[stein]:
über = False
for i in range(1, abs(stein)+1):
über = von + n * i
zu = über + n
if (zu not in brett or über not in brett) or (brett[zu] != 0 and brett[ü... |
# Generated by Django 3.2.7 on 2021-09-30 07:50
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_m... |
from __future__ import annotations
import threading
import queue
from core.service import BaseService, ServiceEvent
from .app_settings import GEOSERVER_WINDOW
from .models import ShipGeometries
import logging
from logformat import StyleAdapter
logger = StyleAdapter(logging.getLogger(__name__))
class GeoserverServi... |
__all__ = ["Reloader"]
from .api import Reloader
|
#!/usr/bin/env python3
import os
# import glob
import re
import shutil
def download_glass(product, h, v, years, output):
# lf = "url.txt"
remoteRoot = "http://www.glass.umd.edu/{PP}/MODIS/1km".format(PP=product)
rpathPattern = "{REMOTE_ROOT}/{YYYY}/"
lpathPattern = "{LOCAL_ROOT}/h{HH}v{VV}/{YYYY}"
... |
from typing import Any, Optional
import models
import schemas
from core.auth import get_password_hash, verify_password
from crud.base import CRUDBase
from sqlalchemy.orm import Session
class CRUDUser(CRUDBase[models.User, schemas.UserCreate, schemas.UserUpdate, Any]):
def get_by_email(self, db: Session... |
#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from typing import IO
from typing import Iterator
from absl.testing import absltest
import mock
from grr_response_core.lib import parsers
from grr_response_core.lib import rdfvalue
fro... |
from django.db import models
from django.conf import settings
# Create your models here.
class library_profile(models.Model):
username = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
library_id = models.CharField(max_length=50)
library_password = models.CharField(max_length=50)
... |
from pymaze.gui import App
if __name__ == '__main__':
app = App()
app.run() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.