code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import copy
import datetime
import re
from .base import BaseModel
import sys
if sys.version_info < (3, 9):
import typing
_re_date_format = re.compile(r'^\d\d\d\d-\d\d-\d\d$')
_re_datetime_format = re.compile(
r'^(\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d)\+(\d\d):(\d\d)$')
def _datetime_value(values: dict, key: st... | [
"datetime.datetime.fromtimestamp",
"datetime.datetime.strptime",
"copy.deepcopy",
"re.compile"
] | [((146, 188), 're.compile', 're.compile', (['"""^\\\\d\\\\d\\\\d\\\\d-\\\\d\\\\d-\\\\d\\\\d$"""'], {}), "('^\\\\d\\\\d\\\\d\\\\d-\\\\d\\\\d-\\\\d\\\\d$')\n", (156, 188), False, 'import re\n'), ((204, 294), 're.compile', 're.compile', (['"""^(\\\\d\\\\d\\\\d\\\\d-\\\\d\\\\d-\\\\d\\\\dT\\\\d\\\\d:\\\\d\\\\d:\\\\d\\\\d)\\... |
"""13Migration
Revision ID: 2425b<PASSWORD>c
Revises: <PASSWORD>
Create Date: 2018-09-08 18:25:12.151586
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '2<PASSWORD>'
down_revision = '<PASSWORD>'
branch_labels = None
depends_on = None
def upgrade():
# ###... | [
"sqlalchemy.String",
"alembic.op.drop_column"
] | [((588, 622), 'alembic.op.drop_column', 'op.drop_column', (['"""pitches"""', '"""title"""'], {}), "('pitches', 'title')\n", (602, 622), False, 'from alembic import op\n'), ((425, 446), 'sqlalchemy.String', 'sa.String', ([], {'length': '(255)'}), '(length=255)\n', (434, 446), True, 'import sqlalchemy as sa\n')] |
import numpy as np
import cv2
import pdb
# https://github.com/zju3dv/clean-pvnet/blob/master/lib/datasets/augmentation.py
def debug_visualize(image, mask, pts2d, sym_cor, name_prefix='debug'):
from random import sample
cv2.imwrite('{}_image.png'.format(name_prefix), image * 255)
cv2.imwrite('{}_mask.png'.... | [
"numpy.ones",
"cv2.warpAffine",
"numpy.random.randint",
"numpy.mean",
"numpy.round",
"cv2.line",
"numpy.zeros_like",
"numpy.max",
"cv2.resize",
"numpy.stack",
"cv2.circle",
"numpy.asarray",
"numpy.min",
"numpy.concatenate",
"numpy.random.uniform",
"numpy.float32",
"numpy.zeros",
"n... | [((675, 691), 'numpy.nonzero', 'np.nonzero', (['mask'], {}), '(mask)\n', (685, 691), True, 'import numpy as np\n'), ((1159, 1175), 'numpy.nonzero', 'np.nonzero', (['mask'], {}), '(mask)\n', (1169, 1175), True, 'import numpy as np\n'), ((1241, 1268), 'numpy.float32', 'np.float32', (['sym_cor[ys, xs]'], {}), '(sym_cor[ys... |
import os
from conans import ConanFile, CMake, tools
required_conan_version = ">=1.33.0"
class NsimdConan(ConanFile):
name = "nsimd"
homepage = "https://github.com/agenium-scale/nsimd"
description = "Agenium Scale vectorization library for CPUs and GPUs"
topics = ("hpc", "neon", "cuda", "avx", "simd"... | [
"conans.tools.get",
"conans.tools.replace_in_file",
"conans.CMake",
"os.path.join",
"conans.tools.collect_libs"
] | [((1613, 1723), 'conans.tools.get', 'tools.get', ([], {'strip_root': '(True)', 'destination': 'self._source_subfolder'}), "(**self.conan_data['sources'][self.version], strip_root=True,\n destination=self._source_subfolder)\n", (1622, 1723), False, 'from conans import ConanFile, CMake, tools\n'), ((1830, 1841), 'cona... |
import pytest
@pytest.mark.asyncio
@pytest.mark.ttftt_engine
@pytest.mark.parametrize(
"query,errors",
[
(
"""
subscription Sub {
newDog {
name
}
newHuman {
name
}
}
... | [
"pytest.mark.parametrize"
] | [((64, 3172), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""query,errors"""', '[(\n """\n subscription Sub {\n newDog {\n name\n }\n newHuman {\n name\n }\n }\n """\n , [{\'message\': \... |
import argparse
from builtins import input
import datetime
import logging
import pprint
import sys
import ee
import openet.ssebop as ssebop
import utils
# from . import utils
def main(ini_path=None, overwrite_flag=False, delay_time=0, gee_key_file=None,
max_ready=-1):
"""Compute default Tcorr image ass... | [
"argparse.ArgumentParser",
"utils.read_ini",
"utils.delay_task",
"ee.ServiceAccountCredentials",
"logging.error",
"ee.data.cancelTask",
"logging.warning",
"ee.Initialize",
"utils.get_ee_tasks",
"datetime.datetime.today",
"sys.exit",
"logging.debug",
"ee.data.getInfo",
"logging.basicConfig"... | [((992, 1046), 'logging.info', 'logging.info', (['"""\nCompute default Tcorr image asset"""'], {}), '("""\nCompute default Tcorr image asset""")\n', (1004, 1046), False, 'import logging\n'), ((1055, 1079), 'utils.read_ini', 'utils.read_ini', (['ini_path'], {}), '(ini_path)\n', (1069, 1079), False, 'import utils\n'), ((... |
import numpy as np
import os
import gym
import torch
import torch.nn as nn
import collections
import copy
import random
# hype-params
learn_freq = 5 #经验池攒一些经验再开启训练
buffer_size = 20000 #经验池大小
buffer_init_size = 200 #开启训练最低经验条数
batch_size = 32 #每次sample的数量
learning_rate = 0.001 #学习率
GAMMA = 0.99 # reward折扣因子
class Mode... | [
"copy.deepcopy",
"torch.nn.MSELoss",
"gym.make",
"numpy.argmax",
"random.sample",
"torch.save",
"numpy.mean",
"numpy.random.randint",
"numpy.array",
"torch.nn.Linear",
"numpy.random.rand",
"torch.tensor",
"numpy.squeeze",
"collections.deque",
"torch.from_numpy"
] | [((5045, 5065), 'numpy.mean', 'np.mean', (['eval_reward'], {}), '(eval_reward)\n', (5052, 5065), True, 'import numpy as np\n'), ((5104, 5127), 'gym.make', 'gym.make', (['"""CartPole-v0"""'], {}), "('CartPole-v0')\n", (5112, 5127), False, 'import gym\n'), ((6878, 6925), 'torch.save', 'torch.save', (['agent.dqn.target_mo... |
from intake.source.base import DataSource
from intake.source import import_name
class StreamzSource(DataSource):
name = 'streamz'
container = 'streamz'
"""
"""
def __init__(self, method_chain, start=False, metadata=None, **kwargs):
"""
method_chain: list[tuple(str, dict)]
... | [
"intake.source.import_name"
] | [((922, 949), 'intake.source.import_name', 'import_name', (['kw[functional]'], {}), '(kw[functional])\n', (933, 949), False, 'from intake.source import import_name\n')] |
from collections import namedtuple
AcquireCredResult = namedtuple('AcquireCredResult',
['creds', 'mechs', 'lifetime'])
InquireCredResult = namedtuple('InquireCredResult',
['name', 'lifetime', 'usage',
'mechs'])
InquireCr... | [
"collections.namedtuple"
] | [((57, 120), 'collections.namedtuple', 'namedtuple', (['"""AcquireCredResult"""', "['creds', 'mechs', 'lifetime']"], {}), "('AcquireCredResult', ['creds', 'mechs', 'lifetime'])\n", (67, 120), False, 'from collections import namedtuple\n'), ((174, 245), 'collections.namedtuple', 'namedtuple', (['"""InquireCredResult"""'... |
from tkinter import Tk
from tkinter.filedialog import askopenfilename
from gtts import gTTS
import PyPDF2
import os
Tk().withdraw()
filelocation = askopenfilename()
basename = os.path.basename(filelocation)
filename = os.path.splitext(basename)[0]
with open(filelocation, 'rb') as f:
text = P... | [
"os.path.basename",
"gtts.gTTS",
"tkinter.filedialog.askopenfilename",
"PyPDF2.PdfFileReader",
"os.path.splitext",
"tkinter.Tk"
] | [((159, 176), 'tkinter.filedialog.askopenfilename', 'askopenfilename', ([], {}), '()\n', (174, 176), False, 'from tkinter.filedialog import askopenfilename\n'), ((191, 221), 'os.path.basename', 'os.path.basename', (['filelocation'], {}), '(filelocation)\n', (207, 221), False, 'import os\n'), ((236, 262), 'os.path.split... |
# https://www.hackerrank.com/challenges/text-wrap/problem
import textwrap
def wrap(string, max_width):
# return "\n".join(string[i:i+max_width] for i in range(0, len(string), max_width))
return textwrap.fill(string, max_width)
if __name__ == "__main__":
string, max_width = input(), int(input())
# ... | [
"textwrap.fill"
] | [((206, 238), 'textwrap.fill', 'textwrap.fill', (['string', 'max_width'], {}), '(string, max_width)\n', (219, 238), False, 'import textwrap\n')] |
import tensorflow as tf
from .utils import noisy_labels, smooth_fake_labels, smooth_real_labels, CONFIG
class SGANDiscriminatorLoss(tf.keras.losses.Loss):
def __init__(self):
"""Standard GAN loss for discriminator.
"""
super().__init__()
self.bce = tf.keras.losses.BinaryCrossentr... | [
"tensorflow.keras.losses.BinaryCrossentropy",
"tensorflow.reduce_mean",
"tensorflow.zeros_like",
"tensorflow.ones_like"
] | [((289, 341), 'tensorflow.keras.losses.BinaryCrossentropy', 'tf.keras.losses.BinaryCrossentropy', ([], {'from_logits': '(True)'}), '(from_logits=True)\n', (323, 341), True, 'import tensorflow as tf\n'), ((871, 896), 'tensorflow.ones_like', 'tf.ones_like', (['real_output'], {}), '(real_output)\n', (883, 896), True, 'imp... |
import sys
import subprocess
import os
runSnifflesScript = "./call_sniffles.sh"
resultDir = "/CGF/Bioinformatics/Production/Wen/20200117_pacbio_snp_call/29461_WGS_cell_line/bam_location_ngmlr/SV/Sniffles"
class ClsSample:
def __init__(self):
self.strName = ""
self.strPath = ""
self.strBAM ... | [
"os.path.basename",
"os.path.dirname",
"os.path.exists",
"os.system",
"subprocess.getoutput"
] | [((459, 490), 'os.path.dirname', 'os.path.dirname', (['strFullPathBAM'], {}), '(strFullPathBAM)\n', (474, 490), False, 'import os\n'), ((1754, 1782), 'os.path.exists', 'os.path.exists', (['strLogStdOut'], {}), '(strLogStdOut)\n', (1768, 1782), False, 'import os\n'), ((1861, 1889), 'os.path.exists', 'os.path.exists', ([... |
##
# @file electric_overflow.py
# @author <NAME>
# @date Aug 2018
#
import math
import numpy as np
import torch
from torch import nn
from torch.autograd import Function
from torch.nn import functional as F
import dreamplace.ops.electric_potential.electric_potential_cpp as electric_potential_cpp
import dreamplace.... | [
"torch.ones",
"numpy.meshgrid",
"math.sqrt",
"math.ceil",
"numpy.argmax",
"matplotlib.pyplot.close",
"numpy.amax",
"matplotlib.pyplot.figure",
"matplotlib.use",
"numpy.arange",
"numpy.mean",
"torch.zeros",
"matplotlib.pyplot.savefig"
] | [((530, 551), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (544, 551), False, 'import matplotlib\n'), ((12631, 12643), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (12641, 12643), True, 'import matplotlib.pyplot as plt\n'), ((12687, 12718), 'numpy.arange', 'np.arange', (['density... |
from django.conf.urls import include, url, patterns
from polls import views
urlpatterns = [
url(r'^home/$', views.home, name='home'),
url(r'^about/$', views.about, name='about'),
]
| [
"django.conf.urls.url"
] | [((97, 136), 'django.conf.urls.url', 'url', (['"""^home/$"""', 'views.home'], {'name': '"""home"""'}), "('^home/$', views.home, name='home')\n", (100, 136), False, 'from django.conf.urls import include, url, patterns\n'), ((143, 185), 'django.conf.urls.url', 'url', (['"""^about/$"""', 'views.about'], {'name': '"""about... |
# app/robo_advisor.py
import csv
import os
import json
from dotenv import load_dotenv
import requests
from datetime import datetime
now = datetime.now()
datelabel = now.strftime("%d/%m/%Y %H:%M:%S")
load_dotenv()
# utility function to convert float or integer to usd-formatted string (for printing
# ... adapted fr... | [
"json.loads",
"os.path.dirname",
"dotenv.load_dotenv",
"os.environ.get",
"requests.get",
"datetime.datetime.now",
"csv.DictWriter"
] | [((141, 155), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (153, 155), False, 'from datetime import datetime\n'), ((204, 217), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (215, 217), False, 'from dotenv import load_dotenv\n'), ((476, 514), 'os.environ.get', 'os.environ.get', (['"""ALPHAVANTAGE_... |
#!/usr/bin/env python
"""
Wrapper to ROS publisher.
Author: <NAME>
Date: 05/18
"""
import rospy
class ROSPublisher(object):
def __init__(self, _topic, _message_type, _queue_size=1, rate=10):
"""
ROSPublisher constructor.
:param _topic: string, ROS topic to publish on
:param _me... | [
"rospy.loginfo",
"rospy.Publisher",
"rospy.Rate"
] | [((657, 727), 'rospy.Publisher', 'rospy.Publisher', (['self.topic', 'self.message_type'], {'queue_size': '_queue_size'}), '(self.topic, self.message_type, queue_size=_queue_size)\n', (672, 727), False, 'import rospy\n'), ((748, 764), 'rospy.Rate', 'rospy.Rate', (['rate'], {}), '(rate)\n', (758, 764), False, 'import ros... |
"""Helper functions and classes for temporary folders."""
import logging
import shutil
from pathlib import Path
from types import TracebackType
from typing import Optional, Type
from .location import Location
LOGGER = logging.getLogger(__name__)
class TmpDir(Location):
"""A temporary folder that can create fil... | [
"pathlib.Path",
"logging.getLogger"
] | [((221, 248), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (238, 248), False, 'import logging\n'), ((1503, 1513), 'pathlib.Path', 'Path', (['name'], {}), '(name)\n', (1507, 1513), False, 'from pathlib import Path\n'), ((1782, 1792), 'pathlib.Path', 'Path', (['name'], {}), '(name)\n', (1... |
import socket
from threading import Thread, Lock
from time import time
from .BenchmarkData import BenchmarkData
class UDPServer:
def __init__(self, host, port, benchmark_file_path, chunk_size, ack):
self.__host = host
self.__port = port
self.__running = False
self.__running_lock ... | [
"threading.Lock",
"threading.Thread",
"socket.socket",
"time.time"
] | [((322, 328), 'threading.Lock', 'Lock', ([], {}), '()\n', (326, 328), False, 'from threading import Thread, Lock\n'), ((483, 531), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_DGRAM'], {}), '(socket.AF_INET, socket.SOCK_DGRAM)\n', (496, 531), False, 'import socket\n'), ((2304, 2310), 'time.time', ... |
from typing import Tuple
from functools import lru_cache
from ..core.base import FeatureExtractorSingleBand
import pandas as pd
import logging
class SupernovaeDetectionFeatureExtractor(FeatureExtractorSingleBand):
@lru_cache(1)
def get_features_keys_without_band(self) -> Tuple[str, ...]:
return ('del... | [
"functools.lru_cache",
"pandas.Series"
] | [((222, 234), 'functools.lru_cache', 'lru_cache', (['(1)'], {}), '(1)\n', (231, 234), False, 'from functools import lru_cache\n'), ((568, 580), 'functools.lru_cache', 'lru_cache', (['(1)'], {}), '(1)\n', (577, 580), False, 'from functools import lru_cache\n'), ((2699, 2734), 'pandas.Series', 'pd.Series', ([], {'data': ... |
#-*- coding: utf-8 -*-
import os
from gluoncv.model_zoo import ssd_512_mobilenet1_0_voc
import sys
sys.path.append("..")
from convert import convert_ssd_model, save_model
if __name__ == "__main__":
if not os.path.exists("tmp"):
os.mkdir("tmp")
net = ssd_512_mobilenet1_0_voc(pretrained=True)
tex... | [
"sys.path.append",
"os.mkdir",
"os.path.exists",
"convert.save_model",
"gluoncv.model_zoo.ssd_512_mobilenet1_0_voc",
"convert.convert_ssd_model"
] | [((101, 122), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (116, 122), False, 'import sys\n'), ((271, 312), 'gluoncv.model_zoo.ssd_512_mobilenet1_0_voc', 'ssd_512_mobilenet1_0_voc', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (295, 312), False, 'from gluoncv.model_zoo import ssd_512_... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import pytest
@pytest.mark.parametrize("value, format_, expectation", [
("01-Jan-15 10:00:00 +07:00", "DD-MMM-YY HH:mm:ss Z", "2015-01-01T03:00:00+00:00"), # noqa
... | [
"pytest.mark.parametrize",
"mishapp_ds.scrape.loaders.datetime_to_utc"
] | [((167, 406), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""value, format_, expectation"""', "[('01-Jan-15 10:00:00 +07:00', 'DD-MMM-YY HH:mm:ss Z',\n '2015-01-01T03:00:00+00:00'), ('01-01-2015 10:00:00 +07:00',\n 'DD-MM-YYYY HH:mm:ss Z', '2015-01-01T03:00:00+00:00')]"], {}), "('value, format_, expe... |
# -*- coding: utf-8 -*-
# Copyright 2014 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | [
"io.StringIO",
"os_net_config.utils.get_file_data",
"sys.stderr.getvalue",
"random.random",
"sys.stdout.flush",
"yaml.safe_load",
"sys.stdout.getvalue",
"sys.stderr.flush",
"re.compile"
] | [((1355, 1365), 'io.StringIO', 'StringIO', ([], {}), '()\n', (1363, 1365), False, 'from io import StringIO\n'), ((1387, 1397), 'io.StringIO', 'StringIO', ([], {}), '()\n', (1395, 1397), False, 'from io import StringIO\n'), ((2078, 2096), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (2094, 2096), False, 'im... |
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('protectedErr/', views.protected_error, name='protected_error'),
path('accounts/', include('django.contrib.auth.urls')),
path('auth/', include('social_django.urls', namespace='social')),... | [
"django.urls.path",
"django.urls.include"
] | [((80, 115), 'django.urls.path', 'path', (['""""""', 'views.index'], {'name': '"""index"""'}), "('', views.index, name='index')\n", (84, 115), False, 'from django.urls import path, include\n'), ((121, 189), 'django.urls.path', 'path', (['"""protectedErr/"""', 'views.protected_error'], {'name': '"""protected_error"""'})... |
import os
from logging import getLogger
from src.constants import CONSTANTS, PLATFORM_ENUM
logger = getLogger(__name__)
class PlatformConfigurations:
platform = os.getenv("PLATFORM", PLATFORM_ENUM.DOCKER.value)
if not PLATFORM_ENUM.has_value(platform):
raise ValueError(f"PLATFORM must be one of {[v.... | [
"src.constants.PLATFORM_ENUM.has_value",
"src.constants.PLATFORM_ENUM.__members__.values",
"os.getenv",
"logging.getLogger"
] | [((102, 121), 'logging.getLogger', 'getLogger', (['__name__'], {}), '(__name__)\n', (111, 121), False, 'from logging import getLogger\n'), ((169, 218), 'os.getenv', 'os.getenv', (['"""PLATFORM"""', 'PLATFORM_ENUM.DOCKER.value'], {}), "('PLATFORM', PLATFORM_ENUM.DOCKER.value)\n", (178, 218), False, 'import os\n'), ((421... |
# Generated by Django 2.2.7 on 2020-07-15 07:26
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('newsletter', '0002_auto_20200514_1518'),
]
operations = [
migrations.RemoveField(
model_name='subscriber',
name='last_sent',... | [
"django.db.migrations.RemoveField"
] | [((230, 295), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""subscriber"""', 'name': '"""last_sent"""'}), "(model_name='subscriber', name='last_sent')\n", (252, 295), False, 'from django.db import migrations\n')] |
import numpy as np
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import LeaveOneOut
import pandas as pd
import os
import sys
from feature_selection import read_data
def leaveOneOut(df):
# target and data selection
y=df.iloc[:,-1]
X=df.iloc[:,:-1]
y=y.to_numpy()
loo = LeaveOne... | [
"feature_selection.read_data",
"sklearn.model_selection.StratifiedKFold",
"os.mkdir",
"sklearn.model_selection.LeaveOneOut"
] | [((312, 325), 'sklearn.model_selection.LeaveOneOut', 'LeaveOneOut', ([], {}), '()\n', (323, 325), False, 'from sklearn.model_selection import LeaveOneOut\n'), ((762, 780), 'sklearn.model_selection.StratifiedKFold', 'StratifiedKFold', (['k'], {}), '(k)\n', (777, 780), False, 'from sklearn.model_selection import Stratifi... |
"""
Dependencies:
tensorflow: 1.2.0
matplotlib
numpy
"""
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
tf.set_random_seed(1)
np.random.seed(1)
#fake data
n_data = np.ones((100,2))
x0 = np.random.normal(2*n_data, 1) #class0 x shape = (100, 2))
y0 = np.zeros(100) ... | [
"numpy.random.seed",
"numpy.ones",
"tensorflow.local_variables_initializer",
"numpy.random.normal",
"tensorflow.set_random_seed",
"tensorflow.placeholder",
"matplotlib.pyplot.cla",
"tensorflow.squeeze",
"matplotlib.pyplot.pause",
"matplotlib.pyplot.show",
"tensorflow.global_variables_initializer... | [((134, 155), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(1)'], {}), '(1)\n', (152, 155), True, 'import tensorflow as tf\n'), ((156, 173), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (170, 173), True, 'import numpy as np\n'), ((195, 212), 'numpy.ones', 'np.ones', (['(100, 2)'], {}), '((10... |
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.common.exceptions import NoSuchElementException, TimeoutException, ElementNotVisibleException, \
ElementNotInter... | [
"selenium.webdriver.support.expected_conditions.presence_of_element_located",
"time.sleep",
"os.environ.get",
"selenium.webdriver.Chrome",
"selenium.webdriver.support.ui.WebDriverWait",
"sys.exit"
] | [((1926, 1998), 'selenium.webdriver.Chrome', 'webdriver.Chrome', (['"""bins/chromedriver"""'], {'desired_capabilities': 'capabilities'}), "('bins/chromedriver', desired_capabilities=capabilities)\n", (1942, 1998), False, 'from selenium import webdriver\n'), ((2258, 2271), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)... |
"""
Functions to be used as JobControl jobs
"""
from datetime import datetime
import logging
import os
from jobcontrol.globals import execution_context
from harvester.utils import (get_storage_direct,
jobcontrol_integration, report_progress)
logger = logging.getLogger('harvester_odt.pat... | [
"os.getpid",
"harvester_odt.pat_geocatalogo.crawler.Geocatalogo",
"harvester.utils.jobcontrol_integration",
"harvester_odt.pat_statistica.converter.convert_statistica_to_ckan",
"harvester_odt.pat_statistica.converter.convert_statistica_subpro_to_ckan",
"harvester_odt.pat_geocatalogo.converter.GeoCatalogoT... | [((284, 333), 'logging.getLogger', 'logging.getLogger', (['"""harvester_odt.pat_statistica"""'], {}), "('harvester_odt.pat_statistica')\n", (301, 333), False, 'import logging\n'), ((1854, 1896), 'harvester_odt.pat_geocatalogo.crawler.Geocatalogo', 'Geocatalogo', (['""""""', "{'with_resources': False}"], {}), "('', {'wi... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 7 10:51:21 2018
@author: hertta
"""
from shapely.ops import cascaded_union
from copy import deepcopy
import random
from shapely.geometry import LineString
class SchoolDistr:
""" The class representing the school districts """
def _... | [
"copy.deepcopy",
"shapely.ops.cascaded_union"
] | [((2389, 2414), 'shapely.ops.cascaded_union', 'cascaded_union', (['geom_list'], {}), '(geom_list)\n', (2403, 2414), False, 'from shapely.ops import cascaded_union\n'), ((4826, 4847), 'copy.deepcopy', 'deepcopy', (['self.blocks'], {}), '(self.blocks)\n', (4834, 4847), False, 'from copy import deepcopy\n'), ((4986, 5011)... |
#!/usr/bin/env python
import time
from optparse import OptionParser
from .component_manager import ComponentManager
if __name__ == '__main__':
parser = OptionParser()
parser.add_option('-p', '--profile', dest='profile', default=None)
# parser.add_option('-f', '--file', dest='file', default=None)
parser... | [
"socket.gethostname",
"optparse.OptionParser",
"time.sleep"
] | [((157, 171), 'optparse.OptionParser', 'OptionParser', ([], {}), '()\n', (169, 171), False, 'from optparse import OptionParser\n'), ((1179, 1194), 'time.sleep', 'time.sleep', (['(1.0)'], {}), '(1.0)\n', (1189, 1194), False, 'import time\n'), ((614, 634), 'socket.gethostname', 'socket.gethostname', ([], {}), '()\n', (63... |
# (c) 2012-2019, Ansible by Red Hat
#
# This file is part of Ansible Galaxy
#
# Ansible Galaxy is free software: you can redistribute it and/or modify
# it under the terms of the Apache License as published by
# the Apache Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
... | [
"galaxy.main.models.Namespace.objects.get",
"pulpcore.app.models.Repository.objects.get",
"pulpcore.app.response.OperationPostponedResponse",
"pulpcore.app.serializers.ArtifactSerializer",
"rest_framework.exceptions.PermissionDenied",
"pulpcore.tasking.tasks.enqueue_with_reservation",
"galaxy.api.v2.ser... | [((1682, 1774), 'galaxy.api.v2.serializers.collection.UploadCollectionSerializer', 'serializers.UploadCollectionSerializer', ([], {'data': 'request.data', 'context': "{'request': request}"}), "(data=request.data, context={\n 'request': request})\n", (1720, 1774), True, 'from galaxy.api.v2.serializers import collecti... |
from flexx import flx
from flexx import event
import os
from tornado.web import StaticFileHandler
class ScaleImageWidget(flx.Widget):
""" Display an image from a url.
The ``node`` of this widget is an
`<img> <https://developer.mozilla.org/docs/Web/HTML/Element/img>`_
wrapped in a `<div> <https://... | [
"flexx.flx.Label",
"flexx.flx.TabLayout",
"flexx.flx.App",
"flexx.event.StringProp",
"flexx.event.BoolProp",
"flexx.flx.run",
"flexx.flx.create_server",
"flexx.flx.VFix",
"os.path.expanduser",
"flexx.flx.HFix"
] | [((5691, 5758), 'os.path.expanduser', 'os.path.expanduser', (['"""~/Documents/knoplab/yeastimages_presentation/"""'], {}), "('~/Documents/knoplab/yeastimages_presentation/')\n", (5709, 5758), False, 'import os\n'), ((5863, 5879), 'flexx.flx.App', 'flx.App', (['FewShot'], {}), '(FewShot)\n', (5870, 5879), False, 'from f... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2021 Tianmian Tech. 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/LI... | [
"functools.partial",
"kernel.utils.abnormal_detection.empty_table_detection",
"kernel.transfer.variables.transfer_class.vert_feature_calculation_transfer_variable.VertFeatureCalculationTransferVariable",
"json.loads",
"kernel.protobuf.generated.feature_calculation_param_pb2.FeatureCalculationValueResultPara... | [((2385, 2407), 'common.python.utils.log_utils.get_logger', 'log_utils.get_logger', ([], {}), '()\n', (2405, 2407), False, 'from common.python.utils import log_utils\n'), ((2698, 2738), 'kernel.transfer.variables.transfer_class.vert_feature_calculation_transfer_variable.VertFeatureCalculationTransferVariable', 'VertFea... |
# Generated by Django 3.1 on 2020-08-07 04:53
from django.db import migrations, models
def set_images_names(apps, schema_editor):
UploadImage = apps.get_model('resizer', 'UploadImage')
for image in UploadImage.objects.all():
image_name = image.original_image.name.split('/')[-1]
image.image_na... | [
"django.db.migrations.RunPython",
"django.db.models.CharField"
] | [((675, 713), 'django.db.migrations.RunPython', 'migrations.RunPython', (['set_images_names'], {}), '(set_images_names)\n', (695, 713), False, 'from django.db import migrations, models\n'), ((610, 654), 'django.db.models.CharField', 'models.CharField', ([], {'default': '""""""', 'max_length': '(128)'}), "(default='', m... |
"""Created comments
Revision ID: fa4f694e986a
Revises: <KEY>
Create Date: 2021-08-16 21:48:43.079233
"""
# revision identifiers, used by Alembic.
revision = 'fa4f694e986a'
down_revision = '<KEY>'
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic - please ad... | [
"alembic.op.drop_column",
"sqlalchemy.DateTime"
] | [((532, 565), 'alembic.op.drop_column', 'op.drop_column', (['"""pitches"""', '"""time"""'], {}), "('pitches', 'time')\n", (546, 565), False, 'from alembic import op\n'), ((377, 390), 'sqlalchemy.DateTime', 'sa.DateTime', ([], {}), '()\n', (388, 390), True, 'import sqlalchemy as sa\n')] |
from unittest import TestCase
from flow_py_sdk import AccountKey, SignAlgo, HashAlgo
from flow_py_sdk.proto.flow.entities import AccountKey as ProtoAccountKey
class TestAccountKey(TestCase):
def test_rlp(self):
expected_rlp_hex = "f847b840c51c02aa382d8d382a121178de8ac97eb6a562a1008660669ab6a220c96fce76e1... | [
"flow_py_sdk.AccountKey.from_proto",
"flow_py_sdk.proto.flow.entities.AccountKey"
] | [((1317, 1334), 'flow_py_sdk.proto.flow.entities.AccountKey', 'ProtoAccountKey', ([], {}), '()\n', (1332, 1334), True, 'from flow_py_sdk.proto.flow.entities import AccountKey as ProtoAccountKey\n'), ((1424, 1464), 'flow_py_sdk.AccountKey.from_proto', 'AccountKey.from_proto', (['proto_account_key'], {}), '(proto_account... |
# -*- coding: UTF-8 -*-
"""PyRamen Homework Starter."""
# @TODO: Import libraries
import csv
from pathlib import Path
# @TODO: Set file paths for menu_data.csv and sales_data.csv
menu_filepath = Path('')
sales_filepath = Path('')
# @TODO: Initialize list objects to hold our menu and sales data
menu = []
sales = []
... | [
"pathlib.Path"
] | [((197, 205), 'pathlib.Path', 'Path', (['""""""'], {}), "('')\n", (201, 205), False, 'from pathlib import Path\n'), ((223, 231), 'pathlib.Path', 'Path', (['""""""'], {}), "('')\n", (227, 231), False, 'from pathlib import Path\n')] |
'''
Collection of shared tools for appengine page rendering.
'''
# My modules
from macro.render.defs import *
from macro.render.util import render_template
from macro.data.appengine.savedmacro import SavedMacroOps
# Generate a search results page.
def generate_search_page(path, terms, p... | [
"macro.render.util.render_template",
"macro.data.appengine.savedmacro.SavedMacroOps.search"
] | [((784, 848), 'macro.data.appengine.savedmacro.SavedMacroOps.search', 'SavedMacroOps.search', (['terms'], {'page': 'page', 'num': 'page_size', 'sort': 'sort'}), '(terms, page=page, num=page_size, sort=sort)\n', (804, 848), False, 'from macro.data.appengine.savedmacro import SavedMacroOps\n'), ((1523, 1848), 'macro.rend... |
import numpy as N
import win32com.client
# generate and import apogee ActiveX module
apogee_module = win32com.client.gencache.EnsureModule(
'{A2882C73-7CFB-11D4-9155-0060676644C1}', 0, 1, 0)
if apogee_module is None:
raise ImportError # prevent plugin from being imported
from win32com.client import constants ... | [
"traits.api.Float",
"Camera.CameraError",
"numpy.copy",
"traits.api.Int",
"numpy.zeros",
"traits.api.Bool",
"traits.api.Str",
"traitsui.api.Item",
"traits.api.Enum"
] | [((715, 721), 'traits.api.Int', 'Int', (['(0)'], {}), '(0)\n', (718, 721), False, 'from traits.api import Str, Int, Enum, Float, Bool\n'), ((741, 746), 'traits.api.Str', 'Str', ([], {}), '()\n', (744, 746), False, 'from traits.api import Str, Int, Enum, Float, Bool\n'), ((768, 773), 'traits.api.Str', 'Str', ([], {}), '... |
# -*- coding: utf-8 -*-
from app.airport.airports_parsers import get_country, get_money, get_kerosene_supply, get_kerosene_capacity, \
get_engines_supply, get_planes_capacity, get_airport_name
from app.common.http_methods_unittests import get_request
from app.common.target_urls import MY_AIRPORT
import unittest
... | [
"unittest.main",
"app.airport.airports_parsers.get_country",
"app.airport.airports_parsers.get_kerosene_supply",
"app.airport.airports_parsers.get_planes_capacity",
"app.airport.airports_parsers.get_kerosene_capacity",
"app.airport.airports_parsers.get_engines_supply",
"app.airport.airports_parsers.get_... | [((1473, 1488), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1486, 1488), False, 'import unittest\n'), ((433, 456), 'app.common.http_methods_unittests.get_request', 'get_request', (['MY_AIRPORT'], {}), '(MY_AIRPORT)\n', (444, 456), False, 'from app.common.http_methods_unittests import get_request\n'), ((504, 53... |
import json
class Gabi:
def myFunc(self, game, hand, cards):
print("GABI")
try:
if (hand[0]["rank"] == hand[1]["rank"]):
print("pair, returning 800")
return 800
elif (hand[0]["rank"] in "89TJQKA" and hand[1]["rank"] in "89TJQKA"):
... | [
"json.loads"
] | [((2138, 2159), 'json.loads', 'json.loads', (['json_data'], {}), '(json_data)\n', (2148, 2159), False, 'import json\n')] |
"""Build and install the windspharm package."""
# Copyright (c) 2012-2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights... | [
"versioneer.get_version",
"versioneer.get_cmdclass"
] | [((1579, 1603), 'versioneer.get_version', 'versioneer.get_version', ([], {}), '()\n', (1601, 1603), False, 'import versioneer\n'), ((1620, 1645), 'versioneer.get_cmdclass', 'versioneer.get_cmdclass', ([], {}), '()\n', (1643, 1645), False, 'import versioneer\n')] |
"""tests for vak.cli.predict module"""
import pytest
import vak.cli.predict
import vak.config
import vak.constants
import vak.paths
from . import cli_asserts
from ..test_core.test_predict import predict_output_matches_expected
@pytest.mark.parametrize(
"audio_format, spect_format, annot_format",
[
(... | [
"pytest.mark.parametrize"
] | [((232, 379), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""audio_format, spect_format, annot_format"""', "[('cbin', None, 'notmat'), ('wav', None, 'birdsong-recognition-dataset')]"], {}), "('audio_format, spect_format, annot_format', [(\n 'cbin', None, 'notmat'), ('wav', None, 'birdsong-recognition-da... |
import json
import logging
import config as cfg
from modules.zabbix_sender import send_to_zabbix
logger = logging.getLogger(__name__)
"""zabbixにDevice LLDデータを送信します。
result = {"/dev/sda": {"model": EXAMPLE SSD 250, "POWER_CYCLE": 123 ...}}
@param result 送信するデータ
@param discoveryKey zabbix discovery key. ex) megacli.... | [
"modules.zabbix_sender.send_to_zabbix",
"logging.getLogger",
"json.dumps"
] | [((108, 135), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (125, 135), False, 'import logging\n'), ((682, 720), 'json.dumps', 'json.dumps', (["{'data': discovery_result}"], {}), "({'data': discovery_result})\n", (692, 720), False, 'import json\n'), ((849, 869), 'modules.zabbix_sender.se... |
# coding=utf-8
"""
Provides a common interface for executing commands.
"""
import sys
import subprocess
import doctor.report as report
from doctor.report import supports_color
def get_argv(cmd: str) -> list:
""" Return a list of arguments from a fully-formed command line. """
return cmd.strip().split(' '... | [
"subprocess.run",
"doctor.report.supports_color",
"doctor.report.information"
] | [((564, 609), 'doctor.report.information', 'report.information', (['diagnostic'], {'wrapped': '(False)'}), '(diagnostic, wrapped=False)\n', (582, 609), True, 'import doctor.report as report\n'), ((1237, 1378), 'subprocess.run', 'subprocess.run', (['argv'], {'stdout': '(sys.stdout if show_output else subprocess.DEVNULL)... |
"""
Drive stepper motor 28BYJ-48 using ULN2003
"""
from machine import Pin
from time import sleep_ms
# define pins for ULN2003
IN1 = Pin(16, Pin.OUT)
IN2 = Pin(17, Pin.OUT)
IN3 = Pin(5, Pin.OUT)
IN4 = Pin(18, Pin.OUT)
# half-step mode
# counter clockwise step sequence
seq_ccw = [[1, 0, 0, 0],
[1, 1, 0, 0... | [
"time.sleep_ms",
"machine.Pin"
] | [((135, 151), 'machine.Pin', 'Pin', (['(16)', 'Pin.OUT'], {}), '(16, Pin.OUT)\n', (138, 151), False, 'from machine import Pin\n'), ((158, 174), 'machine.Pin', 'Pin', (['(17)', 'Pin.OUT'], {}), '(17, Pin.OUT)\n', (161, 174), False, 'from machine import Pin\n'), ((181, 196), 'machine.Pin', 'Pin', (['(5)', 'Pin.OUT'], {})... |
import vectorincrement
import os
import gin
import sparse_causal_model_learner_rl.learners.rl_learner as learner
import sparse_causal_model_learner_rl.learners.abstract_learner as abstract_learner
import sparse_causal_model_learner_rl.config as config
import pytest
from sparse_causal_model_learner_rl.sacred_gin_... | [
"os.path.dirname",
"pytest.fixture",
"gin.clear_config",
"sparse_causal_model_learner_rl.sacred_gin_tune.sacred_wrapper.load_config_files",
"sparse_causal_model_learner_rl.config.Config"
] | [((1376, 1404), 'pytest.fixture', 'pytest.fixture', ([], {'autouse': '(True)'}), '(autouse=True)\n', (1390, 1404), False, 'import pytest\n'), ((662, 718), 'sparse_causal_model_learner_rl.sacred_gin_tune.sacred_wrapper.load_config_files', 'load_config_files', (['[ve_config_path, learner_config_path]'], {}), '([ve_config... |
# !/usr/bin/env python
# -- coding: utf-8 --
# @Author zengxiaohui
# Datatime:4/29/2021 8:38 PM
# @File:obj_utils
from python_developer_tools.python.string_utils import str_is_null
def obj_is_null(obj):
"""判断对象是否为空"""
if obj is None:
return True
if isinstance(obj, list) and len(obj) == 0:
... | [
"python_developer_tools.python.string_utils.str_is_null"
] | [((376, 392), 'python_developer_tools.python.string_utils.str_is_null', 'str_is_null', (['obj'], {}), '(obj)\n', (387, 392), False, 'from python_developer_tools.python.string_utils import str_is_null\n')] |
"""
The pypositioning.system.load_files.py module contains functions allowing to load measurement results from various
types of files. The currently available functions allow to load **.psd** files collected with TI Packet Sniffer and
results obtained using IONIS localization system.
Copyright (C) 2020 <NAME>
"""
impo... | [
"pandas.DataFrame",
"pandas.cut",
"numpy.rint",
"numpy.array",
"numpy.linalg.norm",
"numpy.log10",
"pandas.concat",
"numpy.nanmean"
] | [((1886, 1903), 'numpy.array', 'np.array', (['ble_res'], {}), '(ble_res)\n', (1894, 1903), True, 'import numpy as np\n'), ((1918, 1935), 'numpy.array', 'np.array', (['uwb_res'], {}), '(uwb_res)\n', (1926, 1935), True, 'import numpy as np\n'), ((7188, 7201), 'numpy.array', 'np.array', (['tse'], {}), '(tse)\n', (7196, 72... |
import ChessFuntions
import pprint
game = ChessFuntions.Chessgame()
game.setup()
game.wereToMove(2, 1) | [
"ChessFuntions.Chessgame"
] | [((42, 67), 'ChessFuntions.Chessgame', 'ChessFuntions.Chessgame', ([], {}), '()\n', (65, 67), False, 'import ChessFuntions\n')] |
import logging
import inspect
import mechanize
log = logging.getLogger(__name__)
class Service(object):
"""
The superclass of all services.
When creating a service, inherit from this class
and implement the following methods as necessary:
__init__
authenticate
check_<attribute>... | [
"inspect.getargspec",
"mechanize.Browser",
"inspect.getdoc",
"logging.getLogger"
] | [((53, 80), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (70, 80), False, 'import logging\n'), ((669, 688), 'inspect.getdoc', 'inspect.getdoc', (['cls'], {}), '(cls)\n', (683, 688), False, 'import inspect\n'), ((1965, 2003), 'logging.getLogger', 'logging.getLogger', (["('service.%s' % n... |
# A collection of various tools to help estimate and analyze the tail exponent.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from FatTailedTools.plotting import plot_survival_function
from FatTailedTools.survival import get_survival_function
def fit_alpha_linear(series, tail_start_mad=2.5,... | [
"numpy.poly1d",
"seaborn.histplot",
"matplotlib.pyplot.show",
"numpy.polyfit",
"FatTailedTools.survival.get_survival_function",
"numpy.hstack",
"pandas.MultiIndex.from_product",
"FatTailedTools.plotting.plot_survival_function",
"numpy.random.normal",
"numpy.log10",
"matplotlib.pyplot.subplots"
] | [((1093, 1159), 'numpy.log10', 'np.log10', (["survival.loc[survival['Values'] >= tail_start].iloc[:-1]"], {}), "(survival.loc[survival['Values'] >= tail_start].iloc[:-1])\n", (1101, 1159), True, 'import numpy as np\n'), ((1199, 1257), 'numpy.polyfit', 'np.polyfit', (["survival_tail['Values']", "survival_tail['P']", '(1... |
import types
import warnings
from collections.abc import Iterable
from inspect import getfullargspec
import numpy as np
class _DatasetApply:
"""
Helper class to apply function to
`pysprint.core.bases.dataset.Dataset` objects.
"""
def __init__(
self,
obj,
func,
... | [
"numpy.vectorize",
"inspect.getfullargspec",
"numpy.concatenate",
"numpy.asarray",
"warnings.warn",
"numpy.unique"
] | [((1015, 1035), 'inspect.getfullargspec', 'getfullargspec', (['func'], {}), '(func)\n', (1029, 1035), False, 'from inspect import getfullargspec\n'), ((2363, 2396), 'numpy.asarray', 'np.asarray', (['val'], {'dtype': 'np.float64'}), '(val, dtype=np.float64)\n', (2373, 2396), True, 'import numpy as np\n'), ((2494, 2547),... |
# CONTAGEM DE PARES — Crie um programa que mostre na tela todos os números pares entre 1 e 50.
from time import sleep
print('NÚMEROS PARES ENTRE 2 E 50\n')
sleep(1)
for i in range(2, 51, 2):
print(i)
| [
"time.sleep"
] | [((157, 165), 'time.sleep', 'sleep', (['(1)'], {}), '(1)\n', (162, 165), False, 'from time import sleep\n')] |
import os
import pytest
from sqlalchemy.inspection import inspect
from sqlalchemy_utils.functions import drop_database
from alembic import config
from dbutils import conn_uri_factory, DbConnection
def pytest_addoption(parser):
"""
Custom command line options required for test runs
"""
parser.addopti... | [
"sqlalchemy.inspection.inspect",
"os.path.dirname",
"pytest.fixture",
"dbutils.DbConnection",
"dbutils.conn_uri_factory",
"sqlalchemy_utils.functions.drop_database"
] | [((1059, 1090), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (1073, 1090), False, 'import pytest\n'), ((1166, 1197), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (1180, 1197), False, 'import pytest\n'), ((1273, 1304), 'pytes... |
# -*- coding: utf-8 -*-
"""
# HarmonicNet.
# Copyright (C) 2021 <NAME>, <NAME>, S.Koppers, <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 Liceense at
#
# http://www.apache.org/licenses/LICE... | [
"argparse.Namespace",
"torch.nn.PReLU",
"argparse.ArgumentParser",
"torch.utils.data.DataLoader",
"torch.stack",
"torch.nn.Conv3d",
"torch.nn.ConvTranspose3d",
"torch.load",
"torch.nn.functional.l1_loss",
"torch.cat",
"torch.mul",
"torchvision.utils.make_grid",
"collections.OrderedDict",
"... | [((9704, 9732), 'torch.cat', 'torch.cat', (['(det1, shape1)', '(1)'], {}), '((det1, shape1), 1)\n', (9713, 9732), False, 'import torch\n'), ((9829, 9857), 'torch.cat', 'torch.cat', (['(det2, shape2)', '(1)'], {}), '((det2, shape2), 1)\n', (9838, 9857), False, 'import torch\n'), ((9954, 9982), 'torch.cat', 'torch.cat', ... |
# -*- coding: utf-8 -*-
# @Time : 2019-11-08 10:08
# @Author : binger
from .draw_by_html import EffectFont
from .draw_by_html import FontDrawByHtml
from . import FontDraw, FontAttr
from PIL import Image, ImageDraw, ImageFont
class FontFactory(object):
def __init__(self, effect_font, render_by_mixed=False)... | [
"PIL.ImageFont.truetype",
"os.path.abspath"
] | [((1556, 1619), 'PIL.ImageFont.truetype', 'ImageFont.truetype', ([], {'font': 'self._effect_font.base.path', 'size': 'size'}), '(font=self._effect_font.base.path, size=size)\n', (1574, 1619), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((2574, 2595), 'os.path.abspath', 'os.path.abspath', (['path'], {}), '(... |
# Generated by Django 4.0.3 on 2022-03-12 20:16
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('university', '0008_rename_course_id_course_courseid_and_more'),
]
operations = [
migrations.RenameField(
model_name='course',
... | [
"django.db.migrations.RenameField"
] | [((253, 343), 'django.db.migrations.RenameField', 'migrations.RenameField', ([], {'model_name': '"""course"""', 'old_name': '"""courseId"""', 'new_name': '"""courseid"""'}), "(model_name='course', old_name='courseId', new_name=\n 'courseid')\n", (275, 343), False, 'from django.db import migrations\n')] |
""" Test for the API that handle models
Copyright (c) 2021 Idiap Research Institute, https://www.idiap.ch/
Written by <NAME> <<EMAIL>>,
"""
import unittest
from fastapi.testclient import TestClient # type: ignore
from personal_context_builder import config
from personal_context_builder.wenet_fastapi_app import app
... | [
"fastapi.testclient.TestClient"
] | [((409, 424), 'fastapi.testclient.TestClient', 'TestClient', (['app'], {}), '(app)\n', (419, 424), False, 'from fastapi.testclient import TestClient\n')] |
import pytest
from exception.argument_not_instance_of_exception import ArgumentNotInstanceOfException
from guard import Guard
@pytest.mark.parametrize(
"param, typeof, param_name, message, expected",
[
(2, str, None, "parameter is not from type <class 'str'>.", pytest.raises(ArgumentNotInstanceOfExce... | [
"pytest.raises",
"guard.Guard.is_not_instance_of_type"
] | [((815, 900), 'guard.Guard.is_not_instance_of_type', 'Guard.is_not_instance_of_type', ([], {'param': 'param', 'typeof': 'typeof', 'param_name': 'param_name'}), '(param=param, typeof=typeof, param_name=param_name\n )\n', (844, 900), False, 'from guard import Guard\n'), ((281, 326), 'pytest.raises', 'pytest.raises', (... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 28 13:22:41 2022
@author: sampasmann
"""
import numpy as np
from time import process_time
def reeds_data(Nx=1000, LB=-8.0, RB=8.0):
G = 1 # number of energy groups
sigt = np.empty((Nx,G))
sigs = np.empty((Nx,G,G))
source = np.empty(... | [
"numpy.empty",
"time.process_time",
"numpy.linspace"
] | [((251, 268), 'numpy.empty', 'np.empty', (['(Nx, G)'], {}), '((Nx, G))\n', (259, 268), True, 'import numpy as np\n'), ((279, 299), 'numpy.empty', 'np.empty', (['(Nx, G, G)'], {}), '((Nx, G, G))\n', (287, 299), True, 'import numpy as np\n'), ((311, 328), 'numpy.empty', 'np.empty', (['(Nx, G)'], {}), '((Nx, G))\n', (319,... |
import sqlite3
import time
import hashlib
conn = None
c = None
def connect(path):
global conn, c
conn = sqlite3.connect(path)
c = conn.cursor()
c.execute(' PRAGMA foreign_keys=ON; ')
conn.commit()
return
def drop_tables():
global conn, c
c.execute("drop table if exists demeritNotice... | [
"sqlite3.connect"
] | [((115, 136), 'sqlite3.connect', 'sqlite3.connect', (['path'], {}), '(path)\n', (130, 136), False, 'import sqlite3\n')] |
#! /opt/jython/bin/jython
# -*- coding: utf-8 -*-
#
# delete/text_delete.py
#
# Oct/12/2016
import sys
import string
#
# ---------------------------------------------------------------
sys.path.append ('/var/www/data_base/common/python_common')
sys.path.append ('/var/www/data_base/common/jython_common')
from jython... | [
"sys.path.append",
"jython_text_manipulate.text_read_proc",
"text_manipulate.dict_delete_proc",
"sys.stderr.write",
"jython_text_manipulate.text_write_proc"
] | [((189, 247), 'sys.path.append', 'sys.path.append', (['"""/var/www/data_base/common/python_common"""'], {}), "('/var/www/data_base/common/python_common')\n", (204, 247), False, 'import sys\n'), ((249, 307), 'sys.path.append', 'sys.path.append', (['"""/var/www/data_base/common/jython_common"""'], {}), "('/var/www/data_b... |
import functools
def run_once(func):
""" The decorated function will only run once. Other calls to it will
return None. The original implementation can be found on StackOverflow(https://stackoverflow.com/questions/4103773/efficient-way-of-having-a-function-only-execute-once-in-a-loop)
:param func: the fu... | [
"functools.wraps"
] | [((416, 437), 'functools.wraps', 'functools.wraps', (['func'], {}), '(func)\n', (431, 437), False, 'import functools\n')] |
import argparse
import os
from scheduled_bots.ontology.obographs import Graph, Node
from wikidataintegrator import wdi_login, wdi_core, wdi_helpers
from scheduled_bots import PROPS
def ec_formatter(ec_number):
splits = ec_number.split('.')
if len(splits) < 4:
for x in range(4 - len(splits)):
... | [
"wikidataintegrator.wdi_login.WDLogin",
"wikidataintegrator.wdi_core.WDItemEngine.log",
"argparse.ArgumentParser"
] | [((3164, 3236), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""run wikidata disease ontology bot"""'}), "(description='run wikidata disease ontology bot')\n", (3187, 3236), False, 'import argparse\n'), ((3635, 3712), 'wikidataintegrator.wdi_login.WDLogin', 'wdi_login.WDLogin', (['"""test... |
from django.shortcuts import render, get_object_or_404, redirect
from .models import (
Category,
Post,
Profile,
Comment,
PostCreationForm,
PostEditForm,
UserLoginForm,
UserRegistrationForm,
UserUpdateForm,
ProfileUpdateForm,
CommentForm
)
from django.views.generic.edit import... | [
"django.shortcuts.redirect",
"django.template.loader.render_to_string",
"django.db.models.Q",
"django.http.JsonResponse",
"django.utils.text.slugify",
"django.urls.reverse",
"django.shortcuts.get_object_or_404",
"django.contrib.auth.logout",
"django.core.paginator.Paginator",
"django.http.Http404"... | [((2637, 2660), 'django.core.paginator.Paginator', 'Paginator', (['post_list', '(4)'], {}), '(post_list, 4)\n', (2646, 2660), False, 'from django.core.paginator import Paginator\n'), ((4369, 4412), 'django.shortcuts.render', 'render', (['requests', '"""blog/home.html"""', 'context'], {}), "(requests, 'blog/home.html', ... |
from tensorflow.keras.callbacks import ModelCheckpoint
import os
def produce_callback():
checkpoint_filepath = "./run/weights-improvement-{epoch:02d}-{val_psnr_metric:.2f}-{val_ssim_metric:.2f}.hdf5"
os.makedirs(os.path.dirname(checkpoint_filepath), exist_ok=True)
model_checkpoint = ModelCheckpoint(checkp... | [
"os.path.dirname",
"tensorflow.keras.callbacks.ModelCheckpoint"
] | [((298, 402), 'tensorflow.keras.callbacks.ModelCheckpoint', 'ModelCheckpoint', (['checkpoint_filepath'], {'monitor': '"""val_loss"""', 'verbose': '(1)', 'save_best_only': '(True)', 'mode': '"""min"""'}), "(checkpoint_filepath, monitor='val_loss', verbose=1,\n save_best_only=True, mode='min')\n", (313, 402), False, '... |
from brownie import *
from brownie.network.contract import InterfaceContainer
import json
def loadConfig():
global contracts, acct
thisNetwork = network.show_active()
if thisNetwork == "development":
acct = accounts[0]
configFile = open('./scripts/contractInteraction/testnet_contracts.json... | [
"json.load"
] | [((1058, 1079), 'json.load', 'json.load', (['configFile'], {}), '(configFile)\n', (1067, 1079), False, 'import json\n')] |
from Joueur import Joueur
from Plateau import Plateau
from BonusType import BonusType
from random import randrange
nbBonus = int(input("Nombre de bonus : "))
nbJoueur = int(input("Saisissez le nombre de joueur : "))
listJoueur = []
for i in range(0,nbJoueur):
listJoueur.append(Joueur(input("Nom du joueur " + str(... | [
"Plateau.Plateau",
"random.randrange"
] | [((395, 411), 'Plateau.Plateau', 'Plateau', (['nbBonus'], {}), '(nbBonus)\n', (402, 411), False, 'from Plateau import Plateau\n'), ((612, 627), 'random.randrange', 'randrange', (['(1)', '(6)'], {}), '(1, 6)\n', (621, 627), False, 'from random import randrange\n')] |
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 6 21:52:54 2019
@author: USER
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import sklearn as sk
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_scor... | [
"torch.tensor",
"sklearn.preprocessing.StandardScaler",
"sklearn.model_selection.train_test_split",
"utilities.load_census_data",
"sklearn.metrics.roc_auc_score",
"DNN_model.training_fair_model",
"sklearn.metrics.f1_score",
"fairness_metrics.computeEDFforData",
"sklearn.utils.shuffle",
"torch.no_g... | [((971, 1009), 'utilities.load_census_data', 'load_census_data', (['"""data/adult.data"""', '(1)'], {}), "('data/adult.data', 1)\n", (987, 1009), False, 'from utilities import load_census_data\n'), ((1148, 1168), 'numpy.unique', 'np.unique', (['S'], {'axis': '(0)'}), '(S, axis=0)\n', (1157, 1168), True, 'import numpy a... |
# -*- coding: utf-8 -*-
"""
Created on Thu May 2 13:42:37 2019
@author: <NAME>
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.cm as cm
from mpl_toolkits.mplot3d import Axes3D
import cycler
def spectral_decay(case = 4,
vname = 'example_0',
... | [
"matplotlib.pyplot.subplot",
"numpy.load",
"matplotlib.pyplot.show",
"numpy.amin",
"numpy.asarray",
"numpy.amax",
"matplotlib.pyplot.figure",
"numpy.arange",
"matplotlib.pyplot.tick_params",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.savefig"
] | [((1133, 1149), 'numpy.arange', 'np.arange', (['(2)', '(12)'], {}), '(2, 12)\n', (1142, 1149), True, 'import numpy as np\n'), ((6195, 6205), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6203, 6205), True, 'import matplotlib.pyplot as plt\n'), ((2010, 2028), 'numpy.load', 'np.load', (['iter_name'], {}), '(it... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'C:\Users\conta\Documents\script\Wizard\App\work\ui_files\server_widget.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(o... | [
"PyQt5.QtWidgets.QLabel",
"PyQt5.QtWidgets.QSizePolicy",
"PyQt5.QtWidgets.QFrame",
"PyQt5.QtWidgets.QWidget",
"PyQt5.QtWidgets.QTextEdit",
"PyQt5.QtWidgets.QHBoxLayout",
"PyQt5.QtWidgets.QPushButton",
"PyQt5.QtCore.QSize",
"PyQt5.QtWidgets.QSpacerItem",
"PyQt5.QtWidgets.QVBoxLayout",
"PyQt5.QtCo... | [((6016, 6048), 'PyQt5.QtWidgets.QApplication', 'QtWidgets.QApplication', (['sys.argv'], {}), '(sys.argv)\n', (6038, 6048), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((6060, 6079), 'PyQt5.QtWidgets.QWidget', 'QtWidgets.QWidget', ([], {}), '()\n', (6077, 6079), False, 'from PyQt5 import QtCore, QtGui, QtWi... |
import cv2
import numpy as np
import mediapipe as mp
import glob
import os
mp_drawing = mp.solutions.drawing_utils
mp_drawing_styles = mp.solutions.drawing_styles
mp_face_mesh = mp.solutions.face_mesh
#import os
os.environ['JOBLIB_TEMP_FOLDER'] = '/tmp'
# wait for process: "W016","W017","W018","W019","W023","W024","W... | [
"cv2.line",
"numpy.save",
"cv2.cvtColor",
"cv2.VideoCapture",
"numpy.array",
"os.path.splitext",
"glob.glob",
"os.path.split"
] | [((612, 670), 'glob.glob', 'glob.glob', (['"""/data3/MEAD/W036/video/front/*/level_*/0*.mp4"""'], {}), "('/data3/MEAD/W036/video/front/*/level_*/0*.mp4')\n", (621, 670), False, 'import glob\n'), ((891, 910), 'os.path.split', 'os.path.split', (['path'], {}), '(path)\n', (904, 910), False, 'import os\n'), ((924, 943), 'o... |
# coding=utf-8
from tornado.web import RequestHandler, HTTPError
from tornado.gen import coroutine
from bson import ObjectId
from bson.json_util import dumps, loads
__author__ = '<EMAIL>'
__date__ = "2018/12/14 下午9:58"
UID_KEY = 'uid'
class LoginHandler(RequestHandler):
def check_xsrf_cookie(self):
pas... | [
"tornado.web.HTTPError",
"bson.json_util.loads"
] | [((587, 611), 'bson.json_util.loads', 'loads', (['self.request.body'], {}), '(self.request.body)\n', (592, 611), False, 'from bson.json_util import dumps, loads\n'), ((536, 550), 'tornado.web.HTTPError', 'HTTPError', (['(404)'], {}), '(404)\n', (545, 550), False, 'from tornado.web import RequestHandler, HTTPError\n')] |
from insights import combiner
from insights.combiners.hostname import hostname
from insights.core.context import create_product
from insights.parsers.metadata import MetadataJson
from insights.specs import Specs
@combiner(MetadataJson, [hostname, Specs.machine_id])
def multinode_product(md, hn, machine_id):
hn = ... | [
"insights.core.context.create_product",
"insights.combiner"
] | [((215, 267), 'insights.combiner', 'combiner', (['MetadataJson', '[hostname, Specs.machine_id]'], {}), '(MetadataJson, [hostname, Specs.machine_id])\n', (223, 267), False, 'from insights import combiner\n'), ((412, 439), 'insights.combiner', 'combiner', (['multinode_product'], {}), '(multinode_product)\n', (420, 439), ... |
"""
Performance Comparision with Commercial APIs like Face++, Google, MS and Amazon
"""
import sys
import os
import requests
import numpy as np
import pandas as pd
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
sys.path.append('../')
from config.cfg import cfg
def prepare_te... | [
"sys.path.append",
"sklearn.metrics.accuracy_score",
"numpy.array",
"numpy.loadtxt",
"requests.post",
"os.path.join",
"os.listdir"
] | [((254, 276), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (269, 276), False, 'import sys\n'), ((481, 568), 'os.path.join', 'os.path.join', (["cfg['root']", '"""RAF-Face"""', "('%s/EmoLabel/list_patition_label.txt' % type)"], {}), "(cfg['root'], 'RAF-Face', '%s/EmoLabel/list_patition_label.tx... |
import pycurl
from io import BytesIO
import json
import datetime
import pandas as pd
myaddress = input('Enter Bitcoin Address: ')
btcval = 100000000.0 # in santoshis
block_time_in_min = 10
block_time_in_sec = block_time_in_min*60
def getBalance(address: str):
strbuf = BytesIO()
getreq = pycurl.Curl(... | [
"pandas.DataFrame",
"io.BytesIO",
"pycurl.Curl",
"datetime.datetime.fromtimestamp"
] | [((281, 290), 'io.BytesIO', 'BytesIO', ([], {}), '()\n', (288, 290), False, 'from io import BytesIO\n'), ((308, 321), 'pycurl.Curl', 'pycurl.Curl', ([], {}), '()\n', (319, 321), False, 'import pycurl\n'), ((890, 899), 'io.BytesIO', 'BytesIO', ([], {}), '()\n', (897, 899), False, 'from io import BytesIO\n'), ((917, 930)... |
from scipy.signal import find_peaks
import numpy as np
import math
def search_peaks(x_data, y_data, height=0.1, distance=10):
prominence = np.mean(y_data)
peak_list = find_peaks(y_data, height=height, prominence=prominence, distance=distance)
peaks = []
for i in peak_list[0]:
peak = (x_data[i]... | [
"numpy.mean",
"scipy.signal.find_peaks",
"math.isclose"
] | [((144, 159), 'numpy.mean', 'np.mean', (['y_data'], {}), '(y_data)\n', (151, 159), True, 'import numpy as np\n'), ((176, 251), 'scipy.signal.find_peaks', 'find_peaks', (['y_data'], {'height': 'height', 'prominence': 'prominence', 'distance': 'distance'}), '(y_data, height=height, prominence=prominence, distance=distanc... |
import pandas as pd
from transformers import BertTokenizer, RobertaTokenizer, AutoTokenizer
import os
import numpy as np
import re
import glob
from nltk import sent_tokenize
from utils import num_tokens
import math
def read_generic_file(filepath):
""" reads any generic text file into
list conta... | [
"pandas.DataFrame",
"utils.num_tokens",
"numpy.random.seed",
"os.path.join",
"nltk.sent_tokenize",
"math.floor",
"transformers.AutoTokenizer.from_pretrained",
"re.search",
"numpy.random.choice",
"re.sub",
"os.listdir"
] | [((5885, 5908), 'nltk.sent_tokenize', 'sent_tokenize', (['document'], {}), '(document)\n', (5898, 5908), False, 'from nltk import sent_tokenize\n'), ((15283, 15314), 'math.floor', 'math.floor', (['augmentation_factor'], {}), '(augmentation_factor)\n', (15293, 15314), False, 'import math\n'), ((17416, 17434), 'numpy.ran... |
'''
Created on 2015/12/14
:author: hubo
'''
from __future__ import print_function
import unittest
from vlcp.server.server import Server
from vlcp.event.runnable import RoutineContainer
from vlcp.event.lock import Lock, Semaphore
from vlcp.config.config import manager
class Test(unittest.TestCase):
def setUp(self... | [
"unittest.main",
"vlcp.event.lock.Semaphore",
"vlcp.event.runnable.RoutineContainer",
"vlcp.event.lock.Lock",
"vlcp.server.server.Server"
] | [((5137, 5152), 'unittest.main', 'unittest.main', ([], {}), '()\n', (5150, 5152), False, 'import unittest\n'), ((345, 353), 'vlcp.server.server.Server', 'Server', ([], {}), '()\n', (351, 353), False, 'from vlcp.server.server import Server\n'), ((433, 472), 'vlcp.event.runnable.RoutineContainer', 'RoutineContainer', (['... |
#!/usr/bin/env python
"""Convert Directory.
Usage: convert_directory.py <src_dir> <dest_dir>
-h --help show this
"""
import errno
import os
import subprocess
from docopt import docopt
def convert_directory(src, dest):
# Convert the files in place
for root, dirs, files in os.walk(src):
for fil... | [
"docopt.docopt",
"os.walk",
"subprocess.call",
"os.path.splitext",
"os.path.join"
] | [((291, 303), 'os.walk', 'os.walk', (['src'], {}), '(src)\n', (298, 303), False, 'import os\n'), ((821, 870), 'subprocess.call', 'subprocess.call', (["['rsync', '-a', src + '/', dest]"], {}), "(['rsync', '-a', src + '/', dest])\n", (836, 870), False, 'import subprocess\n'), ((875, 949), 'subprocess.call', 'subprocess.c... |
from django.test import TestCase
from hknweb.candidate.tests.models.utils import ModelFactory
class CommitteeProjectRequirementModelTests(TestCase):
def setUp(self):
semester = ModelFactory.create_semester(
semester="Spring",
year=0,
)
committeeproject = ModelFacto... | [
"hknweb.candidate.tests.models.utils.ModelFactory.create_committeeproject_requirement",
"hknweb.candidate.tests.models.utils.ModelFactory.create_semester"
] | [((192, 247), 'hknweb.candidate.tests.models.utils.ModelFactory.create_semester', 'ModelFactory.create_semester', ([], {'semester': '"""Spring"""', 'year': '(0)'}), "(semester='Spring', year=0)\n", (220, 247), False, 'from hknweb.candidate.tests.models.utils import ModelFactory\n'), ((310, 397), 'hknweb.candidate.tests... |
# Copyright 2021 DeepMind Technologies Limited.
#
# 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... | [
"tensorflow.compat.v2.reshape",
"rdkit.Chem.RemoveHs",
"rdkit.Chem.AllChem.UFFGetMoleculeForceField",
"absl.logging.exception",
"tensorflow.compat.v2.matmul",
"copy.deepcopy",
"rdkit.Chem.AllChem.ETKDGv3",
"tensorflow.compat.v2.zeros_like",
"tensorflow.compat.v2.stack",
"tensorflow.compat.v2.linal... | [((1968, 1991), 'copy.deepcopy', 'copy.deepcopy', (['molecule'], {}), '(molecule)\n', (1981, 1991), False, 'import copy\n'), ((2000, 2015), 'rdkit.Chem.AddHs', 'Chem.AddHs', (['mol'], {}), '(mol)\n', (2010, 2015), False, 'from rdkit import Chem\n'), ((2492, 2539), 'rdkit.Chem.AllChem.AlignMolConformers', 'AllChem.Align... |
"""Module for handling plotting functions
This module contains plotting classes to plot :class:`.Binning` objects.
Examples
--------
::
plt = plotting.get_plotter(binning)
plt.plot_values()
plt.savefig('output.png')
"""
from itertools import cycle
import numpy as np
from matplotlib import pyplot as ... | [
"numpy.random.uniform",
"numpy.quantile",
"numpy.sum",
"numpy.ceil",
"numpy.zeros_like",
"matplotlib.pyplot.close",
"numpy.asarray",
"numpy.asfarray",
"matplotlib.ticker.MaxNLocator",
"numpy.isfinite",
"numpy.ones",
"numpy.append",
"numpy.min",
"numpy.max",
"numpy.array",
"numpy.arange... | [((1942, 1973), 'itertools.cycle', 'cycle', (["['//', '\\\\\\\\', 'O', '*']"], {}), "(['//', '\\\\\\\\', 'O', '*'])\n", (1947, 1973), False, 'from itertools import cycle\n'), ((4113, 4126), 'numpy.array', 'np.array', (['ret'], {}), '(ret)\n', (4121, 4126), True, 'import numpy as np\n'), ((4253, 4276), 'numpy.arange', '... |
"""
ported from https://github.com/NASA-DEVELOP/dnppy/tree/master/dnppy/landsat
"""
# standard imports
from .landsat_metadata import landsat_metadata
from . import core
import os
from pathlib import Path
import numpy as np
import rasterio
__all__ = ['toa_radiance_8', # complete
'toa_radiance_457',... | [
"pathlib.Path"
] | [((5409, 5424), 'pathlib.Path', 'Path', (['meta_path'], {}), '(meta_path)\n', (5413, 5424), False, 'from pathlib import Path\n'), ((7077, 7092), 'pathlib.Path', 'Path', (['meta_path'], {}), '(meta_path)\n', (7081, 7092), False, 'from pathlib import Path\n')] |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as img
import h5py #s a common package to interact with
# a dataset that is stored on an H5 file.
#from lr_utils import load_dataset
#load datasets
#Load lr_utils for loading train and testinng datasets
def load_dataset():
t... | [
"h5py.File",
"matplotlib.pyplot.show",
"numpy.dot",
"matplotlib.pyplot.plot",
"numpy.sum",
"numpy.log",
"matplotlib.pyplot.imshow",
"numpy.abs",
"numpy.zeros",
"numpy.array",
"numpy.exp",
"numpy.squeeze",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel"
] | [((1383, 1418), 'matplotlib.pyplot.imshow', 'plt.imshow', (['train_set_x_orig[index]'], {}), '(train_set_x_orig[index])\n', (1393, 1418), True, 'import matplotlib.pyplot as plt\n'), ((1420, 1430), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1428, 1430), True, 'import matplotlib.pyplot as plt\n'), ((12747, ... |
import botorch
import gpytorch
from torch import Tensor
from gpytorch.kernels.kernel import Kernel
from gpytorch.mlls.exact_marginal_log_likelihood import ExactMarginalLogLikelihood
from gpytorch.priors.torch_priors import GammaPrior
from botorch.models import SingleTaskGP
from botorch.fit import fit_gpytorch_model
fr... | [
"gpytorch.mlls.exact_marginal_log_likelihood.ExactMarginalLogLikelihood",
"botorch.posteriors.gpytorch.GPyTorchPosterior",
"gpytorch.kernels.RBFKernel",
"gpytorch.kernels.RQKernel",
"gpytorch.priors.torch_priors.GammaPrior",
"botorch.models.SingleTaskGP",
"botorch.models.utils.gpt_posterior_settings",
... | [((808, 826), 'botorch.models.SingleTaskGP', 'SingleTaskGP', (['x', 'y'], {}), '(x, y)\n', (820, 826), False, 'from botorch.models import SingleTaskGP\n'), ((1546, 1597), 'gpytorch.mlls.exact_marginal_log_likelihood.ExactMarginalLogLikelihood', 'ExactMarginalLogLikelihood', (['model.likelihood', 'model'], {}), '(model.... |
import math
def poly2(a,b,c):
''' solves quadratic equations of the
form ax^2 + bx + c = 0 '''
x1 = (-b + math.sqrt(b**2 - 4*a*c))/(2*a)
x2 = (-b - math.sqrt(b**2 - 4*a*c))/(2*a)
return x1, x2
| [
"math.sqrt"
] | [((123, 152), 'math.sqrt', 'math.sqrt', (['(b ** 2 - 4 * a * c)'], {}), '(b ** 2 - 4 * a * c)\n', (132, 152), False, 'import math\n'), ((169, 198), 'math.sqrt', 'math.sqrt', (['(b ** 2 - 4 * a * c)'], {}), '(b ** 2 - 4 * a * c)\n', (178, 198), False, 'import math\n')] |
# models.py
from flask import abort, redirect, request, url_for
from flask_admin import form
from flask_admin.contrib.sqla import ModelView
from flask_security import current_user, RoleMixin, UserMixin
from wtforms import SelectField, TextAreaField
from reel_miami import db
# Database models
class Venue(db.Model):... | [
"wtforms.SelectField",
"reel_miami.db.backref",
"reel_miami.db.String",
"flask_admin.form.ImageUploadField",
"reel_miami.db.relationship",
"reel_miami.db.Boolean",
"flask_security.current_user.has_role",
"flask.abort",
"reel_miami.db.Integer",
"flask.url_for",
"reel_miami.db.ForeignKey",
"reel... | [((360, 399), 'reel_miami.db.Column', 'db.Column', (['db.Integer'], {'primary_key': '(True)'}), '(db.Integer, primary_key=True)\n', (369, 399), False, 'from reel_miami import db\n'), ((411, 447), 'reel_miami.db.Column', 'db.Column', (['db.String'], {'nullable': '(False)'}), '(db.String, nullable=False)\n', (420, 447), ... |
import os
import unittest
import torch
import numpy as np
from PIL import Image
from embryovision import util
from embryovision.tests.common import get_loadable_filenames
class TestReadImage(unittest.TestCase):
def test_read_image_returns_numpy(self):
filename = get_loadable_filenames()[0]
image... | [
"unittest.main",
"embryovision.util.augment_focus",
"numpy.random.seed",
"numpy.random.randn",
"embryovision.util.read_image",
"os.path.exists",
"embryovision.util.split_all",
"PIL.Image.open",
"embryovision.util.ImageTransformingCollection",
"embryovision.util.TransformingCollection",
"numpy.ar... | [((4960, 4984), 'embryovision.tests.common.get_loadable_filenames', 'get_loadable_filenames', ([], {}), '()\n', (4982, 4984), False, 'from embryovision.tests.common import get_loadable_filenames\n'), ((4996, 5039), 'embryovision.util.ImageTransformingCollection', 'util.ImageTransformingCollection', (['filenames'], {}),... |
import tensorflow as tf
import numpy as np
import helper
import problem_unittests as tests
# Number of Epochs
num_epochs = 2
# Batch Size
batch_size = 64
# RNN Size
rnn_size = 256
# Embedding Dimension Size
embed_dim = 300
# Sequence Length
seq_length = 100
# Learning Rate
learning_rate = 0.001
# Show stats for every ... | [
"helper.save_params",
"tensorflow.train.import_meta_graph",
"helper.load_params",
"tensorflow.Session",
"problem_unittests.test_pick_word",
"problem_unittests.test_get_tensors",
"helper.load_preprocess",
"numpy.array",
"tensorflow.Graph"
] | [((531, 573), 'helper.save_params', 'helper.save_params', (['(seq_length, save_dir)'], {}), '((seq_length, save_dir))\n', (549, 573), False, 'import helper\n'), ((839, 863), 'helper.load_preprocess', 'helper.load_preprocess', ([], {}), '()\n', (861, 863), False, 'import helper\n'), ((887, 907), 'helper.load_params', 'h... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Contains tests for accessing env vars as Django's secret key.
import pytest
from djangokeys.core.djangokeys import DjangoKeys
from djangokeys.exceptions import EnvironmentVariableNotFound
from djangokeys.exceptions import ValueIsEmpty
from tests.files import EMPTY_EN... | [
"pytest.raises",
"tests.utils.environment_vars.use_environment_variable",
"djangokeys.core.djangokeys.DjangoKeys"
] | [((529, 555), 'djangokeys.core.djangokeys.DjangoKeys', 'DjangoKeys', (['EMPTY_ENV_PATH'], {}), '(EMPTY_ENV_PATH)\n', (539, 555), False, 'from djangokeys.core.djangokeys import DjangoKeys\n'), ((565, 607), 'pytest.raises', 'pytest.raises', (['EnvironmentVariableNotFound'], {}), '(EnvironmentVariableNotFound)\n', (578, 6... |
from examplepackage.badmodule import bad_function
def test_bad_function():
assert bad_function(1) == 1
| [
"examplepackage.badmodule.bad_function"
] | [((88, 103), 'examplepackage.badmodule.bad_function', 'bad_function', (['(1)'], {}), '(1)\n', (100, 103), False, 'from examplepackage.badmodule import bad_function\n')] |
import os
import pickle
from lib.model.model import Model
class PersistenceHandler:
def __init__(self, folder):
self.__model_file_name = os.path.join("model.bin")
def store_model(self, model):
"""
@type model: Model
@return: None
"""
with open(s... | [
"pickle.dump",
"pickle.load",
"os.path.join"
] | [((160, 185), 'os.path.join', 'os.path.join', (['"""model.bin"""'], {}), "('model.bin')\n", (172, 185), False, 'import os\n'), ((378, 409), 'pickle.dump', 'pickle.dump', (['model', 'output_file'], {}), '(model, output_file)\n', (389, 409), False, 'import pickle\n'), ((572, 595), 'pickle.load', 'pickle.load', (['input_f... |
import discord
from commands.framework.CommandBase import CommandBase
class HelpCommand(CommandBase):
def __init__(self):
super(HelpCommand, self).__init__('help')
async def execute(self, client, message, args):
embed = discord.Embed(
title="Help Page",
description="... | [
"discord.Colour.red"
] | [((354, 374), 'discord.Colour.red', 'discord.Colour.red', ([], {}), '()\n', (372, 374), False, 'import discord\n')] |
from os import listdir
from os.path import isdir, isfile, join
from itertools import chain
import numpy as np
import matplotlib.pyplot as plt
from utils import shelf
def dlist(key, dat):
r"""Runs over a list of dictionaries and outputs a list of values corresponding to `key`
Short version (no checks): ret... | [
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.boxplot",
"matplotlib.pyplot.figure",
"numpy.array",
"utils.shelf",
"os.path.join",
"os.listdir"
] | [((554, 567), 'numpy.array', 'np.array', (['ret'], {}), '(ret)\n', (562, 567), True, 'import numpy as np\n'), ((4199, 4225), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 3)'}), '(figsize=(8, 3))\n', (4209, 4225), True, 'import matplotlib.pyplot as plt\n'), ((4235, 4251), 'matplotlib.pyplot.subplot', ... |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | [
"proton.Message",
"traceback.print_exc"
] | [((3978, 3995), 'proton.Message', '_proton.Message', ([], {}), '()\n', (3993, 3995), True, 'import proton as _proton\n'), ((4220, 4242), 'traceback.print_exc', '_traceback.print_exc', ([], {}), '()\n', (4240, 4242), True, 'import traceback as _traceback\n')] |
import argparse
import math
import random
import os
import copy
from numpy.core.fromnumeric import resize
import dnnlib
import numpy as np
import torch
from torch import nn, autograd, optim
from torch.nn import functional as F
from torch.utils import data
import torch.distributed as dist
from torchvision import trans... | [
"swagan.Discriminator",
"torch.distributed.init_process_group",
"argparse.ArgumentParser",
"torch.load",
"torch.randn",
"torchvision.utils.save_image",
"torch.cuda.set_device",
"torch.no_grad",
"swagan.Generator",
"distributed.synchronize"
] | [((755, 807), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""mpnet trainer"""'}), "(description='mpnet trainer')\n", (778, 807), False, 'import argparse\n'), ((2824, 2895), 'torch.load', 'torch.load', (['args.style_model'], {'map_location': '(lambda storage, loc: storage)'}), '(args.styl... |