text string | size int64 | token_count int64 |
|---|---|---|
import gym
import numpy as np
import torch
import stable_baselines3 as sb3
from stable_baselines3.common.evaluation import evaluate_policy
from stable_baselines3.common.env_util import make_vec_env
import pybullet_envs
import pandas as pd
import pickle
import os
import matplotlib.pyplot as plt
import seaborn as sns
s... | 11,453 | 3,589 |
import torch
import torch.nn.functional as F
from ..registry import LOSSES
from .metric_learning_base import BaseMetricLearningLoss
@LOSSES.register_module()
class ArcLoss(BaseMetricLearningLoss):
"""Computes the Arc loss: https://arxiv.org/pdf/1904.13148.pdf
"""
def __init__(self, **kwargs):
su... | 572 | 207 |
import base64
def generate_service_url(function_path, params=None, encrypted=False):
if not params:
return function_path
else:
path_end = str()
for key, value in params.iteritems():
if encrypted:
value = base64.urlsafe_b64encode(str(value)).replace('=', '')
... | 576 | 170 |
from setuptools import setup
setup(name="some_module", py_modules=["some_module"])
| 84 | 27 |
#!/usr/bin/env python
# This file was created automatically
longversion = '0.2.2-1-g9c91991'
| 93 | 38 |
from enum import Enum, auto
class TYPE(Enum): # 자료형
INT = auto()
STR = auto()
class Variable:
def __init__(self):
self.var = dict()
def insert(self, name):
try:
self.var[name]
except KeyError:
self.var[name] = [f"var_{len(self.var)}", TYPE.INT]
... | 787 | 265 |
# -*- coding: utf-8 -*-
"""Basic classes for running Genetic Algorithms.
"""
__author__ = "Justin Hocking"
__copyright__ = "Copyright 2021, Zipfian Science"
__credits__ = []
__license__ = ""
__version__ = "0.0.1"
__maintainer__ = "Justin Hocking"
__email__ = "justin.hocking@zipfian.science"
__status__ = "Development"
... | 12,016 | 3,272 |
import pytest
from sqlalchemy.ext.asyncio import AsyncSession
from virtool.uploads.models import Upload
@pytest.fixture
async def test_uploads(pg, fake, static_time):
user_1 = await fake.users.insert()
user_2 = await fake.users.insert()
upload_1 = Upload(id=1, name="test.fq.gz", type="reads", user=user_1... | 615 | 228 |
# Copyright Jamie Allsop 2013-2018
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
#-------------------------------------------------------------------------------
# CompileMethod
#---------... | 3,029 | 920 |
import json
import os
try:
os.rename(os.path.join(os.getcwd(),'config','like.json'),os.path.join(os.getcwd(),'config','like_copy.json'))
except:
print("无法进行重命名")
f = open(os.path.join(os.getcwd(),'config','like_copy.json'),mode='r',encoding='utf8')
likes = json.loads(f.read())
list = {"likes":[{"name":"默认收藏夹... | 593 | 252 |
# %% import libraries
import numpy as np
import random
import cv2
import PIL
import matplotlib.pyplot as plt
from copy import deepcopy
# %% 1 Extract Harris interest points
def get_points(img, threshold=0.1, coordinate=False):
"""
Extract harris points of given image
:param img: An image of type open c... | 8,440 | 3,220 |
import torch
import os.path as osp
from PIL import Image
from torch.utils.data import Dataset
import numpy as np
from torchvision import transforms as T
import glob
import re
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
def read_image(img_path):
"""Keep reading image until succe... | 6,592 | 2,156 |
from starlette.requests import Request
from starlette.responses import JSONResponse, Response
def hello_world(scope):
return Response("Hello World!")
def hello_world_form_data(scope):
async def parse(receive, send):
request = Request(scope, receive)
data = await request.form()
respon... | 407 | 109 |
import gnupg
import os
GNUPG_KEY_TYPE = "RSA"
GNUPG_KEY_LENGTH = 2048
class Encryptor(object):
def __init__(self):
self.gpg = gnupg.GPG()
self.gpg.encoding = "utf-8"
if self.gpg.list_keys() == []:
self.generate_keypair()
def generate_keypair(self):
"""Generate th... | 1,726 | 560 |
"""
Django settings for project.
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
PROJECT_PATH = os.path.abspath(os.path.split(__file__)[0])
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = (
'django.contri... | 4,966 | 1,776 |
from itertools import count
from common import mymath
def GouGu():
for m in count(1):
for n in xrange(1, m):
if mymath.gcd(m, n) == 1 and (m % 2 == 0 or n % 2 == 0):
mm = m * m
nn = n * n
mn = 2 * m * n
pp = mm * 2 + mn
... | 895 | 343 |
'''
import analyze
any = analyze.Analyze()
# 吻别是由张学友演唱的一首歌曲。
#text = '《盗墓笔记》是2014年欢瑞世纪影视传媒股份有限公司出品的一部网络季播剧,改编自南派三叔所著的同名小说,由郑保瑞和罗永昌联合导演,李易峰、杨洋、唐嫣、刘天佐、张智尧、魏巍等主演。'
#text = '姚明1980年9月12日出生于上海市徐汇区,祖籍江苏省苏州市吴江区震泽镇,前中国职业篮球运动员,司职中锋,现任中职联公司董事长兼总经理。'
knowledge = any.knowledge(text)
print(knowledge)
'''
from medext import getTripl... | 587 | 661 |
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2017 Dean Jackson <deanishe@deanishe.net>
#
# MIT Licence. See http://opensource.org/licenses/MIT
#
# Created on 2017-05-06
#
"""Unit tests for Workflow's XML feedback generation."""
import sys
from contextlib import contextmanager
from xml.etree import Eleme... | 4,460 | 1,544 |
from coc.api import ClashOfClans
from os import environ
import pytest
@pytest.fixture
def api_key():
return environ['COC_API_KEY']
slow_test = pytest.mark.skipif(
not pytest.config.getoption("--runslow"),
reason="need --runslow option to run"
)
@slow_test
@pytest.mark.api_call
def test_locations_apicall... | 2,323 | 985 |
# coding=utf-8
"""Evaluation of different training and test sizes."""
import argparse
import logging
import random
import mlflow
import numpy
import torch
import tqdm
from kgm.data import get_dataset_by_name
from kgm.eval.matching import evaluate_matching_model
from kgm.models import GCNAlign
from kgm.modules import ... | 4,618 | 1,381 |
# SPDX-FileCopyrightText: David Fritzsche
# SPDX-License-Identifier: CC0-1.0
import re
from pytest_mypy_testing import __version__
def test_version():
assert re.match("^[0-9]*([.][0-9]*)*$", __version__)
| 212 | 86 |
from microsoft.gestures.fingertip_placement_relation import FingertipPlacementRelation
from microsoft.gestures.fingertip_distance_relation import FingertipDistanceRelation
from xml.etree.ElementTree import Element, SubElement, Comment, tostring
from microsoft.gestures.relative_placement import RelativePlacement
from mi... | 5,204 | 1,445 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-09-15 20:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("old_submit", "0004_submit_protocol")]
operations = [
migrations.AlterField(
model_name="submit",
name="p... | 1,650 | 481 |
from rest_framework import serializers
from .models import Todo
class TodoSerializer(serializers.ModelSerializer):
"""."""
class Meta:
model = Todo
fields = "__all__"
read_only_fields = ("belongs_to", "is_complete", "created_at", "updated_at")
| 281 | 87 |
from .get_imformation import GI
class DM:
def __init__(self, adj_matrix, ins_matrix):
self.Adjacency_Matrix = adj_matrix
self.Insidence_Matrix = ins_matrix
self.N = len(self.Adjacency_Matrix)
### Packing: Find Maximal ###
def clique(self):
"""
Returns:
... | 7,027 | 2,130 |
from .basemoveeffect import BaseMoveEffect
from game.combat.effects.genericeffect import GenericEffect
class Cure(BaseMoveEffect):
def after_action(self):
if self.scene.board.random_roll(self.move.chance):
target_effects = self.scene.get_effects_on_target(self.move.target)
for stat... | 680 | 199 |
import json
import os
import trafaret as t
import yaml
from dataclasses import dataclass, asdict
from pathlib import Path
from typing import Any, List, Dict
ModelMeta = t.Dict(
{
t.Key('name'): t.String,
t.Key('description'): t.String,
t.Key('model_path'): t.String,
t.Key('data_s... | 2,945 | 998 |
"""this script crawls for the profile pictures of researchers in google scholar
and saves them in a folder called [figures]
the crawler exploit the informations via the description of the tags in the html of google scholar
be aware that too many requests to a server might interrupt your script, please
... | 2,844 | 862 |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
#
# redisClient.py
# chdb
#
# 🎂"Here's to the crazy ones. The misfits. The rebels.
# The troublemakers. The round pegs in the square holes.
# The ones who see things differently. They're not found
# of rules. And they have no respect for the status quo.
# You can quote t... | 2,246 | 754 |
import csv
import matplotlib.pyplot as plt
import requests
class nurul:
def ganjilgenap(self):
with open('kelas_2c/nurul.csv') as files:
reader=csv.reader(files, delimiter=',')
for row in reader:
if int(row[0])%2 == 1:
print(row[0],"merupakan Bi... | 3,438 | 1,340 |
'''
Витя работает недалеко от одной из станций кольцевой линии Московского метро, а живет рядом с другой станцией той же линии. Требуется выяснить, мимо какого наименьшего количества промежуточных станций необходимо проехать Вите по кольцу, чтобы добраться с работы домой.
Формат ввода
Станции пронумерованы подряд нату... | 1,227 | 476 |
from rest_framework.routers import DefaultRouter
from django.urls import path, include
from .views import *
router = DefaultRouter()
router.register('user', User, basename='user')
urlpatterns = [
path('', include(router.urls))
]
| 236 | 69 |
####################################
# author: Gonzalo Salazar
# course: Python for Data Science and Machine Learning Bootcamp
# purpose: lecture notes
# description: Section 15 - Linear Regression
# other: N/A
####################################
#%%
import os
from numpy.lib.function_base import corrcoef
import panda... | 7,110 | 2,185 |
#!/usr/bin/env python
import numpy as np
import argparse
from ctypes import *
import sys
################################ Load library: ################################
lib_name = 'libhypot.so'
try:
# try to use the one the OS finds (e.g. in /usr/local/lib)
libhypot = CDLL(lib_name)
except OSError:
# lib... | 1,994 | 605 |
import time
import json
from redis import ConnectionError
import logging
import jsonpickle
from retrying import retry
log = logging.getLogger("redis-conn")
def retry_if_connection_error(exception):
return isinstance(exception, ConnectionError)
class RedisConn(object):
def __init__(self, redis_conn, sub_cha... | 3,066 | 1,008 |
import pytest
import pytest_inmanta.plugin
import os
import sys
import pkg_resources
pytest_plugins = ["pytester"]
@pytest.fixture(autouse=True)
def set_cwd(testdir):
pytest_inmanta.plugin.CURDIR = os.getcwd()
@pytest.fixture(scope="function", autouse=True)
def deactive_venv():
old_os_path = os.environ.ge... | 560 | 208 |
# __init__.py
from .weheartit import whi | 41 | 16 |
import itertools
from contextlib import ExitStack as does_not_raise # noqa: N813
import pandas as pd
import pytest
from sid.vaccination import vaccinate_individuals
@pytest.mark.integration
@pytest.mark.parametrize(
"vaccination_models, expectation, expected",
[
({}, does_not_raise(), pd.Series([Fal... | 1,546 | 462 |
import argparse
import json
import numpy as np
import prettytable as pt
import torch
import torch.autograd
import torch.nn as nn
import transformers
from sklearn.metrics import precision_recall_fscore_support, f1_score
from torch.utils.data import DataLoader
import config
import data_loader
import utils
... | 12,216 | 4,038 |
def odd_one(L):
d={}
for i in L:
try:
if(type(i) == str):
d['str']+=1
if(type(i) == bool):
d['bool']+=1
if(type(i) == int):
d['int']+=1
if(type(i) == float):
d['float']+=1
... | 764 | 254 |
# -*- coding: utf-8 -*-
"""
Microsoft-AppV-SharedPerformance
GUID : fb4a19ee-eb5a-47a4-bc52-e71aac6d0859
"""
from construct import Int8sl, Int8ul, Int16ul, Int16sl, Int32sl, Int32ul, Int64sl, Int64ul, Bytes, Double, Float32l, Struct
from etl.utils import WString, CString, SystemTime, Guid
from etl.dtyp import Sid
from ... | 30,800 | 15,443 |
from typing import Dict
from urllib.parse import quote
def request_path(env: Dict):
return quote('/' + env.get('PATH_INFO', '').lstrip('/'))
| 147 | 49 |
#!/usr/bin/env python3
from heyvector import cache, github
@cache.memoize(50)
def list_user_repositories(user, **kwargs):
return github.get('/users/%s/repos' % user,
params = {
'visibility': 'public',
'affiliation': 'owner',
'sort': 'created',
**kwargs})
@... | 522 | 169 |
from __future__ import print_function
from math import atan2, cos, sin, pi, sqrt, tan
from utils import dist, lerp, frpart
from array import array
from PIL import Image
def FancyEye(x, y):
a = atan2(x, y)
r = dist(x, y, 0.0, 0.0)
if r == 0:
return (0, 0)
u = 0.04 * y + 0.06 * cos(a * 3.0) /... | 3,965 | 1,650 |
# -*- coding:utf-8 -*-
query = 'https://en.wikipedia.org/w/api.php?action=parse&formatversion=2&contentmodel=text&disableeditsection=&disablelimitreport=&disabletoc=&prop=text|iwlinks|parsetree|wikitext|displaytitle|properties&redirects&page=Blue%20Train%20%28album%29'
response = r"""
{
"parse": {
"title"... | 79,991 | 30,613 |
def get_optimizer_parameters_with_llrd(model, peak_lr, multiplicative_factor):
num_encoder_layers = len(model.transformer.encoder.layer)
# Task specific layer gets the peak_lr
tsl_parameters = [
{
"params": [param for name, param in model.task_specific_layer.named_parameters()],
... | 1,687 | 490 |
# Glasnost Parser v2.
# Developed 2011/2012 by Hadi Asghari (http://deeppacket.info)
#
# Statistics about test streams
class GlasMeasurement:
"""" Class to hold statistics about one test stream """
def __init__(self, direction, port_typ, flow_typ, tcp_port):
assert direction in ['u','d']
... | 4,812 | 1,840 |
import numpy as np
from GPy.kern.src.kern import Kern
from GPy.core.parameterization import Param
from paramz.transformations import Logexp
from paramz.caching import Cache_this
class LinearWithOffset(Kern):
"""
Linear kernel with horizontal offset
.. math::
k(x,y) = \sigma^2 (x - o)(y - o)
... | 2,563 | 825 |
# This file shows some example usage of Python functions to read an OCT file.
# To use exectute this test reader, scroll to the bottom and pass an OCT file to the function unzip_OCTFile.
# Find the comment #Example usage.
#
# Additional modules to be installed should be 'xmltodict', 'shutil', and 'gdown'.
# Tested in P... | 12,829 | 4,267 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 28 13:19:06 2019
@author: juangabriel
"""
# Plantilla de Pre Procesado - Datos Categóricos
# Cómo importar las librerías
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importar el data set
dataset = pd.read_csv('Data.csv... | 1,095 | 386 |
# Copyright 2018 Saphetor S.A.
#
# 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... | 7,281 | 2,084 |
################################################################################
##
## This library is free software; you can redistribute it and/or
## modify it under the terms of the GNU Lesser General Public
## License as published by the Free Software Foundation; either
## version 2.1 of the License, or (at your op... | 77,806 | 23,172 |
import pathlib
from unittest import TestCase
from unittest.mock import patch
from DALI import Annotations
from lyre.data import DaliDataset, Chunk
from lyre.utils import sample2time
class TestDaliDataset(TestCase):
def test_creation_of_dataset(self):
self.maxDiff = None
with patch("lyre.data.da... | 7,068 | 2,434 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: houzhiwei
# time: 2019/7/13 19:12
import json
import os
import re
from JSON2OWL.OwlConvert.OwlUtils import OWLUtils
module_path = os.path.dirname(__file__)
with open(module_path + '/grass.json', 'r') as f:
jdata = json.load(f) # list
for i,d in enumerate(jdat... | 434 | 191 |
# Copyright (c) 2021, Galois, Inc.
#
# All Rights Reserved
#
# This material is based upon work supported by the Defense Advanced Research
# Projects Agency (DARPA) under Contract No. FA8750-20-C-0203.
#
# Any opinions, findings and conclusions or recommendations expressed in this
# material are those of the author(s) ... | 1,861 | 619 |
class MyRange:
def __init__(self, start, stop, step=1):
self.start = start
self.stop = stop
self.step = step
def __iter__(self):
return MyRangeIterator(self)
class MyRangeIterator:
def __init__(self, myrange_object):
self.my_range = myrange_object
self.coun... | 1,215 | 433 |
from rest_framework.test import APITestCase, APIClient
from django.urls import include, path, reverse
from ..views import posts
from ..utils import methods, generate_id
# https://www.django-rest-framework.org/api-guide/testing/
class TestPost(APITestCase):
urlpatterns = [
path("author/<str:authorID>/post... | 932 | 299 |
# helper functions for testing properties of candidate schedules
import requests
from sets import Set
import json
import calendar
import itertools
import os
from collections import OrderedDict
import random
from definitions import ROOT_DIR, lessonTypeCodes, LOCAL_API_DIR
from z3 import *
LUNCH_HOURS = [11, 12, 13]
def... | 11,399 | 3,824 |
"""Docker container registry commands
"""
| 42 | 11 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
This script has been used perform functional load calculations on CANCORP.
author: Andrea Ceolin
date: February 2021
'''
from collections import Counter
import math
'''
Get the token frequencies of the corpus
'''
words_tokens = Counter()
for line in open('cantonese... | 2,484 | 789 |
import random
import matplotlib.pyplot as plt
import tensorflow as tf
import keras as K
from os import path
from src.lib import *
#from src.logging import *
from copy import deepcopy
from datetime import datetime
class Agent:
def __init__(self, model, batch_size=12, discount_factor=0.95,
buffer_size=200, pre... | 15,401 | 6,853 |
#!/usr/bin/env python3
# --- Day 3: Binary Diagnostic ---
from typing import Dict, List, Tuple
from copy import deepcopy
MOST_COMMON = 1
LEAST_COMMON = 0
EXAMPLE = """\
00100
11110
10110
10111
10101
01111
00111
11100
10000
11001
00010
01010\
"""
def lines_to_matrix(lines: List[str]) -> List[List[str]]:
matrix... | 3,036 | 1,146 |
# -*- coding:utf-8 -*-
__author__ = 'Ren Kang'
__date__ = '2018/3/27 19:05'
from django.http import JsonResponse
class JSONResponseMixin:
"""
a mixin that can be used to render a JSON response
"""
def render_to_response(self, context, **response_kwargs):
"""
:param cont... | 665 | 224 |
# 데이터 다운로드
from keras.datasets import imdb
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)
# 데이터 변환
import numpy as np
def vectorize_sequences(sequences, dimension=10000):
results = np.zeros((len(sequences), dimension))
for i, sequence in enumerate(sequences):
r... | 1,760 | 673 |
# Copyright 2021 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
import logging
import traceback
from myuw.dao import get_netid_of_current_user
from myuw.dao.gws import is_student, is_applicant
from myuw.dao.pws import get_display_name_of_current_user
from myuw.dao.password import get_pw_json
fro... | 2,268 | 621 |
class Solution:
def convert(self, s: str, numRows: int) -> str:
strings = {i: [] for i in range(0, numRows)}
increasing = True
row = 0
for i in s:
strings[row].append(i)
if numRows == 1:
continue
if increasing:
row +... | 666 | 172 |
from django.apps import AppConfig
class BpConfig(AppConfig):
name = "bp"
| 79 | 27 |
_base_ = [
'../../_base_/models/memory_r50-d8.py', '../../_base_/datasets/camvid_video.py',
'../../_base_/default_runtime.py', '../../_base_/schedules/schedule_80k.py'
]
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0005)
model = dict(
decode_head=dict(num_classes=12), auxiliary_head=di... | 413 | 190 |
"""
Modified from WikiSQL/lib/dbengine.py
BSD 3-Clause License
Copyright (c) 2017, Salesforce Research
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the ... | 5,721 | 1,847 |
def setup(app):
return {
'parallel_write_safe': False
}
| 72 | 24 |
print('demo')
for x in range(1000):
print(x, end=' ')
| 59 | 27 |
"""
"""
import os
import json
import logging
from maya import cmds
__title__ = 'mayaprefs'
__version__ = '0.1.6'
__author__ = 'Marcus Albertsson <marcus.arubertoson@gmail.com>'
__url__ = 'http://github.com/arubertoson/maya-mayaprefs'
__license__ = 'MIT'
__copyright__ = 'Copyright 2016 Marcus Albertsson'
... | 2,195 | 820 |
#!/usr/bin/python
""" Sonos Node Server for Polyglot
by Einstein.42(James Milne)
milne.james@gmail.com"""
from polyglot.nodeserver_api import SimpleNodeServer, PolyglotConnector
from sonos_types import SonosSpeaker, SonosControl
VERSION = "0.2.1"
class SonosNodeServer(SimpleNodeServer):
""" Sonos N... | 1,567 | 498 |
"""A cube bouncing inside a box. (5 seconds)
This is used to test the rigid body equations.
"""
import numpy as np
from pysph.base.kernels import CubicSpline
from pysph.base.utils import get_particle_array_rigid_body
from pysph.sph.equation import Group
from pysph.sph.integrator import EPECIntegrator
from pysph.so... | 2,973 | 1,171 |
import subprocess, os, time, shutil
from datetime import datetime
import jarvis_cli as jc
from jarvis_cli import config, client
from jarvis_cli.client import log_entry as cle
def create_snapshot(environment, config_map):
snapshot_filepath = "jarvis_snapshot_{0}_{1}.tar.gz".format(environment,
datetime... | 4,986 | 1,555 |
"""Flower client example using MXNet for MNIST classification.
The code is generally adapted from:
https://mxnet.apache.org/api/python/docs/tutorials/packages/gluon/image/mnist.html
"""
import flwr as fl
import numpy as np
import mxnet as mx
from mxnet import nd
from mxnet import gluon
from mxnet.gluon import nn
fro... | 4,609 | 1,500 |
#!/usr/bin/env python3
#
# @Author: Josh Erb <josh.erb>
# @Date: 27-Feb-2017 11:02
# @Email: josh.erb@excella.com
# @Last modified by: josh.erb
# @Last modified time: 27-Feb-2017 11:02
"""
Main driver script for ingesting RSS data. Uses the ArticleFeed() object
from the feeder.py script and a dictionary of public... | 2,116 | 684 |
#!/usr/bin/env python
import os,sys,pdb,scipy,glob
from pylab import *
import urllib, urllib2
import xml.dom.minidom
import datetime
def ADS():
thisMirror = 'http://adsabs.harvard.edu/'
print 'Retrieving from ',thisMirror
baseUrl = thisMirror + 'cgi-bin/nph-abs_connect?'
return baseUrl
def get_text(... | 10,033 | 3,235 |
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.routers import auth
from . import models
from .database import engine
from .routers import posts, users, auth, votes
#create our posts table if its not present
models.Base.metadata.create_all(bind=engine)
# aplication instance
app... | 919 | 298 |
from callbacks.callback import *
from callbacks.vis import *
class VisdomCallback(Callback):
def __init__(self, experiment_name):
self.vis=Vis("lnn", 8097)
# self.iter_nr=0
self.experiment_name=experiment_name
def after_forward_pass(self, phase, loss, loss_dice, lr, pred_softmax, targ... | 1,068 | 407 |
#python3 Steven 12/05/20,Auckland,NZ
#pytorch backbone models
import torch
from commonTorch import ClassifierCNN_NetBB
from summaryModel import summaryNet
from backbones import*
def main():
nClass = 10
net = ClassifierCNN_NetBB(nClass, backbone=alexnet)
summaryNet(net, (3,512,512))
#net = Class... | 1,451 | 641 |
# -*- coding: utf-8 -*-
# @Time : 2021/2/19 下午4:22
# @Author : 司云中
# @File : foot_models.py
# @Software: Pycharm
from django.contrib.auth import get_user_model
from django.db import models
from django.db.models import Manager
from django.utils.translation import gettext_lazy as _
from shop_app.models.commodity_models ... | 953 | 380 |
import subprocess as sp
import scikits.audiolab
import numpy as np
from scipy.fftpack import fft, ifft
from scipy.io import wavfile
#--CONVERT MP3 TO WAV------------------------------------------
song_path = '/home/gris/Music/vblandr/test_small/punk/07 Alkaline Trio - Only Love.mp3'
command = [ 'ffmpeg',
'-i'... | 1,569 | 587 |
from django.conf.urls import patterns, include, url
from django.http import HttpResponseRedirect
from LCD12864.views import *
def auto_redirect(request):
return HttpResponseRedirect('/MIC/index/')
urlpatterns = patterns('',
url(r'index/$', index),
url(r'search/$', search),
url(r'update_database/... | 372 | 119 |
"""SQL for storing and working on tasks."""
SQL_TEMPLATE = """
CREATE TABLE IF NOT EXISTS pgtq_{0}_scheduled (
key INTEGER PRIMARY KEY,
not_before TIMESTAMP WITHOUT TIME ZONE NOT NULL,
task JSON NOT NULL,
attempts INTEGER NOT NULL,
max_retries INTEGER
);
CREATE INDEX IF NOT EXISTS
ix_pgtq_{0}_scheduled_no... | 3,243 | 1,125 |
import unittest
import visgraph.graphcore as v_graphcore
s1paths = [
('a','c','f'),
('a','b','d','f'),
('a','b','e','f'),
]
s2paths = [
('a','b'),
('a','b','c'),
]
class GraphCoreTest(unittest.TestCase):
def getSampleGraph1(self):
# simple branching/merging graph
g = v_graphc... | 6,259 | 2,289 |
import logging
from chatty_goose.cqr import Hqe, Ntr
from chatty_goose.pipeline import RetrievalPipeline
from chatty_goose.settings import HqeSettings, NtrSettings
from chatty_goose.types import CqrType, PosFilter
from parlai.core.agents import Agent, register_agent
from pyserini.search import SimpleSearcher
@regist... | 4,029 | 1,314 |
"""
Utils and functions to for MizuRoute postprocessing on Cheyenne
Inne Vanderkelen - March 2021
"""
import numpy as np
def set_plot_param():
"""Set my own customized plotting parameters"""
import matplotlib as mpl
mpl.rc('xtick',labelsize=12)
mpl.rc('ytick',labelsize=12)
mpl.rc('axes',tit... | 5,639 | 1,905 |
from django.contrib import admin
from web.models import Subscribers, Article, Post, Profile
admin.site.register(Subscribers)
admin.site.register(Article)
admin.site.register(Post)
admin.site.register(Profile)
| 210 | 63 |
"""This module defines the settings to be altered and how to handle them.
Each setting should contain a dict with the following keys:
'value': The content to be placed in `local_settings.py`
'default': The content will be set as the default value in `settings.py`
`<SETTING_NAME> = getattr(local_setting... | 875 | 262 |
import sys
import logging
from typing import Union, Dict, Optional
import json
from elasticsearch import Elasticsearch
from elasticsearch.exceptions import (
NotFoundError as ESNotFoundError,
RequestError as ESRequestError,
AuthenticationException as ESAuthenticationException,
)
import pydantic
from pymong... | 14,611 | 3,846 |
import torch
import torch.nn as nn
from torchvision.models import vgg11
from torchvision.models import vgg13
from torchvision.models import vgg16
from torchvision.models import vgg19
from torchvision.models import vgg11_bn
from torchvision.models import vgg13_bn
from torchvision.models import vgg16_bn
from torchvision... | 1,276 | 502 |
from utils_queue import Queue
class _Node:
__slots__ = '_val', '_left', '_right'
def __init__(self, val, left=None, right=None):
self._val = val
self._left = left
self._right = right
class BinaryTree:
__slots__ = '_root'
def __init__(self, root=None):
self._root = roo... | 3,684 | 1,215 |
NAMAFILE = 'Telkomsel Opok v1'
REQ = ''
LHOST = '127.0.0.1'
LPORT = 8080
FQUERY = ('dGVsa29tLnR1eXVsY3J5cHRvcy5jb20vaXBrLWJpbi9pcGsucG5nL25wYXpvbmUvMDAvaHR0cC8=').decode('base64')
MQUERY = ''
BQUERY = ''
RQUERY = ('di53aGF0c2FwcC5jb20uYmVyYmFnaW1hbmZhYXQuY28uaWQ=').decode('base64')
CQUERY = ''
IQUERY = ''
IMETHOD = 0
I... | 35,625 | 11,405 |
from wishlist.domain.product.ports import CreateProduct
from wishlist.test.helpers import AsyncMock
class TestCreateProduct:
async def test_create_product_with_success(
self,
create_product_request,
product_response
):
create_product = CreateProduct(
AsyncMock(retu... | 472 | 121 |
from .conceptualize import ProbaseConcept | 41 | 12 |
import platform
class MATGenerator:
def __init__(self, ownerComp):
self.ownerComp = ownerComp
self.OUT_glsl_struct = ''
self.OUT_pixel = ''
self.OUT_vertex = ''
self.use_alpha_hashed = False
self.Update(self.ownerComp.op('in1'))
def eval_template(self, tmpl_dat_name, ctx):
t = op.ShaderB... | 3,798 | 1,864 |
import pytest
import xml.etree.ElementTree as ET
import numpy as np
from mujoco_py import load_model_from_xml, MjSim, load_model_from_path
from simmod.modification.mujoco import MujocoBodyModifier
from simmod.modification.mujoco import MujocoJointModifier
TEST_MODEL_FURUTA_PATH = 'assets/test_mujoco_furuta.xml'
TEST... | 7,707 | 2,861 |
"""
test_list.py
written in Python3
author: C. Lockhart
"""
from typelike.core import ListLike
from hypothesis import given
import hypothesis.strategies as st
import numpy as np
import pandas as pd
import unittest
# Contents
__all__ = [
'TestList'
]
# Test typelike/core/list.py
class TestList(unittest.TestCas... | 1,265 | 448 |
import rethinkdb as r
conn = r.connect("192.168.6.26", 28015)
try:
r.db_drop("hackiiitd").run(conn)
print("deleted old db")
except:
print("inital creation")
r.db_create("hackiiitd").run(conn)
r.db("hackiiitd").table_create("fall").run(conn)
print("."),
r.db("hackiiitd").table_create("medicine").run(conn)
print(".... | 484 | 216 |