content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2017 SML
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 restriction, including without limitation
the rights to use, copy... |
import discord
import re
import asyncio
import aiohttp
import os
import subprocess
from redbot.core import commands
from redbot.core.bot import Red
from redbot.core.data_manager import cog_data_path
from concurrent.futures.thread import ThreadPoolExecutor
import youtube_dl
class LoudVideos(commands.Cog):
def __ini... |
from rpvm.opcodes import *
from collections import Iterator
from types import CodeType
from opcode import opname
import io
class VirtualMachine(object):
"""
designed for Python3.6
playground: https://grassfedcode.com/pbe
Lib/dis.py: https://docs.python.org/ja/3/library/dis.html
CPython: https://gi... |
import argparse
import os
import flask
import pandas as pd
from six.moves import configparser
from six.moves.urllib import parse
app = flask.Flask(__name__)
app.config['DEBUG'] = True
def get_app():
return app
def format_for_highcharts(df):
#df.index = list(df.index.fillna('NODATA'))
#categories = lis... |
from os import popen
def command(instr):
return popen(instr).read()
|
# -*- encoding: utf-8 -*-
"""
@File : serializers
@Date : 2019/11/16
@Author : Regulus
@Contact : yusheng831143@gmail.com
@Desc : Warframes模块Model的序列化处理。
"""
from django.forms import URLField
from rest_framework import serializers
from apps.warframes.models import Warframe
class WarframesSerializer(seriali... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-09-11 10:41
from __future__ import unicode_literals
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('signage', '0008_asset_parameters'),
]
operations = [
... |
import numpy as np
class Sudoku:
def __init__(self, sudo=None, grid=None):
self.possible_values_grid = np.empty((9, 9), dtype=list)
if sudo is None:
self.initial_grid = np.zeros((9, 9), dtype=int)
self.grid = np.zeros((9, 9), dtype=int)
self.count_possible_grid ... |
from dataclasses import dataclass
from dataclasses_json import dataclass_json
from datetime import timedelta
from enum import auto, Enum, unique
from scavenger.api import util
from typing import Union
import abc
import functools
import logging as log
class interfaces:
class JsonSerializable_:
"""
Declares method... |
_base_ = [
'../_base_/models/resnet50_c1.py', '../_base_/datasets/TBX11K_C2.py',
'../_base_/schedules/resnetStrikesBack_C2.py', '../_base_/default_runtime.py'
]
|
# coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# 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 applicab... |
import keras.backend as K
from keras.callbacks import Callback
from sklearn.metrics import roc_auc_score
class auc_callback(Callback):
def __init__(self, x_trn, y_trn, x_dev=None, y_dev=None):
super(Callback, self).__init__()
self.x_dev = x_dev
self.y_dev = y_dev
self.x_trn = x_trn... |
import argparse
import http.server
import multiprocessing
import os
import random
import requests
import socketserver
import string
import subprocess
__auth__ = 'Jayson Grace'
def __parse_args__():
"""Parse CLI arguments.
"""
parser = argparse.ArgumentParser(description='Create web server, pull persistenc... |
from django.db import models
from fields import ListField, ColourField
# Create your models here.
class MapCity(models.Model):
#Creation date
create_date = models.DateTimeField('Date Created', auto_now_add=True)
#Name of the city
city_name = models.CharField(max_length=200)
#Local rail name
rail_na... |
# -*- coding: utf-8 -*-
"""
refer: rlpack
Actor Critic 框架
Proximal Policy Optimization.
目标loss由三部分组成:1. clipped policy loss;2. value loss;3. entropy。
policy loss需要计算当前policy和old policy在当前state上的ratio。
需要注意的是,state分布依赖于old policy。因此,更新中的old policy是一样的。
"""
import numpy as np
import tensorflow as tf
from .base impor... |
import numpy as np
@profile
def pythondot(list1, list2):
dotsum = 0
for i in xrange(len(list1)):
dotsum += list1[i] * list2[i]
return dotsum
def numpydot(arr1, arr2):
return arr1.dot(arr2)
def testfuns(arrsize, numiter):
mylist = [1] * arrsize
myarray = np.ones(arrsize)
for ... |
# Copyright (c) 2010-12, Pierre-Antoine Delsart, Kurtis Geerlings, Joey Huston,
# Brian Martin, and Christopher Vermilion
#
#----------------------------------------------------------------------
# This file is part of SpartyJet.
#
# SpartyJet is free software; you can redistribute it and/or modify
# ... |
from bcipy.signal.evaluate.rules import HighVoltage, LowVoltage
class Evaluator:
"""Evaluator.
Takes in raw data and tests them against given
rules, which elicit the rejection of a sequence when broken.
Feeds warnings to artifact rejector as suggestions.
Add rules given in parameters to evaluato... |
import numpy as np
from sklearn.datasets import load_iris
from sklearn import tree
iris = load_iris()
test_idx = [0, 50, 100]
# Delete training data
train_target = np.delete(iris.target, test_idx)
train_data = np.delete(iris.data, test_idx, axis=0)
# Testing data
test_target = iris.target[test_idx]
test_data = iris.... |
from typing import List
from fastapi import Depends, FastAPI
from fastapi.responses import JSONResponse
from fastapi_discord import DiscordOAuthClient, RateLimited, Unauthorized, User
from fastapi_discord.models import GuildPreview
app = FastAPI()
discord = DiscordOAuthClient(
"<client-id>", "<client-secret>", "... |
import pytest
def test_passes(request):
request.config.instrument["logger"].info("log record by test_passes")
assert True
class TestClass:
def test_in_class_passes(self, request):
request.config.instrument["logger"].info("log record by TestClass test_passes")
assert True
@pytest.fixtur... |
# Copyright 2018 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
load(
"@io_bazel_rules_dart//dart/build_rules/common:context.bzl",
"collect_dart_context",
"make_dart_context",
)
load(
"@io_bazel_rules_dart/... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-03-27 09:40
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('ebayinfo', '0013_auto_20180327_1634'),
]
operations = [
migrations.RenameField(
... |
"""Pylons middleware initialization"""
from beaker.middleware import CacheMiddleware
from paste.cascade import Cascade
from paste.registry import RegistryManager
from paste.urlparser import StaticURLParser
from paste.deploy.converters import asbool
from pylons import config
from pylons.middleware import ErrorHandler, S... |
import os
import sys
from contextlib import contextmanager
@contextmanager
def suppress_output():
null_out = open(os.devnull, "w")
null_err = open(os.devnull, "w")
out_fd = sys.stdout.fileno()
err_fd = sys.stderr.fileno()
out_dup_fd = os.dup(out_fd)
err_dup_fd = os.dup(err_fd)
os.dup2(null... |
import glob
print(
glob.glob('./[0-9][0-9]_*'),
"\n",
glob.glob('*.py'),
"\n",
glob.glob('?.gif'),
"\n",
glob.glob('**/*.txt', recursive=True),
"\n",
glob.glob('./**/', recursive=True),
) |
palavra = input('Digite uma palavra para ser advinhada: ')
digitadas =[]
chances = int(len(palavra)/2)
print('\n'*50)
while True:
if chances <= 0:
print(f'Voce perdeu! A palavra era {palavra}')
break
letra = input('Digite uma letra: ')
if len(letra) > 1:
print ('Favor, digitar so... |
"""
Django settings for longqiao project.
Generated by 'django-admin startproject' using Django 1.11.18.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import ... |
# -*- coding: utf-8 -*-
"""Stage changes for registered model versions."""
from verta._internal_utils import documentation
from ._stage_change import _StageChange
from ._archived import Archived
from ._development import Development
from ._production import Production
from ._staging import Staging
documentation.re... |
import os
import abc
import sys
import inspect
import pkgutil
from contextlib import contextmanager, _GeneratorContextManager
from typing import Any, Callable, Optional, List
from . import exceptions
from .util.swig import WrapperMetaClass, pointer_class, ContextManagedPointerClass
from .util.calculate import calculat... |
NAME='sharder'
VERSION = 0
DEPENDS = []
|
"""
Xiangnan He et al., "Neural Collaborative Filtering." in WWW 2017.
@author: WuBin
"""
from model.AbstractRecommender import AbstractRecommender
import tensorflow as tf
import numpy as np
from time import time
from util import data_generator, learner, tool
from util.data_iterator import DataIterator
from util import... |
# 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
__al... |
import asyncio
import os
from dataclasses import asdict
import aiofiles
import aiohttp
import json
# 4153, 5810, 9310, 471 = no image
from aiostream import stream
from fewman_svg_parser import FewmanSVG
N = 9999
CONTRACT = '0xad5f6cdda157694439ef9f6dd409424321c74628'
ALL = range(0, N + 1)
URL = "https://api.opens... |
#!/usr/bin/env python3
import sys
import os
from pymzml.utils.utils import index_gzip
from pymzml.run import Reader
def main(mzml_path, out_path):
"""
Create and indexed gzip mzML file from a plain mzML.
Usage: python3 gzip_mzml.py <path/to/mzml> <path/to/output>
"""
with open(mzml_path) as fin:... |
from scipy import *
from Reference import*
################################################################################
# ROCKET PARAMETER FUNCTIONS
################################################################################
def inert_mass(m_inert, m_prop): # inert mass fraction
return m_inert / (m_i... |
import unittest
from memcnn.config.tests.test_config import ConfigTestCase
from memcnn.models.tests.test_revop import ReversibleOperationsTestCase
from memcnn.models.tests.test_memory_saving import ReversibleMemorySavingTestCase
def collect_tests():
suites = [ConfigTestCase, ReversibleOperationsTestCase, Reversib... |
from app import Base
from app import db
from app import model
def initialiseDB() :
Base.metadata.drop_all(db)
Base.metadata.create_all(db) |
from typing import Optional, List, Union, BinaryIO
import numpy as np
from .encoder import SentenceEncoder
__all__ = ['BPESentenceEmbedding']
class BPESentenceEmbedding:
"""
LASER embeddings computation from BPE-encoded sentences.
Args:
encoder (str or BinaryIO): the path to LASER's encoder Py... |
# coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import os
from builtins import open
from unittest import skipIf
from pants.base.build_en... |
#!/usr/bin/env python
# EFILTER sample project - star catalog filter.
#
# Copyright 2015 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.a... |
import pytest
from typing import List
from tests.globals.constants import NUMBER_OF_DOCUMENTS
from tests.globals.document import vector_document
@pytest.fixture(scope="session")
def vector_documents() -> List:
return [vector_document() for _ in range(NUMBER_OF_DOCUMENTS)]
|
# function to find average marks
def find_average_marks(marks):
sum_of_marks = sum(marks)
total_subjects = len(marks)
average_mark = sum_of_marks/total_subjects
return average_mark
# function to calculate grade and return it
def grading_scale(average_mark):
if average_mark >= 80:
grade = "A... |
__author__ = 'Brice PARENT'
|
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import os, os.path, sys
import fnmatch
import tensorflow as tf
import math
import random
from sklearn import preprocessing
import operator
from sklearn.cross_validation import train_test_split
from scipy.stats.stats import pearsonr
from sklearn.me... |
"""Kaggle Challenge module"""
|
#!/usr/bin/env python
from datetime import datetime
import traceback
import glob
import datetime
import os
from stat import *
import time
import sys
from multiprocessing import Pool
import subprocess
FORMAT = '%-20s: %s'
FRAMES_ROOT = '/nfs2/datasets/TED/frames'
SPEAKER_ROOT = '/nfs1/shared/for_aniruddha/pose/speaker... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.rests_list, name='rests_list'),
url(r'^new/$', views.restaurant_new, name='restaurant_new'),
url(r'^edit/(?P<pk>[0-9]+)/$', views.restaurant_edit,
name='restaurant_edit'),
url(r'^del/(?P<pk>[0-9]+)/$', views.r... |
#Uses python3
import sys
from queue import Queue
def bipartite(adj):
n = len(adj)
color = [-1] * n
for u in range(n):
if color[u] == -1:
queue = Queue()
queue.put(u)
color[u] = 0
while not queue.empty():
u = queue.get_nowait()
... |
from dataclasses import dataclass
@dataclass
class AIgenerator:
name: str
amount: str
def setAIName(self, text):
self.name = self.text
|
import numpy as np
from bokeh.plotting import figure, show, output_file
x = np.linspace(0.1, 5, 100)
p = figure(title="log axis example", y_axis_type="log",
y_range=(0.001, 10**22))
p.line(x, np.sqrt(x), legend="y=sqrt(x)",
line_color="tomato", line_dash="dotdash")
p.line(x, x, legend="y=x")
p.ci... |
import re
# Global functions
def recommended(word):
return isNotInteger(word)
# Specific filters
def isNotInteger(word):
"""
Just allows words that are not all numbers
"""
pattern = re.compile('(?:(?:\d+,?)+(?:\.?\d+)?)')
return not pattern.match(word)
|
# Copyright (c) 2021 Cristian Patrasciuc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest
from ui.game_options import GameOptions
class GameOptionsTest(unittest.TestCase):
def test_default_options(self):
game_options... |
from datetime import datetime
from django import http
from django.http import HttpResponseNotFound
from django.http import HttpResponseServerError
from django.http import JsonResponse
from django.shortcuts import render
# Create your views here.
from django.views import View
from apps.contents.utils import get_cate... |
#!/usr/bin/env python
import sys
import re
import os
root = os.getcwd()
files = [sys.argv[1]]
def parse(index):
target = root + '/' + files[index]
with open(target, "r") as zepfile:
for line in zepfile:
if line.strip().startswith('use'):
class_name = line.strip().split(' ')[1].split(';')[0]
class_path... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import argparse
import numpy as np
import cv2
import tqdm as tqdm
from models import build_stixel_net
from data_loader import KittiStixelDataset
from albumentations import (
Compose,
Resize,
Normalize,
)
import tensorflow.keras.backend as K
parser = a... |
import os
import sys
from shutil import copyfile
def rename(img_path):
image_name_list = os.listdir(img_path)
image_name_list = [image_name for image_name in image_name_list \
if (image_name != 'train') or (image_name != 'val')]
image_dir_list = [os.path.join(img_path, image_name) for image_name ... |
import transforms3d
import math
import numpy as np
import scipy.io as sio
# Returns intrinsic camera matrix
# Parameters are hard-coded since all SURREAL images use the same.
def get_intrinsic():
# These are set in Blender (datageneration/main_part1.py)
res_x_px = 320 # *scn.render.resolution_x
res_y_px =... |
import re
supported_filetypes_pat = re.compile(r'\.h(h|pp|xx)?$', re.IGNORECASE)
first_token_pat = re.compile(r'\s*', re.MULTILINE)
hash_pat = re.compile(r'^\s*#\s*[a-z]+)', re.MULTILINE)
ifndef_pat = re.compile(r'^\s*#\s*ifndef\s+([_a-zA-Z0-9]+)', re.MULTILINE)
def supports_path(path):
return bool(supported_file... |
from sys import argv, exit
import texts
import desktops
# Flags section
flags = dict (
SHOW_DISCLAIMER = True,
INTERACTIVE = True,
HELP = False,
VERSION = False,
LIST_DEWM = False,
ADD = False,
ADD_ID = "",
REMOVE = False,
REMOVE_ID = "",
SWITCH = False,
SWITCH_ID = "",
ERROR = False,
ERROR_... |
import sys
puzzle_input_path = sys.argv[1]
with open(puzzle_input_path) as puzzle_input_file:
puzzle_input_raw = puzzle_input_file.read()
# parse puzzle input
grid = puzzle_input_raw.splitlines()
grid_width = len(grid[0])
# count trees
indices_gen = zip(range(3, len(grid) * 3, 3), range(1, len(grid), 1))
trees... |
import train_methods
import torch
import json
import numpy as np
from PIL import Image
def load_checkpoint(filepath, gpu):
print("loading {}...".format(filepath))
load_success = True
model = None
try:
checkpoint = torch.load(filepath)
model, _, _ = train_methods.NeuralNetwork(checkpoin... |
'''
This code evaluates the validation and test performance in an epoch of the model trained in jodie.py.
The task is: interaction prediction, i.e., predicting which item will a user interact with?
To calculate the performance for one epoch:
$ python evaluate_interaction_prediction.py --network reddit --model jodie -... |
# oop/class.price.py
class Price:
def __init__(self):
self.net_price = None
def final_price(self, vat, discount=0):
"""Returns price after applying vat and fixed discount."""
return (self.net_price * (100 + vat) / 100) - discount
p1 = Price()
p1.net_price = 100
print(Price.final_price(... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.management.base import BaseCommand
from keeper.core import set_key
class Command(BaseCommand):
args = '<filename ...>'
def handle(self, *args, **kwargs):
for filename in args:
set_key(filename)
|
# 导入所需模块
from cv2 import cv2
from matplotlib import pyplot as plt
import os
import numpy as np
import util
SZ = 20 # 训练图片长宽
MAX_WIDTH = 1000 # 原始图片最大宽度
Min_Area = 2000 # 车牌区域允许最大面积
PROVINCE_START = 1000
# 图像预处理
def img_preprocess(car_pic_file):
"""
:param car_pic_file: 图像文件
:return:已经处理好的图像文件 原图像文件
... |
dict = {"Name":"Aung Ko","Age":7}
dict["Age"] = 9
del dict["Name"]
print("NAME:" + dict["Name"]) # you will get error...
print("Age:" + str(dict["Age"]))
|
from file_1 import target_func
def nothing(x):
pass
target_<caret>func() |
import os
import random
import pickle as pk
import logging
from collections import defaultdict
from chemreader.readers.readmol2 import Mol2
import h5py
import numpy as np
from scipy import sparse
from tqdm import tqdm
from slgnn.config import PAD_ATOM, PAD_BOND
SEED = 1458907
random.seed(SEED)
class ZincToHdf5:
... |
#!/usr/bin/env python
#
# Humanitybot: A Cards-Against Humanity IRC Bot
# -----------------------------------------------------------
# [ https://github.com/Breakthrough/humanitybot ]
#
# Copyright (c) 2013-2014, Matthew Ames <matthew@supermatt.net>
#
# Humanitybot is licensed under the BSD 2-Clause License;... |
class Solution:
# array 二维列表
def Find(self, target, array):
# write code here
row = len(array)-1
col = 0
while row>=0 and col<len(array[0]):
if target == array[row][col]:
return True
elif target > array[row][col]:
col+=1
... |
import HaasoscopeLib
reload(HaasoscopeLib) # in case you changed it, and to always load some defaults
import time, sys
import matplotlib.pyplot as plt
#import numpy as np
from serial import SerialException
#Some options
#HaasoscopeLib.num_board = 2 # Number of Haasoscope boards to read out (default is 1)
#Haa... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Utilities for building pyQt applications (GUI's).
Todo
----
Document all functions.
"""
# from pyqtgraph.Qt import QtCore
# from PyQt5.QtWidgets import QSlider
from pyqtgraph.Qt import QtGui
from pyqtgraph.Qt import uic, QtWidgets
class slider_win(QtG... |
# Copyright 2017 Division of Medical Image Computing, German Cancer Research Center (DKFZ)
#
# 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
#... |
#!/usr/bin/env python
#coding: utf-8
__author__ = (
'weet', 'qian_linfeng@mysite.cn'
'hxz','huang_xuezhong@mysite.cn'
)
"""
TODO:
=====
1. Unit tests
"""
import os
import json
import uuid
import socket
import rfc822
from datetime import datetime
from logging.handlers import SysLogHandler
try:
... |
from django.conf.urls import url, include
from django.urls import path
from django.conf import settings
from user import views
from django.conf.urls.static import static
urlpatterns = [
url(r'^login/$', views.login, name='account_login'),
path('oauth/', include('social_django.urls', namespace="social")),
... |
#!/usr/bin/env python3
# setup.py
# CodeWriter21
from setuptools import setup, Extension, find_packages
from distutils.command.build import build
class Build(build):
def finalize_options(self):
super().finalize_options()
from Cython.Build import cythonize
self.distribution.ext_modules = c... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This module allow you to use the API in a simple and easy way.
-- Example --
params = {
'action' :'query',
'prop' :'revisions',
'titles' :'Test',
'rvlimit' :'2',
'rvprop' :'user|timestamp|content',
}
... |
import numpy as np
import cv2
import heapq
import statistics
import math
def popularity(image,k):
(m,n,_) = image.shape
d = {}
for i in range(m):
for j in range(n):
t = tuple(image[i,j])
if t in d:
d[t] += 1
else:
... |
# -*- coding: utf-8 -*-
"""
jump2python-02_2_4-string_indexing_and_slicing.py
P.47, 문자열 인덱싱과 슬라이싱
인덱싱 = 가리킨다
슬라이싱 = 무언인가를 잘라낸다.
"""
#####################
# 문자열 인덱싱이란? #
#####################
# Python은 0부터 숫자를 센다.
a = "Life is too short. You need Python"
print( a[3] )
# e
# 문자열 인덱싱 활용하기
print( a[0],... |
from django.db.models import Count, CharField, When, Case, Q
from core.rest.viewsets import BaseModelViewSet
from teams.models import Team, get_user_model
from ..models import Snippet, File, Label, Language, SnippetLabel, Extension
from .filters import FileFilter, SnippetFilter, LabelFilter, SnippetLabelFilter
from .... |
"""
Dataset Level Prprocessing Strategies will be written here
Make sure your dataset is present in the preprocessing configurations
"""
import argparse
import json
import logging
import os
import random
from tqdm import tqdm
from config.data import (
DATA_FOLDER,
DATA_FOLDER_PROCESSED,
DATA_FOLDER_RAW,
... |
"""Validation/Testing routine"""
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import torch
from src.utils.misc import MiscUtils
import src.utils.logging as logging
from src.utils.img_ranking_evaluate import *
logger = logging.get_logger(__name__)
import ... |
import random as rand
import os
#forms the number array from file
filePath = os.path.dirname(os.getcwd())+"/testinput.txt"
inputData = open(filePath,'r').read()
nums = inputData.strip().split()
nums = [int(num) for num in nums]
#sorts using selection sort
for i in range(len(nums)):
minInd = i #initializes minimum... |
from serial_j import SerialJ
class Snack(SerialJ):
schema = [
# cheese is nice but is optional.
{'name': 'cheese', 'optional': True},
# chocolate is a MUST have.
{'name': 'chocolate'},
# chips is a must but we have to decide which kind later,
# so its value can be N... |
__all__ = [
'abacus',
'replace_by_aliases',
'InputError',
'SolvingError',
'InputWarning'
]
from calla.html import html2text
from collections import OrderedDict
def replace_by_aliases(expression, aliases):
"""
Replace parameters in expression by their aliases.
e.g. 'alpha*beta-g... |
from django.conf import settings
from django.db import models
User = settings.AUTH_USER_MODEL
class SearchTerm(models.Model):
""" stores the text of each internal search submitted """
q = models.CharField(max_length=50)
search_date = models.DateTimeField(auto_now_add=True)
ip_address = models.Generic... |
# -*- coding: utf-8 -*-
"""
Hydropy package
@author: Stijn Van Hoey
"""
from __future__ import absolute_import, print_function
import datetime
import calendar
import numpy as np
from scipy.signal import argrelmax, argrelmin
import pandas as pd
from pandas.tseries.offsets import DateOffset
from .stor... |
"""
@author like
@since 2021-01-01 20:59
@email 980650920@qq.com
"""
import requests
class RequestSpider(object):
def __init__(self, url):
self.url = url
headers = {
# 浏览器的版本
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chr... |
# -*- encoding: utf-8 -*-
import sys
import time
import telnetlib
import logging
import thread
from threading import Lock
# Python TS3 Library (python-ts3)
#
# Copyright (c) 2011, Andrew Williams
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted... |
from itertools import chain
from typing import TextIO
from sklearn.model_selection import train_test_split
from sklearn.model_selection import KFold
import tensorflow as tf
from utils import base_positions, flip_dict, linearfold_positions
import numpy as np
import re
import sklearn
import pdb
dataset_csv_path = 'dat... |
# See LICENSE file for full copyright and licensing details.
from odoo import models, fields, api
class MoveStandards(models.TransientModel):
_name = 'move.standards'
_description = "Move Standards"
academic_year_id = fields.Many2one('academic.year', 'Academic Year',
... |
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import (
HttpResponseRedirect,
)
from django.shortcuts import get_object_or... |
import copy
import json
import os
from typing import Dict, List
from detectron2.data import DatasetCatalog, MetadataCatalog
from detectron2.data.datasets.cityscapes_panoptic import get_cityscapes_panoptic_files
from detectron2.utils.file_io import PathManager
__all__ = [
"CITYSCAPES_CATEGORIES",
"CITYSCAPES_S... |
import torch
import torch.nn as nn
import torch.nn.utils.spectral_norm as spectralnorm
from torch.nn import init
class Encoder(nn.Module):
def __init__(self, out_dim, ch):
super(Encoder, self).__init__()
self.b1 = nn.Sequential(
nn.Conv2d(3, ch, 4, 2, 1),
nn.BatchNorm2d(64),
nn.LeakyReLU(0.2, True)
)
... |
# Copyright (c) 2017 The Verde Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
#
# This code is part of the Fatiando a Terra project (https://www.fatiando.org)
#
"""
Functions for generating and manipulating coordinates.
"""
import warnings
import numpy as... |
from datetime import date, datetime
from typing import Dict, List
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import ARRAY, JSONB
from sqlalchemy.orm import relationship
from db_api.database import SqlAlchemyBase
class Document(SqlAlchemyBase): # type: ignore
__tablename__ = "documents"
id... |
import pytesseract
from PIL import Image
from tkinter import Tk, Button, PhotoImage, messagebox, filedialog, Canvas
import tkinter
import os
import sys
root= Tk()
def resource_path0(relative_path):
base_path = getattr(
sys,
'_MEIPASS',
os.path.dirname(os.path.abspath(__file__)))
... |
'''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GLSC2 import _types as _cs
# End users want this...
from OpenGL.raw.GLSC2._types import *
from OpenGL.raw.GLSC2 import _errors
from OpenGL.constant import Constant as _C
... |
def print_key_value(key, value):
"""
格式化输出格式: key:value
:param key: key
:param value: value
:return:
"""
print(key, value, sep=" : ")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.