text stringlengths 1 927k |
|---|
# Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import ConvModule, build_activation_layer, build_norm_layer
from mmcv.cnn.bricks.transformer import (FFN, TRANSFORMER_LAYER,
MultiheadAttention,
... |
# Copyright 2020 Alibaba Group Holding Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... |
# file openpyxl/writer/strings.py
# Copyright (c) 2010 openpyxl
#
# 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 logging
import sys
from vax_common.vax_config import get_config
from vax_generator.vax_generator import VaxGenerator
logging.basicConfig(stream=sys.stderr, level=logging.INFO)
def main():
generator = VaxGenerator(get_config())
generator.run()
if __name__ == "__main__":
main() |
# coding: utf-8
"""
vloadbalancer
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from ncloud_vloadbalancer.model.load_balancer_instance import LoadBalancerInstance # noqa: F401,E501
class GetLoadBalancerInstanceListResponse(obj... |
# -*- coding: utf-8 -*-
# Copyright (c) 2021, orlando and Contributors
# See license.txt
from __future__ import unicode_literals
# import frappe
import unittest
class Testanalisis_capital(unittest.TestCase):
pass |
# Configuration file for jupyter-notebook.
#------------------------------------------------------------------------------
# Configurable configuration
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
# Sing... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2019-05-23 13:08
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('instagram', '0005_auto_20190523_1540'),
]
operations = [
migrations.AddField(... |
#!/usr/bin/env python3
# For information about the design of the worker, see design.pdf in the same
# directory as this file. For information about running a worker, see the
# tutorial on the CodaLab documentation.
import argparse
import getpass
import os
import logging
import signal
import socket
import stat
import s... |
#!/usr/bin/env python
"""
Reads GLA12 Release 634 HDF5.
Reads several files in parallel if njobs > 1 is specified.
Extracts a subset of the data based on a mask.tif file.
Example:
python readgla.py /mnt/devon-r0/shared_data/icesat/GLAH12.034/ /mnt/devon-r0/shared_data/icesat/grou... |
#!/usr/bin/env python3
import fire
import json
import os
import re
import numpy as np
import tensorflow as tf
import model, sample, encoder
def modify_raw_text(raw_text, interviewer, interviewee):
return interviewer+": \"" + raw_text + "\" "+ interviewee +":\""
def interact_model(
model_name='124M',
see... |
# 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 agree... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 28 09:28:54 2021
@author: Jian Cao
Collect Tweets from Twitter API (Stream, REST, Lab-COVID19)
"""
## Set environment ------------------------------------------------------------
# import os
import time
import json
import requests
import uuid
import multiprocessing
from... |
import pytest
import numpy as np
from numpy import cos, sin
from cxroots import Circle, Rectangle
from cxroots import CxDerivative
@pytest.mark.parametrize('C', [
pytest.param(Circle(0, 2), id='circle'),
pytest.param(Rectangle([-1.5,1.5],[-2,2]), id='rect'),
pytest.param(None, id='default')
])
def test_Cx... |
from functools import reduce
import re
import json
import fhirpathpy.engine as engine
import fhirpathpy.engine.util as util
import fhirpathpy.engine.nodes as nodes
def boolean_literal(ctx, parentData, node):
if node["text"] == "true":
return [True]
return [False]
def number_literal(ctx, parentData,... |
# stdlib
import logging
import sys
import unittest
import mock
# project
from checks.system.unix import (
IO,
Load,
Memory,
)
from checks.system.unix import System
from config import get_system_stats
from utils.platform import Platform
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__... |
"""
Misc functions.
"""
import ipaddress
import datetime
import hashlib
import json
import netaddr
import netifaces
import os
import re
import requests
import scapy.all as sc
import socket
import subprocess
import sys
import threading
import time
import traceback
import uuid
import webbrowser
import server_config
... |
import os
import pickle
import pandas as pd
from sklearn.cluster import DBSCAN
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report
from sklearn.preprocessing import LabelEncoder
from tensorflow.keras.callbacks import ModelCheckpoint
from tensorflow.keras.layers import D... |
# -*- coding: utf-8 -*-
# https://github.com/Kodi-vStream/venom-xbmc-addons
# Venom.
# vstream = xbmcaddon.Addon('plugin.video.vstream')
# sLibrary = xbmc.translatePath(vstream.getAddonInfo("path")).decode("utf-8")
# sys.path.append (sLibrary)
from resources.lib.comaddon import addon, dialog, VSlog, xbmc, xbmcgui, wi... |
"""Add this directory to your python path""" |
# -*- coding: utf-8 -*-
import os
import struct
from contextlib import contextmanager
from functools import partial
from io import BufferedReader, UnsupportedOperation
from subprocess import call
from zipfile import BadZipFile, ZipFile
from tqdm import tqdm
import time
from emstore.open import open_leveldb
import thre... |
# (c) 2014, Brian Coca, Josh Drake, et al
# (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = '''
author: Unknown (!UNKNOWN)
cache: memcac... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: v1.20.7
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unitte... |
from .module_wifi import * |
import os
import sys
from zipfile import *
import zipfile
import shutil
def zipDir(filename,destDir,index,resultDir):
currentPath = os.getcwd()
#global resultDir
if len(resultDir) == 0 :
resultDir = currentPath
if not os.path.exists(resultDir):
os.makedirs(resultDir)
f = zipfil... |
from fastapi import FastAPI, Depends
from fastapi.middleware.cors import CORSMiddleware
from auth.jwt_bearer import JWTBearer
# from routes.student import router as StudentRouter
# from routes.admin import router as AdminRouter
from routes.user import router as UserRouter
from routes.teacher import router as TeacherRou... |
from flask import Blueprint
from flask_restful import Api
from .get_topic_schema import GetTopicSchemaResource
from .get_topic_names import GetTopicNamesResource
rest_topic_bp = Blueprint("rest_topic", __name__)
rest_topic_api = Api(rest_topic_bp, prefix="/api")
rest_topic_api.add_resource(GetTopicSchemaResource, G... |
# coding: utf-8
# Copyright 2019, 2020 IBM All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
from configparser import ConfigParser
import numpy as np
from sklearn.metrics import mean_squared_error, r2_score
import pygmo as pg
from tengp.individual import IndividualBuilder, NPIndividual
from tengp import Parameters, FunctionSet
from tengp_eval.coevolution import TrainersSet, GaPredictors
def fitness_functio... |
# 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 ... |
import traceback
from utils import *
async def assign_default_role(client, member, role_name):
roles = list(filter(lambda k: k.name == role_name, member.server.roles))
if len(roles) == 0:
return
await client.add_roles(member, roles[0])
async def notify_of_leaving_person(client, member):
bot... |
import os
import sys
if __name__ == '__main__':
if len(sys.argv) < 2:
print 'usage: <path> <old ext> <new ext>'
sys.exit()
change_count = 0
for root, dirs, files in os.walk(sys.argv[1]):
for dir in dirs:
if dir.endswith(sys.argv[2]):
print dir
... |
from models.connection import get_cnx, tables
judge_table = tables["judge"]
conflict_table = tables["conflict"]
ballots_table = tables["ballot"]
ballot_matchup_table = tables["ballot_matchup_info"]
class Judge:
@staticmethod
def add_judge(tournament_id: int, name: str):
with get_cnx() as db:
... |
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
import clr
clr.AddReference("System.Net")
class NetworkInterfaceWrapper:
def __init__(self, networkInterface) -> None:
self.__ni = networkInterface
@property
def Id(self) -> str:
return self.__ni.Id
@property
def Description(self) -> str:
return self.__ni.Description
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from django.db.models import Sum
from django.db.models.aggregates import Count
from django.utils import timezone
from ona... |
import os
from xml.etree.ElementInclude import include
from flask import Flask
from .db import mongo
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY='testing',
)
if test_config is No... |
import json
from decimal import Decimal
from django.db import models
from django.utils.timezone import now
import pytest
from django_unicorn import serializer
from django_unicorn.utils import dicts_equal
from example.coffee.models import Flavor
class SimpleTestModel(models.Model):
name = models.CharField(max_l... |
#!/usr/bin/env python3
import base64
magic = """
eJxlkMlOwzAQhu88xdBLHKiiEprSIvVCCUvpoqhARQ9Ijj1JTLPJdhDh6XHa0rLMxcvM9/8zwzGCqMq
JfXkEJtZYwxBCy5v47tj3nm+m41l/dTuaDebBJLgLXi7G/nT0dG9tqkvK1sgNYPE4OF3UfZfG63q8mA
5WdSebXt0s54/B6Vz4g9ky9h7e+h+T62BoHW1gbpwxZ7Iu.....9Rl5p7LdmO/aaEKirmQOYa1REQqv
EEJUSKBtcxE5fIryQNlbyVKKXJPWHaZ... |
from model.group import Group
def test_group_list(app, db):
ui_list = app.group.get_group_list()
def clean(group):
return Group(id=group.id, name=group.name.strip())
db_list = map(clean, db.get_group_list())
assert sorted(ui_list, key=Group.id_or_max) == sorted (db_list, key=Group.id_or_max) |
import kbr.db_utils as db
class DB(object):
def connect(self, url: str) -> None:
self._db = db.DB(url)
def disconnect(self) -> None:
if self._db is not None:
self._db.close()
def projects(self, **values) -> dict:
return self._db.get('project', **values)
def pr... |
'''This job updates the minute-by-minute trading data for the whole available
futures universe.
'''
'''
Copyright (c) 2017, WinQuant Information and Technology Co. Ltd.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following condi... |
# coding: utf-8
"""
OpenAPI Petstore
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
"""
... |
# ============================================================================
# FILE: view.py
# AUTHOR: Shougo Matsushita <Shougo.Matsu at gmail.com>
# License: MIT license
# ============================================================================
from pathlib import Path
from pynvim import Nvim
from pynvim.api i... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... |
# Copyright (c) 2019. Partners HealthCare and other members of
# Forome Association
#
# Developed by Sergey Trifonov based on contributions by Joel Krier,
# Michael Bouzinier, Shamil Sunyaev and other members of Division of
# Genetics, Brigham and Women's Hospital
#
# Licensed under the Apache License, Version 2.... |
# Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2.0, as
# published by the Free Software Foundation.
#
# This program is also distributed with certain s... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#self.listProduct
#self.label
import os.path
import classes as cl
import datetime
import qdarkstyle
import re
import csv
import sys
import subprocess
from PyQt4 import QtGui, QtCore, uic
cl.load()
options = {'Containers':cl.inv.listAllContainers,
'Product':cl.... |
import serial
# serial communication params
SERIAL_PORT = "/dev/ttyUSB0"
DEFAULT_BAUD_RATE = 9600
class ArduinoControlService:
def __init__(self, port=SERIAL_PORT, baud_rate=DEFAULT_BAUD_RATE):
self._controller = serial.Serial(port, baud_rate)
self._state = 0
# public methods
def get_sta... |
import pytest
from _pytest.config import ExitCode
from _pytest.monkeypatch import MonkeyPatch
from _pytest.pytester import Pytester
class SessionTests:
def test_basic_testitem_events(self, pytester: Pytester) -> None:
tfile = pytester.makepyfile(
"""
def test_one():
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 26 20:45:10 2016
@author: DIP
"""
from lib.contractions import CONTRACTION_MAP
import re
import nltk
import string
from nltk.stem import WordNetLemmatizer
from html.parser import HTMLParser
import unicodedata
stopword_list = nltk.corpus.stopwords.words('english')
wnl =... |
#!/usr/bin/env python
import re
import setuptools
import sys
setuptools.setup(
setup_requires=['pbr', 'pytest-runner'],
tests_require=['pytest'],
pbr=True) |
# -*- coding: utf-8 -*-
from spaceone.core.manager import BaseManager
from spaceone.secret.connector.identity_connector import IdentityConnector
class IdentityManager(BaseManager):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.identity_conn: IdentityConnector = self.... |
''' init for hg_tweetfeeder module '''
from hg_tweetfeeder.bot import TweetFeeder, BotFunctions, BotEvents
from hg_tweetfeeder.config import Config
from hg_tweetfeeder.file_io import LoadFromFile
from hg_tweetfeeder.flags import BotFunctions
__author__ = 'Ian M. <hagudegozaru@gmail.com>'
__version__ = '0.0.1' |
import re
def camel_to_snake(phrase):
s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", phrase)
return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower() |
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
# Copyright (C) 2017 TU Dresden
# Licensed under the ISC license (see LICENSE.txt)
#
# Authors: Christian Menard
from mocasin.util import logging
from mocasin.simulate.channel import RuntimeChannel
from mocasin.simulate.process import RuntimeDataflowProcess
from mocasin.simulate.adapter import SimulateLoggerAdapter
... |
# -*- coding: utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the... |
# Copyright (c) 2015 Red Hat, 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.apache.org/licenses/LICENSE-2.0
#
# Unless require... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Profile mem usage envelope of IPython commands and report interactively"""
from __future__ import division # 1/2 == 0.5, as in Py3
from __future__ import absolute_import # avoid hiding global modules with locals
from __future__ import print_function # force use of pri... |
import pytest
from thefuck.rules.git_remote_seturl_add import match, get_new_command
from thefuck.types import Command
@pytest.mark.parametrize('command', [
Command('git remote set-url origin url', "fatal: No such remote")])
def test_match(command):
assert match(command)
@pytest.mark.parametrize('command', ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations
def update_site_forward(apps, schema_editor):
"""Set site domain and name."""
Site = apps.get_model("sites", "Site")
Site.objects.update_or_create(
id=settings.SITE_ID... |
"""
Copyright 2019 BlazeMeter Inc.
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, softwar... |
# coding: utf-8
"""
FlashArray REST API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 2.7
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re
import six
import typing
from .... |
from django.shortcuts import render
from books import models # 导入models文件
from django.contrib.auth.decorators import login_required,permission_required
from mybooks import settings
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
import re
import os
from PIL import Image
import re
import base6... |
# Detection thread
# Models are from http://alereimondo.no-ip.org/OpenCV/34/
# Check it out, there are plenty of them!
# Useful and fast
'''
If you wanna train your own models check this out!
https://docs.opencv.org/3.4/dc/d88/tutorial_traincascade.html
'''
# Code from https://docs.opencv.org/3.4/d7/d8b/tutorial_py_... |
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
# 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, mo... |
from __future__ import absolute_import, division, print_function
try:
import h5py # if we import h5py after tables we segfault
except ImportError:
pass
from pandas import DataFrame
from odo import odo, convert, append, drop, resource
from odo.backends.csv import CSV
from odo.backends.json import JSON, JSONLi... |
"""utils for entropy-regularized discrete MDPs."""
from __future__ import print_function
import numpy as np
def softmax(x, tau=1.):
e = np.exp(x * tau)
z = -np.log(sum(e))
return np.exp(x * tau + z)
def score_policy(pi, r, p, alpha, gamma):
"""Returns expected score J(pi) = v_pi(start) using soft p... |
from multiprocessing import Process,Queue
import os
import time
q = Queue()
def _write(q):
print('Process(%s) is writing...' % os.getpid())
while 1:
time.sleep(2)
url = 100
q.put(url)
print('Put %s to queue...' % url)
if __name__ == "__main__":
p = Process(target=_write,... |
"""
By default, all models are taken from this package.
But it is possible to customise these models to add some fields.
For such purpose cities_light models are defined as abstract (without
customisation they all inherit abstract versions automatically
without changes).
Steps to customise cities_light models
========... |
import pytest
from gingerit.gingerit import GingerIt
@pytest.mark.parametrize("text,expected", [
(
"The smelt of fliwers bring back memories.",
"The smell of flowers brings back memories."
),
(
"Edwards will be sck yesterday",
"Edwards was sick yesterday"
),
(
... |
#! /usr/bin/python
import cgi, cgitb
cgitb.enable()
def go():
fs = cgi.FieldStorage()
si = [fs.getvalue('name'), fs.getvalue('email'), fs.getvalue('tel'), fs.getvalue('message')]
#old emails
straw = open('emails.csv', 'rU')
oldEmails = straw.read()
straw.close()
#write new one
newE... |
# -*- coding: utf-8 -*-
# File generated according to Generator/ClassesRef/Output/OutStruct.csv
# WARNING! All changes made in this file will be lost!
"""Method code available at https://github.com/Eomys/pyleecan/tree/master/pyleecan/Methods/Output/OutStruct
"""
from os import linesep
from sys import getsizeof
from lo... |
import gc
import os
import time
# Import required modules
from pyaedt import Circuit
from pyaedt.generic.filesystem import Scratch
from pyaedt.generic.TouchstoneParser import read_touchstone
# Setup paths for module imports
from _unittest.conftest import local_path, scratch_path, config
try:
import pytest # noq... |
import numpy as np
# Nonlinearity functions (Numpy implementation)
nl_linear = lambda x: x
nl_tanh = lambda x: np.tanh(x)
nl_sigmoid = lambda x: 1./(1+np.exp(-x))
nl_rect = lambda x: np.clip(x, 0, np.inf)
#nl_rect = lambda x: np.clip(x, -np.inf, np.inf)
nl_shallow_rect = lambda x: np.clip(0.1*x, 0, np.inf)
nl_clip =... |
#!/usr/bin/python3
"""qsubm -- generic queue submission for task-oriented batch scripts
Environment variables:
MCSCRIPT_DIR should specify the directory in which the mcscript package is
installed, i.e., the directory where the file qsubm.py is found. (Note that
qsubm uses this information to locate c... |
"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.
openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, W... |
import z3
from ..utils import logger, utils
from ..model import model_utils
from . import symbols, struct
def const(name, sort):
assert(isinstance(name, str))
return z3.Const(name, sort)
def array(name, ix_sort, cont_sort):
return z3.Array(name, ix_sort, cont_sort)
class SlSort:
"""Representation of... |
"""Package Setup"""
import os
import re
from distutils.core import setup
from setuptools import find_packages
CURRENT_DIR = os.path.dirname(__file__)
def read(path):
with open(path, "r") as filep:
return filep.read()
def get_version(package_name):
with open(os.path.join(os.path.dirname(__file__), ... |
"""
Module for working with Storage
""" |
from loguru import logger
from bot import embeds
@logger.catch
def help_commands(bot):
@bot.group(invoke_without_command=True)
async def help(ctx):
await ctx.send(embed=embeds.help())
@help.command()
async def balance(ctx):
await ctx.send(embed=embeds.help_balance())
@help.comma... |
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
def get_model_gbm():
prostate = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg/prostate.csv"))
prostate.describe()
prostate[1] = prostate[1].asfactor()
from h2o.estimators.gbm import H2OGradientBoostingEstimator
... |
"""
Given a stack, a function is_consecutive takes a stack as a parameter and that
returns whether or not the stack contains a sequence of consecutive integers
starting from the bottom of the stack (returning true if it does, returning
false if it does not).
For example:
bottom [3, 4, 5, 6, 7] top
Then the call of is_... |
from calendar import month_name
from django.contrib.auth import get_user_model
from django.http import Http404
from django.shortcuts import get_object_or_404
from django.template.response import TemplateResponse
from django.utils.translation import ugettext_lazy as _
from mezzanine.blog.models import BlogPost, BlogCa... |
# coding: utf-8
from django.test import TestCase
rst_markup = """
Sample Header
===============
Blah blah blah
Lower Header
-------------
Blah blah blah
"""
class TestAddForm(TestCase):
fixtures = ["test_tasks.json"]
urls = "tasks.tests.tasks_urls"
def setUp(self):
self.client.login(us... |
from pprint import pprint
print('----------- Running {0} --------'.format(__name__))
def pprint_dict(header, d):
print('\n\n-----------------')
print('****** {0} *****')
# from pprint import pprint
# print('------- Running {0} -----------'.format(__name__))
# def pprint_dict(header, d):
# print('*... |
import subprocess
from thefuck.specific.apt import apt_available
from thefuck.specific.sudo import sudo_support
from thefuck.utils import for_app, eager, replace_command
enabled_by_default = apt_available
@for_app('apt', 'apt-get', 'apt-cache')
@sudo_support
def match(command):
return 'E: Invalid operation' in c... |
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: setting.py
Description : 配置文件
Author : JHao
date: 2019/2/15
-------------------------------------------------
Change Activity:
2019/2/15:
-------------------------------------... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2007 Zuza Software Foundation
#
# This file is part of translate.
#
# translate is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of t... |
""" Numerical functions """
import math
import numpy as np
import pymysql.cursors
from sa_db import sa_db_access
ACCESS_OBJ = sa_db_access()
DB_USR = ACCESS_OBJ.username()
DB_PWD = ACCESS_OBJ.password()
DB_NAME = ACCESS_OBJ.db_name()
DB_SRV = ACCESS_OBJ.db_server()
def get_pct_change(ini_val, new_val):
""" xxx """... |
'''
This script creates a regression test over garage-TRPO and baselines-TRPO.
Unlike garage, baselines doesn't set max_path_length. It keeps steps the action
until it's done. So we introduced tests.wrappers.AutoStopEnv wrapper to set
done=True when it reaches max_path_length. We also need to change the
garage.tf.samp... |
# Copyright (c) 2014, 2015, 2019 Wieland Hoffmann, MetaBrainz Foundation
# License: MIT, see LICENSE for details
import argparse
import logging
import multiprocessing
import ConfigParser
import config
from . import init_raven_client
from .amqp.extension_generation import generate_extension
from .amqp.handler import wa... |
__________________________________________________________________________________________________
sample 24 ms submission
class Solution:
def reachNumber(self, target: int) -> int:
# (n+1)*n/2....t
t=abs(target)
n=math.floor((t*2)**0.5)
while True:
diff=(n+1)*n/2-t
... |
# -*- coding: UTF-8 -*-
num_start = 1
loops = 5
ap_step = 5
sum = 0
y = num_start
for num in range(loops):
sum += y
y += ap_step
print(sum)
sum = 0
y = num_start
for num in range(loops):
sum += y
y *= ap_step
print(sum) |
import os
from typing import Any, Callable, Dict, FrozenSet, List, Optional, Set, Tuple
from unittest.mock import patch
import orjson
from django.conf import settings
from django.db.models import Q
from django.utils.timezone import now as timezone_now
from zerver.lib import upload
from zerver.lib.actions import (
... |
"""Make everything from submodules appear at the top level.
"""
from pandana.utils.mpiutils import *
from pandana.utils.pandasutils import * |
import logging
import random
from sqlalchemy import TEXT, INT
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship
from pajbot.managers.db import Base
log = logging.getLogger(__name__)
def salt_gen():
ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJ... |
import pytest
from PyBall import PyBall
from PyBall.models.config import SituationCode
@pytest.fixture(scope='module')
def test_situation_codes():
pyball = PyBall()
return pyball.get_situation_codes()
def test_get_situation_codes_returns_situation_codes(test_situation_codes):
assert isinstance(test_situ... |
# coding=utf-8
# Copyright 2021 Google LLC.
#
# 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 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.