code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import os
import psycopg2
from psycopg2 import OperationalError
from dotenv import load_dotenv
if __name__ == '__main__':
load_dotenv("src/.env-vars")
connection = psycopg2.connect(
database=os.getenv("name"),
user=os.getenv("user"),
password=os.getenv("password"),
host=os.geten... | [
"os.getenv",
"dotenv.load_dotenv"
] | [((127, 155), 'dotenv.load_dotenv', 'load_dotenv', (['"""src/.env-vars"""'], {}), "('src/.env-vars')\n", (138, 155), False, 'from dotenv import load_dotenv\n'), ((208, 225), 'os.getenv', 'os.getenv', (['"""name"""'], {}), "('name')\n", (217, 225), False, 'import os\n'), ((240, 257), 'os.getenv', 'os.getenv', (['"""user... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim: ts=2 sw=2 et ai
###############################################################################
# Copyright (c) 2021 <NAME> <EMAIL>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation fi... | [
"time.sleep",
"network.NetworkChecker",
"systemd.Systemd",
"sys.exit",
"commands.Commands",
"os.path.exists",
"os.path.isdir",
"getopt.getopt",
"os.path.isabs",
"simplequeue.SimpleQueue",
"websocket.HTTPWebSocketsHandler.do_GET",
"os.access",
"packagelist.PackageList",
"time.time",
"trac... | [((8088, 8127), 'os.path.join', 'os.path.join', (['logdir', '"""avnavupdate.log"""'], {}), "(logdir, 'avnavupdate.log')\n", (8100, 8127), False, 'import os\n'), ((2185, 2219), 'websocket.HTTPWebSocketsHandler.do_GET', 'HTTPWebSocketsHandler.do_GET', (['self'], {}), '(self)\n', (2213, 2219), False, 'from websocket impor... |
from __future__ import print_function, division
from argparse import ArgumentParser
import yaml
import logging
import os
import sys
import time
from subprocess import call
from marmot.experiment.import_utils import build_objects, build_object, call_for_each_element, import_class
from marmot.experiment.preprocessing_u... | [
"logging.getLogger",
"sklearn.metrics.precision_score",
"marmot.experiment.import_utils.build_object",
"sklearn.metrics.recall_score",
"marmot.experiment.context_utils.create_contexts_ngram",
"sys.exit",
"argparse.ArgumentParser",
"marmot.experiment.learning_utils.map_classifiers",
"marmot.experimen... | [((768, 863), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s : %(levelname)s : %(message)s"""', 'level': 'logging.INFO'}), "(format='%(asctime)s : %(levelname)s : %(message)s',\n level=logging.INFO)\n", (787, 863), False, 'import logging\n'), ((869, 907), 'logging.getLogger', 'logging.... |
'''
Created on Mar 24, 2020
@author: ballance
'''
from typing import List
from vsc.model.covergroup_model import CovergroupModel
from vsc.model.coverpoint_model import CoverpointModel
from vsc.model.model_visitor import ModelVisitor
from vsc.report.coverage_report import CoverageReport
class CoverageReportVisitor(M... | [
"vsc.report.coverage_report.CoverageReport.Covergroup",
"vsc.report.coverage_report.CoverageReport",
"vsc.report.coverage_report.CoverageReport.Coverpoint"
] | [((672, 688), 'vsc.report.coverage_report.CoverageReport', 'CoverageReport', ([], {}), '()\n', (686, 688), False, 'from vsc.report.coverage_report import CoverageReport\n'), ((922, 976), 'vsc.report.coverage_report.CoverageReport.Covergroup', 'CoverageReport.Covergroup', (['cg.name', '(cg.type_cg is None)'], {}), '(cg.... |
import requests
from flask import current_app, Response, request
from flask_restful import Resource, abort, reqparse
from flask_restful_swagger_2 import swagger
from src.db import db
from src.master.config import SCHEDULER_HOST
from src.master.helpers.io import marshal
from src.master.helpers.socketio_events import j... | [
"src.models.Job.query.all",
"requests.post",
"src.db.db.session.commit",
"src.master.helpers.swagger.oneOf",
"src.db.db.session.flush",
"src.db.db.session.add",
"flask_restful.reqparse.RequestParser",
"src.models.JobSchema.get_swagger",
"src.models.Result",
"src.models.Job.query.get_or_404",
"sr... | [((679, 743), 'requests.post', 'requests.post', (['f"""http://{SCHEDULER_HOST}/api/delete/{container}"""'], {}), "(f'http://{SCHEDULER_HOST}/api/delete/{container}')\n", (692, 743), False, 'import requests\n'), ((4534, 5175), 'flask_restful_swagger_2.swagger.doc', 'swagger.doc', (["{'description': 'Get the log output (... |
'''
HACKMERCED 2021
<NAME> and <NAME>
'''
import os
from flask import Flask, render_template, jsonify, request
from flask_cors import CORS, cross_origin
from sqlalchemy import create_engine, exc
from sqlalchemy.orm import scoped_session, sessionmaker
import traceback
# Get env vars:
if not os.getenv("DATABASE_URL"):
... | [
"sqlalchemy.orm.sessionmaker",
"os.getenv",
"flask_cors.CORS",
"flask.Flask",
"flask.request.get_json",
"flask.jsonify"
] | [((377, 392), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (382, 392), False, 'from flask import Flask, render_template, jsonify, request\n'), ((400, 409), 'flask_cors.CORS', 'CORS', (['app'], {}), '(app)\n', (404, 409), False, 'from flask_cors import CORS, cross_origin\n'), ((293, 318), 'os.getenv', 'os... |
import json
from tornado.httpclient import AsyncHTTPClient, HTTPRequest
async def request(path, method='GET', data=None, header=None):
http_client = AsyncHTTPClient()
request = HTTPRequest(
url=f'http://localhost:6666{path}',
method=method,
body=None if data is None else json.dumps(da... | [
"json.dumps",
"tornado.httpclient.AsyncHTTPClient"
] | [((155, 172), 'tornado.httpclient.AsyncHTTPClient', 'AsyncHTTPClient', ([], {}), '()\n', (170, 172), False, 'from tornado.httpclient import AsyncHTTPClient, HTTPRequest\n'), ((307, 323), 'json.dumps', 'json.dumps', (['data'], {}), '(data)\n', (317, 323), False, 'import json\n')] |
# Generated by Django 2.2.6 on 2019-10-10 08:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('block_producer', '0007_add_status_description_field'),
]
operations = [
migrations.AlterField(
model_name='blockproducer',
... | [
"django.db.models.URLField",
"django.db.models.TextField",
"django.db.models.CharField"
] | [((362, 534), 'django.db.models.URLField', 'models.URLField', ([], {'blank': '(True)', 'default': '"""https://block-producers-directory.s3-us-west-2.amazonaws.com/bps/logos/default-block-producer-logotype.png"""', 'max_length': '(1000)'}), "(blank=True, default=\n 'https://block-producers-directory.s3-us-west-2.amaz... |
import datetime
import json
from requests import Session
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
def get_coins_currencies_list():
coin_url = 'https://web-api.coinmarketcap.com/v1/cryptocurrency/map'
fiat_url = 'https://web-api.coinmarketcap.com/v1/fiat/map'
headers = {'... | [
"json.loads",
"requests.Session",
"datetime.datetime.strptime",
"datetime.timedelta",
"datetime.date.today"
] | [((364, 373), 'requests.Session', 'Session', ([], {}), '()\n', (371, 373), False, 'from requests import Session\n'), ((2441, 2450), 'requests.Session', 'Session', ([], {}), '()\n', (2448, 2450), False, 'from requests import Session\n'), ((2942, 2951), 'requests.Session', 'Session', ([], {}), '()\n', (2949, 2951), False... |
import requests
from lxml import etree
import re
import pymysql
import time
conn = pymysql.connect(host='localhost', user='root', passwd='<PASSWORD>', db='mydb', port=3306, charset='utf8')
cursor = conn.cursor()
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, lik... | [
"pymysql.connect",
"time.sleep",
"requests.get",
"lxml.etree.HTML",
"re.findall"
] | [((90, 200), 'pymysql.connect', 'pymysql.connect', ([], {'host': '"""localhost"""', 'user': '"""root"""', 'passwd': '"""<PASSWORD>"""', 'db': '"""mydb"""', 'port': '(3306)', 'charset': '"""utf8"""'}), "(host='localhost', user='root', passwd='<PASSWORD>', db=\n 'mydb', port=3306, charset='utf8')\n", (105, 200), False... |
# Copyright Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompan... | [
"sagemaker.lineage._api_types.AssociationSummary",
"sagemaker.lineage.context.EndpointContext"
] | [((809, 896), 'sagemaker.lineage.context.EndpointContext', 'context.EndpointContext', (['sagemaker_session'], {'context_name': '"""foo"""', 'context_arn': '"""bazz"""'}), "(sagemaker_session, context_name='foo', context_arn=\n 'bazz')\n", (832, 896), False, 'from sagemaker.lineage import context, _api_types\n'), ((2... |
import math
import random
import numpy
from dataclasses import dataclass
@dataclass
class NetworkParams:
"""
Parameters to tweak the network
"""
A: int
B: int
C: int
D: int
sigma: float
alpha: int = 50
class MatcherNetwork:
"""
The mathcer network
"""
SIZE = 10
... | [
"random.shuffle",
"numpy.random.rand",
"numpy.tanh",
"numpy.sum",
"random.random"
] | [((609, 648), 'numpy.random.rand', 'numpy.random.rand', (['self.SIZE', 'self.SIZE'], {}), '(self.SIZE, self.SIZE)\n', (626, 648), False, 'import numpy\n'), ((1061, 1092), 'numpy.sum', 'numpy.sum', (['self.neurons'], {'axis': '(1)'}), '(self.neurons, axis=1)\n', (1070, 1092), False, 'import numpy\n'), ((1111, 1142), 'nu... |
from __future__ import print_function # Python 2/3 compatibility
import boto3
import json
import decimal
import datetime
from boto3.dynamodb.conditions import Key, Attr
import boto.dynamodb2
from boto.dynamodb2.table import Table
from time import sleep
from elasticsearch import Elasticsearch, RequestsHttpConnection
fro... | [
"requests_aws4auth.AWS4Auth",
"elasticsearch.Elasticsearch",
"boto3.resource",
"boto3.Session"
] | [((369, 472), 'boto3.resource', 'boto3.resource', (['"""dynamodb"""'], {'region_name': '"""us-east-1"""', 'aws_access_key_id': '""""""', 'aws_secret_access_key': '""""""'}), "('dynamodb', region_name='us-east-1', aws_access_key_id='',\n aws_secret_access_key='')\n", (383, 472), False, 'import boto3\n'), ((899, 977),... |
import requests
from .endpoints import API_PATH, API_DATA, ROOT
class InvalidMethod(Exception):
'''Invalid method was passed.'''
class RequestHandler:
'''Handles all requests sent to the Sellix API'''
def get(**kwargs):
return requests.get(
API_PATH[kwargs['endpoint']] + ... | [
"requests.post",
"requests.put",
"requests.delete"
] | [((1256, 1318), 'requests.post', 'requests.post', (['API'], {'json': 'DATA', 'headers': "kwargs['authorization']"}), "(API, json=DATA, headers=kwargs['authorization'])\n", (1269, 1318), False, 'import requests\n'), ((1704, 1765), 'requests.put', 'requests.put', (['API'], {'json': 'DATA', 'headers': "kwargs['authorizati... |
import json
from mayan.apps.document_states.tests.mixins import WorkflowTestMixin
from mayan.apps.document_states.literals import WORKFLOW_ACTION_ON_ENTRY
from mayan.apps.documents.tests.base import GenericDocumentViewTestCase
from ..models import DocumentPageOCRContent
from ..workflow_actions import UpdateDocumentPa... | [
"json.dumps"
] | [((3302, 3387), 'json.dumps', 'json.dumps', ([], {'obj': "{'page_condition': True, 'page_content': '{{ document.label }}'}"}), "(obj={'page_condition': True, 'page_content': '{{ document.label }}'}\n )\n", (3312, 3387), False, 'import json\n')] |
from urllib.parse import urlparse
from logging import getLogger
from django.conf import settings
from django.db import transaction
from requests.auth import HTTPBasicAuth
from zipa import lattice # pylint: disable=no-name-in-module
from zinc import models
from zinc.utils.validation import is_ipv6
logger = getLogge... | [
"logging.getLogger",
"requests.auth.HTTPBasicAuth",
"zinc.utils.validation.is_ipv6",
"urllib.parse.urlparse",
"django.conf.settings.LATTICE_ENV.lower",
"django.db.transaction.atomic",
"zinc.models.IP",
"zinc.models.IP.objects.filter",
"zinc.models.IP.objects.values_list"
] | [((312, 341), 'logging.getLogger', 'getLogger', (["('zinc.' + __name__)"], {}), "('zinc.' + __name__)\n", (321, 341), False, 'from logging import getLogger\n'), ((398, 411), 'urllib.parse.urlparse', 'urlparse', (['url'], {}), '(url)\n', (406, 411), False, 'from urllib.parse import urlparse\n'), ((628, 657), 'requests.a... |
"""
Credit: m3hrdadfi
https://huggingface.co/m3hrdadfi/wav2vec2-large-xlsr-persian-v2
"""
import re
import string
import hazm
_normalizer = hazm.Normalizer()
chars_to_ignore = [
",",
"?",
".",
"!",
"-",
";",
":",
'""',
"%",
"'",
'"',
"�",
"#",
"!",
"؟",
... | [
"re.sub",
"hazm.Normalizer"
] | [((144, 161), 'hazm.Normalizer', 'hazm.Normalizer', ([], {}), '()\n', (159, 161), False, 'import hazm\n'), ((2590, 2613), 're.sub', 're.sub', (['""" +"""', '""" """', 'text'], {}), "(' +', ' ', text)\n", (2596, 2613), False, 'import re\n'), ((2238, 2277), 're.sub', 're.sub', (['chars_to_ignore_regex', '""""""', 'text']... |
import typing as T
import pyproj
import rasterio
import xarray as xr
class GdalRawBackend(xr.backends.common.BackendEntrypoint):
def open_dataset( # type: ignore
self,
filename_or_obj: str,
drop_variables: T.Optional[T.Tuple[str]] = None,
decode_coords: T.Union[bool, None, str] =... | [
"pyproj.CRS.from_user_input",
"rasterio.open",
"xarray.decode_cf",
"xarray.Dataset"
] | [((410, 440), 'rasterio.open', 'rasterio.open', (['filename_or_obj'], {}), '(filename_or_obj)\n', (423, 440), False, 'import rasterio\n'), ((1208, 1254), 'xarray.Dataset', 'xr.Dataset', ([], {'data_vars': 'data_vars', 'coords': 'coords'}), '(data_vars=data_vars, coords=coords)\n', (1218, 1254), True, 'import xarray as ... |
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
from modules.path import add_to_path, add_var
import modules.images
import urllib.request
import os
import threading
import ctypes
import winshell
from win32com.client import Dispatch
import pythoncom
class Ui_MainWindow(object):
def setupUi(self, MainWindow):... | [
"PyQt5.QtWidgets.QTextBrowser",
"PyQt5.QtGui.QIcon",
"PyQt5.QtWidgets.QApplication",
"sys.exit",
"pythoncom.CoInitializeEx",
"os.path.exists",
"PyQt5.QtWidgets.QLabel",
"PyQt5.QtWidgets.QPushButton",
"PyQt5.QtWidgets.QLineEdit",
"os.path.expanduser",
"PyQt5.QtWidgets.QWidget",
"PyQt5.QtWidgets... | [((10634, 10666), 'PyQt5.QtWidgets.QApplication', 'QtWidgets.QApplication', (['sys.argv'], {}), '(sys.argv)\n', (10656, 10666), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((10680, 10703), 'PyQt5.QtWidgets.QMainWindow', 'QtWidgets.QMainWindow', ([], {}), '()\n', (10701, 10703), False, 'from PyQt5 import QtC... |
# -*- coding:utf-8 -*-
# 图片处理代码基于http://fc-lamp.blog.163.com/blog/static/174566687201282424018946/小幅度修改
from PIL import Image as image
def resizeImg(**args):
args_key = {'path': '', 'out_path': '', 'width': '', 'height': '', 'quality': 75}
arg = {}
for key in args_key:
if key in args:
... | [
"PIL.Image.open"
] | [((394, 417), 'PIL.Image.open', 'image.open', (["arg['path']"], {}), "(arg['path'])\n", (404, 417), True, 'from PIL import Image as image\n'), ((1626, 1649), 'PIL.Image.open', 'image.open', (["arg['path']"], {}), "(arg['path'])\n", (1636, 1649), True, 'from PIL import Image as image\n')] |
from django.shortcuts import render
from django.http import JsonResponse
from django.core.serializers.json import DjangoJSONEncoder
from django.views.decorators.csrf import csrf_exempt
from api.tags import method
from core import settings
import json
import numpy as np
import pandas as pd
class NumpyEncoder(DjangoJ... | [
"pandas.read_csv",
"django.http.JsonResponse",
"core.settings.DATASETS.get",
"pandas.DataFrame.from_csv",
"api.tags.method"
] | [((661, 716), 'pandas.DataFrame.from_csv', 'pd.DataFrame.from_csv', (['"""../data/norm_data/norm_all.csv"""'], {}), "('../data/norm_data/norm_all.csv')\n", (682, 716), True, 'import pandas as pd\n'), ((737, 797), 'pandas.DataFrame.from_csv', 'pd.DataFrame.from_csv', (['"""../data/norm_data/norm_metadata.csv"""'], {}), ... |
from django.core.exceptions import PermissionDenied
from django.http import HttpResponseBadRequest
from django.shortcuts import redirect, render
from django.views import View
from .forms import NewVacancyForm
from .models import Vacancy
class VacancyListView(View):
def get(self, request, *args, **kwargs):
... | [
"django.shortcuts.render",
"django.shortcuts.redirect",
"django.http.HttpResponseBadRequest"
] | [((384, 437), 'django.shortcuts.render', 'render', (['request', '"""vacancy/list.html"""'], {'context': 'context'}), "(request, 'vacancy/list.html', context=context)\n", (390, 437), False, 'from django.shortcuts import redirect, render\n'), ((972, 989), 'django.shortcuts.redirect', 'redirect', (['"""/home"""'], {}), "(... |
from random import randint
import random
# You've built an inflight entertainment system with on-demand movie streaming.
# Users on longer flights like to start a second movie right when their first one ends, but they complain that the plane usually lands before they can see the ending.
# So you're building a feature... | [
"random.randint"
] | [((1188, 1205), 'random.randint', 'randint', (['(120)', '(240)'], {}), '(120, 240)\n', (1195, 1205), False, 'from random import randint\n'), ((1240, 1254), 'random.randint', 'randint', (['(2)', '(20)'], {}), '(2, 20)\n', (1247, 1254), False, 'from random import randint\n'), ((1281, 1297), 'random.randint', 'randint', (... |
"""
Test the infrastructure for building a state by projection onto the +1
eigenspace of a set of generators or stabilizers
"""
import numpy as np
from referenceqvm.stabilizer_utils import (compute_action, project_stabilized_state,
binary_stabilizer_to_pauli_stabilizer,
... | [
"numpy.allclose",
"numpy.sqrt",
"numpy.isclose",
"pyquil.paulis.sY",
"pyquil.paulis.sZ",
"referenceqvm.stabilizer_utils.pauli_stabilizer_to_binary_stabilizer",
"referenceqvm.stabilizer_utils.compute_action",
"pyquil.paulis.sI",
"numpy.array",
"numpy.zeros",
"pytest.raises",
"pyquil.paulis.sX",... | [((1212, 1266), 'referenceqvm.stabilizer_utils.pauli_stabilizer_to_binary_stabilizer', 'pauli_stabilizer_to_binary_stabilizer', (['bell_stabilizer'], {}), '(bell_stabilizer)\n', (1249, 1266), False, 'from referenceqvm.stabilizer_utils import compute_action, project_stabilized_state, binary_stabilizer_to_pauli_stabilize... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_django-user-verification
------------
Tests for verification `views`.
"""
import random
# Third Party Stuff
from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase, APIClient
from nose.tools import eq_, ok_
# Local Stuff
cla... | [
"random.choice",
"nose.tools.eq_",
"django.core.urlresolvers.reverse",
"rest_framework.test.APIClient"
] | [((415, 448), 'random.choice', 'random.choice', (["['email', 'phone']"], {}), "(['email', 'phone'])\n", (428, 448), False, 'import random\n'), ((468, 555), 'django.core.urlresolvers.reverse', 'reverse', (['"""verification-send"""'], {'kwargs': "{'verification_type': self.verification_type}"}), "('verification-send', kw... |
from json import dumps
from bs4 import Tag, NavigableString
from datamodel_parser.application import Util
from datamodel_parser.application.Type import Intro_type
from re import search, compile, match
class Intro:
'''Parse intro of file HTML.'''
def __init__(self,logger=None,options=None,body=None):
... | [
"datamodel_parser.application.Util",
"datamodel_parser.application.Type.Intro_type"
] | [((601, 637), 'datamodel_parser.application.Util', 'Util', ([], {'logger': 'logger', 'options': 'options'}), '(logger=logger, options=options)\n', (605, 637), False, 'from datamodel_parser.application import Util\n'), ((2369, 2421), 'datamodel_parser.application.Type.Intro_type', 'Intro_type', ([], {'logger': 'self.log... |
import sys
import serial, time
from scripts.check_asr import get_command
def to_int(command):
if command == 'avanza':
return 8
elif command == 'detente':
return 5
elif command == 'derecha':
return 6
elif command == 'izquierda':
return 4
elif command == 'gira':
... | [
"scripts.check_asr.get_command",
"serial.Serial",
"time.sleep"
] | [((420, 457), 'serial.Serial', 'serial.Serial', (['"""/dev/ttyUSB0"""', '(115200)'], {}), "('/dev/ttyUSB0', 115200)\n", (433, 457), False, 'import serial, time\n'), ((515, 528), 'time.sleep', 'time.sleep', (['(4)'], {}), '(4)\n', (525, 528), False, 'import serial, time\n'), ((669, 693), 'scripts.check_asr.get_command',... |
# Generated by Django 3.0.2 on 2020-01-22 12:34
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0006_auto_20200119_1240'),
]
operations = [
migrations.RemoveField(
model_name='gamer',
name='API_KEY',
),
... | [
"django.db.migrations.RemoveField"
] | [((224, 282), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""gamer"""', 'name': '"""API_KEY"""'}), "(model_name='gamer', name='API_KEY')\n", (246, 282), False, 'from django.db import migrations\n')] |
"""
StarGAN v2
Copyright (c) 2020-present NAVER Corp.
This work is licensed under the Creative Commons Attribution-NonCommercial
4.0 International License. To view a copy of this license, visit
http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to
Creative Commons, PO Box 1866, Mountain View, CA 94042, US... | [
"torch.nn.Tanh",
"torch.nn.LeakyReLU",
"torch.nn.ModuleList",
"math.sqrt",
"torch.nn.functional.avg_pool2d",
"torch.nn.InstanceNorm2d",
"torch.nn.Conv2d",
"torch.chunk",
"torch.nn.Linear",
"torch.nn.functional.interpolate"
] | [((535, 552), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', (['(0.2)'], {}), '(0.2)\n', (547, 552), True, 'import torch.nn as nn\n'), ((889, 923), 'torch.nn.Conv2d', 'nn.Conv2d', (['dim_in', 'dim_in', '(3)', '(1)', '(1)'], {}), '(dim_in, dim_in, 3, 1, 1)\n', (898, 923), True, 'import torch.nn as nn\n'), ((945, 980), 'torch.nn.... |
#!/usr/bin/python3
import math
from typing import Tuple
import matplotlib.pyplot as plt
division_factor_for_reference_values = math.pow(10, 4)/1.5
k = 4 # thread count
def main():
x, y_seq, y_par, res_seq, res_par = get_data("test_code_output.csv")
x_fixed = list()
x_div_k = list()
pi = list()
... | [
"matplotlib.pyplot.ylabel",
"math.pow",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show"
] | [((129, 144), 'math.pow', 'math.pow', (['(10)', '(4)'], {}), '(10, 4)\n', (137, 144), False, 'import math\n'), ((524, 537), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (534, 537), True, 'import matplotlib.pyplot as plt\n'), ((542, 585), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y_seq'], {'labe... |
from nose.tools import *
from exercises import ex8
def test_palindrome():
'''
Test whether our palindrome check returns True
'''
test_is_palindrome = ex8.is_palindrome('radar')
assert_true(test_palindrome)
def test_not_palindrome():
'''
Test whether our palindrome check returns False
... | [
"exercises.ex8.is_palindrome"
] | [((168, 194), 'exercises.ex8.is_palindrome', 'ex8.is_palindrome', (['"""radar"""'], {}), "('radar')\n", (185, 194), False, 'from exercises import ex8\n'), ((354, 379), 'exercises.ex8.is_palindrome', 'ex8.is_palindrome', (['"""test"""'], {}), "('test')\n", (371, 379), False, 'from exercises import ex8\n')] |
import asyncio
import logging.config
from pathlib import Path
from symphony.bdk.core.config.loader import BdkConfigLoader
from symphony.bdk.core.symphony_bdk import SymphonyBdk
async def run():
config = BdkConfigLoader.load_from_symphony_dir("config.yaml")
async with SymphonyBdk(config) as bdk:
ext_a... | [
"symphony.bdk.core.config.loader.BdkConfigLoader.load_from_symphony_dir",
"pathlib.Path",
"symphony.bdk.core.symphony_bdk.SymphonyBdk"
] | [((210, 263), 'symphony.bdk.core.config.loader.BdkConfigLoader.load_from_symphony_dir', 'BdkConfigLoader.load_from_symphony_dir', (['"""config.yaml"""'], {}), "('config.yaml')\n", (248, 263), False, 'from symphony.bdk.core.config.loader import BdkConfigLoader\n'), ((279, 298), 'symphony.bdk.core.symphony_bdk.SymphonyBd... |
import os
import ldap3
from login_mixin import OAuth2LoginMixin
from basehandler import BaseHandler
class OAuth2LoginHandler(BaseHandler, OAuth2LoginMixin):
"""
Handler for authorization for oauth servers
"""
def __init__(self, *args, **kwargs):
BaseHandler.__init__(self, *args, **kwargs)
... | [
"ldap3.Connection",
"basehandler.BaseHandler.__init__",
"os.environ.get",
"ldap3.Server",
"ldap3.ObjectDef"
] | [((273, 316), 'basehandler.BaseHandler.__init__', 'BaseHandler.__init__', (['self', '*args'], {}), '(self, *args, **kwargs)\n', (293, 316), False, 'from basehandler import BaseHandler\n'), ((450, 489), 'os.environ.get', 'os.environ.get', (['"""OAUTH_CLIENT_ID"""', 'None'], {}), "('OAUTH_CLIENT_ID', None)\n", (464, 489)... |
import matplotlib
import matplotlib.pyplot as plt
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import pandas as pd
import os
import matplotlib.pyplot as plt
import sys
import itertools
mpl.rcParams['legend.fontsize'] = 12
DPI = 5000
input_dir = "/home/pablo/ws/log/trajectories"
print("Reading fr... | [
"os.path.exists",
"os.makedirs",
"os.path.join",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show"
] | [((1495, 1507), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1505, 1507), True, 'import matplotlib.pyplot as plt\n'), ((1722, 1732), 'matplotlib.pyplot.ylim', 'plt.ylim', ([], {}), '()\n', (1730, 1732), True, 'import matplotlib.pyplot as plt\n'), ((1804, 1814), 'matplotlib.pyplot.show', 'plt.show', ([],... |
# Copyright (c) OpenMMLab. All rights reserved.
import argparse
import torch
from mmcv import Config, DictAction
import torch.nn as nn
import ptflops
import thop
def prepare_inputs(shape_nchw):
x = torch.zeros(shape_nchw)
return x
class Net(nn.Module):
def __init__(self,
in_channels,
... | [
"thop.profile",
"torch.nn.Conv2d",
"torch.autograd.profiler.profile",
"thop.clever_format",
"torch.no_grad",
"ptflops.get_model_complexity_info",
"torch.zeros"
] | [((204, 227), 'torch.zeros', 'torch.zeros', (['shape_nchw'], {}), '(shape_nchw)\n', (215, 227), False, 'import torch\n'), ((461, 567), 'torch.nn.Conv2d', 'nn.Conv2d', ([], {'in_channels': 'in_channels', 'out_channels': 'out_channels', 'kernel_size': 'kernel_size', 'stride': 'stride'}), '(in_channels=in_channels, out_ch... |
#!/usr/bin/env python
import os.path
import argparse
import json
parser = argparse.ArgumentParser(description=
'Compose ImageMagick arguments to extract sprites from a spritesheet.')
parser.add_argument('png', type=str,
help='the image of the spritesheet')
parser.add_argument('json', type=str,
... | [
"json.load",
"argparse.ArgumentParser"
] | [((76, 188), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Compose ImageMagick arguments to extract sprites from a spritesheet."""'}), "(description=\n 'Compose ImageMagick arguments to extract sprites from a spritesheet.')\n", (99, 188), False, 'import argparse\n'), ((566, 578), 'js... |
import numpy as np
import scipy as sp
import pandas as pd
from scipy import stats
def get_ecdf(series_):
return lambda x: (series_.sort_values() < x).astype(int).mean()
def get_sample_acvf(x, h):
"""
x: series
h: shift param
return: autocovariance estimator
"""
n = x.shape[0]
shift_x... | [
"numpy.abs",
"scipy.stats.ccf",
"numpy.sqrt",
"scipy.stats.norm.cdf",
"scipy.stats.norm.ppf",
"numpy.array",
"pandas.DataFrame",
"scipy.stats.spearmanr"
] | [((1203, 1220), 'numpy.array', 'np.array', (['results'], {}), '(results)\n', (1211, 1220), True, 'import numpy as np\n'), ((1849, 1879), 'numpy.sqrt', 'np.sqrt', (['(gamma_x_0 * gamma_y_0)'], {}), '(gamma_x_0 * gamma_y_0)\n', (1856, 1879), True, 'import numpy as np\n'), ((2515, 2532), 'numpy.array', 'np.array', (['resu... |
"""Implement signup flow v2
Revision ID: <KEY>
Revises: 1c7784767710
Create Date: 2021-06-25 08:17:24.410658
"""
import geoalchemy2
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = "<KEY>"
down_revision = "1c7784767710"
bran... | [
"sqlalchemy.Float",
"sqlalchemy.text",
"sqlalchemy.DateTime",
"alembic.op.drop_table",
"alembic.op.f",
"sqlalchemy.Boolean",
"sqlalchemy.PrimaryKeyConstraint",
"sqlalchemy.LargeBinary",
"sqlalchemy.Date",
"geoalchemy2.types.Geometry",
"sqlalchemy.Integer",
"sqlalchemy.dialects.postgresql.ENUM"... | [((3529, 3559), 'alembic.op.drop_table', 'op.drop_table', (['"""signup_tokens"""'], {}), "('signup_tokens')\n", (3542, 3559), False, 'from alembic import op\n'), ((4259, 4293), 'alembic.op.drop_table', 'op.drop_table', (['"""contributor_forms"""'], {}), "('contributor_forms')\n", (4272, 4293), False, 'from alembic impo... |
# -*- coding: utf-8 -*-
from marshmallow import fields
from eduid_common.api.schemas.base import EduidSchema, FluxStandardAction
from eduid_common.api.schemas.csrf import CSRFRequestMixin, CSRFResponseMixin
from eduid_common.api.schemas.validators import validate_nin
__author__ = 'lundberg'
class LookupMobileProof... | [
"marshmallow.fields.Boolean",
"marshmallow.fields.Nested",
"marshmallow.fields.String"
] | [((380, 431), 'marshmallow.fields.String', 'fields.String', ([], {'required': '(True)', 'validate': 'validate_nin'}), '(required=True, validate=validate_nin)\n', (393, 431), False, 'from marshmallow import fields\n'), ((666, 696), 'marshmallow.fields.Nested', 'fields.Nested', (['ResponsePayload'], {}), '(ResponsePayloa... |
# Copyright (c) 2019 Cisco and/or its affiliates.
# 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 ag... | [
"resources.libraries.python.PapiExecutor.PapiExecutor",
"resources.libraries.python.DUTSetup.DUTSetup.restart_service",
"binascii.hexlify",
"robot.api.logger.info",
"resources.libraries.python.DUTSetup.DUTSetup.get_service_logs",
"resources.libraries.python.ssh.exec_cmd_no_error",
"resources.libraries.p... | [((2290, 2340), 'resources.libraries.python.DUTSetup.DUTSetup.restart_service', 'DUTSetup.restart_service', (['node', 'Constants.VPP_UNIT'], {}), '(node, Constants.VPP_UNIT)\n', (2314, 2340), False, 'from resources.libraries.python.DUTSetup import DUTSetup\n'), ((2858, 2905), 'resources.libraries.python.DUTSetup.DUTSet... |
from test_helper import run_common_tests, failed, passed, get_answer_placeholders, do_not_run_on_check
if __name__ == '__main__':
do_not_run_on_check()
run_common_tests()
| [
"test_helper.run_common_tests",
"test_helper.do_not_run_on_check"
] | [((135, 156), 'test_helper.do_not_run_on_check', 'do_not_run_on_check', ([], {}), '()\n', (154, 156), False, 'from test_helper import run_common_tests, failed, passed, get_answer_placeholders, do_not_run_on_check\n'), ((161, 179), 'test_helper.run_common_tests', 'run_common_tests', ([], {}), '()\n', (177, 179), False, ... |
from __future__ import absolute_import, division, print_function, unicode_literals
import requests
import xmltodict, json
from difflib import SequenceMatcher
_DBLPSEARCH = 'http://dblp.uni-trier.de'
_AUTHSEARCH = '/search/author?xauthor='
_FULLSEARCH = '/pers/xx/'
_COAUTHSEARCH = '/pers/xc/'
_SESSION = requests.Sessi... | [
"difflib.SequenceMatcher",
"json.dumps",
"requests.Session",
"xmltodict.parse"
] | [((306, 324), 'requests.Session', 'requests.Session', ([], {}), '()\n', (322, 324), False, 'import requests\n'), ((3661, 3694), 'xmltodict.parse', 'xmltodict.parse', (['resp_url.content'], {}), '(resp_url.content)\n', (3676, 3694), False, 'import xmltodict, json\n'), ((870, 905), 'xmltodict.parse', 'xmltodict.parse', (... |
# -*- coding: utf-8 -*-
import logging
from itertools import islice
from asgiref.sync import sync_to_async
from channels.generic.websocket import AsyncJsonWebsocketConsumer
from edd import utilities
from .backend import RedisBroker
logger = logging.getLogger(__name__)
class SubscribeError(Exception):
pass
... | [
"logging.getLogger",
"asgiref.sync.sync_to_async",
"itertools.islice",
"edd.utilities.JSONEncoder.dumps",
"edd.utilities.JSONDecoder.loads"
] | [((246, 273), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (263, 273), False, 'import logging\n'), ((615, 648), 'edd.utilities.JSONDecoder.loads', 'utilities.JSONDecoder.loads', (['text'], {}), '(text)\n', (642, 648), False, 'from edd import utilities\n'), ((723, 759), 'edd.utilities.JS... |
#!/usr/local/bin/python3
from random import randint
def sortea_numero():
return randint(1, 6)
def eh_impar(numero: float):
return numero % 2 != 0
def acertou(numero_sorteado: float, numero: float):
return numero_sorteado == numero
if __name__ == '__main__':
numero_sorteado = sortea_numero()
... | [
"random.randint"
] | [((87, 100), 'random.randint', 'randint', (['(1)', '(6)'], {}), '(1, 6)\n', (94, 100), False, 'from random import randint\n')] |
"""
@Description:
@Usage:
@Author: liuxianglong
@Date: 2021/9/1 下午8:50
"""
import re
import logging
from w3lib.url import safe_url_string
from urllib.parse import urljoin, urlparse
from scrapy.exceptions import IgnoreRequest, NotConfigured
from scrapy.downloadermiddlewares.retry import RetryMiddleware
from scrapy.dow... | [
"logging.getLogger",
"urllib.parse.urlparse",
"urllib.parse.urljoin",
"w3lib.url.safe_url_string",
"re.search"
] | [((388, 415), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (405, 415), False, 'import logging\n'), ((1757, 1802), 'w3lib.url.safe_url_string', 'safe_url_string', (["response.headers['Location']"], {}), "(response.headers['Location'])\n", (1772, 1802), False, 'from w3lib.url import safe_... |
# coding=UTF-8
"""Tests for Urban Flood Risk Mitigation Model."""
import unittest
import tempfile
import shutil
import os
from osgeo import gdal
from osgeo import osr
from osgeo import ogr
import numpy
import pygeoprocessing
import shapely.geometry
class UFRMTests(unittest.TestCase):
"""Tests for... | [
"pygeoprocessing.reclassify_raster",
"pygeoprocessing.shapely_geometry_to_vector",
"numpy.isclose",
"pandas.read_csv",
"osgeo.osr.SpatialReference",
"natcap.invest.urban_flood_risk_mitigation._calculate_damage_to_infrastructure_in_aoi",
"numpy.testing.assert_allclose",
"os.path.join",
"natcap.invest... | [((593, 621), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {'suffix': '"""😎"""'}), "(suffix='😎')\n", (609, 621), False, 'import tempfile\n'), ((750, 783), 'shutil.rmtree', 'shutil.rmtree', (['self.workspace_dir'], {}), '(self.workspace_dir)\n', (763, 783), False, 'import shutil\n'), ((875, 900), 'os.path.dirname', 'o... |
# Copyright 2019 by <NAME>. All rights reserved.
#
#
# Authors: <NAME>
# Created : 2015/08/13
# Modified : 2015/0813
import getpass
from networktangents import netdef
gs_DeviceName = input('DeviceName: ')
gs_UserName = getpass.getpass("Username: ")
gs_password = getpass.getpass()
gs_EnablePass = getpass.getpass("E... | [
"networktangents.netdef.NetworkDevice",
"getpass.getpass"
] | [((224, 253), 'getpass.getpass', 'getpass.getpass', (['"""Username: """'], {}), "('Username: ')\n", (239, 253), False, 'import getpass\n'), ((268, 285), 'getpass.getpass', 'getpass.getpass', ([], {}), '()\n', (283, 285), False, 'import getpass\n'), ((302, 339), 'getpass.getpass', 'getpass.getpass', (['"""Enabled Passwo... |
from socket import *
import time
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_DGRAM)
msg = 'send'.encode()
clientSocket.settimeout(1)
for i in range(0, 10):
start = int(round(time.time() * 1000))
rtt = 0
clientSocket.sendto(msg, ('127.0.0.1', serverPort))
try:
message, addr = clientSo... | [
"time.time"
] | [((190, 201), 'time.time', 'time.time', ([], {}), '()\n', (199, 201), False, 'import time\n'), ((431, 442), 'time.time', 'time.time', ([], {}), '()\n', (440, 442), False, 'import time\n')] |
import cx_Oracle
DB = "xxx_high"
DB_USER = "admin"
DB_PASSWORD = "password"
connection = cx_Oracle.connect(DB_USER, DB_PASSWORD, DB)
print ("Connected")
| [
"cx_Oracle.connect"
] | [((91, 134), 'cx_Oracle.connect', 'cx_Oracle.connect', (['DB_USER', 'DB_PASSWORD', 'DB'], {}), '(DB_USER, DB_PASSWORD, DB)\n', (108, 134), False, 'import cx_Oracle\n')] |
"""
test_mod
~~~~~~~~
unit tests for the mkname.mod function.
"""
import unittest as ut
from unittest.mock import patch
from mkname import mod
# Test cases.
class AddLetters(ut.TestCase):
def _core_modify_test(self, exp, base_name, mod_fn, roll_values):
"""Core of the name modifier (mod) tests."""
... | [
"mkname.mod.add_punctuation",
"mkname.mod.compound_names",
"mkname.mod.translate_characters",
"unittest.mock.patch",
"mkname.mod.double_letter"
] | [((6557, 6581), 'mkname.mod.compound_names', 'mod.compound_names', (['a', 'b'], {}), '(a, b)\n', (6575, 6581), False, 'from mkname import mod\n'), ((8639, 8679), 'mkname.mod.translate_characters', 'mod.translate_characters', (['name', 'char_map'], {}), '(name, char_map)\n', (8663, 8679), False, 'from mkname import mod\... |
from agents import *
from models import *
import numpy as np
import matplotlib
matplotlib.use('tkagg')
import matplotlib.pyplot as plt
import sys
import pickle
# end class world
def speed_profile(file_names):
"""
This function is to plot speed profiles for several evaluation results.
Args:
file_nam... | [
"matplotlib.use",
"pickle.load",
"matplotlib.pyplot.figure",
"numpy.linspace",
"numpy.linalg.norm",
"numpy.shape",
"matplotlib.pyplot.subplot",
"numpy.arange"
] | [((79, 102), 'matplotlib.use', 'matplotlib.use', (['"""tkagg"""'], {}), "('tkagg')\n", (93, 102), False, 'import matplotlib\n'), ((732, 744), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (742, 744), True, 'import matplotlib.pyplot as plt\n'), ((754, 774), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2... |
import base64
import json
import requests
from settings import *
def main(event, context):
pubsub_message = base64.b64decode(event['data']).decode('utf-8') # type: json
log_data = json.loads(pubsub_message) # type: dict
print(log_data)
log_name = log_data["logName"] # type: str
resource = log_... | [
"json.dumps",
"json.loads",
"requests.post",
"base64.b64decode"
] | [((191, 217), 'json.loads', 'json.loads', (['pubsub_message'], {}), '(pubsub_message)\n', (201, 217), False, 'import json\n'), ((1090, 1133), 'requests.post', 'requests.post', (['SLACK_WEBHOOK_URL', 'json_data'], {}), '(SLACK_WEBHOOK_URL, json_data)\n', (1103, 1133), False, 'import requests\n'), ((114, 145), 'base64.b6... |
import FWCore.ParameterSet.Config as cms
siStripGainESProducer = cms.ESProducer("SiStripGainESProducer",
appendToDataLabel = cms.string(''),
printDebug = cms.untracked.bool(False),
AutomaticNormalization = cms.bool(False),
APVGain = cms.VPSet(
cms.PSet(
Record = cms.string('SiStripA... | [
"FWCore.ParameterSet.Config.string",
"FWCore.ParameterSet.Config.untracked.string",
"FWCore.ParameterSet.Config.untracked.double",
"FWCore.ParameterSet.Config.untracked.bool",
"FWCore.ParameterSet.Config.bool"
] | [((130, 144), 'FWCore.ParameterSet.Config.string', 'cms.string', (['""""""'], {}), "('')\n", (140, 144), True, 'import FWCore.ParameterSet.Config as cms\n'), ((163, 188), 'FWCore.ParameterSet.Config.untracked.bool', 'cms.untracked.bool', (['(False)'], {}), '(False)\n', (181, 188), True, 'import FWCore.ParameterSet.Conf... |
#
# -= ml_resetChannels.py =-
# __ by <NAME>
# ____ ___ / / http://morganloomis.com
# / __ `__ \/ / Licensed under Creative Commons BY-SA
# / / / / / / / http://creativecommons.org/licenses/by-sa/3.0/
# /_/ /_/ /_/_/ _________
# /______... | [
"maya.cmds.ls",
"ml_utilities.upToDateCheck",
"maya.cmds.setAttr",
"ml_utilities.deselectChannels",
"maya.mel.eval",
"maya.cmds.channelBox",
"maya.cmds.attributeQuery",
"maya.cmds.confirmDialog",
"maya.cmds.showHelp",
"maya.cmds.listAttr"
] | [((2232, 2253), 'ml_utilities.upToDateCheck', 'utl.upToDateCheck', (['(14)'], {}), '(14)\n', (2249, 2253), True, 'import ml_utilities as utl\n'), ((2987, 3020), 'maya.mel.eval', 'mm.eval', (['"""$temp=$gChannelBoxName"""'], {}), "('$temp=$gChannelBoxName')\n", (2994, 3020), True, 'import maya.mel as mm\n'), ((3036, 305... |
from typing import Dict
import numpy as np
import pytorch_lightning as pl
import torch
from omegaconf import DictConfig
from src.utils.technical_utils import load_obj
class LitNER(pl.LightningModule):
def __init__(self, cfg: DictConfig, tag_to_idx: Dict):
super(LitNER, self).__init__()
self.cfg ... | [
"src.utils.technical_utils.load_obj"
] | [((384, 414), 'src.utils.technical_utils.load_obj', 'load_obj', (['cfg.model.class_name'], {}), '(cfg.model.class_name)\n', (392, 414), False, 'from src.utils.technical_utils import load_obj\n'), ((1127, 1166), 'src.utils.technical_utils.load_obj', 'load_obj', (['self.cfg.optimizer.class_name'], {}), '(self.cfg.optimiz... |
import logzero
_log_format = ("%(color)s%(levelname)s:%(end_color)s %(message)s")
formatter = logzero.LogFormatter(fmt=_log_format)
# options
log = logzero.setup_logger(formatter=formatter)
args = None
| [
"logzero.setup_logger",
"logzero.LogFormatter"
] | [((95, 132), 'logzero.LogFormatter', 'logzero.LogFormatter', ([], {'fmt': '_log_format'}), '(fmt=_log_format)\n', (115, 132), False, 'import logzero\n'), ((150, 191), 'logzero.setup_logger', 'logzero.setup_logger', ([], {'formatter': 'formatter'}), '(formatter=formatter)\n', (170, 191), False, 'import logzero\n')] |
"""Defines a background widget to create a single-color background."""
from os.path import dirname as _dirname
from typing import Optional as _Optional
from kivy.lang.builder import Builder as _Builder
from kivy.properties import ListProperty as _ListProperty
from kivy.uix.widget import Widget as _Widget
_Builder.lo... | [
"os.path.dirname",
"kivy.properties.ListProperty"
] | [((577, 601), 'kivy.properties.ListProperty', '_ListProperty', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (590, 601), True, 'from kivy.properties import ListProperty as _ListProperty\n'), ((328, 346), 'os.path.dirname', '_dirname', (['__file__'], {}), '(__file__)\n', (336, 346), True, 'from os.path import dirname as _dirnam... |
from typing import Dict, List, Optional
from request.base_handler import SERVICE_ID_FHIR_IDENTIFIER
from request.mapper_urls import MapperUrls as Url
from utilities import message_utilities
SERVICE_ID_FHIR_IDENTIFIER = "https://fhir.nhs.uk/Id/nhsServiceInteractionId"
def build_bundle_resource(resources: List[Dict],... | [
"utilities.message_utilities.get_uuid"
] | [((413, 441), 'utilities.message_utilities.get_uuid', 'message_utilities.get_uuid', ([], {}), '()\n', (439, 441), False, 'from utilities import message_utilities\n'), ((2720, 2748), 'utilities.message_utilities.get_uuid', 'message_utilities.get_uuid', ([], {}), '()\n', (2746, 2748), False, 'from utilities import messag... |
from dotenv import load_dotenv
import os
load_dotenv()
DISCORD_CLIENT = os.getenv('DISCORD_CLIENT')
DISCORD_GUILD = os.getenv('DISCORD_GUILD')
DISCORD_CHANNEL = os.getenv('DISCORD_CHANNEL')
WORLDCOIN = os.getenv('WORLDCOIN')
| [
"os.getenv",
"dotenv.load_dotenv"
] | [((42, 55), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (53, 55), False, 'from dotenv import load_dotenv\n'), ((74, 101), 'os.getenv', 'os.getenv', (['"""DISCORD_CLIENT"""'], {}), "('DISCORD_CLIENT')\n", (83, 101), False, 'import os\n'), ((118, 144), 'os.getenv', 'os.getenv', (['"""DISCORD_GUILD"""'], {}), "... |
from django.conf.urls import include, url
from know_me.profile import views
app_name = "profile"
profile_urls = [
url(
r"^list-entries/(?P<pk>[0-9]+)/$",
views.ListEntryDetailView.as_view(),
name="list-entry-detail",
),
url(
r"^media-resources/(?P<pk>[0-9]+)/$",
... | [
"know_me.profile.views.ProfileListView.as_view",
"know_me.profile.views.ProfileTopicListView.as_view",
"know_me.profile.views.ListEntryDetailView.as_view",
"know_me.profile.views.ListEntryListView.as_view",
"know_me.profile.views.MediaResourceCoverStyleDetailView.as_view",
"know_me.profile.views.ProfileIt... | [((179, 214), 'know_me.profile.views.ListEntryDetailView.as_view', 'views.ListEntryDetailView.as_view', ([], {}), '()\n', (212, 214), False, 'from know_me.profile import views\n'), ((320, 359), 'know_me.profile.views.MediaResourceDetailView.as_view', 'views.MediaResourceDetailView.as_view', ([], {}), '()\n', (357, 359)... |
from .state import EOF
from .tokens import TokenEof
from .tokens_base import TOKEN_COMMAND_UNABBREVIATE
from .tokens_base import TokenOfCommand
from Vintageous import ex
@ex.command('unabbreviate', 'una')
class TokenUnabbreviate(TokenOfCommand):
def __init__(self, params, *args, **kwargs):
super().__init_... | [
"Vintageous.ex.command"
] | [((173, 206), 'Vintageous.ex.command', 'ex.command', (['"""unabbreviate"""', '"""una"""'], {}), "('unabbreviate', 'una')\n", (183, 206), False, 'from Vintageous import ex\n')] |
# -*- coding: utf-8 -*-
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from rest_framework.serializers import Serializer
from apps.accounts import response_codes
from apps.accounts.api.v1.serializers.login import UsernameOrEmailSerializer
from apps.accounts.models import ... | [
"django.utils.translation.ugettext_lazy",
"rest_framework.serializers.URLField",
"apps.accounts.models.User._meta.get_field",
"rest_framework.serializers.CharField",
"rest_framework.exceptions.ValidationError"
] | [((404, 436), 'apps.accounts.models.User._meta.get_field', 'User._meta.get_field', (['"""password"""'], {}), "('password')\n", (424, 436), False, 'from apps.accounts.models import User\n'), ((2992, 3028), 'rest_framework.serializers.URLField', 'serializers.URLField', ([], {'required': '(False)'}), '(required=False)\n',... |
"""
@author: <NAME>
@brief:
@description:
@external_use:
@internal_use:
"""
import pynetworking as net
from pynetworking.Logging import logger
class _DummyServerFunctions(net.ServerFunctions):
@staticmethod
def return_client_id() -> int:
return net.ClientManager().get().id
@staticmethod
d... | [
"pynetworking.File",
"pynetworking.ClientManager"
] | [((4663, 4700), 'pynetworking.File', 'net.File', (['file_path', 'destination_path'], {}), '(file_path, destination_path)\n', (4671, 4700), True, 'import pynetworking as net\n'), ((267, 286), 'pynetworking.ClientManager', 'net.ClientManager', ([], {}), '()\n', (284, 286), True, 'import pynetworking as net\n'), ((4059, 4... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-26 17:25
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('music', '0002_auto_20170325_1658'),
]
operations = [
migrations.AlterModelOptions(
... | [
"django.db.migrations.AlterModelOptions"
] | [((290, 385), 'django.db.migrations.AlterModelOptions', 'migrations.AlterModelOptions', ([], {'name': '"""ownedrecord"""', 'options': "{'ordering': ['-purchase_date']}"}), "(name='ownedrecord', options={'ordering': [\n '-purchase_date']})\n", (318, 385), False, 'from django.db import migrations\n'), ((425, 514), 'dj... |
import logging
import time
from datetime import timedelta
from threading import Event, Thread
LOGGER = logging.getLogger(__name__)
class Task(Thread):
"""Base class to represent a Task that is executed by a trigger.
"""
def __init__(self, name: str, interval: timedelta, stop_event: Event, log_interval_s... | [
"logging.getLogger",
"threading.Thread.__init__",
"time.time"
] | [((104, 131), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (121, 131), False, 'import logging\n'), ((379, 415), 'threading.Thread.__init__', 'Thread.__init__', (['self'], {'daemon': 'daemon'}), '(self, daemon=daemon)\n', (394, 415), False, 'from threading import Event, Thread\n'), ((679... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from classFig import classFig
fig = classFig('PPT',(2,1),sharex=True,hspace=0.1,figshow=False)
fig.plot([1,2,3,2,1])
#fig.show()
fig.save('classFig_debug.png')
| [
"classFig.classFig"
] | [((85, 148), 'classFig.classFig', 'classFig', (['"""PPT"""', '(2, 1)'], {'sharex': '(True)', 'hspace': '(0.1)', 'figshow': '(False)'}), "('PPT', (2, 1), sharex=True, hspace=0.1, figshow=False)\n", (93, 148), False, 'from classFig import classFig\n')] |
import discord
from discord.ext import commands
from chickensmoothie import _get_web_data
class Oekaki:
def __init__(self, bot):
self.bot = bot
@commands.command()
@commands.guild_only()
async def oekaki(self, ctx, link: str = ''):
data = await _get_web_data(link) # Get Oekaki data
... | [
"chickensmoothie._get_web_data",
"discord.ext.commands.guild_only",
"discord.Embed",
"discord.ext.commands.command"
] | [((165, 183), 'discord.ext.commands.command', 'commands.command', ([], {}), '()\n', (181, 183), False, 'from discord.ext import commands\n'), ((189, 210), 'discord.ext.commands.guild_only', 'commands.guild_only', ([], {}), '()\n', (208, 210), False, 'from discord.ext import commands\n'), ((281, 300), 'chickensmoothie._... |
#!/usr/bin/env python3
# SPDX-License-Identifier: BlueOak-1.0.0
import datetime as dt
import mimetypes
import subprocess
import os
import tempfile
import urllib.parse
import mimetypes
from functools import partial
from pathlib import Path, PurePosixPath
import pygments
import pygments.lexers
import pygments.formatte... | [
"flask.request.args.get",
"flask.Flask",
"utils.content_disposition",
"mimetypes.guess_type",
"pathlib.PurePosixPath",
"pygments.lexers.get_lexer_for_filename",
"pathlib.Path",
"tempfile.NamedTemporaryFile",
"flask.abort",
"utils.natural_size",
"tarfile_stream.open",
"pygments.formatters.HtmlF... | [((1190, 1225), 'flask.Flask', 'Flask', (['__name__'], {'static_folder': 'None'}), '(__name__, static_folder=None)\n', (1195, 1225), False, 'from flask import Flask, Response, abort, render_template, request, redirect, url_for, make_response\n'), ((2154, 2188), 'functools.partial', 'partial', (['ensure_beneath', 'base_... |
from src import Generator
from src import cells
from src import index
from src import offset
from src import print_rows
generator = Generator()
def matrix_elements (list, label, width, height) :
for row in range(height) :
for column in range(width) :
list.append(label + str(column) + str(row))
return l... | [
"src.Generator",
"src.cells",
"src.offset"
] | [((133, 144), 'src.Generator', 'Generator', ([], {}), '()\n', (142, 144), False, 'from src import Generator\n'), ((1616, 1643), 'src.cells', 'cells', (['dimension', 'dimension'], {}), '(dimension, dimension)\n', (1621, 1643), False, 'from src import cells\n'), ((1681, 1711), 'src.offset', 'offset', (['column', 'row', '... |
# Supercell Code
from supercell.breezometer.fires.models.fire_position_distance import (
FirePositionDistance,
)
def test_model():
obj = FirePositionDistance(units="km", value=4.3)
assert "4.3 km" == str(obj)
def test_model_init_from_dict():
obj = FirePositionDistance.initialize_from_dictionary(
... | [
"supercell.breezometer.fires.models.fire_position_distance.FirePositionDistance",
"supercell.breezometer.fires.models.fire_position_distance.FirePositionDistance.initialize_from_dictionary"
] | [((147, 190), 'supercell.breezometer.fires.models.fire_position_distance.FirePositionDistance', 'FirePositionDistance', ([], {'units': '"""km"""', 'value': '(4.3)'}), "(units='km', value=4.3)\n", (167, 190), False, 'from supercell.breezometer.fires.models.fire_position_distance import FirePositionDistance\n'), ((268, 3... |
import keras
from sklearn.metrics import roc_auc_score
auc_score = 0.0
class Histories(keras.callbacks.Callback):
def on_train_begin(self, logs={}):
self.aucs = []
#self.losses = []
def on_train_end(self, logs={}):
return
def on_epoch_begin(self, epoch, logs={}):
global auc_score
print("AUC:",auc_score)... | [
"sklearn.metrics.roc_auc_score"
] | [((507, 559), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (['self.model.validation_data[1]', 'y_pred'], {}), '(self.model.validation_data[1], y_pred)\n', (520, 559), False, 'from sklearn.metrics import roc_auc_score\n')] |
from django.shortcuts import render, redirect
# Create your views here.
from django.http import Http404
from homework_app.models import Homework, Comment
from django.views.generic.list import ListView
from homework_app.forms import CommentForm
def homework(request, homework_id):
p = Homework.objects.get(pk=homew... | [
"django.shortcuts.render",
"homework_app.forms.CommentForm",
"homework_app.models.Comment.objects.filter",
"homework_app.models.Homework.objects.get",
"django.shortcuts.redirect"
] | [((291, 327), 'homework_app.models.Homework.objects.get', 'Homework.objects.get', ([], {'pk': 'homework_id'}), '(pk=homework_id)\n', (311, 327), False, 'from homework_app.models import Homework, Comment\n'), ((774, 815), 'django.shortcuts.render', 'render', (['request', '"""homework.html"""', 'context'], {}), "(request... |
import json
class ResultRecord:
def __init__(self, raw_data, pretty_print):
self.data_dict = json.loads(raw_data)
self.lang_code = self.data_dict['lang_code']
self.category = self.data_dict['category']
self.__pretty_print = pretty_print
def __repr__(self):
return self.... | [
"json.loads"
] | [((106, 126), 'json.loads', 'json.loads', (['raw_data'], {}), '(raw_data)\n', (116, 126), False, 'import json\n')] |
import httpx
from statuscheck.services.bases._base import BaseServiceAPI
from statuscheck.services.models.generic import (
COMPONENT_TYPE_DEGRADED,
COMPONENT_TYPE_GOOD,
COMPONENT_TYPE_MAINTENANCE,
COMPONENT_TYPE_MAJOR_OUTAGE,
COMPONENT_TYPE_PARTIAL_OUTAGE,
COMPONENT_TYPE_SECURITY,
COMPONENT... | [
"statuscheck.services.models.generic.Component",
"httpx.get",
"statuscheck.services.models.generic.Summary"
] | [((3568, 3606), 'statuscheck.services.models.generic.Summary', 'Summary', (['status', 'components', 'incidents'], {}), '(status, components, incidents)\n', (3575, 3606), False, 'from statuscheck.services.models.generic import COMPONENT_TYPE_DEGRADED, COMPONENT_TYPE_GOOD, COMPONENT_TYPE_MAINTENANCE, COMPONENT_TYPE_MAJOR... |
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Layer
class MultiMaskedConv2D(Layer):
"""
Masked multitask 2-dimensional convolutional layer. This layer implements
multiple stacks of the convolutional architecture and implements masking consistent
with the MANN API to sup... | [
"tensorflow.keras.initializers.serialize",
"tensorflow.keras.activations.get",
"tensorflow.keras.initializers.get",
"tensorflow.keras.activations.serialize"
] | [((2103, 2139), 'tensorflow.keras.activations.get', 'tf.keras.activations.get', (['activation'], {}), '(activation)\n', (2127, 2139), True, 'import tensorflow as tf\n'), ((2207, 2252), 'tensorflow.keras.initializers.get', 'tf.keras.initializers.get', (['kernel_initializer'], {}), '(kernel_initializer)\n', (2232, 2252),... |
# -*- coding: utf-8 -*-
"""Data association solver module.
Data association is the key to match a list of observed objects and the list of
currently tracked items. It can be reduced to linear assignment problem and
solved by Hungarian algorithm (or Kuhn–Munkres algorithm). `scipy` package
already implements this alg... | [
"tracker.tracker.get_est_dict",
"scipy.optimize.linear_sum_assignment",
"tracker.tracker",
"absl.flags.DEFINE_integer",
"tracker.tracker.get_bbox",
"absl.logging.info",
"absl.app.run",
"numpy.array",
"numpy.random.randint",
"numpy.empty",
"absl.logging.set_verbosity"
] | [((1987, 2023), 'scipy.optimize.linear_sum_assignment', 'linear_sum_assignment', (['(-match_matrix)'], {}), '(-match_matrix)\n', (2008, 2023), False, 'from scipy.optimize import linear_sum_assignment\n'), ((2646, 2674), 'numpy.array', 'np.array', (['unmatched_bbox_idx'], {}), '(unmatched_bbox_idx)\n', (2654, 2674), Tru... |
from sklearn.neural_network import MLPRegressor
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0.0, 1, 0.01).reshape(-1, 1)
y = np.sinc(x).ravel()
nn = MLPRegressor(hidden_layer_sizes=(3),
activation='tanh', solver='lbfgs')
n = nn.fit(x, y)
test_x = np.arange(-0.1, 1.1, 0.01).re... | [
"sklearn.neural_network.MLPRegressor",
"numpy.arange",
"numpy.sinc",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show"
] | [((172, 241), 'sklearn.neural_network.MLPRegressor', 'MLPRegressor', ([], {'hidden_layer_sizes': '(3)', 'activation': '"""tanh"""', 'solver': '"""lbfgs"""'}), "(hidden_layer_sizes=3, activation='tanh', solver='lbfgs')\n", (184, 241), False, 'from sklearn.neural_network import MLPRegressor\n'), ((368, 380), 'matplotlib.... |
import tensorflow as tf
import tensorflow_probability as tfp
@tf.function
def euclideanPairwiseDistance(x):
distance = tf.expand_dims(x, 1) - tf.expand_dims(tf.stop_gradient(x), 0)
return tf.einsum('ijk,kji->ij', distance, tf.transpose(distance))
class RbfKernel:
@tf.function
def __call__(self, x):
... | [
"tensorflow.transpose",
"tensorflow.math.log",
"tensorflow_probability.stats.percentile",
"tensorflow.stop_gradient",
"tensorflow.constant",
"tensorflow.expand_dims",
"tensorflow.exp"
] | [((124, 144), 'tensorflow.expand_dims', 'tf.expand_dims', (['x', '(1)'], {}), '(x, 1)\n', (138, 144), True, 'import tensorflow as tf\n'), ((232, 254), 'tensorflow.transpose', 'tf.transpose', (['distance'], {}), '(distance)\n', (244, 254), True, 'import tensorflow as tf\n'), ((455, 497), 'tensorflow.exp', 'tf.exp', (['(... |
from flask_wtf import FlaskForm
from wtforms import SubmitField, StringField, TextAreaField, SelectField
from wtforms.fields.html5 import DateField
from wtforms.validators import DataRequired, ValidationError, URL, Optional
from www.core import Env
from ...components import MultiCheckboxField
from www.services.synapse... | [
"re.split",
"www.services.synapse_space.daa.GrantDaaAccessService.Validations.validate_team_name",
"re.compile",
"wtforms.validators.ValidationError",
"re.match",
"wtforms.SubmitField",
"www.core.Env.get_daa_grant_access_data_collection_by_name",
"www.core.Env.get_default_daa_grant_access_config",
"... | [((1286, 1313), 'wtforms.SubmitField', 'SubmitField', (['"""Grant Access"""'], {}), "('Grant Access')\n", (1297, 1313), False, 'from wtforms import SubmitField, StringField, TextAreaField, SelectField\n'), ((1818, 1883), 're.compile', 're.compile', (['"""(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\\\.[a-zA-Z0-9-.]+$)"""'], {}), ... |
# Copyright 2022 Quantapix 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 applicable l... | [
"torch.tensor",
"torch.all",
"torch.cat",
"torch.full"
] | [((1577, 1603), 'torch.tensor', 'torch.tensor', (['DUMMY_INPUTS'], {}), '(DUMMY_INPUTS)\n', (1589, 1603), False, 'import torch\n'), ((1625, 1649), 'torch.tensor', 'torch.tensor', (['DUMMY_MASK'], {}), '(DUMMY_MASK)\n', (1637, 1649), False, 'import torch\n'), ((4689, 4739), 'torch.full', 'torch.full', (['(input_ids.shap... |
# https://codereview.stackexchange.com/questions/182700/python-class-to-manage-a-table-in-sqlite
import sqlite3
class SqliteDatabase(object):
def __init__(self, db_name=''):
self.db_name = db_name
self.connection = sqlite3.connect(self.db_name)
self.cursor = self.connection.cursor()
... | [
"sqlite3.connect"
] | [((237, 266), 'sqlite3.connect', 'sqlite3.connect', (['self.db_name'], {}), '(self.db_name)\n', (252, 266), False, 'import sqlite3\n')] |
import numpy as np
import cv2
import socketserver
from threading import Thread
cap = cv2.VideoCapture(0)
cv2.namedWindow('frame')
def nothing(x):
pass
lowh = 0
lowl = 0
lows = 0
highh = 255
highl = 255
highs = 255
cv2.createTrackbar('lowh', 'frame', 0, 255, nothing)
cv2.createTrackbar('lowl', 'frame', 0, 255, not... | [
"cv2.inRange",
"cv2.contourArea",
"cv2.imshow",
"numpy.array",
"cv2.waitKey",
"cv2.destroyAllWindows",
"cv2.VideoCapture",
"cv2.getTrackbarPos",
"cv2.cvtColor",
"cv2.findContours",
"cv2.moments",
"cv2.createTrackbar",
"cv2.namedWindow",
"cv2.boundingRect"
] | [((86, 105), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (102, 105), False, 'import cv2\n'), ((106, 130), 'cv2.namedWindow', 'cv2.namedWindow', (['"""frame"""'], {}), "('frame')\n", (121, 130), False, 'import cv2\n'), ((220, 272), 'cv2.createTrackbar', 'cv2.createTrackbar', (['"""lowh"""', '"""frame... |
r"""This module implements the RichardGrowth class.
Inheriting from the base Growth class, this class implements a Richard (1959)
growth model.
"""
from growth_modeling import Growth
import numpy as np
class RichardGrowth(Growth):
r"""Implement the Richard's equation growth model.
Attributes
-------... | [
"numpy.exp"
] | [((3190, 3211), 'numpy.exp', 'np.exp', (['(d - a * b * t)'], {}), '(d - a * b * t)\n', (3196, 3211), True, 'import numpy as np\n')] |
import logging
import time, datetime
from thespian.actors import *
from thespian.test import *
import signal
import os
class KillMeActor(Actor):
def receiveMessage(self, msg, sender):
logging.info('EchoActor got %s (%s) from %s', msg, type(msg), sender)
self.send(sender, os.getpid())
class Paren... | [
"datetime.timedelta",
"os.kill",
"os.getpid",
"time.sleep"
] | [((864, 900), 'datetime.timedelta', 'datetime.timedelta', ([], {'milliseconds': '(350)'}), '(milliseconds=350)\n', (882, 900), False, 'import time, datetime\n'), ((1661, 1696), 'os.kill', 'os.kill', (['killme_pid', 'signal.SIGCONT'], {}), '(killme_pid, signal.SIGCONT)\n', (1668, 1696), False, 'import os\n'), ((2027, 20... |
import numpy as np
import pandas as pd
import pathlib
import copy
import sklearn
from sklearn.model_selection import train_test_split
import json
import datetime
import argparse
parser = argparse.ArgumentParser(description='Preprocess data, choose datasets')
parser.add_argument('--dataset', type=str, help="used datase... | [
"pandas.read_csv",
"argparse.ArgumentParser",
"sklearn.model_selection.train_test_split",
"pathlib.Path",
"datetime.datetime.strptime",
"copy.deepcopy",
"pandas.concat",
"json.dump"
] | [((188, 259), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Preprocess data, choose datasets"""'}), "(description='Preprocess data, choose datasets')\n", (211, 259), False, 'import argparse\n'), ((1877, 1894), 'copy.deepcopy', 'copy.deepcopy', (['df'], {}), '(df)\n', (1890, 1894), False... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import math
from pathlib import Path
import argparse
import os
def generate_news(raw_data_path):
for mode in ['train', 'dev', 'test']:
Path(f'./data/speedy_data/{mode}').mkdir(parents=True, exist_ok=True)
fsave = open('./data... | [
"os.path.join",
"pathlib.Path",
"argparse.ArgumentParser",
"math.floor"
] | [((1569, 1597), 'math.floor', 'math.floor', (['(all_l / file_num)'], {}), '(all_l / file_num)\n', (1579, 1597), False, 'import math\n'), ((3195, 3220), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (3218, 3220), False, 'import argparse\n'), ((881, 941), 'os.path.join', 'os.path.join', (['raw_d... |
import nltk
nltk.download()
sentence = """At ten o'clock on friday morning sam didn't feel very good."""
tokens = nltk.word_tokenize(sentence)
print(tokens)
tagged = nltk.pos_tag(tokens)
tagged[0:6]
print(tagged)
| [
"nltk.pos_tag",
"nltk.word_tokenize",
"nltk.download"
] | [((12, 27), 'nltk.download', 'nltk.download', ([], {}), '()\n', (25, 27), False, 'import nltk\n'), ((114, 142), 'nltk.word_tokenize', 'nltk.word_tokenize', (['sentence'], {}), '(sentence)\n', (132, 142), False, 'import nltk\n'), ((167, 187), 'nltk.pos_tag', 'nltk.pos_tag', (['tokens'], {}), '(tokens)\n', (179, 187), Fa... |
# Copyright 2019 UCLA Networked & Embedded Systems Laboratory (Author: <NAME>)
# 2020 Sogang University Auditory Intelligence Laboratory (Author: <NAME>)
#
# MIT License
import os
import sys
import argparse
import librosa
import data_utils
import numpy as np
import torch
import torch.nn.functional as F
fro... | [
"os.path.exists",
"torch.optim.lr_scheduler.ReduceLROnPlateau",
"argparse.ArgumentParser",
"torch.load",
"os.path.join",
"torch.nn.DataParallel",
"models.SiameseNetwork",
"data_utils.Dataset",
"torch.cuda.is_available",
"torch.nn.NLLLoss",
"os.mkdir",
"torch.nn.functional.relu",
"torch.utils... | [((6756, 6781), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (6779, 6781), False, 'import argparse\n'), ((10088, 10113), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (10111, 10113), False, 'import torch\n'), ((6576, 6635), 'torch.nn.functional.relu', 'F.relu', (['(d... |
__author__ = 'Todd.Hay'
# -------------------------------------------------------------------------------
# Name: ProtocolViewer.py
# Purpose:
#
# Author: Todd.Hay
# Email: <EMAIL>
#
# Created: April 13, 2016
# License: MIT
#-------------------------------------------------------------------... | [
"py.trawl.TrawlBackdeckDB_model.SpeciesSamplingPlanLu.select"
] | [((9894, 9924), 'py.trawl.TrawlBackdeckDB_model.SpeciesSamplingPlanLu.select', 'SpeciesSamplingPlanLu.select', ([], {}), '()\n', (9922, 9924), False, 'from py.trawl.TrawlBackdeckDB_model import SpeciesSamplingPlanLu\n')] |
import os
INFERENCE_GPUS = [8]
CENTER_SIZE = 2000 # The effective patch size.
BORDER_SIZE = 100 # The boarder size containing surrounding information.
PATCH_SIZE = CENTER_SIZE + 2 * BORDER_SIZE
format_mapping = {
'tif': 'OpenSlide',
'svs': 'OpenSlide',
'ndpi': 'OpenSlide',
'scn': 'OpenSlide',
'mr... | [
"os.environ.get"
] | [((473, 519), 'os.environ.get', 'os.environ.get', (['"""TF_SERVING_HOST"""', '"""127.0.0.1"""'], {}), "('TF_SERVING_HOST', '127.0.0.1')\n", (487, 519), False, 'import os\n'), ((542, 581), 'os.environ.get', 'os.environ.get', (['"""TF_SERVING_PORT"""', '(9000)'], {}), "('TF_SERVING_PORT', 9000)\n", (556, 581), False, 'im... |
'''
Used for executing slight variations on the same command.
usage:
resaw command arg1 arg2 {x} arg3
then x will be inputted from stdin every time.
The curly braces are required literally.
'''
import subprocess
import sys
if len(sys.argv) < 2:
raise ValueError()
COMMAND = ' '.join('"%s"' % arg for arg in sys.a... | [
"subprocess.run"
] | [((417, 452), 'subprocess.run', 'subprocess.run', (['command'], {'shell': '(True)'}), '(command, shell=True)\n', (431, 452), False, 'import subprocess\n')] |
from opendc.models.datacenter import Datacenter
from opendc.models.model import Model
from opendc.util import exceptions
class Room(Model):
JSON_TO_PYTHON_DICT = {
'room': {
'id': 'id',
'datacenterId': 'datacenter_id',
'name': 'name',
'roomType': 'type',
... | [
"opendc.models.datacenter.Datacenter.from_primary_key"
] | [((780, 830), 'opendc.models.datacenter.Datacenter.from_primary_key', 'Datacenter.from_primary_key', (['(self.datacenter_id,)'], {}), '((self.datacenter_id,))\n', (807, 830), False, 'from opendc.models.datacenter import Datacenter\n')] |
import tkinter as tk #possibly nessesary unsure
import cv2
import numpy as np
import matplotlib.pyplot as plt
import time
import sys
import os
import re
SCALEDOWNFACTOR = 0.2 #This is a magic number but what can ya do. I dont have a good way of getting image resolution.
SCALEUPFACTOR = 2.0
GAIN = 13.2
DIST... | [
"cv2.normalize",
"matplotlib.pyplot.ylabel",
"numpy.log",
"cv2.imshow",
"cv2.destroyAllWindows",
"sys.exit",
"numpy.genfromtxt",
"numpy.arange",
"cv2.threshold",
"matplotlib.pyplot.xlabel",
"numpy.asarray",
"numpy.exp",
"numpy.linspace",
"numpy.dot",
"numpy.empty",
"numpy.vstack",
"m... | [((3702, 3725), 'numpy.linspace', 'np.linspace', (['(-2)', '(2)', '(101)'], {}), '(-2, 2, 101)\n', (3713, 3725), True, 'import numpy as np\n'), ((3738, 3840), 'numpy.genfromtxt', 'np.genfromtxt', (['"""GAUSS-24.dat"""'], {'skip_header': '(1)', 'skip_footer': '(1)', 'names': '(True)', 'dtype': 'None', 'delimiter': '""" ... |
#!/usr/bin/env python
# coding: utf-8
# In[24]:
import json
import random
import numpy as np
from pathlib import Path
from typing import Tuple, List
import math
import matplotlib.pyplot as plt
#get_ipython().run_line_magic('matplotlib', 'inline')
from tensorflow.keras.layers import Input, Dense, Conv2D, MaxPooling2... | [
"matplotlib.pyplot.hist",
"tensorflow.keras.callbacks.EarlyStopping",
"numpy.array",
"tensorflow.keras.layers.Dense",
"numpy.arange",
"matplotlib.pyplot.imshow",
"tensorflow.keras.layers.Input",
"pathlib.Path",
"tensorflow.keras.callbacks.ReduceLROnPlateau",
"tensorflow.Session",
"json.dumps",
... | [((1099, 1115), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {}), '()\n', (1113, 1115), True, 'import tensorflow as tf\n'), ((1165, 1190), 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), '(config=config)\n', (1175, 1190), True, 'import tensorflow as tf\n'), ((1191, 1228), 'tensorflow.keras.backend.s... |
from django.contrib.auth.models import User
from django.test import TestCase
from django.urls import reverse
from silverstrike.models import Account, Category, Split, Transaction
class ModelTests(TestCase):
def test_account_str_method(self):
account = Account.objects.create(name="some_account")
s... | [
"django.contrib.auth.models.User.objects.create_superuser",
"silverstrike.models.Transaction.objects.create",
"silverstrike.models.Account.objects.create",
"silverstrike.models.Split.objects.create",
"silverstrike.models.Category.objects.create",
"silverstrike.models.Transaction.objects.first",
"silvers... | [((267, 310), 'silverstrike.models.Account.objects.create', 'Account.objects.create', ([], {'name': '"""some_account"""'}), "(name='some_account')\n", (289, 310), False, 'from silverstrike.models import Account, Category, Split, Transaction\n'), ((373, 465), 'django.contrib.auth.models.User.objects.create_superuser', '... |
import pexpect
from pexpect import exceptions
import time
from rassh.managers.expect_manager import ExpectManager
from rassh.managers.expect_commands import ExpectCommands
from rassh.managers.blackhole_telnet_commands import BlackholeTelnetCommands
import logging
logging.basicConfig(level=logging.INFO)
logger = loggi... | [
"logging.basicConfig",
"logging.getLogger",
"pexpect.spawn",
"rassh.managers.blackhole_telnet_commands.BlackholeTelnetCommands",
"time.sleep"
] | [((266, 305), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (285, 305), False, 'import logging\n'), ((315, 342), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (332, 342), False, 'import logging\n'), ((1970, 1999), 'rassh.managers... |
import copy
from _seidel import XNode
from hypothesis import given
from . import strategies
@given(strategies.x_nodes)
def test_shallow(x_node: XNode) -> None:
result = copy.copy(x_node)
assert result is not x_node
assert result == x_node
@given(strategies.x_nodes)
def test_deep(x_node: XNode) -> Non... | [
"hypothesis.given",
"copy.copy",
"copy.deepcopy"
] | [((97, 122), 'hypothesis.given', 'given', (['strategies.x_nodes'], {}), '(strategies.x_nodes)\n', (102, 122), False, 'from hypothesis import given\n'), ((259, 284), 'hypothesis.given', 'given', (['strategies.x_nodes'], {}), '(strategies.x_nodes)\n', (264, 284), False, 'from hypothesis import given\n'), ((177, 194), 'co... |
from pywinos import WinOSClient
def test_is_host_available_remote():
tool = WinOSClient('8.8.8.8')
response = tool.is_host_available(port=53)
assert response, 'Response is not True'
def test_is_host_unavailable_remote():
tool = WinOSClient('8.8.8.8')
response = tool.is_host_available(port=22)
... | [
"pywinos.WinOSClient"
] | [((82, 104), 'pywinos.WinOSClient', 'WinOSClient', (['"""8.8.8.8"""'], {}), "('8.8.8.8')\n", (93, 104), False, 'from pywinos import WinOSClient\n'), ((248, 270), 'pywinos.WinOSClient', 'WinOSClient', (['"""8.8.8.8"""'], {}), "('8.8.8.8')\n", (259, 270), False, 'from pywinos import WinOSClient\n'), ((466, 486), 'pywinos... |
import click
def note(message):
click.secho(f'\n==> {message}', fg='green')
def info(message):
click.secho(f'\n==> {message}', fg='yellow')
def warn(message):
click.secho(f'\n==> {message}', fg='red')
| [
"click.secho"
] | [((38, 81), 'click.secho', 'click.secho', (['f"""\n==> {message}"""'], {'fg': '"""green"""'}), "(f'\\n==> {message}', fg='green')\n", (49, 81), False, 'import click\n'), ((107, 151), 'click.secho', 'click.secho', (['f"""\n==> {message}"""'], {'fg': '"""yellow"""'}), "(f'\\n==> {message}', fg='yellow')\n", (118, 151), F... |
from core import sitemaps
from core.views import PrivacyView, SettingsView, TermsView
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.sitemaps.views import sitemap
from django.urls import include, path
from django.utils.translation import ... | [
"django.conf.urls.static.static",
"django.urls.path",
"django.utils.translation.gettext_lazy",
"django.urls.include"
] | [((446, 716), 'django.urls.path', 'path', (['"""sitemap.xml"""', 'sitemap', "{'sitemaps': {'base': sitemaps.BaseSitemap, 'country': sitemaps.\n LeaderboardCountrySitemap, 'trainers': sitemaps.TrainerSitemap,\n 'communities': sitemaps.LeaderboardCommunitySitemap}}"], {'name': '"""django.contrib.sitemaps.views.site... |