text stringlengths 1 927k |
|---|
#!/usr/bin/env python
#coding:utf-8
# Author: mozman --<mozman@gmx.at>
# Purpose: validator2 module - new validator module
# Created: 01.10.2010
# Copyright (C) 2010, Manfred Moitzi
# License: MIT License
from .data import full11
from .data import tiny12
from .data import pattern
validator_cache = {}
def cache_key... |
# -*- coding: utf-8 -*-
## Copyright (c) 2015-2018, Exa Analytics Development Team
## Distributed under the terms of the Apache License 2.0
"""
Tests for :mod:`~exatomic.interfaces.cube`
#############################################
"""
import numpy as np
from unittest import TestCase
from exatomic.base import resource... |
"""
Test that stepping works even when the OS Plugin doesn't report
all threads at every stop.
"""
from __future__ import print_function
import os
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
import lldbsuite.test.lldbutil as lldbutil
class TestOSPluginStepping(TestBase... |
#!/usr/bin/python3
# BY NOMO
from netmiko import Netmiko
from getpass import getpass
from datetime import datetime
from pprint import pprint
import re
import os
import sys
import socket
# Vars
config_dir = "/home/reponeg/logs/asa_configs"
# Function for DNS resolution
def hostnameLookup(hostname):
try:
... |
#!/usr/bin/env python
import rospy
from dbw_mkz_msgs.msg import ThrottleCmd, SteeringCmd, BrakeCmd
from geometry_msgs.msg import TwistStamped
from std_msgs.msg import Bool
from twist_controller import Controller
'''
You can build this node only after you have built (or partially built) the `waypoint_updater` node.
Y... |
import yaml
from models.fasttext import FastText
from models.attention_rnn import AttentionRNN
from models.rcnn import RCNN
from models.textcnn import TextCNN
from models.textrnn import TextRNN
from models.transformer import Transformer
from utils.logger import get_logger
def instantiate_model(model_name, vocab_size... |
import datetime
import logging
from abc import ABCMeta, abstractmethod
from decimal import Decimal
from celery.result import EagerResult, allow_join_result
from celery.backends.base import DisabledBackend
logger = logging.getLogger(__name__)
PROGRESS_STATE = 'PROGRESS'
class AbstractProgressRecorder(object):
_... |
from shamrock.util.ints import uint64
from .constants import ConsensusConstants
testnet_kwargs = {
"SLOT_BLOCKS_TARGET": 32,
"MIN_BLOCKS_PER_CHALLENGE_BLOCK": 16, # Must be less than half of SLOT_BLOCKS_TARGET
"MAX_SUB_SLOT_BLOCKS": 128, # Must be less than half of SUB_EPOCH_BLOCKS
"NUM_SPS_SUB_SLOT... |
"""
This module will run as an independent thread and acts as a wrapper to orchestrate the training, testing, etc.
Supervised training is coordinated here
"""
from queue import Queue
from threading import Thread
from inf import runtime_data
def initialize():
return
class Controller:
def __init__(self):
... |
import re
from os import path
from setuptools import find_namespace_packages, setup
here = path.abspath(path.dirname(__file__))
with open(path.join(here, "src", "covid_health", "__init__.py")) as init:
__version__ = re.findall('__version__ = "([\w\.\-\_]+)"', init.read())[0]
with open(path.join(here, "README.... |
"""
Very minimal unittests for parts of the readline module.
"""
from contextlib import ExitStack
from errno import EIO
import locale
import os
import selectors
import subprocess
import sys
import tempfile
import unittest
from test.support import import_module, unlink, temp_dir, TESTFN, verbose
from test.support.script... |
# Copyright 2019 Canonical Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
# from .models import User
class SignUpForm(UserCreationForm):
username = forms.CharField(max_length=30, required=True)
first_name = forms.CharField(max_length=30, required=True)
las... |
# defusedxml
#
# Copyright (c) 2013 by Christian Heimes <christian@python.org>
# Licensed to PSF under a Contributor Agreement.
# See https://www.python.org/psf/license for licensing details.
"""Defuse XML bomb denial of service vulnerabilities
"""
from __future__ import print_function, absolute_import
from .common im... |
import os
import errno
import traceback
from six.moves import tkinter_messagebox as messagebox
from six import print_
class BrocoliError(Exception):
def __init__(self, exception):
self.exception = exception
def __str__(self):
return type(self.exception).__name__ + ': ' + str(self.exception)
... |
# The MIT License
#
# Copyright (c) 2017 Tarlan Payments.
#
# 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, modify... |
from baidu_spider import spider_main
rooturl = 'https://baike.baidu.com/item/Python/407313'
obj_spider = spider_main.SpiderMain()
obj_spider.craw(rooturl) |
import unittest
import os
from robot.running import userkeyword
from robot.running.model import ResourceFile, UserKeyword
from robot.running.userkeyword import UserLibrary
from robot.errors import DataError
from robot.utils.asserts import (assert_equal, assert_none,
assert_raises_with_... |
"""
python-socketio.py
Sample Mcity OCTANE python socketio script
"""
import os
from dotenv import load_dotenv
import socketio
#Load environment variables
load_dotenv()
api_key = os.environ.get('MCITY_OCTANE_KEY', None)
server = os.environ.get('MCITY_OCTANE_SERVER', 'http://localhost:5000')
namespace = "/octane"
#If... |
dataset_type = 'IcdarDataset'
data_root = 'data/icdar2015'
train = dict(
type=dataset_type,
ann_file=f'{data_root}/instances_training.json',
img_prefix=f'{data_root}/imgs',
pipeline=None)
test = dict(
type=dataset_type,
ann_file=f'{data_root}/instances_test.json',
img_prefix=f'{data_root}/... |
import gym
import pybullet_envs
from PIL import Image
import argparse
import numpy as np
import torch
import copy
import os
from sklearn.preprocessing import normalize as Normalize
from models import TD3, TD3_adv2
def parse_arguments():
parser = argparse.ArgumentParser("TESTING")
parser.add_argument('-p', "-... |
"""Load dependencies needed to compile p4c as a 3rd-party consumer."""
load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def p4c_deps():
"""Loads dependencies need to compile p4c."""
# Third party projects can define the... |
import pandas as pd
import plotly.express as px
url = 'https://health-infobase.canada.ca/src/data/covidLive/covid19-epiSummary-voc.csv'
prov_dict = {
"AB" : "Alberta",
"BC" : "British Columbia",
"CA" : "Canada",
"MB" : "Manitoba",
"NB" : "New Brunswick",
"NL" : "Newfoundland and Labrador",
"NS" : "Nova Scot... |
# Random Point in Non-overlapping Rectangles
'''
Given a list of non-overlapping axis-aligned rectangles rects, write a function pick which randomly and uniformily picks an integer point in the space covered by the rectangles.
Note:
An integer point is a point that has integer coordinates.
A point on the perimeter ... |
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
class TwoLayerNet(object):
"""
A two-layer fully-connected neural network. The net has an input dimension of
N, a hidden layer dimension of H, and performs classification over C classes.
We train the network with a softma... |
# coding: utf-8
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mainconfig.settings')
application = get_wsgi_application() |
from sys import maxsize
class Group:
def __init__(self, name=None, header=None, footer=None, id=None):
self.name = name
self.header = header
self.footer = footer
self.id = id
def __repr__(self):
return "%s:%s:%s:%s" % (self.id, self.name, self.header,self.footer)
... |
"""
@param: n -> int : Upper Limit of the range
"""
def multiples(n: int) -> int:
num: list = []
for i in range(1, n):
if (i % 3 == 0) or (i % 5 == 0):
num.append(i)
return sum(num)
if __name__ == '__main__':
t: int = int(input())
for _x in range(t):
n: int = int(input(... |
class Solution:
r"""
函数注解
>>> def add(x: int, y: int) -> int:
... return a + b
>>> add.__annotations__
{'x': <class 'int'>, 'y': <class 'int'>, 'return': <class 'int'>}
"""
def __init__(self):
pass
def solve(self):
pass
if __name__ == '__main__':
import do... |
# module for the <archdesc/> or collection-level description
import xml.etree.cElementTree as ET
from archdescsimple import archdescsimple
from access_use_restrict import access_use_restrict
import globals
import wx
def archdesc(arch_root, CSheet, version, input_data):
from wx.lib.pubsub import pub
#update GUI p... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-10-17 05:50
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('stream', '0016_auto_20161012_0838'),
]
operations = [
migrations.AddField(
... |
import copy
from gym import Wrapper
from pythogic.base.Symbol import Symbol
from pythogic.base.Alphabet import Alphabet
from pythogic.base.Formula import AtomicFormula, PathExpressionEventually, PathExpressionSequence, And, Not, \
LogicalTrue, PathExpressionStar
from pythogic.base.utils import _to_pythomata_dfa
fro... |
from django.contrib import admin
from krankit.polls.models import Question, Choice, ChoiceVote
admin.site.register(Question)
admin.site.register(Choice)
admin.site.register(ChoiceVote) |
import src.tnet as tnet
import matplotlib.pyplot as plt
import matplotlib as mpl
import pandas as pd
import math
plt.style.use(['science','ieee', 'high-vis'])
def txt2list(fname):
return [line for line in open(fname)]
def read_result(fname):
df = pd.read_csv(fname)
results = df.T.values.tolist()
return resu... |
class BinTree:
def __init__(self):
'''Container for structuring and handling all nodes used in an option-like asset.
Creates a generic binomial option tree whose by planting an option.
Ha, what?
'''
class Binodes:
def __init__(self, u_node, d_node):
... |
"""
Django settings for profiles_project project.
Generated by 'django-admin startproject' using Django 2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
impor... |
import random
import torch
import sys
from contextlib import closing
from torch.multiprocessing import Pool
from random import randint
from exploration_strategies.OUNoise import OrnsteinUhlenbeckActionNoise
class Parallel_Experience_Generator(object):
""" Plays n episode in parallel using a fixed agent. """
... |
import copy
import os
import re
from typing import Any, Dict, List, Optional, Set, Tuple
from unittest import mock
import ujson
from django.conf import settings
from django.test import TestCase, override_settings
from zerver.lib import bugdown, mdiff
from zerver.lib.actions import (
do_add_alert_words,
do_rem... |
from .types import *
from .row import *
from .column import *
from .utils import scope
from .session import * |
###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2021, John McNamara, jmcnamara@cpan.org
#
import unittest
from ...compatibility import StringIO
from ...worksheet import Worksheet
class TestWriteSheetFormatPr(unittest.TestCase):
"""... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from google.ads.google_ads.v1.proto.resources import location_view_pb2 as google_dot_ads_dot_googleads__v1_dot_proto_dot_resources_dot_location__view__pb2
from google.ads.google_ads.v1.proto.services import location_view_service_pb2 as g... |
# -*- coding: utf-8 -*-
# Copyright (c) 2018, frappe and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
import unittest
class TestTest(unittest.TestCase):
pass |
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... |
import sqlite3
from db import db
class StoreModel(db.Model):
__tablename__ = 'stores'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80))
items = db.relationship('ItemModel', lazy='dynamic')
def __init__(self, _id, name):
self.id = _id
self.name = name
... |
import sys
import json
import datetime
from terminalplot import plot
from balsam.launcher.dag import BalsamJob
now = '_'.join(str(datetime.datetime.now(datetime.timezone.utc)).split(" "))
def max_list(l):
rl = [l[0]]
mx = l[0]
for i in range(1, len(l)):
mx = max(mx, l[i])
rl.append(mx)
... |
from . import axes_size as Size
from .axes_divider import Divider, SubplotDivider, LocatableAxes, \
make_axes_locatable
from .axes_grid import Grid, ImageGrid, AxesGrid
#from axes_divider import make_axes_locatable
from matplotlib.cbook import warn_deprecated
warn_deprecated(since='2.1',
name='mpl_... |
import intcode
INPUT_FILE = 'day005.in'
def part1(filename):
source = intcode.load_from_file(filename)
i, o = [], []
# AC Unit input value
i.append(1)
modified = intcode.run_intcode(source, i, o)
return modified[0], i, o
def part2(filename):
source = intcode.load_from_file(filename)
... |
# -*- coding: utf-8 -*-
"""Utilities for working with VPC subnets."""
from . import client as boto3client
def create(profile, cidr_block, vpc, availability_zone=None):
"""Create a subnet in a VPC.
Args:
profile
A profile to connect to AWS with.
cidr_block
The netwo... |
#!/usr/bin/env python3
# Copyright 2016 The Dart project authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import os
import subprocess
import sys
import time
import utils
HOST_OS = utils.GuessOS()
HOST_ARCH = utils.Guess... |
from test_support import verbose, TestFailed, TestSkipped
import nis
print 'nis.maps()'
try:
maps = nis.maps()
except nis.error, msg:
# NIS is probably not active, so this test isn't useful
if verbose:
raise TestFailed, msg
# only do this if running under the regression suite
raise TestSkip... |
import os
from tkinter import *
import db_save
filepath = os.path.dirname(__file__)
icon_eq = os.path.join(filepath, "data\\pics\\pleczak.ico")
tlos = os.path.join(filepath, "data\\pics\\hg.png")
tloe = os.path.join(filepath, "data\\pics\\hp.png")
def informacja(tresc, zrodlo_pliku):
eq = "☆ Otrzymujesz " + tr... |
import random, re, time, uuid
from dtest import Tester, debug
from pytools import since
from pyassertions import assert_invalid
from cassandra import InvalidRequest
from cassandra.query import BatchStatement, SimpleStatement
from cassandra.protocol import ConfigurationException
class TestSecondaryIndexes(Tester):
... |
''' Compute on ANVIL GTEX files'''
# IMPORTS
import sys
import json
from fasp.runner import FASPRunner
# The implementations we're using
from fasp.loc import Gen3DRSClient
from fasp.workflow import GCPLSsamtools
from fasp.loc import anvilDRSClient
class localSearchClient:
def __init__(self):
# edit the follo... |
from apscheduler.schedulers.blocking import BlockingScheduler
from internals.sensors import get_sensors_data
from internals.constants import plants_csv, moisture_alarm, template_email, output_email, \
from_email, to_email, interval_minutes
from internals.utils import get_dry_plants, insert_text_into_mail_body, gene... |
# -*- coding: utf-8 -*-
"""
flask_login.utils
-----------------
General utilities.
"""
import hmac
from hashlib import sha512
from functools import wraps
from werkzeug.local import LocalProxy
from werkzeug.security import safe_str_cmp
from werkzeug.urls import url_decode, url_encode
from flask import (
... |
import pybullet as p
import pybullet_data
p.connect(p.GUI)
p.setAdditionalSearchPath(pybullet_data.getDataPath())
cube = p.loadURDF("cube.urdf")
frequency = 240
timeStep = 1. / frequency
p.setGravity(0, 0, -9.8)
p.changeDynamics(cube, -1, linearDamping=0, angularDamping=0)
p.setPhysicsEngineParameter(fixedTimeStep=tim... |
#https://channels.readthedocs.io/en/latest/installation.html
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import website.routing
application = ProtocolTypeRouter({
# (http->django views is added by default)
'websocket': AuthMiddlewareStack(
U... |
# -*- coding: utf-8 -*-
import numpy as np
from PIL import Image
# /////////////// Corruption Helpers ///////////////
import skimage as sk
from torchvision import transforms
import torchvision.transforms.functional as F
from skimage.filters import gaussian
from io import BytesIO
from wand.image import Image as WandI... |
#!/usr/bin/env python3
'''
Use the Neural Engineering framework to solve Pendulum via an elitist GA
Copyright (C) 2020 Simon D. Levy
MIT License
'''
from lib import NefGym
from sys import argv
import pickle
import numpy as np
from sueap.algorithms.elitist import Elitist
class NefPendulum(NefGym):
def __init__... |
import networkx as nx
g = nx.Graph([x.split(")") for x in open("input.txt").read().splitlines()])
print(sum([nx.shortest_path_length(g, "COM", x) for x in g.nodes]))
print(nx.shortest_path_length(g, "YOU", "SAN") - 2) |
###############################################################################
# Author: Daniil Budanov
# Contact: danbudanov@gmail.com
# Summer Internship - 2016
###############################################################################
# Title: __init__.py
# Project: Security System
# Description:
# package d... |
from .alphavantage import AlphaVantage as av
class TimeSeries(av):
"""This class implements all the api calls to times series
"""
@av._output_format
@av._call_api_on_func
def get_intraday(self, symbol, interval='15min', outputsize='compact'):
""" Return intraday time series in two json ob... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import astropy
from scipy.spatial import cKDTree
import numpy as np
import matplotlib.pyplot as plt
data=np.genfromtxt('ybs.degbv',names=True)
messier=np.genfromtxt('Messierdec.txt',names=True)
vlim=4.5
magscale=10
starsize=magscale*(vl... |
import time
from collections import deque
import gym
import numpy as np
import tensorflow as tf
from stable_baselines import logger
from stable_baselines.common import explained_variance, tf_util, ActorCriticRLModel, SetVerbosity, TensorboardWriter
from stable_baselines.common.policies import ActorCriticPolicy, Recur... |
import os
import pandas as pd
import requests
from datetime import datetime
from furl import furl
SQUASH_API_URL = os.environ.get('SQUASH_API_URL',
'http://localhost:8000/dashboard/api/')
def get_endpoint_urls():
"""
Lookup API endpoint URLs
"""
r = requests.get(SQUAS... |
import time
jobNumber=10
for i in range(jobNumber):
qsub_command = "qsub job.sh"
print(qsub_command)
exit_status = subprocess.call(qsub_command, shell=True)
time.sleep(6) |
from tkinter import *
import tkinter as tk
import studenttracking_main
import studenttracking_fnct
def load_gui(self):
self.lbl_subform = tk.Label(self.master,text='Submission Form')
self.lbl_subform.grid(row=0,column=1,padx=(27,0),pady=(10,0),sticky=N+W)
self.lbl_fname = tk.Label(self.master,text='First ... |
from datetime import datetime, timedelta
from djmail.template_mail import MagicMailBuilder, InlineCSSTemplateMail
from unittest.mock import patch
from django_comments import get_form_target
from django_comments.models import Comment
from django_comments.signals import comment_was_posted
from django.contrib.contenttyp... |
import json
import uuid
import os
from datetime import datetime
from flask import current_app, request, Response, abort, send_from_directory
from webargs import fields
from webargs.flaskparser import use_args, FlaskParser
from enum import Enum
from random import seed, randint
from .. import socketio
from . import main... |
#!/usr/bin/env python
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# TODO(hinoka): Use logging.
import cStringIO
import codecs
import copy
import ctypes
import json
import optparse
import os
import ppr... |
from django.core.management.base import BaseCommand, CommandError
from results.models import ResultStage, ResultCheck
def count_result(model_arg):
if model_arg == "resultcheck":
result_count = ResultCheck.objects.all().count()
else:
result_count = ResultStage.objects.all().count()
return r... |
try:
from BytesIO import BytesIO
except ImportError:
from io import BytesIO
from pyecore.resources import URI
class BytesURI(URI):
def __init__(self, uri, text=None):
super(BytesURI, self).__init__(uri)
if text is not None:
self.__stream = BytesIO(text)
def getvalue(self)... |
#!/usr/bin/python -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
"""Wordcount exercise
Google's Python class
The main() below is already defined and comp... |
import util
import json
import numpy as np
import random
import tensorflow as tf
class DeepDog:
"""
The DeepDog class loads the training and test set images from
disk into RAM, and provides functions to get the test set
and mini batches of the training set.
"""
def __init__(self, imageWidth, ... |
from rest_framework import serializers
class HelloSerializer(serializers.Serializer):
"""Serializes a name field for testing our APIView"""
name = serializers.CharField(max_length=10) |
import os
from functools import partial
import PIL
import lmdb
import numpy as np
from ding.envs import SyncSubprocessEnvManager
from ding.utils.default_helper import deep_merge_dicts
from easydict import EasyDict
from tqdm import tqdm
from haco.DIDrive_core.data import CarlaBenchmarkCollector, BenchmarkDatasetSaver
... |
from django.test import TestCase
from game.ai import TicTacToeAI
class TicTacToeAITest(TestCase):
def setUp(self):
board_state = [['o', ' ', 'x'],
['x', ' ', ' '],
['x', 'o', 'o']]
self.g = TicTacToeAI(board_state)
def test_possible_moves(self)... |
# -*- coding: utf-8 -*-
from typing import Union
class PortBindingGuest:
__slots__ = ("port", "protocol")
port: int
protocol: str
def __init__(self, port: Union[int, str], protocol: str):
if isinstance(port, int):
self.port = port
else:
self.port = int(port)... |
#
# Copyright 2018 Analytics Zoo 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 applicable law or agreed to... |
# Copyright (c) 2021 Lan Peng and Chase Murray
# Licensed under the MIT License. See LICENSING for details.
from veroviz._common import *
from veroviz._internal import locs2Dict
from veroviz._internal import loc2Dict
from veroviz._geometry import geoDistance2D
def pgrGetSnapToRoadLatLon(gid, loc, databaseName):
"""
... |
"""This module contains the general information for PciEquipSlot ManagedObject."""
from ...imcmo import ManagedObject
from ...imccoremeta import MoPropertyMeta, MoMeta
from ...imcmeta import VersionMeta
class PciEquipSlotConsts:
pass
class PciEquipSlot(ManagedObject):
"""This is PciEquipSlot class."""
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 28 13:42:30 2017
@author: hexo
"""
import numpy as np
import pandas as pd
#读取第一个sheet页
df = pd.read_excel('D:\Tableau_data\示例 - 超市.xls',sheetname=0)
print(type(df))
#每一列的数据类型
print(df.dtypes)
#每种类型的数量
print(df.get_dtype_counts())
#还不知道这个ftype到底是干嘛的,sparse|dense,稀疏|密集... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-08-01 03:00
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0001_initial'),
]
operations = [
migrations.AddField(
m... |
from rest_framework import generics, authentication, permissions
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.settings import api_settings
from user.serializers import UserSerailizer, AuthTokenSerializer
class CreateUserView(generics.CreateAPIView):
serializer_class = UserSeraili... |
# Copyright 2013 IBM Corp.
#
# 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 t... |
# pylint: disable=fixme, protected-access
"""The core module contains the SoCo class that implements
the main entry to the SoCo functionality
"""
import datetime
import logging
import re
import socket
from functools import wraps
from xml.sax.saxutils import escape
from xml.parsers.expat import ExpatError
import warni... |
'''Wheels support.'''
from distutils.util import get_platform
import email
import itertools
import os
import re
import zipfile
from pkg_resources import Distribution, PathMetadata, parse_version
from pkg_resources.extern.six import PY3
from setuptools import Distribution as SetuptoolsDistribution
from setuptools impo... |
#
# Generated with MetoceanFatigueAnalysisBlueprint
from dmt.blueprint import Blueprint
from dmt.dimension import Dimension
from dmt.attribute import Attribute
from dmt.enum_attribute import EnumAttribute
from dmt.blueprint_attribute import BlueprintAttribute
from sima.sima.blueprints.condition import ConditionBluepri... |
from django.contrib import admin
from django.contrib.auth import admin as auth_admin
from django.contrib.auth import get_user_model
from feedbackproj.users.forms import UserChangeForm, UserCreationForm
User = get_user_model()
@admin.register(User)
class UserAdmin(auth_admin.UserAdmin):
form = UserChangeForm
... |
#!/usr/bin/env python
import boto3
import sys
import argparse
import ast
import urllib2
from subprocess import call
import time
from datetime import datetime
import shlex
def sqs_get_msg(qname):
sqs = boto3.resource('sqs')
queue = sqs.get_queue_by_name(QueueName=qname)
client = boto3.client('sqs')
me... |
import argparse
import json
import os
import _jsonnet
import tqdm
from seq2struct import datasets
from seq2struct import models
from seq2struct.utils import registry
from seq2struct.utils import vocab
class Preprocessor:
def __init__(self, config):
self.config = config
self.model_preproc = regist... |
import torch.nn as nn
import torch
import numpy as np
def compute_flops(module, inp, out):
if isinstance(module, nn.Conv2d):
return compute_Conv2d_flops(module, inp, out)
elif isinstance(module, nn.BatchNorm2d):
return compute_BatchNorm2d_flops(module, inp, out)
elif isinstance(module, (nn... |
# module solution.py
#
# Copyright (c) 2018 Rafael Reis
#
"""
solution module - Implements Solution, a class that describes a solution for the problem.
"""
__version__ = "1.0"
import copy
import sys
from random import shuffle
import numpy as np
def random(pctsp, start_size):
s = Solution(pctsp)
length = le... |
import numpy as np
from ._CFunctions import _CWithinTimeRange
from ._CTConv import _CTConv
def WithinTimeRange(Timet,Time0,Time1,BoolOut=False):
'''
Performs a simple check on a test time (Timet) to see if it exists
between Time0 and time1.
Inputs
======
Timet : tuple | float
Test time - either a single flo... |
from hangul_romanize import Transliter
from hangul_romanize.rule import academic
class Word:
"""
Object representation of a word record that can update the success_rating of that record.
"""
_romanize = Transliter(academic).translit
def __init__(self, _id: int, english: str, korean: str, score: i... |
import numpy as np
import scipy.special as sp
from termcolor import colored
import sys
if sys.platform == 'linux':
sys.path.append(r'../lib')
else:
sys.path.append(r'../build/x64/Release')
import NumCpp
####################################################################################
NUM_DECIMALS_ROUND = 1... |
# -*- coding: utf-8 -*-
# Define here the models for your spider middleware
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/spider-middleware.html
from scrapy.conf import settings
import os
import random
class RandomUserAgentMiddleware(object):
def process_request(self, request, spider):
... |
'''OpenGL extension AMD.framebuffer_multisample_advanced
This module customises the behaviour of the
OpenGL.raw.GL.AMD.framebuffer_multisample_advanced to provide a more
Python-friendly API
Overview (from the spec)
This extension extends ARB_framebuffer_object by allowing compromises
between image quality and m... |
import logging
import os
import uuid
from distutils import util
from pathlib import Path
import pytest
import test_infra.utils as infra_utils
from test_infra import assisted_service_api, consts, utils
qe_env = False
def is_qe_env():
return os.environ.get('NODE_ENV') == 'QE_VM'
def _get_cluster_name():
clu... |
# coding: utf-8
"""
This is part of the MSS Python's module.
Source: https://github.com/BoboTiG/python-mss
"""
import platform
from .exception import ScreenShotError
def mss(**kwargs):
# type: (**str) -> MSS
""" Factory returning a proper MSS class instance.
It detects the plateform we are running ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.