content stringlengths 5 1.05M |
|---|
# tests/test_api.py
import os
import unittest
from datetime import date
from project import app, db
from project._config import basedir
from project.models import Task
TEST_DB = 'test.db'
class APITests(unittest.TestCase):
############################
#### setup and teardown ####
###################... |
import discord
import random
from discord import client
token =""
intents = discord.Intents.all()
client = discord.Client(intents=intents)
messages = ["https://media.discordapp.net/attachments/922478840356425758/926507839982305340/20211220_162425.jpg", "https://media.discordapp.net/attachments/922478840356... |
from flask import Flask
app = Flask(__name__)
from DogBreedsApp import routes
|
import arcpy
import pandas as pd
import openpyxl
import xlwings as xw
#
data = r"\\arcserver-svr\D\PPA_v2_SVR\PPA_V2.gdb\sacog_region"
data_layer = "datalayer"
file = r"\\arcserver-svr\D\PPA_v2_SVR\PPA2\TestingScript.py"
if(__name__=='__main__'):
t = arcpy.GetParameterAsText(0)
if(arcpy.Exists(data_layer)):... |
from hypnospy import Wearable
from hypnospy import Experiment
import numpy as np
import warnings
class NonWearingDetector(object):
def __init__(self, input: {Wearable, Experiment}):
if input is None:
raise ValueError("Invalid value for input.")
elif type(input) is Wearable:
... |
import os
import typing
def user_shell():
return os.environ['SHELL']
class ExpressionConstructor:
"""Class for constructing shell expression by project configuration."""
def __init__(self, project_name: str, project_conf: dict):
self.project_name = project_name
self.project_conf = proje... |
from experimentum.Storage.SQLAlchemy import Platform
from sqlalchemy import Column, Text, ForeignKey, create_engine
class TestPlatform(object):
@classmethod
def setup_class(cls):
""" init platform """
cls.engine = create_engine('sqlite://')
def _setup_platform(self, mocker):
self.... |
def Try_Glossary(Item,Glossary,Header):
if Item in Glossary.keys():
return Header.append(Glossary[Item])
else:
print(Item)
return Header
def NFL_Shorthand_to_Headers(stats_type,Col_Cats,Col_Names):
Stats_Type = stats_type.upper()
Repeats = []
Header = []
... |
#! usr/bin/python3.6
"""
Module initially auto generated using V5Automation files from CATIA V5 R28 on 2020-06-11 12:40:47.360445
.. warning::
The notes denoted "CAA V5 Visual Basic Help" are to be used as reference only.
They are there as a guide as to how the visual basic / catscript function... |
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
from django.conf.urls import url, patterns, include
from cntapp.views import views, custom, stats
custom_urls = patterns('',
url(r'^$', custom.index, name="index"),
url(r'^login/$', custom.login_page, name="login"),
url(r'^logout/$', custom.logout_... |
from setuptools import setup
from etcli import __version__
with open('README.rst') as f:
readme = f.read()
setup(
name='et-cli',
version=__version__,
packages=['etcli'],
description='ExactTarget CLI Tool',
long_description=readme,
url='https://github.com/tzmfreedom/et-cli',
author='mak... |
# -*- coding: utf-8 -*-
from __future__ import division, print_function, absolute_import
import io
import numpy as np
import glob
from munch import Munch
from collections import OrderedDict
from datetime import datetime
def kpfm_data(fname):
fh = io.open(fname, 'r')
header_lines = [fh.readline()[:-1] for i in... |
from keras.layers import *
from keras import backend as K, initializers, activations
import numpy as np
class AccumulatorCell(Layer):
def __init__(self, locs, channels, units=None, div=None, max_output=256, **kwargs):
self.locs = locs
self.units = units
if self.units is None:
... |
import re
def tuple_to_decimal(gps_tuple):
'''
The definition of the tuple is
degrees, minutes, seconds
Each one has a number and a scale, e.g. seconds can be
(3456, 1000)
meaning it needs to be divided by that number.
'''
degrees_info, minutes_info, seconds_info = gps_tuple
d... |
from timm.models import ByoModelCfg, ByoBlockCfg, ByobNet
from ._base import EncoderMixin
import torch.nn as nn
class GERNetEncoder(ByobNet, EncoderMixin):
def __init__(self, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._depth = depth
self._out_channels = out_channels... |
# Generated by Django 3.2.5 on 2021-08-05 22:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0009_auto_20210805_0242'),
]
operations = [
migrations.AlterModelManagers(
name='user',
managers=[
... |
from typing import Any, Dict, List, Optional, Tuple
from django.contrib import admin, messages
from django.contrib.admin import ModelAdmin
from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin
from django.contrib.auth.tokens import default_token_generator
from django.db.models.query import QuerySet
from d... |
##Patterns: W0404
##Info: W0404
from time import sleep, sleep
##Info: W0404
from lala import missing, missing
import missing1
##Info: W0404
import missing1
|
from abc import ABC, abstractmethod
from functools import total_ordering
from typing import List
@total_ordering
class Peer(ABC):
"""
Class representing peer information.
Attributes
----------
public_key : bytes
The base64 representation of a WireGuard public key for this peer. (read-only... |
from emmet.core.mpid import MPID
from maggma.api.query_operator import QueryOperator
from maggma.api.utils import STORE_PARAMS
from fastapi import Path
class PhononImgQuery(QueryOperator):
"""
Method to generate a query on phonon image data.
"""
def query(
self,
task_id: MPID = Path... |
# Copyright 2018 DataStax, Inc.
#
# 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 writin... |
from .capitol_words import CapitolWords
from .imdb import IMDB
from .oxford_text_archive import OxfordTextArchive
from .reddit_comments import RedditComments
from .supreme_court import SupremeCourt
from .wikimedia import Wikipedia, Wikinews
from .udhr import UDHR
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2011 andelf <andelf@gmail.com>
# Time-stamp: <2011-06-06 16:08:30 andelf>
#from distutils.core import setup
from setuptools import setup, find_packages
import os, sys
lib_path = os.path.join(os.path.dirname(__file__))
sys.path.insert(0, lib_path)
from qqweibo... |
import json
import os
import shutil
def make_if_dont_exist(folder_path, overwrite=False):
"""
creates a folder if it does not exists
input:
folder_path : relative path of the folder which needs to be created
over_write :(default: False) if True overwrite the existing folder
"""
if os.path.... |
#!/usr/bin/env python
"""
Example of URLS to use:
https://www.spamhaus.org/drop/drop.txt
https://check.torproject.org/exit-addresses
https://rules.emergingthreats.net/fwrules/emerging-Block-IPs.txt
https://zeustracker.abuse.ch/blocklist.php?download=ipblocklist
https://www.binarydefense.com/banlist.... |
# From: https://stackoverflow.com/a/39504463
# License: Creative Commons Attribution-Share Alike
# Copyright: Victor Moyseenko
import sys
import threading
import time
class Spinner:
running = False
busy = False
delay = 0.1
@staticmethod
def spinning_cursor():
while 1:
for cur... |
"""
This file contains important constants. Directories are relative to current master directory. Torcs installation folder
must be provided in 'install_directory.txt' file.
"""
import os
import platform
loc = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
prefix = os.path.dirname(os.path.dirn... |
# 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! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
from offpolicy.algorithms.maddpg.algorithm.MADDPGPolicy import MADDPGPolicy
class MATD3Policy(MADDPGPolicy):
def __init__(self, config, policy_config, train=True):
"""See parent class."""
super(MATD3Policy, self).__init__(config, policy_config, target_noise=config["args"].target_action_noise_std, t... |
from .bot import DGGBot
from .chat import DGGChat
from .event import EventType
from .message import Message, PrivateMessage, MuteMessage
|
import os
def make_ext(*name_parts):
''' retuns file name which each part is join by dot. '''
return os.extsep.join(str(part) for part in name_parts)
def datapath(*paths):
''' returns path from data directory to destination file. '''
return os.path.abspath(os.path.join(os.path.dirname(__file__),
... |
# -*- coding: utf-8 -*-
# !/usr/bin/env python
from tkinter import *
import random
import time
from time import gmtime, strftime
import zmq
import json
import queue
import threading
import pandas as pd
import numpy as np
import math
import matlab.engine
class Ball:
def __init__(self, canvas, color):
self... |
# -*- coding: utf-8 -*-
'''
Created on Mar 18, 2016
@author: fky
'''
import smtplib
if not 'SMTP_SSL' in smtplib.__all__:
print('''error: Server does not support SMTP-over-SSL. You could use STARTTLS instead. If SSL is needed, an upgrade to Python 2.6 on the server-side should do the trick.''')
print(sm... |
from django.db import models
# Create your models here.
class image_to_json(models.Model):
# id = models.AutoField(primary_key=True)
movie_image = models.FileField(upload_to='image/', default='image/default.png')
data = models.JSONField(default = {})
def __str__(self):
return self.id |
import tensorflow as tf
import os.path
from datetime import datetime
import numpy as np
import cma
from cma import bbobbenchmarks as bn
import gps
from gps import __file__ as gps_filepath
from gps.agent.lto.agent_cmaes import AgentCMAES
from gps.agent.lto.cmaes_world import CMAESWorld
from gps.algorithm.algorithm impo... |
# coding: utf-8
import os
from bookworm.utils import escape_html
from .base_renderer import TextRenderer
class PlainTextRenderer(TextRenderer):
"""Renders items to a text document."""
name = "text"
# Translators: written to output document when exporting a comment/highlight
display_name = _("Plain T... |
# encoding: utf-8
class Forbidden(Exception):
"""
登录会话或IP被屏蔽了
"""
pass |
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from . import config
SQLALCHEMY_DATABASE_URL = f"mysql+pymysql://{config.settings.DB_USER}:{config.settings.DB_PASS}@{config.settings.DB_HOST}:{config.settings.DB_PORT}/{config.settings.... |
import re
from typing import Optional, Set
from .parse_mypy import get_mypy_output
IMPORT_ERROR_RES = [
# "Skipping analyzing 'google.cloud': found module but no type hints or library stubs"
re.compile(
r"""
Skipping\sanalyzing\s
'(?P<module>.*?)'
:\sfound\smodule\sbut\sno\styp... |
import pandas as pd
pd.read_csv('combined_csv.csv', header=None).T.to_csv('rotated_csv.csv', header=False, index=False)
|
__all__ = ['HuyaExtractor', 'YoukuExtractor', 'TengxunExtractor'] |
"""
* orm.Base.py
*
* Copyright Synerty Pty Ltd 2013
*
* This software is proprietary, you are not free to copy
* or redistribute this code in any format.
*
* All rights to this software are reserved by
* Synerty Pty Ltd
*
"""
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.sc... |
#! /usr/bin/env python3.4
import tensorflow as tf
import numpy as np
import os
import time
import datetime
import data_helpers
from insqa_cnn import InsQACNN
import operator
import random
#print tf.__version__
# Parameters
# ==================================================
# Model Hyperparameters
tf.flags.DEFINE_... |
from functools import partial
import contextlib
import asyncio
import logging
import json
from aiohttp.web import WebSocketResponse, Response
from aiohttp import WSMsgType
logger = logging.getLogger('flamingo.server.jsonrpc')
class JsonRpc:
def __init__(self, server):
self.server = server
self.w... |
'''
TO RUN:
idl vs. legacy comparison: python -c "from simulate_survey import Legacy_vs_IDL;a=Legacy_vs_IDL(camera='decam',leg_dir='/global/cscratch1/sd/kaylanb/kaylan_Test',idl_dir='/global/cscratch1/sd/kaylanb/arjundey_Test')"
idl vs. legacy number star matches: python -c "from simulate_survey import sn_not_matched_b... |
# This file is part of the ISIS IBEX application.
# Copyright (C) 2012-2016 Science & Technology Facilities Council.
# All rights reserved.
#
# This program is distributed in the hope that it will be useful.
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License... |
src/
__init__.py
CaliforniaPublicSalaries.py
UpdateCatalog.py
|
"""Global pytest fixtures."""
import os
from pathlib import Path
from uuid import uuid4
import pytest
TESTS_FOLDER = Path(__file__).parent
ROOT_FOLDER = TESTS_FOLDER.parent
DOTENV_FILE = TESTS_FOLDER.joinpath(".env")
CONFIG_FILE = TESTS_FOLDER.joinpath("vig.config.json")
JSON_FOLDER = TESTS_FOLDER.joinpath("json")
CS... |
## import ####################################################################
import time
import pathlib
import appdirs
import toml
from PySide2 import QtWidgets
import WrightTools as wt
import attune
import yaqc
import yaqc_cmds.__main__
import yaqc_cmds.project.project_globals as g
import yaqc_cmds.project.wid... |
# 4.Which are the top 5 common job in Year 2014 and how much do they cost SFO ?
import pandas as pd
df=pd.read_csv(r'c:\\temp\\Salaries.csv')
temp_df=df.loc[:,['Year','JobTitle','TotalPayBenefits']]
selected_data=temp_df[temp_df['Year']==2014]
print selected_data.groupby('JobTitle')['TotalPayBenefits'].nlargest(5) |
"""Helper functions for fitting NFW concentration histories of individual halos."""
import warnings
import numpy as np
from jax import jit as jjit
from jax import numpy as jnp
from jax import value_and_grad, grad
from jax import vmap as jvmap
from jax.experimental import optimizers as jax_opt
from scipy.optimize import... |
from .reversible_edit import ReversibleEdit
import numpy as np
import torch
class ReversibleWarping(ReversibleEdit):
def forward(self, image):
return self.torch_warp(image)
def torch_warp(self, image, reverse=False):
pixels = np.asarray(image).transpose(2, 0, 1).copy()
device = torch.... |
import unittest
from data import city_visit as city_visit_
from router import city_visit_heap as city_visit_heap_
from router import city_visit_points_left
class MockDayVisitParameters(city_visit_.DayVisitParametersInterface):
def __init__(self, hash_key):
assert isinstance(hash_key, str)
self.hash_key ... |
from .. import Qsys
from ..components import OutputPitchWidget
from .. import Defaults
import numpy as np
from kivy.properties import NumericProperty
from kivy.properties import ListProperty
from kivy.properties import ObjectProperty
from kivy.properties import BooleanProperty
from kivy.properties import StringProperty... |
"""Start xvfb from Python."""
import time
import os
XVFB_INSTALL_NOTES = """Please install Xvfb with:
Debian
$ sudo apt install libgl1-mesa-glx xvfb
CentOS / RHL
$ sudo yum install libgl1-mesa-glx xvfb
"""
def start_xvfb(wait=3, window_size=None):
"""Start the virtual framebuffer Xvfb.
Parameters
---... |
__version__ = "0.59a1"
__version_info__ = tuple(__version__.split("."))
|
import dataclasses
@dataclasses.dataclass
class ClassBase:
a: str = None
b: int = 0
def print_content(self):
print(self.__dict__)
|
from naturalcolors.colorpalette import *
|
from flask import Flask, request, url_for
from twilio.twiml.voice_response import Redirect, VoiceResponse
from twilio.twiml.messaging_response import MessagingResponse
from twilio.rest import Client
from setttings import auth_token, account_sid, repNumber, twilioNumber
app = Flask(__name__)
# Global Variables
@app.... |
"""A zoo 'simulation'
Demonstrates the Observer and Observable classes from reactive.py
"""
import asyncio
import random
from .reactive import Observer, Observable
class AnimalEvent:
def __init__(self, source, action, value = ''):
self.source = source
self.action = action
self.value = ... |
from tqdm import tqdm
import os
import os
import matplotlib.pyplot as plt
import torch.nn as nn
from scipy.ndimage.filters import gaussian_filter1d
from torch.utils.data import TensorDataset, DataLoader
from tqdm import tqdm
from args import get_args
from utils.game_tracker import GameTracker
from utils.util_fns impo... |
# coding=utf-8
from __future__ import print_function
import os
import sys
import signal
import traceback
import logging
import time
import socket
import select
from six import b as bytes
from threading import Thread, Lock
from tantale.utils import load_backend
from tantale.input.check import Check
try:
from Qu... |
#!/usr/bin/python
"""
Author: Omar Santos @santosomar
version 1.0
This is a quick demonstration on how to use the scapy as a scanner
* Pre-requisite: scapy, prettytable, argparse
"""
from __future__ import print_function
import sys
import prettytable
import argparse
import logging
logging.getLogger("scapy.runtime").se... |
from flask import current_app as app
from app import err_logger
from core.exceptions import ValidationException
@app.errorhandler(ValidationException)
def handle_error(e):
err_logger.error(F"Validation error {e.message}")
return e.get_response()
|
def read(user_id):
return user_id + 1
|
import re
from logging import getLogger, StreamHandler, Formatter, DEBUG, FileHandler, ERROR, INFO
import bs4
pttr_num = re.compile('[0-9]+')
# loggerオブジェクトの宣言
def setup_logger(name, logfile='LOGFILENAME.txt'):
logger = getLogger(name)
logger.setLevel(DEBUG)
# create file handler which logs even DEBUG m... |
#!/usr/bin/env python
# coding: utf-8
# # Time Series Analysis and Forecasting with Prophet
#
# **Goal:**
#
# - Explore the data (ECDF, handle missing values etc).
# - Analysis per store type and correlational analysis of stores activity.
# - Perform extensive Time Series Analysis (seasonal decomposition, trends, ... |
from MEG import *
# domain
mesh =generate_mesh(Circle(Point(0., 0.), 1.), 80) # RectangleMesh(Point(0., 0.), Point(1., 1.), 80, 80)
freq = 8 * (2 * np.pi)
Lbd = 1.0
dim = 2
epsilon = Constant(1)
mu = Constant(1.0)
sigma = Constant(0.0000)
class MyFunctionExpression(UserExpression):
def eval(... |
class Python:
def __init__(self,pages):
self.pages = pages
def __add__(self,other):#here self means b1 and other means b2
return self.pages + other.pages
def __gt__(self,other):
return self.pages > other.pages
def __mul__(self,other):
return self.pages * ot... |
import requests, os, tkinter
from bs4 import BeautifulSoup
""" VersionScrapper class is doing the webscrapping and searching for
the latest version number of ValheimPlus.
"""
class VersionScrapper:
def scrap_version(self):
pass |
from django.shortcuts import render
from django.contrib.auth.models import User, Group
from rest_framework import status, viewsets, permissions
from rest_framework.decorators import api_view, renderer_classes
from rest_framework.renderers import TemplateHTMLRenderer, JSONRenderer
from rest_framework.response import Re... |
# -*- coding: utf-8 -*-
# Copyright: 2009 Nadia Alramli
# License: BSD
from progressbar import ProgressBar
import time
p = ProgressBar()
for i in range(101):
p.render(i, 'step %s' % i)
time.sleep(0.05)
p = ProgressBar('green', width=20, block='▣', empty='□')
for i in range(101):
p.render(i, 'step %s\nProc... |
#!/usr/bin/pyhton3
import sys
import csv
from collections import namedtuple
IncomeTaxQuickLookupItem = namedtuple(
'IncomeTaxQuickLookupItem',
['start_point', 'tax_rate', 'quick_subtractor']
)
INCOME_TAX_START_POINT = 3500
INCOME_TAX_QUICK_LOOKUP_TABLE = [
IncomeTaxQuickLookupItem(80000, 0... |
import csv
import shutil
import datetime
ORIGINAL = "rec-center-hourly.csv"
BACKUP = "rec-center-hourly-backup.csv"
DATE_FORMAT = "%m/%d/%y %H:%M"
def isTuesday(date):
return date.weekday() is 1
def withinOctober(date):
return datetime.datetime(2010, 10, 1) <= date < datetime.datetime(2010, 11, 1)
def run(... |
import random
import numpy as np
import torch
from torch.autograd import Variable
layers_alpha = [
("/", 2, 32),
("/", 2, 64),
("/", 2, 128),
("/", 2, 256),
]
layers_alpha_debug = [
("/", 2, 1),
("/", 2, 1),
("/", 2, 1),
("/", 2, 1),
]
layers_cnn_omega = [("*", s, channels) for (c, s,... |
# -*- coding: utf-8 -*-
"""
requests.py - Implements /request & /fill
"""
# Libs
import discord
from discord.ext import commands
class RequestCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
# .request
@commands.command(name='request', aliases=['req'])
async def new_request(self, ... |
import tensorflow as tf
from tensorflow.contrib import rnn
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"]="2"
class PointerLayer():
def __init__(self, args, inputs, scope):
print("building pointer layer", scope)
batch_size = args.batch_size
vocab_size = args.vocab_size
hidden_size = ... |
# -*- coding: utf-8 -*-
import pytest
from vdirsyncer.metasync import MetaSyncConflict, metasync
from vdirsyncer.storage.memory import MemoryStorage
from . import blow_up
def test_irrelevant_status():
a = MemoryStorage()
b = MemoryStorage()
status = {'foo': 'bar'}
metasync(a, b, status, keys=())
... |
t = int(input())
answer = []
for a in range(t):
count1 = [0 for i in range(26)]
count2 = [0 for j in range(26)]
line1 = set(list(input()))
line2 = set(list(input()))
ans = False
for j in line1:
if(j in line2):
ans = True
break
if(ans):
answer.append("Y... |
from deca.gui.main import main
from multiprocessing import freeze_support
if __name__ == "__main__":
freeze_support()
vfs = main()
|
###########################################################################
#
# Copyright 2017 Google Inc.
#
# 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
#
# https://www.apache.org/... |
# Copyright 2017 Google Inc.
#
# 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, ... |
# 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... |
"""
This small snippet will open all the *.natvis files and concat them into a
single one to be able to use them in Visual Studio Code (for Mac for eg)
vscode-cpptools expects only one visualizerFile currently
"""
import xml.etree.ElementTree as ET
import glob as gb
OUT_FILENAME = 'all_concat.natvis'
def concat_all... |
from .act_base import ActBase
from .act_building import ActBuilding
from .act_expand import ActExpand
from .act_tech import ActTech
from .act_unit_once import ActUnitOnce
from .act_many import ActMany
from .act_unit import ActUnit
from .act_warp_unit import ActWarpUnit
from .act_zerg_morph import ActMorphBuilding
from ... |
"""Default paths and variables."""
import logging
import os
from pathlib import Path
from aop2db.constants import AOP_XML_DOWNLOAD
logger = logging.getLogger(__name__)
# Paths
HOME = str(Path.home())
PROJECT_NAME = "aop2db"
BASE_DIR = Path.home().joinpath(f".{PROJECT_NAME}")
AOP_DIR = BASE_DIR.joinpath("aop")
LOG_... |
import random
import os
import sys
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
from torch.utils.data import DataLoader
import numpy as np
from data_loader import GetDataset
from torchvision import datasets
from torchvision import transforms
from model import CNNModel
from te... |
from typing import Union, List, Tuple
import torch
from torch import nn
from transformers import (
PreTrainedTokenizer, PreTrainedTokenizerFast,
AutoConfig, AutoModel, AutoTokenizer
)
from transformers.models.albert.modeling_albert import (
AlbertEmbeddings, AlbertConfig, AlbertLayer
)
from .distributions... |
__version__ = "7.0.0-Beta"
|
from AccessControl import ClassSecurityInfo
from Products.ATContentTypes.content import schemata
from Products.Archetypes import atapi
from Products.Archetypes.ArchetypeTool import registerType
from Products.CMFCore import permissions
from Products.CMFCore.utils import getToolByName
from bika.lims.browser import Browse... |
"""
The help command. The basic idea is that help texts for commands
are best written by those that write the commands - the admins. So
command-help is all auto-loaded and searched from the current command
set. The normal, database-tied help system is used for collaborative
creation of other help topics such as RP help... |
def sSort(a_list):
for fill_slot in range(len(a_list) -1, 0, -1):
pos_of_max = 0
for location in range(1, fill_slot+1):
if a_list[location] > a_list[pos_of_max]:
pos_of_max = location
temp = a_list[fill_slot]
a_list[fill_slot] = a_list[pos_of_max]
... |
class Solution:
def __init__(self):
self.validPositions = []
def validatePosition(self, board, n, position) :
"""
Given a board and the position for the queen to be placed, returns if we can make this move or not
"""
# Primary Diagonal
x, y = len(board)-1, pos... |
import socket
from Message import Message
from rodFSM import compute_rod_linear
from FSMConstants import *
def main():
commands = {"robot_goal_rod_displacement_command":0, "robot_goal_rod_angle_command":0, "robot_2_rod_displacement_command":0, "robot_2_rod_angle_command":0, "robot_5_rod_displacement_command":0, "... |
import typing
from urllib.parse import urlparse, parse_qs
import ipywidgets as ipw
import traitlets
from aiidalab_optimade.exceptions import InputError
from aiidalab_optimade.logger import LOGGER
__all__ = ("StructureDropdown", "ResultsPageChooser")
class StructureDropdown(ipw.Dropdown):
"""Dropdown for showi... |
from datetime import date
from secret_keys import THE_CITY
class DiasUteis():
def __init__(self):
self.feriados_nacionais_2022 = [
date(2022, 1, 1), # Confraternização
date(2022, 2, 28), # Carnaval
date(2022, 3, 1), # Carnaval
date(2022, 3, 2), # quarta-... |
from . import BaseActor
from lib.utils.box_ops import box_cxcywh_to_xyxy, box_xywh_to_xyxy
import torch
from lib.utils.merge import get_qkv, merge_template_search
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.functional import l1_loss
class STARKLightningXtrtdistillActor(BaseActor):
""" Acto... |
"""author: @pythonpips"""
uppercase_python = 'PYTHON'
python = 'Python'
uppercase_python.isupper()
python.isupper()
|
"""
Given two strings s and p, return an array of all the start indices
of p's anagrams in s. You may return the answer in any order.
Example 1:
Input: s = "cbaebabacd", p = "abc"
Output: [0,6]
Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.