content stringlengths 5 1.05M |
|---|
import requests
from requests.exceptions import ProxyError, Timeout, ConnectionError, ChunkedEncodingError
import time
from fake_useragent import UserAgent
ua = UserAgent()
def get_proxy():
r = requests.get('http://localhost:5000/get')
proxy = r.text
return proxy
def get_count_proxys():
r = request... |
import torch
class Node:
__slots__ = [
"depth",
"cost",
"state",
"parent",
"parentMove",
"isSolved",
"hashState",
]
def __init__(self, state, parent, parentMove, depth, cost, isSolved):
self.depth = depth # Moves from root to this state
... |
"""
riesz_pyramid.py
Conversion between Riesz and Laplacian image pyramids
Based on the data structures and methodoligies described in:
Riesz Pyramids for Fast Phase-Based Video Magnification
Neal Wadhwa, Michael Rubinstein, Fredo Durand and William T. Freeman
Computational Photography (ICCP), 2014 IEEE International ... |
# Reading a excel sheet and formatting columns as per requirement
# the excel sheet structure is following.
# Question, Who are you
# Answer, Pradeep
# Question, Where do you live
# Answer, Hyderabad
# Question, What do you do
# Answer, Nothing
# The final structure would be
# 1, 2
# Who are you... |
import json
import logging
from bunq.sdk import context
from bunq.sdk.context import ApiContext, ApiEnvironmentType, BunqContext
from bunq.sdk.model.generated import endpoint
from bunq.sdk.model.generated.endpoint import UserPerson
from bunq.sdk.model.generated.object_ import Amount, Certificate, NotificationFilter, Po... |
import os
from telemanom.ESN import SimpleESN
import yaml
import time
from keras_tuner.engine.hypermodel import HyperModel
from keras_tuner.tuners import Hyperband, RandomSearch
import csv
import tensorflow as tf
class MyHyperModel(HyperModel):
def __init__(self, config, channel):
self.config = config
... |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2011 Justin Santa Barbara
# Copyright (c) 2012 NTT DOCOMO, INC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not... |
'''
Iterate over the snapshot file and retrieve summary data for each publisher
'''
import os
import json
import pandas as pd
import datetime
import gzip
from .PublisherNameConsolidator import PublisherNameConsolidator
from .PublisherCountsByType import PublisherCountsByType
class UnpaywallDataFrame:
... |
from django.http import JsonResponse
from rest_framework import status
from rest_framework.views import APIView
from api.audit_trail import service as audit_trail_service
from api.audit_trail.serializers import AuditSerializer
from api.cases.libraries.get_case import get_case
from api.core.authentication import Export... |
#!/usr/bin/python
# encoding=utf-8
"""
Easy to git clone the stars of somebody to local backup.
By @evilcos
"""
import os
import sys
import json
import requests
import multiprocessing as mul
star_urls = []
def get_star_urls(url, page=1):
url = url%page
r = requests.get(url)
c = r.content
j = json.lo... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 14 17:26:59 2021
@author: matthewyeung
"""
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import MinMaxScaler
def percent_change_column(df, column_names):
for column in column_... |
"""empty message
Revision ID: 865a544d9558
Revises: e6047eb3a998
Create Date: 2018-12-23 19:54:11.534857
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '865a544d9558'
down_revision = 'e6047eb3a998'
branch_labels = None
depends_on = None
def upgrade():
op... |
#encoding:utf-8
"""
脚本目标:爬去目标B站网页的视频,需要安装ffmpeg-python功能包
具体过程为(默认仅下载当前网页视频):
1. 仅下载当前视频: python3 BDownloader.py -single True -url https://www.bilibili.com/video/BV1Ci4y1L7ZZ?p=1
2. 下载右侧列表中所有的视频: python3 BDownloader.py -single False -url https://www.bilibili.com/video/BV1Ci4y1L7ZZ?p=1
PS: 下载所有视频的过程为,先下载所有视频... |
#!/usr/bin/env python3
#############
# Setup
#############
# try: # Get the input
# input_file = 'input.txt'
# with open(input_file, 'r') as fh:
# data = fh.readline()
# data = data.strip().split(',')
# data = [int(x) for x in data]
# except FileNotFoundError:
# exit(f'The input ... |
import sys
import os
from django.core.management.base import BaseCommand
from django.conf import settings
from django.template.loader import render_to_string
from ietf.doc.models import Document
def write(fn, new):
try:
f = open(fn)
old = f.read().decode('utf-8')
f.close
except IOErro... |
#!/usr/bin/env python
# Author: Alex Tereschenko <alext.mkrs@gmail.com>
# Copyright (c) 2016 Alex Tereschenko.
#
# SPDX-License-Identifier: MIT
import mraa as m
import unittest as u
from i2c_checks_shared import *
class I2cChecksWrite(u.TestCase):
def setUp(self):
self.i2c = m.I2c(MRAA_I2C_BUS_NUM)
def tea... |
#!/usr/bin/env python
# encoding: utf-8
import json
import npyscreen
import sys
from subprocess import run
from subprocess import check_output
class Fmt(object):
def __init__(self, fmtId, text):
self.fmtId = fmtId
self.text = text
class FmtList(npyscreen.SelectOne):
def display_value(self, v... |
import torch
import cv2
import numpy as np
from torch.autograd import Variable
from darknet import Darknet
from util import process_result, load_images, resize_image, cv_image2tensor, transform_result
import pickle as pkl
import argparse
import math
import random
import os.path as osp
import os
import sys
from datetime... |
'''
Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
Example:
Input: [1,2,1,3,2,5]
Output: [3,5]
Note:
The order of the result is not important. So in the above example, [5, 3] is also correc... |
import ITlib, numpy, re
stopwords = ["i'm","don't","it's","i'll","you're","the","of","and","to","a","in","for","is","on","that","by","this","with","i","you","it","not","or","be","are","from","at","as","your","all","have","new","more","an","was","we","will","home","can","us","about","if","page","my","has","search","fre... |
#!/usr/bin/env python
import argparse
import os.path
import data
def generate_data_set(in_file, out_file, mode, remove, fractions, count, epsilon, min_points):
for fraction in fractions:
loop_count = count if mode == data.RANDOM else 1
for i in range(loop_count):
print('\tGenerating ... |
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import itertools, collections
from sklearn import mixture, decomposition
from sklearn import cluster as sk_cluster
from matplotlib.patches import Ellipse, Circle, Rectangle
from scipy import fftpack, cluster
import h5py, copy
i... |
# The Morse code encodes every character as a sequence of "dots" and "dashes".
# For example, the letter A is coded as ·−, letter Q is coded as −−·−, and digit 1 is coded as ·−−−−.
# The Morse code is case-insensitive, traditionally capital letters are used.
# When the message is written in Morse code, a single s... |
# coding: utf-8
import collections
import weakref
class Node():
def __init__(self, top, key=None, lo=None, hi=None):
"""
top: nonnegative integer except for terminal nodes
key: unique key to identify the node
lo: the node that the 0-edge leads to
hi: the node that the 1-ed... |
import unittest
from fau import S16
class TestS16(unittest.TestCase):
def test_length_negative_throws_error(self):
with self.assertRaises(OverflowError):
S16(-1)
def test_length_zero_returns_correct_length(self):
s16 = S16(0)
self.assertEqual(0, len(s16))
def test_le... |
class ExtrusionAnalyzerFaceAlignment(Enum,IComparable,IFormattable,IConvertible):
"""
Indicates whether a face of the solid analyzed by ExtrusionAnalyzer is fully aligned,partially aligned,or unaligned with faces of the extrusion.
enum ExtrusionAnalyzerFaceAlignment,values: FullyAligned (0),PartiallyAligne... |
"""This module has a class which will analyse the usage of variables in the data request"""
import operator
import collections
class checkVar(object):
"""checkVar
--------
Class to analyse the usage of variables in the data request.
"""
errorLog = collections.defaultdict( set )
def __init__(self,dq,errorMode='ag... |
import numpy as np
from htsohm.db import Material
from numpy.random import choice
def choose_parent_bins_from_weighted_bin_list(bins, num_parents):
"""
bins: ((binx, biny), weight)
The weights of all the bins will be summed up and each bin will be normalized.
"""
bins.sort(key=lambda x: x[1])
... |
#!/usr/bin/env python
import random
import sqlite3
import sys
import string
def countEdges(n, matrix):
# count the number of edges
numedj = 0
for i in range(n):
for j in range(i):
if matrix[i][j] > 0:
numedj += 1
#print(numedj)
return int(numedj)
def deleteFirst(n, matrix):
for i in range(n):
for... |
"""
This module implements a Convolutional Neural Network in PyTorch.
You should fill in code into indicated sections.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
class ConvNet(nn.Module):
"""
This class implem... |
from collections import deque
def is_matched(expression):
left_symbols = '([{'
right_symbols = ')]}'
stack = deque()
for char in expression:
if char in left_symbols:
stack.append(char)
elif char in right_symbols:
if len(stack) < 1:
return False
... |
import mlflow
import hydra
from omegaconf import DictConfig
from pytorch_lightning.trainer import Trainer, seed_everything
from pytorch_lightning.callbacks import ModelCheckpoint
from pl_module import LightningModuleReg
from pl_data_module import ImageDataModule
from utils.util import git_commits
from utils.factory im... |
# -*- coding: utf-8 -*-
# Copyright 2018 IBM.
#
# 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 agre... |
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import os
import platform
import subprocess
from constants import SELECTORS... |
'''
Created on Feb 20, 2018
@author: enerve
'''
from __future__ import division
import logging
import numpy as np
import matplotlib.pyplot as plt
import ml_lib.util as util
def sigmoid(A):
e = np.exp(-A)
return 1 / (1 + e)
class Logistic(object):
'''
The Logistic Regression classifier, intended to ... |
from fastapi import APIRouter
from apps.todo.routes import crud
api_router = APIRouter()
api_router.include_router(crud.router, tags=["CRUD"])
|
#!/usr/bin/env python
from sys import argv
from argparse import menu
# check number of args at least needs a cmd
n = len(argv)
if n == 1:
print menu['help']['help']
exit()
else:
try:
print menu[argv[1]][argv[2]]
except:
print 'bi: ' + cmd + ': commmand not found'
|
from application import create_app
from dotenv import load_dotenv
from config_dev import Config
app = create_app(Config)
if __name__ == "__main__":
app.run(debug=True)
|
# Generated by Django 4.0.3 on 2022-04-03 15:47
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
import logging
import argparse
import sys
import os
from elasticsearch import Elasticsearch
from routines import DataPreprocessingRoutine, DataCompilationRoutine
from utils.elastic_utils import connect_es, create_es_index, load_es_index
from utils.data_utils import load_pkl_file
logging.basicConfig(level=logging.INFO... |
from tt.exceptz.exceptz import NoTask, BadArguments
def ensure_working(data):
if data.get('work') and 'end' not in data['work'][-1]:
return
raise NoTask("For all I know, you aren't working on anything. "
"I don't know what to do.\n"
"See `tt -h` to know how to start ... |
from ..utils import Object
class InputMessageVideoNote(Object):
"""
A video note message
Attributes:
ID (:obj:`str`): ``InputMessageVideoNote``
Args:
video_note (:class:`telegram.api.types.InputFile`):
Video note to be sent
thumbnail (:class:`telegram.api.type... |
#!/usr/bin/env python
import glob
import json
import math
import random
import sys
def gen_g(w, symmetric):
t = random.randrange(0, 3 if symmetric else 5)
if t == 0 and 1 < w // 3 : # center one
w1 = random.randrange(1, w // 3)
return [[0] * w1 + [1] * (w - 2 * w1) + [0] * w1]
elif t == 1 ... |
from nextcord.ext import commands
from nextcord import Embed, Colour
from Plugin import AutomataPlugin
from Globals import AOC_LEADERBOARD_CHANNEL, PRIMARY_GUILD
AOC_COLOUR = 0x01B204
class AOC(AutomataPlugin):
"""AOC 2021 Countdown"""
@staticmethod
def aoc_embed():
aoc_embed = Embed()
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
from os.path import dirname, join
from setuptools import (
find_packages,
setup,
)
try: # for pip >= 10
from pip._internal.req import parse_requirements
except ImportError: # for pip <= 9.0.3
from pip.req import parse_requirements
with open(join(dirna... |
from django.db import models
from django.db.models import fields
from django.forms import ModelForm
from .models import POST
class PostForm(ModelForm):
class Meta:
model = POST
fields = "__all__"
def __init__(self, *args, **kwargs):
super(PostForm, self).__init__(*args, **kwargs)
... |
# Copyright (c) 2016 The UUV Simulator 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 b... |
from typing import Any
class LLNode:
def __init__(self, data: Any = None) -> None:
self.data = data
self.next = None
def __repr__(self) -> str:
return f"LLNode({self.data})"
def __str__(self) -> str:
return str(self.data)
def __eq__(self, o: object) -> bool... |
# Generated by Django 3.2.6 on 2021-08-21 17:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop_list', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='shoplist',
name='created_at',
... |
# The MIT License (MIT)
#
# Copyright (c) 2017 Tony DiCola for Adafruit Industries
#
# 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 righ... |
import os
import pickle as pkl
from collections import Counter, defaultdict, namedtuple
from nltk import sent_tokenize
from tqdm import tqdm
from typing import List, DefaultDict, Tuple, Union, Dict
from yaml import safe_load
from db_handler import DBHandler
from model_predict import WordPredictModel
from utils import ... |
# Copyright 1999-2021 Alibaba Group Holding 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 a... |
import sys
import json
import datetime
import traceback
import smtplib
from email.mime.text import MIMEText
import main
# Attempt a sync; send failure email with traceback if error.
# Name of configuration is file passed via command-line
try:
print('Start sync at ' + str(datetime.datetime.now()))
main.init_co... |
import collections
from app.models.term import Term
def selectSurroundingTerms(currentTerm, prevTerms=2):
"""
Returns a list of term objects around the provided Term object for the current term.
Chooses the previous terms according to the prevTerms parameter (defaulting to 2),
and then chooses terms ... |
#!/usr/bin/env python
import sys
import os
from pycharm_run_utils import adjust_django_sys_path
from fix_getpass import fixGetpass
from _jb_utils import FileChangesTracker, jb_escape_output
try:
from runpy import run_module
except ImportError:
from runpy_compat import run_module
adjust_django_sys_path()
base... |
from rl.networks.networks import Network, PPONetwork
from rl.networks.architectures import shufflenet_v2
|
import json
from overrides import overrides
from allennlp.common.util import JsonDict
from allennlp.data import DatasetReader, Instance
from allennlp.data.tokenizers.word_splitter import SpacyWordSplitter
from allennlp.predictors.predictor import Predictor
from allennlp.models import Model
@Predictor.register('docqa... |
import torch
import torch.nn as nn
import torchvision.models as models
from PIL import Image
import torchvision.transforms as transforms
import os
import numpy as np
import json
import glob
class VggEncoder(nn.Module):
def __init__(self,tk_dim = 49, hidden_dim = 512, train_CNN=False):
super(VggEncoder, s... |
file = open('hello.txt')
print(file.read()) |
import torchvision
import os
import torch
from PIL import Image
# Lane detection as segmentation
class StandardLaneDetectionDataset(torchvision.datasets.VisionDataset):
def __init__(self, root, image_set, transforms=None, transform=None, target_transform=None, data_set='tusimple'):
super().__init__(root, ... |
from imgaug import augmenters as ia
from blox_old.bimgaug.augmenter import _CompositeAugmenter
from functools import partial
class Sequential(_CompositeAugmenter):
def __init__(self, children=None, seed=None, random_order=False, name=None):
super(Sequential, self).__init__(augmenter_fn=partial(ia.meta.Se... |
#item
from .frame import Frame
"""
Item
| name :str:
| buff :list:
|_cost :int:
Current Buffs
power
damage
"""
class Item:
def __init__(self, **kwargs):
self.name = kwargs.get('name', 'Item')
self.buff = kwargs.get('buff', [])
self.cost = kwargs.get('cost', 0)
@property
def fra... |
#1
sezen=['Bmw','Mercedes','Opel','Mazda']
print(sezen)
#2
print(len(sezen))
#3
print(sezen[0],'ve',sezen[-1])
#4
#sezenReplace=sezen
#sezenReplace[-1]='Toyota'
#print(sezenReplace)
#5
isEleman='Mercedes' in sezen
print("Mercedes, sezen'in elemanı mıdır?",isEleman)
#6
print(sezen[-2])
#7
#print(sezen[:3])
#8
#se... |
# импорт
from flask import url_for, render_template
from flask_mail import Message
from itsdangerous import URLSafeTimedSerializer
from app import app, mail
from .decorators import async
from config import SECRET_KEY, FLASK_MAIL_SENDER
# декоратор синхронной отправки письма
@async
def send_async_email(app, msg):
... |
import json, math, time
from common.constants import *
from common.user import User
import logging
logger = logging.getLogger("sys." + __name__.split(".")[-1])
gLogger = logging.getLogger("game." + __name__.split(".")[-1])
class Command(object):
"""
The common pattern for each command's apply is as follows:
... |
# coding=utf-8
import argparse
import errno
import os
import time
# from ..classes import load_simulation
import subprocess
import numpy as np
def config_filename(run_name, category_name=None, version_number=None):
"""
Prepares config filename for saving.
Parameters
----------
run_name : str
... |
# -*- coding: utf-8 -*-
import json
import sys
from flask import Flask
from flask import request
from flask_cors import CORS
reload(sys)
sys.setdefaultencoding('utf8')
# Defining Flask server
app = Flask(__name__)
app.config['SECRET_KEY'] = 'the quick brown fox jumps over the lazy dog'
app.config['CORS_HEADERS'] = ... |
import numpy as np
# In this module I'm going to construct
# an encoding() function that encodes channels and corresponding indices
# Then The decoding() function which do inverse
enc = {}
def encode(x):
# x1 : List of channels [tv, google, twitter, facebook, ...]
for i in range (0, len(x)):
enc[x[i]] ... |
import sys
import os
THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(1, "{0}/src/".format(THIS_FOLDER))
from helper import log,getConfig
from repositoryForked import repositoryForked
config = getConfig()
if config['repositoryForked']:
log('Setting Up Mirror For Forked Github Repository'... |
from typing import Dict
from urllib.parse import urljoin
import requests
from ansible.plugins.action import ActionBase
NS = "lilatomic_api_http"
class ConnectionInfo(object):
def __init__(self, base, kwargs=None):
self.base = base
self.kwargs = kwargs or {}
class ActionModule(ActionBase):
def run(self, tmp=... |
# SPDX-License-Identifier: MIT
#
# help.py - includes .help
#
# Copyright (c) 2019 Joe Dai.
import discord
from discord.ext import commands
class HelpCog:
def __init__(self, bot):
self.bot = bot
self.bot.remove_command('help')
# .help
@commands.group()
async def help(self, ctx):
... |
# -*- coding: utf-8 -*-
"""
File: serializers.py
Author: jackdan9
Date: 2018/8/18 12:14
"""
from rest_framework import serializers
from webfj_django_doutu.models import Table
class TableSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
title = serializers.CharField(required=Tr... |
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_socketio import SocketIO
db = SQLAlchemy()
login_manager = LoginManager()
socketio = SocketIO()
|
"""URLs file for Django. This will inspect the installed apps and only
include the read/write end points that are associated with the regcore_read
and regcore_write apps"""
from collections import defaultdict
from django.conf import settings
from django.conf.urls import patterns
from regcore_read.views import diff ... |
from ..lp_solver import LpSolver
from ..partitioning.pop import (
SmartSplitter,
BaselineSplitter,
GenericSplitter,
RandomSplitter,
RandomSplitter2,
)
from ..constants import NUM_CORES
from ..runtime_utils import parallelized_rt
from ..graph_utils import path_to_edge_list
from ..path_utils import fi... |
import pytest
def names(argvalue):
if isinstance(argvalue, (list,)):
return '-'
if argvalue.startswith("RRULE"):
return argvalue[6:]
return '-'
params = (
('rrule', 'dtstart', 'exdates', 'expected'),
[
[
"RRULE:FREQ=MONTHLY;BYMONTHDAY=15,30;COUNT=5",
... |
'''
File name: app.py
Authors:
Julien Aubuchon (1954203)
Marc Bussière (1959434)
Jean-Sébastien Patenaude (1961302)
Ava Tingaud (2179192)
Jeanne Tremblay (1855923)
Course: INF8808
Python Version: 3.8
'''
from cv2 import DFT_REAL_OUTPUT
from dash import Dash, dcc... |
import iotbx.file_reader
from cctbx.array_family import flex
import iotbx.phil
master_params_str = """
d_min = None
.type = float
d_max = None
.type = float
label = None
.type = str
"""
def run(mtzin, params):
arrays = iotbx.file_reader.any_file(mtzin).file_server.miller_arrays
if len(arrays) == 1:
... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
from contextlib import contextmanager
import os
import shutil
import subprocess
@contextmanager
def dir_changer(dirname, delete_dir):
"""
Context manager to do not forget change cwd back. Delete `dirname` after
if `delete_dir=True`
"""
old_cwd = os.getcwd()
os.chdir(dirname)
try:
y... |
import torch as torch
import torch.nn as nn
import torch.nn.functional as F
class Critic(nn.Module):
def __init__(self, ns_agent,ng_agent, dim_observation = 112, s_dim_action = 7,g_dim_action=5):
super(Critic, self).__init__()
self.n_agent = ns_agent+ng_agent
self.dim_observation = dim_obs... |
from pepys_import.file.highlighter.level import HighlightLevel
from pepys_import.file.highlighter.support.utils import merge_adjacent_text_locations
from .usages import SingleUsage
class SubToken:
"""
Object representing a single token at a lower level than Token.
Usually there is a single Sub... |
from lovpy.importer.gherkin_importer import convert_specification_to_graph
def get_counter_sample_properties():
rule1 = """WHEN returned by __add__
THEN NOT is_counter
""".replace('\n', '')
rule1 = ' '.join(rule1.split())
rule2 = """WHEN returned by range
THEN is... |
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from .models import Snack
class SnackTests(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(
username="test", email="test@email.com", password="pass"
... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云(BlueKing) available.
Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obt... |
from dotenv import load_dotenv
load_dotenv()
#from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient
def open_azure_input_stream():
raise NotImplementedError
def upload_to_azure_output_stream():
#json_output_stream.seek(0)
#data = json_output_stream.read().encode('utf-8')
... |
"""empty message
Revision ID: 808bc12e1fe5
Revises: b1aef99323cb
Create Date: 2018-08-22 18:32:24.696756
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '808bc12e1fe5'
down_revision = 'b1aef99323cb'
branch_labels = None
depends_on = None
def upgrade():
# ... |
from panda3d.core import *
from direct.distributed.DistributedObject import DistributedObject
from toontown.catalog import CatalogItemList
from toontown.catalog import CatalogItem
class DistributedDeliveryManager(DistributedObject):
neverDisable = 1
def sendHello(self, message):
self.sendUpdate('hello... |
"""
File Name: loss.py
Authors: Kyle Seidenthal
Date: 16-10-2020
Description: Custom loss functions for SPROUTNet Seg
| |!
|| |-
"""
import torch
import network_modules.evaluation_metrics as em
import torch.nn.functional as F
from torch.autograd import Variable
from torch import nn
def ... |
# encoding: utf-8
from __future__ import absolute_import, unicode_literals
import io
from mopidy.m3u import translator
from mopidy.models import Playlist, Ref, Track
def loads(s, basedir=b'.'):
return translator.load_items(io.StringIO(s), basedir=basedir)
def dumps(items):
fp = io.StringIO()
translat... |
"""
Home-grown replacement for networkx IN CASE this package is not found.
This implementation is not meant to be production-quality, but simply
a stub object that provides a reasonable implementation.
Note: Doesn't offer capability to draw graphs.
"""
import unittest
from algs.node import Node
# data associated with... |
import unittest
from unittest import TestCase
import gdk
import pytest
from gdk.commands.Command import Command
from gdk.common.exceptions.CommandError import ConflictingArgumentsError
class CommandTest(TestCase):
@pytest.fixture(autouse=True)
def __inject_fixtures(self, mocker):
self.mocker = mocker... |
import sys
def generate( header, source, language_files ):
print( "header: %s" % header )
print( "source: %s" % source )
print( "language_files:" )
for x in language_files:
print( "\t%s" % x )
out = open( header, "wb" )
out.write( """
#pragma once
#include <set>
#include <string>
#incl... |
import torch
import os
import random
import numpy as np
__all__ = ["accuracy", "AverageMeter"]
@torch.no_grad()
def accuracy(output, target, topk=(1,)):
"""Computes the accuracy over the k top predictions for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.... |
import keras
from keras_preprocessing import image
import keras.backend as K
import os
import numpy as np
import database_actions as db_actions
from triplet_loss import batch_all_triplet_loss
import tensorflow as tf
from tensorflow.python import debug as tf_debug
class Model:
def __init__(self):
self.mod... |
#
# Shared project unknown
#
import os
import unittest
import srutil
import srio
import credentials
class Test(unittest.TestCase):
def runTest(self):
user = credentials.SRSHAREUSER
token = credentials.SRSHARETOKEN
projName = 'TEST(suite1)-Project21' + '~' + credentials.SREMAIL
job... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-09-20 17:32
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('references', '0004_auto_20160920_1710'),
]
operations = [
migrations.Remove... |
from __future__ import absolute_import
from __future__ import unicode_literals
from datetime import datetime, time
from collections import namedtuple
from django import forms
from django.conf import settings
from django.utils.dateparse import parse_datetime
from django.utils import timezone
from django.utils.encodin... |
#!/opt/local/bin/python
from urllib.parse import urlparse
import os
import time
import requests as req
import re
import json
import datetime
import sys
import bigjson
from minerutils.auth import MinerWithAuthentication
class GitHub(MinerWithAuthentication):
root = 'https://api.github.com/'
paginationArg = 'per_pag... |
from flask import (
Blueprint,
Flask,
request,
render_template_string
)
from typing import (
List
)
from flask_ease.schemas import ResponseModel
from pydantic.main import ModelMetaclass
from flask_ease.utils import (
get_operation_id,
parse_response_model,
extract_params,
extract_dep... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.