code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import os
import glob
from PIL import Image, ImageDraw
# ground truth directory
gt_text_dir = './DB/PLATE/gt' #"./DB/ICDAR2015/test/gt" #"./DB/ICDAR2015/train/gt"
# original images directory
image_dir = './DB/PLATE/*.jpg'#"./DB/ICDAR2015/test/*.jpg" #"./DB/ICDAR2015/train/*.jpg"
imgDirs = []
imgLists = glob.glob(imag... | [
"os.path.exists",
"PIL.Image.open",
"os.path.splitext",
"os.path.join",
"PIL.ImageDraw.Draw",
"os.mkdir",
"os.path.basename",
"glob.glob"
] | [((306, 326), 'glob.glob', 'glob.glob', (['image_dir'], {}), '(image_dir)\n', (315, 326), False, 'import glob\n'), ((499, 528), 'os.path.exists', 'os.path.exists', (['imgs_save_dir'], {}), '(imgs_save_dir)\n', (513, 528), False, 'import os\n'), ((531, 554), 'os.mkdir', 'os.mkdir', (['imgs_save_dir'], {}), '(imgs_save_d... |
### hack to avoid hardlinking through python setup.py sdist - doesn't work on vboxfs
import os
del os.link
###
from distutils.core import setup, Extension
#
# https://docs.python.org/3.3/extending/building.html#building
#
module1 = Extension('ipcbridge',
define_macros = [('MAJOR_VERSION', '0'),
... | [
"distutils.core.Extension",
"distutils.core.setup"
] | [((235, 439), 'distutils.core.Extension', 'Extension', (['"""ipcbridge"""'], {'define_macros': "[('MAJOR_VERSION', '0'), ('MINOR_VERSION', '0.5')]", 'include_dirs': "['/usr/include']", 'libraries': "['pthread']", 'library_dirs': "['/usr/lib']", 'sources': "['ipcbridge.c']"}), "('ipcbridge', define_macros=[('MAJOR_VERSI... |
import geoalchemy2
from sqlalchemy import String, Column, DateTime, ARRAY, TEXT, Integer, ForeignKey, Boolean, Numeric
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.dialects.postgresql import UUID, JSONB
from api.db.base_class import BaseTable, BaseAudit... | [
"sqlalchemy.orm.relationship",
"sqlalchemy.ForeignKey",
"sqlalchemy.Column",
"geoalchemy2.types.Geometry"
] | [((525, 558), 'sqlalchemy.Column', 'Column', (['Integer'], {'primary_key': '(True)'}), '(Integer, primary_key=True)\n', (531, 558), False, 'from sqlalchemy import String, Column, DateTime, ARRAY, TEXT, Integer, ForeignKey, Boolean, Numeric\n'), ((584, 760), 'sqlalchemy.Column', 'Column', (['String'], {'comment': '"""WA... |
# coding:utf8
'''
利用synset的embedding,基于SPWE进行义原推荐
输入:所有synset(名词)的embedding,训练集synset及其义原,测试集synset
输出:测试集义原,正确率
'''
import sys
import os
import numpy as np
from numpy import linalg
import time
import random
outputMode = eval(sys.argv[1])
def ReadSysnetSememe(fileName):
'''
读取已经标注好义原的sysnet... | [
"numpy.mean",
"random.shuffle",
"time.clock",
"numpy.dot",
"numpy.linalg.norm"
] | [((4069, 4081), 'time.clock', 'time.clock', ([], {}), '()\n', (4079, 4081), False, 'import time\n'), ((4260, 4286), 'random.shuffle', 'random.shuffle', (['synsetList'], {}), '(synsetList)\n', (4274, 4286), False, 'import random\n'), ((345, 357), 'time.clock', 'time.clock', ([], {}), '()\n', (355, 357), False, 'import t... |
#! /usr/bin/python
# -*- coding: utf-8 -*-
import re
from subprocess import Popen, PIPE
def getIP(interface):
p = Popen('ifconfig %s' % interface, stdout=PIPE, stderr=PIPE, shell=True)
stdout = p.communicate()[0]
r = re.search('inet addr:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})', stdout)
ip = r.group(1)
... | [
"subprocess.Popen",
"re.search"
] | [((121, 191), 'subprocess.Popen', 'Popen', (["('ifconfig %s' % interface)"], {'stdout': 'PIPE', 'stderr': 'PIPE', 'shell': '(True)'}), "('ifconfig %s' % interface, stdout=PIPE, stderr=PIPE, shell=True)\n", (126, 191), False, 'from subprocess import Popen, PIPE\n'), ((232, 306), 're.search', 're.search', (['"""inet addr... |
# coding: utf-8
# Standard Library
import os
import argparse
# Local
import payu
from payu import cli
from payu.experiment import Experiment
from payu.laboratory import Laboratory
import payu.subcommands.args as args
title = 'run'
parameters = {'description': 'Run the model experiment'}
arguments = [args.model, arg... | [
"payu.laboratory.Laboratory",
"payu.cli.get_config",
"os.listdir",
"argparse.ArgumentParser",
"payu.cli.set_env_vars",
"payu.experiment.Experiment",
"payu.cli.submit_job"
] | [((510, 537), 'payu.cli.get_config', 'cli.get_config', (['config_path'], {}), '(config_path)\n', (524, 537), False, 'from payu import cli\n'), ((553, 597), 'payu.cli.set_env_vars', 'cli.set_env_vars', (['init_run', 'n_runs', 'lab_path'], {}), '(init_run, n_runs, lab_path)\n', (569, 597), False, 'from payu import cli\n'... |
from app.persian import PersianCalendar
from django.db import models
from .enums import UnitNameEnum,ProductRequestStatusEnum,LetterStatusEnum,AgentRoleEnum
from app.enums import ColorEnum,IconsEnum,EmployeeEnum,DegreeLevelEnum
from django.shortcuts import reverse
from app.settings import ADMIN_URL
from django.utils.tr... | [
"django.utils.translation.gettext",
"django.shortcuts.reverse"
] | [((466, 476), 'django.utils.translation.gettext', '_', (['"""title"""'], {}), "('title')\n", (467, 476), True, 'from django.utils.translation import gettext as _\n'), ((580, 589), 'django.utils.translation.gettext', '_', (['"""icon"""'], {}), "('icon')\n", (581, 589), True, 'from django.utils.translation import gettext... |
# Generated by Django 3.1.3 on 2021-01-23 15:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('KNSQueries', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='person',
name='is_current',
... | [
"django.db.migrations.RemoveField",
"django.db.models.IntegerField"
] | [((227, 289), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""person"""', 'name': '"""is_current"""'}), "(model_name='person', name='is_current')\n", (249, 289), False, 'from django.db import migrations, models\n'), ((439, 471), 'django.db.models.IntegerField', 'models.IntegerField... |
from PyQt5.Qt import *
from Login_Pane import LoginPane
from Query_Pane import QueryPane
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
login_pane = LoginPane()
login_pane.show()
query_pane = QueryPane()
def success_login_slot(content):
print(content)
lo... | [
"Login_Pane.LoginPane",
"Query_Pane.QueryPane"
] | [((184, 195), 'Login_Pane.LoginPane', 'LoginPane', ([], {}), '()\n', (193, 195), False, 'from Login_Pane import LoginPane\n'), ((236, 247), 'Query_Pane.QueryPane', 'QueryPane', ([], {}), '()\n', (245, 247), False, 'from Query_Pane import QueryPane\n')] |
from dipsim import multiframe, util
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import matplotlib.patches as patches
import os; import time; start = time.time(); print('Running...')
import matplotlib.gridspec as gridspec
# Main input parameters
col_labels = ['Geometry\n (NA = 0.6, $\\beta=80{}... | [
"numpy.array",
"numpy.sin",
"dipsim.util.draw_scene",
"matplotlib.gridspec.GridSpecFromSubplotSpec",
"matplotlib.colors.LogNorm",
"matplotlib.ticker.FuncFormatter",
"matplotlib.gridspec.GridSpec",
"numpy.linspace",
"dipsim.util.plot_sphere",
"numpy.vstack",
"matplotlib.cm.get_cmap",
"numpy.abs... | [((174, 185), 'time.time', 'time.time', ([], {}), '()\n', (183, 185), False, 'import time\n'), ((710, 760), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(2.2 * inch_fig, 3 * inch_fig)'}), '(figsize=(2.2 * inch_fig, 3 * inch_fig))\n', (720, 760), True, 'import matplotlib.pyplot as plt\n'), ((763, 835), 'm... |
import json
import uuid
from jsonfield import JSONField
from django.db import models
class Uploadable(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
url = models.URLField(default="")
meta_data = JSONField(blank=True, null=True)
class Meta:
abstrac... | [
"django.db.models.URLField",
"jsonfield.JSONField",
"django.db.models.UUIDField",
"json.loads"
] | [((129, 199), 'django.db.models.UUIDField', 'models.UUIDField', ([], {'primary_key': '(True)', 'default': 'uuid.uuid4', 'editable': '(False)'}), '(primary_key=True, default=uuid.uuid4, editable=False)\n', (145, 199), False, 'from django.db import models\n'), ((211, 238), 'django.db.models.URLField', 'models.URLField', ... |
import numpy as np
import matplotlib.pyplot as plt
import pickle
from scipy.stats import multivariate_normal
def draw_heatmap(mux, muy, sx, sy, rho, plt = None, bound = 0.1):
x, y = np.meshgrid(np.linspace(mux - bound, mux + bound, 200),
np.linspace(muy - bound, muy + bound, 200))
m... | [
"numpy.dstack",
"numpy.abs",
"scipy.stats.multivariate_normal",
"matplotlib.pyplot.plot",
"pickle.load",
"matplotlib.pyplot.pcolormesh",
"matplotlib.pyplot.figure",
"numpy.linspace",
"matplotlib.pyplot.show"
] | [((453, 492), 'scipy.stats.multivariate_normal', 'multivariate_normal', ([], {'mean': 'mean', 'cov': 'cov'}), '(mean=mean, cov=cov)\n', (472, 492), False, 'from scipy.stats import multivariate_normal\n'), ((505, 522), 'numpy.dstack', 'np.dstack', (['[x, y]'], {}), '([x, y])\n', (514, 522), True, 'import numpy as np\n')... |
#!/home/knielbo/virtenvs/ndhl/bin/python
"""
Describe feature distributions of (meta)data
@author: <EMAIL>
"""
import os
import matplotlib.pyplot as plt
from util import load_pcl
from datetime import datetime
def main():
fname = os.path.join("..", "dat", "target.pcl")
db = load_pcl(fname)
metadata = db["m... | [
"os.path.join",
"matplotlib.pyplot.close",
"datetime.datetime.now",
"util.load_pcl",
"matplotlib.pyplot.title"
] | [((235, 274), 'os.path.join', 'os.path.join', (['""".."""', '"""dat"""', '"""target.pcl"""'], {}), "('..', 'dat', 'target.pcl')\n", (247, 274), False, 'import os\n'), ((284, 299), 'util.load_pcl', 'load_pcl', (['fname'], {}), '(fname)\n', (292, 299), False, 'from util import load_pcl\n'), ((390, 404), 'datetime.datetim... |
# Copyright [2020] [Toyota Research Institute]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... | [
"copy.deepcopy",
"xmltodict.parse",
"os.path.join",
"beep.protocol.maccor_to_biologic_mb.CycleAdvancementRulesSerializer",
"pandas.DataFrame.from_dict",
"os.path.dirname",
"pydash.get",
"beep.protocol.maccor_to_biologic_mb.CycleAdvancementRules",
"beep.protocol.maccor.Procedure.generate_procedure_re... | [((1113, 1138), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (1128, 1138), False, 'import os\n'), ((1155, 1191), 'os.path.join', 'os.path.join', (['TEST_DIR', '"""test_files"""'], {}), "(TEST_DIR, 'test_files')\n", (1167, 1191), False, 'import os\n'), ((1639, 1659), 'beep.protocol.maccor_to... |
from flask_mail import Mail, Message
from flask import Flask
app =Flask(__name__)
app.config['MAIL_SERVER']='smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = '<EMAIL>'
app.config['MAIL_PASSWORD'] = '<PASSWORD>%'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
mail = M... | [
"flask_mail.Mail",
"flask_mail.Message",
"flask.Flask"
] | [((69, 84), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (74, 84), False, 'from flask import Flask\n'), ((319, 328), 'flask_mail.Mail', 'Mail', (['app'], {}), '(app)\n', (323, 328), False, 'from flask_mail import Mail, Message\n'), ((369, 438), 'flask_mail.Message', 'Message', (['"""Hello"""'], {'sender'... |
from .. import berrymq
import os
import glob
import time
import threading
class FileObserver(object):
def __init__(self, target_dir, id_name, interval=5):
self.id_name = id_name
self.target_dir = target_dir
self.interval = interval
self.fileinfo = self._get_fileinfo()
self.t... | [
"threading.Thread",
"time.sleep",
"os.path.getmtime",
"glob.glob"
] | [((328, 367), 'threading.Thread', 'threading.Thread', ([], {'target': 'self._checkdir'}), '(target=self._checkdir)\n', (344, 367), False, 'import threading\n'), ((1348, 1374), 'glob.glob', 'glob.glob', (['self.target_dir'], {}), '(self.target_dir)\n', (1357, 1374), False, 'import glob\n'), ((584, 609), 'time.sleep', 't... |
import os
from redisrpc import RedisRPC
# Add REDIS_URI application enviroment
os.environ.setdefault("REDIS_URI", "redis://:PpkJfHHNph9X5hB5@localhost:6379/0")
rpc = RedisRPC("channel_name") # rename what you want
# event lists
def calc_square(response): # `response` is a sender data
power_of_number = respon... | [
"os.environ.setdefault",
"redisrpc.RedisRPC"
] | [((81, 166), 'os.environ.setdefault', 'os.environ.setdefault', (['"""REDIS_URI"""', '"""redis://:PpkJfHHNph9X5hB5@localhost:6379/0"""'], {}), "('REDIS_URI', 'redis://:PpkJfHHNph9X5hB5@localhost:6379/0'\n )\n", (102, 166), False, 'import os\n'), ((169, 193), 'redisrpc.RedisRPC', 'RedisRPC', (['"""channel_name"""'], {... |
import requests
from server_generator.server_generator import MagicRouter
from tests.utils import start_test_bottle_app
class HelloNameURLHandler(MagicRouter):
route_name = 'hello_name'
def handler(self):
return 'hello {}'.format(self.name)
def test_setup():
route = HelloNameURLHandler()
s... | [
"requests.get",
"tests.utils.start_test_bottle_app"
] | [((319, 347), 'tests.utils.start_test_bottle_app', 'start_test_bottle_app', (['route'], {}), '(route)\n', (340, 347), False, 'from tests.utils import start_test_bottle_app\n'), ((402, 451), 'requests.get', 'requests.get', (['"""http://localhost:8080/hello/world"""'], {}), "('http://localhost:8080/hello/world')\n", (414... |
from GPy.kern import Kern
from GPy.core.parameterization import Param
import numpy as np
import sys
from paramz.transformations import Logexp
from ..kernels.tree.C_tree_kernel import wrapper_raw_SubsetTreeKernel
class SubsetTreeKernel(Kern):
"""
The SST kernel by Moschitti(2006), with two hyperparameters (la... | [
"numpy.ones",
"paramz.transformations.Logexp",
"numpy.hstack",
"numpy.array",
"numpy.sum"
] | [((3309, 3535), 'numpy.array', 'np.array', (["[['(S (NP ns) (VP v))'], ['(S (NP n) (VP v))'], [\n '(S (NP (N a)) (VP (V c)))'], ['(S (NP (Det a) (N b)) (VP (V c)))'], [\n '(S (NP (ADJ colorless) (N ideas)) (VP (V sleep) (ADV furiously)))']]"], {'dtype': 'object'}), "([['(S (NP ns) (VP v))'], ['(S (NP n) (VP v))']... |
import matplotlib.pyplot as plt
import numpy as np
from scipy.io import wavfile
from common import balance, file_name, view, correction
# Read the audio file
rate, audio = wavfile.read(file_name)
audio = balance(audio)
count = audio.shape[0] # Number of data points
length = count / rate # Length of the recording (... | [
"matplotlib.pyplot.savefig",
"common.balance",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.fft.fft",
"common.view.__len__",
"numpy.linspace",
"scipy.io.wavfile.read",
"matplotlib.pyplot.title",
"matplotlib.pyplot.xlim",
"numpy.amax",
"matplotlib.p... | [((174, 197), 'scipy.io.wavfile.read', 'wavfile.read', (['file_name'], {}), '(file_name)\n', (186, 197), False, 'from scipy.io import wavfile\n'), ((206, 220), 'common.balance', 'balance', (['audio'], {}), '(audio)\n', (213, 220), False, 'from common import balance, file_name, view, correction\n'), ((483, 510), 'numpy.... |
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..','..'))
import numpy as np
import pickle
import random
import json
from collections import OrderedDict
import itertools as it
from src.neuralNetwork.policyValueResNet import GenerateModel, Train, saveVariables, sampleData, Approximat... | [
"src.constrainedChasingEscapingEnv.envNoPhysics.TransiteForNoPhysics",
"src.neuralNetwork.policyValueResNet.restoreVariables",
"numpy.array",
"os.path.exists",
"src.neuralNetwork.policyValueResNet.ApproximatePolicy",
"exec.trajectoriesSaveLoad.GetSavePath",
"pygame.display.set_mode",
"itertools.produc... | [((2400, 2423), 'json.loads', 'json.loads', (['sys.argv[1]'], {}), '(sys.argv[1])\n', (2410, 2423), False, 'import json\n'), ((3245, 3270), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (3260, 3270), False, 'import os\n'), ((3303, 3478), 'os.path.join', 'os.path.join', (['dirName', '""".."""... |
# Usage:
# Find and download fred series data
# then find the specific data on yyyy-mm-dd
import requests # used for downloading text files from FRED
import os # used for removing temporary text files
# Usage : download series data in the form of text file and extract data on given date
# param:
# se... | [
"requests.get",
"os.remove"
] | [((547, 614), 'requests.get', 'requests.get', (["('https://fred.stlouisfed.org/data/' + series + '.txt')"], {}), "('https://fred.stlouisfed.org/data/' + series + '.txt')\n", (559, 614), False, 'import requests\n'), ((1163, 1179), 'os.remove', 'os.remove', (['fname'], {}), '(fname)\n', (1172, 1179), False, 'import os\n'... |
import pymongo
import requests
from collections import OrderedDict
from hashlib import sha512
API_URL = 'https://api.coinmarketcap.com/v2/ticker/'
API_URL_START = 'https://api.coinmarketcap.com/v2/ticker/?start={}'
API_URL_LISTINGS = 'https://api.coinmarketcap.com/v2/listings/'
def get_db_connection(uri):
"""
... | [
"pymongo.MongoClient",
"requests.get"
] | [((485, 509), 'pymongo.MongoClient', 'pymongo.MongoClient', (['uri'], {}), '(uri)\n', (504, 509), False, 'import pymongo\n'), ((2675, 2692), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (2687, 2692), False, 'import requests\n'), ((3037, 3067), 'requests.get', 'requests.get', (['API_URL_LISTINGS'], {}), '(A... |
# -*- coding: utf-8 -*-
__author__ = 'gzp'
from danmaku_robot.models import RobotSettings
class Settings(object):
_settings = dict([
('room_id', 'int'),
('cookie', 'str'),
('question_prefix', 'str'),
('answer_prefix', 'str'),
('confidence', 'float'),
('question_rob... | [
"danmaku_robot.models.RobotSettings.get_setting_value",
"danmaku_robot.models.RobotSettings.set_setting_value"
] | [((576, 613), 'danmaku_robot.models.RobotSettings.get_setting_value', 'RobotSettings.get_setting_value', (['item'], {}), '(item)\n', (607, 613), False, 'from danmaku_robot.models import RobotSettings\n'), ((741, 818), 'danmaku_robot.models.RobotSettings.set_setting_value', 'RobotSettings.set_setting_value', (['key', 'v... |
#!/usr/bin/env python
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkFiltersSources import vtkSuperquadricSource
from vtkmodules.vtkIOXML impo... | [
"vtkmodules.vtkRenderingCore.vtkActor",
"vtkmodules.vtkInteractionWidgets.vtkOrientationMarkerWidget",
"vtkmodules.vtkFiltersSources.vtkSuperquadricSource",
"argparse.ArgumentParser",
"vtkmodules.vtkRenderingCore.vtkDataSetMapper",
"vtkmodules.vtkRenderingCore.vtkRenderWindow",
"vtkmodules.vtkRenderingC... | [((614, 630), 'vtkmodules.vtkCommonColor.vtkNamedColors', 'vtkNamedColors', ([], {}), '()\n', (628, 630), False, 'from vtkmodules.vtkCommonColor import vtkNamedColors\n'), ((724, 746), 'vtkmodules.vtkIOXML.vtkXMLPolyDataReader', 'vtkXMLPolyDataReader', ([], {}), '()\n', (744, 746), False, 'from vtkmodules.vtkIOXML impo... |
from django.urls import path
from . import views
app_name = 'todos'
urlpatterns = [
path('', views.index, name="index"),
path('add', views.add, name="add"),
path('complete', views.complete, name="complete"),
path('delete', views.delete, name="delete")
]
| [
"django.urls.path"
] | [((90, 125), 'django.urls.path', 'path', (['""""""', 'views.index'], {'name': '"""index"""'}), "('', views.index, name='index')\n", (94, 125), False, 'from django.urls import path\n'), ((131, 165), 'django.urls.path', 'path', (['"""add"""', 'views.add'], {'name': '"""add"""'}), "('add', views.add, name='add')\n", (135,... |
from datetime import date
from decimal import Decimal
from typing import List, Dict, Iterable, Optional
from vacations.config import (
APPROVE_BUTTON_ACTION_ID,
DENY_BUTTON_ACTION_ID,
DATEPICKER_START_ACTION_ID,
DATEPICKER_END_ACTION_ID,
REASON_INPUT_ACTION_ID,
REQUEST_VIEW_ID,
LEAVE_TYPES,... | [
"datetime.date.today"
] | [((2323, 2335), 'datetime.date.today', 'date.today', ([], {}), '()\n', (2333, 2335), False, 'from datetime import date\n')] |
from datetime import datetime
def greetingTime():
current_hour = datetime.now().hour
if current_hour < 12:
return "Buenos días"
elif 12 <= current_hour < 18:
return "Buenas tardes"
else:
return "Buenas noches" | [
"datetime.datetime.now"
] | [((70, 84), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (82, 84), False, 'from datetime import datetime\n')] |
'''
0) Setup Data
1) Design Model (input_size, output_size, forward_pass)
2) Construct Loss, Optimizer
3) Training Loop
- forward pass
- gradients
- update weights
'''
import torch
import torch as th
import torch.nn as nn
import numpy as np
# Data process
from sklearn import datasets
from sklearn.preproces... | [
"sklearn.model_selection.train_test_split",
"sklearn.datasets.load_breast_cancer",
"sklearn.preprocessing.StandardScaler",
"torch.nn.BCELoss",
"torch.nn.Linear",
"torch.no_grad"
] | [((425, 454), 'sklearn.datasets.load_breast_cancer', 'datasets.load_breast_cancer', ([], {}), '()\n', (452, 454), False, 'from sklearn import datasets\n'), ((576, 631), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.2)', 'random_state': '(123)'}), '(X, y, test_size=0.2, r... |
from rest_framework import serializers
from .models import *
import backend.settings.dev as settings
from rest_framework.validators import UniqueValidator
import jwt
from rest_framework_jwt.utils import jwt_payload_handler
class ProfilePicSerializer(serializers.ModelSerializer):
class Meta:
model = MygUse... | [
"rest_framework.serializers.SerializerMethodField"
] | [((480, 515), 'rest_framework.serializers.SerializerMethodField', 'serializers.SerializerMethodField', ([], {}), '()\n', (513, 515), False, 'from rest_framework import serializers\n')] |
#!/usr/bin/env python
# Superficies de revolucion
import OpenGL
OpenGL.ERROR_ON_COPY = True
from OpenGL.GL import *
from OpenGL.GLU import gluOrtho2D
from OpenGL.GLUT import *
import sys, time
from sympy.core.sympify import sympify
from sympy import *
from OpenGL.constants import GLfloat
from OpenGL.GL.ARB.multisampl... | [
"OpenGL.GLU.gluOrtho2D",
"sympy.core.sympify.sympify",
"math.sqrt",
"math.cos",
"sys.exit",
"math.sin",
"time.time"
] | [((392, 403), 'time.time', 'time.time', ([], {}), '()\n', (401, 403), False, 'import sys, time\n'), ((4597, 4647), 'OpenGL.GLU.gluOrtho2D', 'gluOrtho2D', (['(0.0)', 'ventana_tam_x', '(0.0)', 'ventana_tam_y'], {}), '(0.0, ventana_tam_x, 0.0, ventana_tam_y)\n', (4607, 4647), False, 'from OpenGL.GLU import gluOrtho2D\n'),... |
"""Test /v1/datasets endpoints"""
import json
from unittest.mock import patch
import boto3
import botocore
from moto import mock_s3
from covid_api.core.config import INDICATOR_BUCKET
DATASET_METADATA_FILENAME = "dev-dataset-metadata.json"
DATASET_METADATA_GENERATOR_FUNCTION_NAME = "dev-dataset-metadata-generator"
... | [
"boto3.resource",
"json.dumps",
"unittest.mock.patch",
"json.loads"
] | [((368, 388), 'boto3.resource', 'boto3.resource', (['"""s3"""'], {}), "('s3')\n", (382, 388), False, 'import boto3\n'), ((3379, 3407), 'json.loads', 'json.loads', (['response.content'], {}), '(response.content)\n', (3389, 3407), False, 'import json\n'), ((3697, 3725), 'json.loads', 'json.loads', (['response.content'], ... |
import arrow
from helpers import read_data, write_data, get_settings, package_comment
import api
settings = get_settings()
sync_dates = read_data('sync_dates')
last_sync = arrow.get(sync_dates['comments'])
article_map = read_data('article_map')
comment_map = read_data('comment_map')
comment_article_map = read_data('... | [
"helpers.get_settings",
"arrow.utcnow",
"helpers.write_data",
"api.put_resource",
"api.get_resource_list",
"helpers.read_data",
"arrow.get",
"helpers.package_comment",
"api.post_resource"
] | [((111, 125), 'helpers.get_settings', 'get_settings', ([], {}), '()\n', (123, 125), False, 'from helpers import read_data, write_data, get_settings, package_comment\n'), ((139, 162), 'helpers.read_data', 'read_data', (['"""sync_dates"""'], {}), "('sync_dates')\n", (148, 162), False, 'from helpers import read_data, writ... |
# coding: utf-8
# !/usr/bin/env python3
import csv
import os, os.path
import sys
import argparse
from WriteExcel import Excel
from log import debug, info, error
from baidu_traslate import *
class Nessus(object):
"""处理Nessus扫描结果"""
def __init__(self, csv_name):
self.csv_name = csv_name
self.... | [
"os.listdir",
"WriteExcel.Excel",
"argparse.ArgumentParser",
"log.error",
"os.path.isfile",
"os.chdir",
"log.debug",
"sys.exit",
"os.path.abspath",
"csv.reader"
] | [((1560, 1633), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'prog': '"""nessusor"""', 'description': '"""默认在程序目录下生成xls格式文档"""'}), "(prog='nessusor', description='默认在程序目录下生成xls格式文档')\n", (1583, 1633), False, 'import argparse\n'), ((349, 378), 'os.path.isfile', 'os.path.isfile', (['self.csv_name'], {}), '... |
from django.test import TestCase
from django.core.urlresolvers import reverse
from django.utils import timezone
from django.core.urlresolvers import reverse
from mainapp.forms import CreateReviewForm
from mainapp.models import Researcher, Review, Paper, Query
from django.contrib.auth.models import User
# tests for ... | [
"django.contrib.auth.models.User",
"django.core.urlresolvers.reverse",
"django.contrib.auth.models.User.objects.create_user",
"mainapp.models.Researcher",
"mainapp.models.Query",
"mainapp.forms.CreateReviewForm",
"django.contrib.auth.models.User.objects.get",
"mainapp.models.Paper",
"mainapp.models.... | [((647, 668), 'django.contrib.auth.models.User', 'User', ([], {'username': '"""bill"""'}), "(username='bill')\n", (651, 668), False, 'from django.contrib.auth.models import User\n'), ((752, 806), 'mainapp.models.Researcher', 'Researcher', ([], {'user': 'testUser', 'name': '"""bill"""', 'surname': '"""bill"""'}), "(user... |
"""
Django settings for webDe project.
Generated by 'django-admin startproject' using Django 2.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
from... | [
"os.path.abspath",
"os.path.join",
"django.urls.reverse_lazy"
] | [((3652, 3688), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""staticRoot"""'], {}), "(BASE_DIR, 'staticRoot')\n", (3664, 3688), False, 'import os\n'), ((3702, 3733), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""media"""'], {}), "(BASE_DIR, 'media')\n", (3714, 3733), False, 'import os\n'), ((6097, 6127), 'djang... |
#! python3
# randomQUizGenerator.py - Cria provas com perguntas e respostas em ordem aleatória
# juntamente com os gabaritos contendo as respostas.
import random
captals = {'Acre (AC)': 'Rio Branco', 'Alagoas (AL)': 'Maceió', 'Amapá (AP)': 'Macapá', 'Amazonas (AM)': 'Manaus',
'Bahia (BA)': 'Salvador', 'Cea... | [
"random.sample",
"random.shuffle"
] | [((1675, 1697), 'random.shuffle', 'random.shuffle', (['states'], {}), '(states)\n', (1689, 1697), False, 'import random\n'), ((2011, 2041), 'random.sample', 'random.sample', (['wrongAnswers', '(3)'], {}), '(wrongAnswers, 3)\n', (2024, 2041), False, 'import random\n'), ((2105, 2134), 'random.shuffle', 'random.shuffle', ... |
import pathlib
from setuptools import find_packages, setup
HERE = pathlib.Path(__file__).parent
VERSION = '0.0.0'
PACKAGE_NAME = 'cramer'
AUTHOR = '<NAME>'
AUTHOR_EMAIL = '<EMAIL>'
URL = 'https://github.com/TeengardenB/cramer'
LICENSE = 'MIT'
DESCRIPTION = 'This is a library designed to solve systems ... | [
"setuptools.find_packages",
"pathlib.Path"
] | [((70, 92), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (82, 92), False, 'import pathlib\n'), ((849, 864), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (862, 864), False, 'from setuptools import find_packages, setup\n')] |
#!/usr/bin/env python
import sys
import os
from datetime import datetime
from argparse import ArgumentParser
template="""#!/usr/bin/env python
'''
File: {0}
Author: <NAME> <<EMAIL>>
Org: TralahTek LLC <https://github.com/TralahTek>
Date: {1}
'''
""".format(sys.argv[1],datetime.now().date())
if __name__=='__main__'... | [
"os.system",
"datetime.datetime.now",
"os.sys.exit",
"argparse.ArgumentParser"
] | [((333, 364), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'epilog': 'template'}), '(epilog=template)\n', (347, 364), False, 'from argparse import ArgumentParser\n'), ((593, 626), 'os.system', 'os.system', (["('vim ' + args.filename)"], {}), "('vim ' + args.filename)\n", (602, 626), False, 'import os\n'), ((629, ... |
import zmq
import simpleaudio as sa
import os
from time import sleep
# ----------------------------------------------------------------------------------------------------------------------
# A few ways of playing .wav files ... comment these out but keep for reference
# import pyaudio
# import wave
# from pydub impo... | [
"simpleaudio.WaveObject.from_wave_file",
"time.sleep",
"zmq.Poller",
"os.system",
"zmq.Context"
] | [((1659, 1682), 'os.system', 'os.system', (['pico_command'], {}), '(pico_command)\n', (1668, 1682), False, 'import os\n'), ((1773, 1811), 'simpleaudio.WaveObject.from_wave_file', 'sa.WaveObject.from_wave_file', (['tmp_file'], {}), '(tmp_file)\n', (1801, 1811), True, 'import simpleaudio as sa\n'), ((2009, 2030), 'os.sys... |
from python_framework import Controller, ControllerMethod, HttpStatus
from Role import *
from dto.FeatureDataDto import *
@Controller(url = '/feature-datas', tag='FeatureData', description='Single FeatureData controller')
class FeatureDataController:
@ControllerMethod(url='/<string:featureKey>/<string:sampleKey>... | [
"python_framework.ControllerMethod",
"python_framework.Controller"
] | [((125, 226), 'python_framework.Controller', 'Controller', ([], {'url': '"""/feature-datas"""', 'tag': '"""FeatureData"""', 'description': '"""Single FeatureData controller"""'}), "(url='/feature-datas', tag='FeatureData', description=\n 'Single FeatureData controller')\n", (135, 226), False, 'from python_framework ... |
import matplotlib.pyplot as plt
import numpy as np
def tunediagram(order=range(1,4),integer=[0,0],lines=[1,1,1,1],colors='ordered',linestyle='-',fig=plt.gcf()):
'''
plot resonance diagram up to specified order
mx + ny = p
x = (p-ny)/m
x = 1 where y = (p-m)/n
EXAMPLE:
tunediagram(order=... | [
"numpy.abs",
"matplotlib.pyplot.vlines",
"matplotlib.pyplot.gcf",
"matplotlib.pyplot.hlines",
"numpy.array",
"numpy.linspace",
"numpy.sign",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.xlim"
] | [((151, 160), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (158, 160), True, 'import matplotlib.pyplot as plt\n'), ((1533, 1563), 'numpy.linspace', 'np.linspace', (['(0)', 'pval', '(pval + 1)'], {}), '(0, pval, pval + 1)\n', (1544, 1563), True, 'import numpy as np\n'), ((1957, 1995), 'matplotlib.pyplot.xlim', ... |
import os
import pytest
import shutil
from cloudify_agent.api import exceptions
from cloudify_agent.api import utils
from cloudify_agent.tests.utils import get_daemon_storage
from cloudify_agent.tests import random_id
def test_new_initd(daemon_factory, agent_ssl_cert):
daemon_name = 'test-daemon-{0}'.format(rand... | [
"cloudify_agent.tests.random_id",
"cloudify_agent.api.utils.internal.generate_agent_name",
"pytest.raises"
] | [((1206, 1285), 'pytest.raises', 'pytest.raises', (['exceptions.DaemonNotFoundError', 'daemon_factory.load', 'daemon.name'], {}), '(exceptions.DaemonNotFoundError, daemon_factory.load, daemon.name)\n', (1219, 1285), False, 'import pytest\n'), ((1358, 1463), 'pytest.raises', 'pytest.raises', (['exceptions.DaemonNotImple... |
import asynctest
from uuid import uuid4
from .client import CLIENT
from ...settings import BucketSettings
from ...models.file import FileModel
from ...bucket.awaiting import AwaitingFile
class TestAwaitingFiles(asynctest.TestCase):
use_default_loop = True
async def test_file_listing_names(self):
... | [
"uuid.uuid4"
] | [((410, 417), 'uuid.uuid4', 'uuid4', ([], {}), '()\n', (415, 417), False, 'from uuid import uuid4\n')] |
# Import external modules.
from google.appengine.ext import ndb
import logging
# Import local modules.
from configuration import const as conf
from constants import Constants
const = Constants()
const.MAX_RETRY = 3
# Parent key: none
class RequestForProposals(ndb.Model):
title = ndb.StringProperty()
detail ... | [
"constants.Constants",
"google.appengine.ext.ndb.transactional",
"google.appengine.ext.ndb.BooleanProperty",
"google.appengine.ext.ndb.StringProperty"
] | [((185, 196), 'constants.Constants', 'Constants', ([], {}), '()\n', (194, 196), False, 'from constants import Constants\n'), ((761, 803), 'google.appengine.ext.ndb.transactional', 'ndb.transactional', ([], {'retries': 'const.MAX_RETRY'}), '(retries=const.MAX_RETRY)\n', (778, 803), False, 'from google.appengine.ext impo... |
from selenium.webdriver.support.ui import Select
from model.contact import Contact
import re
class ContactHelper:
def __init__(self, app):
self.app = app
def open_home_page(self):
wd = self.app.wd
if not (wd.current_url.endswith("/index.php") and
len(wd.find_elements_by_xpath(... | [
"model.contact.Contact",
"re.search"
] | [((8447, 8663), 'model.contact.Contact', 'Contact', ([], {'firstname': 'firstname', 'lastname': 'lastname', 'id': 'id', 'address': 'address', 'home_phone': 'home_phone', 'mobile': 'mobile', 'work_phone': 'work_phone', 'secondary_phone': 'secondary_phone', 'email': 'email', 'email2': 'email2', 'email3': 'email3'}), '(fi... |
import numpy as np
import pandas as pd
import pytest
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import TheilSenRegressor
from etna.analysis import get_residuals
from etna.analysis import plot_residuals
from etna.analysis import plot_trend
from etna.analysis.plotters import _get_labels_... | [
"pandas.MultiIndex.from_frame",
"sklearn.linear_model.LinearRegression",
"etna.datasets.TSDataset.to_dataset",
"etna.transforms.BinsegTrendTransform",
"etna.datasets.TSDataset",
"etna.analysis.plot_residuals",
"etna.models.LinearPerSegmentModel",
"sklearn.linear_model.TheilSenRegressor",
"etna.metri... | [((3282, 3465), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""poly_degree, trend_transform_class"""', '([1, LinearTrendTransform], [2, LinearTrendTransform], [1,\n TheilSenTrendTransform], [2, TheilSenTrendTransform])'], {}), "('poly_degree, trend_transform_class', ([1,\n LinearTrendTransform], [2, ... |
import requests
import io
import zipfile
import shutil
STOREPATH = '/data/csv/'
def download_extract_zip(url, dirpath):
response = requests.get(url)
with zipfile.ZipFile(io.BytesIO(response.content)) as zfile:
store_at = STOREPATH + dirpath
zfile.extractall( store_at )
def download_chunk(url, dirpa... | [
"zipfile.ZipFile",
"io.BytesIO",
"shutil.copyfileobj",
"requests.get"
] | [((136, 153), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (148, 153), False, 'import requests\n'), ((368, 398), 'requests.get', 'requests.get', (['url'], {'stream': '(True)'}), '(url, stream=True)\n', (380, 398), False, 'import requests\n'), ((178, 206), 'io.BytesIO', 'io.BytesIO', (['response.content'], ... |
""" Serializers for API views """
# Module imports
from rest_framework import serializers
from django.contrib.auth import authenticate
from funds.models import Wallet
class TransactionSerializer(serializers.Serializer):
""" Serializer for transaction model """
pass
class WalletSerializer(serializers.Serial... | [
"rest_framework.serializers.FloatField",
"rest_framework.serializers.CharField",
"funds.models.Wallet",
"rest_framework.serializers.BooleanField"
] | [((428, 465), 'rest_framework.serializers.CharField', 'serializers.CharField', ([], {'max_length': '(250)'}), '(max_length=250)\n', (449, 465), False, 'from rest_framework import serializers\n'), ((491, 529), 'rest_framework.serializers.CharField', 'serializers.CharField', ([], {'max_length': '(1000)'}), '(max_length=1... |
from setup_api import setup
from mailwizz.endpoint.customers import Customers
"""
SETUP THE API
"""
setup()
"""
CREATE THE ENDPOINT
"""
endpoint = Customers()
"""
CREATE CUSTOMER
"""
response = endpoint.create({
'customer': {
'first_name': 'John',
'last_name': 'Doe',
'email': '<EMAIL>',
... | [
"mailwizz.endpoint.customers.Customers",
"setup_api.setup"
] | [((101, 108), 'setup_api.setup', 'setup', ([], {}), '()\n', (106, 108), False, 'from setup_api import setup\n'), ((149, 160), 'mailwizz.endpoint.customers.Customers', 'Customers', ([], {}), '()\n', (158, 160), False, 'from mailwizz.endpoint.customers import Customers\n')] |
import argparse
import copy
import datetime
import re
import shlex
from typing import Union
import time
import discord
from discord.ext import commands
class Arguments(argparse.ArgumentParser):
def error(self, message):
raise RuntimeError(message)
def setup(bot):
bot.add_cog(Moderation(bot))
def ... | [
"discord.ext.commands.check",
"discord.ext.commands.command",
"copy.copy"
] | [((471, 500), 'discord.ext.commands.command', 'commands.command', ([], {'hidden': '(True)'}), '(hidden=True)\n', (487, 500), False, 'from discord.ext import commands\n'), ((506, 530), 'discord.ext.commands.check', 'commands.check', (['is_owner'], {}), '(is_owner)\n', (520, 530), False, 'from discord.ext import commands... |
from pulp.amply import Amply, AmplyError
from StringIO import StringIO
from nose.tools import assert_raises
def test_data():
result = Amply("param T := 4;")['T']
assert result == 4
result = Amply("param T := -4;")['T']
assert result == -4
result = Amply("param T := 0.04;")['T']
assert result =... | [
"StringIO.StringIO",
"pulp.amply.Amply",
"pulp.amply.Amply.from_file",
"nose.tools.assert_raises"
] | [((1124, 1148), 'StringIO.StringIO', 'StringIO', (['"""param T:= 4;"""'], {}), "('param T:= 4;')\n", (1132, 1148), False, 'from StringIO import StringIO\n'), ((1219, 1254), 'pulp.amply.Amply', 'Amply', (['"""param T:= 4; param X{foo};"""'], {}), "('param T:= 4; param X{foo};')\n", (1224, 1254), False, 'from pulp.amply ... |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import glob
import os
import zipfile
from spack import *
class PyFlitCore(PythonPackage):
"""Distribution-building ... | [
"os.path.join",
"zipfile.ZipFile"
] | [((935, 957), 'zipfile.ZipFile', 'zipfile.ZipFile', (['wheel'], {}), '(wheel)\n', (950, 957), False, 'import zipfile\n'), ((875, 917), 'os.path.join', 'os.path.join', (['"""flit_core"""', '"""dist"""', '"""*.whl"""'], {}), "('flit_core', 'dist', '*.whl')\n", (887, 917), False, 'import os\n')] |
import os
import matplotlib.pyplot as plt
from torch.utils.tensorboard import SummaryWriter
writer = SummaryWriter(log_dir="./logs")
from tqdm import tqdm
import numpy as np
import torch
import torchvision.datasets as dset
import torch.nn as nn
import torchvision.transforms as transforms
import pyro
import pyro.distr... | [
"torch.nn.Softplus",
"torch.utils.tensorboard.SummaryWriter",
"torch.nn.Sigmoid",
"pyro.distributions.Normal",
"pyro.module",
"pyro.clear_param_store",
"tqdm.tqdm",
"pyro.distributions.Bernoulli",
"pyro.infer.Trace_ELBO",
"torch.cuda.is_available",
"torchvision.datasets.MNIST",
"torch.utils.da... | [((101, 132), 'torch.utils.tensorboard.SummaryWriter', 'SummaryWriter', ([], {'log_dir': '"""./logs"""'}), "(log_dir='./logs')\n", (114, 132), False, 'from torch.utils.tensorboard import SummaryWriter\n'), ((5683, 5702), 'pyro.optim.Adam', 'Adam', (["{'lr': 0.001}"], {}), "({'lr': 0.001})\n", (5687, 5702), False, 'from... |
# Copyright 2014: Mirantis 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | [
"traceback.extract_stack",
"inspect.stack",
"oslo_config.cfg.BoolOpt",
"functools.wraps",
"oslo_log.log.setup",
"oslo_log.log.register_options",
"oslo_log.log.getLogger"
] | [((1016, 1048), 'oslo_log.log.register_options', 'oslogging.register_options', (['CONF'], {}), '(CONF)\n', (1042, 1048), True, 'from oslo_log import log as oslogging\n'), ((817, 942), 'oslo_config.cfg.BoolOpt', 'cfg.BoolOpt', (['"""rally-debug"""'], {'default': '(False)', 'help': '"""Print debugging output only for Ral... |
from kivy.uix.screenmanager import Screen
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivymd.app import MDApp
from kivymd.uix.tab import MDTabsBase
from kivymd.icon_definitions import md_icons
from kivymd.uix.button import MDRectangleFlatButton
from kivy.lang import... | [
"kivymd.utils.asynckivy.sleep",
"kivy.lang.Builder.load_string",
"kivymd.uix.filemanager.MDFileManager",
"kivymd.uix.taptargetview.MDTapTargetView",
"kivy.core.window.Window.bind",
"kivymd.icon_definitions.md_icons.items",
"kivymd.uix.button.MDFloatingActionButtonSpeedDial",
"kivy.clock.Clock.schedule... | [((4082, 4098), 'kivy.properties.StringProperty', 'StringProperty', ([], {}), '()\n', (4096, 4098), False, 'from kivy.properties import StringProperty\n'), ((4202, 4238), 'kivy.core.window.Window.bind', 'Window.bind', ([], {'on_keyboard': 'self.events'}), '(on_keyboard=self.events)\n', (4213, 4238), False, 'from kivy.c... |
import json
from typing import List
from sortedcontainers import SortedList
from .allocator import Allocator
from .character import Character
from .char_position import CharPosition
class Doc:
def __init__(self, site=0) -> None:
"""
Create a new document
:param site: author id
:t... | [
"json.dumps",
"json.loads",
"sortedcontainers.SortedList"
] | [((495, 507), 'sortedcontainers.SortedList', 'SortedList', ([], {}), '()\n', (505, 507), False, 'from sortedcontainers import SortedList\n'), ((1933, 1954), 'json.loads', 'json.loads', (['raw_patch'], {}), '(raw_patch)\n', (1943, 1954), False, 'import json\n'), ((2995, 3028), 'json.dumps', 'json.dumps', (['patch'], {'s... |
from unittest import TestCase
import global_functions
import app
from app import flask_app
class TestApp(TestCase):
def setUp(self):
self.app = app
self.username = "newuser"
self.pword = "<PASSWORD>"
self.test_client_app = flask_app.test_client()
self.test_client_app.testin... | [
"global_functions.sha1_hash",
"app.flask_app.test_client"
] | [((261, 284), 'app.flask_app.test_client', 'flask_app.test_client', ([], {}), '()\n', (282, 284), False, 'from app import flask_app\n'), ((2241, 2279), 'global_functions.sha1_hash', 'global_functions.sha1_hash', (['self.pword'], {}), '(self.pword)\n', (2267, 2279), False, 'import global_functions\n')] |
# -*- coding: utf-8 -*- #
"""*********************************************************************************************"""
# FileName [ discriminator.py ]
# Synopsis [ Discriminator model ]
# Author [ <NAME> (Andi611) ]
# Copyright [ Copyleft(c), NTUEE, NTU, Taiwan ]
"""*********************... | [
"tensorflow.get_variable",
"tensorflow.transpose",
"math.sqrt",
"tensorflow.truncated_normal_initializer",
"tensorflow.nn.dropout",
"tensorflow.nn.softmax",
"tensorflow.reduce_mean",
"tensorflow.nn.embedding_lookup",
"tensorflow.placeholder",
"tensorflow.concat",
"tensorflow.train.AdamOptimizer"... | [((1653, 1718), 'tensorflow.placeholder', 'tf.placeholder', (['"""int32"""', '[None, self.max_seq_len]'], {'name': '"""input_x"""'}), "('int32', [None, self.max_seq_len], name='input_x')\n", (1667, 1718), True, 'import tensorflow as tf\n'), ((1736, 1801), 'tensorflow.placeholder', 'tf.placeholder', (['"""float32"""', '... |
#!/usr/bin/env python3
# Created on 05/01/2018
# @author: <NAME>
# @license: MIT-license
# Purpose: example of a simple finite state machine with a text-based game agent
# Explanation:
from enum import Enum
import time
import random
class state_type(Enum):
state_run = "Run Away"
state_patrol = "Patrol"
st... | [
"random.randint",
"time.sleep"
] | [((2224, 2244), 'random.randint', 'random.randint', (['(0)', '(1)'], {}), '(0, 1)\n', (2238, 2244), False, 'import random\n'), ((2759, 2772), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (2769, 2772), False, 'import time\n')] |
import logging
import logging.config
import requests
logging.config.fileConfig('logging.conf', disable_existing_loggers=False)
logger = logging.getLogger(__name__)
def log_response_and_raise_for_status(
response: requests.models.Response) -> None:
logger.debug(f'API response details:\n' \
f'\t- UR... | [
"logging.getLogger",
"logging.config.fileConfig"
] | [((54, 127), 'logging.config.fileConfig', 'logging.config.fileConfig', (['"""logging.conf"""'], {'disable_existing_loggers': '(False)'}), "('logging.conf', disable_existing_loggers=False)\n", (79, 127), False, 'import logging\n'), ((137, 164), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n'... |
from sklearn.linear_model import RidgeClassifierCV as _RidgeClassifierCV
from script.sklearn_like_toolkit.warpper.base.BaseWrapperClf import BaseWrapperClf
from script.sklearn_like_toolkit.warpper.base.MixIn import MetaBaseWrapperClfWithABC
class skRidgeCVClf(_RidgeClassifierCV, BaseWrapperClf, metaclass=MetaB... | [
"script.sklearn_like_toolkit.warpper.base.BaseWrapperClf.BaseWrapperClf.__init__",
"sklearn.linear_model.RidgeClassifierCV.__init__"
] | [((501, 599), 'sklearn.linear_model.RidgeClassifierCV.__init__', '_RidgeClassifierCV.__init__', (['self', 'alphas', 'fit_intercept', 'normalize', 'scoring', 'cv', 'class_weight'], {}), '(self, alphas, fit_intercept, normalize, scoring,\n cv, class_weight)\n', (528, 599), True, 'from sklearn.linear_model import Ridge... |
import random
from loader import *
import pygame
from spritesheet import *
class Powerup(pygame.sprite.Sprite):
#type e o tipo de powerups
def __init__(self,tipo,screen):
pygame.sprite.Sprite.__init__(self)
self.tipo = tipo
if tipo == 1:
#e um escudo
ss = ... | [
"pygame.sprite.Sprite.__init__",
"random.randrange"
] | [((194, 229), 'pygame.sprite.Sprite.__init__', 'pygame.sprite.Sprite.__init__', (['self'], {}), '(self)\n', (223, 229), False, 'import pygame\n'), ((1805, 1841), 'random.randrange', 'random.randrange', (['(70)', '(screen[0] - 70)'], {}), '(70, screen[0] - 70)\n', (1821, 1841), False, 'import random\n'), ((1857, 1893), ... |
"""
Encoding = UTF-8
By <NAME>, 2019/3/18
Usage: get image file from the onstage
"""
from flask import request
import cv2
import os
def get_image():
img = request.files.get('photo')
path = "static/images/"
file_path = path + img.filename
img.save(file_path)
img = cv2.imread(file_path)
cv2.imwri... | [
"os.path.join",
"flask.request.files.get",
"cv2.imread"
] | [((160, 186), 'flask.request.files.get', 'request.files.get', (['"""photo"""'], {}), "('photo')\n", (177, 186), False, 'from flask import request\n'), ((285, 306), 'cv2.imread', 'cv2.imread', (['file_path'], {}), '(file_path)\n', (295, 306), False, 'import cv2\n'), ((323, 364), 'os.path.join', 'os.path.join', (['"""sta... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from subprocess import run, PIPE, TimeoutExpired
from xmltodict import parse as parsexml
# timeout
# errorcode
class IpsetError(RuntimeError):
"""ipset returned an error"""
def _run_cmd(command, args=[]):
"""
Helper function to help calling and decoding i... | [
"subprocess.run",
"xmltodict.parse"
] | [((539, 628), 'subprocess.run', 'run', (["(['ipset', command, '-output', 'xml'] + args)"], {'stdout': 'PIPE', 'stderr': 'PIPE', 'timeout': '(2)'}), "(['ipset', command, '-output', 'xml'] + args, stdout=PIPE, stderr=PIPE,\n timeout=2)\n", (542, 628), False, 'from subprocess import run, PIPE, TimeoutExpired\n'), ((779... |
import os
import paramiko
import queue
from botocore.exceptions import EndpointConnectionError
from ebcli.objects.exceptions import NoRegionError
from ebcli.objects.exceptions import ServiceError
from os.path import expanduser
from paramiko.ssh_exception import SSHException
from threading import Thread
from queue impo... | [
"classes.get_last_rotated_logs.GetLastRotatedLogs",
"paramiko.AutoAddPolicy",
"util.aws_util.authorize_ssh",
"util.aws_util.revoke_ssh_authorization",
"queue.put",
"os.path.basename",
"util.curl_util.curl_post_data",
"threading.Thread",
"queue.Queue",
"paramiko.SSHClient",
"os.path.expanduser",
... | [((1364, 1377), 'queue.Queue', 'queue.Queue', ([], {}), '()\n', (1375, 1377), False, 'import queue\n'), ((11548, 11568), 'paramiko.SSHClient', 'paramiko.SSHClient', ([], {}), '()\n', (11566, 11568), False, 'import paramiko\n'), ((895, 920), 'os.path.basename', 'os.path.basename', (['key_pem'], {}), '(key_pem)\n', (911,... |
from sanic_openapi import doc
'''**********************************************************
>>> 策略model <<<
StrategyDto:入口,tradeCondition:交易条件,riskControl:风险控制
tradeCondition:{
'params':{
'args':[],
'logic':logic
... | [
"sanic_openapi.doc.List",
"sanic_openapi.doc.String",
"sanic_openapi.doc.Float",
"sanic_openapi.doc.Integer"
] | [((446, 478), 'sanic_openapi.doc.String', 'doc.String', (['"""比较方法"""'], {'choices': '"""le"""'}), "('比较方法', choices='le')\n", (456, 478), False, 'from sanic_openapi import doc\n'), ((493, 522), 'sanic_openapi.doc.Float', 'doc.Float', (['"""比较值"""'], {'choices': '(0.8)'}), "('比较值', choices=0.8)\n", (502, 522), False, '... |
from handler.base_plugin import BasePlugin
from vk.helpers import parse_user_id
import peewee_async, peewee, asyncio, random, time
# Requirements:
# PeeweePlugin
#
class DuelerPlugin(BasePlugin):
__slots__ = ("commands", "prefixes", "models", "pwmanager", "active")
def __init__(self, prefixes=("",), _help="... | [
"random.shuffle",
"peewee.BigIntegerField",
"peewee.ForeignKeyField",
"peewee.IntegerField",
"peewee.TextField",
"peewee_async.delete_object",
"peewee_async.create_object",
"vk.helpers.parse_user_id",
"asyncio.sleep",
"random.random",
"time.time"
] | [((5641, 5652), 'time.time', 'time.time', ([], {}), '()\n', (5650, 5652), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((1241, 1259), 'peewee.TextField', 'peewee.TextField', ([], {}), '()\n', (1257, 1259), False, 'import peewee_async, peewee, asyncio, random, time\n'), ((1279, 1297), 'peewee.TextFiel... |
# Loads the data and an autoencoder model. The original data is passed
# through the AE and the latent space is fed to the qsvm network.
import sys
import os
import numpy as np
sys.path.append("..")
from .terminal_colors import tcols
from autoencoders import data as aedata
from autoencoders import util as aeutil
cla... | [
"numpy.ceil",
"autoencoders.data.AE_data",
"numpy.arange",
"os.path.join",
"autoencoders.util.choose_ae_model",
"numpy.array_split",
"os.path.dirname",
"autoencoders.util.import_hyperparams",
"numpy.concatenate",
"sys.path.append",
"numpy.random.RandomState"
] | [((178, 199), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (193, 199), False, 'import sys\n'), ((1928, 1955), 'os.path.dirname', 'os.path.dirname', (['model_path'], {}), '(model_path)\n', (1943, 1955), False, 'import os\n'), ((1974, 2024), 'os.path.join', 'os.path.join', (['model_folder', '"""h... |
# Twisted Imports
from twisted.python.constants import ValueConstant, Values
class State (Values):
READY = ValueConstant("ready")
RUNNING = ValueConstant("running")
PAUSED = ValueConstant("paused")
COMPLETE = ValueConstant("complete")
CANCELLED = ValueConstant("cancelled")
ERROR = ValueConstant("error")
class E... | [
"twisted.python.constants.ValueConstant"
] | [((109, 131), 'twisted.python.constants.ValueConstant', 'ValueConstant', (['"""ready"""'], {}), "('ready')\n", (122, 131), False, 'from twisted.python.constants import ValueConstant, Values\n'), ((143, 167), 'twisted.python.constants.ValueConstant', 'ValueConstant', (['"""running"""'], {}), "('running')\n", (156, 167),... |
import numpy as np
import torch
from torch import nn
def identity(x):
return x
def fanin_init(tensor):
size = tensor.size()
if len(size) == 2:
fan_in = size[0]
elif len(size) > 2:
fan_in = np.prod(size[1:])
else:
raise Exception("Tensor shape must have dimensions >= 2")
... | [
"numpy.prod",
"numpy.sqrt",
"torch.reciprocal",
"torch.sum",
"torch.normal",
"torch.zeros",
"torch.clamp",
"torch.ones"
] | [((530, 568), 'torch.clamp', 'torch.clamp', (['sigmas_squared'], {'min': '(1e-07)'}), '(sigmas_squared, min=1e-07)\n', (541, 568), False, 'import torch\n'), ((336, 351), 'numpy.sqrt', 'np.sqrt', (['fan_in'], {}), '(fan_in)\n', (343, 351), True, 'import numpy as np\n'), ((669, 707), 'torch.sum', 'torch.sum', (['(mus / s... |
from dataclasses import dataclass
import netCDF4
import numpy as np
from openamundsen import constants, errors, fileio, util
import pandas as pd
import pandas.tseries.frequencies
import pyproj
import xarray as xr
_ALLOWED_OFFSETS = [
pd.tseries.offsets.YearEnd,
pd.tseries.offsets.YearBegin,
pd.tseries.off... | [
"openamundsen.errors.ConfigurationError",
"pyproj.crs.CRS",
"numpy.repeat",
"numpy.arange",
"pandas.Timedelta",
"netCDF4.Dataset",
"pandas.to_datetime",
"numpy.flatnonzero",
"xarray.Dataset",
"numpy.array",
"openamundsen.util.offset_to_timedelta",
"pandas.period_range",
"openamundsen.fileio.... | [((17670, 17706), 'openamundsen.util.offset_to_timedelta', 'util.offset_to_timedelta', (['model_freq'], {}), '(model_freq)\n', (17694, 17706), False, 'from openamundsen import constants, errors, fileio, util\n'), ((14361, 14392), 'xarray.Dataset', 'xr.Dataset', (['data'], {'coords': 'coords'}), '(data, coords=coords)\n... |
# Autogenerated by onnx-model-maker. Don't modify it manually.
import onnx
import onnx.helper
import onnx.numpy_helper
from onnx_model_maker import omm
from onnx_model_maker import onnx_mm_export
from onnx_model_maker.ops.op_helper import _add_input
@onnx_mm_export("v2.LabelEncoder")
def LabelEncoder(X, **kwargs):
... | [
"onnx_model_maker.ops.op_helper._add_input",
"onnx.helper.make_node",
"onnx_model_maker.omm.model.graph.node.append",
"onnx.checker.check_node",
"onnx_model_maker.onnx_mm_export"
] | [((254, 287), 'onnx_model_maker.onnx_mm_export', 'onnx_mm_export', (['"""v2.LabelEncoder"""'], {}), "('v2.LabelEncoder')\n", (268, 287), False, 'from onnx_model_maker import onnx_mm_export\n'), ((768, 794), 'onnx_model_maker.onnx_mm_export', 'onnx_mm_export', (['"""v2.Split"""'], {}), "('v2.Split')\n", (782, 794), Fals... |
import shutil
import os
import filecmp
from src.masonite.commands.presets.Remove import Remove
import unittest
class TestRemove(unittest.TestCase):
def test_update_package_array(self):
expected_packages = {}
# Verify it works with no existing packages
self.assertDictEqual(expected_packa... | [
"os.path.exists",
"shutil.copyfile",
"shutil.rmtree",
"filecmp.cmp",
"src.masonite.commands.presets.Remove.Remove",
"os.remove"
] | [((1658, 1685), 'os.remove', 'os.remove', (['"""webpack.mix.js"""'], {}), "('webpack.mix.js')\n", (1667, 1685), False, 'import os\n'), ((2081, 2110), 'shutil.rmtree', 'shutil.rmtree', (['"""resources/js"""'], {}), "('resources/js')\n", (2094, 2110), False, 'import shutil\n'), ((2119, 2150), 'shutil.rmtree', 'shutil.rmt... |
from django.contrib.auth import forms
from django.contrib.auth import models
from django.contrib.auth.models import User
from django import forms
from django.forms import fields, widgets
from .models import Comment, Post, Profile
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit,Layout,F... | [
"django.forms.Textarea",
"django.forms.EmailField",
"crispy_forms.layout.Submit",
"crispy_forms.helper.FormHelper"
] | [((373, 385), 'crispy_forms.helper.FormHelper', 'FormHelper', ([], {}), '()\n', (383, 385), False, 'from crispy_forms.helper import FormHelper\n'), ((986, 1004), 'django.forms.EmailField', 'forms.EmailField', ([], {}), '()\n', (1002, 1004), False, 'from django import forms\n'), ((439, 490), 'crispy_forms.layout.Submit'... |
# coding: utf-8
# Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
from __future__ import absolute_import
import lazy_import as _lazy_import
Bucket = _lazy_import.lazy_class("oci.object_storage.models.bucket.Bucket")
BucketSummary = _lazy_import.lazy_class("oci.object_storage.models.bucke... | [
"lazy_import.lazy_class"
] | [((181, 247), 'lazy_import.lazy_class', '_lazy_import.lazy_class', (['"""oci.object_storage.models.bucket.Bucket"""'], {}), "('oci.object_storage.models.bucket.Bucket')\n", (204, 247), True, 'import lazy_import as _lazy_import\n'), ((264, 350), 'lazy_import.lazy_class', '_lazy_import.lazy_class', (['"""oci.object_stora... |
import matplotlib.pyplot as plt
import seaborn as sns
import pandas
import sklearn.tree
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection impo... | [
"sklearn.model_selection.GridSearchCV",
"sklearn.preprocessing.LabelEncoder",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"sklearn.tree.DecisionTreeClassifier",
"sklearn.ensemble.RandomForestClassifier",
"pandas.cut",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.figure",
"pandas.... | [((400, 414), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (412, 414), False, 'from sklearn.preprocessing import LabelEncoder\n'), ((423, 682), 'pandas.read_csv', 'pandas.read_csv', (['"""adult.data"""'], {'sep': '""","""', 'names': "['age', 'workclass', 'fnlwgt', 'education', 'education-num'... |
# Copyright 2021 DengBoCong. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | [
"dialogue.tools.get_dict_string",
"dialogue.pytorch.load_dataset.load_data",
"dialogue.pytorch.utils.save_checkpoint",
"dialogue.tools.ProgressBar",
"time.time"
] | [((4153, 4574), 'dialogue.pytorch.load_dataset.load_data', 'load_data', ([], {'dict_path': 'self.dict_path', 'batch_size': 'self.batch_size', 'train_data_type': 'self.train_data_type', 'valid_data_type': 'self.valid_data_type', 'max_sentence': 'self.max_sentence', 'valid_data_split': 'valid_data_split', 'train_data_pat... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Importa as bibliotecas básicas para o funcionamento da tradução
import json
import xml
import xmltodict
import jsonschema
# Classe Model é responsável por validar o Input/Output, i.e., a estrutura do autômato
class Model(object):
def __init__(self):
self.m... | [
"json.loads",
"xmltodict.parse",
"json.dumps",
"xmltodict.unparse",
"json.load"
] | [((4306, 4325), 'json.loads', 'json.loads', (['content'], {}), '(content)\n', (4316, 4325), False, 'import json\n'), ((4386, 4422), 'xmltodict.unparse', 'xmltodict.unparse', (['temp'], {'pretty': '(True)'}), '(temp, pretty=True)\n', (4403, 4422), False, 'import xmltodict\n'), ((934, 954), 'json.load', 'json.load', (['d... |
import sys
import numpy as np
import mc3
def quad(p, x):
"""
Quadratic polynomial function.
Parameters
p: Polynomial constant, linear, and quadratic coefficients.
x: Array of dependent variables where to evaluate the polynomial.
Returns
y: Polinomial evaluated at x: y(x) = p0... | [
"numpy.random.normal",
"numpy.abs",
"numpy.array",
"numpy.linspace",
"mc3.sample",
"numpy.random.seed"
] | [((593, 612), 'numpy.random.seed', 'np.random.seed', (['(314)'], {}), '(314)\n', (607, 612), True, 'import numpy as np\n'), ((618, 642), 'numpy.linspace', 'np.linspace', (['(0)', '(10)', '(1000)'], {}), '(0, 10, 1000)\n', (629, 642), True, 'import numpy as np\n'), ((718, 745), 'numpy.random.normal', 'np.random.normal',... |
#!/usr/bin/env python3
# Copyright 2020 <NAME>
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed... | [
"trio.open_nursery",
"importlib_resources.read_text"
] | [((828, 874), 'importlib_resources.read_text', 'pkg_resources.read_text', (['static', '"""device.html"""'], {}), "(static, 'device.html')\n", (851, 874), True, 'import importlib_resources as pkg_resources\n'), ((894, 941), 'importlib_resources.read_text', 'pkg_resources.read_text', (['static', '"""connector.js"""'], {}... |
from typing import List
from fastapi import APIRouter, UploadFile, File, Depends
import file.controllers as file_controller
import level.controllers as level_controller
from decorators import proto_resp
from level.models import Level
from file.models import File as FileT
from level.views import LevelMetaDataOut, Leve... | [
"level.controllers.add_user_to_level",
"level.views.LevelMetaDataOut.from_orm",
"level.controllers.remove_level",
"file.controllers.download_file",
"level.controllers.add_level",
"level.views.LevelMetaDatasOut",
"level.controllers.increment",
"level.controllers.get_level",
"level.controllers.get_lev... | [((449, 460), 'fastapi.APIRouter', 'APIRouter', ([], {}), '()\n', (458, 460), False, 'from fastapi import APIRouter, UploadFile, File, Depends\n'), ((562, 571), 'fastapi.Depends', 'Depends', ([], {}), '()\n', (569, 571), False, 'from fastapi import APIRouter, UploadFile, File, Depends\n'), ((598, 607), 'fastapi.File', ... |
#!/usr/bin/python3
# Copyright 2018 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | [
"tflmlib.LMBasic.get_model_fn",
"tflmlib.InputData",
"tflmlib.TokenizerSimple",
"tensorflow.variable_scope",
"tflmlib.LMBasic.restore_session",
"os.path.join",
"numpy.argmax",
"tflmlib.LMBasic",
"numpy.array",
"tflmlib.Vocab",
"tflmlib.SNLPConnection",
"tflmlib.TokenizerSmartA",
"tflmlib.LMB... | [((1119, 1151), 'tflmlib.SNLPConnection', 'SNLPConnection', (['snlp_server.port'], {}), '(snlp_server.port)\n', (1133, 1151), False, 'from tflmlib import SNLPConnection\n'), ((1407, 1508), 'tflmlib.InputData', 'InputData', (['self.config.batch_size', 'self.config.seq_length'], {'history_size': 'self.config.history_size... |
# !usr/bin/env python
# -*- coding: utf-8 -*-
#
# Licensed under a 3-clause BSD license.
#
# @Author: <NAME>
# @Date: 2018-10-11 17:51:43
# @Last modified by: <NAME>
# @Last Modified time: 2018-11-29 17:23:15
from __future__ import print_function, division, absolute_import
import numpy as np
import astropy
import... | [
"numpy.log10",
"numpy.argmax",
"marvin.utils.general.general.get_drpall_table",
"marvin.utils.plot.scatter.plot",
"marvin.tools.quantities.spectrum.Spectrum",
"numpy.argmin"
] | [((1530, 1567), 'numpy.argmax', 'np.argmax', (["[par1['snr'], par2['snr']]"], {}), "([par1['snr'], par2['snr']])\n", (1539, 1567), True, 'import numpy as np\n'), ((1585, 1622), 'numpy.argmin', 'np.argmin', (["[par1['rms'], par2['rms']]"], {}), "([par1['rms'], par2['rms']])\n", (1594, 1622), True, 'import numpy as np\n'... |
import pathlib
from secret import API_KEY
PATH_ROOT = pathlib.Path(__file__).parent
PATH_REPLAYS_STUB = PATH_ROOT / "replays"
API_BASE = "https://osu.ppy.sh/api/"
API_REPLAY = API_BASE + "get_replay?k=" + API_KEY + "&m=0&b={}&u={}"
API_SCORES_ALL = API_BASE + "get_scores?k=" + API_KEY + "&m=0&b={}&limit={}"
API_SCOR... | [
"pathlib.Path"
] | [((56, 78), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (68, 78), False, 'import pathlib\n')] |
# -*- coding: utf-8 -*-
import logging
from speaklater import make_lazy_string
from quokka.modules.accounts.models import User
logger = logging.getLogger()
def lazy_str_setting(key, default=None):
from flask import current_app
return make_lazy_string(
lambda: current_app.config.get(key, default)
... | [
"logging.getLogger",
"quokka.modules.accounts.models.User.objects.get",
"flask.ext.security.current_user.is_authenticated",
"flask.current_app.config.get"
] | [((137, 156), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (154, 156), False, 'import logging\n'), ((574, 610), 'quokka.modules.accounts.models.User.objects.get', 'User.objects.get', ([], {'id': 'current_user.id'}), '(id=current_user.id)\n', (590, 610), False, 'from quokka.modules.accounts.models import ... |
from __future__ import annotations
from parla.cpu_impl import cpu
from parla.task_runtime import get_current_devices, get_scheduler_context
from parla.device import Device
from .coherence import MemoryOperation, Coherence, CPU_INDEX
import threading
import numpy
try: # if the system has no GPU
import cupy
n... | [
"cupy.asnumpy",
"cupy.empty_like",
"threading.Lock",
"parla.task_runtime.get_current_devices",
"parla.task_runtime.get_scheduler_context",
"cupy.cuda.runtime.getDeviceCount",
"cupy.cuda.stream.get_current_stream",
"cupy.cuda.get_current_stream",
"cupy.asarray"
] | [((333, 367), 'cupy.cuda.runtime.getDeviceCount', 'cupy.cuda.runtime.getDeviceCount', ([], {}), '()\n', (365, 367), False, 'import cupy\n'), ((1528, 1544), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (1542, 1544), False, 'import threading\n'), ((6110, 6140), 'cupy.cuda.get_current_stream', 'cupy.cuda.get_curr... |
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.applications.inception_resnet_v2 import InceptionResNetV2
from tensorflow.keras.applications.inception_resnet_v2 import preprocess_input
from tensorflow.keras.optimizers import Adam
import matplotlib
matplotlib.use('agg')
impo... | [
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.ylabel",
"matplotlib.use",
"matplotlib.pyplot.xlabel",
"tensorflow.keras.layers.Dropout",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.style.use",
"tensorflow.keras.optimizers.Adam",
"matplotlib.pyplot.close",
"matplotlib.pyplot.figure",
"tensorflo... | [((294, 315), 'matplotlib.use', 'matplotlib.use', (['"""agg"""'], {}), "('agg')\n", (308, 315), False, 'import matplotlib\n'), ((2894, 3064), 'tensorflow.keras.preprocessing.image_dataset_from_directory', 'tf.keras.preprocessing.image_dataset_from_directory', (['dataset_Keras_PATH'], {'validation_split': '(0.3)', 'subs... |
"""
File: bsd_patches.py
Author: Nrupatunga
Email: <EMAIL>
Github: https://github.com/nrupatunga
Description: BSDS500 patches
"""
import time
from pathlib import Path
import h5py
import numpy as np
from tqdm import tqdm
mode = 'train'
mat_root_dir = f'/media/nthere/datasets/DIV_superres/patches/train/'
out_root_dir =... | [
"numpy.mean",
"pathlib.Path",
"numpy.asarray",
"h5py.File",
"numpy.std"
] | [((1031, 1048), 'numpy.asarray', 'np.asarray', (['means'], {}), '(means)\n', (1041, 1048), True, 'import numpy as np\n'), ((1060, 1076), 'numpy.asarray', 'np.asarray', (['stds'], {}), '(stds)\n', (1070, 1076), True, 'import numpy as np\n'), ((1088, 1105), 'numpy.mean', 'np.mean', (['means', '(1)'], {}), '(means, 1)\n',... |
#
# (c) Copyright 2018 Hewlett Packard Enterprise Development LP
#
# 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 applicab... | [
"fixtures.FakeLogger"
] | [((1014, 1054), 'fixtures.FakeLogger', 'fixtures.FakeLogger', ([], {'level': 'logging.DEBUG'}), '(level=logging.DEBUG)\n', (1033, 1054), False, 'import fixtures\n')] |
import asyncio
import copy
import discord
import feedparser
import sys
import time
import datetime
import traceback
import os
import json
from discord.ext import commands
from urllib.parse import urlparse, parse_qs
class Loop:
"""
Loop events.
"""
def __init__(self, bot):
self.bot = bot
... | [
"urllib.parse.urlparse",
"feedparser.parse",
"discord.utils.get",
"traceback.print_tb",
"copy.copy",
"os.path.isfile",
"datetime.datetime.now",
"asyncio.sleep",
"json.load",
"datetime.timedelta",
"json.dump"
] | [((590, 620), 'datetime.timedelta', 'datetime.timedelta', ([], {'minutes': '(30)'}), '(minutes=30)\n', (608, 620), False, 'import datetime\n'), ((652, 682), 'datetime.timedelta', 'datetime.timedelta', ([], {'minutes': '(10)'}), '(minutes=10)\n', (670, 682), False, 'import datetime\n'), ((530, 553), 'datetime.datetime.n... |
from unittest.mock import Mock, patch
import pandas as pd
import pytest
from faker import Faker
from faker.config import DEFAULT_LOCALE
from rdt.transformers.numerical import NumericalTransformer
from sdv.constraints.base import Constraint
from sdv.constraints.errors import MissingConstraintColumnError
from sdv.error... | [
"sdv.constraints.base.Constraint",
"pandas.Series",
"unittest.mock.Mock",
"sdv.metadata.Table.from_dict",
"sdv.metadata.Table._make_anonymization_mappings",
"sdv.metadata.Table._validate_data_on_constraints",
"sdv.metadata.Table",
"faker.Faker",
"sdv.metadata.Table._transform_constraints",
"sdv.me... | [((4250, 4277), 'unittest.mock.patch', 'patch', (['"""sdv.metadata.Table"""'], {}), "('sdv.metadata.Table')\n", (4255, 4277), False, 'from unittest.mock import Mock, patch\n'), ((6146, 6173), 'unittest.mock.patch', 'patch', (['"""sdv.metadata.Table"""'], {}), "('sdv.metadata.Table')\n", (6151, 6173), False, 'from unitt... |
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import os
from pymatgen import Composition
class TransformReadingPeriodicTable():
def __init__(self, formula=None, rel_cif_file_path='write cif file path', data_dir='../data'):
self.formula = formula
self.allowed... | [
"pymatgen.Composition.from_dict",
"numpy.sum",
"numpy.zeros",
"pymatgen.Composition",
"numpy.round"
] | [((1828, 1871), 'numpy.zeros', 'np.zeros', (['[4, 7, 18 + 14]'], {'dtype': 'np.float32'}), '([4, 7, 18 + 14], dtype=np.float32)\n', (1836, 1871), True, 'import numpy as np\n'), ((3981, 4016), 'numpy.sum', 'np.sum', (['periodic_table_form'], {'axis': '(0)'}), '(periodic_table_form, axis=0)\n', (3987, 4016), True, 'impor... |
# [h] import ufo into layer
import hTools2.dialogs.font.layer_import
reload(hTools2.dialogs.font.layer_import)
from hTools2.dialogs.font.layer_import import importUFOIntoLayerDialog
importUFOIntoLayerDialog()
| [
"hTools2.dialogs.font.layer_import.importUFOIntoLayerDialog"
] | [((185, 211), 'hTools2.dialogs.font.layer_import.importUFOIntoLayerDialog', 'importUFOIntoLayerDialog', ([], {}), '()\n', (209, 211), False, 'from hTools2.dialogs.font.layer_import import importUFOIntoLayerDialog\n')] |
# -*- coding: utf-8 -*-
import json
import requests
from django.utils.translation import ugettext as _
from django.utils import translation
from django.core.cache import cache
from common.log import logger
from conf.default import APP_ID, APP_TOKEN, BK_PAAS_HOST
from constants import (HEADERS)
def get_data_by_api(... | [
"json.loads",
"requests.post",
"common.log.logger.info",
"json.dumps",
"requests.get",
"constants.HEADERS.update",
"django.utils.translation.get_language",
"django.utils.translation.ugettext",
"django.core.cache.cache.set",
"django.core.cache.cache.get"
] | [((616, 641), 'common.log.logger.info', 'logger.info', (['request_info'], {}), '(request_info)\n', (627, 641), False, 'from common.log import logger\n'), ((2471, 2492), 'django.core.cache.cache.get', 'cache.get', (['cache_name'], {}), '(cache_name)\n', (2480, 2492), False, 'from django.core.cache import cache\n'), ((45... |
import random
from kaggle_environments.envs.rps.utils import get_score
last_counter_action = None
def counter_reactionary(observation, configuration):
global last_counter_action
if observation.step == 0:
last_counter_action = random.randrange(0, configuration.signs)
elif get_score(last_counter_a... | [
"kaggle_environments.envs.rps.utils.get_score",
"random.randrange"
] | [((246, 286), 'random.randrange', 'random.randrange', (['(0)', 'configuration.signs'], {}), '(0, configuration.signs)\n', (262, 286), False, 'import random\n'), ((296, 358), 'kaggle_environments.envs.rps.utils.get_score', 'get_score', (['last_counter_action', 'observation.lastOpponentAction'], {}), '(last_counter_actio... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ======================================================================================================================
# Imports
# ======================================================================================================================
import json
import ya... | [
"moleculerize.generate_hosts_inventory",
"json.loads",
"os.getenv",
"click.testing.CliRunner",
"pytest.raises",
"moleculerize._load_input_file",
"pytest.mark.skipif",
"moleculerize.render_molecule_template"
] | [((1069, 1160), 'pytest.mark.skipif', 'pytest.mark.skipif', (['SKIP_EVERYTHING'], {'reason': '"""Skip if we are creating/modifying tests!"""'}), "(SKIP_EVERYTHING, reason=\n 'Skip if we are creating/modifying tests!')\n", (1087, 1160), False, 'import pytest\n'), ((1534, 1625), 'pytest.mark.skipif', 'pytest.mark.skip... |
from archive.groups import Group
from archive.teams import Team
from logging import Logging
from itertools import cycle
import datetime
from copy import deepcopy
from sys import exit
import collections
from os import path, getcwd
class Tournament:
"""
Store (and initialise) dictionary and storage structures
... | [
"archive.teams.Team",
"collections.namedtuple",
"os.getcwd",
"archive.groups.Group",
"datetime.datetime.now",
"sys.exit",
"datetime.datetime.strftime"
] | [((17594, 17735), 'collections.namedtuple', 'collections.namedtuple', (['"""Timings"""', "['group_game_length', 'game_length', 'game_break', 'day1_start',\n 'day2_start', 'day1_end', 'day2_end']"], {}), "('Timings', ['group_game_length', 'game_length',\n 'game_break', 'day1_start', 'day2_start', 'day1_end', 'day2... |
# Generated by Django 2.1.4 on 2019-07-19 00:50
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='post',
old_name='data_published',
n... | [
"django.db.migrations.RenameField"
] | [((213, 312), 'django.db.migrations.RenameField', 'migrations.RenameField', ([], {'model_name': '"""post"""', 'old_name': '"""data_published"""', 'new_name': '"""date_published"""'}), "(model_name='post', old_name='data_published',\n new_name='date_published')\n", (235, 312), False, 'from django.db import migrations... |
from .base import ConfigMNISTBase
from pipeline.models.classification import ClassificationModuleLinear
from pipeline.models.image_classification import Resnet18Model
import torch.nn as nn
class Config(ConfigMNISTBase):
def __init__(self):
model = nn.Sequential(
Resnet18Model(),
... | [
"pipeline.models.image_classification.Resnet18Model",
"pipeline.models.classification.ClassificationModuleLinear"
] | [((291, 306), 'pipeline.models.image_classification.Resnet18Model', 'Resnet18Model', ([], {}), '()\n', (304, 306), False, 'from pipeline.models.image_classification import Resnet18Model\n'), ((320, 378), 'pipeline.models.classification.ClassificationModuleLinear', 'ClassificationModuleLinear', (['Resnet18Model.NUM_FEAT... |