content
stringlengths
5
1.05M
#Crie um programa que leia vários números inteiros pelo teclado. No final da execução, # mostre a média entre todos os valores e qual foi o maior e o menor valores lidos. # O programa deve perguntar ao usuário se ele quer ou não continuar a digitar valores. '''n = int(input('Digite um número:')) soma = n cont = 1 media...
from oslo.db.sqlalchemy import models from sqlalchemy import ForeignKey from sqlalchemy.orm import relationship from sqlalchemy import Column, schema, Text from sqlalchemy import Float, Integer, String, Boolean from sqlalchemy.dialects.mysql import MEDIUMTEXT from sqlalchemy.ext.declarative import declarative_base fr...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- !pip install Pillow==4.1.1 !pip install "fastai==0.7.0" !pip install torchtext==0.2.3 !apt-get -qq install -y libsm6 libxext6 && pip install -q -U opencv-python import cv2 from os import path from wheel.pep425tags import get_abbr_impl, get_impl_ver, get_abi_tag platform =...
from .market_calendar import MarketCalendar from .exchange_calendar_asx import ASXExchangeCalendar from .exchange_calendar_bmf import BMFExchangeCalendar from .exchange_calendar_cboe import CFEExchangeCalendar from .exchange_calendar_cme import \ CMEEquityExchangeCalendar, \ CMEBondExchangeCalendar from .exchan...
from pathlib import PurePath as _Path files={ 'pentalanine.h5' : str(_Path(__file__).parent.joinpath('pentalanine.h5')), 'pentalanine.inpcrd' : str(_Path(__file__).parent.joinpath('pentalanine.inpcrd')), 'pentalanine.prmtop' : str(_Path(__file__).parent.joinpath('pentalanine.prmtop')), 'metenkephalin.p...
# # voice-skill-sdk # # (C) 2020, Deutsche Telekom AG # # This file is distributed under the terms of the MIT license. # For details see the file LICENSE in the top directory. # # import yaml import unittest import logging from unittest.mock import patch from datetime import timezone as tz from skill_sdk import swagge...
import os, sys import subprocess from datetime import datetime dir = os.path.dirname(__file__) sys.path.insert(0, os.path.join(dir, '../')) def subprocess_open_when_shell_true(command): popen = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) (stdoutdata, stderrdata) = pop...
def wordpresent(word, list): flag =0 for ele in list: ele = ele.split('/') if(ele[0]==word): flag=1 #print(flag) return flag list = ['शिंदे/p\n', 'श्री कृष्ण बिहारी वाजपेयी/p\n', 'पं० श्याम लाल बिहारी वाजपेयी/p\n', 'राष्ट्रीय अध्यक्ष/p\n', 'प्रधानमंत्री/p\n', 'फारुख खान/p\n', 'उमर अब्दुल्ला/p\n', 'राज्यपाल स...
import unittest from pipelinewise_singer.schema import Schema class TestSchema(unittest.TestCase): # Raw data structures for several schema types string_dict = { 'type': 'string', 'maxLength': 32 } integer_dict = { 'type': 'integer', 'maximum': 1000000 } arra...
from saml2 import BINDING_SOAP from saml2 import BINDING_HTTP_REDIRECT from saml2.saml import NAME_FORMAT_URI __author__ = 'rolandh' #BASE = "http://localhost:8091/" #BASE = "http://lingon.catalogix.se:8091/" BASE = "http://lingon.ladok.umu.se:8091/" CONFIG = { "entityid" : BASE+"idp", "service": { "...
import logging from pathlib import Path from scrapy import Spider, Request from scrapy.crawler import CrawlerProcess from scrapy_playwright.page import PageCoroutine class HandleTimeoutMiddleware: def process_exception(self, request, exception, spider): logging.info("Caught exception: %s", exception.__cl...
import matplotlib.gridspec as gridspec import matplotlib.pyplot as plt import numpy as np import os import pickle from scipy.stats import vonmises from skimage.filters import median from skimage.io import imread, imsave import skimage.morphology as morpho from skimage.measure import find_contours from mantis import sdp...
import tensorflow as tf from modeler.tfmodel import TFModel class FastTextModel(TFModel): def __init__(self, label_size, learning_rate, batch_size, decay_steps, decay_rate, num_sampled, sentence_len, vocab_size, embed_size, is_training): """init all hyperparameter here""" # set h...
def fromRGB(rgb: str): """ convert rgb string to 3 element list suitable for passing to OpenGL """ return [int(rgb[2 * i: 2 * i + 2], 16) / 255 for i in range(3)] # TODO: add more color conversions and tools
class Student(Person): # Class Constructor # # Parameters: # firstName - A string denoting the Person's first name. # lastName - A string denoting the Person's last name. # id - An integer denoting the Person's ID number. # scores - An array of integers denoting the Person's t...
# Source and destination file names. test_source = "misc_rst_html5.txt" test_destination = "misc_rst_html5.html" # Keyword parameters passed to publish_file. reader_name = "standalone" parser_name = "rst" writer_name = "html5" # Settings # local copy of stylesheets: # (Test runs in ``docutils/test/``, we need relativ...
import interpretVtt import cv2 import math import datetime def createDateTime(ms): base_datetime = datetime.datetime( 1900, 1, 1 ) delta = datetime.timedelta(0, 0, 0, ms) return base_datetime + delta def frameNumberToDateTime(frameNumber, fps): time = float(frameNumber)/float(fps) # seconds return cr...
from setuptools import setup, find_packages import json package_json = json.load(open('package.json')) version = package_json['version'] setup( name='mockup', version=version, description="A collection of client side patterns for faster and easier " "web development", long_description=...
def info(string): if string.lower() == 'city': return 'warszawa' elif string.lower() == 'product': return 'mieszkanie' elif string.lower() == 'minimumprice': return '125000' else: return ''
from torchvision import transforms from torchvision.datasets.folder import ImageFolder,default_loader,IMG_EXTENSIONS import copy import torch def training_augmentation(resize = 256,crop = 224): return transforms.Compose([ transforms.Resize(resize), transforms.RandomResizedCrop(crop), ...
# Copyright (c) Microsoft Corporation and contributors. # Licensed under the MIT License. import unittest from graspologic.layouts.nooverlap._node import _Node from graspologic.layouts.nooverlap._quad_node import ( _QuadNode, is_overlap, is_overlapping_any_node_and_index, ) class TestOverlapCheck(unitte...
# Copyright 2021 Huawei Technologies Co., Ltd # # 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...
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models from django.db.models import get_app, get_models class Migration(SchemaMigration): # old_name => new_name apps_to_rename = { 'some_old_app' : 'some_new_app', 'ano...
import glob, os import numpy as np from dess_utils.data_utils import imagesc from skimage import measure from scipy import ndimage def convert_3D_to_2D(source, destination): l = glob.glob(source + '*.npy')[:] l.sort() if not os.path.isdir(destination): os.makedirs(destination) for name in l: ...
""" cP_EOS.py SPDX-License-Identifier: BSD-2-Clause Copyright (c) 2021 Stuart Nolan. All rights reserved. """ import pdb import CoolProp.CoolProp as cP from CoolProp import AbstractState as cPAS from tabulate import tabulate from scipy.optimize import minimize def cEOS_fit_kij(kij, data, cPAS_EOS): cPAS_EOS.set_b...
from typing import * # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: """ 给定一个整数 n,生成所有由 1 ... n 为节点所组成的二叉搜索树。 示例: 输入: 3 输出: [ [1,null,3,2], [3,2,null,1], ...
# import webapp2 # import os import logging from google.appengine.api import urlfetch import urllib2 # from urlparse import urlparse from urllib import urlencode import json import secrets import time import base64 import hmac import hashlib import email.utils import Cookie FB_LOGIN_URL = "https://www.facebook.com/...
import sys sys.path.append('/home/cryo/') import pysmurf import time epics_root = 'dev_epics' sd = epics_root + ':AMCc:FpgaTopLevel:AppTop:AppCore:StreamReg:StreamData[{}]' S = pysmurf.SmurfControl(setup=False, epics_root=epics_root, make_logfile=False) ch = 0 step_size = 2**6 a = -2**15 S....
#!/usr/bin/env python # # ___INFO__MARK_BEGIN__ ####################################################################################### # Copyright 2016-2021 Univa Corporation (acquired and owned by Altair Engineering Inc.) # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file ex...
ENV_ID_TO_POLICY = { 'gallop_ol': ('rex_gym/policies/gallop/ol', 'model.ckpt-4000000'), 'gallop_ik': ('rex_gym/policies/gallop/ik', 'model.ckpt-2000000'), 'walk_ik': ('rex_gym/policies/walk/ik', 'model.ckpt-2000000'), 'walk_ol': ('rex_gym/policies/walk/ol', 'model.ckpt-4000000'), 'standup_ol': ('rex...
from distutils.core import setup setup( name='Cochlear', version='0.1', author='Brad Buran (bburan@alum.mit.edu)', packages=['cochlear'], url='http://github.com/bburan/cochlear', license='LICENSE.txt', description='Module for various auditory experiments', requires=['numpy'], script...
"""Test for Word cloud Xmodule functional logic.""" import json from unittest.mock import Mock from django.test import TestCase from fs.memoryfs import MemoryFS from lxml import etree from opaque_keys.edx.locator import BlockUsageLocator, CourseLocator from webob.multidict import MultiDict from xblock.field_data impo...
# -*- coding: utf-8 -*- """ Created on Wed Aug 16 11:05:33 2017 Example of loading a forest file and updating for use with sage. This sorts forests (prunes as well for all forests with <2 halos, and adds meta information) @author: Pascal Jahan Elahi """ import sys import os import glob #load python routines scriptp...
colormap = plt.cm.YlGnBu # choose your favourite one! fig = plt.figure(figsize=(15, 10)) ax = plt.axes(projection=lambert93) X = sp98_dept_filled.mean() norm = plt.Normalize(X.min(axis=0), X.max(axis=0)) for dept, value in zip(X.index[:-1], X): if dept not in ["20", "974"]: # On omet la Corse et la Réunion... ...
''' trading start data importer ''' import os, json, sys from pathlib import Path import data if len(sys.argv) < 2: sys.exit('Usage: %s config-path' % sys.argv[0]) if not os.path.exists(sys.argv[1]): sys.exit('ERROR: Database %s was not found!' % sys.argv[1]) pwd = sys.argv[1] root = Path(pwd).parent data_p...
# runNBA_Data.py import time import pandas as pd import numpy as np # Machine Learning algorithms from sklearn.pipeline import Pipeline from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures,scale from sklearn.cross_validation import train_test_split, KFold from sklearn....
import pyeccodes.accessors as _ def load(h): def wrapped(h): table2Version = h.get_l('table2Version') indicatorOfParameter = h.get_l('indicatorOfParameter') indicatorOfTypeOfLevel = h.get_l('indicatorOfTypeOfLevel') level = h.get_l('level') if table2Version == 1 and indi...
import asyncio import aiohttp import discord import io import chat_exporter from discord.ext import commands from cogs.utils import hypixel class Tickets(commands.Cog, name="Tickets"): def __init__(self, bot): self.bot = bot @commands.command(aliases=['reg', 'verify']) async def register(self, ...
import argparse import tqdm import pickle import numpy as np import dmc2gym import torch import gin import super_sac from super_sac.wrappers import Uint8Wrapper, FrameStack from train_dmc import IdentityEncoder def main(): parser = argparse.ArgumentParser() parser.add_argument("--policy", type=str, required...
import discord from discord.ext import commands import datetime class Snipe(commands.Cog): def __init__(self, bot): self.bot = bot self.ta = "ORDER BY time DESC LIMIT 1" @commands.Cog.listener() async def on_message_delete(self, message): if message.content == "": retu...
""" Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ class Tests: preprocess_instance_count = ( "Pre-process instance counts are accurate", "Un...
from setuptools import setup setup( name='flask-apidoc', version='1.1.2', packages=['flask_apidoc'], url='https://github.com/viniciuschiele/flask-apidoc', license='MIT', author='Vinicius Chiele', author_email='vinicius.chiele@gmail.com', description='Adds ApiDoc support to Flask', k...
from flask import Flask, jsonify import numpy as np import datetime as dt import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func from sqlalchemy.pool import StaticPool engine = create_engine("sqlite:///Resources/hawaii.sqlite", c...
# -*- coding: utf-8 -*- """ File Name: maxDepth Author : jing Date: 2020/4/13 二叉树的深度 https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof/ """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None ...
# Copyright 2017 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompa...
from tool.runners.python import SubmissionPy class BadouralixSubmission(SubmissionPy): def __init__(self): self.preamble_size = 25 def run(self, s): """ :param s: input in string format :return: solution flag """ xmas = list(map(int, s.split())) for i ...
# Copyright 2017 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 required by applicable law or a...
from threading import Thread from time import sleep from pratidarshan import ( pradarshanam, alert, get_registry, lang_code, AJAY, sahAyikA, ver, Tk, ttk, display_lang_lists, ) from pystray import MenuItem as item, Menu as menu, Icon as SysTray from PIL import Image from kuJjikop...
from random import randrange from threading import Barrier, Thread from time import ctime, sleep num_runners = 3 finish_line = Barrier(num_runners) runners = ['Huey', 'Dewey', 'Louie'] def runner(): name = runners.pop() sleep(randrange(2, 5)) print('%s reached the barrier at: %s \n' % (name, ctime())) ...
import logging from sentry_sdk import Hub async def test_capture_exc(catch_sentry): assert not catch_sentry try: 1 / 0 except ZeroDivisionError: Hub.current.capture_exception() assert catch_sentry async def test_logging(catch_sentry): assert not catch_sentry logging.getLog...
import markdown from commons import file_name_tools from commons.file import file_utils import bleach from commons.errors import PageNotFoundError from logging import getLogger logger = getLogger(__name__) def md_to_html(md_text): logger.debug("md_to_html:start") main_contents = markdown.markdown(md_text, e...
# dict——字典——{key:value}——无序 # key-value类型 # key必须是不可变的类型 # 不支持 下标、切片 print(type({ 1: 1, 2: 2, 3: 3 })) print(type({ '1': 1, 1: 1, 2: 2, 3: 3 })) print({ 1: 1, 2: 2, 3: 3 }) print({ '1': 1, 1: 1, 2: 2, 3: 3 }) #异常:TypeError: unhashable type: 'list' # print({ # ...
# -*- coding: utf-8 -*- """Nobeyama Radioheliograph TimeSeries subclass definitions.""" from collections import OrderedDict import pandas import numpy as np import matplotlib.pyplot as plt import astropy.units as u from astropy.time import TimeDelta import sunpy.io from sunpy import config from sunpy.time import par...
#! /usr/bin/env python # -*- coding: utf-8 -*- # # Interpreter version: python 2.7 # # Imports ===================================================================== import dhtmlparser from dhtmlparser import first # Variables =================================================================== TEXT = "<div><nonpair />...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ if root == None: return 0 ...
# -*- coding: UTF-8 -*- from app import app app.run(debug=True, host="0.0.0.0")
# -*- coding: utf-8 -*- # Generated by Django 1.11.8 on 2018-01-01 13:32 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('cmdb', '0004_category_createtimes'), ] operations = [ migrations.RemoveField( ...
#!/usr/bin/env python from __future__ import absolute_import, division, print_function import os import subprocess import logging import shutil import glob import uuid from pyglidein.client_util import get_presigned_put_url, get_presigned_get_url class Submit(object): """ Base class for the submit classes ...
# -*- coding: utf-8 -*- """ Created on Thu Nov 22 13:19:47 2018 This script loads (pre-processed) CMF and PCR output as well as observed discharge. It subsequently alignes the lengths of the time series in case they differ. Time series are plotted for both Hardinge Bridge and Bahadurabad. For further analysis o...
#!/usr/bin/python import sys import os import pickle from optparse import OptionParser parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(parent_dir) from tp_utils import pipe def write_debug_pipe(obj): with open(pipe.DEBUG_PIPE_PATH, 'wb') as fd: pickle.dump(obj, fd) ...
from __future__ import division import caffe import numpy as np from sklearn.externals import joblib BN_EPS = 1e-8 def get_caffenet(model_filename): return caffe.Net(model_filename, caffe.TEST) def load_weights(weights_filename): return joblib.load(weights_filename) def check_caffe_weights(weights): # ...
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn import linear_model from itertools import cycle class Lasso: def __init__(self): self.res = None self.type = None self.alpha = None # lasso with parameter selected using cross ...
import decimal from django.test.client import RequestFactory from mock import patch, sentinel from hypothesis import given from hypothesis.strategies import characters, text, integers, booleans, datetimes, dates, decimals, uuids, binary, dictionaries from perma.utils import * from .utils import PermaTestCase, Sentin...
''' █████████████████████████████████████████████████████████████████████████████████████████████████████████████ █▄─▄▄─█▄─▄███▄─▄▄─█─▄▄▄─█─▄─▄─█▄─▄▄▀█─▄▄─█▄─▀█▄─▄███▄─█─▄█▄─▄█─▄▄▄▄█▄─██─▄██▀▄─██▄─▄███▄─▄█░▄▄░▄█▄─▄▄─█▄─▄▄▀█ ██─▄█▀██─██▀██─▄█▀█─███▀███─████─▄─▄█─██─██─█▄▀─█████▄▀▄███─██▄▄▄▄─██─██─███─▀─███─██▀██─███▀▄█▀...
from .action import Action class Create(Action): name = 'create' group_attrs = { 'help': 'Create supported objects' }
# Generated by Django 3.2.4 on 2021-06-21 23:32 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('blog', '0013_auto_20210622_0126'), ] operations = [ migrations.RenameField( model_name='profile', old_name='twitter_bio', ...
from kfilter import kalman from kfilter import simplify print("kalman filter version 1.1.0")
import os import pytest @pytest.mark.skipif( not os.getenv("FAST_BITRIX24_TEST_WEBHOOK"), reason="Нет аккаунта, на котором можно проверить", ) class TestsWithLiveServer: class TestBasic: def test_simple_add_lead(self, get_test): b = get_test lead_no = b.call( ...
N, S, T = map(int, input().split()) sb, tb = S.bit_length(), T.bit_length() print(tb - sb if (T >> max(0, tb - sb)) == S else -1)
""" Author: Jianyou (Andre) Wang Date: Sep 2020 """ import tensorflow as tf import numpy as np import nltk from nltk.corpus import wordnet as wn from gensim.parsing.preprocessing import remove_stopwords from collections import defaultdict, Counter import os import re import random import requests im...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Helper function to generate Figure-of-Merit (FoM) plots. Called by 'runToolkit.py' and 'runToolkitExtended.py'. For the full procedure, see "README.md". For method details, please see "A toolkit for data-driven discovery of governing equations in high-noise regime...
import os.path as path import pytest from pymongo_inmemory import downloader def test_env_folders_overwrite_default_downloadfolder(monkeypatch): monkeypatch.setenv("PYMONGOIM__DOWNLOAD_FOLDER", "test_folder") assert downloader._download_folder() == "test_folder" def test_env_folders_overwrite_default_extr...
from collections import Counter import copy from Item import ItemInfo from ItemPool import triforce_blitz_items from Region import Region, TimeOfDay class State(object): def __init__(self, parent): self.prog_items = Counter() self.world = parent self.search = None if se...
from gym_cooking.environment.game.game import Game from gym_cooking.environment import cooking_zoo n_agents = 2 num_humans = 1 max_steps = 100 render = False level = 'open_room_salad' seed = 1 record = False max_num_timesteps = 1000 recipes = ["TomatoLettuceOnionSalad", 'TomatoLettuceOnionSalad'] parallel_env = coo...
from sphinx.directives.code import CodeBlock class PylitFile(CodeBlock): def run(self): caption = self.options.get('caption') if not caption: caption = "" newcaption = '<<' + caption + '>>==' self.options['caption'] = newcaption # format the block and return ...
"""Test 2D autorefocusing of legacy minimizer""" import numpy as np import nrefocus import pytest from test_helper import load_cell @pytest.mark.filterwarnings('ignore::nrefocus.minimizers.mz_legacy.' 'LegacyDeprecationWarning') def test_2d_autofocus_cell_helmholtz_average_gradient(): ...
# crossCorrelationPIV.py # ====================== # # Particle image velocimetry (PIV) based on cross correlation. CLIJ does the PIV in all three dimensions individually. # This allows fast analysis of optical flow with the drawback of not being super precised. It is assumed that CLIJ # over estimates the flow a b...
import math import numpy as np import string import random import json import argparse import torch as T import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import os from transformers import * import sys sys.path.append('../') from DataLoader.bucket_and_batch import bucket_and_batch from ...
'''Returns a fact to indicate if this is a physical or virtual machine''' # sysctl function by Michael Lynn # https://gist.github.com/pudquick/581a71425439f2cf8f09 from __future__ import absolute_import, print_function import plistlib import subprocess from ctypes import CDLL, c_uint, byref, create_string_buffer fr...
""" Feature preprocessing of data, such as expanding categorical features to numerical ones. """ from sklearn.base import ClassifierMixin, BaseEstimator, TransformerMixin from sklearn.preprocessing import LabelBinarizer, LabelEncoder import numpy as np class ColumnSelector(BaseEstimator, TransformerMixin): """Sel...
from sqlalchemy import Column, String, Integer, Boolean from honeypot_detection.database.base import Base from honeypot_detection.database.dictionary import Dictionary class HoneyBadgerLabel(Dictionary): __tablename__ = "honey_badger_labels" class HoneyBadgerNormalizedContractLabel(Base): __tablename__ = "...
from django.test.testcases import TestCase from .utils import create_group_community class GroupModelTest(TestCase): def test_grouprules_created(self): gp = create_group_community() self.assertIsNotNone( gp.rules, msg='Rules not created')
# -*- coding: utf-8 -*- """ Created on Sun Dec 15 16:04:10 2019 @author: danpo This script compares the CFF assay's waveform alignment when I use two strategies for finding on/off windows: with markers for on, and without markers for on. """ import importlib import erg import erg.plotting as plotting importlib.relo...
from jnpr.junos.op.phyport import * from jnpr.junos import Device dev = Device( user='netconf', host='172.16.0.1', password='test123' ) dev.open() ports = PhyPortTable(dev).get() print "Port,Status,Flapped" #Print Header for CSV for port in ports: print("%s,%s,%s" % (port.key, port.oper, p...
""" DB Model for Likes and relevant junction tables """ import datetime from sqlalchemy.sql import and_, select from app.main import db, login_manager class Reaction(db.Model): """ Description of User model. Columns ----------- :id: int [pk] :value: int [pk] :user_id: int [Foreign Key ->...
# coding=utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function import torch import torch.nn as nn class RMSNorm(nn.Module): def __init__(self, d, p=-1., eps=1e-8, bias=False): """ Root Mean Square Layer Normalization :para...
import seaborn as sns import matplotlib.pyplot as plt import numpy as np def generate_dataset(D, N, K, mu0, sigma0, sigma): z = np.random.randint(K, size=N) mu = np.random.multivariate_normal(mean=mu0, cov=sigma0, size=K) X = np.zeros((N, D)) for i in xrange(N): X[i] = np.random.multivariate_n...
# -------------------------------------------------------- # ImageNet-21K Pretraining for The Masses # Copyright 2021 Alibaba MIIL (c) # Licensed under MIT License [see the LICENSE file for details] # Written by Tal Ridnik # -------------------------------------------------------- import os import urllib from argparse...
# Generated by Django 2.1.5 on 2019-05-10 21:24 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0001_initial'), ] operations = [ migrations.CreateModel( name='Project', fields=[ ...
from sympy import partition as p from time import time from rich import print t1 = time() n = 10000 while p(n) % 1_000_000 != 0: n += 1 print(n) print(f"Process completed in {time()-t1}s")
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-09-13 08:55 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ...
# ============================================================================== # Copyright 2019 - Philip Paquette # # NOTICE: 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...
""" Test cases for the L{xmantissa.webadmin} module. """ from twisted.trial.unittest import TestCase from nevow.athena import LivePage from nevow.context import WovenContext from nevow.testutil import FakeRequest from nevow.loaders import stan from nevow.tags import html, head, body, directive from nevow.inevow imp...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os, datetime from django.db import migrations from django.conf import settings def rename_x3s3dot3_forwards(apps, schema_editor): Group = apps.get_model("group", "Group") Group.objects.filter(acronym="x3s3.3").update(acronym="x3s3dot3") ...
"""The main graph kernel class, implemented as a sci-kit transformer.""" import copy import time import warnings import numpy as np from scipy.linalg import svd from sklearn.base import BaseEstimator from sklearn.base import TransformerMixin from sklearn.utils.validation import check_is_fitted from grakel.kernels im...
from query.query import ProjectQuery from utils.csv_ops import write_csv from config import conf from labels_from_csv import read_labels_from_csv HEADERS = ['commit_id', 'la', 'ld', 'lt', 'ns', 'nd', 'nf', 'entropy', 'fix', 'ndev', 'age', 'nuc', 'exp', 'rexp', 'sexp'] def combine_label_with_features(change_list, bu...
import pytest import click import os import pathlib import ghia.configreader as creader import ghia.rule as rule def config(name): return pathlib.Path(__file__).parent / 'fixtures' / name def test_read_auth_empty_file(): with pytest.raises(Exception): creader.read_auth(config('auth.invalid.cfg')) ...
import os from shutil import copyfile import pytest from cascade.word_header_footer import replace_in_header_footer # Get the path to the test directory (this file's path) test_root_path = os.path.dirname(os.path.realpath(__file__)) def test_header_footer(): in_filename = os.path.join(test_root_path, 'assets', ...
"""Module containing class `Plugin`.""" class Plugin: """ Abstract base class for plugins. This class has all of the attributes required of plugin classes, but the attributes have `None` values instead of real ones. The attributes are provided mainly for the purpose of documentation. ...
# Git Author n, m,l = list(map(int, input().split())) if (n <= l and l <= m) : print("Yes") elif (m <= l and l <= n): print("Yes") else : print("No")