code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
"""Driver for gradient calculations."""
__authors__ = "<NAME>, <NAME>, <NAME>"
__copyright__ = "(c) 2011, Universite de Montreal"
__license__ = "3-clause BSD License"
__contact__ = "theano-dev <<EMAIL>>"
__docformat__ = "restructuredtext en"
import __builtin__
import logging
import warnings
_logger = logging.getLogg... | [
"logging.getLogger",
"numpy.array",
"__builtin__.min",
"numpy.isfinite",
"theano.tensor.arange",
"theano.tensor.as_tensor_variable",
"warnings.warn",
"theano.compile.function",
"numpy.dtype",
"theano.raise_op.Raise",
"__builtin__.max",
"theano.tensor.sum",
"theano.gof.utils.uniq",
"numpy.a... | [((305, 341), 'logging.getLogger', 'logging.getLogger', (['"""theano.gradient"""'], {}), "('theano.gradient')\n", (322, 341), False, 'import logging\n'), ((4439, 4478), 'theano.gof.utils.uniq', 'gof.utils.uniq', (['[r for r, g in sources]'], {}), '([r for r, g in sources])\n', (4453, 4478), False, 'from theano import g... |
import sys
import json
from datetime import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
import numpy as np
import pickle
if __name__ == '__main__':
fname = sys.argv[1]
with open(fname, 'r') as f:
all_dates = []
for line in f:
twee... | [
"pandas.Series",
"datetime.datetime",
"json.loads",
"matplotlib.pyplot.savefig",
"pandas.DatetimeIndex",
"matplotlib.dates.DateFormatter",
"matplotlib.dates.MinuteLocator",
"matplotlib.pyplot.subplots"
] | [((448, 475), 'pandas.DatetimeIndex', 'pd.DatetimeIndex', (['all_dates'], {}), '(all_dates)\n', (464, 475), True, 'import pandas as pd\n'), ((557, 583), 'pandas.Series', 'pd.Series', (['ones'], {'index': 'idx'}), '(ones, index=idx)\n', (566, 583), True, 'import pandas as pd\n'), ((801, 815), 'matplotlib.pyplot.subplots... |
from functools import wraps
from typing import Callable, List, Optional, Tuple
from sanic.request import Request
from sanic_jwt_extended.exceptions import (
AccessDeniedError,
ConfigurationConflictError,
CSRFError,
FreshTokenRequiredError,
InvalidHeaderError,
NoAuthorizationError,
RevokedT... | [
"sanic_jwt_extended.exceptions.AccessDeniedError",
"sanic_jwt_extended.tokens.Token",
"sanic_jwt_extended.exceptions.CSRFError",
"sanic_jwt_extended.jwt_manager.JWT.blacklist.is_blacklisted",
"hmac.compare_digest",
"sanic_jwt_extended.exceptions.FreshTokenRequiredError",
"functools.wraps",
"sanic_jwt_... | [((5310, 5325), 'functools.wraps', 'wraps', (['function'], {}), '(function)\n', (5315, 5325), False, 'from functools import wraps\n'), ((2178, 2232), 'sanic_jwt_extended.exceptions.NoAuthorizationError', 'NoAuthorizationError', (['f"""Missing header "{header_key}\\""""'], {}), '(f\'Missing header "{header_key}"\')\n', ... |
"""
This module converts code written for numarray to run with numpy
Makes the following changes:
* Changes import statements
import numarray.package
--> import numpy.numarray.package as numarray_package
with all numarray.package in code changed to numarray_package
import numarray --> import... | [
"re.compile",
"os.rename",
"os.path.join",
"os.path.splitext",
"os.path.split",
"re.sub",
"datetime.date.today",
"os.path.walk",
"os.remove"
] | [((2994, 3028), 're.compile', 're.compile', (['"""([.]flat(\\\\s*?[[=]))"""'], {}), "('([.]flat(\\\\s*?[[=]))')\n", (3004, 3028), False, 'import re\n'), ((4482, 4531), 're.compile', 're.compile', (['"""(\\\\S+)\\\\s*[.]\\\\s*info\\\\s*[(]\\\\s*[)]"""'], {}), "('(\\\\S+)\\\\s*[.]\\\\s*info\\\\s*[(]\\\\s*[)]')\n", (4492,... |
from flask import request
from flask_restful import Resource
import src.error.errors as error
from src import logger
from src.conf.auth import auth
from src.database.database import db
from src.models.models import User, Blacklist
class Index(Resource):
@staticmethod
def get():
return {"status": "Fli... | [
"src.models.models.Blacklist.query.filter_by",
"src.logger.info",
"src.database.database.db.session.add",
"flask.request.json.get",
"src.database.database.db.session.commit",
"src.models.models.User",
"src.models.models.User.query.filter_by",
"src.models.models.Blacklist"
] | [((1016, 1071), 'src.models.models.User', 'User', ([], {'username': 'username', 'password': 'password', 'email': 'email'}), '(username=username, password=password, email=email)\n', (1020, 1071), False, 'from src.models.models import User, Blacklist\n'), ((1080, 1100), 'src.database.database.db.session.add', 'db.session... |
# pylint: disable=g-bad-file-header
# Copyright 2017 The Bazel 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
... | [
"os.linesep.join",
"src.test.py.bazel.test_base.TestBase.setUp",
"src.test.py.bazel.test_base.TestBase.tearDown",
"unittest.main",
"threading.Thread"
] | [((7275, 7290), 'unittest.main', 'unittest.main', ([], {}), '()\n', (7288, 7290), False, 'import unittest\n'), ((1354, 1399), 'threading.Thread', 'threading.Thread', ([], {'target': 'server.serve_forever'}), '(target=server.serve_forever)\n', (1370, 1399), False, 'import threading\n'), ((1691, 1721), 'src.test.py.bazel... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import BCEWithLogitsLoss
class BCEWithWeights(BCEWithLogitsLoss):
def __init__(self, reduction="none", **kwargs):
super().__init__(reduction="none", **kwargs)
self._w_reduction = reduction
def forward(self, input... | [
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"torch.mean",
"torch.sigmoid",
"torch.Tensor",
"torch.square",
"torch.nn.Conv2d",
"torch.nn.MaxPool2d",
"torch.sum",
"torch.nn.ConvTranspose2d",
"torch.cat"
] | [((897, 918), 'torch.sigmoid', 'torch.sigmoid', (['logits'], {}), '(logits)\n', (910, 918), False, 'import torch\n'), ((968, 1006), 'torch.sum', 'torch.sum', (['(y_true * y_pred)'], {'dim': 'hw_dim'}), '(y_true * y_pred, dim=hw_dim)\n', (977, 1006), False, 'import torch\n'), ((3342, 3372), 'torch.nn.Conv2d', 'nn.Conv2d... |
# 1.导入蓝图类
from flask import Blueprint
"""
1.导入蓝图类
2.创建蓝图对象
3.使用蓝图对象装饰视图函数
4.注册蓝图对象
"""
# 2.创建蓝图对象
# url_prefix: 登录注册模块的url访问前缀
passport_bp = Blueprint("passport", __name__, url_prefix="/passport")
from .views import *
# from info.moduls.index.views import *
| [
"flask.Blueprint"
] | [((142, 197), 'flask.Blueprint', 'Blueprint', (['"""passport"""', '__name__'], {'url_prefix': '"""/passport"""'}), "('passport', __name__, url_prefix='/passport')\n", (151, 197), False, 'from flask import Blueprint\n')] |
from os import path
# load file
file1 = open('data/sketch/sketchPath.csv', 'r')
Lines = file1.readlines()
# file to save
file2 = open('sketchPath_process.csv', 'w')
file2.writelines(f'path,label\n')
count = 0
for line in Lines:
count += 1
tmp = line.strip()
tmp1 = tmp[:24]
tmp1 = tmp1.replace(',', ''... | [
"os.path.isfile"
] | [((366, 400), 'os.path.isfile', 'path.isfile', (['f"""data/sketch/{tmp1}"""'], {}), "(f'data/sketch/{tmp1}')\n", (377, 400), False, 'from os import path\n')] |
"""Get information about the current wmt-exe environment."""
from __future__ import print_function
import sys
def dict_to_ini(d, section):
from configparser import ConfigParser
from io import StringIO
config = ConfigParser()
config.add_section(section)
for (key, value) in list(d.items()):
... | [
"socket.getfqdn",
"io.StringIO",
"configparser.ConfigParser",
"argparse.ArgumentParser"
] | [((227, 241), 'configparser.ConfigParser', 'ConfigParser', ([], {}), '()\n', (239, 241), False, 'from configparser import ConfigParser\n'), ((370, 380), 'io.StringIO', 'StringIO', ([], {}), '()\n', (378, 380), False, 'from io import StringIO\n'), ((535, 551), 'socket.getfqdn', 'socket.getfqdn', ([], {}), '()\n', (549, ... |
from podr_connection import podr_connection
from cdisc_library import CDISCConnector
from load_specifications import load_usecase_specification
from dotenv import load_dotenv
from yaml import load
import re
import os
# load the environment variables
load_dotenv(dotenv_path=os.path.join(os.path.dirname(__file__), '..'... | [
"os.path.exists",
"cdisc_library.CDISCConnector",
"re.compile",
"os.path.dirname",
"load_specifications.load_usecase_specification",
"podr_connection.podr_connection"
] | [((374, 411), 're.compile', 're.compile', (['"""([A-Z]{2,4})\\\\.([A-Z]+)"""'], {}), "('([A-Z]{2,4})\\\\.([A-Z]+)')\n", (384, 411), False, 'import re\n'), ((2686, 2724), 'load_specifications.load_usecase_specification', 'load_usecase_specification', (['self._name'], {}), '(self._name)\n', (2712, 2724), False, 'from loa... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2019 Intel Corporation
#
# 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
#
# Un... | [
"keras.backend.set_image_data_format",
"tensorflow.round",
"keras.optimizers.Adam",
"keras.losses.binary_crossentropy",
"keras.layers.Conv3DTranspose",
"tensorflow.reduce_sum",
"keras.layers.Input",
"keras.layers.concatenate",
"keras.models.Model",
"tensorflow.constant",
"keras.layers.Activation... | [((1314, 1363), 'keras.backend.set_image_data_format', 'K.backend.set_image_data_format', (['self.data_format'], {}), '(self.data_format)\n', (1345, 1363), True, 'import keras as K\n'), ((1797, 1837), 'keras.optimizers.Adam', 'K.optimizers.Adam', ([], {'lr': 'self.learning_rate'}), '(lr=self.learning_rate)\n', (1814, 1... |
#!/usr/bin/env python
# -*- coding: utf-8 -*
from collections import OrderedDict
BASE_URL = 'https://img.tl/%s'
# SERVERS
SERVERS = OrderedDict((
('S1', 's1.img.tl'),
('S2', 's2.img.tl'),
))
# OBJ_TYPE
TYPE_IMAGE = 1
TYPE_FILE = 2
TYPE_TEXT = 3
# EXPIRE_BEHAVIOR
EXPIRE_BEHAVIORS = (
'delete',
'priv... | [
"collections.OrderedDict"
] | [((135, 190), 'collections.OrderedDict', 'OrderedDict', (["(('S1', 's1.img.tl'), ('S2', 's2.img.tl'))"], {}), "((('S1', 's1.img.tl'), ('S2', 's2.img.tl')))\n", (146, 190), False, 'from collections import OrderedDict\n')] |
# 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 ... | [
"uuid.uuid1",
"msrest.pipeline.ClientRawResponse",
"msrestazure.azure_exceptions.CloudError",
"msrestazure.azure_operation.AzureOperationPoller"
] | [((8212, 8337), 'msrestazure.azure_operation.AzureOperationPoller', 'AzureOperationPoller', (['long_running_send', 'get_long_running_output', 'get_long_running_status', 'long_running_operation_timeout'], {}), '(long_running_send, get_long_running_output,\n get_long_running_status, long_running_operation_timeout)\n',... |
# Standard library imports
import json
import logging
# Third party imports
from django.contrib import messages
from django.contrib.auth.decorators import user_passes_test
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.con... | [
"logging.getLogger",
"django.shortcuts.render",
"dojo.models.Rule.objects.all",
"dojo.models.System_Settings.objects.get",
"dojo.forms.RuleFormSet",
"dojo.models.Child_Rule.objects.filter",
"django.urls.reverse",
"django.shortcuts.get_object_or_404",
"json.dumps",
"dojo.models.Rule.objects.filter"... | [((673, 700), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (690, 700), False, 'import logging\n'), ((1394, 1436), 'django.contrib.auth.decorators.user_passes_test', 'user_passes_test', (['(lambda u: u.is_superuser)'], {}), '(lambda u: u.is_superuser)\n', (1410, 1436), False, 'from djang... |
# 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, software
# d... | [
"json.loads",
"json.dumps",
"functools.wraps",
"urllib.urlencode",
"six.iteritems"
] | [((770, 788), 'functools.wraps', 'functools.wraps', (['f'], {}), '(f)\n', (785, 788), False, 'import functools\n'), ((1378, 1401), 'json.dumps', 'json.dumps', (['object_dict'], {}), '(object_dict)\n', (1388, 1401), False, 'import json\n'), ((1502, 1524), 'json.loads', 'json.loads', (['object_str'], {}), '(object_str)\n... |
from taurex.log import Logger
from taurex.util import get_molecular_weight
from taurex.data.fittable import Fittable
import numpy as np
from taurex.output.writeable import Writeable
from taurex.cache import OpacityCache
class Chemistry(Fittable, Logger, Writeable):
"""
*Abstract Class*
Skeleton for defin... | [
"taurex.data.fittable.Fittable.__init__",
"taurex.cache.OpacityCache",
"taurex.util.get_molecular_weight",
"taurex.log.Logger.__init__",
"numpy.zeros"
] | [((978, 1005), 'taurex.log.Logger.__init__', 'Logger.__init__', (['self', 'name'], {}), '(self, name)\n', (993, 1005), False, 'from taurex.log import Logger\n'), ((1014, 1037), 'taurex.data.fittable.Fittable.__init__', 'Fittable.__init__', (['self'], {}), '(self)\n', (1031, 1037), False, 'from taurex.data.fittable impo... |
# Copyright 2008-2015 Nokia Networks
# Copyright 2016- Robot Framework Foundation
#
# 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
... | [
"unittest.main",
"datafilereader.get_ctrl_by_name",
"datafilereader.construct_project"
] | [((2236, 2251), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2249, 2251), False, 'import unittest\n'), ((788, 851), 'datafilereader.construct_project', 'datafilereader.construct_project', (['datafilereader.ALL_FILES_PATH'], {}), '(datafilereader.ALL_FILES_PATH)\n', (820, 851), False, 'import datafilereader\n'),... |
# 保存
import requests
import json
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36',
# 'Content-Type': 'application/json; charset=UTF-8'
}
data = {
'username': '121213',
'password': '<PASSWORD>'
}
cookies... | [
"requests.get"
] | [((496, 610), 'requests.get', 'requests.get', (['"""http://localhost:8081/ydyl/sso/verificationUser"""'], {'params': 'data', 'headers': 'headers', 'cookies': 'cookies'}), "('http://localhost:8081/ydyl/sso/verificationUser', params=data,\n headers=headers, cookies=cookies)\n", (508, 610), False, 'import requests\n')] |
# --------------
# Importing header files
import numpy as np
# Path of the file has been stored in variable called 'path'
#New record
new_record=[[50, 9, 4, 1, 0, 0, 40, 0]]
#Code starts here
data = np.genfromtxt(path, delimiter=',' ,skip_header=1)
census = np.concatenate((data,np.asarray(new_recor... | [
"numpy.mean",
"numpy.asarray",
"numpy.genfromtxt",
"numpy.std"
] | [((217, 266), 'numpy.genfromtxt', 'np.genfromtxt', (['path'], {'delimiter': '""","""', 'skip_header': '(1)'}), "(path, delimiter=',', skip_header=1)\n", (230, 266), True, 'import numpy as np\n'), ((540, 552), 'numpy.mean', 'np.mean', (['age'], {}), '(age)\n', (547, 552), True, 'import numpy as np\n'), ((564, 575), 'num... |
# Description: Cog that houses owner-only commands (inspired by EvieePy)
import app_logger
import config
import discord
from datetime import datetime
from discord.ext import commands
from importlib import reload as importlib_reload
from typing import Optional
from utils import tools
logger = app_logger.get_logger(__... | [
"utils.tools.seconds_to_str",
"datetime.datetime.utcnow",
"discord.ext.commands.group",
"app_logger.get_logger",
"importlib.reload",
"discord.ext.commands.BadArgument",
"discord.Embed",
"discord.ext.commands.command",
"discord.ext.commands.NotOwner"
] | [((296, 327), 'app_logger.get_logger', 'app_logger.get_logger', (['__name__'], {}), '(__name__)\n', (317, 327), False, 'import app_logger\n'), ((871, 916), 'discord.ext.commands.command', 'commands.command', ([], {'aliases': "['load', 'loadcog']"}), "(aliases=['load', 'loadcog'])\n", (887, 916), False, 'from discord.ex... |
import string
import random
def uuid(length=8, lower=True):
"""sebbe-approved UUID"""
# risk of collision
# mixed case: 8 characters -> 1 in 54 trillion
# lower case: 8 characters -> 1 in 208 billion
letters = string.ascii_letters
if lower:
letters = letters.lower()
return ''.join... | [
"random.choice"
] | [((321, 343), 'random.choice', 'random.choice', (['letters'], {}), '(letters)\n', (334, 343), False, 'import random\n')] |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import logging
import json
from .divide import divide
class Node:
"""
Build up a 2d tree.
"""
parent = None
children = None
key = None
position = None
"""node resized by user"""
resized = False
DIMENSION = 2
__leafnodemap = Non... | [
"json.dumps"
] | [((390, 431), 'json.dumps', 'json.dumps', (['obj'], {'indent': '(4)', 'sort_keys': '(True)'}), '(obj, indent=4, sort_keys=True)\n', (400, 431), False, 'import json\n')] |
"""
cloudalbum/tests/test_admin.py
~~~~~~~~~~~~~~~~~~~~~~~
Test cases for admin REST API
:description: CloudAlbum is a fully featured sample application for 'Moving to AWS serverless' training course
:copyright: © 2019 written by <NAME>, <NAME>.
:license: MIT, see LICENSE for more details.
"""
... | [
"unittest.main"
] | [((863, 878), 'unittest.main', 'unittest.main', ([], {}), '()\n', (876, 878), False, 'import unittest\n')] |
import asyncio
import filecmp
import logging
import os
import pickle
import tempfile
import warnings
import re
from asyncio import AbstractEventLoop
from pathlib import Path
from typing import Text, Any, Union, List, Type, Callable, TYPE_CHECKING, Pattern
import rasa.shared.constants
import rasa.shared.utils.io
if TY... | [
"re.compile",
"os.path.exists",
"jsonpickle.ext.numpy.register_handlers",
"pathlib.Path",
"filecmp.dircmp",
"tempfile.NamedTemporaryFile",
"warnings.simplefilter",
"asyncio.get_event_loop",
"coloredlogs.DEFAULT_FIELD_STYLES.copy",
"jsonpickle.loads",
"pickle.load",
"tempfile.TemporaryDirectory... | [((620, 659), 'coloredlogs.DEFAULT_FIELD_STYLES.copy', 'coloredlogs.DEFAULT_FIELD_STYLES.copy', ([], {}), '()\n', (657, 659), False, 'import coloredlogs\n'), ((712, 751), 'coloredlogs.DEFAULT_LEVEL_STYLES.copy', 'coloredlogs.DEFAULT_LEVEL_STYLES.copy', ([], {}), '()\n', (749, 751), False, 'import coloredlogs\n'), ((787... |
import os, pickle, json
from collections import deque
import numpy as np
import tensorflow as tf
import torch
import torch.nn.functional as F
from guacamol.distribution_matching_generator import DistributionMatchingGenerator
from rdkit import Chem
from torch.utils.data import DataLoader, Dataset
from tqdm import tqdm
... | [
"torch.distributions.Categorical",
"data.gen_targets.get_symbol_list",
"torch.nn.functional.softmax",
"numpy.mean",
"os.listdir",
"tensorflow.__version__.split",
"collections.deque",
"src.utils.set_seed_if",
"tensorflow.Session",
"rdkit.Chem.MolToSmiles",
"src.utils.filter_top_k",
"tensorflow.... | [((639, 655), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {}), '()\n', (653, 655), True, 'import tensorflow as tf\n'), ((710, 735), 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), '(config=config)\n', (720, 735), True, 'import tensorflow as tf\n'), ((24563, 24586), 'os.listdir', 'os.listdir', (['cp... |
# Copyright 1999-2018 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... | [
"operator.attrgetter",
"numpy.isscalar",
"numpy.asarray",
"itertools.count",
"numpy.empty",
"numpy.cumsum",
"numpy.dtype"
] | [((7440, 7454), 'numpy.isscalar', 'np.isscalar', (['v'], {}), '(v)\n', (7451, 7454), True, 'import numpy as np\n'), ((7642, 7656), 'numpy.isscalar', 'np.isscalar', (['v'], {}), '(v)\n', (7653, 7656), True, 'import numpy as np\n'), ((8465, 8479), 'numpy.isscalar', 'np.isscalar', (['v'], {}), '(v)\n', (8476, 8479), True,... |
#!/usr/bin/python
#coding: utf-8
#
# Copyright (c) 2012 <NAME> <<EMAIL>>
#
# 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
# ... | [
"sys.stderr.write",
"random.randint",
"sys.exit"
] | [((1201, 1259), 'sys.stderr.write', 'sys.stderr.write', (['"""usage: ./fuzz-p12.py input_file.p12\n"""'], {}), "('usage: ./fuzz-p12.py input_file.p12\\n')\n", (1217, 1259), False, 'import random, sys\n'), ((1264, 1275), 'sys.exit', 'sys.exit', (['(2)'], {}), '(2)\n', (1272, 1275), False, 'import random, sys\n'), ((14... |
import numpy as np
import mixem
def logsumexp(X,axis=None,keepdims=1,log=1):
'''
log(
sum(
exp(X)
)
)
'''
xmax = np.max(X,axis=axis,keepdims=keepdims)
y = np.exp(X-xmax)
S = y.sum(axis=axis,keepdims=keepdims)
if log:
S = np.log(S) + xmax
e... | [
"numpy.mean",
"numpy.ones",
"numpy.log",
"numpy.max",
"numpy.exp",
"numpy.array",
"numpy.zeros",
"numpy.sum",
"numpy.empty",
"numpy.isnan"
] | [((168, 207), 'numpy.max', 'np.max', (['X'], {'axis': 'axis', 'keepdims': 'keepdims'}), '(X, axis=axis, keepdims=keepdims)\n', (174, 207), True, 'import numpy as np\n'), ((214, 230), 'numpy.exp', 'np.exp', (['(X - xmax)'], {}), '(X - xmax)\n', (220, 230), True, 'import numpy as np\n'), ((1851, 1873), 'numpy.zeros', 'np... |
'''
Generates the image stream resource definitions.
'''
import powershift.resources as resources
image_stream = resources.v1_ImageStream(
metadata = resources.v1_ObjectMeta(
name = 'jupyter-notebook',
annotations = {
'openshift.io/display-name': 'Jupyter Notebook'
}
),
... | [
"powershift.resources.v1_ObjectReference",
"powershift.resources.v1_ObjectMeta",
"powershift.resources.dump",
"powershift.resources.v1_ImageStreamSpec"
] | [((2308, 2362), 'powershift.resources.dump', 'resources.dump', (['image_stream'], {'indent': '(4)', 'sort_keys': '(True)'}), '(image_stream, indent=4, sort_keys=True)\n', (2322, 2362), True, 'import powershift.resources as resources\n'), ((157, 273), 'powershift.resources.v1_ObjectMeta', 'resources.v1_ObjectMeta', ([],... |
# Live tracking of your mouse's location
# Works in Command Prompt and when you double click this file
import pyautogui
print("Ctrl+C quits the program")
try:
while True:
x, y = pyautogui.position()
pos = "X: " + str(x).rjust(4) + " Y: " + str(y).rjust(4)
print(pos, end='')
print... | [
"pyautogui.position"
] | [((194, 214), 'pyautogui.position', 'pyautogui.position', ([], {}), '()\n', (212, 214), False, 'import pyautogui\n')] |
"""AOC 2020 Day 19"""
import pathlib
import time
import re
TEST_INPUT = """0: 4 1 5
1: 2 3 | 3 2
2: 4 4 | 5 5
3: 4 5 | 5 4
4: "a"
5: "b"
ababbb
bababa
abbbab
aaabbb
aaaabbb"""
TEST_INPUT_2 = """42: 9 14 | 10 1
9: 14 27 | 1 26
10: 23 14 | 28 1
1: "a"
11: 42 31
5: 1 14 | 15 1
19: 14 1 | 14 14
12: 24 14 | 19 1
16: 15 ... | [
"re.fullmatch",
"time.time",
"pathlib.Path"
] | [((1773, 1798), 're.fullmatch', 're.fullmatch', (['"""".\\""""', 'rule'], {}), '(\'"."\', rule)\n', (1785, 1798), False, 'import re\n'), ((2393, 2418), 're.fullmatch', 're.fullmatch', (['"""".\\""""', 'rule'], {}), '(\'"."\', rule)\n', (2405, 2418), False, 'import re\n'), ((3538, 3549), 'time.time', 'time.time', ([], {... |
# Copyright 2016 <NAME> (<EMAIL>)
#
# 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 writ... | [
"logging.getLogger",
"os.path.join",
"diskimage_builder.block_device.utils.parse_abs_size_spec",
"diskimage_builder.block_device.utils.exec_sudo",
"os.remove"
] | [((951, 978), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (968, 978), False, 'import logging\n'), ((1238, 1257), 'os.remove', 'os.remove', (['filename'], {}), '(filename)\n', (1247, 1257), False, 'import os\n'), ((1409, 1457), 'diskimage_builder.block_device.utils.exec_sudo', 'exec_sud... |
from django.template.loader import render_to_string
class GenericHandler(object):
template = 'django_congen/gunicorn_release.py'
pb = None
def __init__(self, path_builder_instance, template=None):
self.pb = path_builder_instance
if template:
self.template = template
def ... | [
"django.template.loader.render_to_string"
] | [((379, 413), 'django.template.loader.render_to_string', 'render_to_string', (['self.template', 'c'], {}), '(self.template, c)\n', (395, 413), False, 'from django.template.loader import render_to_string\n')] |
import os
from flask_oauthlib.client import OAuth
from requirements import app
oauth = OAuth(app)
github = oauth.remote_app(
'github',
consumer_key=os.environ.get('GH_CLIENT_ID'),
consumer_secret=os.environ.get('GH_CLIENT_SECRET'),
request_token_params={'scope': 'repo,user:email'},
base_url='htt... | [
"flask_oauthlib.client.OAuth",
"os.environ.get"
] | [((90, 100), 'flask_oauthlib.client.OAuth', 'OAuth', (['app'], {}), '(app)\n', (95, 100), False, 'from flask_oauthlib.client import OAuth\n'), ((160, 190), 'os.environ.get', 'os.environ.get', (['"""GH_CLIENT_ID"""'], {}), "('GH_CLIENT_ID')\n", (174, 190), False, 'import os\n'), ((212, 246), 'os.environ.get', 'os.enviro... |
# Generated by Django 1.9.13 on 2017-10-15 21:03
import django.db.models.deletion
from django.db import migrations, models
import djangocms_bootstrap4.fields
from djangocms_bootstrap4.constants import TAG_CHOICES
class Migration(migrations.Migration):
initial = True
dependencies = [
('cms', '0016_a... | [
"django.db.models.OneToOneField",
"django.db.models.SlugField",
"django.db.models.CharField"
] | [((493, 720), 'django.db.models.OneToOneField', 'models.OneToOneField', ([], {'auto_created': '(True)', 'on_delete': 'django.db.models.deletion.CASCADE', 'parent_link': '(True)', 'primary_key': '(True)', 'related_name': '"""bootstrap4_collapse_bootstrap4collapse"""', 'serialize': '(False)', 'to': '"""cms.CMSPlugin"""'}... |
# tests.test_cmake_parser
from io import StringIO
from unittest import TestCase
from tests.cmake_parser import lex, find_command, parse_if, parse
def mk_cmd(command, *args):
return (command, list(args))
def call_parse_if(predicate, *cmds):
return parse_if(predicate, iter(cmds))
def call_parse(*cmds):... | [
"tests.cmake_parser.lex",
"io.StringIO",
"tests.cmake_parser.find_command"
] | [((432, 452), 'io.StringIO', 'StringIO', (['"""if(if())"""'], {}), "('if(if())')\n", (440, 452), False, 'from io import StringIO\n'), ((615, 630), 'io.StringIO', 'StringIO', (['"""if)"""'], {}), "('if)')\n", (623, 630), False, 'from io import StringIO\n'), ((822, 838), 'io.StringIO', 'StringIO', (['"""if()"""'], {}), "... |
#/*
# * Copyright (c) 2019,2020 Xilinx Inc. All rights reserved.
# *
# * Author:
# * <NAME> <<EMAIL>>
# *
# * SPDX-License-Identifier: BSD-3-Clause
# */
import copy
import struct
import sys
import types
import unittest
import os
import getopt
import re
import subprocess
import shutil
from pathlib import Path
fro... | [
"os.path.dirname",
"re.search"
] | [((534, 559), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (549, 559), False, 'import os\n'), ((1206, 1258), 're.search', 're.search', (['"""openamp,xlnx-rpu"""', 'compat_string_to_test'], {}), "('openamp,xlnx-rpu', compat_string_to_test)\n", (1215, 1258), False, 'import re\n')] |
import itertools
import unittest
from parameterized import parameterized
import torch
import torch.nn as nn
from nsoltChannelConcatenation2dLayer import NsoltChannelConcatenation2dLayer
nchs = [ [3, 3], [4, 4] ]
datatype = [ torch.float, torch.double ]
nrows = [ 4, 8, 16 ]
ncols = [ 4, 8, 16 ]
class NsoltAtomExtentio... | [
"nsoltChannelConcatenation2dLayer.NsoltChannelConcatenation2dLayer",
"itertools.product",
"torch.allclose",
"unittest.main",
"torch.no_grad",
"torch.randn"
] | [((4216, 4231), 'unittest.main', 'unittest.main', ([], {}), '()\n', (4229, 4231), False, 'import unittest\n'), ((1191, 1240), 'nsoltChannelConcatenation2dLayer.NsoltChannelConcatenation2dLayer', 'NsoltChannelConcatenation2dLayer', ([], {'name': 'expctdName'}), '(name=expctdName)\n', (1223, 1240), False, 'from nsoltChan... |
from json import dumps, loads
import jwt
import pytest
from flask import current_app as app
from src.main.core.database import *
JSON_DECODE_ERR_MSG = (
"Expecting property name enclosed in " "double quotes: line 1 column 2 (char 1)"
)
owner_role = ("Owner", True, True, True, True)
user_role = ("User", False, Fa... | [
"jwt.encode"
] | [((2149, 2196), 'jwt.encode', 'jwt.encode', (["{'id': 1}", "app.config['SECRET_KEY']"], {}), "({'id': 1}, app.config['SECRET_KEY'])\n", (2159, 2196), False, 'import jwt\n')] |
import enum
import json
import pathlib
import shutil
from typing import Any, Dict, List, Optional
from determined_common import api, storage
from determined_common.api import gql
class ModelFramework(enum.Enum):
PYTORCH = 1
TENSORFLOW = 2
class Checkpoint(object):
"""
Class representing a checkpoin... | [
"pathlib.Path",
"determined_common.storage.StorageMetadata.from_json",
"determined_common.api.gql.uuid_comparison_exp",
"determined_common.api.gql.checkpoint_state_comparison_exp",
"json.load",
"determined_common.storage.build",
"determined_common.api.GraphQLQuery"
] | [((8229, 8253), 'determined_common.api.GraphQLQuery', 'api.GraphQLQuery', (['master'], {}), '(master)\n', (8245, 8253), False, 'from determined_common import api, storage\n'), ((6711, 6729), 'pathlib.Path', 'pathlib.Path', (['path'], {}), '(path)\n', (6723, 6729), False, 'import pathlib\n'), ((2241, 2260), 'pathlib.Pat... |
from sympy import QQ, ZZ
from sympy.abc import x, theta
from sympy.core.mul import prod
from sympy.ntheory import factorint
from sympy.ntheory.residue_ntheory import n_order
from sympy.polys import Poly, cyclotomic_poly
from sympy.polys.matrices import DomainMatrix
from sympy.polys.numberfields.basis import round_two
f... | [
"sympy.polys.cyclotomic_poly",
"sympy.QQ.alg_field_from_poly",
"sympy.polys.numberfields.modules.PowerBasis",
"sympy.polys.numberfields.modules.to_col",
"sympy.polys.numberfields.primes.prime_decomp",
"sympy.polys.Poly",
"sympy.QQ",
"sympy.polys.numberfields.basis.round_two",
"sympy.ntheory.factorin... | [((714, 727), 'sympy.polys.numberfields.modules.PowerBasis', 'PowerBasis', (['T'], {}), '(T)\n', (724, 727), False, 'from sympy.polys.numberfields.modules import PowerBasis, to_col\n'), ((1456, 1468), 'sympy.polys.numberfields.basis.round_two', 'round_two', (['T'], {}), '(T)\n', (1465, 1468), False, 'from sympy.polys.n... |
from flask import render_template, Blueprint
import json
SCODA = Blueprint('SCODA',__name__)
@SCODA.route('/')
def index():
return render_template("scoda.html") | [
"flask.render_template",
"flask.Blueprint"
] | [((65, 93), 'flask.Blueprint', 'Blueprint', (['"""SCODA"""', '__name__'], {}), "('SCODA', __name__)\n", (74, 93), False, 'from flask import render_template, Blueprint\n'), ((133, 162), 'flask.render_template', 'render_template', (['"""scoda.html"""'], {}), "('scoda.html')\n", (148, 162), False, 'from flask import rende... |
import pytest
from models.gameState import Game, States
def test_defaultGameState():
systemUnderTest = Game()
assert systemUnderTest.state == States.MARSHALLING
assert len(systemUnderTest.players) == 0 | [
"models.gameState.Game"
] | [((108, 114), 'models.gameState.Game', 'Game', ([], {}), '()\n', (112, 114), False, 'from models.gameState import Game, States\n')] |
import torch
class MinibatchStdDev(torch.nn.Module):
'''Mini-batch standard deviation
Arguments:
group_size: int
Size of the group to calculate the statistics.
num_channels: int (default: 1)
Number of channels to be appended.
'''
def __init__(self, group_size:... | [
"torch.cat"
] | [((872, 896), 'torch.cat', 'torch.cat', (['[x, y]'], {'dim': '(1)'}), '([x, y], dim=1)\n', (881, 896), False, 'import torch\n')] |
"""
==========
ISOMAP neighbours parameter CV pipeline
==========
Use a pipeline to find the best neighbourhood size parameter for ISOMAP.
Adapted from:
http://scikit-learn.org/stable/auto_examples/decomposition/plot_kernel_pca.html#example-decomposition-plot-kernel-pca-py
http://scikit-learn.org/stable/auto... | [
"sklearn.cluster.KMeans",
"pickle.dump",
"numpy.hstack",
"numpy.arange",
"sklearn.manifold.Isomap",
"optparse.OptionParser",
"extract_datasets.extract_labeled_chunkrange",
"sklearn.metrics.make_scorer",
"numpy.vstack",
"numpy.random.seed",
"numpy.nonzero",
"sklearn.pipeline.Pipeline",
"sklea... | [((807, 824), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (821, 824), True, 'import numpy as np\n'), ((861, 875), 'optparse.OptionParser', 'OptionParser', ([], {}), '()\n', (873, 875), False, 'from optparse import OptionParser\n'), ((1752, 1799), 'extract_datasets.extract_labeled_chunkrange', 'extrac... |
from django.db import models
from authors.models import Author
class Book(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
description = models.TextField()
pages = models.IntegerField()
editor = models.CharField(max_length=50)
... | [
"django.db.models.TextField",
"django.db.models.IntegerField",
"django.db.models.ForeignKey",
"django.db.models.BooleanField",
"django.db.models.ImageField",
"django.db.models.CharField"
] | [((103, 154), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Author'], {'on_delete': 'models.CASCADE'}), '(Author, on_delete=models.CASCADE)\n', (120, 154), False, 'from django.db import models\n'), ((167, 199), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(200)'}), '(max_length=200)\n... |
import datetime
import os
import yaml
def get_steps(scenario):
text = ''
for step in scenario.steps:
text += step.step_type.upper() + ' ' + step.name + ' '
return text
def get_scenarios(feature):
text = ''
for scenario in feature.scenarios:
text += get_steps(scenario)
tex... | [
"datetime.datetime.now",
"yaml.safe_dump",
"os.path.join",
"yaml.load"
] | [((475, 498), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (496, 498), False, 'import datetime\n'), ((639, 685), 'os.path.join', 'os.path.join', (['"""BDD"""', 'context.scenario.filename'], {}), "('BDD', context.scenario.filename)\n", (651, 685), False, 'import os\n'), ((849, 894), 'os.path.join'... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %%
# from IPython import get_ipython
# get_ipython().run_line_magic('matplotlib', 'inline')
import sys
import os
import pandas as pd
import matplotlib.pyplot as plt
# %%
def split_... | [
"pandas.read_csv",
"os.path.join",
"os.path.dirname",
"matplotlib.pyplot.figure",
"os.path.basename"
] | [((1134, 1157), 'os.path.dirname', 'os.path.dirname', (['ifname'], {}), '(ifname)\n', (1149, 1157), False, 'import os\n'), ((1173, 1197), 'os.path.basename', 'os.path.basename', (['ifname'], {}), '(ifname)\n', (1189, 1197), False, 'import os\n'), ((1237, 1274), 'os.path.join', 'os.path.join', (['dirname', '"""tmp_file.... |
import logging
logging.basicConfig(level=logging.DEBUG)
from slack_bolt import App, BoltContext
from slack_bolt.oauth import OAuthFlow
from slack_sdk import WebClient
app = App(oauth_flow=OAuthFlow.sqlite3(database="./slackapp.db"))
@app.use
def dump(context, next, logger):
logger.info(context)
next()
@... | [
"logging.basicConfig",
"slack_bolt.oauth.OAuthFlow.sqlite3"
] | [((16, 56), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG'}), '(level=logging.DEBUG)\n', (35, 56), False, 'import logging\n'), ((192, 235), 'slack_bolt.oauth.OAuthFlow.sqlite3', 'OAuthFlow.sqlite3', ([], {'database': '"""./slackapp.db"""'}), "(database='./slackapp.db')\n", (209, 235), Fals... |
import numpy as np
a = np.arange(24).reshape(3, 2, 4) + 10
for val in a:
print('item:', val)
# N维枚举
for i, val in np.ndenumerate(a):
if sum(i) % 5 == 0:
print(i, val)
| [
"numpy.ndenumerate",
"numpy.arange"
] | [((120, 137), 'numpy.ndenumerate', 'np.ndenumerate', (['a'], {}), '(a)\n', (134, 137), True, 'import numpy as np\n'), ((24, 37), 'numpy.arange', 'np.arange', (['(24)'], {}), '(24)\n', (33, 37), True, 'import numpy as np\n')] |
#
# Dispatcher.py
#
# (c) 2020 by <NAME>
# License: BSD 3-Clause License. See the LICENSE file for further details.
#
# Most internal requests are routed through here.
#
from __future__ import annotations
import sys, traceback, re
from copy import deepcopy
import isodate
from flask import Request
from typing import An... | [
"Utils.noDomain",
"Logging.Logging.logWarn",
"CSE.storage.countDirectChildResources",
"Utils.fanoutPointResource",
"CSE.storage.hasResource",
"Logging.Logging.log",
"Utils.isVirtualResource",
"copy.deepcopy",
"CSE.event.createResource",
"Logging.Logging.logDebug",
"CSE.event.updateResource",
"... | [((1237, 1285), 'Configuration.Configuration.get', 'Configuration.get', (['"""cse.sortDiscoveredResources"""'], {}), "('cse.sortDiscoveredResources')\n", (1254, 1285), False, 'from Configuration import Configuration\n'), ((1288, 1325), 'Logging.Logging.log', 'Logging.log', (['"""Dispatcher initialized"""'], {}), "('Dis... |
import glob
import os
import pickle
import shlex
import tarfile
import tempfile
import threading
from typing import Any, Dict, Iterable, List, NamedTuple, Optional, Set, Tuple, Union
import boto3
from redun.file import File
from redun.hashing import hash_stream
from redun.scheduler import Job
# Constants.
REDUN_PROG... | [
"tempfile.TemporaryDirectory",
"tarfile.open",
"boto3.client",
"redun.file.File",
"shlex.split",
"redun.hashing.hash_stream",
"boto3.Session",
"os.path.join",
"pickle.load",
"os.path.split",
"threading.get_ident"
] | [((2005, 2019), 'redun.file.File', 'File', (['tar_path'], {}), '(tar_path)\n', (2009, 2019), False, 'from redun.file import File\n'), ((2644, 2698), 'os.path.join', 'os.path.join', (['s3_scratch_prefix', '"""jobs"""', 'job.eval_hash'], {}), "(s3_scratch_prefix, 'jobs', job.eval_hash)\n", (2656, 2698), False, 'import os... |
from typing import Callable, Dict, List, Union
import dgl
import dgl.nn.pytorch as dglnn
import torch
import torch.nn as nn
class RelGraphEmbedding(nn.Module):
def __init__(
self,
hg: dgl.DGLHeteroGraph,
embedding_size: int,
num_nodes: Dict[str, int],
node_feats: Dict[str,... | [
"torch.nn.ParameterDict",
"torch.split",
"torch.nn.Dropout",
"dgl.dataloading.MultiLayerFullNeighborSampler",
"torch.nn.ModuleList",
"torch.nn.init.xavier_uniform_",
"torch.nn.LayerNorm",
"torch.Tensor",
"torch.nn.init.zeros_",
"torch.matmul",
"torch.nn.ModuleDict",
"torch.nn.init.calculate_ga... | [((566, 581), 'torch.nn.ModuleDict', 'nn.ModuleDict', ([], {}), '()\n', (579, 581), True, 'import torch.nn as nn\n'), ((6067, 6092), 'torch.nn.Dropout', 'nn.Dropout', (['input_dropout'], {}), '(input_dropout)\n', (6077, 6092), True, 'import torch.nn as nn\n'), ((6117, 6136), 'torch.nn.Dropout', 'nn.Dropout', (['dropout... |
"""MCTS module: where MuZero thinks inside the tree."""
import math
import random
import numpy as np
from xt.agent.muzero.default_config import PB_C_BASE, PB_C_INIT
from xt.agent.muzero.default_config import ROOT_DIRICHLET_ALPHA
from xt.agent.muzero.default_config import ROOT_EXPLORATION_FRACTION
from xt.agent.muzer... | [
"xt.agent.muzero.util.soft_max_sample",
"math.sqrt",
"numpy.argmax",
"math.log",
"numpy.random.dirichlet",
"xt.agent.muzero.util.MinMaxStats",
"xt.agent.muzero.util.Node"
] | [((733, 750), 'xt.agent.muzero.util.MinMaxStats', 'MinMaxStats', (['None'], {}), '(None)\n', (744, 750), False, 'from xt.agent.muzero.util import MinMaxStats, Node, soft_max_sample\n'), ((1042, 1049), 'xt.agent.muzero.util.Node', 'Node', (['(0)'], {}), '(0)\n', (1046, 1049), False, 'from xt.agent.muzero.util import Min... |
'''
AUTHORS:
NORSTRÖM, ARVID 19940206-3193,
HISELIUS, LEO 9402214192
'''
from collections import namedtuple
import numpy as np
import gym
import torch
import matplotlib.pyplot as plt
from tqdm import trange
from DDPG_agent import RandomAgent, Critic, Actor
from DDPG_agent import ExperienceReplayBuffer
import... | [
"numpy.random.rand",
"DDPG_agent.ExperienceReplayBuffer",
"torch.nn.MSELoss",
"numpy.array",
"gym.make",
"DDPG_agent.Actor",
"numpy.eye",
"collections.namedtuple",
"numpy.ones",
"torch.save",
"tqdm.trange",
"torch.device",
"DDPG_agent.Critic",
"numpy.copy",
"torch.tensor",
"numpy.zeros... | [((397, 433), 'gym.make', 'gym.make', (['"""LunarLanderContinuous-v2"""'], {}), "('LunarLanderContinuous-v2')\n", (405, 433), False, 'import gym\n'), ((525, 543), 'torch.device', 'torch.device', (['ddev'], {}), '(ddev)\n', (537, 543), False, 'import torch\n'), ((970, 1023), 'tqdm.trange', 'trange', (['self.N_episodes']... |
# Copyright 2020 The FedLearner 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 applica... | [
"sqlalchemy.orm.sessionmaker",
"sqlalchemy.ext.automap.automap_base",
"sqlalchemy.create_engine",
"os.environ.get",
"logging.error"
] | [((1018, 1056), 'os.environ.get', 'os.environ.get', (['"""DB_SOCKET_PATH"""', 'None'], {}), "('DB_SOCKET_PATH', None)\n", (1032, 1056), False, 'import os\n'), ((7212, 7268), 'sqlalchemy.create_engine', 'create_engine', (['conn_string'], {'echo': '(False)', 'pool_recycle': '(180)'}), '(conn_string, echo=False, pool_recy... |
import cv2
print(cv2.__version__)
rows = int(input('Enter Number of ROWS: '))
columns = int(input('Enter Number of COLUMNS: '))
width = 1000
height = 1000
import numpy as np
while True:
frame = np.zeros([width,height,3],dtype=np.uint8)
WhiteW = width // columns
WhiteH = height // rows
for i in range(0,r... | [
"numpy.zeros",
"cv2.waitKey",
"cv2.imshow"
] | [((198, 242), 'numpy.zeros', 'np.zeros', (['[width, height, 3]'], {'dtype': 'np.uint8'}), '([width, height, 3], dtype=np.uint8)\n', (206, 242), True, 'import numpy as np\n'), ((614, 643), 'cv2.imshow', 'cv2.imshow', (['"""myWindow"""', 'frame'], {}), "('myWindow', frame)\n", (624, 643), False, 'import cv2\n'), ((652, 6... |
import sys
if len(sys.argv) > 1 and sys.argv[1] == "--pre":
from aiida import orm
group, _ = orm.Group.objects.get_or_create("delete-nodes")
group.remove_nodes(group.nodes[:])
for i in range(1000):
node = orm.Data()
node.store()
group.add_nodes([node])
else:
from aiida import... | [
"aiida.orm.Group.objects.get_or_create",
"aiida.orm.Data",
"aiida.manage.database.delete.nodes.delete_nodes"
] | [((101, 148), 'aiida.orm.Group.objects.get_or_create', 'orm.Group.objects.get_or_create', (['"""delete-nodes"""'], {}), "('delete-nodes')\n", (132, 148), False, 'from aiida import orm\n'), ((404, 451), 'aiida.orm.Group.objects.get_or_create', 'orm.Group.objects.get_or_create', (['"""delete-nodes"""'], {}), "('delete-no... |
from datetime import datetime
from typing import Callable
from unittest.mock import Mock, patch
import visiology_py as vi
from tests.fixtures import *
def test_token_expires(
expire_date: datetime,
before_expire_date: datetime,
after_expire_date: datetime,
fixed_datetime: Callable[[datetime], Mock],
... | [
"visiology_py.AuthorizationToken"
] | [((343, 430), 'visiology_py.AuthorizationToken', 'vi.AuthorizationToken', ([], {'type': '"""Something"""', 'secret': '"""Anything"""', 'expires_at': 'expire_date'}), "(type='Something', secret='Anything', expires_at=\n expire_date)\n", (364, 430), True, 'import visiology_py as vi\n')] |
import pytest
import networkx as nx
class TestFilterFactory(object):
def test_no_filter(self):
nf = nx.filters.no_filter
assert nf()
assert nf(1)
assert nf(2, 1)
def test_hide_nodes(self):
f = nx.classes.filters.hide_nodes([1, 2, 3])
assert not f(1)
ass... | [
"networkx.classes.filters.hide_nodes",
"networkx.classes.filters.show_nodes",
"pytest.raises"
] | [((244, 284), 'networkx.classes.filters.hide_nodes', 'nx.classes.filters.hide_nodes', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (273, 284), True, 'import networkx as nx\n'), ((427, 460), 'pytest.raises', 'pytest.raises', (['TypeError', 'f', '(1)', '(2)'], {}), '(TypeError, f, 1, 2)\n', (440, 460), False, 'import pytest\n')... |
#!/usr/bin/env python
def getinput(): return open('day8.input.txt').read().splitlines()
import re, pytesseract
from PIL import Image, ImageOps
def solve(cx, cy, instrs):
grid = [['.'] * cx for _ in range(cy)]
for instr in instrs:
nums = [int(v) for v in re.findall('\d+', instr)]
if 'rect' in ... | [
"re.findall",
"pytesseract.image_to_string"
] | [((1585, 1617), 'pytesseract.image_to_string', 'pytesseract.image_to_string', (['img'], {}), '(img)\n', (1612, 1617), False, 'import re, pytesseract\n'), ((273, 298), 're.findall', 're.findall', (['"""\\\\d+"""', 'instr'], {}), "('\\\\d+', instr)\n", (283, 298), False, 'import re, pytesseract\n')] |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from collections import defaultdict
from contextlib import contextmanager
import theano
from theano import tensor as T
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
from theano.tensor.si... | [
"theano.tensor.zeros_like",
"theano.tensor.argmin",
"theano.tensor.nnet.abstract_conv.AbstractConv2d_gradInputs",
"theano.tensor.alloc",
"theano.map",
"theano.tensor.tile",
"theano.tensor.squeeze",
"theano.tensor.stack",
"theano.tensor.inv",
"theano.tensor.std",
"theano.tensor.nnet.abstract_conv... | [((1191, 1243), 'theano.tensor.scalar', 'T.scalar', ([], {'dtype': '"""uint8"""', 'name': '"""keras_learning_phase"""'}), "(dtype='uint8', name='keras_learning_phase')\n", (1199, 1243), True, 'from theano import tensor as T\n'), ((1260, 1276), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (1271, 1... |
import logging
class Contract():
def __init__(self, name, event_handlers, commit_processors, schedule_processors, contract_connection):
self._name = name
self._address = contract_connection.address
self._contract_connection = contract_connection
self._event_handlers = event_handlers... | [
"logging.getLogger"
] | [((550, 577), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (567, 577), False, 'import logging\n')] |
from flask import Flask, make_response
from flask_restful import Api
import logging
import sys
def create_app():
app = Flask(__name__, instance_relative_config=True)
api = Api(app)
app.config.from_object('config')
logger = logging.getLogger('tagging')
try:
logging_level = os.environ.get("LO... | [
"logging.getLogger",
"logging.StreamHandler",
"flask_restful.Api",
"flask.Flask",
"logging.Formatter"
] | [((124, 170), 'flask.Flask', 'Flask', (['__name__'], {'instance_relative_config': '(True)'}), '(__name__, instance_relative_config=True)\n', (129, 170), False, 'from flask import Flask, make_response\n'), ((181, 189), 'flask_restful.Api', 'Api', (['app'], {}), '(app)\n', (184, 189), False, 'from flask_restful import Ap... |
import copy
from tool.runners.python import SubmissionPy
BUG = "#"
EMPTY = "."
class ThoreSubmission(SubmissionPy):
def run(self, s):
# :param s: input in string format
# :return: solution flag
world = parse_input(s)
seen_states = set()
while True:
seen_state... | [
"copy.deepcopy"
] | [((690, 710), 'copy.deepcopy', 'copy.deepcopy', (['world'], {}), '(world)\n', (703, 710), False, 'import copy\n')] |
from komoog.komoot import choose_downloaded_komoot_tour
from komoog.audio import convert_tour_to_audio, play_audio
tour = choose_downloaded_komoot_tour()
audio, sampling_rate = convert_tour_to_audio(tour,
tune='C#',
approximate_l... | [
"komoog.audio.play_audio",
"komoog.audio.convert_tour_to_audio",
"komoog.komoot.choose_downloaded_komoot_tour"
] | [((123, 154), 'komoog.komoot.choose_downloaded_komoot_tour', 'choose_downloaded_komoot_tour', ([], {}), '()\n', (152, 154), False, 'from komoog.komoot import choose_downloaded_komoot_tour\n'), ((178, 291), 'komoog.audio.convert_tour_to_audio', 'convert_tour_to_audio', (['tour'], {'tune': '"""C#"""', 'approximate_length... |
from setuptools import setup, find_packages
# read readme
with open("README.md", "r") as f:
readme = f.read()
setup(
name="bpreg",
version="1.1.0",
packages=find_packages(),
url="https://github.com/MIC-DKFZ/BodyPartRegression",
include_package_data=True,
package_data={"bpreg": ["settings/b... | [
"setuptools.find_packages"
] | [((175, 190), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (188, 190), False, 'from setuptools import setup, find_packages\n')] |
import xlwt # 这是操作excel的库,需要安装这个库 命令: pip install xlwt
import requests
from lxml import etree
# 上面这两行是需要装的库
# 目前只取了列表页店铺名和商品名和价格信息,评价数暂时拿不到
def get_lsf_info_from_jd():
"""京东螺狮粉部分信息"""
# 这是请求头信息
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KH... | [
"xlwt.Workbook",
"lxml.etree.HTML",
"requests.get"
] | [((549, 583), 'requests.get', 'requests.get', (['url'], {'headers': 'headers'}), '(url, headers=headers)\n', (561, 583), False, 'import requests\n'), ((649, 672), 'lxml.etree.HTML', 'etree.HTML', (['res.content'], {}), '(res.content)\n', (659, 672), False, 'from lxml import etree\n'), ((2211, 2226), 'xlwt.Workbook', 'x... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Date: 2022/2/24 14:50
Desc: 真气网-空气质量
https://www.zq12369.com/environment.php
空气质量在线监测分析平台的空气质量数据
https://www.aqistudy.cn/
"""
import json
import os
import re
import pandas as pd
import requests
from py_mini_racer import py_mini_racer
from akshare.utils import demjson
... | [
"requests.post",
"re.compile",
"pandas.read_html",
"json.dumps",
"os.path.join",
"py_mini_racer.py_mini_racer.MiniRacer",
"requests.get",
"os.path.dirname",
"pandas.to_numeric",
"pandas.DataFrame"
] | [((667, 707), 'os.path.join', 'os.path.join', (['module_folder', '"""air"""', 'name'], {}), "(module_folder, 'air', name)\n", (679, 707), False, 'import os\n'), ((2907, 2932), 'py_mini_racer.py_mini_racer.MiniRacer', 'py_mini_racer.MiniRacer', ([], {}), '()\n', (2930, 2932), False, 'from py_mini_racer import py_mini_ra... |
import requests
from difflib import get_close_matches
import xml.etree.ElementTree as ET
from .list_data import states, districts
def get_state_data(state):
url = "https://api.covid19india.org/data.json"
response = requests.get(url).json()
if state == "India":
state = "Total"
if state ==... | [
"xml.etree.ElementTree.fromstring",
"difflib.get_close_matches",
"requests.get"
] | [((2427, 2450), 'requests.get', 'requests.get', (['news_link'], {}), '(news_link)\n', (2439, 2450), False, 'import requests\n'), ((2462, 2490), 'xml.etree.ElementTree.fromstring', 'ET.fromstring', (['repsonse.text'], {}), '(repsonse.text)\n', (2475, 2490), True, 'import xml.etree.ElementTree as ET\n'), ((809, 858), 'di... |
#!/usr/bin/python
#
# Various helper methods and includes for Cityscapes
#
# Python imports
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os, sys, getopt
import glob
import math
import json
from collections import namedtuple
# Image processing
# Ch... | [
"collections.namedtuple",
"os.makedirs",
"json.dumps",
"os.path.dirname",
"os.path.isdir",
"os.path.basename",
"sys.exit",
"math.isnan"
] | [((1098, 1215), 'collections.namedtuple', 'namedtuple', (['"""Label"""', "['name', 'id', 'trainId', 'category', 'categoryId', 'hasInstances',\n 'ignoreInEval', 'color']"], {}), "('Label', ['name', 'id', 'trainId', 'category', 'categoryId',\n 'hasInstances', 'ignoreInEval', 'color'])\n", (1108, 1215), False, 'from... |
try:
import unittest
from copy import copy
from numpy.testing import assert_allclose
import numpy as np
from spitfire.chemistry.mechanism import ChemicalMechanismSpec
from spitfire.chemistry.library import Library, Dimension
from spitfire.chemistry.flamelet import FlameletSpec
from spi... | [
"spitfire.chemistry.library.Library",
"spitfire.chemistry.library.Dimension",
"numpy.testing.assert_allclose",
"cantera.__version__.replace",
"numpy.squeeze",
"numpy.swapaxes",
"numpy.linspace",
"numpy.isnan",
"spitfire.chemistry.tabulation.build_adiabatic_eq_library",
"spitfire.chemistry.mechanis... | [((490, 526), 'cantera.__version__.replace', 'cantera.__version__.replace', (['"""."""', '""""""'], {}), "('.', '')\n", (517, 526), False, 'import cantera\n'), ((9336, 9351), 'unittest.main', 'unittest.main', ([], {}), '()\n', (9349, 9351), False, 'import unittest\n'), ((625, 674), 'cantera.Solution', 'ct.Solution', ([... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2022/3/16 7:27 下午
# @Author : xinming
# @File : 542_update_matrix.py
from typing import List
import collections
class Solution:
def updateMatrix(self, matrix: List[List[int]]) -> List[List[int]]:
m, n = len(matrix), len(matrix[0])
dist... | [
"collections.deque"
] | [((476, 505), 'collections.deque', 'collections.deque', (['zeroes_pos'], {}), '(zeroes_pos)\n', (493, 505), False, 'import collections\n')] |
from copy import deepcopy
import datetime
import decimal
from sqlalchemy import ARRAY
from sqlalchemy import bindparam
from sqlalchemy import Boolean
from sqlalchemy import Column
from sqlalchemy import Date
from sqlalchemy import DateTime
from sqlalchemy import extract
from sqlalchemy import func
from sqlalchemy impo... | [
"sqlalchemy.func.current_timestamp",
"sqlalchemy.sql.quoted_name",
"sqlalchemy.sql.annotation._deep_annotate",
"copy.deepcopy",
"sqlalchemy.testing.assertions.expect_warnings",
"sqlalchemy.Column",
"sqlalchemy.func.rollup",
"sqlalchemy.func.rows",
"sqlalchemy.func.count",
"decimal.Decimal",
"sql... | [((1543, 1566), 'sqlalchemy.sql.column', 'column', (['"""myid"""', 'Integer'], {}), "('myid', Integer)\n", (1549, 1566), False, 'from sqlalchemy.sql import column\n'), ((1572, 1594), 'sqlalchemy.sql.column', 'column', (['"""name"""', 'String'], {}), "('name', String)\n", (1578, 1594), False, 'from sqlalchemy.sql import... |
from st2common.runners.base_action import Action
import requests
__all__ = [
'InfobloxBaseAction'
]
class InfobloxBaseAction(Action):
"""Base Action for all Infoblox API based actions
"""
def __init__(self, config):
super(InfobloxBaseAction, self).__init__(config)
def _make_request(se... | [
"requests.patch",
"requests.put",
"requests.post",
"requests.get"
] | [((1205, 1282), 'requests.get', 'requests.get', (['url'], {'verify': "self.config['ssl_verify']", 'auth': 'auth', 'params': 'kwargs'}), "(url, verify=self.config['ssl_verify'], auth=auth, params=kwargs)\n", (1217, 1282), False, 'import requests\n'), ((1418, 1494), 'requests.post', 'requests.post', (['url'], {'verify': ... |
# -*- coding: utf-8 -*-
import scrapy
from shiyanlougithub.items import ShiyanlougithubItem
class ShiyanlouSpider(scrapy.Spider):
name = 'shiyanlou'
allowed_domains = ['github.com']
def start_urls(self):
return ('https://github.com/shiyanlou?tab=repositories',)
def parse(self, response):
... | [
"scrapy.Request"
] | [((735, 796), 'scrapy.Request', 'scrapy.Request', (['responsitory_url'], {'callback': 'self.parse_commits'}), '(responsitory_url, callback=self.parse_commits)\n', (749, 796), False, 'import scrapy\n')] |
"""Internal module for human-friendly color generation.
.. important::
End users of this library should not use anything in this module.
Code adapted from:
- https://github.com/davidmerfield/randomColor (CC0)
- https://github.com/kevinwuhoo/randomcolor-py (MIT License)
Additional reference from:
- https://en.wi... | [
"random.Random",
"math.fabs",
"random.randint",
"colorsys.hsv_to_rgb"
] | [((9710, 9756), 'colorsys.hsv_to_rgb', 'colorsys.hsv_to_rgb', (['(h / 360)', '(s / 100)', '(v / 100)'], {}), '(h / 360, s / 100, v / 100)\n', (9729, 9756), False, 'import colorsys\n'), ((3380, 3404), 'random.Random', 'random.Random', (['self.seed'], {}), '(self.seed)\n', (3393, 3404), False, 'import random\n'), ((3323,... |
# The MIT License
#
# Copyright (c) 2009-2015 the bpython authors.
# Copyright (c) 2015-2020 <NAME>
#
# 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 li... | [
"logging.getLogger",
"glob.escape",
"jedi.Script",
"os.path.isdir",
"rlcompleter.get_class_members",
"typing.cast",
"os.path.expanduser",
"re.search"
] | [((4919, 4937), 're.search', 're.search', (['s', 'word'], {}), '(s, word)\n', (4928, 4937), False, 'import re\n'), ((10026, 10054), 'os.path.expanduser', 'os.path.expanduser', (['username'], {}), '(username)\n', (10044, 10054), False, 'import os\n'), ((11027, 11066), 'typing.cast', 'cast', (['Dict[str, Any]', "kwargs['... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2018-2018 by ExopyI3py Authors, see AUTHORS for more details.
#
# Distributed under the terms of the BSD license.
#
# The full license is in the file LICENCE, distributed with this software.
# -----------... | [
"enaml.imports"
] | [((565, 580), 'enaml.imports', 'enaml.imports', ([], {}), '()\n', (578, 580), False, 'import enaml\n')] |
"""
CLI, main routine
"""
import logging
import sys
from pathlib import Path
from synthaser import (
search,
models,
parsers,
download,
config,
classify
)
from synthaser.plot import plot_synthases
from Bio import Entrez
logging.basicConfig(
format="[%(asctime)s] %(levelname)s - %(messag... | [
"logging.basicConfig",
"synthaser.config.get_config_parser",
"logging.getLogger",
"synthaser.parsers.parse_args",
"pathlib.Path",
"synthaser.classify.classify",
"synthaser.models.SynthaseContainer.from_json",
"synthaser.genbank.convert",
"synthaser.search.prepare_input",
"synthaser.config.write_co... | [((249, 344), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""[%(asctime)s] %(levelname)s - %(message)s"""', 'datefmt': '"""%H:%M:%S"""'}), "(format='[%(asctime)s] %(levelname)s - %(message)s',\n datefmt='%H:%M:%S')\n", (268, 344), False, 'import logging\n'), ((354, 384), 'logging.getLogger', 'logg... |
"""Terraform version management."""
from distutils.version import LooseVersion # noqa pylint: disable=import-error,no-name-in-module
import glob
import json
import logging
import os
import platform
import re
import shutil
import sys
import tempfile
import zipfile
# Old pylint on py2.7 incorrectly flags these
from six... | [
"logging.getLogger",
"sys.exit",
"botocore.vendored.requests.get",
"os.path.join",
"re.match",
"os.environ.get",
"os.getcwd",
"os.path.isfile",
"platform.system",
"os.path.isdir",
"tempfile.mkdtemp",
"os.mkdir",
"shutil.rmtree",
"runway.embedded.hcl.load",
"os.path.expanduser",
"re.sea... | [((733, 760), 'logging.getLogger', 'logging.getLogger', (['"""runway"""'], {}), "('runway')\n", (750, 760), False, 'import logging\n'), ((1158, 1193), 'os.path.join', 'os.path.join', (['versions_dir', 'version'], {}), '(versions_dir, version)\n', (1170, 1193), False, 'import os\n'), ((1872, 1890), 'tempfile.mkdtemp', '... |
from os.path import join
import torchvision.datasets as datasets
__DATASETS_DEFAULT_PATH = '/media/ssd/Datasets/'
def get_dataset(name, train, transform, target_transform=None, download=True, datasets_path=__DATASETS_DEFAULT_PATH):
root = datasets_path # '/mnt/ssd/ImageNet/ILSVRC/Data/CLS-LOC' #os.path.join(dat... | [
"os.path.join",
"torchvision.datasets.ImageFolder",
"torchvision.datasets.CIFAR100",
"torchvision.datasets.CIFAR10"
] | [((382, 501), 'torchvision.datasets.CIFAR10', 'datasets.CIFAR10', ([], {'root': 'root', 'train': 'train', 'transform': 'transform', 'target_transform': 'target_transform', 'download': 'download'}), '(root=root, train=train, transform=transform,\n target_transform=target_transform, download=download)\n', (398, 501), ... |
# coding: utf-8
# """
# 8 TILE GAME
# States: location of 8 each tiles in 3x3 grid
# Initial state: Any state
# Actions: Up, Down, Left, Right
# Transition model: Given a state and an action, return resulting state
# Goal test: state matches the goal state?
# Path cost: Total moves, each move costs 1
# Expand: functio... | [
"resource.getrusage",
"collections.deque",
"time.time",
"sys.exit"
] | [((511, 522), 'time.time', 'time.time', ([], {}), '()\n', (520, 522), False, 'import time\n'), ((1293, 1300), 'collections.deque', 'deque', ([], {}), '()\n', (1298, 1300), False, 'from collections import deque\n'), ((878, 889), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (886, 889), False, 'import sys\n'), ((2886, ... |
import logging
import logging.config
import yaml
def load_logging():
with open("logging_config.yaml", "r") as f:
config = yaml.safe_load(f.read())
logging.config.dictConfig(config)
logger = logging.getLogger(__name__)
# Demonstration code. This logs the handlers just for this logger
lo... | [
"logging.getLogger",
"logging.config.dictConfig"
] | [((216, 243), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (233, 243), False, 'import logging\n'), ((169, 202), 'logging.config.dictConfig', 'logging.config.dictConfig', (['config'], {}), '(config)\n', (194, 202), False, 'import logging\n')] |
from django.urls import include, path
urlpatterns = [
path("", include("src.apps.blog.urls")),
path("", include("src.apps.shop.urls")),
path("", include("src.apps.menu.urls")),
path("", include("src.apps.slider.urls")),
path("", include("src.apps.account.urls")),
path("", include("src.apps.subs... | [
"django.urls.include"
] | [((68, 97), 'django.urls.include', 'include', (['"""src.apps.blog.urls"""'], {}), "('src.apps.blog.urls')\n", (75, 97), False, 'from django.urls import include, path\n'), ((113, 142), 'django.urls.include', 'include', (['"""src.apps.shop.urls"""'], {}), "('src.apps.shop.urls')\n", (120, 142), False, 'from django.urls i... |
import socket
alert = 'test'
stomp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
stomp.connect(('localhost', 61613))
stomp.send('CONNECT\n\n\x00')
recv = stomp.recv(4096)
if 'CONNECTED' in recv:
stomp.send('SEND\ndestination:%s\n\n' % '/queue/test')
stomp.send(alert)
stomp.send('\x00')
else:
pr... | [
"socket.socket"
] | [((40, 89), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (53, 89), False, 'import socket\n')] |
import os
import json
import copy
import unittest
import shutil
from dxtrack import dxtrack
output_file = './.dxtrack_output/error.jsonl'
context = 'test_error_track'
stage = 'test'
run_id = 'test_run_id'
default_metadata = {'default': 'metadata'}
class TestErrorTrack(unittest.TestCase):
def setUp(self):
... | [
"os.path.exists",
"json.loads",
"dxtrack.dxtrack.errors",
"dxtrack.dxtrack.error",
"dxtrack.dxtrack.configure",
"shutil.rmtree",
"os.path.dirname",
"copy.deepcopy",
"unittest.main"
] | [((3036, 3051), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3049, 3051), False, 'import unittest\n'), ((323, 369), 'shutil.rmtree', 'shutil.rmtree', (['output_file'], {'ignore_errors': '(True)'}), '(output_file, ignore_errors=True)\n', (336, 369), False, 'import shutil\n'), ((379, 480), 'dxtrack.dxtrack.config... |
from typing import NamedTuple, List
from explorer.models.blockchain_models import BlockV2,TransactionV2,Chain
from explorer.utils.misc_helpers import str_datetime_to_timestamp
from explorer.utils import CustomLogger
import traceback
import asyncio
import aiohttp
import traceback
import time
from eth_utils.address imp... | [
"aiohttp.ClientSession",
"eth_utils.address.to_checksum_address",
"explorer.utils.CustomLogger",
"time.perf_counter",
"explorer.utils.misc_helpers.str_datetime_to_timestamp",
"explorer.models.blockchain_models.TransactionV2",
"traceback.print_exc",
"time.time",
"explorer.models.blockchain_models.Blo... | [((612, 626), 'explorer.utils.CustomLogger', 'CustomLogger', ([], {}), '()\n', (624, 626), False, 'from explorer.utils import CustomLogger\n'), ((1448, 1467), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (1465, 1467), False, 'import time\n'), ((420, 434), 'explorer.utils.CustomLogger', 'CustomLogger', ([... |
"""
Unit tests for Metric class
"""
from sys import version_info
from statistics import StatisticsError
from pytest import raises
from mtg_mana_simulator.metric import Metric
def traces():
"""Example traces"""
trace1 = [1,2,3]
trace2 = [1,2,2]
trace3 = [0,0,1]
trace4 = [0,0,0]
return [trace1, ... | [
"mtg_mana_simulator.metric.Metric.minimum_mana",
"mtg_mana_simulator.metric.Metric.percentile",
"pytest.raises"
] | [((1755, 1780), 'mtg_mana_simulator.metric.Metric.minimum_mana', 'Metric.minimum_mana', (['mana'], {}), '(mana)\n', (1774, 1780), False, 'from mtg_mana_simulator.metric import Metric\n'), ((2045, 2072), 'mtg_mana_simulator.metric.Metric.percentile', 'Metric.percentile', (['fraction'], {}), '(fraction)\n', (2062, 2072),... |
#!/usr/bin/env python
"""Check that the commits that the user is about to push, do not look
like the user has forgotten to squash work-in-progress commits.
"""
import os
import subprocess
import sys
from cogite import interaction
# If the user pushes MAX_COMMITS or more, ask for confirmation.
MAX_COMMITS = 2
DISPLA... | [
"subprocess.Popen",
"cogite.interaction.confirm",
"sys.exit"
] | [((438, 499), 'subprocess.Popen', 'subprocess.Popen', (['command'], {'shell': '(True)', 'stdout': 'subprocess.PIPE'}), '(command, shell=True, stdout=subprocess.PIPE)\n', (454, 499), False, 'import subprocess\n'), ((2463, 2481), 'sys.exit', 'sys.exit', (['os.ex_OK'], {}), '(os.ex_OK)\n', (2471, 2481), False, 'import sys... |
from SpoonacularCLI.spoonacular_client import SpoonacularClient, SpoonacularEnums
from unittest import TestCase
from unittest.mock import patch
import pytest
import json
import os
BASE_DIR = os.path.dirname((os.path.abspath(__file__)))
class TestSpoonacularClient(TestCase):
def setUp(self) -> None:
self.... | [
"os.path.join",
"SpoonacularCLI.spoonacular_client.SpoonacularClient",
"pytest.fixture",
"json.load",
"os.path.abspath",
"unittest.mock.patch"
] | [((209, 234), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (224, 234), False, 'import os\n'), ((1312, 1340), 'pytest.fixture', 'pytest.fixture', ([], {'autouse': '(True)'}), '(autouse=True)\n', (1326, 1340), False, 'import pytest\n'), ((3795, 3852), 'unittest.mock.patch', 'patch', (['"""Spo... |
from flask_restful import Resource, reqparse
import docker
import os
import json
import yaml
import ast
import subprocess
# This endpoint takes care of building the Hadoop cluster from a docker-compose file
class Builder(Resource):
def __init__(self):
self.origin = 'http://localhost:3000'
self.stat... | [
"subprocess.check_output",
"flask_restful.reqparse.RequestParser",
"yaml.dump",
"yaml.load",
"ast.literal_eval",
"json.load",
"json.dump",
"os.remove"
] | [((969, 993), 'flask_restful.reqparse.RequestParser', 'reqparse.RequestParser', ([], {}), '()\n', (991, 993), False, 'from flask_restful import Resource, reqparse\n'), ((2977, 3055), 'subprocess.check_output', 'subprocess.check_output', (["['docker', 'run', '-d', 'johnnoon74/getting-started']"], {}), "(['docker', 'run'... |
import torch
import torch.nn as nn
from bert_seq2seq.tokenizer import load_chinese_base_vocab, Tokenizer
class BasicBert(nn.Module):
def __init__(self):
super().__init__()
#self.device = torch.device("cpu")
def load_pretrain_params(self, pretrain_model_path, keep_tokens=None):
check... | [
"torch.load",
"torch.cuda.empty_cache"
] | [((328, 359), 'torch.load', 'torch.load', (['pretrain_model_path'], {}), '(pretrain_model_path)\n', (338, 359), False, 'import torch\n'), ((864, 888), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (886, 888), False, 'import torch\n'), ((1025, 1068), 'torch.load', 'torch.load', (['model_path'], {... |
from datetime import datetime
from django.db import models
# Create your models here.
class Posts(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
created_ts = models.DateTimeField(default=datetime.now, blank=True)
def __str__(self):
return s... | [
"django.db.models.DateTimeField",
"django.db.models.TextField",
"django.db.models.CharField"
] | [((136, 168), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(200)'}), '(max_length=200)\n', (152, 168), False, 'from django.db import models\n'), ((187, 205), 'django.db.models.TextField', 'models.TextField', ([], {}), '()\n', (203, 205), False, 'from django.db import models\n'), ((224, 278), '... |
# -*- coding: utf-8 -*-
# Copyright 2020 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... | [
"google.cloud.networkconnectivity_v1.types.hub.DeleteHubRequest",
"google.cloud.networkconnectivity_v1.services.hub_service.pagers.ListSpokesAsyncPager",
"google.cloud.networkconnectivity_v1.types.hub.GetHubRequest",
"google.cloud.networkconnectivity_v1.services.hub_service.pagers.ListHubsAsyncPager",
"goog... | [((10367, 10395), 'google.cloud.networkconnectivity_v1.types.hub.ListHubsRequest', 'hub.ListHubsRequest', (['request'], {}), '(request)\n', (10386, 10395), False, 'from google.cloud.networkconnectivity_v1.types import hub\n'), ((10692, 10819), 'google.api_core.gapic_v1.method_async.wrap_method', 'gapic_v1.method_async.... |
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
SQLALCHEMY_DATABASE_URL = "mysql://local:testing@localhost/test"
# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db"
engine = create_engine(
'mysql+my... | [
"sqlalchemy.orm.sessionmaker",
"sqlalchemy.create_engine",
"sqlalchemy.ext.declarative.declarative_base"
] | [((291, 379), 'sqlalchemy.create_engine', 'create_engine', (['"""mysql+mysqlconnector://local:testing@localhost:3306/test"""'], {'echo': '(True)'}), "('mysql+mysqlconnector://local:testing@localhost:3306/test',\n echo=True)\n", (304, 379), False, 'from sqlalchemy import create_engine\n'), ((407, 467), 'sqlalchemy.or... |
#
# /$$ /$$ /$$ /$$ /$$ /$$$$$$ /$$ /$$ /$$$$$$ /$$
# | $$$ | $$ | $$ | $$$ /$$$ /$$__ $$| $$ | $$ /$$__ $$| $$
# | $$$$| $$ /$$$$$$ /$$$$$$$ /$$$$$$ | $$$$ /$$$$| $$ \__/| $$ | $$ | $$ \ $$| $$ /$$$$$$ /$$$$$$ /$$$$$$/$$... | [
"os.system",
"secrets.token_urlsafe"
] | [((2021, 2046), 'secrets.token_urlsafe', 'secrets.token_urlsafe', (['(32)'], {}), '(32)\n', (2042, 2046), False, 'import string, secrets\n'), ((1212, 1225), 'os.system', 'system', (['"""cls"""'], {}), "('cls')\n", (1218, 1225), False, 'from os import system, name\n'), ((1251, 1266), 'os.system', 'system', (['"""clear""... |
import logging
from kubedriver.kegd.model import ReadyResult
from kubedriver.keg import CompositionLoader
from kubedriver.sandbox import Sandbox, SandboxConfiguration, SandboxError, ExecuteError
from kubedriver.kegd.scripting import KegCollection, ReadyResultHolder
logger = logging.getLogger(__name__)
#Different to r... | [
"logging.getLogger",
"kubedriver.kegd.scripting.ReadyResultHolder",
"kubedriver.kegd.model.ReadyResult.not_ready",
"kubedriver.sandbox.Sandbox",
"kubedriver.kegd.scripting.KegCollection",
"kubedriver.kegd.model.ReadyResult.ready",
"kubedriver.kegd.model.ReadyResult.failed",
"kubedriver.keg.Composition... | [((276, 303), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (293, 303), False, 'import logging\n'), ((860, 879), 'kubedriver.kegd.scripting.ReadyResultHolder', 'ReadyResultHolder', ([], {}), '()\n', (877, 879), False, 'from kubedriver.kegd.scripting import KegCollection, ReadyResultHolde... |
import random
import re
from locustio.common_utils import confluence_measure, fetch_by_re, timestamp_int, \
TEXT_HEADERS, NO_TOKEN_HEADERS, JSON_HEADERS, RESOURCE_HEADERS, generate_random_string, init_logger, \
raise_if_login_failed
from locustio.confluence.requests_params import confluence_datasets, Login, Vi... | [
"locustio.common_utils.raise_if_login_failed",
"locustio.confluence.requests_params.CreateBlog",
"locustio.common_utils.fetch_by_re",
"random.choice",
"uuid.uuid4",
"locustio.confluence.requests_params.ViewPage",
"locustio.confluence.requests_params.Login",
"locustio.confluence.requests_params.conflue... | [((479, 513), 'locustio.common_utils.init_logger', 'init_logger', ([], {'app_type': '"""confluence"""'}), "(app_type='confluence')\n", (490, 513), False, 'from locustio.common_utils import confluence_measure, fetch_by_re, timestamp_int, TEXT_HEADERS, NO_TOKEN_HEADERS, JSON_HEADERS, RESOURCE_HEADERS, generate_random_str... |