content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from django.db import models
from django.contrib.auth.models import AbstractUser
from PIL import Image
class User(AbstractUser):
is_teacher = models.BooleanField(default=False)
is_student = models.BooleanField(default=False)
first_name = models.CharField(max_length=100)
last_name = models.CharField(ma... | python |
from django.urls import reverse
from rest_framework.test import APIClient
from django.test import TestCase
from people.models import Person
from owf_groups.models import OwfGroup, OwfGroupPeople
requests = APIClient()
class GroupsApiTests(TestCase):
fixtures = ['resources/fixtures/default_data.json', ]... | python |
from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import UserRegisterForm, UserUpdateForm, UserTypeForm, UserDeleteForm
from django.contrib.auth.decorators import login_required
from functions import find_special_chars
# Form for registration page
def register(request):
... | python |
import os
import csv
import json
import glob
import gzip
import random
import tarfile
import zipfile
import pandas as pd
from .downloader_utils import get_corpora_dict
from .downloader_utils import get_resource_dir
def _extract_tarfile(filename, target_dir):
with tarfile.open(filename, 'r:*') as tar:
ta... | python |
import argparse
try:
from . import treedata_pb2 as proto
from . import utils
except (ValueError, ImportError):
import treedata_pb2 as proto
import utils
import represent_ast as ra
class Node:
def __init__(self, id, label, position):
self.id = id
self.label = labe... | python |
from setuptools import setup
def get_install_requires():
install_requires = [
'Django>=3,<4',
'django-jsoneditor>0.1,<0.2',
]
try:
import importlib
except ImportError:
install_requires.append('importlib')
try:
from collections import OrderedDict
except... | python |
"""
:py:class:`Model` is an abstract class representing
an AllenNLP model.
"""
import logging
import os
from typing import Dict, Union, List
import numpy
import torch
from allennlp.common.checks import ConfigurationError
from allennlp.common.params import Params
from allennlp.common.registrable import Registrable
fr... | python |
# Importing Specific Items
# Fill in the blanks so that the program below prints 90.0.
# Do you find this version easier to read than preceding ones?
# Why wouldn’t programmers always use this form of import?
____ math import ____, ____
angle = degrees(pi / 2)
print(angle) | python |
# coding=utf-8
# Copyright 2018 The HuggingFace Inc. team.
#
# 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... | python |
from .base import Widget
class PasswordInput(Widget):
""" This widgets behaves like a TextInput but does not reveal what text is entered.
Args:
id (str): An identifier for this widget.
style (:obj:`Style`): An optional style object. If no style is provided then
a new one will be c... | python |
import os
import alignfaces as af
expression = ["an", "ca", "di", "fe", "ha", "ne", "sa", "sp"]
mouth = ["o", "c"]
databases = []
for ex in expression:
for mo in mouth:
databases.append("NIM-" + ex + "-" + mo)
num_dirs = len(expression) * len(mouth)
file_postfixes = ["bmp"] * num_dirs
my_project_path = os.... | python |
import unittest
import json
from lambda_function import get_user, get_users
class TestTwitterUpdates(unittest.TestCase):
def test_get_users(self):
users_resp = get_users()
self.assertEqual(200, users_resp['statusCode'])
users = users_resp['body']
self.assertEqual(10, len(users))
self.assertEqua... | python |
# Copyright 2015 Google
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software... | python |
import cv2
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from python_util.image_processing.image_stats import get_scaling_factor
def load_image_paths(image_list):
with open(image_list) as f:
image_paths = f.readlines()
return [image_path.rstrip() for image_path in image_pa... | python |
# Copyright (C) 2019 Intel Corporation. All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
#
import os
import subprocess
BIOS_INFO_KEY = ['BIOS Information', 'Vendor:', 'Version:', 'Release Date:', 'BIOS Revision:']
BASE_BOARD_KEY = ['Base Board Information', 'Manufacturer:', 'Product Name:', 'Version:']... | python |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** 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 _utilities
fro... | python |
# -*- 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, softwa... | python |
from arekit.common.experiment.api.enums import BaseDocumentTag
from arekit.common.experiment.api.ops_doc import DocumentOperations
class CustomDocOperations(DocumentOperations):
def iter_tagget_doc_ids(self, tag):
assert(isinstance(tag, BaseDocumentTag))
assert(tag == BaseDocumentTag.Annotate)
... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from distutils.core import setup
"""
@author: Kirill Python
@contact: https://vk.com/python273
@license Apache License, Version 2.0, see LICENSE file
Copyright (C) 2017
"""
setup(
name='vk_api',
version='8.3.1',
author='python273',
author_email='whoami@p... | python |
import pytest
import torch
from src.defs import layers
def test_flatten():
x = torch.arange(12).view(2, 1, 3, 2)
print('Before flattening: ', x)
print('After flattening: ', layers.flatten(x))
| python |
#!/usr/bin/env python3
import unittest
from typing import Tuple, Union
import numpy as np
import torch
from torch import Tensor
from reagent.ope.estimators.types import TypeWrapper, Values
class TestTypes(unittest.TestCase):
TestType = Union[int, Tuple[int], float, Tuple[float], np.ndarray, Tensor]
TestCla... | python |
#!/usr/bin/python
#TODO Update the line below
#Date last updated: 27 Mar 2018
#NO7 Web logs
#Software: Microsoft Internet Information Services 7.0
#Version: 1.0
#Date: 2011-12-11 00:00:00
#Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) sc-status sc-substatus sc-win32-s... | python |
import os
import sys
import time
import argparse
import re
from tqdm import tqdm
from colorama import Fore, Back, Style
from google.cloud import translate
'''
* @desc load input file function
* @param string file_path - input file path and name
* @param string split_on - split each line with. Default: "\n"
*... | python |
# Generated by Django 3.2.3 on 2021-06-01 05:05
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('reviews', '0003_vote'),
]
operations = [
migrations.RemoveField(
model_name='project',
name='voters',
),
]
| python |
from flask import render_template, request, jsonify, make_response, url_for, redirect, Blueprint
from blueprints.hotdog.static.forms.hotdog_form import FileUploadForm
from blueprints.hotdog.model.pretrained_resnet import Hotdog_Model_Resnet
from PIL import Image
from torch.nn.functional import softmax
from torch import... | python |
""" Keeps track of configured datastore indexes. """
import json
import logging
import time
from kazoo.client import NoNodeError
from kazoo.protocol.states import KazooState
from tornado import gen
from tornado.ioloop import IOLoop
from tornado.locks import Event as AsyncEvent
from appscale.common.async_retrying impo... | python |
from territory import Territory
from player import Player
from continent import Continent
class BoardUtils:
# @staticmethod
# def get_distance(self, source: Territory, target: Territory):
# if source.ruler == target.ruler:
# return float("inf")
@staticmethod
def get_continent_ratio... | python |
# coding: utf-8
# Copyright (c) Henniggroup.
# Distributed under the terms of the MIT License.
"""
This package contains modules to generate various input files for running VASP calculations and parse the relevant outputs which are required for our defect-related analysis.
Currently, only io interfacing with VASP is p... | python |
class Solution:
def largestOverlap(self, A: List[List[int]], B: List[List[int]]) -> int:
n = len(A)
A1 = set()
B1 = set()
for i in range(n):
for j in range(n):
if B[i][j] == 1:
B1.add((i, j))
if A[i][j] == 1:
... | python |
try:
import uarray as array
except ImportError:
try:
import array
except ImportError:
print("SKIP")
raise SystemExit
a = array.array('B', [1, 2, 3])
print(a, len(a))
i = array.array('I', [1, 2, 3])
print(i, len(i))
print(a[0])
print(i[-1])
a = array.array('l', [-1])
print(len(a), a[... | python |
#!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Michael A.G. Aivazis
# California Institute of Technology
# (C) 1998-2005 All Rights Reserved
#
# {LicenseText}
#
# ~~~~~~~~~~~~~~~~~~~~~~~~... | python |
import sys
import mariadb
import time
def export_to_db(dbconfig, temperature, weatherCode, windSpeed, windDirection):
# Connect to MariaDB Platform
try:
conn = mariadb.connect(
user=dbconfig['username'],
password=dbconfig['password'],
host=dbconfig['host'],
... | python |
# Modules
import discord
from json import loads, dumps
from discord.ext import commands
from assets.prism import Tools, Constants
# Main Command Class
class Warn(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.desc = "Warns a member on the server"
self.usage = "warn [user] [re... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from conans import ConanFile, CMake, tools
import os
class GlObjectsConan(ConanFile):
name = "globjects"
version = "2.0.0"
description = "Cross platform C++ wrapper for OpenGL API objects"
url = ""
homepage = "https://github.com/cginternals/globjects"... | python |
from .base import BaseCFObject
class Metadata(BaseCFObject):
top_level_key = 'Metadata'
| python |
from django.shortcuts import render, HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout
from tracker.models import Expense
from datetime import datetime, timedelta
import json
@login_re... | python |
# -*- coding: utf-8 -*-
from sbscraper import product
from sbscraper.transform import base
class RedMartProductTransformer(base.ProductTransformer):
"""Transforms RedMart data to :class:`~sbscraper.product.Product`."""
API_VERSION = 'v1.5.6'
def get_currency(self, datum):
# RedMart only deals i... | python |
# Counting Sundays
WEEKDAYS = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
"Sunday")
MONTHS = ("January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December")
month_dict = {}
for m in MONTHS:
if m in ("September", "April", "June", "... | python |
import sys
import os
import getopt
import pygame
pygame.init()
grass_tiles = pygame.image.load(os.path.join('sprite_art','Multi_Platformer_Tileset_v2','Grassland','Terrain','Grass_Tileset.png'))
ground_tiles = pygame.image.load(os.path.join('sprite_art','Multi_Platformer_Tileset_v2','Grassland','Background','GrassLan... | python |
import tkinter
from tkinter import *
from tkinter import messagebox
import dbhelper
def add():
if(len(addtask.get()) == 0):
messagebox.showerror(
"ERROR", "No data Available\nPlease Enter Some Task")
else:
dbhelper.insertdata(addtask.get())
addtask.delete(0, END)
po... | python |
# This file is part of the clacks framework.
#
# http://clacks-project.org
#
# Copyright:
# (C) 2010-2012 GONICUS GmbH, Germany, http://www.gonicus.de
#
# License:
# GPL-2: http://www.gnu.org/licenses/gpl-2.0.html
#
# See the LICENSE file in the project's top-level directory for details.
import string
import os
imp... | python |
import io
import os
import re
from setuptools import find_packages, setup
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
def read(filename):
filename = os.path.join(os.path.dirname(__file__), filename)
text_type = type(u"")
with io... | python |
from toontown.coghq.SpecImports import *
GlobalEntities = {1000: {'type': 'levelMgr',
'name': 'LevelMgr',
'comment': '',
'parentEntId': 0,
'cogLevel': 0,
'farPlaneDistance': 1500,
'modelFilename': 'phase_11/models/lawbotHQ/LB_Zone08a',
'wantDoors': 1},
1001: {'ty... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 17 16:17:25 2017
@author: jorgemauricio
"""
# librerias
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
# crear una serie
ser1 = Series([1,2,3,4,1,2,3,4])
# desplegar
ser1
# usando replace .replace(valor a ser rempla... | python |
from django.db import IntegrityError
from rest_framework.exceptions import ErrorDetail, ValidationError
from rest_framework import serializers
from ..models import Customer
from django.contrib.auth.models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
field... | python |
# fetch mnist dataset
"""by GeoHotz"""
def fetch(url):
import requests
import hashlib
import os
import tempfile
fp = os.path.join(tempfile.gettempdir(), hashlib.md5(
url.encode('utf-8')).hexdigest())
if os.path.isfile(fp):
with open(fp, "rb") as f:
dat = f.read()
... | python |
import sys
from briefcase.platforms.linux.appimage import LinuxAppImageCreateCommand
def test_support_package_url(first_app_config, tmp_path):
command = LinuxAppImageCreateCommand(base_path=tmp_path)
# Set some properties of the host system for test purposes.
command.host_arch = 'wonky'
command.plat... | python |
import pymongo
import pandas as pd
class mongo:
'''
mongodb class through which we can perform most of the mongodb tasks using python
'''
def __init__(self):
'''
init function
'''
self.db = ""
def connect(self, connection_url,db):
'''
connect func... | python |
# Copyright 2019, 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 appli... | python |
import json
import pathlib
import pytest
import laskea
import laskea.config as cfg
def test_generate_template_command():
json_string = cfg.generate_template()
assert '"markers": "[[[fill ]]] [[[end]]]"' in json_string
def test_process_spoc_no_file(capsys):
with pytest.raises(SystemExit):
cfg.p... | python |
from copy import *
import re
class TaggedWord:
def __init__(self, word='', tag=''):
self.word = word
self.tag = tag
def getWord(self):
return self.word
def getTag(self):
return self.tag
def replaceCharAt(str, pos, c):
return str[:pos]+c+str[pos+1:]
class CorpusReader... | python |
from nuscenes.nuscenes import NuScenes
nusc = NuScenes(version='v1.0-mini', dataroot='../../data/nuscenes-mini', verbose=True) | python |
import numpy
n, m = map(int, input().split())
arr = numpy.array([list(map(int, input().split())) for _ in range(n)])
arr = numpy.min(arr, axis=1)
arr = numpy.max(arr)
print(arr)
| python |
# 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... | python |
# coding: utf-8
from tests.util import BaseGrabTestCase
from tests.spider_sigint import BaseKeyboardInterruptTestCase
SCRIPT_TPL = '''
import sys
import logging
try:
from grab import Grab
import os
import grab
#logging.error('PATH: ' + grab.__file__)
#logging.error('PID: ' + str(os.getpid()))
g... | python |
import magma
def AXI4SlaveType(addr_width, data_width):
"""
This function returns a axi4-slave class (parameterized by @addr_width and
@data_width) which can be used as the magma ports with these inputs
and outputs
Below is AXI4-Lite interface ports in verilog
input logic [`$axi_addr_width-1`... | python |
#Задача №1 Вариант 9
#Программа выводит имя и запрашивает его псевдоним
#Гасанов АФ
#29.02.2016
print ("Герой нашей сегоднящней программы - Доменико Теотокопули")
psev=input("Под каким же именем мы знаем этого человека? Ваш ответ:")
if (psev)==("Эль Греко"):
print ("Всё верно: - Доменико Теотокопули"+psev)... | python |
"""
- Double check that the targets are correct
- verify that substorms.get_next(input_idx + return idx) == input_idx + return idx
- verify all >= 0
- create files to test different situations?
- missing data -> mask is correct
""" | python |
USAGE = """USAGE
$ python anipix.py [imfile1] [imfile2] [outfile] [--color]
[outfile] must be .mp4
[--c] is an optional flag to use color mode (slower)
Examples:
$ python anipix.py cameraman.png lena.png gray.mp4
$ python anipix.py peppers.png mandrill.png color.mp4 --c
"""
if __name__ == "__main__":
... | python |
import numpy as np
from lmfit import Parameters
import sys
import os
sys.path.append(os.path.abspath('.'))
sys.path.append(os.path.abspath('./Functions'))
from utils import find_minmax
from PeakFunctions import Gaussian, LogNormal
from numba import jit
@jit(nopython=False)
def calc_dist(q,r,dist,sumdist):
ffactor... | python |
from tkinter import*
from tkinter import ttk
from tkinter import messagebox
import random
from datetime import date
import time
import sqlite3
root=Tk()
root.title("Cafe Management System")
root.geometry("1000x650")
root.resizable(width=False,height=False)
root.configure(bg="#220D0B")
logo = PhotoImage(file="logo.png... | python |
def get_version():
return "1.0.0"
| python |
import pygame
import time
import random
pygame.init()
white = (255,255,255)
black = (0,0,0)
red =(200,0,0)
light_red = (255,0,0)
yellow = (200,200,0)
light_yellow = (255,255,0)
green = (34,177,76)
light_green = (0,255,0)
display_width = 800
display_height = 600
clock = pygame.time.Clock()
gameDisplay = pygame.d... | python |
# Problem: https://www.hackerrank.com/challenges/apple-and-orange/problem
# Score: 10.0
first_multiple_input = input().rstrip().split()
s = int(first_multiple_input[0])
t = int(first_multiple_input[1])
second_multiple_input = input().rstrip().split()
a = int(second_multiple_input[0])
b = int(second_multiple_input[1]... | python |
from flask import Flask, jsonify, request
from Chem_Faiss import pipeline
import Chem_Faiss
app = Flask(__name__)
searcher = pipeline()
searcher.load_pipeline('sample')
mols = Chem_Faiss.load_sdf('molecules.sdf')
@app.route('/query', methods = ['GET','POST'])
def query():
d = request.get_json()
... | python |
from typing import Optional
from _custom_constants import *
import miscellaneous
import random
# defs is a package which claims to export all constants and some JavaScript objects, but in reality does
# nothing. This is useful mainly when using an editor like PyCharm, so that it 'knows' that things like Object, Cree... | python |
import os
import sys
from CM.CM_TUW40.f2_investment import dh_demand
from CM.CM_TUW40.f3_coherent_areas import distribuition_costs
path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
if path not in sys.path:
sys.path.append(path)
def main(P, OFP):
# f2: calculate pixel based ... | python |
import os
import requests
import time
import random
import jieba
import matplotlib.pyplot as plt
from fake_useragent import UserAgent
from wordcloud import WordCloud, ImageColorGenerator
def get_response(user_agent, proxy_list, product_id, page):
url = 'https://sclub.jd.com/comment/productPageComments.action'
... | python |
####
####
####
#### Python Pocket Primer -
#### Exercises for chapter two
####
####
####
import sys
def wordPlay(list):
vowel = ['a','e','i','o','u']
list = list.split(' ')
v_list = []
for i in list:
if i[0] in vowel or i[-1] in vowel:
v_list.append(i)
dic ={}
for i in v_li... | python |
from .paac import PAAC
from .base_runner import BaseRunner
from .single_runner import SingleRunner
from .paac_runner import PAACRunner
from .eval_runner import EvalRunner
__all__ = ["BaseRunner", "SingleRunner", "PAACRunner"]
| python |
#!/usr/bin/env python
"""
create tilespecs from TEMCA metadata file
"""
import json
import os
import numpy
import renderapi
from asap.module.render_module import (
StackOutputModule, RenderModuleException)
from asap.dataimport.schemas import (GenerateEMTileSpecsOutput,
... | python |
# -*- coding: utf-8 -*-
import operator
import six
from sage.arith.misc import GCD
from sage.combinat.q_analogues import q_int
from sage.functions.generalized import sgn
from sage.functions.log import log
from sage.functions.other import ceil
from sage.functions.other import floor
from sage.functions.other import sqrt
... | python |
import sys
import os
import subprocess
from smt.sampling_methods import LHS
import numpy as np
from scipy import stats
from surmise.emulation import emulator
from dt import cross_section, s_factor
# Reduced mass in the deuteron channel.
MU_D = 1124.6473494927284
rel_unc = float(sys.argv[1])
indices = np.array([0, 1... | python |
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
# (c) 2013-2015 Zedge Inc.
#
# Author: Muhammad A. Norozi
# (ali@zedge.net)
import yaml
def get_options(config_file):
return yaml.load(open(config_file))
if __name__ == '__main__':
from pprint import PrettyPrinter
pp = PrettyPrinter()
c... | python |
from tkinter import *
from tkinter import messagebox
from tkinter import filedialog
from tkinter.ttk import Button, Style
from tkinter import ttk
import binascii
import os
import json
import sys
import base64
import datetime
import pprint
import copy
from core.client_core import ClientCore as Core
from transaction.tra... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import math
import numpy as np
from .AxiElement import AxiElement
from .Index import Index
from .tools import path_length,... | python |
from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'accounts/login/$',
'django.contrib.auth.views.login',
name='login'),
url(r'accounts/logout/$',
'django.contrib.auth.views.logout',
name='logout'),
url(r'^$', views.IndexView.as_view(), name=... | python |
from setuptools import setup, find_packages
long_description_text = '''
Pula is a python library that is meant to encompass the many various functions that the ordinary user
finds themselves needing in the different projects they are working on. These functions can span from
simple is_number functions all the way to ... | python |
# Copyright 2019-2021 by Peter Cock, The James Hutton Institute.
# All rights reserved.
# This file is part of the THAPBI Phytophthora ITS1 Classifier Tool (PICT),
# and is released under the "MIT License Agreement". Please see the LICENSE
# file that should have been included as part of this package.
"""Explore confli... | python |
# Generated by Django 2.0 on 2019-03-12 20:51
from django.db import migrations, models
import wagtail.core.blocks
import wagtail.core.fields
class Migration(migrations.Migration):
dependencies = [
('portfolio', '0016_auto_20190312_1954'),
]
operations = [
migrations.AddField(
... | python |
from __future__ import absolute_import
from __future__ import unicode_literals
from collections import defaultdict
from sqlalchemy.dialects.postgresql.base import PGDialect
from sqlalchemy.sql import sqltypes
from sqlalchemy import util, sql
from sqlalchemy.engine import reflection
from .base import BaseDialect, Mixed... | python |
#!/usr/bin/env python
# Copyright (c) 2014-2017 Max Beloborodko.
#
# 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
#
# Unl... | python |
"""
#####################################################################
Copyright (C) 1999-2015, Michele Cappellari
E-mail: michele.cappellari_at_physics.ox.ac.uk
For details on the method see:
Cappellari M., 2002, MNRAS, 333, 400
Updated versions of the software are available from my web page
http://purl.org/ca... | python |
"""Simple script for converting SVG files to PDF files."""
import argparse
import glob
import os
import subprocess
import sys
import textwrap
def main():
"""The main function of the application"""
try:
args = _parse_args()
svg_files = find_svgs(args.source_dir)
for svg in svg_files:... | python |
#
# Dynamic Routing Between Capsules
# https://arxiv.org/pdf/1710.09829.pdf
#
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from torchvision import datasets, transforms
import torch.nn.functional as F
class Conv1(nn.Module):
def __init__(self, channels):
super(... | python |
# Generated by Django 3.0.7 on 2020-06-19 00:16
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0011_update_proxy_permissions'),
]
operations = [
migrations.CreateModel(
name='User',
f... | python |
from time import *
from base import *
def convert():
print("\n"+f"""\
{CRed}Valeur à convertir{CEnd}
""")
volumes = float(input(cmdline))
volumesChoices(volumes)
def volumesChoices(quantity):
print("\n"+f"""\
{CRed}Unité de volumes de base
\n
{CBlu... | python |
"""
BERT/RoBERTa layers from the huggingface implementation
(https://github.com/huggingface/transformers)
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from apex.normalization.fused_layer_norm import\
FusedLayerNorm as BertLayerNorm
from .modeling_utils import prune_linear_layer
import math... | python |
from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import gettext_lazy as _
from core.admin_filters import UserIsActiveFilter
from .models import CustomUser, UserProfileDriver, \
UserProfileStaff
from .services import UserDeleteSe... | python |
from django.urls import path
from . import views
urlpatterns = [
path("sprawa-<int:case_pk>/", views.EventCreateView.as_view(), name="add"),
path("wydarzenie-<int:pk>", views.EventUpdateView.as_view(), name="edit"),
path(
"<int:year>-<int:month>",
views.CalendarEventView.as_view(month_form... | python |
# Generated from JavaParser.g4 by ANTLR 4.5.3
# encoding: utf-8
from antlr4 import *
from io import StringIO
def serializedATN():
with StringIO() as buf:
buf.write("\3\u0430\ud6d1\u8206\uad2d\u4417\uaef1\u8d80\uaadd\3q")
buf.write("\u0568\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7")
bu... | python |
"""
tests module
"""
import os
import sys
import sure
ROOT_DIR = os.path.join(os.path.dirname(__file__), "../..")
sys.path.append(ROOT_DIR)
| python |
from .binonobj import BinONObj
from .ioutil import MustRead
class IntObj(BinONObj):
kBaseType = 2
@classmethod
def DecodeData(cls, inF, asObj=False):
data = bytearray(MustRead(inF, 1))
byte0 = data[0]
if (byte0 & 0x80) == 0:
m = 0x7f
n = 1
elif (byte0 & 0x40) == 0:
m = 0x3fff
n = 2
elif (byt... | python |
from .genshin import get_user_stat
__all__ = ["get_user_stat"]
| python |
from bokeh.core.properties import (
Any, Bool, Dict, Either, Instance, List, Null, Nullable, String
)
from bokeh.models import ColumnDataSource, HTMLBox
class Perspective(HTMLBox):
aggregates = Either(Dict(String, Any), Null())
split_by = Either(List(String), Null())
columns = Either(List(Either(St... | python |
from validator.rules import Base64
def test_base64_01():
assert Base64().check("c2hPd1MgaSBMSWtFOg==")
assert Base64().check("U09VVEggUEFSSw==")
assert Base64().check("QkxBQ0sgTUlSUk9S")
assert Base64().check("RkFSR08=")
assert Base64().check("QnJlYUtJTkcgQmFkIA==")
def test_base64_02():
... | python |
#Free fall
#Askng for height
#Initial velociy is 0 m/s
#Acceleration due to gravity(g) = 9.8 sq.(m/s)
h = float(input("Enter the height = "))
#Final velocity = v
import math
v = math.sqrt(2 * 9.8 * h)
print("Final Velocity = ",v)
| python |
"""
"""
import os
import shutil
from pathlib import Path
from typing import List, Optional
from TestSuite.conf_json import ConfJSON
from TestSuite.global_secrets import GlobalSecrets
from TestSuite.json_based import JSONBased
from TestSuite.pack import Pack
class Repo:
"""A class that mocks a content repo
... | python |
import urllib, json
import sys
from __builtin__ import raw_input
from termcolor import colored
import os
import glob
import webbrowser
def jumbo():
print(colored(" .::.", "cyan"))
print(colored(" .:' .:", ... | python |
from pychology.behavior_trees import Action
from pychology.behavior_trees import Priorities
from pychology.behavior_trees import Chain
from pychology.behavior_trees import DoneOnPrecondition
from pychology.behavior_trees import FailOnPrecondition
import wecs
from wecs.panda3d.behavior_trees import DoneTimer
from wecs... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.