code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
from matplotlib import pyplot as plt
def compare_planned_to_actual(z_actual, z_path, t, additional=None):
plt.subplot(211)
plt.plot(t,z_path,linestyle='-',marker='.',color='red')
plt.plot(t,z_actual,linestyle='-',color='blue')
if additional:
plt.plot(t, additional, linestyle="-", color="black")... | [
"matplotlib.pyplot.grid",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show... | [((111, 127), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(211)'], {}), '(211)\n', (122, 127), True, 'from matplotlib import pyplot as plt\n'), ((132, 191), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'z_path'], {'linestyle': '"""-"""', 'marker': '"""."""', 'color': '"""red"""'}), "(t, z_path, linestyle='-', marker... |
import torchvision.transforms as T
from torchvision.datasets import ImageFolder
class WHURS19(ImageFolder):
""" WHU-RS19 dataset from'Structural High-resolution Satellite Image Indexing', Xia at al. (2010)
https://hal.archives-ouvertes.fr/file/index/docid/458685/filename/structural_satellite_indexing_XYDG.pdf... | [
"torchvision.transforms.ToTensor"
] | [((442, 454), 'torchvision.transforms.ToTensor', 'T.ToTensor', ([], {}), '()\n', (452, 454), True, 'import torchvision.transforms as T\n')] |
import numpy as np
import pandas as pd
import plotly.graph_objs as go
# import plotly.plotly as py
dates = pd.date_range('01-Jan-2010', pd.datetime.now().date(), freq='D')
df = pd.DataFrame(100 + np.random.randn(dates.size).cumsum(), dates, columns=['AAPL'])
trace = go.Scatter(x=df.index, y=df.AAPL)
data = [trace]
l... | [
"plotly.graph_objs.Figure",
"numpy.random.randn",
"plotly.graph_objs.Scatter",
"pandas.datetime.now"
] | [((270, 303), 'plotly.graph_objs.Scatter', 'go.Scatter', ([], {'x': 'df.index', 'y': 'df.AAPL'}), '(x=df.index, y=df.AAPL)\n', (280, 303), True, 'import plotly.graph_objs as go\n'), ((1145, 1156), 'plotly.graph_objs.Figure', 'go.Figure', ([], {}), '()\n', (1154, 1156), True, 'import plotly.graph_objs as go\n'), ((138, ... |
# Python 3 server example
from http.server import BaseHTTPRequestHandler, HTTPServer
import sys
import os.path
import socket
import base64
hostName = socket.gethostbyname(socket.gethostname())
serverPort = 8080
reply = b"\x12\01Hi there - from the Python server!\x12\x00\x80"
def recover(a):
# hexdump via https:... | [
"base64.b64encode",
"http.server.HTTPServer",
"socket.gethostname"
] | [((172, 192), 'socket.gethostname', 'socket.gethostname', ([], {}), '()\n', (190, 192), False, 'import socket\n'), ((2565, 2609), 'http.server.HTTPServer', 'HTTPServer', (['(hostName, serverPort)', 'MyServer'], {}), '((hostName, serverPort), MyServer)\n', (2575, 2609), False, 'from http.server import BaseHTTPRequestHan... |
from lcu_driver import Connector
connector = Connector()
@connector.ready
async def connect(connection):
print('LCU API is ready to be used.')
@connector.close
async def disconnect(connection):
print('Finished task')
connector.start()
| [
"lcu_driver.Connector"
] | [((46, 57), 'lcu_driver.Connector', 'Connector', ([], {}), '()\n', (55, 57), False, 'from lcu_driver import Connector\n')] |
from flask_babel import gettext
from dateutil import rrule, parser
from datetime import datetime, date, timedelta
from supermamas.areas.districts import District
from supermamas.areas.cities import City
class Service:
__instance = None
def __new__(cls, district_repository=None, city_repository=None):
... | [
"supermamas.areas.cities.City",
"flask_babel.gettext",
"supermamas.areas.districts.District"
] | [((1368, 1400), 'flask_babel.gettext', 'gettext', (['u"""City name is missing"""'], {}), "(u'City name is missing')\n", (1375, 1400), False, 'from flask_babel import gettext\n'), ((1444, 1450), 'supermamas.areas.cities.City', 'City', ([], {}), '()\n', (1448, 1450), False, 'from supermamas.areas.cities import City\n'), ... |
# -*- coding: utf-8 -*-
# @Author: Clarence
# @Date: 2018-08-11 17:24:59
# @Last Modified by: Clarence
# @Last Modified time: 2018-08-12 01:16:19
import redis
class TestString(object):
"""
set --设置值
get --获取值
mset --设置多个键值对
mget --获取多个键值对
append --添加字符串
del --删除
incr/decr --增加/减少1
"""
def __init__(self)... | [
"redis.StrictRedis"
] | [((433, 485), 'redis.StrictRedis', 'redis.StrictRedis', ([], {'host': '"""localhost"""', 'port': '(6379)', 'db': '(0)'}), "(host='localhost', port=6379, db=0)\n", (450, 485), False, 'import redis\n')] |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 15 21:56:08 2020
@author: <NAME>
"""
# STEP1----------------- # Importing the libraries------------
#-------------------------------------------------------------
import os
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import glob
... | [
"sklearn.preprocessing.LabelEncoder",
"tensorflow.python.client.device_lib.list_local_devices",
"pandas.read_csv",
"matplotlib.pyplot.ylabel",
"sklearn.metrics.classification_report",
"sklearn.ensemble.AdaBoostClassifier",
"sklearn.model_selection.StratifiedKFold",
"keras.layers.Dense",
"numpy.mean"... | [((1638, 1678), 'os.chdir', 'os.chdir', (['"""\\\\ML4TakeOver\\\\Data\\\\RawData"""'], {}), "('\\\\ML4TakeOver\\\\Data\\\\RawData')\n", (1646, 1678), False, 'import os\n'), ((1692, 1703), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1701, 1703), False, 'import os\n'), ((1827, 1872), 'pandas.read_csv', 'pd.read_csv', ([... |
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# @author: <NAME>
import os
from typing import Dict, Optional, Tuple, cast
import gym
import hydra.utils
from mbrl.env.offline_data import load_dataset_and_env
import numpy as np
import omegacon... | [
"numpy.random.default_rng",
"mbrl.env.offline_data.load_dataset_and_env",
"numpy.logical_or",
"os.getcwd",
"torch.Generator"
] | [((1098, 1134), 'numpy.random.default_rng', 'np.random.default_rng', ([], {'seed': 'cfg.seed'}), '(seed=cfg.seed)\n', (1119, 1134), True, 'import numpy as np\n'), ((2285, 2342), 'mbrl.env.offline_data.load_dataset_and_env', 'load_dataset_and_env', (['cfg.model_pretraining.train_dataset'], {}), '(cfg.model_pretraining.t... |
#!/usr/bin/env python3
import rospy
from sensor_msgs.msg import JointState
from std_msgs.msg import Header, Float32
from geometry_msgs.msg import Twist, TwistStamped
from nav_msgs.msg import Odometry
import math
rear_vel = 0
front_rot = 0
def callback_cmd(cmd):
global front_rot
global rear_vel
rear_ve... | [
"rospy.Subscriber",
"rospy.is_shutdown",
"rospy.init_node",
"sensor_msgs.msg.JointState",
"rospy.Time.now",
"rospy.Rate",
"rospy.Publisher",
"std_msgs.msg.Header"
] | [((643, 701), 'rospy.Publisher', 'rospy.Publisher', (['"""joint_states"""', 'JointState'], {'queue_size': '(10)'}), "('joint_states', JointState, queue_size=10)\n", (658, 701), False, 'import rospy\n'), ((706, 756), 'rospy.Subscriber', 'rospy.Subscriber', (['"""/odom"""', 'Odometry', 'callback_odom'], {}), "('/odom', O... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
__version__ = "0.1"
from .lap_tracking import LAPTracker
from .tester import *
import os
import logging
from .utils.color_system import color
... | [
"logging.getLogger",
"logging.StreamHandler",
"logging.Formatter",
"os.path.join",
"os.path.dirname",
"warnings.filterwarnings"
] | [((970, 994), 'os.path.dirname', 'os.path.dirname', (['thisdir'], {}), '(thisdir)\n', (985, 994), False, 'import os\n'), ((1008, 1039), 'os.path.join', 'os.path.join', (['pkgdir', '"""samples"""'], {}), "(pkgdir, 'samples')\n", (1020, 1039), False, 'import os\n'), ((1050, 1077), 'logging.getLogger', 'logging.getLogger'... |
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from dashboard.helpers import (list_container,
start_container,
stop_container,
... | [
"django.shortcuts.render",
"dashboard.helpers.create_container",
"dashboard.helpers.stop_container",
"rest_framework.response.Response",
"dashboard.helpers.delete_container",
"dashboard.helpers.list_container",
"dashboard.helpers.start_container"
] | [((439, 455), 'dashboard.helpers.list_container', 'list_container', ([], {}), '()\n', (453, 455), False, 'from dashboard.helpers import list_container, start_container, stop_container, create_container, delete_container\n'), ((488, 536), 'django.shortcuts.render', 'render', (['request', '"""dashboard/containers.html"""... |
import unittest
from solargis.request import Module, ModuleType
class TestModule(unittest.TestCase):
def test_module_element(self):
module = Module(ModuleType.CSI, 0, 0.8, 45, -0.38)
expected = (
'<pv:module type="CSI">'
'<pv:degradation>0</pv:degradation>'
'... | [
"solargis.request.Module"
] | [((157, 198), 'solargis.request.Module', 'Module', (['ModuleType.CSI', '(0)', '(0.8)', '(45)', '(-0.38)'], {}), '(ModuleType.CSI, 0, 0.8, 45, -0.38)\n', (163, 198), False, 'from solargis.request import Module, ModuleType\n'), ((679, 706), 'solargis.request.Module', 'Module', (['ModuleType.CSI', '(0.5)'], {}), '(ModuleT... |
import torch
import torch.nn as nn
import torchvision
import os
from train import train
from transform import get_transform
# each layer consists of [expansion_ratio, output_channels, repeat_number, stride_of_first_sublayer]
bottleneck_layers_config = [
[1, 16, 1, 1],
[6, 24, 2, 2],
[6, 32, 3, 2... | [
"torch.nn.BatchNorm2d",
"train.train",
"torch.nn.CrossEntropyLoss",
"torch.nn.init.constant_",
"torch.nn.Sequential",
"torch.nn.Flatten",
"os.path.join",
"torch.nn.Conv2d",
"transform.get_transform",
"torch.nn.init.kaiming_uniform_",
"torch.utils.data.DataLoader",
"torch.nn.AvgPool2d",
"torc... | [((3075, 3095), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (3087, 3095), False, 'import torch\n'), ((3708, 3751), 'torch.nn.CrossEntropyLoss', 'torch.nn.CrossEntropyLoss', ([], {'reduction': '"""mean"""'}), "(reduction='mean')\n", (3733, 3751), False, 'import torch\n'), ((3870, 3943), 'train.tr... |
from django.shortcuts import render
from api.models import NowPPM
from api.models import PPMData
import datetime
import matplotlib
from matplotlib import pyplot
# Create your views here.
def home(request):
nowppm = NowPPM.objects.get(id=1)
return render(request, 'home.html', {'nowppm': nowppm, })
| [
"django.shortcuts.render",
"api.models.NowPPM.objects.get"
] | [((223, 247), 'api.models.NowPPM.objects.get', 'NowPPM.objects.get', ([], {'id': '(1)'}), '(id=1)\n', (241, 247), False, 'from api.models import NowPPM\n'), ((260, 308), 'django.shortcuts.render', 'render', (['request', '"""home.html"""', "{'nowppm': nowppm}"], {}), "(request, 'home.html', {'nowppm': nowppm})\n", (266,... |
# -*- coding: UTF-8 -*-
import torch
import torch.nn as nn
from torch.autograd import Variable
import my_dataset
from captcha_VGG16 import *
from captcha_resnet import ResNet18
from captcha_optimizer import RAdam, GradualWarmupScheduler
from captcha_resnet34 import ResNet34
# 断点续训标识
RESUME = True
checkpoint_path = r'.... | [
"captcha_resnet34.ResNet34",
"torch.load",
"torch.optim.lr_scheduler.StepLR",
"my_dataset.get_train_data_loader",
"torch.save",
"torch.nn.MultiLabelSoftMarginLoss",
"captcha_optimizer.GradualWarmupScheduler"
] | [((540, 584), 'my_dataset.get_train_data_loader', 'my_dataset.get_train_data_loader', (['batch_size'], {}), '(batch_size)\n', (572, 584), False, 'import my_dataset\n'), ((664, 674), 'captcha_resnet34.ResNet34', 'ResNet34', ([], {}), '()\n', (672, 674), False, 'from captcha_resnet34 import ResNet34\n'), ((757, 786), 'to... |
# -*- coding: utf-8 -*-
from flask import Blueprint,request,jsonify,redirect
from common.libs.Helper import ops_render,get_current_date,i_pagination,get_dict_filter_field
from application import app,db
from common.models.food.Food import Food
from common.models.food.FoodCat import FoodCat
from common.models.food.FoodS... | [
"common.libs.UrlManager.UrlManager.build_url",
"common.models.food.Food.Food.id.desc",
"common.models.food.FoodCat.FoodCat",
"common.models.food.Food.Food.query.filter_by",
"common.libs.Helper.get_current_date",
"flask.jsonify",
"common.models.food.FoodCat.FoodCat.id.desc",
"common.models.food.FoodCat... | [((528, 560), 'flask.Blueprint', 'Blueprint', (['"""food_page"""', '__name__'], {}), "('food_page', __name__)\n", (537, 560), False, 'from flask import Blueprint, request, jsonify, redirect\n'), ((1407, 1432), 'common.libs.Helper.i_pagination', 'i_pagination', (['page_params'], {}), '(page_params)\n', (1419, 1432), Fal... |
import theano.tensor as tt
from theano import scan
from . import multivariate
from . import continuous
from . import distribution
__all__ = [
'AR1',
'GaussianRandomWalk',
'GARCH11',
'EulerMaruyama',
'MvGaussianRandomWalk',
'MvStudentTRandomWalk'
]
class AR1(distribution.Continuous):
"""
... | [
"theano.tensor.sqrt",
"theano.tensor.sum",
"theano.scan",
"theano.tensor.square",
"theano.tensor.concatenate"
] | [((3265, 3398), 'theano.scan', 'scan', ([], {'fn': 'volatility_update', 'sequences': '[x]', 'outputs_info': '[self.initial_vol]', 'non_sequences': '[self.omega, self.alpha_1, self.beta_1]'}), '(fn=volatility_update, sequences=[x], outputs_info=[self.initial_vol],\n non_sequences=[self.omega, self.alpha_1, self.beta_... |
import pytest
from monty.serialization import MontyDecoder
from monty.serialization import loadfn
from emmet.core.thermo import ThermoDoc
@pytest.fixture(scope="session")
def Fe3O4_structure(test_dir):
structure = loadfn(test_dir / "thermo/Fe3O4_structure.json")
return structure
@pytest.fixture(scope="sessi... | [
"pytest.fixture",
"emmet.core.thermo.ThermoDoc.from_entries",
"monty.serialization.MontyDecoder",
"monty.serialization.loadfn"
] | [((141, 172), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (155, 172), False, 'import pytest\n'), ((293, 324), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (307, 324), False, 'import pytest\n'), ((447, 478), 'pytest.fixture'... |
# python
import json
import os
import random
import re
import traceback
import modo
from . import util
import yaml
from .defaults import get
from .symbols import *
def yaml_save_dialog():
"""
By <NAME> for Mechanical Color
File dialog requesting YAML file destination.
"""
try:
return ... | [
"os.path.exists",
"traceback.format_exc",
"yaml.dump",
"os.path.join",
"modo.dialogs.customFile",
"os.path.normpath",
"os.path.dirname",
"os.mkdir",
"random.randint",
"os.remove"
] | [((1178, 1314), 'modo.dialogs.customFile', 'modo.dialogs.customFile', (['"""fileSave"""', '"""Image Destination"""', '[i[0] for i in savers]', '[i[1] for i in savers]'], {'ext': '[i[2] for i in savers]'}), "('fileSave', 'Image Destination', [i[0] for i in\n savers], [i[1] for i in savers], ext=[i[2] for i in savers]... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import os
from collections import defaultdict
import numpy as np
from scipy.spatial import distance
from tqdm import tqdm
np.set_printoptions(threshold=np.inf, suppress=True)
def main(args):
num_batches = args.num_batches
bert_data = defaultdic... | [
"numpy.mean",
"scipy.spatial.distance.cosine",
"argparse.ArgumentParser",
"collections.defaultdict",
"numpy.concatenate",
"numpy.load",
"numpy.set_printoptions"
] | [((188, 240), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'threshold': 'np.inf', 'suppress': '(True)'}), '(threshold=np.inf, suppress=True)\n', (207, 240), True, 'import numpy as np\n'), ((310, 327), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (321, 327), False, 'from collections im... |
import markdown
import re, socket
TLDS = ('gw', 'gu', 'gt', 'gs', 'gr', 'gq', 'gp', 'gy', 'gg', 'gf', 'ge', 'gd', 'ga', 'edu', 'va', 'gn', 'gl', 'gi',
'gh', 'iq', 'lb', 'lc', 'la', 'tv', 'tw', 'tt', 'arpa', 'lk', 'li', 'lv', 'to', 'lt', 'lr', 'ls', 'th', 'tf',
'su', 'td', 'aspx', 'tc', 'ly', 'do', 'coo... | [
"socket.inet_aton",
"re.compile"
] | [((1807, 2251), 're.compile', 're.compile', (['"""\n (?P<ws>.?\\\\s*)\n (?P<url>\n (?:(?P<format1>\n ((?P<protocol1>[a-z][a-z]+)://)?\n (?P<domain1>\\\\w(?:[\\\\w-]*\\\\w)?\\\\.\\\\w(?:[\\\\w-]*\\\\w)?(?:\\\\.\\\\w(?:[\\\\w-]*\\\\w)?)*)\n ) | (?P<format2>\n ((?P<prot... |
from dataclasses import dataclass
from iou_tracker import track_iou
from util_iou import load_mot, save_to_csv
from time import time
import os
from multiprocessing.pool import ThreadPool
import pandas as pd
@dataclass
class Config_mta_tracker:
detections_folder: str
track_output_folder : str
cam_ids: lis... | [
"os.makedirs",
"os.path.join",
"iou_tracker.track_iou",
"multiprocessing.pool.ThreadPool",
"pandas.DataFrame",
"util_iou.load_mot",
"time.time"
] | [((586, 653), 'os.path.join', 'os.path.join', (['config_mta_tracker.detections_folder', 'detections_name'], {}), '(config_mta_tracker.detections_folder, detections_name)\n', (598, 653), False, 'import os\n'), ((679, 715), 'util_iou.load_mot', 'load_mot', ([], {'detections': 'detections_path'}), '(detections=detections_... |
from functools import cache
import backtest.backtest_config as backtest_config
import requests
import json
import pandas as pd
class APIError(Exception):
pass
class MarketStackBackEnd:
"""
A specific class to handle the particularities of the market stack API, can be swapped out for other classes with
... | [
"requests.session",
"json.loads",
"json.dump",
"json.load",
"pandas.DataFrame",
"pandas.to_datetime"
] | [((408, 426), 'requests.session', 'requests.session', ([], {}), '()\n', (424, 426), False, 'import requests\n'), ((1314, 1340), 'pandas.to_datetime', 'pd.to_datetime', (["df['date']"], {}), "(df['date'])\n", (1328, 1340), True, 'import pandas as pd\n'), ((3211, 3249), 'pandas.DataFrame', 'pd.DataFrame', (["response_con... |
from snovault import (
calculated_property,
collection,
load_schema,
)
from .base import (
Item,
)
@collection(
name='cell-annotations',
properties={
'title': 'Cell annotations',
'description': 'Listing of cell annotations',
})
class CellAnnotation(Item):
item_type = 'c... | [
"snovault.collection",
"snovault.calculated_property",
"snovault.load_schema"
] | [((118, 245), 'snovault.collection', 'collection', ([], {'name': '"""cell-annotations"""', 'properties': "{'title': 'Cell annotations', 'description': 'Listing of cell annotations'}"}), "(name='cell-annotations', properties={'title': 'Cell annotations',\n 'description': 'Listing of cell annotations'})\n", (128, 245)... |
from fastapi import FastAPI
import requests
import pytest
import inspect
from ray import serve
from ray.serve.utils import make_fastapi_class_based_view
def test_fastapi_function(serve_instance):
client = serve_instance
app = FastAPI()
@app.get("/{a}")
def func(a: int):
return {"result": a}
... | [
"ray.serve.ingress",
"requests.post",
"fastapi.FastAPI",
"ray.serve.utils.make_fastapi_class_based_view",
"requests.get",
"pytest.main",
"inspect.isfunction"
] | [((237, 246), 'fastapi.FastAPI', 'FastAPI', ([], {}), '()\n', (244, 246), False, 'from fastapi import FastAPI\n'), ((326, 344), 'ray.serve.ingress', 'serve.ingress', (['app'], {}), '(app)\n', (339, 344), False, 'from ray import serve\n'), ((428, 472), 'requests.get', 'requests.get', (['f"""http://localhost:8000/f/100""... |
# pylint: disable=g-bad-file-header
# Copyright 2020 DeepMind Technologies Limited. 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/... | [
"numpy.mean",
"numpy.abs"
] | [((1677, 1699), 'numpy.mean', 'np.mean', (['squared_error'], {}), '(squared_error)\n', (1684, 1699), True, 'import numpy as np\n'), ((1883, 1917), 'numpy.abs', 'np.abs', (['(predictions - ground_truth)'], {}), '(predictions - ground_truth)\n', (1889, 1917), True, 'import numpy as np\n')] |
# Copyright (c) 2019, NVIDIA CORPORATION. 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 applicabl... | [
"architectures.VGG",
"architectures.G_Res_Net",
"utils.split_meshes",
"utils.reset_meshes",
"utils.loss_lap",
"argparse.ArgumentParser",
"tqdm.tqdm.write",
"json.dumps",
"os.path.isdir",
"utils.loss_surf",
"torch.abs",
"architectures.MeshEncoder",
"utils.setup_meshes",
"torch.Size",
"tor... | [((1120, 1145), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1143, 1145), False, 'import argparse\n'), ((3585, 3664), 'torch.utils.data.DataLoader', 'DataLoader', (['valid_set'], {'batch_size': 'args.batch_size', 'shuffle': '(False)', 'num_workers': '(8)'}), '(valid_set, batch_size=args.batc... |
import pytest
import responses
import json as jsonlib
from pathlib import Path
import pgark
import pgark.archivers.wayback as wb
FIXTURES_DIR = Path("tests/fixtures/_old")
@pytest.fixture
def success_urls():
target_url = "https://plainlanguage.gov/"
expected_url = wb.url_for_snapshot(target_url, "202009041... | [
"pathlib.Path",
"pgark.archivers.wayback.url_for_snapshot",
"pgark.archivers.wayback.url_for_jobstatus",
"responses.RequestsMock",
"pgark.archivers.wayback.url_for_savepage",
"pgark.archivers.wayback.extract_job_id",
"responses.urlencoded_params_matcher"
] | [((147, 174), 'pathlib.Path', 'Path', (['"""tests/fixtures/_old"""'], {}), "('tests/fixtures/_old')\n", (151, 174), False, 'from pathlib import Path\n'), ((278, 327), 'pgark.archivers.wayback.url_for_snapshot', 'wb.url_for_snapshot', (['target_url', '"""20200904183020"""'], {}), "(target_url, '20200904183020')\n", (297... |
import pygame as pg
from pygame.sprite import Sprite
class Alien(Sprite):
"""Uma classe que representa um único alienígena da frota."""
def __init__(self, config, tela):
super(Alien, self).__init__()
self.tela = tela
self.config = config
# Carrega a imagem do alienígena e def... | [
"pygame.image.load"
] | [((365, 400), 'pygame.image.load', 'pg.image.load', (['"""imagens/alien1.png"""'], {}), "('imagens/alien1.png')\n", (378, 400), True, 'import pygame as pg\n')] |
import sqlite3
class DbController:
"""Allows user to update and search reference database"""
def __init__(self, db_name):
self.db_name = db_name
#Default sql statement for displaying search results. Search terms may be concatenated to this string.
self.search_default_sql = """SEL... | [
"sqlite3.connect"
] | [((778, 807), 'sqlite3.connect', 'sqlite3.connect', (['self.db_name'], {}), '(self.db_name)\n', (793, 807), False, 'import sqlite3\n'), ((1028, 1057), 'sqlite3.connect', 'sqlite3.connect', (['self.db_name'], {}), '(self.db_name)\n', (1043, 1057), False, 'import sqlite3\n')] |
#
# Copyright (c) 2015-2021 <NAME> <tflorac AT ulthar.net>
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE... | [
"pyams_utils.traversing.get_parent",
"pyams_utils.adapter.adapter_config",
"pyams_thesaurus._",
"pyams_thesaurus.interfaces.thesaurus.IThesaurus",
"pyams_form.ajax.ajax_form_config",
"pyams_utils.factory.get_object_factory",
"pyams_form.field.Fields",
"pyams_viewlet.viewlet.viewlet_config"
] | [((1694, 1897), 'pyams_viewlet.viewlet.viewlet_config', 'viewlet_config', ([], {'name': '"""add-term.menu"""', 'context': 'IThesaurus', 'layer': 'IAdminLayer', 'view': 'ThesaurusTermsTreeView', 'manager': 'IToolbarViewletManager', 'weight': '(10)', 'permission': 'MANAGE_THESAURUS_CONTENT_PERMISSION'}), "(name='add-term... |
import torch
import torch.nn.functional as F
from exptune.exptune import ExperimentSettings, Metric, TrialResources
from exptune.hyperparams import (
ChoiceHyperParam,
LogUniformHyperParam,
UniformHyperParam,
)
from exptune.search_strategies import GridSearchStrategy
from exptune.summaries.final_run_summari... | [
"exptune.utils.PatientStopper",
"torch.cuda.is_available",
"ogb.graphproppred.evaluate.Evaluator",
"exptune.hyperparams.ChoiceHyperParam",
"ray.tune.schedulers.AsyncHyperBandScheduler",
"experiments.mol.pna_style_models.GatHIVNet",
"experiments.utils.data_location",
"experiments.mol.pna_style_models.M... | [((2201, 2216), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2214, 2216), False, 'import torch\n'), ((3726, 3762), 'ogb.graphproppred.evaluate.Evaluator', 'Evaluator', (['f"""ogbg-mol{self.dataset}"""'], {}), "(f'ogbg-mol{self.dataset}')\n", (3735, 3762), False, 'from ogb.graphproppred.evaluate import Evaluator... |
import cv2
img = cv2.imread('assets/PersLogo_4.jpg', -1)
img = cv2.resize(img, (0, 0), fx=0.5, fy=0.5)
img = cv2.rotate(img, cv2.cv2.ROTATE_90_COUNTERCLOCKWISE)
cv2.imwrite('assets/new_img.jpg', img)
cv2.imshow('Image ', img)
cv2.waitKey(0)
cv2.destroyWindow()
| [
"cv2.imwrite",
"cv2.destroyWindow",
"cv2.imshow",
"cv2.rotate",
"cv2.waitKey",
"cv2.resize",
"cv2.imread"
] | [((18, 57), 'cv2.imread', 'cv2.imread', (['"""assets/PersLogo_4.jpg"""', '(-1)'], {}), "('assets/PersLogo_4.jpg', -1)\n", (28, 57), False, 'import cv2\n'), ((64, 103), 'cv2.resize', 'cv2.resize', (['img', '(0, 0)'], {'fx': '(0.5)', 'fy': '(0.5)'}), '(img, (0, 0), fx=0.5, fy=0.5)\n', (74, 103), False, 'import cv2\n'), (... |
"""convert-two-streets-cache-to-single
Revision ID: d365c792c756
Revises: <KEY>
Create Date: 2021-12-30 16:57:22.196091
"""
# revision identifiers, used by Alembic.
revision = 'd365c792c756'
down_revision = '<KEY>'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
from typing imp... | [
"sqlalchemy.types.JSON",
"alembic.op.drop_table",
"alembic.op.f",
"sqlalchemy.PrimaryKeyConstraint",
"sqlalchemy.Integer",
"alembic.op.drop_index",
"alembic.op.create_index",
"sqlalchemy.JSON"
] | [((1011, 1170), 'alembic.op.create_index', 'op.create_index', (['"""infographics_street_data_cache_id_years_idx"""', '"""infographics_street_data_cache"""', "['yishuv_symbol', 'street', 'years_ago']"], {'unique': '(True)'}), "('infographics_street_data_cache_id_years_idx',\n 'infographics_street_data_cache', ['yishu... |
#!/usr/bin/env python3
## cachefy.py
##
## Add or remove numba "cache" decorators
##
## Copyright (C) 2018, <NAME> <<EMAIL>> and contributors
##
## This program is licenced under the BSD 2-Clause License,
## contained in the LICENCE file in this directory.
## See CREDITS for a list of contributors.
##
import sys
imp... | [
"glob.glob"
] | [((341, 358), 'glob.glob', 'glob.glob', (['"""*.py"""'], {}), "('*.py')\n", (350, 358), False, 'import glob\n')] |
import requests
from bs4 import BeautifulSoup, SoupStrainer
from chapter_3.file_cache import FileCache
class Downloader:
def __init__(self, cache=None, parser='html.parser', hard_cache=True):
if not cache:
self.cache = FileCache('sainsbury_compressed', compressed=True)
else:
... | [
"chapter_3.file_cache.FileCache",
"bs4.BeautifulSoup",
"requests.get",
"bs4.SoupStrainer"
] | [((929, 969), 'bs4.SoupStrainer', 'SoupStrainer', ([], {'name': 'tag', 'attrs': 'attributes'}), '(name=tag, attrs=attributes)\n', (941, 969), False, 'from bs4 import BeautifulSoup, SoupStrainer\n'), ((1096, 1113), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (1108, 1113), False, 'import requests\n'), ((246... |
import rospy
from std_msgs.msg import Float64
def set_wheel_velocity(velocity):
pub1 = rospy.Publisher('/my_robot/joint_wheel_1_controller/command', Float64, queue_size=10)
pub2 = rospy.Publisher('/my_robot/joint_wheel_2_controller/command', Float64, queue_size=10)
rate = rospy.Rate(2) # 2hz
rate.slee... | [
"rospy.Publisher",
"rospy.Rate",
"rospy.loginfo"
] | [((92, 181), 'rospy.Publisher', 'rospy.Publisher', (['"""/my_robot/joint_wheel_1_controller/command"""', 'Float64'], {'queue_size': '(10)'}), "('/my_robot/joint_wheel_1_controller/command', Float64,\n queue_size=10)\n", (107, 181), False, 'import rospy\n'), ((189, 278), 'rospy.Publisher', 'rospy.Publisher', (['"""/m... |
# Generated by Django 3.0.5 on 2020-05-14 06:37
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('interceptor', '0005_auto_20200514_0617'),
]
operations = [
migrations.AddField(
model_name='int... | [
"django.db.models.CharField",
"django.db.models.ForeignKey"
] | [((381, 426), 'django.db.models.CharField', 'models.CharField', ([], {'default': '"""/"""', 'max_length': '(255)'}), "(default='/', max_length=255)\n", (397, 426), False, 'from django.db import migrations, models\n'), ((559, 686), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'blank': '(True)', 'null': '(Tr... |
import panel as pn
def test_alert():
my_alert = pn.pane.Alert("foo", alert_type="primary")
my_button = pn.widgets.Button(name="Toggle")
def toggle(event):
if my_alert.alert_type == "primary":
my_alert.alert_type == "success"
else:
my_alert.alert_type = "... | [
"panel.Row",
"panel.widgets.Button",
"panel.pane.Alert"
] | [((58, 100), 'panel.pane.Alert', 'pn.pane.Alert', (['"""foo"""'], {'alert_type': '"""primary"""'}), "('foo', alert_type='primary')\n", (71, 100), True, 'import panel as pn\n'), ((118, 150), 'panel.widgets.Button', 'pn.widgets.Button', ([], {'name': '"""Toggle"""'}), "(name='Toggle')\n", (135, 150), True, 'import panel ... |
# Generated by Django 3.2.4 on 2021-06-10 23:08
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('order_status', '0003_alter_orderstatus_bought_by'),
]
operations = [
migrations.AlterModelOptions(
name='orderstatus',
optio... | [
"django.db.migrations.AlterModelOptions"
] | [((241, 334), 'django.db.migrations.AlterModelOptions', 'migrations.AlterModelOptions', ([], {'name': '"""orderstatus"""', 'options': "{'ordering': ['order_number']}"}), "(name='orderstatus', options={'ordering': [\n 'order_number']})\n", (269, 334), False, 'from django.db import migrations\n')] |
"""initial migration
Revision ID: 0930fdefb325
Revises:
Create Date: 2020-09-27 21:13:23.088570
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '0930fdefb325'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto g... | [
"sqlalchemy.ForeignKeyConstraint",
"sqlalchemy.Computed",
"sqlalchemy.text",
"sqlalchemy.DateTime",
"alembic.op.drop_table",
"sqlalchemy.Text",
"sqlalchemy.Boolean",
"sqlalchemy.PrimaryKeyConstraint",
"sqlalchemy.Integer",
"sqlalchemy.UniqueConstraint",
"sqlalchemy.String"
] | [((8159, 8188), 'alembic.op.drop_table', 'op.drop_table', (['"""task_history"""'], {}), "('task_history')\n", (8172, 8188), False, 'from alembic import op\n'), ((8193, 8222), 'alembic.op.drop_table', 'op.drop_table', (['"""user_project"""'], {}), "('user_project')\n", (8206, 8222), False, 'from alembic import op\n'), (... |
from pyg_mongo import Q, q, mongo_table
import re
import pytest
regex = re.compile
def D(value):
if isinstance(value, dict):
return {x : D(y) for x, y in value.items()} ### this converts mdict to normal dict
elif isinstance(value, list):
return [D(y) for y in value]
else:
return val... | [
"re.compile",
"pyg_mongo.Q",
"pyg_mongo.q.a.isinstance",
"pyg_mongo.mongo_table",
"pytest.raises",
"pyg_mongo.q"
] | [((5805, 5838), 'pyg_mongo.Q', 'Q', (["['<NAME>', '<NAME>', '<NAME>']"], {}), "(['<NAME>', '<NAME>', '<NAME>'])\n", (5806, 5838), False, 'from pyg_mongo import Q, q, mongo_table\n'), ((6613, 6677), 'pyg_mongo.Q', 'Q', (["['@@Adam%+Aaron', '++Beth---Brown++', '---James%%% Joyce%']"], {}), "(['@@Adam%+Aaron', '++Beth--... |
'create a subspace phone-loop model'
import argparse
import copy
import pickle
import sys
import torch
import yaml
import beer
# Create a view of the emissions (aka modelset) for each units.
def iterate_units(modelset, nunits, nstates):
for idx in range(nunits):
start, end = idx * nstates, (idx + 1) *... | [
"pickle.dump",
"beer.GSMSet.create",
"beer.Mixture.create",
"beer.GSM.create",
"pickle.load",
"yaml.load",
"beer.SubspaceBayesianParameter.from_parameter",
"copy.deepcopy",
"torch.zeros_like",
"torch.zeros",
"torch.ones"
] | [((784, 807), 'torch.zeros_like', 'torch.zeros_like', (['stats'], {}), '(stats)\n', (800, 807), False, 'import torch\n'), ((1200, 1223), 'torch.zeros_like', 'torch.zeros_like', (['stats'], {}), '(stats)\n', (1216, 1223), False, 'import torch\n'), ((5883, 5906), 'copy.deepcopy', 'copy.deepcopy', (['units[0]'], {}), '(un... |
#!/usr/bin/env python
import markovify
with open("NAGERECHT.txt") as f:
text = f.read()
text_model = markovify.Text(text)
for i in range(8):
print(text_model.make_sentence())
| [
"markovify.Text"
] | [((108, 128), 'markovify.Text', 'markovify.Text', (['text'], {}), '(text)\n', (122, 128), False, 'import markovify\n')] |
from django.http import HttpResponse
from django.template.loader import get_template
from io import BytesIO
from xhtml2pdf import pisa
from tablib import Dataset
from .models import Barcode
def get_status(obj):
if int(obj.quantity) <= int(obj.reorder_level):
obj.status = 'low'
elif int(obj.quantity) >... | [
"io.BytesIO",
"django.template.loader.get_template"
] | [((931, 957), 'django.template.loader.get_template', 'get_template', (['template_src'], {}), '(template_src)\n', (943, 957), False, 'from django.template.loader import get_template\n'), ((1007, 1016), 'io.BytesIO', 'BytesIO', ([], {}), '()\n', (1014, 1016), False, 'from io import BytesIO\n')] |
# Generated by Django 3.1 on 2020-08-09 01:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Main', '0004_auto_20200809_0425'),
]
operations = [
migrations.AlterField(
model_name='address',
name='apartment_addre... | [
"django.db.models.CharField"
] | [((343, 386), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)', 'null': '(True)'}), '(max_length=100, null=True)\n', (359, 386), False, 'from django.db import migrations, models\n'), ((517, 560), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)', 'null': '(True)'... |
'''
Restore configuration model.
'''
from typing import Any, Dict, Literal, Optional, Union
from pydantic import NonNegativeInt, validator
from .configuration import Configuration
class RestoreConfiguration(Configuration):
'''
Restore configuration model.
'''
#: Configuration type.
type: Liter... | [
"pydantic.validator"
] | [((540, 579), 'pydantic.validator', 'validator', (['"""final_version"""'], {'always': '(True)'}), "('final_version', always=True)\n", (549, 579), False, 'from pydantic import NonNegativeInt, validator\n')] |
import torch
import torch.nn as nn
import argparse
from torch.utils.data import Dataset
import sys
'''
Block of net
'''
def net_block(n_in, n_out):
block = nn.Sequential(nn.Linear(n_in, n_out),
nn.BatchNorm1d(n_out),
nn.ReLU())
return block
class M... | [
"torch.nn.ReLU",
"torch.nn.Dropout",
"torch.optim.lr_scheduler.MultiStepLR",
"torch.nn.Softmax",
"torch.nn.CrossEntropyLoss",
"torch.nn.init.constant_",
"torch.load",
"torch.from_numpy",
"torch.nn.init.xavier_normal_",
"torch.nn.BatchNorm1d",
"torch.nn.Linear",
"torch.utils.data.DataLoader",
... | [((1855, 1946), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', ([], {'dataset': 'dset', 'batch_size': 'param_batch_size', 'shuffle': 'shuffle'}), '(dataset=dset, batch_size=param_batch_size,\n shuffle=shuffle)\n', (1882, 1946), False, 'import torch\n'), ((2418, 2456), 'torch.load', 'torch.load', (['""... |
import numpy as np
import cv2
import glob
import PIL.ExifTags
import PIL.Image
from tqdm import tqdm
import os
import matplotlib.pyplot as plt
from pyntcloud import PyntCloud
import open3d as o3d
def create_output(vertices, colors, filename):
colors = colors.reshape(-1,3)
vertices = np.hstack([vertices.reshape(-1,3)... | [
"matplotlib.pyplot.imsave",
"cv2.undistort",
"cv2.reprojectImageTo3D",
"os.path.join",
"cv2.getOptimalNewCameraMatrix",
"cv2.StereoSGBM_create",
"cv2.cvtColor",
"numpy.savetxt",
"cv2.imread",
"numpy.float32"
] | [((997, 1013), 'cv2.imread', 'cv2.imread', (['left'], {}), '(left)\n', (1007, 1013), False, 'import cv2\n'), ((1026, 1043), 'cv2.imread', 'cv2.imread', (['right'], {}), '(right)\n', (1036, 1043), False, 'import cv2\n'), ((1253, 1310), 'cv2.getOptimalNewCameraMatrix', 'cv2.getOptimalNewCameraMatrix', (['K', 'dist', '(w,... |
#
# ZoomBase.py -- Zoom plugin base class for Ginga fits viewer
#
# <NAME> (<EMAIL>)
#
# Copyright (c) <NAME>. All rights reserved.
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
import time
from ginga.misc import Bunch
from ginga import GingaPlugin
cl... | [
"time.time"
] | [((966, 977), 'time.time', 'time.time', ([], {}), '()\n', (975, 977), False, 'import time\n'), ((6072, 6083), 'time.time', 'time.time', ([], {}), '()\n', (6081, 6083), False, 'import time\n'), ((7245, 7256), 'time.time', 'time.time', ([], {}), '()\n', (7254, 7256), False, 'import time\n')] |
import json
from pprint import pprint
filename = "readfile_4.json"
with open(filename) as f:
readdata = json.load(f)
new_dict = {}
for a_keys, a_values in readdata.items():
if a_keys == "ipV4Neighbors":
for nei_list in a_values:
for nei_keys, nei_values in nei_list.items():
... | [
"json.load"
] | [((109, 121), 'json.load', 'json.load', (['f'], {}), '(f)\n', (118, 121), False, 'import json\n')] |
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class SessionConfig(AppConfig):
name = "vbb_backend.session"
verbose_name = _("Session")
def ready(self):
try:
import vbb_backend.session.signals # noqa F401
except ImportError:
... | [
"django.utils.translation.gettext_lazy"
] | [((175, 187), 'django.utils.translation.gettext_lazy', '_', (['"""Session"""'], {}), "('Session')\n", (176, 187), True, 'from django.utils.translation import gettext_lazy as _\n')] |
import os
import ssl
import ipaddress
import hashlib
from ipaddress import *
import asyncio
import pyminizip
import base64
import datetime
from time import gmtime, strftime
from aiohttp import web
import urllib.parse
from shutil import copyfile
import sys
import pycdlib
from io import BytesIO
stage0UrlPrefix = '/doc... | [
"base64.b64encode",
"aiohttp.web.Application",
"io.BytesIO",
"aiohttp.web.TCPSite",
"ipaddress.ip_network",
"os.remove",
"os.path.exists",
"pathlib.Path",
"aiohttp.web.Response",
"aiohttp.web.AppRunner",
"hashlib.md5",
"ssl.SSLContext",
"pycdlib.PyCdlib",
"os.path.isfile",
"shutil.copyfi... | [((2652, 2751), 'aiohttp.web.Response', 'web.Response', ([], {'body': 'png', 'status': '(200)', 'content_type': '"""image/png"""', 'headers': "{'Server': 'Apache/2.4'}"}), "(body=png, status=200, content_type='image/png', headers={\n 'Server': 'Apache/2.4'})\n", (2664, 2751), False, 'from aiohttp import web\n'), ((2... |
import random
def binary_search(data, target, low_index, high_index):
""" Binary Search recursiva """
if (low_index > high_index):
return False
mid_index = (low_index + high_index) // 2
if target == data[mid_index]:
return True
elif target < data[mid_index]:
return binary_... | [
"random.randint"
] | [((1184, 1206), 'random.randint', 'random.randint', (['(0)', '(100)'], {}), '(0, 100)\n', (1198, 1206), False, 'import random\n')] |
# -*- coding: utf-8 -*-
from collections import OrderedDict
from . import instance
import future.utils
# https://blog.ionelmc.ro/2015/02/09/understanding-python-metaclasses/
#
# Instance creation:
# metaclass.__call__()
# instance = class.__new__(self,)
# class.__init__(instance,...)
# return in... | [
"collections.OrderedDict"
] | [((2415, 2428), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (2426, 2428), False, 'from collections import OrderedDict\n'), ((2461, 2474), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (2472, 2474), False, 'from collections import OrderedDict\n')] |
import tensorflow as tf
from tfoptests.persistor import TensorFlowPersistor
from tfoptests.test_graph import TestGraph
class ConcatTest(TestGraph):
def list_inputs(self):
return []
def test_concat_one():
concat_test = ConcatTest(seed=13)
arrs = []
for i in range(1, 5, 1):
arrs.append... | [
"tensorflow.concat",
"tfoptests.persistor.TensorFlowPersistor"
] | [((424, 457), 'tensorflow.concat', 'tf.concat', (['arrs', '(0)'], {'name': '"""output"""'}), "(arrs, 0, name='output')\n", (433, 457), True, 'import tensorflow as tf\n'), ((543, 581), 'tfoptests.persistor.TensorFlowPersistor', 'TensorFlowPersistor', ([], {'save_dir': '"""concat"""'}), "(save_dir='concat')\n", (562, 581... |
import sys
import json
sys.path.insert(0, '../')
import config
from data_utils import (make_conll_format, make_embedding, make_vocab,
make_vocab_from_squad, process_file, make_graph_vector)
def make_sent_dataset():
train_src_file = "./para-train.txt"
train_trg_file = "./tgt-train.txt... | [
"sys.path.insert",
"data_utils.make_graph_vector",
"data_utils.make_embedding",
"data_utils.make_conll_format",
"data_utils.process_file",
"data_utils.make_vocab_from_squad",
"json.load",
"data_utils.make_vocab"
] | [((24, 49), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""../"""'], {}), "(0, '../')\n", (39, 49), False, 'import sys\n'), ((476, 552), 'data_utils.make_vocab', 'make_vocab', (['train_src_file', 'train_trg_file', 'word2idx_file', 'config.vocab_size'], {}), '(train_src_file, train_trg_file, word2idx_file, config.vo... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
"""
Functions for getting Pipe data
"""
from __future__ import annotations
from meerschaum.utils.typing import Optional, Dict, Any
def get_data(
self,
begin : Optional[datetime.datetime] = None,
end : Optional[datetime.datetime] ... | [
"meerschaum.utils.warnings.warn"
] | [((5221, 5273), 'meerschaum.utils.warnings.warn', 'warn', (['f"""Failed to get a rowcount for pipe \'{self}\'."""'], {}), '(f"Failed to get a rowcount for pipe \'{self}\'.")\n', (5225, 5273), False, 'from meerschaum.utils.warnings import warn\n'), ((5166, 5173), 'meerschaum.utils.warnings.warn', 'warn', (['e'], {}), '(... |
import torch
from typing import Tuple
class FastGRNN(torch.nn.Module):
def __init__(self, Fi, Fh):
super().__init__()
self.input_linear = torch.nn.Linear(Fi, Fh, bias = False)
self.state_linear = torch.nn.Linear(Fh, Fh, bias = False)
self.gate_bias = torch.nn.Parameter(torch.ones(1,... | [
"torch.tanh",
"torch.sigmoid",
"torch.nn.Linear",
"torch.ones"
] | [((159, 194), 'torch.nn.Linear', 'torch.nn.Linear', (['Fi', 'Fh'], {'bias': '(False)'}), '(Fi, Fh, bias=False)\n', (174, 194), False, 'import torch\n'), ((225, 260), 'torch.nn.Linear', 'torch.nn.Linear', (['Fh', 'Fh'], {'bias': '(False)'}), '(Fh, Fh, bias=False)\n', (240, 260), False, 'import torch\n'), ((630, 668), 't... |
import datetime
from urllib.parse import quote, unquote
from directory_ch_client.client import ch_search_api_client
from directory_forms_api_client import actions
from directory_forms_api_client.helpers import FormSessionMixin, Sender
from formtools.wizard.views import NamedUrlSessionWizardView
from formtools.wizard.f... | [
"core.helpers.get_form_cleaned_data",
"core.helpers.get_form_display_data",
"core.helpers.search_commodity_by_term",
"django.template.response.TemplateResponse",
"django.urls.reverse",
"core.helpers.form_data_to_initial",
"core.helpers.get_sender_ip_address",
"core.helpers.search_commodity_by_code",
... | [((20098, 20126), 'django.urls.reverse_lazy', 'reverse_lazy', (['"""landing-page"""'], {}), "('landing-page')\n", (20110, 20126), False, 'from django.urls import reverse, reverse_lazy\n'), ((3781, 3794), 'django.shortcuts.redirect', 'redirect', (['url'], {}), '(url)\n', (3789, 3794), False, 'from django.shortcuts impor... |
# Copyright (c) 2016 <NAME>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, s... | [
"theano.tensor.exp",
"theano.tensor.gt",
"numpy.sqrt",
"numpy.log",
"numpy.array",
"theano.shared",
"theano.function",
"numpy.asarray",
"theano.tensor.fvector",
"numpy.exp",
"theano.tensor.fill_diagonal",
"numpy.random.normal",
"sklearn.utils.check_random_state",
"theano.tensor.maximum",
... | [((2250, 2281), 'theano.tensor.fill_diagonal', 'T.fill_diagonal', (['esqdistance', '(0)'], {}), '(esqdistance, 0)\n', (2265, 2281), True, 'import theano.tensor as T\n'), ((2753, 2793), 'theano.tensor.fill_diagonal', 'T.fill_diagonal', (['(1 / (sqdistance + 1))', '(0)'], {}), '(1 / (sqdistance + 1), 0)\n', (2768, 2793),... |
import io
from PIL import Image, ImageDraw, ImageFont
import tensorflow as tf
import numpy as np
from matplotlib import cm
from matplotlib.colors import ListedColormap
import pdb
default_color = 'blue'
highlight_color = 'red'
class SemanticSegmentationOverlay:
def __init__(self, args):
self.segmap_key = arg... | [
"numpy.uint8",
"PIL.Image.fromarray",
"tensorflow.io.decode_image",
"tensorflow.io.parse_single_example",
"PIL.Image.blend",
"io.BytesIO",
"PIL.ImageFont.truetype",
"matplotlib.colors.ListedColormap",
"PIL.ImageDraw.Draw",
"numpy.zeros",
"tensorflow.io.FixedLenFeature",
"tensorflow.io.decode_r... | [((459, 513), 'PIL.ImageFont.truetype', 'ImageFont.truetype', (['"""./fonts/OpenSans-Regular.ttf"""', '(12)'], {}), "('./fonts/OpenSans-Regular.ttf', 12)\n", (477, 513), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((1067, 1086), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['img'], {}), '(img)\n', (1081, 1086)... |
import copy
import torch as th
from torch.optim import Adam
import torch.nn.functional as F
from torch.nn.utils import clip_grad_norm_
class SACLearner:
def __init__(self, mac, args):
self.args = args
self.mac = mac
self.params = list(mac.parameters())
self.learn_cnt= 0
sel... | [
"torch.optim.Adam",
"torch.nn.functional.mse_loss",
"torch.LongTensor",
"torch.min",
"torch.eq",
"copy.deepcopy",
"torch.no_grad",
"torch.FloatTensor",
"torch.arange"
] | [((334, 363), 'torch.optim.Adam', 'Adam', (['self.params'], {'lr': 'args.lr'}), '(self.params, lr=args.lr)\n', (338, 363), False, 'from torch.optim import Adam\n'), ((527, 545), 'copy.deepcopy', 'copy.deepcopy', (['mac'], {}), '(mac)\n', (540, 545), False, 'import copy\n'), ((1628, 1647), 'torch.FloatTensor', 'th.Float... |
'''
Authors: <NAME> and <NAME>
Date: July 10, 2017
Pre-cnmf-e processing of videos in chunks:
- Downsampling
- Motion Correction
'''
from os import path, system
import pims
import av
import numpy as np
import math
from tqdm import tqdm
from skimage import img_as_uint
from motion import align_video
import skimage.io
i... | [
"os.path.exists",
"numpy.mean",
"numpy.reshape",
"skimage.img_as_uint",
"skimage.morphology.square",
"os.path.splitext",
"h5py.File",
"av.VideoFrame.from_ndarray",
"os.path.dirname",
"av.open",
"numpy.array",
"os.path.basename",
"pims.ImageIOReader",
"motion.align_video",
"os.system",
... | [((1431, 1459), 'pims.ImageIOReader', 'pims.ImageIOReader', (['filename'], {}), '(filename)\n', (1449, 1459), False, 'import pims\n'), ((4013, 4031), 'numpy.arange', 'np.arange', (['dims[0]'], {}), '(dims[0])\n', (4022, 4031), True, 'import numpy as np\n'), ((4040, 4058), 'numpy.arange', 'np.arange', (['dims[1]'], {}),... |
import numpy as np
import pytest
import pytoolkit as tk
def test_load_voc_od_split(data_dir):
ds = tk.datasets.load_voc_od_split(data_dir / "od", split="train")
assert len(ds) == 3
assert tuple(ds.metadata["class_names"]) == ("~", "〇")
ann = ds.labels[0]
assert ann.path == (data_dir / "od" / "JP... | [
"numpy.array",
"pytoolkit.datasets.load_voc_od_split"
] | [((106, 167), 'pytoolkit.datasets.load_voc_od_split', 'tk.datasets.load_voc_od_split', (["(data_dir / 'od')"], {'split': '"""train"""'}), "(data_dir / 'od', split='train')\n", (135, 167), True, 'import pytoolkit as tk\n'), ((493, 510), 'numpy.array', 'np.array', (['[False]'], {}), '([False])\n', (501, 510), True, 'impo... |
try:
from . import generic as g
except BaseException:
import generic as g
class AdjacencyTest(g.unittest.TestCase):
def test_radius(self):
for radius in [0.1, 1.0, 3.1459, 29.20]:
m = g.trimesh.creation.cylinder(
radius=radius, height=radius * 10)
# remov... | [
"generic.trimesh.util.attach_to_log",
"generic.np.sign",
"generic.trimesh.creation.cylinder",
"generic.np.allclose",
"generic.unittest.main",
"generic.np.isfinite"
] | [((771, 801), 'generic.trimesh.util.attach_to_log', 'g.trimesh.util.attach_to_log', ([], {}), '()\n', (799, 801), True, 'import generic as g\n'), ((806, 823), 'generic.unittest.main', 'g.unittest.main', ([], {}), '()\n', (821, 823), True, 'import generic as g\n'), ((220, 282), 'generic.trimesh.creation.cylinder', 'g.tr... |
import os
from abc import ABC, abstractmethod
from typing import List
from prefect import Client, Flow, Task
from prefect.executors import LocalDaskExecutor
from prefect.run_configs import UniversalRun
from prefect.storage import Local
from flows.abstract_settings import AbstractDemands, AbstractTasks
PROJECT_NAME =... | [
"os.getenv",
"flows.abstract_settings.AbstractTasks",
"prefect.storage.Local",
"prefect.executors.LocalDaskExecutor",
"prefect.run_configs.UniversalRun",
"prefect.Client"
] | [((321, 371), 'os.getenv', 'os.getenv', (['"""PREFECT_PROJECT_NAME"""', '"""etude-Prefect"""'], {}), "('PREFECT_PROJECT_NAME', 'etude-Prefect')\n", (330, 371), False, 'import os\n'), ((694, 709), 'flows.abstract_settings.AbstractTasks', 'AbstractTasks', ([], {}), '()\n', (707, 709), False, 'from flows.abstract_settings... |
import Foundation
from PyObjCTools.TestSupport import TestCase
import objc
class Behaviour(Foundation.NSObject):
def scale(self):
return 1
def roundingMode(self):
return 1
def exceptionDuringOperation_error_leftOperand_rightOperand_(self, exc, err, l, r):
pass
class TestNSDecim... | [
"Foundation.NSNumber.numberWithFloat_",
"objc.protocolNamed",
"Foundation.NSDecimal",
"Foundation.NSDecimalNumber.alloc",
"Foundation.NSScanner.alloc",
"Foundation.NSDecimalNumber.decimalNumberWithDecimal_"
] | [((739, 767), 'Foundation.NSDecimal', 'Foundation.NSDecimal', (['"""55.0"""'], {}), "('55.0')\n", (759, 767), False, 'import Foundation\n'), ((960, 1017), 'Foundation.NSDecimalNumber.decimalNumberWithDecimal_', 'Foundation.NSDecimalNumber.decimalNumberWithDecimal_', (['dec'], {}), '(dec)\n', (1012, 1017), False, 'impor... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
import pytest
from clastic.contrib.obj_browser import create_app
_IS_PYPY = '__pypy__' in sys.builtin_module_names
@pytest.mark.skipif(_IS_PYPY, reason='pypy gc cannot support obj browsing')
def test_flaw_basic():
app = create_app()
... | [
"clastic.contrib.obj_browser.create_app",
"pytest.mark.skipif"
] | [((198, 272), 'pytest.mark.skipif', 'pytest.mark.skipif', (['_IS_PYPY'], {'reason': '"""pypy gc cannot support obj browsing"""'}), "(_IS_PYPY, reason='pypy gc cannot support obj browsing')\n", (216, 272), False, 'import pytest\n'), ((306, 318), 'clastic.contrib.obj_browser.create_app', 'create_app', ([], {}), '()\n', (... |
#!/usr/bin/env python3
# Author: <NAME>
# Purpose: Profile the read lengths which map to regions in a bed file
# Created: 2019-08-14
# Depends: pysam, samtools, python >= 3.6
import pysam
import gzip
from os.path import exists
from argparse import ArgumentParser
from sys import exit
def magic_open(input_file):
... | [
"pysam.index",
"os.path.exists",
"argparse.ArgumentParser",
"gzip.open",
"pysam.AlignmentFile",
"sys.exit"
] | [((1458, 1589), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'description': '"""Profile the reads between a minimum and maximum length from regions defined by a .bed file."""'}), "(description=\n 'Profile the reads between a minimum and maximum length from regions defined by a .bed file.'\n )\n", (1472, 158... |
import datetime
import io
import json
import zipfile
from pathlib import Path
import pyrsistent
import pytest
import yaml
from aiohttp import web
from openapi_core.shortcuts import create_spec
from yarl import URL
from rororo import (
BaseSettings,
get_openapi_context,
get_openapi_schema,
get_openapi_... | [
"zipfile.ZipFile",
"io.BytesIO",
"yaml.load",
"aiohttp.web.Application",
"rororo.openapi.get_validated_data",
"aiohttp.web.json_response",
"yarl.URL",
"pathlib.Path",
"aiohttp.web.Response",
"rororo.openapi.exceptions.validation_error_context",
"rororo.get_openapi_context",
"rororo.setup_opena... | [((1360, 1379), 'rororo.OperationTableDef', 'OperationTableDef', ([], {}), '()\n', (1377, 1379), False, 'from rororo import BaseSettings, get_openapi_context, get_openapi_schema, get_openapi_spec, openapi_context, OperationTableDef, setup_openapi, setup_settings_from_environ\n'), ((1401, 1420), 'rororo.OperationTableDe... |
#!/usr/bin/python
# Classification (U)
"""Program: server_disconnect.py
Description: Unit testing of Server.disconnect in mongo_class.py.
Usage:
test/unit/mongo_class/server_disconnect.py
Arguments:
"""
# Libraries and Global Variables
# Standard
import sys
import os
if sys.version_info < ... | [
"unittest.main",
"mongo_class.Server",
"mock.patch",
"os.getcwd"
] | [((439, 450), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (448, 450), False, 'import os\n'), ((1136, 1181), 'mock.patch', 'mock.patch', (['"""mongo_class.pymongo.MongoClient"""'], {}), "('mongo_class.pymongo.MongoClient')\n", (1146, 1181), False, 'import mock\n'), ((1778, 1793), 'unittest.main', 'unittest.main', ([], {... |
import argparse
from flask import Flask, render_template, redirect, jsonify
from data import DataRetriever
from flask import request
from gevent.pywsgi import WSGIServer
app = Flask(__name__)
data_retriever = DataRetriever()
def parse_distance(amount):
return round(float(amount), 2)
@app.route('/')
def index... | [
"flask.render_template",
"argparse.ArgumentParser",
"flask.Flask",
"flask.redirect",
"gevent.pywsgi.WSGIServer",
"flask.request.form.values",
"data.DataRetriever"
] | [((178, 193), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (183, 193), False, 'from flask import Flask, render_template, redirect, jsonify\n'), ((212, 227), 'data.DataRetriever', 'DataRetriever', ([], {}), '()\n', (225, 227), False, 'from data import DataRetriever\n'), ((335, 364), 'flask.render_template... |
from django import forms
from django.contrib.auth.password_validation import CommonPasswordValidator
class ChangePasswordForm(forms.Form):
password = forms.CharField(label='密碼', max_length=50, widget=forms.PasswordInput)
def clean_password(self):
password = self.cleaned_data['password']
valida... | [
"django.contrib.auth.password_validation.CommonPasswordValidator",
"django.forms.CharField"
] | [((155, 225), 'django.forms.CharField', 'forms.CharField', ([], {'label': '"""密碼"""', 'max_length': '(50)', 'widget': 'forms.PasswordInput'}), "(label='密碼', max_length=50, widget=forms.PasswordInput)\n", (170, 225), False, 'from django import forms\n'), ((326, 351), 'django.contrib.auth.password_validation.CommonPasswo... |
# ------------------ [ Authors: ] ------------------ #
# <NAME>
# <NAME>
# <NAME>
import os, json, inspect, discord, asyncio, importlib, sys, keep_alive
from helper.cLog import elog
from helper.cEmbed import denied_msg, greeting_msg
from helper.User import User
from helper.Algorithm import Algorithm
from c... | [
"cDatabase.DB_Settings.DB_Settings",
"background_tasks.my_background_task__Role_Management",
"importlib.import_module",
"cDatabase.DB_Algorithm.DB_Algorithm",
"helper.User.User",
"helper.GitHub.GitHub",
"inspect.stack",
"discord.Game",
"keep_alive.keep_alive",
"discord.Intents.all",
"helper.Algo... | [((765, 785), 'cDatabase.DB_Users.DB_Users', 'DB_Users', (['"""db_users"""'], {}), "('db_users')\n", (773, 785), False, 'from cDatabase.DB_Users import DB_Users\n'), ((796, 825), 'cDatabase.DB_Algorithm.DB_Algorithm', 'DB_Algorithm', (['"""db_algorithms"""'], {}), "('db_algorithms')\n", (808, 825), False, 'from cDataba... |
import logging
from arango.exceptions import (
CollectionCreateError
)
from multichaindb import backend
from multichaindb.backend.localarangodb.connection import LocalArangoDBConnection
from multichaindb.backend.utils import module_dispatch_registrar
logger = logging.getLogger(__name__)
register_schema = module... | [
"logging.getLogger",
"multichaindb.backend.utils.module_dispatch_registrar"
] | [((268, 295), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (285, 295), False, 'import logging\n'), ((314, 355), 'multichaindb.backend.utils.module_dispatch_registrar', 'module_dispatch_registrar', (['backend.schema'], {}), '(backend.schema)\n', (339, 355), False, 'from multichaindb.back... |
# Copyright 2019 TerraPower, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... | [
"numpy.array",
"armi.utils.units.getTc",
"armi.materials.material.Material.__init__"
] | [((1378, 1401), 'armi.materials.material.Material.__init__', 'Material.__init__', (['self'], {}), '(self)\n', (1395, 1401), False, 'from armi.materials.material import Material\n'), ((3236, 3249), 'armi.utils.units.getTc', 'getTc', (['Tc', 'Tk'], {}), '(Tc, Tk)\n', (3241, 3249), False, 'from armi.utils.units import get... |
# -*- coding: utf-8 -*-
"""
An example url status checker implementation consumes urls from a queue.
"""
import threading
import queue
import requests
class StatusChecker(threading.Thread):
"""
The thread that will check HTTP statuses.
"""
#: The queue of urls
url_queue = None
#: The queue o... | [
"queue.Queue",
"requests.get"
] | [((1247, 1260), 'queue.Queue', 'queue.Queue', ([], {}), '()\n', (1258, 1260), False, 'import queue\n'), ((1329, 1342), 'queue.Queue', 'queue.Queue', ([], {}), '()\n', (1340, 1342), False, 'import queue\n'), ((856, 878), 'requests.get', 'requests.get', (['to_check'], {}), '(to_check)\n', (868, 878), False, 'import reque... |
from logging import getLogger
import shutil
from configparser import ConfigParser
from pathlib import Path
import yaml
from dulwich.errors import NotGitRepository
from dulwich.repo import Repo
from matador import git
logger = getLogger(__name__)
def deployment_repository(project_folder):
project = Path(project... | [
"logging.getLogger",
"matador.git.checkout",
"configparser.ConfigParser",
"pathlib.Path",
"pathlib.Path.home",
"matador.git.fetch_all",
"yaml.load",
"pathlib.Path.mkdir",
"dulwich.repo.Repo.discover"
] | [((229, 248), 'logging.getLogger', 'getLogger', (['__name__'], {}), '(__name__)\n', (238, 248), False, 'from logging import getLogger\n'), ((426, 463), 'pathlib.Path', 'Path', (['deployment_folder', '"""repository"""'], {}), "(deployment_folder, 'repository')\n", (430, 463), False, 'from pathlib import Path\n'), ((469,... |
# Generated by Django 3.1.4 on 2020-12-14 13:44
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('projects', '0002_auto_20201202_1826'),
]
operati... | [
"django.db.models.DateTimeField",
"django.db.migrations.swappable_dependency",
"django.db.models.ManyToManyField"
] | [((194, 251), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (225, 251), False, 'from django.db import migrations, models\n'), ((443, 500), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'blank': '(True... |
#!/usr/bin/python3
import pandas as pd
import csv
runs = [ ('games120.col',7),
('miles250.col',5),
('miles500.col',5),
('miles750.col',5),
('miles1000.col',5),
('miles1500.col',3),
('le450_5b.col',18),
('le450_15b.col',15),
('le450_25b.c... | [
"csv.writer",
"pandas.read_csv"
] | [((625, 660), 'pandas.read_csv', 'pd.read_csv', (['file_name'], {'header': 'None'}), '(file_name, header=None)\n', (636, 660), True, 'import pandas as pd\n'), ((943, 978), 'csv.writer', 'csv.writer', (['csvfile'], {'delimiter': '"""\t"""'}), "(csvfile, delimiter='\\t')\n", (953, 978), False, 'import csv\n')] |
from src.objects.Track import Track
from src.usesful_func import start_pygame_headless
start_pygame_headless()
track = Track("tracks/tiny.tra")
def test_car_human():
from src.cars.CarHuman import CarHuman
car = CarHuman(track)
assert car
def test_car_ai():
from src.cars.CarAI import CarAI
fr... | [
"src.usesful_func.start_pygame_headless",
"src.cars.CarHuman.CarHuman",
"src.cars.CarAI.CarAI",
"src.objects.Track.Track",
"src.objects.NeuralNet.NeuralNet.from_path"
] | [((89, 112), 'src.usesful_func.start_pygame_headless', 'start_pygame_headless', ([], {}), '()\n', (110, 112), False, 'from src.usesful_func import start_pygame_headless\n'), ((121, 145), 'src.objects.Track.Track', 'Track', (['"""tracks/tiny.tra"""'], {}), "('tracks/tiny.tra')\n", (126, 145), False, 'from src.objects.Tr... |
from grammar import SimpleGrammar
sg = SimpleGrammar()
sg.add_tag("story", ["#story_beginning# #story_problem# #story_climax# #story_ending#"])
sg.add_tag("story_beginning", ["Once upon a time there was a valiant #animal#"])
sg.add_tag("story_problem", ["that never #difficulty_verb#.", \
"that one day hear... | [
"grammar.SimpleGrammar"
] | [((40, 55), 'grammar.SimpleGrammar', 'SimpleGrammar', ([], {}), '()\n', (53, 55), False, 'from grammar import SimpleGrammar\n')] |
import requests
import json
from decimal import Decimal as D
from typing import Iterable, Any, Dict
from django.core.exceptions import ValidationError
from django.core.validators import validate_email, validate_ipv46_address
IPINTEL_URL = 'https://check.getipintel.net/check.php'
VALID_FLAGS = ['m', 'b', 'f', None]
P... | [
"json.loads",
"decimal.Decimal",
"django.core.exceptions.ValidationError",
"requests.get",
"django.core.validators.validate_email",
"django.core.validators.validate_ipv46_address"
] | [((333, 340), 'decimal.Decimal', 'D', (['(0.99)'], {}), '(0.99)\n', (334, 340), True, 'from decimal import Decimal as D\n'), ((1909, 1934), 'json.loads', 'json.loads', (['response.text'], {}), '(response.text)\n', (1919, 1934), False, 'import json\n'), ((2889, 2915), 'django.core.validators.validate_email', 'validate_e... |
import os
import csv
from utils import check_dir, make_sentences
import numpy as np
import pandas as pd
def transform(source_path):
rows = []
sentence_count = 1
new_sentence=True
for root, __subFolders, files in os.walk(source_path):
for file in files:
if file.endswith('.tags'):
... | [
"utils.make_sentences",
"os.path.join",
"numpy.setdiff1d",
"pandas.DataFrame",
"utils.check_dir",
"os.walk"
] | [((230, 250), 'os.walk', 'os.walk', (['source_path'], {}), '(source_path)\n', (237, 250), False, 'import os\n'), ((1461, 1497), 'numpy.setdiff1d', 'np.setdiff1d', (['sentence_idx', 'test_idx'], {}), '(sentence_idx, test_idx)\n', (1473, 1497), True, 'import numpy as np\n'), ((1577, 1616), 'utils.check_dir', 'check_dir',... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from Resource import Resource
from Audio import Audio
from Scene import Scene
from Song import Song, Note, loadSong
from Input import Input
import pygame
from pygame.locals import *
import sys
import getopt
import Constants
#import cProfile as profile
class DanceCV():
... | [
"getopt.getopt",
"Audio.Audio",
"pygame.display.set_caption",
"pygame.init",
"sys.exit",
"Scene.Scene",
"Song.loadSong",
"pygame.display.set_mode",
"pygame.event.get",
"pygame.display.get_surface",
"Resource.Resource",
"Input.Input",
"pygame.time.Clock",
"pygame.display.update"
] | [((1501, 1536), 'getopt.getopt', 'getopt.getopt', (['sys.argv[1:]', '"""s:x:"""'], {}), "(sys.argv[1:], 's:x:')\n", (1514, 1536), False, 'import getopt\n'), ((377, 384), 'Input.Input', 'Input', ([], {}), '()\n', (382, 384), False, 'from Input import Input\n'), ((409, 419), 'Resource.Resource', 'Resource', ([], {}), '()... |
# Generated by Django 2.0 on 2017-12-18 09:39
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('codenerix', '0020_remotelog'),
]
operations = [
migrations.AddField(
... | [
"django.db.models.CharField",
"django.db.models.ForeignKey"
] | [((390, 476), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'default': '""""""', 'max_length': '(200)', 'verbose_name': '"""Username"""'}), "(blank=True, default='', max_length=200, verbose_name=\n 'Username')\n", (406, 476), False, 'from django.db import migrations, models\n'), ((596, 6... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
def find_template(signal, rr):
return signal[200:400]
def conv(signal, template):
scores = []
template_length = len(template)
signal_length = len(signal)
for ind in ... | [
"numpy.dot",
"numpy.sqrt"
] | [((374, 425), 'numpy.dot', 'np.dot', (['signal[ind:ind + template_length]', 'template'], {}), '(signal[ind:ind + template_length], template)\n', (380, 425), True, 'import numpy as np\n'), ((440, 472), 'numpy.sqrt', 'np.sqrt', (['(score / template_length)'], {}), '(score / template_length)\n', (447, 472), True, 'import ... |
from __future__ import unicode_literals
import argparse
import mock
import pytest
from git import Repo, TagObject, Commit, GitCommandError
from git.util import hex_to_bin
import release
PREVIOUS_TAG = "v1.2.2"
CURRENT_TAG = "v1.2.3"
def _h2b(prefix):
return hex_to_bin(_pad(prefix))
def _pad(prefix):
ret... | [
"mock.patch",
"release.Repository",
"pytest.mark.parametrize",
"argparse.Namespace",
"git.GitCommandError",
"mock.MagicMock"
] | [((2234, 2377), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""dirty,untracked,result"""', '((True, True, False), (True, False, False), (False, True, False), (False, \n False, True))'], {}), "('dirty,untracked,result', ((True, True, False), (\n True, False, False), (False, True, False), (False, False... |
'''
Case Sensetive.
Support Numbers and Symbols.
Key Must be an Integer Lower Than Word Length and Higher than 1.
'''
def encryptRailFence(text, key):
rail = [['\n' for i in range(len(text))]
for j in range(key)]
dir_down = False
row, col = 0, 0
for i in range(len(text)):
... | [
"os.system"
] | [((1795, 1813), 'os.system', 'os.system', (['"""clear"""'], {}), "('clear')\n", (1804, 1813), False, 'import os\n'), ((2545, 2563), 'os.system', 'os.system', (['"""pause"""'], {}), "('pause')\n", (2554, 2563), False, 'import os\n')] |
from __future__ import print_function
import numpy as np
try:
import QENSmodels
except ImportError:
print('Module QENSmodels not found')
def hwhmChudleyElliotDiffusion(q, D=0.23, L=1.0):
""" Returns some characteristics of `ChudleyElliotDiffusion` as functions
of the momentum transfer `q`:
the ha... | [
"numpy.reshape",
"numpy.ones",
"QENSmodels.lorentzian",
"numpy.asarray",
"numpy.sinc",
"numpy.zeros",
"doctest.testmod"
] | [((1468, 1499), 'numpy.asarray', 'np.asarray', (['q'], {'dtype': 'np.float32'}), '(q, dtype=np.float32)\n', (1478, 1499), True, 'import numpy as np\n'), ((1512, 1528), 'numpy.zeros', 'np.zeros', (['q.size'], {}), '(q.size)\n', (1520, 1528), True, 'import numpy as np\n'), ((1540, 1555), 'numpy.ones', 'np.ones', (['q.siz... |
#!/usr/bin/env python3
import os
from setuptools import setup, find_packages
PKG_NAME = "flavuer"
def package_files(directory):
paths = []
for root, _, files in os.walk(directory):
root_strip = root.lstrip(f"{PKG_NAME}/")
for filename in files:
paths.append(os.path.join(root_stri... | [
"setuptools.find_packages",
"os.path.join",
"os.walk"
] | [((173, 191), 'os.walk', 'os.walk', (['directory'], {}), '(directory)\n', (180, 191), False, 'import os\n'), ((546, 576), 'setuptools.find_packages', 'find_packages', ([], {'exclude': '"""tests"""'}), "(exclude='tests')\n", (559, 576), False, 'from setuptools import setup, find_packages\n'), ((298, 332), 'os.path.join'... |
# SPDX-FileCopyrightText: 2021 Division of Intelligent Medical Systems, DKFZ
# SPDX-FileCopyrightText: 2021 <NAME>
# SPDX-License-Identifier: MIT
import numpy as np
from simpa.utils import Tags
from simpa.utils.libraries.molecule_library import MolecularComposition
from simpa.utils.libraries.structure_library.Structur... | [
"numpy.tile",
"numpy.asarray",
"numpy.subtract",
"numpy.stack",
"numpy.zeros",
"numpy.dot",
"numpy.linalg.norm",
"numpy.arange"
] | [((3772, 3809), 'numpy.subtract', 'np.subtract', (['end_voxels', 'start_voxels'], {}), '(end_voxels, start_voxels)\n', (3783, 3809), True, 'import numpy as np\n'), ((4076, 4115), 'numpy.zeros', 'np.zeros', (['self.volume_dimensions_voxels'], {}), '(self.volume_dimensions_voxels)\n', (4084, 4115), True, 'import numpy as... |
"""
Unit tests for SentencePiece tokenizer.
"""
import unittest
import os
import pickle
import tempfile
from texar.torch.data.data_utils import maybe_download
from texar.torch.data.tokenizers.sentencepiece_tokenizer import \
SentencePieceTokenizer
class SentencePieceTokenizerTest(unittest.TestCase):
def s... | [
"tempfile.TemporaryDirectory",
"pickle.dump",
"texar.torch.data.tokenizers.sentencepiece_tokenizer.SentencePieceTokenizer",
"os.path.join",
"pickle.load",
"texar.torch.data.tokenizers.sentencepiece_tokenizer.SentencePieceTokenizer.load",
"texar.torch.data.data_utils.maybe_download",
"unittest.main"
] | [((5718, 5733), 'unittest.main', 'unittest.main', ([], {}), '()\n', (5731, 5733), False, 'import unittest\n'), ((355, 384), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (382, 384), False, 'import tempfile\n'), ((413, 549), 'texar.torch.data.data_utils.maybe_download', 'maybe_download'... |
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import List, Union, Optional, Tuple
from OCP.BRepFeat import BRepFeat
from OCP.TopAbs import TopAbs_FACE
from OCP.TopExp import TopExp_Explorer
from cadquery import cq
from cq_cam.commands.base_command import Command
from cq_cam.... | [
"OCP.BRepFeat.BRepFeat",
"cadquery.cq.Workplane",
"cadquery.cq.Face.makeFromWires",
"cadquery.cq.Vector",
"OCP.TopExp.TopExp_Explorer",
"dataclasses.field",
"cadquery.cq.Face"
] | [((556, 595), 'dataclasses.field', 'field', ([], {'init': '(False)', 'default_factory': 'list'}), '(init=False, default_factory=list)\n', (561, 595), False, 'from dataclasses import dataclass, field\n'), ((692, 723), 'dataclasses.field', 'field', ([], {'default': '(20)', 'kw_only': '(True)'}), '(default=20, kw_only=Tru... |
# -*- coding: utf-8 -*-
"""
# @file name : 3_save_checkpoint.py
# @author : <NAME>
# @date : 20210403
# @brief : simulate the accident break
"""
import os
import random
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import torchvision.transforms as transfor... | [
"torch.nn.CrossEntropyLoss",
"matplotlib.pyplot.ylabel",
"torch.max",
"sys.path.append",
"os.path.exists",
"tools.my_dataset.RMBDataset",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"torchvision.transforms.ToTensor",
"os.path.dirname",
"torchvision.transforms.Normalize",
"torch.save"... | [((632, 666), 'sys.path.append', 'sys.path.append', (['hello_pytorch_DIR'], {}), '(hello_pytorch_DIR)\n', (647, 666), False, 'import sys\n'), ((668, 679), 'tools.common_tools.set_seed', 'set_seed', (['(1)'], {}), '(1)\n', (676, 679), False, 'from tools.common_tools import set_seed\n'), ((909, 958), 'os.path.join', 'os.... |
#!/usr/bin/env python3
import os
import re
import shutil
import subprocess
def matchFilm(s):
'''
Given string s,
Return true if s match conventional film name
'''
film = re.fullmatch(r'(.*?)(19|20)\d{2}(.*?)(.mp4|.mkv|.rar|.zip)$', s)
psarips = re.fullmatch(r'(.*?)(\d\d\d\d)(.*?)(\.x265\.HEVC\... | [
"os.path.exists",
"os.listdir",
"shutil.move",
"os.waitpid",
"subprocess.Popen",
"os.path.join",
"re.fullmatch",
"os.mkdir",
"os.unlink",
"os.path.expanduser"
] | [((2142, 2175), 'os.path.expanduser', 'os.path.expanduser', (['"""~/Downloads"""'], {}), "('~/Downloads')\n", (2160, 2175), False, 'import os\n'), ((2189, 2225), 'os.path.join', 'os.path.join', (['download_dir', '"""Series"""'], {}), "(download_dir, 'Series')\n", (2201, 2225), False, 'import os\n'), ((2237, 2272), 'os.... |
#!/usr/bin/env python
""" MultiQC submodule to parse output from Roary """
import logging
import statistics
from multiqc.modules.base_module import BaseMultiqcModule
from multiqc import config
from multiqc.plots import bargraph, heatmap, linegraph
log = logging.getLogger('multiqc')
class MultiqcModule(BaseMultiqcMo... | [
"logging.getLogger",
"statistics.mean",
"multiqc.plots.linegraph.plot",
"multiqc.plots.heatmap.plot",
"multiqc.plots.bargraph.plot"
] | [((257, 285), 'logging.getLogger', 'logging.getLogger', (['"""multiqc"""'], {}), "('multiqc')\n", (274, 285), False, 'import logging\n'), ((6152, 6198), 'multiqc.plots.bargraph.plot', 'bargraph.plot', (['self.summary_data', 'keys', 'config'], {}), '(self.summary_data, keys, config)\n', (6165, 6198), False, 'from multiq... |
#!/usr/bin/python3
# Usage:
# Encipher: python3 cipher.py -e input-file output-file
# Decipher: python3 cipher.py -d input-file output-file
import os, hashlib, struct
from sys import argv, exit
# ChaCha20 cipher
def keystream(key, iv, position=0):
assert isinstance(key,bytes) and len(key) == 32
assert isinst... | [
"os.urandom",
"hashlib.sha256",
"struct.unpack",
"sys.exit"
] | [((892, 917), 'struct.unpack', 'struct.unpack', (['"""<8L"""', 'key'], {}), "('<8L', key)\n", (905, 917), False, 'import os, hashlib, struct\n'), ((970, 994), 'struct.unpack', 'struct.unpack', (['"""<LL"""', 'iv'], {}), "('<LL', iv)\n", (983, 994), False, 'import os, hashlib, struct\n'), ((1795, 1811), 'hashlib.sha256'... |