code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import logging
import sys
_logger = logging.getLogger()
def configure(log_file=None, level=logging.DEBUG):
if not log_file or log_file == '-' or log_file == 'stdout':
formatter = logging.Formatter('%(message)s')
handler = logging.StreamHandler(sys.stderr)
else:
formatter = logging.Fo... | [
"logging.getLogger",
"logging.Formatter",
"logging.StreamHandler",
"logging.FileHandler"
] | [((38, 57), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (55, 57), False, 'import logging\n'), ((195, 227), 'logging.Formatter', 'logging.Formatter', (['"""%(message)s"""'], {}), "('%(message)s')\n", (212, 227), False, 'import logging\n'), ((246, 279), 'logging.StreamHandler', 'logging.StreamHandler', ([... |
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from members.models import User
from mailinglists.models import Mailinglist, Subscription, MailmanAccount, MailmanService
import sys,os
class Command(BaseCommand):
help = 'Compare mailinglist(s) in mailman with da... | [
"mailinglists.models.MailmanService",
"sys.exit",
"mailinglists.models.Mailinglist.objects.all",
"mailinglists.models.Subscription.objects.all",
"mailinglists.models.Mailinglist.objects.get",
"django.core.management.base.CommandError",
"mailinglists.models.MailmanAccount"
] | [((1463, 1492), 'mailinglists.models.MailmanService', 'MailmanService', (['password', 'url'], {}), '(password, url)\n', (1477, 1492), False, 'from mailinglists.models import Mailinglist, Subscription, MailmanAccount, MailmanService\n'), ((2284, 2295), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (2292, 2295), False,... |
import json
import pytest
import asyncio
from api_test_utils.oauth_helper import OauthHelper
from api_test_utils.apigee_api_apps import ApigeeApiDeveloperApps
from api_test_utils.apigee_api_products import ApigeeApiProducts
from e2e.scripts.generic_request import GenericRequest
from time import time
from e2e.scripts im... | [
"api_test_utils.oauth_helper.OauthHelper",
"e2e.scripts.generic_request.GenericRequest",
"urllib.parse.urlparse",
"json.dumps",
"urllib.parse.parse_qs",
"time.time",
"pytest.fixture",
"api_test_utils.apigee_api_products.ApigeeApiProducts",
"api_test_utils.apigee_api_trace.ApigeeApiTraceDebug",
"ap... | [((638, 654), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (652, 654), False, 'import pytest\n'), ((2391, 2407), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (2405, 2407), False, 'import pytest\n'), ((2594, 2610), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (2608, 2610), False, 'import pytes... |
"""
Generic type & functions for torch.Tensor and np.ndarray
"""
import torch
from torch import Tensor
import numpy as np
from numpy import ndarray
from typing import Tuple, Union, List, TypeVar
TensArr = TypeVar('TensArr', Tensor, ndarray)
def convert(a: TensArr, astype: type) -> TensArr:
if astype == Tenso... | [
"torch.tensor",
"numpy.any",
"typing.TypeVar"
] | [((210, 245), 'typing.TypeVar', 'TypeVar', (['"""TensArr"""', 'Tensor', 'ndarray'], {}), "('TensArr', Tensor, ndarray)\n", (217, 245), False, 'from typing import Tuple, Union, List, TypeVar\n'), ((2063, 2088), 'numpy.any', 'np.any', (['(types != types[0])'], {}), '(types != types[0])\n', (2069, 2088), True, 'import num... |
import requests
import checking_functions
#res = requests.get("http://localhost:8080/v1.0/Datastreams?$filter=name eq 'test-6'")
#obj = res.json()
#print(obj["value"])
res = checking_functions.get_item_by_name("http://localhost:8080/v1.0/Datastreams?$filter=name eq 'test-6'")
print(res) | [
"checking_functions.get_item_by_name"
] | [((177, 284), 'checking_functions.get_item_by_name', 'checking_functions.get_item_by_name', (['"""http://localhost:8080/v1.0/Datastreams?$filter=name eq \'test-6\'"""'], {}), '(\n "http://localhost:8080/v1.0/Datastreams?$filter=name eq \'test-6\'")\n', (212, 284), False, 'import checking_functions\n')] |
import time
from abc import abstractmethod
from datetime import datetime
from typing import Optional, List, Tuple, Union
from bxcommon.messages.bloxroute.tx_message import TxMessage
from bxcommon.models.transaction_flag import TransactionFlag
from bxcommon.utils import crypto, convert
from bxcommon.utils.blockchain_ut... | [
"bxgateway.messages.ont.tx_ont_message.TxOntMessage",
"datetime.datetime.utcnow",
"bxcommon.utils.blockchain_utils.bdn_tx_to_bx_tx.bdn_tx_to_bx_tx",
"time.time",
"bxcommon.utils.crypto.double_sha256"
] | [((1901, 1918), 'datetime.datetime.utcnow', 'datetime.utcnow', ([], {}), '()\n', (1916, 1918), False, 'from datetime import datetime\n'), ((3396, 3432), 'bxgateway.messages.ont.tx_ont_message.TxOntMessage', 'TxOntMessage', ([], {'buf': 'raw_ont_tx_msg.buf'}), '(buf=raw_ont_tx_msg.buf)\n', (3408, 3432), False, 'from bxg... |
# Copyright 2018 The TensorFlow Constrained Optimization 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
#
#... | [
"tensorflow.compat.v1.placeholder",
"tensorflow_constrained_optimization.python.rates.helpers.get_num_columns_of_2d_tensor",
"tensorflow_constrained_optimization.python.rates.helpers.get_num_elements_of_tensor",
"tensorflow_constrained_optimization.python.rates.helpers.convert_to_1d_tensor",
"tensorflow.exe... | [((1053, 1091), 'tensorflow.compat.v1.disable_eager_execution', 'tf.compat.v1.disable_eager_execution', ([], {}), '()\n', (1089, 1091), True, 'import tensorflow as tf\n'), ((6989, 7003), 'tensorflow.test.main', 'tf.test.main', ([], {}), '()\n', (7001, 7003), True, 'import tensorflow as tf\n'), ((1424, 1457), 'tensorflo... |
"""TODO."""
import os
import pandas as pd
from dotenv import load_dotenv
from facebook_client import FacebookClient
load_dotenv()
fb = FacebookClient(access_token=os.getenv('FACEBOOK_ACCESS_TOKEN'))
nonprofit_df = pd.read_csv('nonprofit_facebook.csv')
nonprofit_df['fan_count'] = nonprofit_df['facebook'].map(fb.get_... | [
"os.getenv",
"pandas.read_csv",
"dotenv.load_dotenv"
] | [((119, 132), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (130, 132), False, 'from dotenv import load_dotenv\n'), ((217, 254), 'pandas.read_csv', 'pd.read_csv', (['"""nonprofit_facebook.csv"""'], {}), "('nonprofit_facebook.csv')\n", (228, 254), True, 'import pandas as pd\n'), ((166, 200), 'os.getenv', 'os.ge... |
''' Controller para fornecer dados da CEE '''
from flask import request
from flask_restful_swagger_2 import swagger
from resources.base import BaseResource
class CardTemplateResource(BaseResource):
''' Classe que obtém a estrutura de dados de um modelo de card. '''
@swagger.doc({
'tags':['card_template... | [
"flask.request.args.get",
"flask_restful_swagger_2.swagger.doc",
"flask.request.args.copy"
] | [((276, 961), 'flask_restful_swagger_2.swagger.doc', 'swagger.doc', (["{'tags': ['card_template'], 'description':\n 'Obtém um a estrutura de dados de um modelo de card', 'parameters': [{\n 'name': 'cd_template', 'description': 'Código do template', 'required':\n True, 'type': 'string', 'in': 'path'}, {'name': ... |
#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
import os
import sys
import time
import logging
from buckshot import distribute
TIMEOUT = 1.5
@distribute(timeout=TIMEOUT)
def sleep_and_unicode(x):
print("Process %s sle... | [
"buckshot.distribute",
"logging.basicConfig",
"os.getpid",
"time.sleep"
] | [((241, 268), 'buckshot.distribute', 'distribute', ([], {'timeout': 'TIMEOUT'}), '(timeout=TIMEOUT)\n', (251, 268), False, 'from buckshot import distribute\n'), ((366, 379), 'time.sleep', 'time.sleep', (['x'], {}), '(x)\n', (376, 379), False, 'import time\n'), ((676, 716), 'logging.basicConfig', 'logging.basicConfig', ... |
import requests
from pymongo import MongoClient
client = MongoClient()
db = client.wp
url = 'https://public-api.wordpress.com/rest/v1.1/sites/73194874/posts'
params = {'number': 100}
offset = 0
while True:
response = requests.get(url, params=params).json()
found = response['found']
posts = response['pos... | [
"pymongo.MongoClient",
"requests.get"
] | [((58, 71), 'pymongo.MongoClient', 'MongoClient', ([], {}), '()\n', (69, 71), False, 'from pymongo import MongoClient\n'), ((225, 257), 'requests.get', 'requests.get', (['url'], {'params': 'params'}), '(url, params=params)\n', (237, 257), False, 'import requests\n')] |
import glob
import os
import os.path as osp
import sys
import torch
import torch.utils.data as data
import cv2
import numpy as np
import torchvision.transforms as T
from layers.box_utils import point_form
from PIL import ImageDraw, ImageOps, Image, ImageFont
import string
tv_transform = T.Compose([
T.ToTensor(),
... | [
"numpy.ones_like",
"PIL.Image.open",
"utils.augmentations.SSDAugmentation",
"numpy.hstack",
"os.path.join",
"os.path.isfile",
"numpy.array",
"pdb.set_trace",
"numpy.concatenate",
"torchvision.transforms.Normalize",
"torchvision.transforms.ToTensor",
"sys.path.append"
] | [((787, 877), 'numpy.concatenate', 'np.concatenate', (['[boxes[:, :2] - boxes[:, 2:] / 2, boxes[:, :2] + boxes[:, 2:] / 2]', '(1)'], {}), '([boxes[:, :2] - boxes[:, 2:] / 2, boxes[:, :2] + boxes[:, 2:\n ] / 2], 1)\n', (801, 877), True, 'import numpy as np\n'), ((2849, 2906), 'sys.path.append', 'sys.path.append', (['... |
# Copyright 2021 NVIDIA 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
#
# Unless required by applicable law or agreed to in wr... | [
"argparse.ArgumentParser",
"time",
"pandas.DataFrame",
"numpy.random.randn",
"numpy.arange"
] | [((1831, 1842), 'numpy.random.randn', 'randn', (['size'], {}), '(size)\n', (1836, 1842), False, 'from numpy.random import randn\n'), ((1853, 1899), 'pandas.DataFrame', 'pd.DataFrame', (["{'key': key, 'payload': payload}"], {}), "({'key': key, 'payload': payload})\n", (1865, 1899), True, 'import pandas as pd\n'), ((2618... |
from django_athm import constants, utils
def test_parse_error_code():
assert utils.parse_error_code("3020") == constants.ERROR_DICT["3020"]
class TestSyncHTTPAdapter:
def test_adapter_get_with_data(self, mock_httpx):
adapter = utils.SyncHTTPAdapter()
response = adapter.get_with_data(constan... | [
"django_athm.utils.parse_error_code",
"django_athm.utils.SyncHTTPAdapter"
] | [((83, 113), 'django_athm.utils.parse_error_code', 'utils.parse_error_code', (['"""3020"""'], {}), "('3020')\n", (105, 113), False, 'from django_athm import constants, utils\n'), ((247, 270), 'django_athm.utils.SyncHTTPAdapter', 'utils.SyncHTTPAdapter', ([], {}), '()\n', (268, 270), False, 'from django_athm import cons... |
# -*- coding utf-8-*-
"""
Created on Tue Nov 23 10:15:35 2018
@author: galad-loth
"""
import numpy as npy
import mxnet as mx
class SSDHLoss(mx.operator.CustomOp):
"""
Loss layer for supervised semantics-preserving deep hashing.
"""
def __init__(self, w_bin, w_balance):
self._w_b... | [
"numpy.mean",
"mxnet.sym.Activation",
"numpy.ones",
"mxnet.symbol.Custom",
"mxnet.nd.zeros",
"mxnet.symbol.FullyConnected",
"mxnet.cpu",
"mxnet.sym.Variable",
"numpy.zeros",
"mxnet.symbol.SoftmaxOutput",
"mxnet.nd.array",
"numpy.maximum",
"mxnet.sym.Group",
"mxnet.operator.register"
] | [((968, 1001), 'mxnet.operator.register', 'mx.operator.register', (['"""ssdh_loss"""'], {}), "('ssdh_loss')\n", (988, 1001), True, 'import mxnet as mx\n'), ((2789, 2825), 'mxnet.operator.register', 'mx.operator.register', (['"""siam_dh_Loss"""'], {}), "('siam_dh_Loss')\n", (2809, 2825), True, 'import mxnet as mx\n'), (... |
from kivy.properties import StringProperty
from kivymd.uix.card import MDCard
class KitchenSinkSwiperManagerCard(MDCard):
text = StringProperty()
| [
"kivy.properties.StringProperty"
] | [((136, 152), 'kivy.properties.StringProperty', 'StringProperty', ([], {}), '()\n', (150, 152), False, 'from kivy.properties import StringProperty\n')] |
""" Python Obit SpectrumFit class
Class for fitting spectra to image pixels
This class does least squares fitting of log(s) as a polynomial in log($\nu$).
Either an image cube or a set of single plane images at arbitrary
frequencies may be fitted.
Model: S = S_0 exp (alpha*ln(nu/nu_0) + beta*ln(nu/nu_0)**2+...)
The r... | [
"Obit.SpectrumFitCreate",
"Obit.SpectrumFitImArr",
"OErr.printErr",
"Obit.SpectrumFit_Get_me",
"Obit.CreateSpectrumFit",
"Obit.SpectrumFitGetList",
"Obit.SpectrumFitCube",
"OErr.printErrMsg",
"Obit.SpectrumFitIsA",
"Obit.SpectrumFitSingle",
"Obit.SpectrumFit_Set_me",
"Obit.SpectrumFitGetName",... | [((12332, 12367), 'Obit.SpectrumFitCreate', 'Obit.SpectrumFitCreate', (['name', 'nterm'], {}), '(name, nterm)\n', (12354, 12367), False, 'import Obit, _Obit, OErr, Image, InfoList\n'), ((13177, 13265), 'Obit.SpectrumFitSingle', 'Obit.SpectrumFitSingle', (['nfreq', 'nterm', 'refFreq', 'freq', 'flux', 'sigma', 'doBrokePo... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('what_meta', '0003_add_artist_aliases'),
]
operations = [
migrations.AlterField(
model_name='whatmetafulltext',
... | [
"django.db.models.OneToOneField"
] | [((364, 422), 'django.db.models.OneToOneField', 'models.OneToOneField', ([], {'null': '(True)', 'to': '"""what_meta.WhatArtist"""'}), "(null=True, to='what_meta.WhatArtist')\n", (384, 422), False, 'from django.db import migrations, models\n'), ((560, 623), 'django.db.models.OneToOneField', 'models.OneToOneField', ([], ... |
import itertools
import random
import ranking
from collections import defaultdict
from sqlalchemy import Column, Integer, String, desc, func
from sqlalchemy.orm import relationship
from scoring_engine.models.base import Base
from scoring_engine.models.check import Check
from scoring_engine.models.round import Round
... | [
"sqlalchemy.orm.relationship",
"scoring_engine.db.session.query",
"sqlalchemy.func.sum",
"sqlalchemy.desc",
"sqlalchemy.func.max",
"sqlalchemy.String",
"sqlalchemy.Column",
"scoring_engine.models.check.Check.result.is_",
"collections.defaultdict",
"ranking.Ranking",
"random.randint"
] | [((465, 498), 'sqlalchemy.Column', 'Column', (['Integer'], {'primary_key': '(True)'}), '(Integer, primary_key=True)\n', (471, 498), False, 'from sqlalchemy import Column, Integer, String, desc, func\n'), ((607, 668), 'sqlalchemy.orm.relationship', 'relationship', (['"""Service"""'], {'back_populates': '"""team"""', 'la... |
from notifications_utils.clients.antivirus.antivirus_client import (
AntivirusClient,
)
from notifications_utils.clients.redis.redis_client import RedisClient
from notifications_utils.clients.zendesk.zendesk_client import ZendeskClient
antivirus_client = AntivirusClient()
zendesk_client = ZendeskClient()
redis_cli... | [
"notifications_utils.clients.antivirus.antivirus_client.AntivirusClient",
"notifications_utils.clients.zendesk.zendesk_client.ZendeskClient",
"notifications_utils.clients.redis.redis_client.RedisClient"
] | [((260, 277), 'notifications_utils.clients.antivirus.antivirus_client.AntivirusClient', 'AntivirusClient', ([], {}), '()\n', (275, 277), False, 'from notifications_utils.clients.antivirus.antivirus_client import AntivirusClient\n'), ((295, 310), 'notifications_utils.clients.zendesk.zendesk_client.ZendeskClient', 'Zende... |
""" Module builds a dictionary based on training data containing
typical hateful and neutral words """
from feature_extraction.ngram.tfidf import TfIdf
class Dictionary:
"""Creates a Dictionary of hateful/neutral words based on passed training data
and returns the dataframe with the new feature columns for t... | [
"feature_extraction.ngram.tfidf.TfIdf"
] | [((1885, 1904), 'feature_extraction.ngram.tfidf.TfIdf', 'TfIdf', (['(1)', '"""english"""'], {}), "(1, 'english')\n", (1890, 1904), False, 'from feature_extraction.ngram.tfidf import TfIdf\n')] |
# MIT License
# This project is a software package to automate the performance tracking of the HPC algorithms
# Copyright (c) 2021. <NAME>, <NAME>, <NAME>, <NAME>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to ... | [
"model.get_field_values",
"numpy.unique",
"model.get_concat_dataframe",
"visuals.make_graph_table",
"dash_html_components.P",
"specs.get_specs"
] | [((3849, 3890), 'model.get_concat_dataframe', 'model.get_concat_dataframe', (['collection_ls'], {}), '(collection_ls)\n', (3875, 3890), False, 'import model\n'), ((4451, 4571), 'visuals.make_graph_table', 'visuals.make_graph_table', (['concat_df', '"""Performance Plot"""', 'graph[0]', 'versions', 'speedup_options', 'li... |
import contextlib
import errno
import os
import sys
import tempfile
MS_WINDOWS = (sys.platform == 'win32')
@contextlib.contextmanager
def temporary_file():
tmp_filename = tempfile.mktemp()
try:
yield tmp_filename
finally:
try:
os.unlink(tmp_filename)
except OSError as... | [
"tempfile.mktemp",
"os.unlink"
] | [((179, 196), 'tempfile.mktemp', 'tempfile.mktemp', ([], {}), '()\n', (194, 196), False, 'import tempfile\n'), ((271, 294), 'os.unlink', 'os.unlink', (['tmp_filename'], {}), '(tmp_filename)\n', (280, 294), False, 'import os\n')] |
"""MPC Algorithms."""
import torch
from torch.distributions import MultivariateNormal
from rllib.util.parameter_decay import Constant, ParameterDecay
from .abstract_solver import MPCSolver
class MPPIShooting(MPCSolver):
"""Solve MPC using Model Predictive Path Integral control.
References
----------
... | [
"torch.max",
"rllib.util.parameter_decay.Constant",
"torch.tensor",
"torch.sum",
"torch.zeros_like"
] | [((1000, 1033), 'torch.tensor', 'torch.tensor', (['filter_coefficients'], {}), '(filter_coefficients)\n', (1012, 1033), False, 'import torch\n'), ((1070, 1105), 'torch.sum', 'torch.sum', (['self.filter_coefficients'], {}), '(self.filter_coefficients)\n', (1079, 1105), False, 'import torch\n'), ((922, 937), 'rllib.util.... |
#!/usr/bin/env python3
from __future__ import print_function
import argparse
import datetime
import os
import pickle
import re
import sys
import time
import googleapiclient
import icalendar
import ics
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth... | [
"os.path.exists",
"pickle.dump",
"argparse.ArgumentParser",
"re.compile",
"ics.calendar.walk",
"ics.find_component",
"google.auth.transport.requests.Request",
"pickle.load",
"time.sleep",
"googleapiclient.discovery.build",
"os.popen",
"google_auth_oauthlib.flow.InstalledAppFlow.from_client_sec... | [((1495, 1519), 're.compile', 're.compile', (['"""^UID:(.+)$"""'], {}), "('^UID:(.+)$')\n", (1505, 1519), False, 'import re\n'), ((1736, 1760), 'sys.stdout.write', 'sys.stdout.write', (['output'], {}), '(output)\n', (1752, 1760), False, 'import sys\n'), ((1765, 1783), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '... |
from math import sqrt, log
from random import shuffle
from artificial_idiot.util.misc import randint
class Node:
"""A node in a search tree. Contains a pointer to the parent (the node
that this is a successor of) and to the actual state for this node. Note
that if a state is arrived at by two paths, then ... | [
"random.shuffle",
"math.log"
] | [((4341, 4374), 'random.shuffle', 'shuffle', (['self.unexpanded_children'], {}), '(self.unexpanded_children)\n', (4348, 4374), False, 'from random import shuffle\n'), ((5401, 5417), 'math.log', 'log', (['self.visits'], {}), '(self.visits)\n', (5404, 5417), False, 'from math import sqrt, log\n')] |
import keras
import numpy as np
import pandas as pd
import os
from keras import backend as K
from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout
import keras.backend as backend
from keras.models import Model, Sequential
from keras.callbacks import ModelCheckpoint, CSVLogg... | [
"sklearn.preprocessing.LabelEncoder",
"keras.backend.sum",
"pandas.read_csv",
"keras.callbacks.History",
"keras.layers.Dense",
"numpy.arange",
"keras.backend.square",
"numpy.random.seed",
"keras.models.Model",
"keras.backend.transpose",
"keras.layers.GaussianNoise",
"keras.callbacks.CSVLogger"... | [((1716, 1763), 'sklearn.model_selection.train_test_split', 'train_test_split', (['x_data', 'y_data'], {'test_size': '(0.3)'}), '(x_data, y_data, test_size=0.3)\n', (1732, 1763), False, 'from sklearn.model_selection import train_test_split\n'), ((2107, 2139), 'keras.layers.Input', 'Input', ([], {'shape': '(x_train.shap... |
from string import ascii_letters, digits
from random import choice
CARACTERES = ascii_letters + digits
class Clave:
def __init__(self: object, longitud: int = 12) -> None:
"""..."""
self.__clave = self.__crear_clave(longitud)
def __crear_clave(self: object, longitud: int) -> str:
""... | [
"random.choice"
] | [((353, 371), 'random.choice', 'choice', (['CARACTERES'], {}), '(CARACTERES)\n', (359, 371), False, 'from random import choice\n')] |
import sys
from unittest import TestCase
from dropSQL.ast import ColumnDef, IntegerTy, VarCharTy
from dropSQL.fs.db_file import DBFile
from dropSQL.parser.tokens.identifier import Identifier
class LayoutCase(TestCase):
def test(self):
connection = DBFile(":memory:")
db_name = "Database name!"
... | [
"dropSQL.ast.IntegerTy",
"dropSQL.fs.db_file.DBFile",
"dropSQL.ast.VarCharTy",
"dropSQL.parser.tokens.identifier.Identifier"
] | [((263, 281), 'dropSQL.fs.db_file.DBFile', 'DBFile', (['""":memory:"""'], {}), "(':memory:')\n", (269, 281), False, 'from dropSQL.fs.db_file import DBFile\n'), ((986, 1003), 'dropSQL.parser.tokens.identifier.Identifier', 'Identifier', (['"""ind"""'], {}), "('ind')\n", (996, 1003), False, 'from dropSQL.parser.tokens.ide... |
import math
import torch
from torch import nn, Tensor
from torch.nn import functional as F
import torchvision
from typing import List, Tuple, Dict, Optional
@torch.jit.unused
def _resize_image_and_masks_onnx(image, self_min_size, self_max_size, target):
# type: (Tensor, float, float, Optional[Dict[str, Tensor]]) -> ... | [
"torchvision._is_tracing",
"torch.as_tensor",
"torch.stack",
"torch.max",
"torch.min",
"torch.tensor",
"torch.onnx.operators.shape_as_tensor",
"torch._C._get_tracing_state",
"torch.nn.functional.interpolate",
"torch.nn.functional.pad"
] | [((580, 641), 'torch.min', 'torch.min', (['(self_min_size / min_size)', '(self_max_size / max_size)'], {}), '(self_min_size / min_size, self_max_size / max_size)\n', (589, 641), False, 'import torch\n'), ((1242, 1272), 'torch.tensor', 'torch.tensor', (['image.shape[-2:]'], {}), '(image.shape[-2:])\n', (1254, 1272), Fal... |
import logging
import sys
import logging.handlers as handlers
from enum import Enum
RESET_SEQ = "\033[0m"
class Color(Enum):
RED = '\033[31m'
GREEN = '\033[32m'
YELLOW = '\033[33m'
CYAN = '\033[36m'
BLUE = '\033[34m'
LIGHT_GREEN = '\033[92m'
NORMAL_COLOR = '\033[39m'
WHITE = '\033[37m'... | [
"logging.getLogger",
"logging.StreamHandler",
"logging.handlers.RotatingFileHandler",
"logging.Formatter.format",
"logging.Formatter.__init__"
] | [((1638, 1657), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (1655, 1657), False, 'import logging\n'), ((1738, 1771), 'logging.StreamHandler', 'logging.StreamHandler', (['sys.stdout'], {}), '(sys.stdout)\n', (1759, 1771), False, 'import logging\n'), ((2016, 2035), 'logging.getLogger', 'logging.getLogger'... |
import arcpy
source = "C:\\TxDOT\\Shapefiles\\District_Offices.shp"
outputcopy = "T:\\DATAMGT\\MAPPING\\Personal Folders\\Adam\\District_Offices.shp"
def copyPhone():
arcpy.JoinField_management(outputcopy, "Address", source, "Address", ["Phone"])
return "complete"
copyPhone()
| [
"arcpy.JoinField_management"
] | [((168, 247), 'arcpy.JoinField_management', 'arcpy.JoinField_management', (['outputcopy', '"""Address"""', 'source', '"""Address"""', "['Phone']"], {}), "(outputcopy, 'Address', source, 'Address', ['Phone'])\n", (194, 247), False, 'import arcpy\n')] |
# built-in
import ast
import inspect
import sys
from trace import Trace
from typing import Any, Iterator, NamedTuple, Optional, Set, Tuple
class TraceResult(NamedTuple):
file_name: str
func_result: Any
covered_lines: Set[int]
all_lines: Set[int]
@property
def coverage(self) -> int:
re... | [
"ast.walk",
"sys.gettrace",
"trace.Trace",
"inspect.unwrap",
"sys.settrace"
] | [((704, 724), 'inspect.unwrap', 'inspect.unwrap', (['func'], {}), '(func)\n', (718, 724), False, 'import inspect\n'), ((785, 803), 'trace.Trace', 'Trace', ([], {'trace': '(False)'}), '(trace=False)\n', (790, 803), False, 'from trace import Trace\n'), ((979, 993), 'sys.gettrace', 'sys.gettrace', ([], {}), '()\n', (991, ... |
"""
A collection of classes extending the functionality of Python's builtins.
email <EMAIL>
"""
import re
import typing
import string
import enum
import os
import sys
from glob import glob
from pathlib import Path
import copy
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# %% ===============... | [
"pandas.read_csv",
"gzip.open",
"scipy.io.loadmat",
"webbrowser.open",
"numpy.array_split",
"matplotlib.colors.CSS4_COLORS.keys",
"matplotlib.pyplot.MultipleLocator",
"matplotlib.pyplot.style.context",
"copy.deepcopy",
"numpy.sin",
"numpy.arange",
"textwrap.dedent",
"re.split",
"subprocess... | [((3278, 3284), 'pathlib.Path', 'Path', ([], {}), '()\n', (3282, 3284), False, 'from pathlib import Path\n'), ((32307, 32333), 'numpy.concatenate', 'np.concatenate', (['op'], {'axis': '(0)'}), '(op, axis=0)\n', (32321, 32333), True, 'import numpy as np\n'), ((1126, 1164), 'numpy.save', 'np.save', (['path', 'self.__dict... |
import numpy as np
import scipy.signal
from gym.spaces import Box, Discrete
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions.normal import Normal
from torch.distributions.categorical import Categorical
def initialize_weights_he(m):
if isinstance(m, nn.Linear) or isinstan... | [
"numpy.prod",
"torch.nn.ReLU",
"torch.nn.init.constant_",
"torch.nn.Sequential",
"torch.distributions.normal.Normal",
"numpy.log",
"torch.exp",
"torch.squeeze",
"torch.tanh",
"numpy.isscalar",
"torch.nn.AdaptiveAvgPool2d",
"torch.argmax",
"torch.nn.init.kaiming_uniform_",
"torch.nn.functio... | [((962, 984), 'torch.nn.Sequential', 'nn.Sequential', (['*layers'], {}), '(*layers)\n', (975, 984), True, 'import torch.nn as nn\n'), ((1035, 1044), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (1042, 1044), True, 'import torch.nn as nn\n'), ((346, 386), 'torch.nn.init.kaiming_uniform_', 'torch.nn.init.kaiming_uniform... |
# Create your views here.
from django.http import HttpResponse
def index(request):
return HttpResponse("Our roommate finder page ^_^")
| [
"django.http.HttpResponse"
] | [((96, 140), 'django.http.HttpResponse', 'HttpResponse', (['"""Our roommate finder page ^_^"""'], {}), "('Our roommate finder page ^_^')\n", (108, 140), False, 'from django.http import HttpResponse\n')] |
'''
Author: <NAME>
Created Date: 2021-08-20
Last Modified: 2021-09-14
content:
'''
import torch
from torch import nn
import torch.nn.functional as F
from ..builder import LOSSES
from .utils import get_class_weight, weight_reduce_loss
@LOSSES.register_module()
class LabelSmoothing(nn.Module):
"""NLL loss with... | [
"torch.nn.functional.log_softmax"
] | [((1805, 1831), 'torch.nn.functional.log_softmax', 'F.log_softmax', (['pred'], {'dim': '(1)'}), '(pred, dim=1)\n', (1818, 1831), True, 'import torch.nn.functional as F\n'), ((689, 725), 'torch.nn.functional.log_softmax', 'nn.functional.log_softmax', (['x'], {'dim': '(-1)'}), '(x, dim=-1)\n', (714, 725), False, 'from to... |
from __future__ import absolute_import, division, print_function, unicode_literals
import unittest
import io
import os
import tempfile
import numpy as np
from pystan import stan, stanc
class TestStanFileIO(unittest.TestCase):
def test_stan_model_from_file(self):
bernoulli_model_code = """
d... | [
"numpy.mean",
"pystan.stanc",
"os.path.join",
"io.open",
"pystan.stan",
"tempfile.mkdtemp",
"numpy.var",
"os.remove"
] | [((698, 716), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (714, 716), False, 'import tempfile\n'), ((735, 775), 'os.path.join', 'os.path.join', (['temp_dir', '"""modelcode.stan"""'], {}), "(temp_dir, 'modelcode.stan')\n", (747, 775), False, 'import os\n'), ((936, 978), 'pystan.stan', 'stan', ([], {'model_... |
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 26 15:55:37 2017
@author: Administrator
"""
import numpy as np#使用import导入模块numpy
import matplotlib.pyplot as plt#使用import导入模块matplotlib.pyplot
import plotly as py # 导入plotly库并命名为py
# -------------pre def
pympl = py.offline.plot_mpl
# 配置中文显示
plt.rcParams['font.family'] =... | [
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.xlabel",
"numpy.sin",
"matplotlib.pyplot.subplots",
"numpy.arange"
] | [((411, 425), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (423, 425), True, 'import matplotlib.pyplot as plt\n'), ((438, 454), 'numpy.arange', 'np.arange', (['(1)', '(30)'], {}), '(1, 30)\n', (447, 454), True, 'import numpy as np\n'), ((457, 466), 'numpy.sin', 'np.sin', (['x'], {}), '(x)\n', (463, 4... |
# Python3
# ESSENTIALS
from subprocess import Popen
import traceback
class Run:
# COMMANDS
MANAGE = ['python', 'manage.py']
RUNSERVER = MANAGE + ['runserver']
CRONTAB = MANAGE + ['crontab']
CRONTAB_RUN = CRONTAB + ['add']
CRONTAB_RM = CRONTAB + ['remove']
def __init__(self):
self... | [
"subprocess.Popen",
"traceback.print_exc"
] | [((333, 366), 'subprocess.Popen', 'Popen', (['self.RUNSERVER'], {'stdin': 'None'}), '(self.RUNSERVER, stdin=None)\n', (338, 366), False, 'from subprocess import Popen\n'), ((394, 429), 'subprocess.Popen', 'Popen', (['self.CRONTAB_RUN'], {'stdin': 'None'}), '(self.CRONTAB_RUN, stdin=None)\n', (399, 429), False, 'from su... |
import random
import time
from collections import deque
from threading import Lock
import HABApp
from HABApp.core.events import ValueUpdateEvent
from .bench_base import BenchBaseRule
from .bench_times import BenchContainer, BenchTime
LOCK = Lock()
class OpenhabBenchRule(BenchBaseRule):
BENCH_TYPE = 'openHAB'
... | [
"collections.deque",
"threading.Lock",
"time.sleep",
"time.time",
"random.randint",
"HABApp.core.Items.get_all_item_names"
] | [((243, 249), 'threading.Lock', 'Lock', ([], {}), '()\n', (247, 249), False, 'from threading import Lock\n'), ((646, 653), 'collections.deque', 'deque', ([], {}), '()\n', (651, 653), False, 'from collections import deque\n'), ((1478, 1489), 'time.time', 'time.time', ([], {}), '()\n', (1487, 1489), False, 'import time\n... |
# coding=utf-8
#
# Copyright 2008 <NAME>.
#
# 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... | [
"django.contrib.admin.site.register",
"logging.info"
] | [((680, 712), 'logging.info', 'logging.info', (['"""Admin loading..."""'], {}), "('Admin loading...')\n", (692, 712), False, 'import logging\n'), ((2223, 2265), 'django.contrib.admin.site.register', 'admin.site.register', (['Article', 'ArticleAdmin'], {}), '(Article, ArticleAdmin)\n', (2242, 2265), False, 'from django.... |
import torch.nn as nn
import torch
class VGG(nn.Module):
def __init__(self, features, num_classes=2, init_weights=True):
super(VGG, self).__init__()
self.features = features
self.classifier = nn.Sequential(
nn.Linear(512*27, 2048),
nn.ReLU(True),
nn.Dro... | [
"torch.nn.MaxPool1d",
"torch.nn.ReLU",
"torch.nn.Dropout",
"torch.nn.init.constant_",
"torch.nn.Sequential",
"torch.nn.init.xavier_uniform_",
"torch.nn.Linear",
"torch.nn.Conv1d",
"torch.flatten"
] | [((1452, 1474), 'torch.nn.Sequential', 'nn.Sequential', (['*layers'], {}), '(*layers)\n', (1465, 1474), True, 'import torch.nn as nn\n'), ((609, 638), 'torch.flatten', 'torch.flatten', (['x'], {'start_dim': '(1)'}), '(x, start_dim=1)\n', (622, 638), False, 'import torch\n'), ((250, 275), 'torch.nn.Linear', 'nn.Linear',... |
import json
import requests
import logging
from datetime import date, timedelta
logging.basicConfig(level=logging.ERROR)
class EODAPI:
BASE_URL = "https://eodhistoricaldata.com/api/"
def __init__(self, apiToken):
self.apiToken = apiToken
# Do basic API call to EOD API and retry if fail
def doRequest(self, url,... | [
"logging.basicConfig",
"datetime.date.today",
"requests.get",
"datetime.timedelta"
] | [((80, 120), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.ERROR'}), '(level=logging.ERROR)\n', (99, 120), False, 'import logging\n'), ((4178, 4190), 'datetime.date.today', 'date.today', ([], {}), '()\n', (4188, 4190), False, 'from datetime import date, timedelta\n'), ((535, 574), 'requests.get'... |
"""
Django settings for qed splash page.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
print('settings.py')
# Build paths inside the project like t... | [
"os.path.dirname",
"os.path.join"
] | [((482, 522), 'os.path.join', 'os.path.join', (['PROJECT_ROOT', '"""templates/"""'], {}), "(PROJECT_ROOT, 'templates/')\n", (494, 522), False, 'import os\n'), ((4829, 4881), 'os.path.join', 'os.path.join', (['PROJECT_ROOT', '"""docs"""', '"""_build"""', '"""html"""'], {}), "(PROJECT_ROOT, 'docs', '_build', 'html')\n", ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
from django.conf import settings
from django.db import migrations
from corehq.apps.userreports.models import DataSourceConfiguration
from corehq.preindex import get_preindex_plugin
from corehq.sql_db.connections impo... | [
"corehq.util.couch.IterDB",
"corehq.apps.userreports.models.DataSourceConfiguration.all_ids",
"corehq.preindex.get_preindex_plugin",
"corehq.apps.userreports.models.DataSourceConfiguration.get_db",
"django.db.migrations.RunPython"
] | [((593, 625), 'corehq.apps.userreports.models.DataSourceConfiguration.get_db', 'DataSourceConfiguration.get_db', ([], {}), '()\n', (623, 625), False, 'from corehq.apps.userreports.models import DataSourceConfiguration\n'), ((980, 1024), 'django.db.migrations.RunPython', 'migrations.RunPython', (['set_default_engine_ids... |
from Button import Button
import pygame
class SmallButton(Button):
def __init__(self, position, value, label):
Button.__init__(self, position, value, label)
self.unPressedImage = pygame.transform.smoothscale(self.unPressedImage, (104, 32))
self.pressedImage = pygame.transform.smoothscale(s... | [
"pygame.transform.smoothscale",
"Button.Button.__init__"
] | [((125, 170), 'Button.Button.__init__', 'Button.__init__', (['self', 'position', 'value', 'label'], {}), '(self, position, value, label)\n', (140, 170), False, 'from Button import Button\n'), ((201, 261), 'pygame.transform.smoothscale', 'pygame.transform.smoothscale', (['self.unPressedImage', '(104, 32)'], {}), '(self.... |
import moeda
p = float(input('Digite um valor: R$ '))
moeda.resumo(p, 10, 10) | [
"moeda.resumo"
] | [((55, 78), 'moeda.resumo', 'moeda.resumo', (['p', '(10)', '(10)'], {}), '(p, 10, 10)\n', (67, 78), False, 'import moeda\n')] |
import os
import random
def create_temp_dir(tailor_home_path):
temp_dir_path = os.path.join(tailor_home_path, "temp")
if not os.path.exists(temp_dir_path): os.mkdir(temp_dir_path)
return temp_dir_path
def create_temp_result_file(temp_dir_path):
temp_result_file_path = os.path.join(temp_dir_path, "temp... | [
"os.path.exists",
"random.choice",
"os.path.join",
"os.mkdir",
"os.walk"
] | [((84, 122), 'os.path.join', 'os.path.join', (['tailor_home_path', '"""temp"""'], {}), "(tailor_home_path, 'temp')\n", (96, 122), False, 'import os\n'), ((287, 333), 'os.path.join', 'os.path.join', (['temp_dir_path', '"""temp_result.txt"""'], {}), "(temp_dir_path, 'temp_result.txt')\n", (299, 333), False, 'import os\n'... |
import responses
from selvpcclient.resources.tokens import TokensManager
from tests.rest import client
from tests.util import answers
@responses.activate
def test_add():
responses.add(responses.POST, 'http://api/v2/tokens',
json=answers.TOKENS_CREATE)
manager = TokensManager(client)
t... | [
"responses.add",
"selvpcclient.resources.tokens.TokensManager"
] | [((177, 263), 'responses.add', 'responses.add', (['responses.POST', '"""http://api/v2/tokens"""'], {'json': 'answers.TOKENS_CREATE'}), "(responses.POST, 'http://api/v2/tokens', json=answers.\n TOKENS_CREATE)\n", (190, 263), False, 'import responses\n'), ((292, 313), 'selvpcclient.resources.tokens.TokensManager', 'To... |
from celery import Celery
import redis
import msgpack
app = Celery('tasks', broker='pyamqp://guest:guest@rabbitmq:5672//')
r = redis.Redis(host="redis-mozart.7c5iht.0001.use1.cache.amazonaws.com", port=6379, db=0)
REDIS_LIST = "logstash"
@app.task
def get_data(payload):
r.rpush(REDIS_LIST, msgpack.dumps(payload... | [
"celery.Celery",
"msgpack.dumps",
"redis.Redis"
] | [((61, 123), 'celery.Celery', 'Celery', (['"""tasks"""'], {'broker': '"""pyamqp://guest:guest@rabbitmq:5672//"""'}), "('tasks', broker='pyamqp://guest:guest@rabbitmq:5672//')\n", (67, 123), False, 'from celery import Celery\n'), ((128, 219), 'redis.Redis', 'redis.Redis', ([], {'host': '"""redis-mozart.7c5iht.0001.use1.... |
from django.contrib.auth import get_user_model
from rest_framework import status
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase
from authors.apps.authentication.models import UserManager
from .models import Profile
from authors.apps.authentication.token import generate_token
cl... | [
"authors.apps.authentication.token.generate_token",
"rest_framework.reverse.reverse"
] | [((892, 935), 'rest_framework.reverse.reverse', 'reverse', (['"""authentication:user-registration"""'], {}), "('authentication:user-registration')\n", (899, 935), False, 'from rest_framework.reverse import reverse\n'), ((961, 997), 'rest_framework.reverse.reverse', 'reverse', (['"""authentication:user_login"""'], {}), ... |
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2018, Exa Analytics Development Team
# Distributed under the terms of the Apache License 2.0
from unittest import TestCase
from ipywidgets import Button
from ..widget_utils import _ListDict, Folder, GUIBox, gui_field_widgets
class TestFolder(TestCase):
def test_ini... | [
"ipywidgets.Button"
] | [((350, 358), 'ipywidgets.Button', 'Button', ([], {}), '()\n', (356, 358), False, 'from ipywidgets import Button\n'), ((642, 650), 'ipywidgets.Button', 'Button', ([], {}), '()\n', (648, 650), False, 'from ipywidgets import Button\n'), ((1003, 1011), 'ipywidgets.Button', 'Button', ([], {}), '()\n', (1009, 1011), False, ... |
# Copyright 2020 The Cirq Developers
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | [
"cirq.is_parameterized",
"cirq.parameter_symbols",
"cirq.resolve_parameters",
"cirq.parameter_names"
] | [((687, 712), 'cirq.parameter_names', 'cirq.parameter_names', (['val'], {}), '(val)\n', (707, 712), False, 'import cirq\n'), ((727, 754), 'cirq.parameter_symbols', 'cirq.parameter_symbols', (['val'], {}), '(val)\n', (749, 754), False, 'import cirq\n'), ((824, 850), 'cirq.is_parameterized', 'cirq.is_parameterized', (['v... |
import matplotlib
import matplotlib.pyplot as plt
import os
import numpy as np
import torch
import torch.nn.functional as F
from configs.Config_chd import get_config
from utilities.file_and_folder_operations import subfiles
def reshape_array(numpy_array, axis=1):
image_shape = numpy_array.shape[1]
channel = n... | [
"matplotlib.pyplot.imshow",
"utilities.file_and_folder_operations.subfiles",
"torch.max",
"os.path.join",
"torch.argmax",
"torch.tensor",
"matplotlib.pyplot.figure",
"configs.Config_chd.get_config",
"torch.nn.functional.interpolate",
"numpy.concatenate",
"matplotlib.pyplot.title",
"numpy.shape... | [((1511, 1523), 'configs.Config_chd.get_config', 'get_config', ([], {}), '()\n', (1521, 1523), False, 'from configs.Config_chd import get_config\n'), ((2877, 2935), 'utilities.file_and_folder_operations.subfiles', 'subfiles', (['c.scaled_image_16_dir'], {'suffix': '""".npy"""', 'join': '(False)'}), "(c.scaled_image_16_... |
import restrict_download_region.restrict_region as restrict_region
import boto3
import json
import pytest
import botocore
from pytest_mock import MockerFixture
def test_get_bucket_policy__has_statement(mocker: MockerFixture):
mock_s3 = mocker.MagicMock(spec=boto3.client('s3'))
policy = {
"Version": "... | [
"json.dumps",
"boto3.client",
"restrict_download_region.restrict_region.update_bucket_policy"
] | [((857, 920), 'restrict_download_region.restrict_region.update_bucket_policy', 'restrict_region.update_bucket_policy', (['mock_s3', '"""foobar"""', 'policy'], {}), "(mock_s3, 'foobar', policy)\n", (893, 920), True, 'import restrict_download_region.restrict_region as restrict_region\n'), ((1308, 1371), 'restrict_downloa... |
# -*- coding: utf-8 -*-
import os
import re
import shutil
from queue import Queue
from threading import Thread
def load_features(file):
with open(file, mode='r', encoding='utf-8') as fp:
features_list = fp.readlines()
return [feature.strip('\n') for feature in features_list]
def valid_feature(q, f... | [
"os.listdir",
"re.compile",
"shutil.rmtree",
"threading.Thread",
"queue.Queue",
"os.remove"
] | [((885, 892), 'queue.Queue', 'Queue', ([], {}), '()\n', (890, 892), False, 'from queue import Queue\n'), ((937, 962), 'os.listdir', 'os.listdir', (['features_path'], {}), '(features_path)\n', (947, 962), False, 'import os\n'), ((977, 1002), 're.compile', 're.compile', (['"""^PNF_|^SCP_"""'], {}), "('^PNF_|^SCP_')\n", (... |
# Copyright 2017 The TensorFlow 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... | [
"image_manipulation.rotate180",
"official.resnet.resnet_run_loop.resnet_model_fn",
"tensorflow.logging.set_verbosity",
"official.resnet.resnet_run_loop.ResnetArgParser",
"image_manipulation.rotate270",
"numpy.array",
"image_manipulation.grayscale_contrast",
"tensorflow.nn.dropout",
"sys.path.append"... | [((1288, 1365), 'sys.path.append', 'sys.path.append', (['"""/work/generalisation-humans-DNNs/code/accuracy_evaluation/"""'], {}), "('/work/generalisation-humans-DNNs/code/accuracy_evaluation/')\n", (1303, 1365), False, 'import sys\n'), ((1604, 1612), 'functools.wraps', 'wraps', (['f'], {}), '(f)\n', (1609, 1612), False... |
from rest_framework.test import APIClient
from election.tests.test_case import BallotsTestCase
class BallotsApiTestCase(BallotsTestCase):
def setUp(self):
super().setUp()
self.client = APIClient()
response = self.client.post('/api/login/', {'username': 'admin', 'password': '<PASSWORD>'})
... | [
"rest_framework.test.APIClient"
] | [((208, 219), 'rest_framework.test.APIClient', 'APIClient', ([], {}), '()\n', (217, 219), False, 'from rest_framework.test import APIClient\n')] |
import functools
import json
import pathlib
from matplotlib.cm import register_cmap
from matplotlib.colors import ListedColormap
mod_dir = pathlib.Path(__file__).parent.parent
@functools.lru_cache()
def colormaps():
'''return a dictionary of colormaps'''
with open(mod_dir / 'data' / 'colormaps.json', mode=... | [
"matplotlib.cm.register_cmap",
"pathlib.Path",
"matplotlib.colors.ListedColormap",
"json.load",
"functools.lru_cache"
] | [((181, 202), 'functools.lru_cache', 'functools.lru_cache', ([], {}), '()\n', (200, 202), False, 'import functools\n'), ((760, 794), 'matplotlib.cm.register_cmap', 'register_cmap', ([], {'name': 'v.name', 'cmap': 'v'}), '(name=v.name, cmap=v)\n', (773, 794), False, 'from matplotlib.cm import register_cmap\n'), ((141, 1... |
import logging
from xml.etree import ElementTree
from django.urls import reverse
from saml2 import BINDING_HTTP_POST, md, saml, samlp, xmlenc, xmldsig
from saml2.client import Saml2Client
from saml2.config import Config as Saml2Config
from saml2.saml import NAMEID_FORMAT_EMAILADDRESS
from zentral.conf import settings
f... | [
"logging.getLogger",
"realms.models.RealmUser.objects.update_or_create",
"xml.etree.ElementTree.register_namespace",
"saml2.config.Config",
"realms.exceptions.RealmUserError",
"django.urls.reverse",
"realms.models.RealmAuthenticationSession"
] | [((420, 469), 'logging.getLogger', 'logging.getLogger', (['"""zentral.realms.backends.saml"""'], {}), "('zentral.realms.backends.saml')\n", (437, 469), False, 'import logging\n'), ((2590, 2603), 'saml2.config.Config', 'Saml2Config', ([], {}), '()\n', (2601, 2603), True, 'from saml2.config import Config as Saml2Config\n... |
from django import forms
from booking_portal.models.instrument.requests import Rheometer
from .base import UserDetailsForm, UserRemarkForm
class RheometerForm(UserDetailsForm, UserRemarkForm):
title = "Rheometer"
subtitle = "Rheometer, <NAME>"
help_text = '''
<b>Please provide any other information ... | [
"django.forms.Select",
"django.forms.TextInput"
] | [((1681, 1729), 'django.forms.TextInput', 'forms.TextInput', ([], {'attrs': "{'class': 'form-control'}"}), "(attrs={'class': 'form-control'})\n", (1696, 1729), False, 'from django import forms\n'), ((1825, 1873), 'django.forms.TextInput', 'forms.TextInput', ([], {'attrs': "{'class': 'form-control'}"}), "(attrs={'class'... |
import numpy as np
import random
from nltk import word_tokenize
from nltk.corpus import stopwords
from nltk import WordNetLemmatizer
from sklearn import svm
from sklearn.model_selection import GridSearchCV
import random
with open('./data/vocab.txt', 'r') as fp:
vocab_list = fp.read().split('\n')
vocab = {wo... | [
"sklearn.model_selection.GridSearchCV",
"nltk.corpus.stopwords.words",
"nltk.word_tokenize",
"nltk.WordNetLemmatizer",
"numpy.array",
"sklearn.svm.SVC"
] | [((748, 774), 'nltk.corpus.stopwords.words', 'stopwords.words', (['"""english"""'], {}), "('english')\n", (763, 774), False, 'from nltk.corpus import stopwords\n'), ((787, 806), 'nltk.WordNetLemmatizer', 'WordNetLemmatizer', ([], {}), '()\n', (804, 806), False, 'from nltk import WordNetLemmatizer\n'), ((826, 849), 'nlt... |
from django import forms
from django.core.exceptions import ValidationError
from django.utils import formats
from django.utils.translation import ugettext_lazy as _
from ..models.timesheets import Timesheet, TimesheetEntry
from .fields import ReadonlyField
from .form import FormMixin
class TimesheetEntryAdminForm(fo... | [
"django.utils.translation.ugettext_lazy",
"django.utils.formats.date_format"
] | [((3349, 3414), 'django.utils.translation.ugettext_lazy', '_', (['"""An overlaping entry has already been added in the timesheet."""'], {}), "('An overlaping entry has already been added in the timesheet.')\n", (3350, 3414), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((1015, 1024), 'django.util... |
"""
Analyses Views | Cannlytics API
Created: 4/21/2021
API to interface with cannabis regulation information.
"""
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['GET', 'POST', 'DELETE'])
def analyses(request, format=None):
... | [
"rest_framework.response.Response",
"rest_framework.decorators.api_view"
] | [((245, 280), 'rest_framework.decorators.api_view', 'api_view', (["['GET', 'POST', 'DELETE']"], {}), "(['GET', 'POST', 'DELETE'])\n", (253, 280), False, 'from rest_framework.decorators import api_view\n'), ((854, 889), 'rest_framework.decorators.api_view', 'api_view', (["['GET', 'POST', 'DELETE']"], {}), "(['GET', 'POS... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: <NAME>(<EMAIL>)
# Loss function for Pose Estimation.
import torch.nn as nn
class MseLoss(nn.Module):
def __init__(self, configer):
super(MseLoss, self).__init__()
self.configer = configer
self.reduction = self.configer.get('loss.para... | [
"torch.nn.MSELoss"
] | [((384, 420), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {'reduction': 'self.reduction'}), '(reduction=self.reduction)\n', (394, 420), True, 'import torch.nn as nn\n')] |
from suwako.modules.storage_management import BOT_DATA_DIR
import os
if os.environ.get('SUWAKO_TOKEN'):
bot_token = os.environ.get('SUWAKO_TOKEN')
else:
try:
with open(BOT_DATA_DIR + "/token.txt", "r+") as token_file:
bot_token = token_file.read().strip()
except FileNotFoundError as e:
... | [
"os.environ.get"
] | [((73, 103), 'os.environ.get', 'os.environ.get', (['"""SUWAKO_TOKEN"""'], {}), "('SUWAKO_TOKEN')\n", (87, 103), False, 'import os\n'), ((500, 536), 'os.environ.get', 'os.environ.get', (['"""SUWAKO_OSU_API_KEY"""'], {}), "('SUWAKO_OSU_API_KEY')\n", (514, 536), False, 'import os\n'), ((121, 151), 'os.environ.get', 'os.en... |
'''The module creates image directories for various
classes out of a dataframe for data augmentation purposes.'''
#importing libraries
import numpy as np
import pandas as pd
import os
from PIL import Image
def create_dir(path,class_list):
''' The function takes in the path and list of the classes to
c... | [
"numpy.array",
"PIL.Image.fromarray",
"os.path.join",
"os.mkdir"
] | [((581, 608), 'os.path.join', 'os.path.join', (['path', '"""train"""'], {}), "(path, 'train')\n", (593, 608), False, 'import os\n'), ((621, 648), 'os.path.join', 'os.path.join', (['path', '"""valid"""'], {}), "(path, 'valid')\n", (633, 648), False, 'import os\n'), ((650, 670), 'os.mkdir', 'os.mkdir', (['train_path'], {... |
# Generated by Django 3.1.2 on 2020-11-14 09:28
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... | [
"django.db.models.ForeignKey",
"django.db.models.ImageField",
"django.db.models.AutoField",
"django.db.models.URLField",
"django.db.migrations.swappable_dependency",
"django.db.models.CharField"
] | [((247, 304), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (278, 304), False, 'from django.db import migrations, models\n'), ((434, 527), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)... |
import inspect
from doubles.class_double import ClassDouble
from doubles.exceptions import ConstructorDoubleError
from doubles.lifecycle import current_space
def expect(target):
"""
Prepares a target object for a method call expectation (mock). The name of the method to expect
should be called as a metho... | [
"doubles.lifecycle.current_space",
"inspect.currentframe"
] | [((1476, 1491), 'doubles.lifecycle.current_space', 'current_space', ([], {}), '()\n', (1489, 1491), False, 'from doubles.lifecycle import current_space\n'), ((2063, 2085), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (2083, 2085), False, 'import inspect\n')] |
import socket
import sys
import time
from threading import Thread
import requests
from logger import logger
from cbagent.stores import SerieslyStore
from cbagent.metadata_client import MetadataClient
class Collector(object):
COLLECTOR = None
def __init__(self, settings):
self.session = requests.Se... | [
"cbagent.metadata_client.MetadataClient",
"requests.Session",
"socket.socket",
"time.sleep",
"logger.logger.warn",
"logger.logger.interrupt",
"sys.exit",
"cbagent.stores.SerieslyStore",
"threading.Thread"
] | [((309, 327), 'requests.Session', 'requests.Session', ([], {}), '()\n', (325, 327), False, 'import requests\n'), ((704, 741), 'cbagent.stores.SerieslyStore', 'SerieslyStore', (['settings.seriesly_host'], {}), '(settings.seriesly_host)\n', (717, 741), False, 'from cbagent.stores import SerieslyStore\n'), ((760, 784), 'c... |
import os
import json
import urllib3
def lambda_handler(event, context):
url = os.environ["FADIP_URL"]
url = url + "/predict_all"
http = urllib3.PoolManager()
r = http.request("GET", url)
data = r.data
return {
"statusCode": r.status,
"headers": {
"Content-Type": ... | [
"json.dumps",
"urllib3.PoolManager"
] | [((151, 172), 'urllib3.PoolManager', 'urllib3.PoolManager', ([], {}), '()\n', (170, 172), False, 'import urllib3\n'), ((366, 382), 'json.dumps', 'json.dumps', (['data'], {}), '(data)\n', (376, 382), False, 'import json\n')] |
#!/usr/bin/env python3
""" Import comunity modules. """
import os
import sys
import docker
import json
from click.testing import CliRunner
HERE = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(1, f"{HERE}/../dugaire")
""" Import custom modules. """
import dugaire
import info
import common
def test_f... | [
"json.loads",
"sys.path.insert",
"common.docker_run",
"os.path.realpath",
"common.cli"
] | [((193, 233), 'sys.path.insert', 'sys.path.insert', (['(1)', 'f"""{HERE}/../dugaire"""'], {}), "(1, f'{HERE}/../dugaire')\n", (208, 233), False, 'import sys\n'), ((165, 191), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (181, 191), False, 'import os\n'), ((472, 487), 'common.cli', 'common... |
import cv2
import numpy as np
def build_transformation_matrix(transform):
"""Convert transform list to transformation matrix
:param transform: transform list as [dx, dy, da]
:return: transform matrix as 2d (2, 3) numpy array
"""
transform_matrix = np.zeros((2, 3))
transform_matrix[0, 0] = np... | [
"cv2.copyMakeBorder",
"numpy.array",
"numpy.zeros",
"numpy.arctan2",
"numpy.cos",
"cv2.cvtColor",
"numpy.sin"
] | [((271, 287), 'numpy.zeros', 'np.zeros', (['(2, 3)'], {}), '((2, 3))\n', (279, 287), True, 'import numpy as np\n'), ((1269, 1414), 'cv2.copyMakeBorder', 'cv2.copyMakeBorder', (['frame'], {'top': 'border_size', 'bottom': 'border_size', 'left': 'border_size', 'right': 'border_size', 'borderType': 'border_mode', 'value': ... |
import binascii
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
from baker import logger
from baker import settings
from baker.storage import Storage
class SecretKey:
"""
Secret key is the key generated from a key pass to encrypt and decript secret values in recipes
"""
@staticmethod
... | [
"binascii.hexlify",
"Crypto.Cipher.AES.new",
"Crypto.Hash.SHA256.new",
"baker.settings.get",
"binascii.unhexlify"
] | [((492, 514), 'Crypto.Hash.SHA256.new', 'SHA256.new', (['b_key_pass'], {}), '(b_key_pass)\n', (502, 514), False, 'from Crypto.Hash import SHA256\n'), ((1278, 1308), 'binascii.unhexlify', 'binascii.unhexlify', (['secret_key'], {}), '(secret_key)\n', (1296, 1308), False, 'import binascii\n'), ((1522, 1553), 'Crypto.Ciphe... |
# -*- coding: utf-8 -*-
from frsaccess import FrsAccess
from frscommon import FrsConstantV2
from frscommon import ImageType
from frsutils import http_utils
from frsclient.result import AddFaceResult
from frsclient.result import GetFaceResult
from frsclient.result import DeleteFaceResult
class FaceServiceV... | [
"frsutils.http_utils.HttpRequestUtils.load_file_as_multi_part",
"frsutils.http_utils.HttpResponseUtils.http_response2_result"
] | [((1545, 1630), 'frsutils.http_utils.HttpResponseUtils.http_response2_result', 'http_utils.HttpResponseUtils.http_response2_result', (['AddFaceResult', 'http_response'], {}), '(AddFaceResult, http_response\n )\n', (1595, 1630), False, 'from frsutils import http_utils\n'), ((3067, 3152), 'frsutils.http_utils.HttpResp... |
# -*- coding: utf-8 -*-
# pylint: disable=line-too-long
import logger
import testutil
import test_engine
log = logger.Logger(__name__, logger.INFO)
class TestTypes(test_engine.EngineTestCase):
sample = testutil.parse_test_sample({
"SCHEMA": [
[1, "Types", [
[21, "text", "Text", False, "", "... | [
"testutil.parse_test_sample",
"logger.Logger"
] | [((113, 149), 'logger.Logger', 'logger.Logger', (['__name__', 'logger.INFO'], {}), '(__name__, logger.INFO)\n', (126, 149), False, 'import logger\n'), ((207, 1133), 'testutil.parse_test_sample', 'testutil.parse_test_sample', (["{'SCHEMA': [[1, 'Types', [[21, 'text', 'Text', False, '', '', ''], [22,\n 'numeric', 'Num... |
from xml.etree.cElementTree import fromstring
from xmljson import yahoo
import core
from core.helpers import Url
from core.providers.base import NewzNabProvider
from core.providers import torrent_modules # noqa
import logging
logging = logging.getLogger(__name__)
trackers = '&tr='.join(('udp://tracker.leechers-para... | [
"logging.getLogger",
"xml.etree.cElementTree.fromstring",
"core.sql.torznab_caps",
"logging.warning",
"core.sql.write",
"core.helpers.Url.open",
"logging.info"
] | [((238, 265), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (255, 265), False, 'import logging\n'), ((4611, 4661), 'logging.info', 'logging.info', (['"""Syncing Torrent indexer RSS feeds."""'], {}), "('Syncing Torrent indexer RSS feeds.')\n", (4623, 4661), False, 'import logging\n'), ((2... |
# !/usr/bin/env python3
import os
import xlsxwriter
servers = [61, 62, 63, 64, 66, 67, 68, 69, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52]
storage1 = [236, 237, 238, 239, 240, 241, 242, 243]
storage2 = [101, 102, 103, 104, 105, 106, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126... | [
"os.path.join"
] | [((3082, 3103), 'os.path.join', 'os.path.join', (['dst', 'km'], {}), '(dst, km)\n', (3094, 3103), False, 'import os\n'), ((3337, 3377), 'os.path.join', 'os.path.join', (['basepath', '"""chiaNodes.xlsx"""'], {}), "(basepath, 'chiaNodes.xlsx')\n", (3349, 3377), False, 'import os\n')] |
#
# Simulations: discharge of a lead-acid battery
#
import argparse
import matplotlib.pyplot as plt
import numpy as np
import pickle
import pybamm
import shared_plotting
from collections import defaultdict
from shared_solutions import model_comparison, convergence_study
try:
from config import OUTPUT_DIR
except Im... | [
"pybamm.set_logging_level",
"shared_plotting.plot_variable",
"numpy.array",
"pybamm.lead_acid.LOQS",
"shared_solutions.model_comparison",
"shared_plotting.plot_voltage_components",
"argparse.ArgumentParser",
"shared_plotting.plot_voltages",
"pybamm.rmse",
"numpy.linspace",
"pybamm.lead_acid.Comp... | [((515, 567), 'shared_plotting.plot_voltages', 'shared_plotting.plot_voltages', (['all_variables', 't_eval'], {}), '(all_variables, t_eval)\n', (544, 567), False, 'import shared_plotting\n'), ((813, 847), 'numpy.array', 'np.array', (['[0, 0.195, 0.375, 0.545]'], {}), '([0, 0.195, 0.375, 0.545])\n', (821, 847), True, 'i... |
# Copyright 2018-2021 Lawrence Livermore National Security, LLC and other
# Fat Crayon Toolkit Project Developers. See the top-level COPYRIGHT file for details.
from __future__ import print_function
""" Classes and routines for generating 3D objects
"""
import math
import numpy as np
from scipy.spatial import ConvexHul... | [
"math.sqrt",
"math.cos",
"numpy.array",
"numpy.linalg.norm",
"copy.deepcopy",
"numpy.cross",
"numpy.asarray",
"numpy.dot",
"numpy.random.seed",
"numpy.vstack",
"sys.stdout.flush",
"numpy.random.normal",
"re.match",
"scipy.spatial.ConvexHull",
"math.atan2",
"numpy.transpose",
"scipy.s... | [((8328, 8496), 'numpy.asarray', 'np.asarray', (['[[-0.5, -0.5, -0.5], [0.5, -0.5, -0.5], [-0.5, 0.5, -0.5], [0.5, 0.5, -0.5],\n [-0.5, -0.5, 0.5], [0.5, -0.5, 0.5], [-0.5, 0.5, 0.5], [0.5, 0.5, 0.5]]'], {}), '([[-0.5, -0.5, -0.5], [0.5, -0.5, -0.5], [-0.5, 0.5, -0.5], [0.5,\n 0.5, -0.5], [-0.5, -0.5, 0.5], [0.5,... |
import numpy as np
from pommerman.constants import Item
from util.analytics import Stopwatch
def transform_observation(obs, p_obs=False, centralized=False):
"""
Transform a singular observation of the board into a stack of
binary planes.
:param obs: The observation containing the board
... | [
"numpy.ones",
"numpy.isin",
"numpy.stack",
"numpy.zeros",
"numpy.array",
"numpy.moveaxis"
] | [((1877, 1902), 'numpy.stack', 'np.stack', (['planes'], {'axis': '(-1)'}), '(planes, axis=-1)\n', (1885, 1902), True, 'import numpy as np\n'), ((1922, 1953), 'numpy.moveaxis', 'np.moveaxis', (['transformed', '(-1)', '(0)'], {}), '(transformed, -1, 0)\n', (1933, 1953), True, 'import numpy as np\n'), ((2506, 2548), 'nump... |
import random
import torch
from structured.butterfly import *
def _group_counts_to_group_sizes(params, group_counts):
"""Convert numbers of groups to sizes of groups."""
_, out_channels, _ = params
group_sizes = [out_channels // count for count in group_counts]
return group_sizes
def _sequence_test... | [
"torch.autograd.Variable",
"torch.Tensor",
"random.randint"
] | [((2433, 2455), 'random.randint', 'random.randint', (['(3)', '(100)'], {}), '(3, 100)\n', (2447, 2455), False, 'import random\n'), ((2515, 2537), 'random.randint', 'random.randint', (['(1)', '(100)'], {}), '(1, 100)\n', (2529, 2537), False, 'import random\n'), ((2591, 2612), 'random.randint', 'random.randint', (['(2)',... |
import os
import time
def single_gpu_check_and_wait(gpu_id,memory_limit):
while True:
#os.system('clear')
time.sleep(1)
result = os.popen('nvidia-smi').read()
#print(result)
lines = result.split('\n')
gpu_info_line = lines[8+gpu_id*3]
#print(gpu_info_line)
... | [
"os.popen",
"time.sleep"
] | [((127, 140), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (137, 140), False, 'import time\n'), ((158, 180), 'os.popen', 'os.popen', (['"""nvidia-smi"""'], {}), "('nvidia-smi')\n", (166, 180), False, 'import os\n')] |
#!/usr/bin/env python
#
# Copyright (c) 2018 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# All Rights Reserved.
#
from cgtsclient.common import utils
from cgtsclient import exc
from cgtsclient.v1 import ihost as ihost_utils
def _print_label_show(ob... | [
"cgtsclient.common.utils.print_tuple_list",
"cgtsclient.exc.CommandError",
"cgtsclient.v1.ihost._find_ihost",
"cgtsclient.common.utils.extract_keypairs",
"cgtsclient.common.utils.arg",
"cgtsclient.common.utils.print_list"
] | [((477, 573), 'cgtsclient.common.utils.arg', 'utils.arg', (['"""hostnameorid"""'], {'metavar': '"""<hostname or id>"""', 'help': '"""Name or ID of host [REQUIRED]"""'}), "('hostnameorid', metavar='<hostname or id>', help=\n 'Name or ID of host [REQUIRED]')\n", (486, 573), False, 'from cgtsclient.common import utils\... |
#!/usr/bin/python3
import sqlite3
import filecmp
import os
import subprocess
os.system("python3 manage.py makemigrations CarSalon_App")
os.system("python3 manage.py migrate CarSalon_App")
os.system("python3 manage.py makemigrations")
os.system("python3 manage.py migrate")
os.system("python3 manage.py loaddata data")
o... | [
"os.system"
] | [((78, 136), 'os.system', 'os.system', (['"""python3 manage.py makemigrations CarSalon_App"""'], {}), "('python3 manage.py makemigrations CarSalon_App')\n", (87, 136), False, 'import os\n'), ((137, 188), 'os.system', 'os.system', (['"""python3 manage.py migrate CarSalon_App"""'], {}), "('python3 manage.py migrate CarSa... |
from django.db import models
import os
class Lpg(models.Model):
date = models.DateTimeField()
price = models.FloatField()
volume = models.FloatField()
benz_price = models.FloatField()
cost = models.FloatField()
mileage = models.FloatField()
mileage_total = models.FloatField()
consump ... | [
"django.db.models.FloatField",
"django.db.models.IntegerField",
"django.db.models.FileField",
"os.path.basename",
"django.db.models.DateTimeField"
] | [((78, 100), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {}), '()\n', (98, 100), False, 'from django.db import models\n'), ((113, 132), 'django.db.models.FloatField', 'models.FloatField', ([], {}), '()\n', (130, 132), False, 'from django.db import models\n'), ((146, 165), 'django.db.models.FloatField... |
# -*- coding: utf-8 -*-
# original implementations of the methods below are
# Copyright © 2001-2017 Python Software Foundation; All Rights Reserved
# they are licensed under the PSF LICENSE AGREEMENT FOR PYTHON 3.5.4
# changes were applied to allow these methods to deal with ansi color escape codes. These changes are... | [
"re.findall",
"gettext.gettext",
"colors.strip_color"
] | [((1214, 1226), 'gettext.gettext', '_', (['"""usage: """'], {}), "('usage: ')\n", (1215, 1226), True, 'from gettext import gettext as _\n'), ((7459, 7482), 'colors.strip_color', 'strip_color', (['chunks[-1]'], {}), '(chunks[-1])\n', (7470, 7482), False, 'from colors import strip_color\n'), ((8408, 8433), 'colors.strip_... |
import gym
import numpy as np
class SpaceWrapper:
def __init__(self, space):
if isinstance(space, gym.spaces.Discrete):
self.shape = ()
self.dtype = np.dtype(np.int64)
elif isinstance(space, gym.spaces.Box):
self.shape = space.shape
self.dtype = np.d... | [
"numpy.dtype"
] | [((187, 205), 'numpy.dtype', 'np.dtype', (['np.int64'], {}), '(np.int64)\n', (195, 205), True, 'import numpy as np\n'), ((316, 337), 'numpy.dtype', 'np.dtype', (['space.dtype'], {}), '(space.dtype)\n', (324, 337), True, 'import numpy as np\n')] |
from rightarrow.parser import Parser
def check(ty, val):
"Checks that `val` adheres to type `ty`"
if isinstance(ty, basestring):
ty = Parser().parse(ty)
return ty.enforce(val)
def guard(ty):
"A decorator that wraps a function so it the type passed is enforced via `check`"
return... | [
"rightarrow.parser.Parser"
] | [((161, 169), 'rightarrow.parser.Parser', 'Parser', ([], {}), '()\n', (167, 169), False, 'from rightarrow.parser import Parser\n')] |
import numpy as np
import torch.nn.functional as F
import math
from torchvision import transforms
import torch
import cv2
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as patches
matplotlib.use('agg')
MAPS = ['map3','map4']
Scales = [0.9, 1.1]
MIN_HW = 384
MAX_HW = 1584
IM_NORM_MEAN = [0... | [
"cv2.rectangle",
"torch.from_numpy",
"torch.nn.functional.interpolate",
"torch.nn.functional.pad",
"torch.floor",
"torch.clamp_min",
"numpy.exp",
"matplotlib.pyplot.close",
"torchvision.transforms.ToTensor",
"cv2.waitKey",
"torch.nn.functional.mse_loss",
"matplotlib.use",
"torch.Tensor",
"... | [((209, 230), 'matplotlib.use', 'matplotlib.use', (['"""agg"""'], {}), "('agg')\n", (223, 230), False, 'import matplotlib\n'), ((1447, 1495), 'numpy.exp', 'np.exp', (['(-(x * x + y * y) / (2.0 * sigma * sigma))'], {}), '(-(x * x + y * y) / (2.0 * sigma * sigma))\n', (1453, 1495), True, 'import numpy as np\n'), ((2742, ... |
#!/usr/bin/env python
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
A very simple example of C{twisted.words.protocols.oscar} code
To run the script:
$ python oscardemo.py
"""
from __future__ import print_function
from twisted.words.protocols import oscar
from twisted.internet im... | [
"twisted.internet.protocol.ClientCreator",
"getpass.getpass",
"twisted.internet.reactor.run"
] | [((429, 458), 'getpass.getpass', 'getpass.getpass', (['"""Password: """'], {}), "('Password: ')\n", (444, 458), False, 'import getpass\n'), ((4525, 4538), 'twisted.internet.reactor.run', 'reactor.run', ([], {}), '()\n', (4536, 4538), False, 'from twisted.internet import protocol, reactor\n'), ((4444, 4502), 'twisted.in... |
#!/usr/bin/env python3
"""
Unit tests for ShoulderBird command line module
To run these tests from command line use the following:
$ python -m pytest -v testes/test_module_shoulderbirdcli.py
Author : Preocts <<EMAIL>>
Discord : Preocts#8196
Git Repo: https://github.com/Preocts/Egg_Bot
"""
from typing import Name... | [
"unittest.mock.Mock",
"discord.Client",
"modules.shoulderbirdcli.COMMAND_CONFIG.items",
"unittest.mock.patch.object",
"pytest.fixture",
"modules.shoulderbirdconfig.ShoulderBirdConfig"
] | [((585, 629), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""', 'name': '"""cli"""'}), "(scope='function', name='cli')\n", (599, 629), False, 'import pytest\n'), ((841, 889), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""', 'name': '"""message"""'}), "(scope='function', name='mess... |
#! Работа с материалами Metanit, глава 8, часть 2. Операции с датами.
import locale
from datetime import datetime, timedelta
# Форматирование дат и времени.
# Для форматирования объектов date и time в этих классах предусмотрен
# метод strftime(format). Этот метод принимает только один параметр,
# указываю... | [
"datetime.datetime",
"datetime.datetime.now",
"datetime.timedelta",
"locale.setlocale"
] | [((1304, 1318), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1316, 1318), False, 'from datetime import datetime, timedelta\n'), ((1535, 1570), 'locale.setlocale', 'locale.setlocale', (['locale.LC_ALL', '""""""'], {}), "(locale.LC_ALL, '')\n", (1551, 1570), False, 'import locale\n'), ((2185, 2203), 'datet... |
# Created by <NAME>.
# GitHub: https://github.com/ikostan
# LinkedIn: https://www.linkedin.com/in/egor-kostan/
# FUNDAMENTALS
import allure
import unittest
from utils.log_func import print_log
from kyu_5.directions_reduction.directions_reduction import dirReduc
@allure.epic('5 kyu')
@allure.parent_suite('Novice'... | [
"allure.parent_suite",
"allure.tag",
"allure.sub_suite",
"allure.dynamic.severity",
"allure.story",
"allure.link",
"allure.dynamic.description_html",
"kyu_5.directions_reduction.directions_reduction.dirReduc",
"allure.epic",
"allure.suite",
"allure.dynamic.title",
"allure.feature",
"utils.lo... | [((270, 290), 'allure.epic', 'allure.epic', (['"""5 kyu"""'], {}), "('5 kyu')\n", (281, 290), False, 'import allure\n'), ((292, 321), 'allure.parent_suite', 'allure.parent_suite', (['"""Novice"""'], {}), "('Novice')\n", (311, 321), False, 'import allure\n'), ((323, 349), 'allure.suite', 'allure.suite', (['"""Algorithms... |
from datetime import datetime
from fastapi import FastAPI, HTTPException
from http.client import HTTPException
from fastapi.staticfiles import StaticFiles
from uuid import uuid4
import random
import os
from datetime import datetime, timedelta
from pydantic import BaseModel
from data import User, Resource, get_last_upd... | [
"fastapi.FastAPI",
"random.choice",
"http.client.HTTPException",
"data.User",
"data.get_last_update_db",
"fastapi.staticfiles.StaticFiles",
"datetime.timedelta",
"random.randint",
"data.Resource"
] | [((456, 469), 'datetime.timedelta', 'timedelta', (['(60)'], {}), '(60)\n', (465, 469), False, 'from datetime import datetime, timedelta\n'), ((477, 486), 'fastapi.FastAPI', 'FastAPI', ([], {}), '()\n', (484, 486), False, 'from fastapi import FastAPI, HTTPException\n'), ((493, 502), 'fastapi.FastAPI', 'FastAPI', ([], {}... |
from djitellopy import Tello
import time
tello = Tello()
tello.connect()
user_input = ' '
while user_input != 'x':
user_input = input()
if user_input == 't':
print("takeoff")
tello.takeoff()
if user_input == 'l':
print("land")
tello.land()
... | [
"djitellopy.Tello"
] | [((55, 62), 'djitellopy.Tello', 'Tello', ([], {}), '()\n', (60, 62), False, 'from djitellopy import Tello\n')] |
from utils import show_messages, get_input
# lets the teachers to add a score for a student of a course
class AddScoreView(object):
def run(self, site, messages=None):
site.clear()
show_messages(messages)
course = get_input('Course Serial: ')
course = site.get_course(serial=course... | [
"utils.show_messages",
"utils.get_input"
] | [((204, 227), 'utils.show_messages', 'show_messages', (['messages'], {}), '(messages)\n', (217, 227), False, 'from utils import show_messages, get_input\n'), ((245, 273), 'utils.get_input', 'get_input', (['"""Course Serial: """'], {}), "('Course Serial: ')\n", (254, 273), False, 'from utils import show_messages, get_in... |
def method1(n: int, m: int) -> int:
def gcd(n: int, m: int) -> int:
while m:
n, m = m, n % m
return n
return abs((n * m) // gcd(n, m))
def method2(n: int, m: int) -> int:
from math import gcd
return abs(n * m) // gcd(n, m)
if __name__ == "__main__":
"""
from tim... | [
"math.gcd"
] | [((261, 270), 'math.gcd', 'gcd', (['n', 'm'], {}), '(n, m)\n', (264, 270), False, 'from math import gcd\n'), ((161, 170), 'math.gcd', 'gcd', (['n', 'm'], {}), '(n, m)\n', (164, 170), False, 'from math import gcd\n')] |
#!/usr/bin/env py3
from __future__ import division, print_function, absolute_import
import os
import sys
import re
import numpy as np
import pdb
'''
============================
@FileName: gen_fi_validation_data.py
@Author: <NAME> (<EMAIL>)
@Version: 1.0
@DateTime: 2018-03-22 17:07:19
=====================... | [
"logging.getLogger",
"logging.StreamHandler",
"argparse.ArgumentParser",
"logging.Formatter",
"numpy.zeros",
"logging.FileHandler",
"re.sub",
"numpy.load",
"time.time"
] | [((4064, 4116), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'description': '"""gen_fi_validation_data"""'}), "(description='gen_fi_validation_data')\n", (4078, 4116), False, 'from argparse import ArgumentParser\n'), ((4711, 4730), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (4728, 4730), False, '... |