code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
"""
OpenVINO DL Workbench
Class for model optimizer job
Copyright (c) 2021 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
... | [
"wb.extensions_factories.database.get_db_session_for_celery",
"logging.error",
"wb.main.jobs.models.model_optimizer_job_state.ModelOptimizerJobStateSubject",
"json.loads",
"json.dumps",
"wb.main.console_tool_wrapper.model_optimizer.tool.ModelOptimizerTool",
"pathlib.Path",
"wb.error.job_error.ManualTa... | [((2045, 2088), 'wb.main.jobs.models.model_optimizer_job_state.ModelOptimizerJobStateSubject', 'ModelOptimizerJobStateSubject', (['self._job_id'], {}), '(self._job_id)\n', (2074, 2088), False, 'from wb.main.jobs.models.model_optimizer_job_state import ModelOptimizerJobStateSubject\n'), ((2114, 2159), 'wb.main.jobs.inte... |
from quail.egg import Egg
import numpy as np
import pytest
def test_spc():
presented=[[['cat', 'bat', 'hat', 'goat'],['zoo', 'animal', 'zebra', 'horse']]]
recalled=[[['bat', 'cat', 'goat', 'hat'],['animal', 'horse', 'zoo']]]
egg = Egg(pres=presented,rec=recalled)
assert np.array_equal(egg.analyze('spc'... | [
"numpy.array",
"pytest.raises",
"quail.egg.Egg"
] | [((244, 277), 'quail.egg.Egg', 'Egg', ([], {'pres': 'presented', 'rec': 'recalled'}), '(pres=presented, rec=recalled)\n', (247, 277), False, 'from quail.egg import Egg\n'), ((740, 773), 'quail.egg.Egg', 'Egg', ([], {'pres': 'presented', 'rec': 'recalled'}), '(pres=presented, rec=recalled)\n', (743, 773), False, 'from q... |
import os
import matplotlib.pyplot as plt
import numpy as np
from skimage import img_as_float, io
from skimage.measure import compare_ssim as ssim
from skimage.transform import resize
def bitmap_to_3ch(im):
img = im.copy()
r = img[:,:,0]
g = img[:,:,1]
b = img[:,:,2]
return r,g,b
def main():
avg = 0
#get fi... | [
"skimage.measure.compare_ssim",
"skimage.io.show",
"skimage.io.imshow_collection",
"skimage.io.imshow",
"os.listdir",
"skimage.io.imread"
] | [((923, 941), 'skimage.io.imread', 'io.imread', (['le_file'], {}), '(le_file)\n', (932, 941), False, 'from skimage import img_as_float, io\n'), ((976, 995), 'skimage.io.imshow', 'io.imshow', (['le_image'], {}), '(le_image)\n', (985, 995), False, 'from skimage import img_as_float, io\n'), ((997, 1006), 'skimage.io.show'... |
#!/usr/bin/python
# ex:set fileencoding=utf-8:
from __future__ import unicode_literals
from django.contrib import messages
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ValidationError
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q
... | [
"djangobmf.utils.form_class_factory",
"djangobmf.signals.activity_update.send",
"djangobmf.models.Report.objects.get",
"django.contrib.messages.info",
"django.utils.encoding.force_text",
"django.utils.translation.ugettext_lazy",
"django.utils.timezone.now",
"djangobmf.notification.models.Activity.obje... | [((6899, 6904), 'django.utils.timezone.now', 'now', ([], {}), '()\n', (6902, 6904), False, 'from django.utils.timezone import now\n'), ((9627, 9673), 'django.contrib.contenttypes.models.ContentType.objects.get_for_model', 'ContentType.objects.get_for_model', (['self.object'], {}), '(self.object)\n', (9660, 9673), False... |
import sys
import argparse
import logging
import numpy as np
from scipy.spatial import distance_matrix
np.set_printoptions(precision=5)
np.set_printoptions(suppress=True)
# Logging options
logging.basicConfig(
# filename=os.path.join(dir_path, 'thomson_problem.log'),
level=logging.INFO,
format='%(asctime... | [
"numpy.stack",
"numpy.fill_diagonal",
"numpy.set_printoptions",
"logging.debug",
"argparse.ArgumentParser",
"logging.basicConfig",
"numpy.random.seed",
"numpy.zeros",
"numpy.ones",
"scipy.spatial.distance_matrix",
"numpy.random.standard_normal",
"numpy.linalg.norm"
] | [((105, 137), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(5)'}), '(precision=5)\n', (124, 137), True, 'import numpy as np\n'), ((138, 172), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'suppress': '(True)'}), '(suppress=True)\n', (157, 172), True, 'import numpy as np\n'), ((192, 315)... |
# coding=utf-8
import logging
import os
import time
import json
from web.contrib.template import render_jinja
file = "logs/webpy.log" # 日志文件路径 #
logformat = "[%(asctime)s] %(filename)s:%(lineno)d(%(funcName)s): [%(levelname)s] %(message)s" # 日志格式 #
datefmt = "%Y-%m-%d %H:%M:%S" # 日志中显示的时间格式 #
loglevel = logging.DEBUG
... | [
"os.path.dirname",
"time.tzset",
"os.path.join",
"web.contrib.template.render_jinja"
] | [((390, 415), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (405, 415), False, 'import os\n'), ((432, 466), 'os.path.join', 'os.path.join', (['app_root', '"""template"""'], {}), "(app_root, 'template')\n", (444, 466), False, 'import os\n'), ((475, 520), 'web.contrib.template.render_jinja', '... |
from . import settings
from django.conf import settings
from django.db import models
from django.utils.module_loading import import_string
class CustomStorageFileFieldMixin:
def deconstruct(self):
name, path, args, kwargs = super(CustomStorageFileFieldMixin, self).deconstruct()
del kwargs['storage... | [
"django.utils.module_loading.import_string"
] | [((572, 615), 'django.utils.module_loading.import_string', 'import_string', (['settings.PUBLIC_FILE_STORAGE'], {}), '(settings.PUBLIC_FILE_STORAGE)\n', (585, 615), False, 'from django.utils.module_loading import import_string\n'), ((895, 939), 'django.utils.module_loading.import_string', 'import_string', (['settings.PR... |
import os
def find_files(suffix, path):
"""
Find all files beneath path with file name suffix.
Note that a path may contain further subdirectories
and those subdirectories may also contain further subdirectories.
There are no limit to the depth of the subdirectories can be.
... | [
"os.path.isdir",
"os.path.isfile",
"os.path.join",
"os.listdir"
] | [((742, 758), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (752, 758), False, 'import os\n'), ((854, 878), 'os.path.join', 'os.path.join', (['path', 'file'], {}), '(path, file)\n', (866, 878), False, 'import os\n'), ((613, 632), 'os.path.isdir', 'os.path.isdir', (['path'], {}), '(path)\n', (626, 632), False,... |
# Copyright 2018 eBay Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | [
"napalm_baseebay.ebay_exceptions.EntityDoesNotExistsException",
"oslo_log.log.getLogger",
"re.split",
"json.loads",
"napalm_base.helpers.mac",
"time.sleep",
"napalm_baseebay.ebay_exceptions.InvalidValueForParameterException",
"re.search",
"re.sub"
] | [((962, 989), 'oslo_log.log.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (979, 989), True, 'from oslo_log import log as logging\n'), ((1995, 2020), 'json.loads', 'json.loads', (['response_dict'], {}), '(response_dict)\n', (2005, 2020), False, 'import json\n'), ((11602, 11640), 're.sub', 're.sub'... |
import pytest
from llckbdm.min_rmse_kbdm import min_rmse_kbdm
def test_min_rmse_kbdm(data_brain_sim, dwell):
# because the number of points used to compute KBDM, only third element is capable of reproduce a good result
m_range = [30, 31, 180, 32, 33, 34]
l = 30
min_rmse_results = min_rmse_kbdm(
... | [
"llckbdm.min_rmse_kbdm.min_rmse_kbdm",
"pytest.approx"
] | [((301, 370), 'llckbdm.min_rmse_kbdm.min_rmse_kbdm', 'min_rmse_kbdm', ([], {'data': 'data_brain_sim', 'dwell': 'dwell', 'm_range': 'm_range', 'l': 'l'}), '(data=data_brain_sim, dwell=dwell, m_range=m_range, l=l)\n', (314, 370), False, 'from llckbdm.min_rmse_kbdm import min_rmse_kbdm\n'), ((552, 568), 'pytest.approx', '... |
# -*- coding: utf-8 -*-
# test/unit/stat/test_flushtosql.py
# Copyright (C) 2016 authors and contributors (see AUTHORS file)
#
# This module is released under the MIT License.
"""Test flushtosql()"""
# ============================================================================
# Imports
# ===========================... | [
"pandas.Timestamp.now",
"pytest.mark.parametrize",
"loadlimit.stat.timedata",
"loadlimit.stat.FlushToSQL",
"loadlimit.stat.flushtosql.flushfailure",
"loadlimit.stat.CountStore",
"loadlimit.stat.timedata.open",
"loadlimit.stat.flushtosql.flusherror",
"loadlimit.core.BaseLoop",
"functools.partial",
... | [((1208, 1281), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""fake_shutdown_channel"""', '"""fake_timedata_channel"""'], {}), "('fake_shutdown_channel', 'fake_timedata_channel')\n", (1231, 1281), False, 'import pytest\n'), ((1490, 1530), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""num"""',... |
from django.test import tag
from test import cases as case
from test import fixtures as data
@tag('keyword')
class KeywordTest(case.APITestCase, metaclass = case.MetaAPISchema):
fixtures = data.get_category_fixtures()
schema = {
'object': {
'tags': ('keyword_object',),
'&... | [
"test.fixtures.get_category_fixtures",
"django.test.tag"
] | [((97, 111), 'django.test.tag', 'tag', (['"""keyword"""'], {}), "('keyword')\n", (100, 111), False, 'from django.test import tag\n'), ((201, 229), 'test.fixtures.get_category_fixtures', 'data.get_category_fixtures', ([], {}), '()\n', (227, 229), True, 'from test import fixtures as data\n')] |
#! /usr/bin/env python3
#Dont forget to module load linuxbrew/colsa
#This script renames the headers after running transdecoder.
#A typical header looks like: >Gene.1::Ec_actinula_t.1::g.1::m.1 type:complete len:236 gc:universal Ec_actinula_t.1:2328-1621(-)
#This script will use the last segment of the transdecoder... | [
"argparse.ArgumentParser"
] | [((731, 756), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (754, 756), False, 'import argparse\n')] |
"""Classes that represent issues that the script can detect."""
from pathlib import Path
from mdtools.util import clr
from mdtools.model.tree import Link, Anchor
class Issue:
"""Base class for all issues that the script can detect."""
# The Path to the file where this issue was found
path: Path
def... | [
"mdtools.util.clr"
] | [((770, 777), 'mdtools.util.clr', 'clr', (['""""""'], {}), "('')\n", (773, 777), False, 'from mdtools.util import clr\n'), ((1228, 1235), 'mdtools.util.clr', 'clr', (['""""""'], {}), "('')\n", (1231, 1235), False, 'from mdtools.util import clr\n'), ((1496, 1503), 'mdtools.util.clr', 'clr', (['""""""'], {}), "('')\n", (... |
#!/usr/bin/env python
"""
NAME
suServer - websocket server for su data
RETURNS
returns a json string
"""
from datetime import datetime
import sys
import asyncio
import json
import websockets
import numpy as np
import scipy.signal as sig
#import pprint
#print("loading obspy...")
from obspy.io.segy.segy import... | [
"obspy.io.segy.segy._read_su",
"websockets.serve",
"scipy.signal.welch",
"scipy.signal.filtfilt",
"asyncio.get_event_loop",
"json.loads",
"json.dumps",
"numpy.max",
"numpy.mean",
"sys.stdout.flush",
"numpy.min",
"numpy.arange",
"numpy.array",
"scipy.signal.decimate",
"datetime.datetime.n... | [((10545, 10585), 'websockets.serve', 'websockets.serve', (['api', '"""localhost"""', '(9191)'], {}), "(api, 'localhost', 9191)\n", (10561, 10585), False, 'import websockets\n'), ((10668, 10686), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (10684, 10686), False, 'import sys\n'), ((1354, 1373), 'numpy.mean... |
# <NAME> <<EMAIL>>
import pytest
from alphatwirl.selection.factories.expand import expand_path_cfg
##__________________________________________________________________||
@pytest.fixture()
def alias_dict():
return {
'var_cut': ('ev : {low} <= ev.var[0] < {high}', dict(low=10, high=200)),
}
##_________... | [
"pytest.mark.parametrize",
"alphatwirl.selection.factories.expand.expand_path_cfg",
"pytest.fixture"
] | [((173, 189), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (187, 189), False, 'import pytest\n'), ((706, 759), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""path_cfg, expected"""', 'params'], {}), "('path_cfg, expected', params)\n", (729, 759), False, 'import pytest\n'), ((821, 878), 'alphatwirl.... |
#!/usr/bin/python
# -*- coding: latin-1 -*-
from telegram.ext import Updater, CommandHandler
from bs4 import BeautifulSoup
from json_parser import *
import sys
import logging
MIN_FIXTURES = 1
MAX_FIXTURES = 38
MSG_ERROR_FIXTURES = "O número da rodada deve estar no intervalo de 1 a 38."
TOKEN = sys.argv[1]
def showCl... | [
"telegram.ext.Updater",
"telegram.ext.CommandHandler",
"logging.basicConfig"
] | [((2998, 3018), 'telegram.ext.Updater', 'Updater', ([], {'token': 'TOKEN'}), '(token=TOKEN)\n', (3005, 3018), False, 'from telegram.ext import Updater, CommandHandler\n'), ((3053, 3160), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s - %(name)s - %(levelname)s - %(message)s"""', 'level': ... |
from __future__ import print_function
import gym
import math
import random
import numpy as np
import matplotlib
from collections import namedtuple
from itertools import count
import time
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import os
import gym_graph
from vi... | [
"random.sample",
"visdom.Visdom",
"torch.cat",
"numpy.mean",
"torch.no_grad",
"torch.load",
"os.path.exists",
"torch.nn.Linear",
"torch.zeros",
"itertools.count",
"time.sleep",
"random.random",
"math.exp",
"torch.nn.ReLU",
"gym.make",
"numpy.array",
"collections.namedtuple",
"rando... | [((360, 368), 'visdom.Visdom', 'Visdom', ([], {}), '()\n', (366, 368), False, 'from visdom import Visdom\n'), ((661, 730), 'collections.namedtuple', 'namedtuple', (['"""Transition"""', "('state', 'action', 'next_state', 'reward')"], {}), "('Transition', ('state', 'action', 'next_state', 'reward'))\n", (671, 730), False... |
"""
For compatibility between Python versions.
Taken mostly from six.py by <NAME>.
"""
import sys
import types
import os
# True if we are running on Python 3.
PY3 = sys.version_info[0] == 3
if PY3:
string_types = str,
integer_types = int,
class_types = type,
text_type = str
binary_type = bytes
... | [
"os.chmod",
"os.path.islink"
] | [((389, 432), 'os.chmod', 'os.chmod', (['path', 'mode'], {'follow_symlinks': '(False)'}), '(path, mode, follow_symlinks=False)\n', (397, 432), False, 'import os\n'), ((609, 629), 'os.path.islink', 'os.path.islink', (['path'], {}), '(path)\n', (623, 629), False, 'import os\n'), ((647, 667), 'os.chmod', 'os.chmod', (['pa... |
import logging
logger = logging.getLogger(__name__)
class FailedToCleanUpError(Exception):
pass
class Cleanups:
def __init__(self):
self._cleanups = []
def add_cleanup(self, func):
self._cleanups.append(func)
def clean_up(self):
success = True
for func in revers... | [
"logging.getLogger"
] | [((26, 53), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (43, 53), False, 'import logging\n')] |
'''
members_init - command line database initialization - clean database initialize tasks
=========================================================================================
run from 3 levels up, like python -m members.scripts.scripts.members_init
'''
# standard
from os.path import join, dirname
# pypi
# homeg... | [
"members.settings.Development",
"os.path.join",
"members.model.db.init_app",
"os.path.dirname",
"members.model.update_local_tables",
"members.model.db.create_all",
"members.model.db.session.commit",
"members.model.db.drop_all",
"members.applogging.setlogging"
] | [((610, 627), 'os.path.dirname', 'dirname', (['__file__'], {}), '(__file__)\n', (617, 627), False, 'from os.path import join, dirname\n'), ((699, 727), 'os.path.join', 'join', (['scriptfolder', '"""config"""'], {}), "(scriptfolder, 'config')\n", (703, 727), False, 'from os.path import join, dirname\n'), ((780, 813), 'o... |
"""empty message
Revision ID: 1def126b8921
Revises: <PASSWORD>
Create Date: 2020-05-06 23:59:31.796105
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '1def126b8921'
down_revision = '<PASSWORD>'
branch_labels = None
depends_... | [
"sqlalchemy.dialects.mysql.VARCHAR",
"alembic.op.drop_column",
"alembic.op.create_table_comment",
"alembic.op.drop_table_comment",
"sqlalchemy.Integer"
] | [((417, 494), 'alembic.op.create_table_comment', 'op.create_table_comment', (['"""grade"""', '"""年级班级表"""'], {'existing_comment': 'None', 'schema': 'None'}), "('grade', '年级班级表', existing_comment=None, schema=None)\n", (440, 494), False, 'from alembic import op\n'), ((1573, 1603), 'alembic.op.drop_column', 'op.drop_colu... |
from lettuce import step
from salad.steps.browser.finders import (ELEMENT_FINDERS, LINK_FINDERS,
ELEMENT_THING_STRING, LINK_THING_STRING, PICK_EXPRESSION,
_get_visible_element)
# Click on things, mouse over, move the mouse around.
# General syntax:
# <action> the <how-many-eth> <thing> <find clause>
... | [
"salad.steps.browser.finders.ELEMENT_FINDERS.iteritems",
"salad.steps.browser.finders._get_visible_element",
"salad.steps.browser.finders.LINK_FINDERS.iteritems",
"lettuce.step"
] | [((3931, 3958), 'salad.steps.browser.finders.ELEMENT_FINDERS.iteritems', 'ELEMENT_FINDERS.iteritems', ([], {}), '()\n', (3956, 3958), False, 'from salad.steps.browser.finders import ELEMENT_FINDERS, LINK_FINDERS, ELEMENT_THING_STRING, LINK_THING_STRING, PICK_EXPRESSION, _get_visible_element\n'), ((1421, 1517), 'lettuce... |
import neuro
import pickle
import os.path
import numpy as np
import matplotlib.pyplot as plt
import os
import data_collector
import time
import datetime
earth_population = 8000
zero_human = 1/(earth_population*2)
doomsday = 1735689600
max_gini_index = 70
min_lat = -90
max_lat = 90
min_lng = -180
max_l... | [
"pickle.dump",
"numpy.argmax",
"data_collector.Country_info_collector",
"numpy.asfarray",
"os.path.isfile",
"pickle.load",
"neuro.NeuralNetwork",
"datetime.datetime.strptime",
"os.listdir"
] | [((382, 413), 'os.listdir', 'os.listdir', (['covid_reports_files'], {}), '(covid_reports_files)\n', (392, 413), False, 'import os\n'), ((681, 711), 'os.path.isfile', 'os.path.isfile', (['"""neuro.pickle"""'], {}), "('neuro.pickle')\n", (695, 711), False, 'import os\n'), ((2943, 2967), 'numpy.asfarray', 'np.asfarray', (... |
import numpy as np
import pandas as pd
import pytest
from sklearn.ensemble import ExtraTreesClassifier, RandomForestClassifier
from sklearn.base import ClassifierMixin
from sklearn.pipeline import Pipeline
from poniard import PoniardClassifier
def test_add():
clf = PoniardClassifier()
clf.add_estimators([Ext... | [
"sklearn.ensemble.RandomForestClassifier",
"poniard.PoniardClassifier",
"sklearn.ensemble.ExtraTreesClassifier",
"numpy.array",
"pytest.mark.parametrize"
] | [((1228, 1337), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""include_preprocessor,output_type"""', '[(True, Pipeline), (False, ClassifierMixin)]'], {}), "('include_preprocessor,output_type', [(True,\n Pipeline), (False, ClassifierMixin)])\n", (1251, 1337), False, 'import pytest\n'), ((273, 292), 'poni... |
import pytest
from loslassa._loslassa import LoslassaProject, GitPorcelainPorcelain
class TestGitIntegration(object):
@pytest.mark.usefixtures("work_in_empty_tmpdir")
def test_local_repo(self):
lp = LoslassaProject("test")
lp.create_project()
gpp = GitPorcelainPorcelain(lp.inputContai... | [
"loslassa._loslassa.GitPorcelainPorcelain",
"pytest.mark.usefixtures",
"loslassa._loslassa.LoslassaProject"
] | [((126, 173), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""work_in_empty_tmpdir"""'], {}), "('work_in_empty_tmpdir')\n", (149, 173), False, 'import pytest\n'), ((383, 430), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""work_in_empty_tmpdir"""'], {}), "('work_in_empty_tmpdir')\n", (406, 430)... |
#!/usr/bin/python3
from imaplib import IMAP4_SSL
import ssl
import requests
import time
from config import *
context = ssl.SSLContext(ssl.PROTOCOL_TLS)
| [
"ssl.SSLContext"
] | [((119, 151), 'ssl.SSLContext', 'ssl.SSLContext', (['ssl.PROTOCOL_TLS'], {}), '(ssl.PROTOCOL_TLS)\n', (133, 151), False, 'import ssl\n')] |
import numpy as np
import torch
from torch.autograd import Variable
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde, norm
from torch.distributions import multivariate_normal
from tqdm import tqdm
# ## debugging
def numpy_p(x):
return 1/3 * norm.pdf(x, -2, 1) + 2/3 * norm.pdf(x, 2, 1)
def nump... | [
"torch.sqrt",
"matplotlib.pyplot.figure",
"numpy.arange",
"torch.median",
"torch.dist",
"torch.exp",
"torch.Tensor",
"torch.zeros",
"torch.matmul",
"torch.mean",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylim",
"torch.autograd.Variable",
"matplotlib.pyplot.legend",
"torch.norm",
"ma... | [((576, 596), 'torch.Tensor', 'torch.Tensor', (['[0, 0]'], {}), '([0, 0])\n', (588, 596), False, 'import torch\n'), ((614, 644), 'torch.tensor', 'torch.tensor', (['[[5, 2], [2, 1]]'], {}), '([[5, 2], [2, 1]])\n', (626, 644), False, 'import torch\n'), ((656, 685), 'scipy.stats.norm.pdf', 'norm.pdf', (['x', 'mean', 'cova... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import gzip
import time
from multiprocessing import cpu_count, Queue, Process, current_process
import logging
import re
import os.path
from db.model import Block
from db.helper import setup_connection
from netaddr import iprange_to_cidrs
import math
VERS... | [
"gzip.open",
"argparse.ArgumentParser",
"multiprocessing.current_process",
"logging.StreamHandler",
"netaddr.iprange_to_cidrs",
"time.time",
"logging.Formatter",
"re.findall",
"db.helper.setup_connection",
"multiprocessing.Queue",
"multiprocessing.Process",
"db.model.Block",
"logging.getLogg... | [((514, 525), 'multiprocessing.cpu_count', 'cpu_count', ([], {}), '()\n', (523, 525), False, 'from multiprocessing import cpu_count, Queue, Process, current_process\n'), ((841, 871), 'logging.getLogger', 'logging.getLogger', (['"""create_db"""'], {}), "('create_db')\n", (858, 871), False, 'import logging\n'), ((954, 98... |
import numpy as np
import numba
from typing import List, Callable
from scipy.constants import speed_of_light
from divergence_approx import div_vec_approx, gradient_vec
"""Adams-Bashforth 2-step method coeffs"""
adams_bashforth2_c0: float = 3. / 2.
adams_bashforth2_c1: float = -1. / 2.
"""Adams-Bashforth 3-step method... | [
"numpy.abs",
"numpy.ceil",
"numpy.floor",
"numpy.zeros",
"numpy.array",
"numpy.arange",
"numba.jit",
"numpy.exp",
"numpy.round"
] | [((901, 952), 'numba.jit', 'numba.jit', ([], {'nopython': '(True)', 'parallel': '(True)', 'nogil': '(True)'}), '(nopython=True, parallel=True, nogil=True)\n', (910, 952), False, 'import numba\n'), ((1421, 1472), 'numba.jit', 'numba.jit', ([], {'nopython': '(True)', 'parallel': '(True)', 'nogil': '(True)'}), '(nopython=... |
from typing import Tuple, cast
import torch
from torch import Tensor, nn
from torchtext.legacy.data import Field
class MyClassifier(nn.Module):
def __init__(self, emb_dim: int, v_size: int, max_length: int, class_num: int, text_field: Field = None):
super().__init__()
self.embed = nn.Embedding(v_... | [
"torch.mean",
"torch.nn.Dropout",
"torch.nn.Tanh",
"torch.nn.Embedding",
"torch.nn.BatchNorm1d",
"torch.exp",
"torch.nn.Linear",
"torch.zeros"
] | [((305, 334), 'torch.nn.Embedding', 'nn.Embedding', (['v_size', 'emb_dim'], {}), '(v_size, emb_dim)\n', (317, 334), False, 'from torch import Tensor, nn\n'), ((447, 483), 'torch.nn.Linear', 'nn.Linear', (['(emb_dim * max_length)', '(508)'], {}), '(emb_dim * max_length, 508)\n', (456, 483), False, 'from torch import Ten... |
"""Tests for OpenWeatherMap utils."""
import datetime as dt
from openweathermap_client.utils import dt_from_timestamp
class TestUtils():
"""Utils tests."""
def test_utils_dt_from_timestamp(self):
"""Tests from timestamp conversion."""
# with timezone awareness
dt_utcnow = dt.dateti... | [
"openweathermap_client.utils.dt_from_timestamp",
"datetime.datetime.now",
"datetime.datetime.utcnow"
] | [((598, 615), 'datetime.datetime.now', 'dt.datetime.now', ([], {}), '()\n', (613, 615), True, 'import datetime as dt\n'), ((421, 472), 'openweathermap_client.utils.dt_from_timestamp', 'dt_from_timestamp', (['ts_utcnow'], {'ts_tz': 'dt.timezone.utc'}), '(ts_utcnow, ts_tz=dt.timezone.utc)\n', (438, 472), False, 'from ope... |
# -*- coding: utf-8 -*-
from orangengine.dispatcher import dispatch
from orangengine import utils
import logging
__all__ = ['dispatch', 'utils']
# Set default logging handler to avoid "No handler found" warnings.
try:
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
... | [
"logging.getLogger",
"logging.NullHandler"
] | [((408, 421), 'logging.NullHandler', 'NullHandler', ([], {}), '()\n', (419, 421), False, 'from logging import NullHandler\n'), ((369, 396), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (386, 396), False, 'import logging\n')] |
from convert_dna_to_rna import convert_dna_to_rna
def test_convert_tyrosine_to_uracil() -> None:
result = convert_dna_to_rna('GCAT')
assert result == 'GCAU'
def test_convert_tyrosine_to_uracil_multiple_instances() -> None:
result = convert_dna_to_rna('GCATTA')
assert result == 'GCAUUA'
def test_co... | [
"convert_dna_to_rna.convert_dna_to_rna"
] | [((112, 138), 'convert_dna_to_rna.convert_dna_to_rna', 'convert_dna_to_rna', (['"""GCAT"""'], {}), "('GCAT')\n", (130, 138), False, 'from convert_dna_to_rna import convert_dna_to_rna\n'), ((248, 276), 'convert_dna_to_rna.convert_dna_to_rna', 'convert_dna_to_rna', (['"""GCATTA"""'], {}), "('GCATTA')\n", (266, 276), Fals... |
#--------------------------------- utils.py file ---------------------------------------#
"""
This file contains utility functions and classes that support the TBNN-s class.
This includes cleaning and processing functions.
"""
# ------------ Import statements
import os
import timeit
import numpy as np
from t... | [
"numpy.trace",
"tensorflow.reduce_sum",
"numpy.sum",
"numpy.amin",
"numpy.abs",
"tensorflow.maximum",
"numpy.argmin",
"numpy.argsort",
"numpy.arange",
"numpy.linalg.norm",
"numpy.diag",
"numpy.zeros_like",
"numpy.transpose",
"numpy.linalg.eig",
"tensorflow.minimum",
"numpy.random.shuff... | [((1223, 1241), 'numpy.arange', 'np.arange', (['n_total'], {}), '(n_total)\n', (1232, 1241), True, 'import numpy as np\n'), ((1315, 1341), 'numpy.random.shuffle', 'np.random.shuffle', (['idx_tot'], {}), '(idx_tot)\n', (1332, 1341), True, 'import numpy as np\n'), ((4838, 4860), 'timeit.default_timer', 'timeit.default_ti... |
# Generated by Django 3.2 on 2021-04-17 08:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Employee', '0014_auto_20210416_1809'),
]
operations = [
migrations.AlterField(
model_name='rating',
name='note',
... | [
"django.db.models.CharField"
] | [((333, 376), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(200)', 'null': '(True)'}), '(max_length=200, null=True)\n', (349, 376), False, 'from django.db import migrations, models\n')] |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 17 17:43:51 2020
@author: emc1977
"""
# Energy of the system can be found as
# 1/2*kb*(sqrt(x1^2+(Lb+x2)^2)-Lb)^2
# 1/2*ka*(sqrt(x1^2+(La-x2)^2)-La)^2
# -F1x1-F2x2
import sympy
import numpy as np
x,y = sympy.symbols('x,y')
#need the following to create fun... | [
"sympy.symbols",
"numpy.empty",
"sympy.utilities.lambdify.lambdify",
"sympy.Matrix",
"numpy.shape",
"numpy.append",
"sympy.init_printing",
"sympy.hessian",
"numpy.array",
"numpy.linalg.norm"
] | [((263, 283), 'sympy.symbols', 'sympy.symbols', (['"""x,y"""'], {}), "('x,y')\n", (276, 283), False, 'import sympy\n'), ((494, 509), 'sympy.init_printing', 'init_printing', ([], {}), '()\n', (507, 509), False, 'from sympy import symbols, Matrix, Function, simplify, exp, hessian, solve, init_printing\n'), ((563, 577), '... |
import tensorflow as tf
import tensorflow.keras.layers as KL
from models.fcos import fcos_head_graph
from models.fpn import fpn_graph
from models.protonet import protonet_graph
def BlendMask(cfg):
"""return BlendMask as keras model
Arguments:
cfg:
"""
input_images = KL.Input(shape=[cfg.DATA.... | [
"models.fcos.fcos_head_graph",
"tensorflow.keras.layers.Conv2D",
"models.protonet.protonet_graph",
"models.fpn.fpn_graph",
"tensorflow.constant",
"tensorflow.concat",
"tensorflow.keras.Model",
"tensorflow.cast",
"tensorflow.divide",
"tensorflow.keras.layers.Input"
] | [((295, 404), 'tensorflow.keras.layers.Input', 'KL.Input', ([], {'shape': '[cfg.DATA.IMAGE_SIZE, cfg.DATA.IMAGE_SIZE, cfg.DATA.IMAGE_CHANNELS]', 'name': '"""input_images"""'}), "(shape=[cfg.DATA.IMAGE_SIZE, cfg.DATA.IMAGE_SIZE, cfg.DATA.\n IMAGE_CHANNELS], name='input_images')\n", (303, 404), True, 'import tensorflo... |
from datetime import datetime
from binance.client import Client
# Add Api key and secret
client = Client('CLIENT KEY', 'CLIENT SECRET')
# Set start balance
Balance = {
'EUR' : 270,
'BTC' : 0.00171993
}
# Add all pairs to analyse trades for
crypto_pairs_to_analyse = {
'BTCEUR',
'BTCBUSD',
'ETHEUR'... | [
"binance.client.Client"
] | [((99, 136), 'binance.client.Client', 'Client', (['"""CLIENT KEY"""', '"""CLIENT SECRET"""'], {}), "('CLIENT KEY', 'CLIENT SECRET')\n", (105, 136), False, 'from binance.client import Client\n')] |
# -*- coding: utf-8 -*-
# snapshottest: v1 - https://goo.gl/zC4yUc
from __future__ import unicode_literals
from snapshottest import Snapshot
snapshots = Snapshot()
snapshots['TestCase01PostVerificationDetailsAPITestCase::test_case status'] = 400
snapshots['TestCase01PostVerificationDetailsAPITestCase::test_case bo... | [
"snapshottest.Snapshot"
] | [((156, 166), 'snapshottest.Snapshot', 'Snapshot', ([], {}), '()\n', (164, 166), False, 'from snapshottest import Snapshot\n')] |
import random
POSITIVE_ANSWERS = ['Хорошо', 'Поняла', 'Отлично', 'Поняла Вас', 'Ясно', 'Понятно', 'Записала']
def add_positive_answer(text):
return random.choice(POSITIVE_ANSWERS) + '. ' + text
| [
"random.choice"
] | [((155, 186), 'random.choice', 'random.choice', (['POSITIVE_ANSWERS'], {}), '(POSITIVE_ANSWERS)\n', (168, 186), False, 'import random\n')] |
#
# Implement bill of materials (bom)
import copy
import datetime
import hashlib
import os
import shutil
import socket
import sys
import tempfile
def system_module(mod):
"""A simple way to determine if a module is a system module"""
try:
return "lib/python" in mod.__file__
except AttributeError:
... | [
"sys.modules.items",
"os.path.abspath",
"os.path.getsize",
"hashlib.sha1"
] | [((1180, 1199), 'sys.modules.items', 'sys.modules.items', ([], {}), '()\n', (1197, 1199), False, 'import sys\n'), ((563, 577), 'hashlib.sha1', 'hashlib.sha1', ([], {}), '()\n', (575, 577), False, 'import hashlib\n'), ((2161, 2183), 'os.path.abspath', 'os.path.abspath', (['fname'], {}), '(fname)\n', (2176, 2183), False,... |
# -*- coding: utf-8 -*-
# Copyright 2020 PyePAL authors
#
# 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... | [
"warnings.warn",
"numpy.array"
] | [((4101, 4244), 'warnings.warn', 'warnings.warn', (['"""Only one epsilon value provided,\nwill automatically expand to use the same value in every dimension"""', 'UserWarning'], {}), '(\n """Only one epsilon value provided,\nwill automatically expand to use the same value in every dimension"""\n , UserWarning)\n'... |
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional
__NAMESPACE__ = "NISTSchema-SV-IV-list-NMTOKENS-enumeration-1-NS"
class NistschemaSvIvListNmtokensEnumeration1Type(Enum):
IMPROVED_IS_STANDARDS_ADVENT_XML_THE_RETRIEVE_WITH_C_INVESTIGATION_SPECIFICATIONS_IS_ONLY_INFO_OF_AD... | [
"dataclasses.field"
] | [((4217, 4265), 'dataclasses.field', 'field', ([], {'default': 'None', 'metadata': "{'required': True}"}), "(default=None, metadata={'required': True})\n", (4222, 4265), False, 'from dataclasses import dataclass, field\n')] |
from . import Drawable
from pygame import rect
from pygame import transform
from pygame import math
class Transformable(Drawable.Drawable):
"""
Inherits Drawable
The main parent class to all functional subtype drawn objects. Contains functionality for scaling, rotating, and moving
drawn objects.
pos: s.e;
ima... | [
"pygame.transform.scale",
"pygame.math.Vector2",
"pygame.transform.rotate"
] | [((1452, 1499), 'pygame.math.Vector2', 'math.Vector2', (['self.rect.width', 'self.rect.height'], {}), '(self.rect.width, self.rect.height)\n', (1464, 1499), False, 'from pygame import math\n'), ((2777, 2820), 'pygame.transform.rotate', 'transform.rotate', (['self.image', 'deltaRotation'], {}), '(self.image, deltaRotati... |
import os
import sys
from .utils import READ_PATH, Processor, read_image, save_image, show
def run():
args_1 = ["--file", "-f"]
args_2 = ["--gauss-blur", "-gb"]
args_3 = ["--avg-blur", "-ab"]
args_4 = ["--median-blur", "-mb"]
args_5 = ["--gamma", "-g"]
args_6 = ["--linear", "-l"]
ar... | [
"sys.argv.index",
"os.path.join",
"os.listdir"
] | [((5369, 5390), 'os.listdir', 'os.listdir', (['READ_PATH'], {}), '(READ_PATH)\n', (5379, 5390), False, 'import os\n'), ((5433, 5466), 'os.path.join', 'os.path.join', (['READ_PATH', 'filename'], {}), '(READ_PATH, filename)\n', (5445, 5466), False, 'import os\n'), ((1169, 1194), 'sys.argv.index', 'sys.argv.index', (['arg... |
from ..datastore import db
from ..mailchimp import mc
from datetime import datetime, timezone
from flask_security import UserMixin, RoleMixin
roles_users = db.Table('roles_users',
db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))... | [
"datetime.datetime.now"
] | [((2935, 2961), 'datetime.datetime.now', 'datetime.now', (['timezone.utc'], {}), '(timezone.utc)\n', (2947, 2961), False, 'from datetime import datetime, timezone\n')] |
from django.db import models
from django.db.models import F
class Topic(models.Model):
title = models.CharField(max_length=100)
create_dt = models.DateTimeField('create datetime', auto_now_add=True)
update_dt = models.DateTimeField('update datetime', auto_now=True)
pin = models.BooleanField(
... | [
"django.db.models.TextField",
"django.db.models.CharField",
"django.db.models.ForeignKey",
"django.db.models.BooleanField",
"django.db.models.IntegerField",
"django.db.models.F",
"django.db.models.DateTimeField"
] | [((101, 133), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)'}), '(max_length=100)\n', (117, 133), False, 'from django.db import models\n'), ((151, 209), 'django.db.models.DateTimeField', 'models.DateTimeField', (['"""create datetime"""'], {'auto_now_add': '(True)'}), "('create datetime', ... |
# -*- coding: utf8 -*-
"Workflow related variables"
from uuid import uuid4
from django.db import models
class Workflow(models.Model):
"A workflow"
uuid = models.UUIDField(primary_key=True, default=uuid4, editable=False)
namespace = models.ForeignKey("backend.Namespace", related_name="workflows_relation")... | [
"django.db.models.ForeignKey",
"django.db.models.UUIDField",
"django.db.models.IntegerField",
"django.db.models.CharField"
] | [((165, 230), 'django.db.models.UUIDField', 'models.UUIDField', ([], {'primary_key': '(True)', 'default': 'uuid4', 'editable': '(False)'}), '(primary_key=True, default=uuid4, editable=False)\n', (181, 230), False, 'from django.db import models\n'), ((247, 320), 'django.db.models.ForeignKey', 'models.ForeignKey', (['"""... |
#!/usr/bin/env python3
#
# Copyright (c) 2015, <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list... | [
"empower.core.pnfpserver.PNFPServer.__init__",
"empower.vbspp.vbspconnection.VBSPConnection",
"empower.vbspp.MAC_STATS_TYPE.update",
"tornado.tcpserver.TCPServer.__init__",
"empower.vbspp.MAC_UE_STATS_TYPES.update",
"empower.vbspp.MAC_STATS_REPORT_FREQ.update",
"empower.vbspp.MAC_CELL_STATS_TYPES.update... | [((2662, 2830), 'empower.vbspp.MAC_STATS_TYPE.update', 'MAC_STATS_TYPE.update', (["{'complete': stats_messages_pb2.PRST_COMPLETE_STATS, 'cell':\n stats_messages_pb2.PRST_CELL_STATS, 'ue': stats_messages_pb2.PRST_UE_STATS}"], {}), "({'complete': stats_messages_pb2.PRST_COMPLETE_STATS,\n 'cell': stats_messages_pb2.... |
import os
import re
import requests
import htmlmin
from bs4 import BeautifulSoup
from pony import orm
base = "https://ulisses-regelwiki.de/"
blacklist = [
"/index.php/tde-games-reference-en.html",
"index.php/start.html",
"index.php/kontakt.html",
"index.php/impressum.html",
"index.php/datenschutze... | [
"htmlmin.minify",
"pony.orm.PrimaryKey",
"pony.orm.Database",
"requests.get",
"pony.orm.Optional",
"bs4.BeautifulSoup",
"pony.orm.Required",
"re.sub",
"os.getenv"
] | [((344, 358), 'pony.orm.Database', 'orm.Database', ([], {}), '()\n', (356, 358), False, 'from pony import orm\n'), ((6730, 6748), 'requests.get', 'requests.get', (['base'], {}), '(base)\n', (6742, 6748), False, 'import requests\n'), ((6756, 6787), 'bs4.BeautifulSoup', 'BeautifulSoup', (['res.text', '"""lxml"""'], {}), ... |
#!/usr/bin/env python3
# -*- encoding: utf8 -*-
import json
import subprocess
def list_executables(*command):
command = list(command)
command.append("--no-run")
command.append("--message-format=json")
result = subprocess.run(command, check=True, stdout=subprocess.PIPE)
# convert successive JSON d... | [
"subprocess.run",
"json.loads"
] | [((229, 288), 'subprocess.run', 'subprocess.run', (['command'], {'check': '(True)', 'stdout': 'subprocess.PIPE'}), '(command, check=True, stdout=subprocess.PIPE)\n', (243, 288), False, 'import subprocess\n'), ((471, 489), 'json.loads', 'json.loads', (['stdout'], {}), '(stdout)\n', (481, 489), False, 'import json\n')] |
from fastapi import applications
from fastapi.openapi.docs import get_redoc_html as _get_redoc_html
from fastapi.openapi.docs import get_swagger_ui_html as _get_swagger_ui_html
from fastapi_aad_auth.ui.jinja import Jinja2Templates
from starlette.responses import HTMLResponse
from docserver import config
# TODO: chec... | [
"fastapi.openapi.docs.get_swagger_ui_html",
"starlette.responses.HTMLResponse",
"fastapi.openapi.docs.get_redoc_html",
"fastapi_aad_auth.ui.jinja.Jinja2Templates"
] | [((361, 380), 'fastapi_aad_auth.ui.jinja.Jinja2Templates', 'Jinja2Templates', (['""""""'], {}), "('')\n", (376, 380), False, 'from fastapi_aad_auth.ui.jinja import Jinja2Templates\n'), ((757, 794), 'fastapi.openapi.docs.get_swagger_ui_html', '_get_swagger_ui_html', (['*args'], {}), '(*args, **kwargs)\n', (777, 794), Tr... |
import argparse
parser.add_argument('--reward_freq',type=int,default=-1)
parser.add_argument('--policy', type=str, default='pso_td3')
parser.add_argument('--env', type=str, default='HalfCheetah-v3')
parser.add_argument('--datestamp', action='store_true')
parser.add_argument('--seed', '-s', type=int, default=0)
from u... | [
"utils.logx.setup_logger_kwargs"
] | [((404, 494), 'utils.logx.setup_logger_kwargs', 'setup_logger_kwargs', (['f"""{args.policy}_{args.env}"""', 'args.seed'], {'datestamp': 'args.datestamp'}), "(f'{args.policy}_{args.env}', args.seed, datestamp=args.\n datestamp)\n", (423, 494), False, 'from utils.logx import setup_logger_kwargs\n')] |
# utility.py
"""library of utility functions
Available functions
- file_to_list: makes a list out of the lines of a file
- copy_local_to_remote: copies files from local to remote system
- remote_command: executes a command on a remote system
"""
import subprocess
import os
# local imports
import constants as CONST
#... | [
"os.path.isfile",
"subprocess.call",
"os.listdir"
] | [((1130, 1150), 'os.listdir', 'os.listdir', (['dir_name'], {}), '(dir_name)\n', (1140, 1150), False, 'import os\n'), ((2145, 2187), 'subprocess.call', 'subprocess.call', (["['./ssh-cmd.sh', ip, cmd]"], {}), "(['./ssh-cmd.sh', ip, cmd])\n", (2160, 2187), False, 'import subprocess\n'), ((1239, 1259), 'os.path.isfile', 'o... |
import enum
import os
import re
from typing import Optional, Tuple
import numpy as np
from scipy.ndimage import median_filter
from skimage.io import imread
OCTOPUSLITE_FILEPATTERN = (
"img_channel(?P<channel>[0-9]+)_position(?P<position>[0-9]+)"
"_time(?P<time>[0-9]+)_z(?P<z>[0-9]+)"
)
@enum.unique
class Ch... | [
"numpy.matrix",
"numpy.ravel",
"numpy.zeros",
"re.match",
"numpy.nonzero",
"numpy.min",
"numpy.max",
"numpy.arange",
"numpy.reshape",
"numpy.linalg.inv",
"os.path.split",
"scipy.ndimage.median_filter",
"skimage.io.imread"
] | [((827, 851), 'scipy.ndimage.median_filter', 'median_filter', (['x'], {'size': '(2)'}), '(x, size=2)\n', (840, 851), False, 'from scipy.ndimage import median_filter\n'), ((2153, 2191), 'numpy.zeros', 'np.zeros', (['(x.shape[0] * x.shape[1], 6)'], {}), '((x.shape[0] * x.shape[1], 6))\n', (2161, 2191), True, 'import nump... |
from django.shortcuts import render, render_to_response, RequestContext
from gowan.forms import PieceForm, GlazeLookupForm, DocumentationForm, ConditionChoiceForm, ExhibitionForm, HeathLineLookupForm, LogoForm, MakerLookupForm, MaterialLookupForm, MethodLookupForm, PublicationForm, SetCollectionForm
def home(request):... | [
"gowan.forms.DocumentationForm",
"gowan.forms.MaterialLookupForm",
"gowan.forms.LogoForm",
"gowan.forms.SetCollectionForm",
"gowan.forms.ExhibitionForm",
"gowan.forms.MakerLookupForm",
"gowan.forms.MethodLookupForm",
"gowan.forms.GlazeLookupForm",
"django.shortcuts.RequestContext",
"gowan.forms.Co... | [((333, 364), 'gowan.forms.PieceForm', 'PieceForm', (['(request.POST or None)'], {}), '(request.POST or None)\n', (342, 364), False, 'from gowan.forms import PieceForm, GlazeLookupForm, DocumentationForm, ConditionChoiceForm, ExhibitionForm, HeathLineLookupForm, LogoForm, MakerLookupForm, MaterialLookupForm, MethodLook... |
"""
Copyright (C) 2019 <NAME>, ETH Zurich
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distri... | [
"functools.partial",
"rpy2.robjects.packages.importr",
"rpy2.robjects.numpy2ri.activate",
"numpy.std",
"rpy2.robjects.pandas2ri.activate",
"numpy.expand_dims",
"numpy.mean",
"numpy.array",
"sklearn.decomposition.PCA",
"numpy.where",
"numpy.column_stack",
"numpy.reshape",
"rpy2.robjects.Formu... | [((2039, 2059), 'rpy2.robjects.packages.importr', 'importr', (['"""causaldrf"""'], {}), "('causaldrf')\n", (2046, 2059), False, 'from rpy2.robjects.packages import importr\n'), ((2212, 2231), 'rpy2.robjects.numpy2ri.activate', 'numpy2ri.activate', ([], {}), '()\n', (2229, 2231), False, 'from rpy2.robjects import numpy2... |
# from django.contrib import admin
# Register your models here.
from django.contrib import admin
from .models import Program
from .models import Profile, Affirmations, InspirationalQuotes, Dailyquote, Reward
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from django.contrib... | [
"django.contrib.admin.site.register",
"django.contrib.admin.site.unregister"
] | [((630, 671), 'django.contrib.admin.site.register', 'admin.site.register', (['Program', 'ProgramList'], {}), '(Program, ProgramList)\n', (649, 671), False, 'from django.contrib import admin\n'), ((1191, 1218), 'django.contrib.admin.site.unregister', 'admin.site.unregister', (['User'], {}), '(User)\n', (1212, 1218), Fal... |
import torch
import torch.nn as nn
def cosine_dist(x, y):
'''
:param x: torch.tensor, 2d
:param y: torch.tensor, 2d
:return:
'''
bs1 = x.size()[0]
bs2 = y.size()[0]
frac_up = torch.matmul(x, y.transpose(0, 1))
frac_down = (torch.sqrt(torch.sum(torch.pow(x, 2), 1))).view(bs1, 1).r... | [
"torch.ones_like",
"torch.nn.MarginRankingLoss",
"torch.sort",
"torch.pow"
] | [((3069, 3130), 'torch.nn.MarginRankingLoss', 'nn.MarginRankingLoss', ([], {'margin': 'margin', 'reduction': 'self.reduction'}), '(margin=margin, reduction=self.reduction)\n', (3089, 3130), True, 'import torch.nn as nn\n'), ((1629, 1717), 'torch.sort', 'torch.sort', (['(mat_distance + -9999999.0 * (1 - mat_similarity))... |
import pathlib
import nox
DJANGO_VERSIONS = ["3.1", "3.2"]
LOCATIONS = ["deprecated_field", "tests"]
def install(*deps: str, session) -> None:
"""
Helper to install dependencies constrained by Poetry's lock file.
"""
tmpdir = pathlib.Path(session._runner.envdir) / "tmp"
tmpdir.mkdir(exist_ok=Tr... | [
"pathlib.Path",
"nox.session",
"nox.parametrize"
] | [((661, 674), 'nox.session', 'nox.session', ([], {}), '()\n', (672, 674), False, 'import nox\n'), ((676, 726), 'nox.parametrize', 'nox.parametrize', (['"""django_version"""', 'DJANGO_VERSIONS'], {}), "('django_version', DJANGO_VERSIONS)\n", (691, 726), False, 'import nox\n'), ((913, 926), 'nox.session', 'nox.session', ... |
from inspect import ismethod
import factory
from factory.alchemy import SQLAlchemyModelFactory
from factory import fuzzy
from ichnaea.constants import (
CELL_MIN_ACCURACY,
LAC_MIN_ACCURACY,
WIFI_MIN_ACCURACY,
)
from ichnaea.models import (
Cell,
CellArea,
CellBlacklist,
CellObservation,
... | [
"factory.fuzzy.FuzzyInteger",
"inspect.ismethod",
"factory.fuzzy.random.randint"
] | [((1323, 1351), 'factory.fuzzy.FuzzyInteger', 'fuzzy.FuzzyInteger', (['(100)', '(999)'], {}), '(100, 999)\n', (1341, 1351), False, 'from factory import fuzzy\n'), ((1521, 1551), 'factory.fuzzy.FuzzyInteger', 'fuzzy.FuzzyInteger', (['(1000)', '(9999)'], {}), '(1000, 9999)\n', (1539, 1551), False, 'from factory import fu... |
import models.alexnet as alexnet
import models.vgg16 as vgg16
def load_model(arch, code_length):
"""
Load cnn model.
Args
arch(str): CNN model name.
code_length(int): Hash code length.
Returns
model(torch.nn.Module): CNN model.
"""
if arch == 'alexnet':
model =... | [
"models.alexnet.load_model",
"models.vgg16.load_model"
] | [((321, 352), 'models.alexnet.load_model', 'alexnet.load_model', (['code_length'], {}), '(code_length)\n', (339, 352), True, 'import models.alexnet as alexnet\n'), ((395, 424), 'models.vgg16.load_model', 'vgg16.load_model', (['code_length'], {}), '(code_length)\n', (411, 424), True, 'import models.vgg16 as vgg16\n')] |
import unittest
from ..fsf import *
import numpy as np
from numpy.testing import assert_array_equal, assert_array_almost_equal
class TestFSF(unittest.TestCase):
def setUp(self) -> None:
self.A = np.array([[0, 1], [-2, -3]])
self.b = np.array([[0], [1]])
self.poles = np.array([-3, -4])
... | [
"numpy.poly",
"numpy.testing.assert_array_equal",
"numpy.array"
] | [((210, 238), 'numpy.array', 'np.array', (['[[0, 1], [-2, -3]]'], {}), '([[0, 1], [-2, -3]])\n', (218, 238), True, 'import numpy as np\n'), ((256, 276), 'numpy.array', 'np.array', (['[[0], [1]]'], {}), '([[0], [1]])\n', (264, 276), True, 'import numpy as np\n'), ((298, 316), 'numpy.array', 'np.array', (['[-3, -4]'], {}... |
# -*- coding: UTF-8 -*-
import CONSTANT
import time
from wrapper import client as CLIENT
from wrapper import builder as BUILDER
from tools import load_json
from wrapper import keypair
def all_in_one(activate_the_distributor=True, activate_accounts=True, send_native_asset_to_accounts=True, issue_asset=True, do_trust=T... | [
"wrapper.client.Client",
"wrapper.builder.Builder",
"random.random",
"tools.load_json.file2json",
"CONSTANT.Constant"
] | [((386, 411), 'CONSTANT.Constant', 'CONSTANT.Constant', (['"""test"""'], {}), "('test')\n", (403, 411), False, 'import CONSTANT\n'), ((423, 483), 'wrapper.client.Client', 'CLIENT.Client', (['constant.SEED'], {'api_server': 'constant.API_SERVER'}), '(constant.SEED, api_server=constant.API_SERVER)\n', (436, 483), True, '... |
import requests
from logger import logger, pp
from config import (SLACK_CHANNEL, SLACK_API_TOKEN)
import json
POST_URL = 'https://slack.com/api/chat.postMessage'
def send_to_slack_channel(text, channel):
"""
this method post message to slack channel
"""
payload = {
'token': SLACK_API_TOKEN,
... | [
"logger.logger.info",
"requests.post",
"json.dumps"
] | [((478, 498), 'logger.logger.info', 'logger.info', (['payload'], {}), '(payload)\n', (489, 498), False, 'from logger import logger, pp\n'), ((515, 552), 'requests.post', 'requests.post', (['POST_URL'], {'data': 'payload'}), '(POST_URL, data=payload)\n', (528, 552), False, 'import requests\n'), ((972, 992), 'logger.logg... |
import logging
from typing import Any, List, Optional
from fastapi import APIRouter, Depends, Body, File, UploadFile
from antarest.core.config import Config
from antarest.core.jwt import JWTUser
from antarest.core.requests import (
UserHasNotPermissionError,
RequestParameters,
)
from antarest.core.utils.web i... | [
"antarest.core.requests.UserHasNotPermissionError",
"fastapi.Body",
"antarest.core.requests.RequestParameters",
"fastapi.Depends",
"antarest.login.auth.Auth",
"fastapi.File",
"logging.getLogger",
"fastapi.APIRouter"
] | [((544, 571), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (561, 571), False, 'import logging\n'), ((828, 851), 'fastapi.APIRouter', 'APIRouter', ([], {'prefix': '"""/v1"""'}), "(prefix='/v1')\n", (837, 851), False, 'from fastapi import APIRouter, Depends, Body, File, UploadFile\n'), ((... |
from django.shortcuts import render
from electronic_app.models import ElectronicApplication, ElectronicApplicationDocument
from django.http import HttpResponse, FileResponse
from documents import main
from documents.models import DocumentSet, Document
import json
from model_api.auth import login_required
from django.co... | [
"os.mkdir",
"electronic_app.models.ElectronicApplication",
"documents.main.fill_doc",
"electronic_app.main.send_mails",
"os.path.dirname",
"model_api.auth.login_required",
"django.contrib.auth.models.User.objects.filter",
"json.dumps",
"documents.models.DocumentSet.objects.filter",
"os.path.splite... | [((520, 553), 'model_api.auth.login_required', 'login_required', ([], {'strong_auth': '(False)'}), '(strong_auth=False)\n', (534, 553), False, 'from model_api.auth import login_required\n'), ((722, 768), 'documents.models.Document.objects.filter', 'Document.objects.filter', ([], {'doc_set_id': 'doc_set_id'}), '(doc_set... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd
import nltk
from sklearn.preprocessing import LabelEncoder
from nltk.stem import WordNetLemmatizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_selection.univariate_selection import SelectKBest, chi2
from sklearn.linea... | [
"nltk.stem.WordNetLemmatizer",
"sklearn.linear_model.SGDClassifier",
"sklearn.feature_extraction.text.TfidfVectorizer",
"pandas.read_csv",
"sklearn.preprocessing.LabelEncoder",
"sklearn.feature_selection.univariate_selection.SelectKBest",
"sys.setdefaultencoding",
"nltk.tokenize.word_tokenize"
] | [((372, 402), 'sys.setdefaultencoding', 'sys.setdefaultencoding', (['"""UTF8"""'], {}), "('UTF8')\n", (394, 402), False, 'import sys\n'), ((555, 574), 'nltk.stem.WordNetLemmatizer', 'WordNetLemmatizer', ([], {}), '()\n', (572, 574), False, 'from nltk.stem import WordNetLemmatizer\n'), ((848, 878), 'nltk.tokenize.word_t... |
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PointMatcher.__init__ import __appname__
from PointMatcher.widgets import *
from PointMatcher.actions import *
from PointMatcher.data.matching import Matching
from PointMatcher.settings import Settings
from PointMatcher.utils.struct... | [
"PointMatcher.utils.qt.addActions",
"PointMatcher.data.matching.Matching",
"PointMatcher.settings.Settings"
] | [((1089, 1099), 'PointMatcher.settings.Settings', 'Settings', ([], {}), '()\n', (1097, 1099), False, 'from PointMatcher.settings import Settings\n'), ((2884, 3001), 'PointMatcher.utils.qt.addActions', 'addActions', (['self.menus.file', '(a.newProject, a.openImageDir, a.openAnnotDir, a.save, a.export, a.close, a\n .q... |
import sys
import time
import os
import torch
import random
import sklearn
# Ignore sklearn related warnings
import warnings
warnings.filterwarnings("ignore", category=RuntimeWarning)
import numpy as np
import torch.nn as nn
import torchvision.utils as vutils
import torch.optim as optim
import finetune_utils as ftu
i... | [
"wandb.run.save",
"model_utils.compute_val_metrics",
"numpy.random.seed",
"torch.eye",
"utils.calc_topk_accuracy",
"model_3d.DpcRnn",
"model_3d.ImageFetCombiner",
"torch.cat",
"sim_utils.CorrSimHandler",
"torch.cuda.device_count",
"collections.defaultdict",
"sim_utils.AlignSimHandler",
"torc... | [((126, 184), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'RuntimeWarning'}), "('ignore', category=RuntimeWarning)\n", (149, 184), False, 'import warnings\n'), ((480, 510), 'sys.path.append', 'sys.path.append', (['"""../backbone"""'], {}), "('../backbone')\n", (495, 510), False... |
#!/usr/bin/env python
# coding: utf-8
import unittest
from lingobarter import create_app
from lingobarter.utils.shorturl import ShorterURL
class TestShorterUrl(unittest.TestCase):
def create_app(self):
# create_app return a tuple, app object is at index 0
return create_app(config='lingobarter.te... | [
"lingobarter.create_app",
"lingobarter.utils.shorturl.ShorterURL"
] | [((287, 357), 'lingobarter.create_app', 'create_app', ([], {'config': '"""lingobarter.test_settings"""', 'DEBUG': '(False)', 'test': '(True)'}), "(config='lingobarter.test_settings', DEBUG=False, test=True)\n", (297, 357), False, 'from lingobarter import create_app\n'), ((560, 572), 'lingobarter.utils.shorturl.ShorterU... |
# ----------------------------------------------------------------------------
# Copyright [2017] [<NAME> <<EMAIL>> <lem<EMAIL>>]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://ww... | [
"network.WLAN",
"esp.osdebug"
] | [((966, 983), 'esp.osdebug', 'esp.osdebug', (['None'], {}), '(None)\n', (977, 983), False, 'import esp\n'), ((1147, 1175), 'network.WLAN', 'network.WLAN', (['network.STA_IF'], {}), '(network.STA_IF)\n', (1159, 1175), False, 'import network\n')] |
import os
import argparse
import six
import txaio
txaio.use_twisted()
import RPi.GPIO as GPIO
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks
from twisted.internet.error import ReactorNotRunning
from autobahn.util import utcnow
from autobahn.twisted.util import sleep
from au... | [
"RPi.GPIO.setwarnings",
"RPi.GPIO.setmode",
"argparse.ArgumentParser",
"RPi.GPIO.setup",
"os.environ.get",
"autobahn.twisted.wamp.ApplicationRunner",
"autobahn.util.utcnow",
"twisted.internet.reactor.stop",
"txaio.start_logging",
"RPi.GPIO.output",
"autobahn.twisted.util.sleep",
"txaio.use_twi... | [((52, 71), 'txaio.use_twisted', 'txaio.use_twisted', ([], {}), '()\n', (69, 71), False, 'import txaio\n'), ((5256, 5309), 'os.environ.get', 'os.environ.get', (['"""CBURL"""', 'u"""wss://demo.crossbar.io/ws"""'], {}), "('CBURL', u'wss://demo.crossbar.io/ws')\n", (5270, 5309), False, 'import os\n'), ((5322, 5364), 'os.e... |
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
class SliderUniteOptionsAdmin(admin.ModelAdmin):
'''
Compact theme
Default theme
Grid theme
Slider
'''
fieldsets = (
(_('Navigation options'), {
'classes': ('collapse',),
... | [
"django.utils.translation.ugettext_lazy"
] | [((245, 268), 'django.utils.translation.ugettext_lazy', '_', (['"""Navigation options"""'], {}), "('Navigation options')\n", (246, 268), True, 'from django.utils.translation import ugettext_lazy as _\n')] |
from osgeo import gdal, gdalconst, ogr
import os
def polygon_to_raster(
input_raster,
shapefile,
target_raster,
field_name=None
):
"""
Creates a mask for the polygons in shapefile that coincides with the input_raster.
The mask values are set using the 'field_name' attr... | [
"os.makedirs",
"osgeo.ogr.Open",
"osgeo.gdal.RasterizeLayer",
"osgeo.ogr.GetDriverByName",
"os.path.exists",
"osgeo.gdal.Translate",
"osgeo.gdal.Open",
"osgeo.gdal.GetDriverByName"
] | [((1030, 1049), 'osgeo.ogr.Open', 'ogr.Open', (['shapefile'], {}), '(shapefile)\n', (1038, 1049), False, 'from osgeo import gdal, gdalconst, ogr\n'), ((4301, 4338), 'osgeo.ogr.GetDriverByName', 'ogr.GetDriverByName', (['"""ESRI Shapefile"""'], {}), "('ESRI Shapefile')\n", (4320, 4338), False, 'from osgeo import gdal, g... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""=================================================================
@Project : Algorithm_YuweiYin/LeetCode-All-Solution/Python3
@File : LC-1288-Remove-Covered-Intervals.py
@Author : [YuweiYin](https://github.com/YuweiYin)
@Date : 2022-02-20
==========================... | [
"time.process_time"
] | [((2806, 2825), 'time.process_time', 'time.process_time', ([], {}), '()\n', (2823, 2825), False, 'import time\n'), ((2889, 2908), 'time.process_time', 'time.process_time', ([], {}), '()\n', (2906, 2908), False, 'import time\n')] |
import xml.etree.ElementTree as ET
import re
PATH = "./DescriptorRecordSet/DescriptorRecord"
data_path = "/home/tsung/CODE/Information-Retrieval/Whole_MESH_keyword.txt"
class xmldata:
def __init__(self, title=None, content=None, char_count=None, word_count=None, sentence_count=None, score=None):
self.tit... | [
"xml.etree.ElementTree.fromstring"
] | [((865, 914), 'xml.etree.ElementTree.fromstring', 'ET.fromstring', (["('<fake>' + fileContent + '</fake>')"], {}), "('<fake>' + fileContent + '</fake>')\n", (878, 914), True, 'import xml.etree.ElementTree as ET\n')] |
# <NAME>/Feb 2022
import numpy as np
from numpy import linalg as LA
import matplotlib
import matplotlib.dates
import datetime
from alive_progress import alive_bar
from floodsystem.datafetcher import fetch_measure_levels
from floodsystem.station import MonitoringStation
from floodsystem.flood import stations_level_ove... | [
"floodsystem.station.inconsistent_typical_range_stations",
"floodsystem.flood.stations_level_over_threshold",
"numpy.poly1d",
"numpy.polyfit",
"numpy.array",
"datetime.timedelta",
"matplotlib.dates.date2num"
] | [((486, 518), 'matplotlib.dates.date2num', 'matplotlib.dates.date2num', (['dates'], {}), '(dates)\n', (511, 518), False, 'import matplotlib\n'), ((1851, 1896), 'floodsystem.station.inconsistent_typical_range_stations', 'inconsistent_typical_range_stations', (['stations'], {}), '(stations)\n', (1886, 1896), False, 'from... |
import unittest
from nymms.utils import commands
class TestCommands(unittest.TestCase):
def test_execute_failure(self):
with self.assertRaises(commands.CommandFailure):
# Non-existant command
commands.execute('xxxps auwwwx', 10)
def test_execute_timeout(self):
with se... | [
"nymms.utils.commands.execute"
] | [((456, 489), 'nymms.utils.commands.execute', 'commands.execute', (['"""echo test"""', '(10)'], {}), "('echo test', 10)\n", (472, 489), False, 'from nymms.utils import commands\n'), ((231, 267), 'nymms.utils.commands.execute', 'commands.execute', (['"""xxxps auwwwx"""', '(10)'], {}), "('xxxps auwwwx', 10)\n", (247, 267... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
game.py
(c) <NAME> 25 December, 2016
An object representing a game of cribbage between two CribbagePlayers.
'''
from __future__ import absolute_import, print_function
import random
from cribbage.round import Round
class Game(object):
'''
An object represent... | [
"random.randrange",
"cribbage.round.Round"
] | [((802, 821), 'random.randrange', 'random.randrange', (['(2)'], {}), '(2)\n', (818, 821), False, 'import random\n'), ((2010, 2052), 'cribbage.round.Round', 'Round', (['self', 'self.players', 'self.dealer_idx'], {}), '(self, self.players, self.dealer_idx)\n', (2015, 2052), False, 'from cribbage.round import Round\n')] |
# Generated by Django 2.0.13 on 2020-07-21 13:18
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('con... | [
"django.db.models.TextField",
"django.db.models.URLField",
"django.db.migrations.swappable_dependency",
"django.db.models.ManyToManyField",
"django.db.models.ForeignKey",
"django.db.models.CharField",
"django.db.models.PositiveIntegerField",
"django.db.models.BooleanField",
"django.db.models.AutoFie... | [((248, 305), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (279, 305), False, 'from django.db import migrations, models\n'), ((6341, 6449), 'django.db.migrations.AlterUniqueTogether', 'migrations.AlterUniqueTogether',... |
import requests
import threading
import time
from bsedata.bse import BSE
mutex=threading.Lock()
stock_api=BSE()
def handler(response):
query=response['result'][0]['message']['text']
sender=response['result'][0]['message']['chat']['id']
query=query.split(" ")
if len(query)!=2:
return
if query[0]=="/price" an... | [
"threading.Thread",
"bsedata.bse.BSE",
"time.sleep",
"threading.Lock",
"requests.post"
] | [((81, 97), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (95, 97), False, 'import threading\n'), ((108, 113), 'bsedata.bse.BSE', 'BSE', ([], {}), '()\n', (111, 113), False, 'from bsedata.bse import BSE\n'), ((720, 824), 'requests.post', 'requests.post', (['"""https://api.telegram.org/apikey/sendMessage"""'], {... |
import os
import os.path as osp
import sys
import torch
import numpy as np
import scipy.sparse as sp
from torch.utils.data import DataLoader
from torch_geometric.nn import Node2Vec
from torch_geometric.utils import from_scipy_sparse_matrix
from torch_geometric.data import Data
from scipy import io
from tqdm import tqdm... | [
"json.dump",
"tqdm.tqdm",
"torch_geometric.nn.Node2Vec",
"torch_geometric.data.Data",
"torch_geometric.utils.from_scipy_sparse_matrix",
"torch.cuda.is_available",
"torch.no_grad",
"os.path.join"
] | [((1512, 1539), 'torch_geometric.utils.from_scipy_sparse_matrix', 'from_scipy_sparse_matrix', (['N'], {}), '(N)\n', (1536, 1539), False, 'from torch_geometric.utils import from_scipy_sparse_matrix\n'), ((1686, 1716), 'torch_geometric.data.Data', 'Data', ([], {'x': 'x', 'edge_index': 'edge_idx'}), '(x=x, edge_index=edge... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import numpy as np
import numpy.ma as ma
import itertools
class TPM:
"""
A collecton of static methods to calculate transition probability matrix of a
descrete markov process from an unbalanced panel data
"""
@staticmethod
def f(x):
... | [
"numpy.divide",
"numpy.sum",
"numpy.unique",
"numpy.zeros",
"numpy.ma.masked_invalid",
"numpy.isnan",
"numpy.argsort",
"numpy.apply_along_axis",
"numpy.array",
"numpy.array_split",
"numpy.random.shuffle"
] | [((12699, 12723), 'numpy.random.shuffle', 'np.random.shuffle', (['array'], {}), '(array)\n', (12716, 12723), True, 'import numpy as np\n'), ((13262, 13286), 'numpy.random.shuffle', 'np.random.shuffle', (['array'], {}), '(array)\n', (13279, 13286), True, 'import numpy as np\n'), ((1869, 1886), 'numpy.argsort', 'np.argso... |
import time
from utils.utils import log
def run_policy_loop(agent, env, max_num_episodes, fps=7, deterministic=False):
"""Execute the policy and render onto the screen, using the standard agent interface."""
agent.initialize()
episode_rewards = []
for _ in range(max_num_episodes):
obs, done ... | [
"time.time",
"time.sleep"
] | [((772, 787), 'time.sleep', 'time.sleep', (['(0.2)'], {}), '(0.2)\n', (782, 787), False, 'import time\n'), ((413, 424), 'time.time', 'time.time', ([], {}), '()\n', (422, 424), False, 'import time\n'), ((493, 514), 'time.sleep', 'time.sleep', (['(1.0 / fps)'], {}), '(1.0 / fps)\n', (503, 514), False, 'import time\n'), (... |
# coding: utf-8
# In[20]:
from keras import applications
from keras.preprocessing.image import ImageDataGenerator
from keras import optimizers
from keras.models import Sequential, Model
from keras.layers import Dropout, Flatten, Dense, GlobalAveragePooling2D
from keras import backend as k
from keras.callbacks imp... | [
"keras.preprocessing.image.ImageDataGenerator",
"os.mkdir",
"zipfile.ZipFile",
"keras.callbacks.ModelCheckpoint",
"keras.layers.Dropout",
"read_data.read_ids",
"os.path.exists",
"keras.layers.Flatten",
"keras.models.Model",
"read_data.read_text_data",
"keras.layers.Dense",
"keras.applications.... | [((898, 924), 'read_data.read_text_data', 'read_data.read_text_data', ([], {}), '()\n', (922, 924), False, 'import read_data\n'), ((943, 963), 'read_data.read_ids', 'read_data.read_ids', ([], {}), '()\n', (961, 963), False, 'import read_data\n'), ((1806, 1908), 'keras.applications.VGG16', 'applications.VGG16', ([], {'w... |
from __future__ import absolute_import
import os
import sys
common_utils_path = os.path.join(
"/", *os.path.abspath(__file__).split("/")[:-4], "utils")
sys.path.append(common_utils_path)
from yaml_wrapper import read_yaml
from misc import AttrDict
from comm import CommunicatorWrapper
from gan_losses import Relativi... | [
"sys.path.append",
"os.path.abspath"
] | [((156, 190), 'sys.path.append', 'sys.path.append', (['common_utils_path'], {}), '(common_utils_path)\n', (171, 190), False, 'import sys\n'), ((104, 129), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (119, 129), False, 'import os\n')] |
import numpy as np
import gym
import time
from matplotlib import pyplot as plt
import sys, os
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)),'../../'))
from fetch_cam import FetchDiscreteEnv
# from fetch_cam import FetchCameraEnv
from fetch_cam import FetchDiscreteCamEnv
from fetch_cam.fetch_di... | [
"os.makedirs",
"cv2.imwrite",
"os.path.dirname",
"os.path.exists",
"time.time",
"fetch_cam.FetchDiscreteCamEnv",
"PIL.Image.fromarray",
"shutil.rmtree",
"fetch_cam.FetchDiscreteEnv"
] | [((532, 556), 'os.path.exists', 'os.path.exists', (['dir_name'], {}), '(dir_name)\n', (546, 556), False, 'import os, shutil\n'), ((594, 615), 'os.makedirs', 'os.makedirs', (['dir_name'], {}), '(dir_name)\n', (605, 615), False, 'import os, shutil\n'), ((701, 753), 'fetch_cam.FetchDiscreteEnv', 'FetchDiscreteEnv', ([], {... |
import html2md
"""
User needs to change the two paths here or else it wont work.
"""
path = "Path/To/Your/HTML"
def html_to_md():
#opens your html file
html = open(path, "r").read()
#converts the html file to a md file
md = html2md.convert(html)
#Path where your md file is saved
md_path = "Pa... | [
"html2md.convert"
] | [((243, 264), 'html2md.convert', 'html2md.convert', (['html'], {}), '(html)\n', (258, 264), False, 'import html2md\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Xtreme RGB Colourspace
======================
Defines the *Xtreme RGB* colourspace:
- :attr:`XTREME_RGB_COLOURSPACE`.
See Also
--------
`RGB Colourspaces IPython Notebook
<http://nbviewer.ipython.org/github/colour-science/colour-ipython/blob/master/notebooks/model... | [
"colour.models.normalised_primary_matrix",
"colour.models.RGB_Colourspace",
"colour.colorimetry.ILLUMINANTS.get",
"numpy.linalg.inv",
"numpy.array"
] | [((1215, 1249), 'numpy.array', 'np.array', (['[[1, 0], [0, 1], [0, 0]]'], {}), '([[1, 0], [0, 1], [0, 0]])\n', (1223, 1249), True, 'import numpy as np\n'), ((1549, 1619), 'colour.models.normalised_primary_matrix', 'normalised_primary_matrix', (['XTREME_RGB_PRIMARIES', 'XTREME_RGB_WHITEPOINT'], {}), '(XTREME_RGB_PRIMARI... |
#-------------------------------------------------------------------------------------------------------------
## Import Statements
#-------------------------------------------------------------------------------------------------------------
from __future__ import print_function
import sys
import os
import argparse
i... | [
"requests.get",
"fuzzywuzzy.process.extract",
"json.load",
"sys.exit"
] | [((3403, 3453), 'fuzzywuzzy.process.extract', 'process.extract', (['searchTerm', 'packages'], {'limit': '(10000)'}), '(searchTerm, packages, limit=10000)\n', (3418, 3453), False, 'from fuzzywuzzy import process\n'), ((6753, 6800), 'fuzzywuzzy.process.extract', 'process.extract', (['filterTerm', 'tempSet'], {'limit': '(... |
import os
import sys
import logging
from flask import Flask, session, render_template
from datetime import timedelta, datetime
from logging.handlers import RotatingFileHandler, SMTPHandler
from helpers.config_reader import (FLASK_DEBUG, GLOBAL_PATH, SECRET_KEY,
SUPPORT_EMAIL, SERVER_N... | [
"logging.handlers.SMTPHandler",
"flask.Flask",
"logging.Formatter",
"datetime.timedelta",
"flask.render_template",
"datetime.datetime.now",
"logging.handlers.RotatingFileHandler"
] | [((433, 448), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (438, 448), False, 'from flask import Flask, session, render_template\n'), ((482, 503), 'datetime.timedelta', 'timedelta', ([], {'minutes': '(60)'}), '(minutes=60)\n', (491, 503), False, 'from datetime import timedelta, datetime\n'), ((714, 728),... |
#!/usr/bin/env python2.7
from random import randint, choice, seed
from common import *
class Memory(object):
def __init__(self, filename):
self.data = []
fp = open(filename, "rb")
byte = fp.read(1)
while byte != "":
self.data.append(ord(byte))
byte = fp.read(... | [
"random.seed",
"random.randint"
] | [((835, 842), 'random.seed', 'seed', (['(0)'], {}), '(0)\n', (839, 842), False, 'from random import randint, choice, seed\n'), ((505, 520), 'random.randint', 'randint', (['(0)', '(255)'], {}), '(0, 255)\n', (512, 520), False, 'from random import randint, choice, seed\n'), ((543, 556), 'random.randint', 'randint', (['(0... |
import numpy as np
import pickle as pkl
import os
import pandas as pd
# Creates a dictionary, path_dict, with all of the required path information for the following
# functions including save directory and finding the s2p-output
# Parameters:
# fdir - the path to the original recording file
# fna... | [
"pandas.DataFrame",
"numpy.load",
"numpy.save",
"os.path.join"
] | [((635, 674), 'os.path.join', 'os.path.join', (['fdir', '"""suite2p"""', '"""plane0"""'], {}), "(fdir, 'suite2p', 'plane0')\n", (647, 674), False, 'import os\n'), ((706, 749), 'os.path.join', 'os.path.join', (["path_dict['s2p_dir']", '"""F.npy"""'], {}), "(path_dict['s2p_dir'], 'F.npy')\n", (718, 749), False, 'import o... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | [
"azure.cli.core.commands.cli_command"
] | [((1740, 1874), 'azure.cli.core.commands.cli_command', 'cli_command', (['__name__', '"""documentdb create"""', '"""azure.cli.command_modules.documentdb.custom#cli_documentdb_create"""', 'cf_documentdb'], {}), "(__name__, 'documentdb create',\n 'azure.cli.command_modules.documentdb.custom#cli_documentdb_create',\n ... |
import tkinter
temp_account = []
file = open('moneyData.txt', 'r')
for line in file:
# remove linebreak which is the last character of the string
currentCurrency = float(line.replace("\n", ""))
# add item to the list
temp_account.append(currentCurrency)
file.close()
account = {"MDL": 0, "EUR": 0, "U... | [
"tkinter.StringVar",
"tkinter.Button",
"tkinter.Entry",
"tkinter.Frame",
"tkinter.Label",
"tkinter.Tk"
] | [((523, 535), 'tkinter.Tk', 'tkinter.Tk', ([], {}), '()\n', (533, 535), False, 'import tkinter\n'), ((2116, 2135), 'tkinter.StringVar', 'tkinter.StringVar', ([], {}), '()\n', (2133, 2135), False, 'import tkinter\n'), ((2149, 2168), 'tkinter.StringVar', 'tkinter.StringVar', ([], {}), '()\n', (2166, 2168), False, 'import... |
# -*- coding: utf-8 -*-
"""
coord_model
mantém os detalhes de um sistema de coordenadas
2015.nov 0.2 mlabru pep8 style conventions
2014.nov 0.1 mlabru initial version (Linux/Python)
"""
# < imports >----------------------------------------------------------------------------------
# python library
import loggin... | [
"logging.getLogger"
] | [((478, 505), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (495, 505), False, 'import logging\n')] |
import subprocess
import os
import pytest
import helper.helper as hlp
import tests.conftest as cft
def run_python_subprocess(*args):
return subprocess.run(["python", *args], cwd=pytest.config.rootdir.strpath)
def test_convert_labels():
length_orig = hlp.file_length(cft.eval_label_list)
ret = run_pytho... | [
"subprocess.run",
"helper.helper.get_binary_bool_permutations",
"convert_video_to_xml.get_default_target_filename",
"helper.helper.file_length",
"os.path.isfile",
"pytest.mark.skip"
] | [((561, 595), 'pytest.mark.skip', 'pytest.mark.skip', ([], {'reason': '"""Intense"""'}), "(reason='Intense')\n", (577, 595), False, 'import pytest\n'), ((148, 216), 'subprocess.run', 'subprocess.run', (["['python', *args]"], {'cwd': 'pytest.config.rootdir.strpath'}), "(['python', *args], cwd=pytest.config.rootdir.strpa... |
from typing import Optional, Tuple
import numpy as np
from sklearn import datasets
from torch.utils.data import DataLoader, Dataset
import torch
# import torch.multiprocessing as multiprocessing
# multiprocessing.set_start_method("spawn")
# class DensityDataset:
# def __init__(self, data, dtype=np.float32):
# ... | [
"numpy.random.seed",
"numpy.concatenate",
"numpy.random.randn",
"numpy.std",
"numpy.power",
"numpy.floor",
"sklearn.datasets.make_blobs",
"numpy.random.RandomState",
"sklearn.datasets.make_moons",
"sklearn.datasets.make_swiss_roll",
"numpy.mean",
"numpy.sin",
"numpy.linspace",
"sklearn.dat... | [((2267, 2284), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (2281, 2284), True, 'import numpy as np\n'), ((2293, 2314), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)', 'N'], {}), '(-1, 1, N)\n', (2304, 2314), True, 'import numpy as np\n'), ((2451, 2461), 'numpy.mean', 'np.mean', (['Y'], {}), '(Y)\n... |