code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
from datetime import datetime
from queue import deque
from time import time
import numpy as np
from comet_ml import Experiment
class Logger:
def __init__(self, opts=None, exp=None, n_train=None, n_val=None, n_test=None):
self.opts = opts
self.exp: Experiment = exp
self.n_train = n_train
... | [
"numpy.mean",
"time.time",
"datetime.datetime.now",
"queue.deque"
] | [((1131, 1137), 'time.time', 'time', ([], {}), '()\n', (1135, 1137), False, 'from time import time\n'), ((1255, 1277), 'numpy.mean', 'np.mean', (['self.qs[mode]'], {}), '(self.qs[mode])\n', (1262, 1277), True, 'import numpy as np\n'), ((548, 568), 'queue.deque', 'deque', (['[]'], {'maxlen': '(25)'}), '([], maxlen=25)\n... |
from shadowlands.sl_dapp import SLDapp, SLFrame
import pyperclip, os
import schedule
from shadowlands.tui.debug import debug
import pdb
class NetworkConnection(SLDapp):
def initialize(self):
self.add_sl_frame( NetworkStrategies(self, 10, 26, title="Network Options"))
self.connection_strategy = None
def at... | [
"schedule.once",
"os.environ.get"
] | [((2274, 2314), 'os.environ.get', 'os.environ.get', (['"""WEB3_INFURA_PROJECT_ID"""'], {}), "('WEB3_INFURA_PROJECT_ID')\n", (2288, 2314), False, 'import pyperclip, os\n'), ((2441, 2481), 'os.environ.get', 'os.environ.get', (['"""WEB3_INFURA_API_SECRET"""'], {}), "('WEB3_INFURA_API_SECRET')\n", (2455, 2481), False, 'imp... |
import flask
from flask import Response
from flask_babel import lazy_gettext as _
from api.admin.problem_details import *
from api.odl import SharedODLAPI
from api.registration.registry import Registration, RemoteRegistry
from core.model import Collection, ConfigurationSetting, Library, get_one
from core.util.http imp... | [
"core.model.ConfigurationSetting.for_library_and_externalintegration",
"core.model.get_one",
"flask.request.form.get",
"flask_babel.lazy_gettext",
"api.registration.registry.RemoteRegistry"
] | [((2629, 2668), 'flask.request.form.get', 'flask.request.form.get', (['"""collection_id"""'], {}), "('collection_id')\n", (2651, 2668), False, 'import flask\n'), ((2698, 2742), 'flask.request.form.get', 'flask.request.form.get', (['"""library_short_name"""'], {}), "('library_short_name')\n", (2720, 2742), False, 'impor... |
import re
def per_line(line):
li = line.split("__label__")
labels=[]
for l in li[1:]:
punctuation = r"""0123456789"""
text = re.sub(r'[{}]+'.format(punctuation), ' ', str(l))
text = ' '.join(text.split())
text = text.lower()
text = ' '.join(text.split("\x01_"))
... | [
"re.sub"
] | [((595, 736), 're.sub', 're.sub', (["'[.com\\u200b\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b\\x0c\\r\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a]+'", '""""""', 'text'], {}), "(\n '[.com\\u200b\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b\\x0c\\r\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\... |
import os, re, csv, requests, json
import numpy as np
import pandas as pd
from flags import CONST
from enum import Enum
from tqdm import trange
from bs4 import BeautifulSoup
from util import downloadByURL, downloadIfNotExist
class KEYS(Enum):
# -1 : 아직 라벨링 안함 (default)
# 0 : 개발과 관련없는 문서
# 1 : 개발과 관련있는 문서... | [
"util.downloadIfNotExist",
"pandas.read_csv",
"requests.get",
"os.path.isfile",
"pandas.DataFrame",
"re.sub",
"tqdm.trange"
] | [((1414, 1462), 'requests.get', 'requests.get', (['CONST.origin_data_url', "{'size': 1}"], {}), "(CONST.origin_data_url, {'size': 1})\n", (1426, 1462), False, 'import os, re, csv, requests, json\n'), ((2075, 2118), 'requests.get', 'requests.get', (['CONST.origin_data_url', 'params'], {}), '(CONST.origin_data_url, param... |
from flask import render_template
from dashboard import app
from dashboard.auth import Auth
@app.route('/')
@Auth.requires_auth
def index():
return render_template("index.html")
| [
"flask.render_template",
"dashboard.app.route"
] | [((96, 110), 'dashboard.app.route', 'app.route', (['"""/"""'], {}), "('/')\n", (105, 110), False, 'from dashboard import app\n'), ((155, 184), 'flask.render_template', 'render_template', (['"""index.html"""'], {}), "('index.html')\n", (170, 184), False, 'from flask import render_template\n')] |
##############################################
# Data Preprocessing for RoBERTa Base #
##############################################
import argparse
import json
import os
import pickle
import sys
import time
import torch
from transformers import AutoTokenizer
def preprocess_config(parser):
""" Adds Comman... | [
"os.listdir",
"pickle.dump",
"argparse.ArgumentParser",
"os.path.isdir",
"os.mkdir",
"transformers.AutoTokenizer.from_pretrained"
] | [((2963, 2988), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2986, 2988), False, 'import argparse\n'), ((4075, 4128), 'transformers.AutoTokenizer.from_pretrained', 'AutoTokenizer.from_pretrained', (["args['tokenizer_type']"], {}), "(args['tokenizer_type'])\n", (4104, 4128), False, 'from tran... |
import datetime
import backtrader as bt
from btplotting import BacktraderPlotting, BacktraderPlottingOptBrowser
from btplotting.schemes import Tradimo
class MyStrategy(bt.Strategy):
params = (
('buydate', 21),
('holdtime', 20),
)
def __init__(self):
sma1 = bt.indicators.SMA(peri... | [
"datetime.datetime",
"backtrader.Cerebro",
"btplotting.schemes.Tradimo",
"backtrader.indicators.SMA",
"backtrader.indicators.RSI"
] | [((698, 719), 'backtrader.Cerebro', 'bt.Cerebro', ([], {'maxcpus': '(1)'}), '(maxcpus=1)\n', (708, 719), True, 'import backtrader as bt\n'), ((298, 340), 'backtrader.indicators.SMA', 'bt.indicators.SMA', ([], {'period': '(11)', 'subplot': '(True)'}), '(period=11, subplot=True)\n', (315, 340), True, 'import backtrader a... |
import csv
import io
from typing import List, Dict
from datahub_metrics_ingest.DHMetric import DHMetric
def read_csv(infile: io.TextIOWrapper) -> List[Dict[str, str]]:
recs = []
str_line = lambda line: line.decode('utf-8') if type(line) == bytes else line
process_line = lambda line: [i.strip() for i in st... | [
"csv.writer"
] | [((811, 830), 'csv.writer', 'csv.writer', (['outfile'], {}), '(outfile)\n', (821, 830), False, 'import csv\n')] |
import unittest
import numpy
import chainer
from chainer import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
@testing.parameterize(*testing.product({
'shape': [(3, 2), ()],
'dtype': [numpy.float16, numpy.float32, numpy.flo... | [
"chainer.Variable",
"chainer.testing.fix_random",
"chainer.testing.run_module",
"chainer.functions.softplus",
"chainer.functions.Softplus",
"chainer.cuda.to_cpu",
"chainer.testing.product",
"numpy.exp",
"numpy.random.uniform",
"chainer.testing.assert_allclose",
"chainer.cuda.to_gpu"
] | [((332, 352), 'chainer.testing.fix_random', 'testing.fix_random', ([], {}), '()\n', (350, 352), False, 'from chainer import testing\n'), ((1835, 1873), 'chainer.testing.run_module', 'testing.run_module', (['__name__', '__file__'], {}), '(__name__, __file__)\n', (1853, 1873), False, 'from chainer import testing\n'), ((5... |
import FWCore.ParameterSet.Config as cms
process = cms.Process("CALIB")
process.MessageLogger = cms.Service("MessageLogger",
debugModules = cms.untracked.vstring(''),
QualityReader = cms.untracked.PSet(
threshold = cms.untracked.string('INFO')
),
destinations = cms.untracked.vstring('QualityRe... | [
"FWCore.ParameterSet.Config.string",
"FWCore.ParameterSet.Config.untracked.string",
"FWCore.ParameterSet.Config.Service",
"FWCore.ParameterSet.Config.untracked.int32",
"FWCore.ParameterSet.Config.Process",
"FWCore.ParameterSet.Config.uint32",
"FWCore.ParameterSet.Config.untracked.vstring",
"FWCore.Par... | [((52, 72), 'FWCore.ParameterSet.Config.Process', 'cms.Process', (['"""CALIB"""'], {}), "('CALIB')\n", (63, 72), True, 'import FWCore.ParameterSet.Config as cms\n'), ((639, 678), 'FWCore.ParameterSet.Config.Service', 'cms.Service', (['"""SiStripDetInfoFileReader"""'], {}), "('SiStripDetInfoFileReader')\n", (650, 678), ... |
import copy
from .tox_helper import Tox
class ToxBaseCase(object):
def __init__(self):
# Some of the matrix fields we might care about later. They should be
# copied in the "expand" method below, if you add any more to this
# area in the future
self.python = None
self.ansi... | [
"copy.copy"
] | [((1243, 1258), 'copy.copy', 'copy.copy', (['self'], {}), '(self)\n', (1252, 1258), False, 'import copy\n'), ((2606, 2618), 'copy.copy', 'copy.copy', (['v'], {}), '(v)\n', (2615, 2618), False, 'import copy\n')] |
from math import sqrt, pow, sin, pi, cos
from jmetal.core.problem import FloatProblem
from jmetal.core.solution import FloatSolution
"""
.. module:: ZDT
:platform: Unix, Windows
:synopsis: ZDT problem family of multi-objective problems.
.. moduleauthor:: <NAME> <<EMAIL>>
"""
class ZDT1(FloatProblem):
"""... | [
"math.pow",
"math.cos",
"math.sin",
"math.sqrt"
] | [((4549, 4561), 'math.pow', 'pow', (['g', '(0.25)'], {}), '(g, 0.25)\n', (4552, 4561), False, 'from math import sqrt, pow, sin, pi, cos\n'), ((1583, 1594), 'math.sqrt', 'sqrt', (['(f / g)'], {}), '(f / g)\n', (1587, 1594), False, 'from math import sqrt, pow, sin, pi, cos\n'), ((2453, 2468), 'math.pow', 'pow', (['(f / g... |
"""
Get the total install's of installed custom component. More info on: https://www.home-assistant.io/integrations/analytics/
"""
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from datetime import timedelta
import logging
import aiohttp
from homeassistant.components.sensor import (
S... | [
"logging.getLogger",
"datetime.timedelta",
"homeassistant.util.Throttle",
"homeassistant.helpers.aiohttp_client.async_get_clientsession"
] | [((517, 544), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (534, 544), False, 'import logging\n'), ((573, 594), 'datetime.timedelta', 'timedelta', ([], {'minutes': '(60)'}), '(minutes=60)\n', (582, 594), False, 'from datetime import timedelta\n'), ((834, 863), 'homeassistant.helpers.aio... |
from dicesapi import DicesAPI
api = DicesAPI() #Create a link to the dicesAPI
speeches = api.getSpeeches(author_name="Homer") #Get all speeches from Homer
print(len(speeches)) #Print how many speeches there are | [
"dicesapi.DicesAPI"
] | [((37, 47), 'dicesapi.DicesAPI', 'DicesAPI', ([], {}), '()\n', (45, 47), False, 'from dicesapi import DicesAPI\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# <NAME>
# orthologue
# (c) 1998-2022 all rights reserved
#
"""
Assemble an integration entirely through a local configuration file
"""
def test():
# load the local configuration file
# import pyre
# pyre.executive.configurator.dump()
# get the montec... | [
"gauss.integrators.montecarlo"
] | [((385, 426), 'gauss.integrators.montecarlo', 'gauss.integrators.montecarlo', ([], {'name': '"""mc-π"""'}), "(name='mc-π')\n", (413, 426), False, 'import gauss\n')] |
"""
Module for testing the model_selection.search module.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import os
import numpy as np
import pytest
from surprise import Dataset
from surprise import Reader
from surprise import SVD
from surprise.model_s... | [
"surprise.model_selection.GridSearchCV",
"numpy.mean",
"surprise.model_selection.PredefinedKFold",
"os.path.dirname",
"pytest.raises",
"numpy.std",
"numpy.argmin",
"surprise.Reader",
"surprise.model_selection.KFold"
] | [((1134, 1163), 'surprise.model_selection.GridSearchCV', 'GridSearchCV', (['SVD', 'param_grid'], {}), '(SVD, param_grid)\n', (1146, 1163), False, 'from surprise.model_selection import GridSearchCV\n'), ((2541, 2579), 'surprise.model_selection.KFold', 'KFold', (['(3)'], {'shuffle': '(True)', 'random_state': '(4)'}), '(3... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
本测试模块用于测试与 :class:`sqlite4dummy.schema.Delete` 有关的功能
class, method, func, exception
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
from __future__ import print_function, unicode_literals
from sqlite4dummy import *
fr... | [
"unittest.main"
] | [((1897, 1912), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1910, 1912), False, 'import unittest\n')] |
""" Train a network."""
import logging
import argparse
# This is a weird hack to avoid Intel MKL issues on the cluster when this is called as a subprocess of a process that has itself initialized PyTorch.
# Since numpy gets imported later anyway for dataset stuff, this shouldn't affect performance.
import numpy as np ... | [
"torch.randperm",
"nequip.data.dataset_from_config",
"torch.cuda.is_available",
"logging.info",
"nequip.utils.Config",
"nequip.train.trainer.Trainer.from_dict",
"argparse.ArgumentParser",
"os.path.isdir",
"nequip.model.model_from_config",
"nequip.utils.dtype_from_name",
"torch.autograd.set_detec... | [((1578, 1619), 'os.path.isdir', 'isdir', (['f"""{config.root}/{config.run_name}"""'], {}), "(f'{config.root}/{config.run_name}')\n", (1583, 1619), False, 'from os.path import isdir\n'), ((2113, 2173), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Train a NequIP model."""'}), "(descript... |
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 18 16:17:59 2019
@author: Petronium
"""
import psycopg2
conn = psycopg2.connect("dbname='Baltic_project' \
host='localhost' \
user='postgres' \
password='<PASSWORD>'")
cur = conn.cursor()
cur.ex... | [
"psycopg2.connect"
] | [((113, 296), 'psycopg2.connect', 'psycopg2.connect', (['"""dbname=\'Baltic_project\' host=\'localhost\' user=\'postgres\' password=\'<PASSWORD>\'"""'], {}), '(\n "dbname=\'Baltic_project\' host=\'localhost\' ... |
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.validators import RegexValidator
from phonenumber_field.modelfields import PhoneNumberField
import student
import weekday_field
from datetime impo... | [
"django.db.models.OneToOneField",
"django.db.models.TextField",
"django.db.models.TimeField",
"django.db.models.ForeignKey",
"django.core.validators.RegexValidator",
"django.db.models.ManyToManyField",
"django.db.models.FileField",
"django.db.models.DateTimeField",
"phonenumber_field.modelfields.Pho... | [((382, 460), 'django.core.validators.RegexValidator', 'RegexValidator', (['"""^[0-9a-zA-Z]*/$"""', '"""Only alphanumeric characters are allowed."""'], {}), "('^[0-9a-zA-Z]*/$', 'Only alphanumeric characters are allowed.')\n", (396, 460), False, 'from django.core.validators import RegexValidator\n'), ((4040, 4072), 'dj... |
""" This module handles everything related to log parsing """
import re # For parsing the log file (regular expressions)
import os # For working with files on the operating system
import logging # For logging
from game_objects.item import Item
from game_objects.floor import Floor, Curse
from game_objects.... | [
"logging.getLogger",
"os.path.getsize",
"options.Options",
"game_objects.item.Item.get_item_info",
"game_objects.item.Item",
"game_objects.floor.Floor",
"game_objects.item.Item.contains_info",
"re.search"
] | [((682, 710), 'logging.getLogger', 'logging.getLogger', (['"""tracker"""'], {}), "('tracker')\n", (699, 710), False, 'import logging\n'), ((2409, 2418), 'options.Options', 'Options', ([], {}), '()\n', (2416, 2418), False, 'from options import Options\n'), ((5091, 5133), 're.search', 're.search', (['"""Added \\\\d+ Coll... |
import os
from TB2J.myTB import MyTB, merge_tbmodels_spin
import numpy as np
from TB2J.exchange import ExchangeCL, ExchangeNCL
from TB2J.exchangeCL2 import ExchangeCL2
from TB2J.utils import read_basis, auto_assign_basis_name
from ase.io import read
from TB2J.sisl_wrapper import SislWrapper
from TB2J.gpaw_wrapper impor... | [
"os.path.exists",
"TB2J.exchangeCL2.ExchangeCL2",
"TB2J.myTB.merge_tbmodels_spin",
"TB2J.exchange.ExchangeNCL",
"TB2J.gpaw_wrapper.GPAWWrapper",
"TB2J.sisl_wrapper.SislWrapper",
"os.path.join",
"TB2J.utils.read_basis",
"sisl.get_sile",
"numpy.vstack",
"TB2J.utils.auto_assign_basis_name",
"TB2J... | [((1130, 1161), 'os.path.join', 'os.path.join', (['path', '"""basis.txt"""'], {}), "(path, 'basis.txt')\n", (1142, 1161), False, 'import os\n'), ((5483, 5507), 'sisl.get_sile', 'sisl.get_sile', (['fdf_fname'], {}), '(fdf_fname)\n', (5496, 5507), False, 'import sisl\n'), ((8615, 8647), 'TB2J.gpaw_wrapper.GPAWWrapper', '... |
"""
mark domains/boundaries with dolfin MeshFunctions
"""
"""
ueberlegungen bzgl. abstraktion:
subdomain numbers werden gebraucht fuer:
-) bilinearformen (masse) --> als tupel
-> jede variable in (v,ionen,wasser) ist mit einem tupel \subset (0,1,2,..) assoziiert
-> diese assoziation ist eine geometrische eigens... | [
"math.pow"
] | [((1811, 1820), 'math.pow', 'pow', (['x', '(2)'], {}), '(x, 2)\n', (1814, 1820), False, 'from math import sqrt, pow\n'), ((1822, 1831), 'math.pow', 'pow', (['y', '(2)'], {}), '(y, 2)\n', (1825, 1831), False, 'from math import sqrt, pow\n')] |
import sys
import pysynth
if __name__ == '__main__':
pysynth.main(*sys.argv[1:])
| [
"pysynth.main"
] | [((59, 86), 'pysynth.main', 'pysynth.main', (['*sys.argv[1:]'], {}), '(*sys.argv[1:])\n', (71, 86), False, 'import pysynth\n')] |
'''
File: abstract_gatherer.py
Project: Envirosave: A simple attempt at saving a lot of
information about the execution environment at a given point
Author: csm10495
Copyright: MIT License - 2018
'''
import datetime
import os
import pprint
import threading
import time
import subprocess
GATHERER_MAGIC = '... | [
"subprocess.check_output",
"os.makedirs",
"threading.Lock",
"time.sleep",
"pprint.pformat",
"datetime.datetime.now",
"threading.Thread",
"six.iteritems",
"time.time"
] | [((781, 797), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (795, 797), False, 'import threading\n'), ((1104, 1120), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (1118, 1120), False, 'import threading\n'), ((2438, 2462), 'six.iteritems', 'iteritems', (['self.itemDict'], {}), '(self.itemDict)\n', (2447,... |
import torch
import torch.nn.functional as F
import numpy as np
import math
from PIL import Image
import cv2
def gaussian(window_size, sigma):
"""
Generates a list of Tensor values drawn from a gaussian distribution with standard
diviation = sigma and sum of all elements = 1.
Length of list = window_s... | [
"torch.nn.functional.conv2d",
"os.listdir",
"torch.mean",
"cv2.imshow",
"cv2.waitKey",
"cv2.resize",
"cv2.imread"
] | [((1594, 1646), 'torch.nn.functional.conv2d', 'F.conv2d', (['img1', 'window'], {'padding': 'pad', 'groups': 'channels'}), '(img1, window, padding=pad, groups=channels)\n', (1602, 1646), True, 'import torch.nn.functional as F\n'), ((1657, 1709), 'torch.nn.functional.conv2d', 'F.conv2d', (['img2', 'window'], {'padding': ... |
import io
import cv2
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from estimation.coordinates import get_coordinates
from estimation.connections import get_connections
from estimation.estimators import estimate
from estimation.renderers import draw
from train_config import *
# find connec... | [
"matplotlib.pyplot.grid",
"io.BytesIO",
"estimation.coordinates.get_coordinates",
"matplotlib.pyplot.imshow",
"estimation.estimators.estimate",
"matplotlib.pyplot.close",
"matplotlib.pyplot.yticks",
"numpy.concatenate",
"tensorflow.convert_to_tensor",
"numpy.tile",
"matplotlib.pyplot.savefig",
... | [((1411, 1423), 'io.BytesIO', 'io.BytesIO', ([], {}), '()\n', (1421, 1423), False, 'import io\n'), ((1428, 1458), 'matplotlib.pyplot.savefig', 'plt.savefig', (['buf'], {'format': '"""png"""'}), "(buf, format='png')\n", (1439, 1458), True, 'import matplotlib.pyplot as plt\n'), ((1557, 1574), 'matplotlib.pyplot.close', '... |
#!/usr/bin/env python
import os
def load_numbers():
with open(os.path.join(os.path.dirname(__file__), "../data/problem_13_data")) as f:
return map(int, f.read().splitlines())
print(str(sum(load_numbers()))[:10])
| [
"os.path.dirname"
] | [((82, 107), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (97, 107), False, 'import os\n')] |
import setuptools
from os import path
pkg_name = "raphael_schema_test"
with open("README.md", "r") as fh:
long_description = fh.read()
with open(path.join(path.abspath(path.dirname(__file__)), pkg_name, 'meta.py')) as f:
exec(f.read())
setuptools.setup(
name=pkg_name,
version=__version__,
author... | [
"os.path.dirname",
"setuptools.find_packages"
] | [((590, 616), 'setuptools.find_packages', 'setuptools.find_packages', ([], {}), '()\n', (614, 616), False, 'import setuptools\n'), ((175, 197), 'os.path.dirname', 'path.dirname', (['__file__'], {}), '(__file__)\n', (187, 197), False, 'from os import path\n')] |
import json
from multiprocessing import Pool
from random import randint
from typing import List, Dict, Callable, Any
import numpy as np
import os
from tqdm import tqdm
from pietoolbelt.datasets.common import BasicDataset
from pietoolbelt.pipeline.abstract_step import AbstractStep, DatasetInPipeline, AbstractStepDirR... | [
"os.path.exists",
"os.path.join",
"numpy.argmax",
"numpy.array",
"numpy.linspace",
"pietoolbelt.pipeline.abstract_step.AbstractStep.__init__",
"multiprocessing.Pool",
"json.load",
"numpy.load",
"json.dump"
] | [((471, 502), 'os.path.join', 'os.path.join', (['path', '"""meta.json"""'], {}), "(path, 'meta.json')\n", (483, 502), False, 'import os\n'), ((515, 546), 'os.path.exists', 'os.path.exists', (['self._meta_file'], {}), '(self._meta_file)\n', (529, 546), False, 'import os\n'), ((1558, 1576), 'numpy.load', 'np.load', (['fi... |
import pandas as pd
import datetime
from copy import deepcopy
from rgtfs import io, tables
def calculate_exits(row, calendar_dates_by_trip_id):
dow = {
0: "monday",
1: "tuesday",
2: "wednesday",
3: "thursday",
4: "friday",
5: "saturday",
6: "sunday",
}... | [
"rgtfs.io.read_gtfs",
"pandas.merge",
"pandas.DataFrame",
"datetime.timedelta",
"pandas.concat"
] | [((1231, 1272), 'pandas.DataFrame', 'pd.DataFrame', (["{'departure_datetime': _df}"], {}), "({'departure_datetime': _df})\n", (1243, 1272), True, 'import pandas as pd\n'), ((1744, 1773), 'rgtfs.io.read_gtfs', 'io.read_gtfs', (['gtfs_path', '"""km"""'], {}), "(gtfs_path, 'km')\n", (1756, 1773), False, 'from rgtfs import... |
"""
Programmer: <NAME>
Date of Development: 28/10/2020
"""
# set the directory path
import os,sys
import os.path as path
abs_path_pkg = path.abspath(path.join(__file__ ,"../../../"))
dir_path = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, abs_path_pkg)
# import other libraries
import numpy as np
f... | [
"numpy.mean",
"sys.path.insert",
"Py_FS.filter._utilities.normalize",
"os.path.join",
"numpy.square",
"os.path.realpath",
"numpy.sum",
"numpy.zeros",
"numpy.argsort",
"sklearn.datasets.load_wine"
] | [((241, 273), 'sys.path.insert', 'sys.path.insert', (['(0)', 'abs_path_pkg'], {}), '(0, abs_path_pkg)\n', (256, 273), False, 'import os, sys\n'), ((152, 184), 'os.path.join', 'path.join', (['__file__', '"""../../../"""'], {}), "(__file__, '../../../')\n", (161, 184), True, 'import os.path as path\n'), ((213, 239), 'os.... |
from invoke import task
from tasks.changelog_check import changelog_check
from tasks.lint import lint
from tasks.test import test
from tasks.typecheck import typecheck
@task(post=[changelog_check, lint, typecheck, test])
def verify(_ctx):
"""Run all verification steps."""
| [
"invoke.task"
] | [((172, 223), 'invoke.task', 'task', ([], {'post': '[changelog_check, lint, typecheck, test]'}), '(post=[changelog_check, lint, typecheck, test])\n', (176, 223), False, 'from invoke import task\n')] |
# Circuit Playground Express Flip Detect
#
# Author: <NAME>
# MIT License (https://opensource.org/licenses/MIT)
import time
from adafruit_circuitplayground.express import cpx
while True:
# Wait for Circuit Playground to be flipped over (face down)
while cpx.acceleration[2] > 0:
pass # do nothing
... | [
"adafruit_circuitplayground.express.cpx.play_tone",
"time.sleep"
] | [((351, 366), 'time.sleep', 'time.sleep', (['(0.5)'], {}), '(0.5)\n', (361, 366), False, 'import time\n'), ((539, 560), 'adafruit_circuitplayground.express.cpx.play_tone', 'cpx.play_tone', (['(800)', '(1)'], {}), '(800, 1)\n', (552, 560), False, 'from adafruit_circuitplayground.express import cpx\n')] |
import numpy as np
from scipy import signal
from scipy.spatial.transform import Rotation as R
class Resize:
def __init__(self, size=125):
"""
Initiates transform with a target number for resize
:param size: int
"""
self.size = size
def __call__(self, x):
"""
... | [
"numpy.random.choice",
"scipy.signal.resample",
"numpy.zeros",
"scipy.spatial.transform.Rotation.from_euler"
] | [((2319, 2354), 'numpy.random.choice', 'np.random.choice', (['self.choices_list'], {}), '(self.choices_list)\n', (2335, 2354), True, 'import numpy as np\n'), ((2374, 2430), 'scipy.spatial.transform.Rotation.from_euler', 'R.from_euler', (['"""xy"""', '(rotate_to, rotate_to)'], {'degrees': '(True)'}), "('xy', (rotate_to,... |
#!/usr/bin/python3
import numpy as np
from matrixll import matrixll
class MLNTopology():
INDEX_INT_TYPE = int
def __init__(self):
# alt: tuple(int), xor, np.array(int), xor: simply an int !
self.layers_shape = [] # : List[int]
# nominal coord system dimensions: e.g. (x,y,ch) (theta,... | [
"matrixll.matrixll.create_matrixll",
"numpy.prod",
"matrixll.matrixll.check",
"matrixll.matrixll.shape"
] | [((7014, 7046), 'matrixll.matrixll.shape', 'matrixll.shape', (['matrix', '"""derive"""'], {}), "(matrix, 'derive')\n", (7028, 7046), False, 'from matrixll import matrixll\n'), ((2613, 2637), 'matrixll.matrixll.check', 'matrixll.check', (['m', '(-1)', 'h'], {}), '(m, -1, h)\n', (2627, 2637), False, 'from matrixll import... |
from clint.textui import colored, indent, puts, columns
from datetime import datetime
def broadcast_printer(b):
puts(columns([user_id(b), 7], [broadcast_id(b), 10], [created_at(b), 25], [feed(b), None]))
puts(colored.yellow('Content: ▼'))
# with indent(10):
puts(b.content)
puts()
def broadcast_i... | [
"clint.textui.colored.cyan",
"clint.textui.colored.yellow",
"datetime.datetime.strptime",
"clint.textui.puts",
"clint.textui.colored.blue",
"clint.textui.colored.magenta"
] | [((276, 291), 'clint.textui.puts', 'puts', (['b.content'], {}), '(b.content)\n', (280, 291), False, 'from clint.textui import colored, indent, puts, columns\n'), ((296, 302), 'clint.textui.puts', 'puts', ([], {}), '()\n', (300, 302), False, 'from clint.textui import colored, indent, puts, columns\n'), ((219, 247), 'cli... |
# -*- coding: utf-8 -*-
"""
contains main loop for training
"""
import torch
import utils
import matplotlib.pyplot as plt
import numpy as np
import torch.nn as nn
from torch.utils.data.sampler import SubsetRandomSampler
from model.dataset_class import AffectiveMonitorDataset
from model.net_valence import myLSTM_valen... | [
"torch.utils.data.sampler.SubsetRandomSampler",
"numpy.random.shuffle",
"torch.nn.CrossEntropyLoss",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.floor",
"torch.max",
"model.net_valence.myLSTM_valence",
"torch.cuda.is_available",
"model.net_arousal.myL... | [((854, 884), 'utils.load_object', 'utils.load_object', (['pickle_file'], {}), '(pickle_file)\n', (871, 884), False, 'import utils\n'), ((1325, 1359), 'torch.utils.data.sampler.SubsetRandomSampler', 'SubsetRandomSampler', (['train_indices'], {}), '(train_indices)\n', (1344, 1359), False, 'from torch.utils.data.sampler ... |
import time
import numpy as np
import random
import sys
import os
import argparse
import cv2
import zipfile
import itertools
import pybullet
import json
import time
import numpy as np
import imageio
import pybullet as p
from collect_pose_data import PoseDataCollector
sys.path.insert(1, '../utils/')
from coord_helper i... | [
"numpy.flip",
"sys.path.insert",
"argparse.ArgumentParser",
"numpy.searchsorted",
"os.path.join",
"os.path.isfile",
"numpy.array",
"numpy.argsort",
"os.path.isdir",
"os.mkdir",
"numpy.linalg.norm",
"json.load",
"numpy.load",
"numpy.save"
] | [((269, 300), 'sys.path.insert', 'sys.path.insert', (['(1)', '"""../utils/"""'], {}), "(1, '../utils/')\n", (284, 300), False, 'import sys\n'), ((2681, 2703), 'numpy.array', 'np.array', (['filtered_idx'], {}), '(filtered_idx)\n', (2689, 2703), True, 'import numpy as np\n'), ((3202, 3227), 'argparse.ArgumentParser', 'ar... |
import json
from pandajedi.jedimsgprocessor.base_msg_processor import BaseMsgProcPlugin
from pandajedi.jedimsgprocessor.tape_carousel_msg_processor import TapeCarouselMsgProcPlugin
from pandajedi.jedimsgprocessor.hpo_msg_processor import HPOMsgProcPlugin
from pandajedi.jedimsgprocessor.processing_msg_processor import ... | [
"pandajedi.jedimsgprocessor.base_msg_processor.BaseMsgProcPlugin.initialize",
"json.loads",
"pandajedi.jedimsgprocessor.tape_carousel_msg_processor.TapeCarouselMsgProcPlugin",
"pandajedi.jedimsgprocessor.hpo_msg_processor.HPOMsgProcPlugin",
"pandacommon.pandalogger.logger_utils.make_logger",
"pandajedi.je... | [((662, 696), 'pandajedi.jedimsgprocessor.base_msg_processor.BaseMsgProcPlugin.initialize', 'BaseMsgProcPlugin.initialize', (['self'], {}), '(self)\n', (690, 696), False, 'from pandajedi.jedimsgprocessor.base_msg_processor import BaseMsgProcPlugin\n'), ((732, 759), 'pandajedi.jedimsgprocessor.tape_carousel_msg_processo... |
# SPDX-License-Identifier: MIT
from riskmetrics import riskmetrics
def test_construct_cpe():
cpe = riskmetrics.construct_cpe("vendor", "product", "0.1")
assert cpe == 'cpe:/a:vendor:product:0.1'
def test_get_latest_version():
version = riskmetrics.get_latest_version("35g3q", "fq34gf")
assert version... | [
"riskmetrics.riskmetrics.get_latest_version",
"riskmetrics.riskmetrics.construct_cpe"
] | [((105, 158), 'riskmetrics.riskmetrics.construct_cpe', 'riskmetrics.construct_cpe', (['"""vendor"""', '"""product"""', '"""0.1"""'], {}), "('vendor', 'product', '0.1')\n", (130, 158), False, 'from riskmetrics import riskmetrics\n'), ((252, 301), 'riskmetrics.riskmetrics.get_latest_version', 'riskmetrics.get_latest_vers... |
from marshmallow import ValidationError
from clean_architecture_basic_classes.basic_interactors.basic_delete import (
BasicDeleteInteractor,
BasicDeleteRequestModel,
BasicDeleteResponseModel
)
from clean_architecture_basic_classes.basic_interactors.basic_get import (
BasicGetRequestModel,
BasicGetI... | [
"clean_architecture_basic_classes.basic_interactors.basic_post.BasicPostInteractor",
"clean_architecture_basic_classes.basic_interactors.basic_get_all.BasicGetAllInteractor",
"clean_architecture_basic_classes.basic_interactors.basic_get_all.BasicGetAllRequestModel",
"clean_architecture_basic_classes.basic_int... | [((4000, 4068), 'clean_architecture_basic_classes.basic_routes.exceptions.NotFoundException', 'NotFoundException', (['f"""{self._object_name} {entity_id} não encontrado"""'], {}), "(f'{self._object_name} {entity_id} não encontrado')\n", (4017, 4068), False, 'from clean_architecture_basic_classes.basic_routes.exceptions... |
from django.shortcuts import render
from techblog.models import TechblogPage
from wagtail.search.models import Query
from wagtail.core.models import Page
def index(request):
blogpages = TechblogPage.objects.live().order_by('-date')
return render(request, 'techblog/index.html', {
'blogpages': blogpage... | [
"django.shortcuts.render",
"wagtail.search.models.Query.get",
"wagtail.core.models.Page.objects.none",
"techblog.models.TechblogPage.objects.live"
] | [((250, 314), 'django.shortcuts.render', 'render', (['request', '"""techblog/index.html"""', "{'blogpages': blogpages}"], {}), "(request, 'techblog/index.html', {'blogpages': blogpages})\n", (256, 314), False, 'from django.shortcuts import render\n'), ((685, 814), 'django.shortcuts.render', 'render', (['request', '"""t... |
# -*- coding: utf-8 -*-
from __future__ import division, print_function
__all__ = ["simplexy"]
import numpy as np
from ._simplexy import simplexy as run_simplexy
_dtype = np.dtype([("x", np.float32), ("y", np.float32),
("flux", np.float32), ("bkg", np.float32)])
def simplexy(img, **kwargs):
... | [
"numpy.dtype",
"numpy.ascontiguousarray"
] | [((177, 273), 'numpy.dtype', 'np.dtype', (["[('x', np.float32), ('y', np.float32), ('flux', np.float32), ('bkg', np.\n float32)]"], {}), "([('x', np.float32), ('y', np.float32), ('flux', np.float32), (\n 'bkg', np.float32)])\n", (185, 273), True, 'import numpy as np\n'), ((340, 385), 'numpy.ascontiguousarray', 'n... |
# Generated by Django 3.1.7 on 2021-03-05 21:32
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('users', '0003_auto_20210305_2112'),
]
operations = [
migrations.AlterField(
model_name='user',
name='use... | [
"uuid.UUID"
] | [((370, 419), 'uuid.UUID', 'uuid.UUID', (['"""105c578f-e803-4f0e-ab70-e0b2895b2bf3"""'], {}), "('105c578f-e803-4f0e-ab70-e0b2895b2bf3')\n", (379, 419), False, 'import uuid\n')] |
# https://github.com/lukecavabarrett/pna/blob/master/models/pytorch_geometric/example.py
import torch
import torch.nn.functional as F
from torch.nn import ModuleList
from torch.nn import Sequential, ReLU, Linear
from ogb.graphproppred.mol_encoder import AtomEncoder, BondEncoder
from torch_geometric.nn import BatchNorm... | [
"ogb.graphproppred.mol_encoder.BondEncoder",
"torch.nn.ReLU",
"ogb.graphproppred.mol_encoder.AtomEncoder",
"torch.nn.ModuleList",
"torch_geometric.nn.BatchNorm",
"torch.nn.functional.dropout",
"torch.nn.Linear"
] | [((1416, 1428), 'torch.nn.ModuleList', 'ModuleList', ([], {}), '()\n', (1426, 1428), False, 'from torch.nn import ModuleList\n'), ((1456, 1468), 'torch.nn.ModuleList', 'ModuleList', ([], {}), '()\n', (1466, 1468), False, 'from torch.nn import ModuleList\n'), ((797, 829), 'ogb.graphproppred.mol_encoder.AtomEncoder', 'At... |
import pytest
import numpy as np
from mindspore import ops, Tensor, context
from mindspore.common.parameter import Parameter
from mindspore.nn import Cell
class AssignNet(Cell):
def __init__(self, input_variable):
super(AssignNet, self).__init__()
self.op = ops.Assign()
self.input_data = i... | [
"mindspore.context.set_context",
"numpy.random.seed",
"mindspore.Tensor",
"mindspore.ops.Assign",
"numpy.random.randn"
] | [((774, 791), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (788, 791), True, 'import numpy as np\n'), ((856, 903), 'mindspore.context.set_context', 'context.set_context', ([], {'mode': 'context.PYNATIVE_MODE'}), '(mode=context.PYNATIVE_MODE)\n', (875, 903), False, 'from mindspore import ops, Tensor, c... |
import json
def handler(event: dict, context) -> dict:
return {
'statusCode': 200,
'body': json.dumps('Hello World')
} | [
"json.dumps"
] | [((113, 138), 'json.dumps', 'json.dumps', (['"""Hello World"""'], {}), "('Hello World')\n", (123, 138), False, 'import json\n')] |
from setuptools import setup, find_packages
setup(
name='Player',
packages=find_packages(),
)
setup(
name='Vendor',
version='0.0.1',
description='Vending machine software',
long_description='long_description',
url='https://github.com/LMCMLJ/samnple',
author='<NAME>',
license='Apache... | [
"setuptools.find_packages",
"setuptools.setup"
] | [((103, 489), 'setuptools.setup', 'setup', ([], {'name': '"""Vendor"""', 'version': '"""0.0.1"""', 'description': '"""Vending machine software"""', 'long_description': '"""long_description"""', 'url': '"""https://github.com/LMCMLJ/samnple"""', 'author': '"""<NAME>"""', 'license': '"""Apache_2.0"""', 'classifiers': "['D... |
"""
Gym-Retro Random-agent
"""
import argparse
#import gym
#from gym import spaces
import retro
import os
import time
import csv
os.environ['DISPLAY'] = ':1'
timestr = time.strftime("%Y%m%d-%H%M%S")
parser = argparse.ArgumentParser()
#parser.add_argument('--game', default='SMB-JU', help='the name or path for the game... | [
"argparse.ArgumentParser",
"csv.writer",
"time.strftime",
"os.path.join",
"os.getcwd",
"retro.data.list_games",
"retro.make"
] | [((170, 200), 'time.strftime', 'time.strftime', (['"""%Y%m%d-%H%M%S"""'], {}), "('%Y%m%d-%H%M%S')\n", (183, 200), False, 'import time\n'), ((210, 235), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (233, 235), False, 'import argparse\n'), ((1324, 1335), 'os.getcwd', 'os.getcwd', ([], {}), '()\... |
# Copyright 2019 Google 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 writing, ... | [
"protorpc.message_types.VoidMessage",
"tradefed_cluster.device_manager.HideDevice",
"logging.debug",
"tradefed_cluster.api_common.tradefed_cluster_api.api_class",
"tradefed_cluster.util.ndb_shim.put_multi",
"tradefed_cluster.datastore_entities.DeviceInfoHistory.query",
"tradefed_cluster.datastore_entiti... | [((1239, 1326), 'tradefed_cluster.api_common.tradefed_cluster_api.api_class', 'api_common.tradefed_cluster_api.api_class', ([], {'resource_name': '"""devices"""', 'path': '"""devices"""'}), "(resource_name='devices', path=\n 'devices')\n", (1280, 1326), False, 'from tradefed_cluster import api_common\n'), ((2643, 27... |
# -*- coding: utf-8 -*-
import functools
import threading
from typing import TYPE_CHECKING, Any, Callable
if TYPE_CHECKING:
from pandas import DataFrame
from pyathenajdbc.cursor import Cursor
def as_pandas(cursor: "Cursor", coerce_float: bool = False) -> "DataFrame":
from pandas import DataFrame
de... | [
"jpype.java.lang.Thread.isAttached",
"threading.RLock",
"functools.wraps",
"jpype.java.lang.Thread.attach",
"pandas.DataFrame"
] | [((705, 722), 'threading.RLock', 'threading.RLock', ([], {}), '()\n', (720, 722), False, 'import threading\n'), ((729, 753), 'functools.wraps', 'functools.wraps', (['wrapped'], {}), '(wrapped)\n', (744, 753), False, 'import functools\n'), ((943, 967), 'functools.wraps', 'functools.wraps', (['wrapped'], {}), '(wrapped)\... |
# Generated by Django 3.1.2 on 2020-11-01 18:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('flights', '0002_auto_20201101_1957'),
]
operations = [
migrations.AddField(
model_name='flight',
name='number_flight... | [
"django.db.models.IntegerField"
] | [((341, 371), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'default': '(1)'}), '(default=1)\n', (360, 371), False, 'from django.db import migrations, models\n')] |
# Generated by Django 3.1 on 2020-10-02 19:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0030_color'),
('market', '0007_auto_20201002_2108'),
]
operations = [
migrations.AlterField(
model_name='product',
... | [
"django.db.models.ManyToManyField"
] | [((365, 454), 'django.db.models.ManyToManyField', 'models.ManyToManyField', ([], {'blank': '(True)', 'null': '(True)', 'to': '"""app.Color"""', 'verbose_name': '"""رنگ ها"""'}), "(blank=True, null=True, to='app.Color', verbose_name=\n 'رنگ ها')\n", (387, 454), False, 'from django.db import migrations, models\n')] |
"""
SC101 Baby Names Project
Adapted from <NAME>'s Baby Names assignment by
<NAME>.
YOUR DESCRIPTION HERE
"""
import tkinter
import babynames
import babygraphicsgui as gui
FILENAMES = [
'data/full/baby-1900.txt', 'data/full/baby-1910.txt',
'data/full/baby-1920.txt', 'data/full/baby-1930.txt',
'data/full/... | [
"babygraphicsgui.make_gui",
"babynames.read_files",
"tkinter.Tk"
] | [((8081, 8112), 'babynames.read_files', 'babynames.read_files', (['FILENAMES'], {}), '(FILENAMES)\n', (8101, 8112), False, 'import babynames\n'), ((8162, 8174), 'tkinter.Tk', 'tkinter.Tk', ([], {}), '()\n', (8172, 8174), False, 'import tkinter\n'), ((8219, 8316), 'babygraphicsgui.make_gui', 'gui.make_gui', (['top', 'CA... |
"""
Template matching
Template matching is a technique for finding areas of an image that are similar to
a patch (template).
A patch is a small image with certain features. The goal of template matching is
to find the patch/template in an image.
To find it, the user has to give two input images... | [
"cv2.rectangle",
"numpy.where",
"cv2.imshow",
"cv2.cvtColor",
"cv2.matchTemplate",
"cv2.imread"
] | [((1881, 1911), 'cv2.imread', 'cv2.imread', (['"""../images/1.jpeg"""'], {}), "('../images/1.jpeg')\n", (1891, 1911), False, 'import cv2\n'), ((1950, 1991), 'cv2.cvtColor', 'cv2.cvtColor', (['img_rgb', 'cv2.COLOR_BGR2GRAY'], {}), '(img_rgb, cv2.COLOR_BGR2GRAY)\n', (1962, 1991), False, 'import cv2\n'), ((2024, 2049), 'c... |
from hashlib import md5
from django.shortcuts import render, get_object_or_404
from django.views.generic import View
from django.contrib.auth.models import User
from accounts.models import UserProfile
class UserProfileView(View):
def get_object(self, username):
return get_object_or_404(User, username=u... | [
"django.shortcuts.render",
"django.shortcuts.get_object_or_404"
] | [((286, 344), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (['User'], {'username': 'username', 'is_active': '(True)'}), '(User, username=username, is_active=True)\n', (303, 344), False, 'from django.shortcuts import render, get_object_or_404\n'), ((634, 693), 'django.shortcuts.render', 'render', (['reques... |
# coding=utf-8
"""Retrieve Pokémon information from a PKM file."""
__author__ = '<NAME> <<EMAIL>>'
import datetime
import struct
from pypkm.structs import gen4, gen5
from pypkm.crypto import checksum, encrypt, decrypt
from pypkm.sqlite import get_level, get_nature, get_basestats
from pypkm.util import calcstat, Leng... | [
"pypkm.sqlite.get_basestats",
"pypkm.crypto.checksum",
"pypkm.util.calcstat",
"pypkm.crypto.decrypt",
"struct.pack",
"datetime.datetime.now",
"pypkm.sqlite.get_level",
"pypkm.sqlite.get_nature"
] | [((1411, 1429), 'pypkm.crypto.checksum', 'checksum', (['data[8:]'], {}), '(data[8:])\n', (1419, 1429), False, 'from pypkm.crypto import checksum, encrypt, decrypt\n'), ((1450, 1475), 'struct.pack', 'struct.pack', (['"""<H"""', 'chksum'], {}), "('<H', chksum)\n", (1461, 1475), False, 'import struct\n'), ((2147, 2196), '... |
# --coding:utf-8--
#
# Copyright (c) 2020 vesoft inc. All rights reserved.
#
# This source code is licensed under Apache 2.0 License,
# attached with Common Clause Condition 1.0, found in the LICENSES directory.
import time
import pytest
from tests.common.nebula_test_suite import NebulaTestSuite, T_NULL
class TestI... | [
"time.sleep"
] | [((813, 835), 'time.sleep', 'time.sleep', (['self.delay'], {}), '(self.delay)\n', (823, 835), False, 'import time\n')] |
"""
ASGI config for syarpa_k8s project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/howto/deployment/asgi/
"""
import os
import pathlib
import dotenv
import django
django.setup()
from syarpa_k8s.routin... | [
"os.environ.setdefault",
"channels.routing.URLRouter",
"django.setup",
"pathlib.Path",
"django.core.asgi.get_asgi_application"
] | [((282, 296), 'django.setup', 'django.setup', ([], {}), '()\n', (294, 296), False, 'import django\n'), ((660, 730), 'os.environ.setdefault', 'os.environ.setdefault', (['"""DJANGO_SETTINGS_MODULE"""', '"""syarpa_k8s.settings"""'], {}), "('DJANGO_SETTINGS_MODULE', 'syarpa_k8s.settings')\n", (681, 730), False, 'import os\... |
from django.test import Client, TestCase
from bug_reports.models import BugReport
class TestBugReport(TestCase):
def test_get_bug_report_view(self):
c = Client()
response = c.get("/report_problem/?source=foo&source_url=barbaz")
self.assertEqual(200, response.status_code)
expected_s... | [
"bug_reports.models.BugReport.objects.all",
"django.test.Client"
] | [((167, 175), 'django.test.Client', 'Client', ([], {}), '()\n', (173, 175), False, 'from django.test import Client, TestCase\n'), ((879, 887), 'django.test.Client', 'Client', ([], {}), '()\n', (885, 887), False, 'from django.test import Client, TestCase\n'), ((1201, 1224), 'bug_reports.models.BugReport.objects.all', 'B... |
import matplotlib
matplotlib.use('Agg')
import argparse
import tkinter as tk
import torch
from isegm.utils import exp
from isegm.inference import utils
from interactive_demo.app import InteractiveDemoApp
def main():
args, cfg = parse_args()
torch.backends.cudnn.deterministic = True
checkpoint_path = ut... | [
"argparse.ArgumentParser",
"matplotlib.use",
"isegm.inference.utils.find_checkpoint",
"tkinter.Tk",
"isegm.inference.utils.load_is_model",
"isegm.utils.exp.load_config_file",
"interactive_demo.app.InteractiveDemoApp",
"torch.device"
] | [((18, 39), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (32, 39), False, 'import matplotlib\n'), ((318, 385), 'isegm.inference.utils.find_checkpoint', 'utils.find_checkpoint', (['cfg.INTERACTIVE_MODELS_PATH', 'args.checkpoint'], {}), '(cfg.INTERACTIVE_MODELS_PATH, args.checkpoint)\n', (339, 38... |
#!/usr/bin/env ipython
# -*- coding: utf-8 -*-
import random as ran
import math
import numpy as np
"""Define auxiliary functions for Corona Testing Simulation."""
def _make_test(testlist, current_success_rate, false_posivite_rate, prob_sick,
tests_repetitions=1, test_result_decision_strategy='max'):
... | [
"numpy.ceil",
"numpy.ones",
"numpy.random.rand",
"numpy.max",
"random.random",
"numpy.random.shuffle"
] | [((3063, 3083), 'numpy.ones', 'np.ones', (['sample_size'], {}), '(sample_size)\n', (3070, 3083), True, 'import numpy as np\n'), ((3121, 3143), 'numpy.random.shuffle', 'np.random.shuffle', (['arr'], {}), '(arr)\n', (3138, 3143), True, 'import numpy as np\n'), ((1127, 1139), 'random.random', 'ran.random', ([], {}), '()\n... |
# Generated by Django 2.2.6 on 2019-10-21 08:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('award', '0005_rating_vote_average'),
]
operations = [
migrations.AlterField(
model_name='rating',
name='vote_average... | [
"django.db.models.DecimalField"
] | [((341, 404), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'blank': '(True)', 'decimal_places': '(2)', 'max_digits': '(2)'}), '(blank=True, decimal_places=2, max_digits=2)\n', (360, 404), False, 'from django.db import migrations, models\n')] |
# Copyright 2022 Google.
#
# 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 writing, soft... | [
"jax.numpy.full",
"jax.numpy.concatenate",
"jax.tree_structure",
"jax.numpy.sum",
"functools.partial",
"jax.numpy.ones",
"t5x.models.remove_prefix"
] | [((813, 837), 'jax.tree_structure', 'jax.tree_structure', (['None'], {}), '(None)\n', (831, 837), False, 'import jax\n'), ((6339, 6445), 'functools.partial', 'functools.partial', (['self._compute_logits_from_slice'], {'params': 'params', 'max_decode_length': 'max_decode_length'}), '(self._compute_logits_from_slice, par... |
import unittest
import decimal
import os
import datetime
import hashlib
from nose.plugins.attrib import attr
from eactivities import EActivities
from eactivities.parsers.documentation import InventoryParser, RiskAssessmentParser, KeyListsParser
import eactivities.parsers.finances as finance_parsers
# l... | [
"eactivities.parsers.finances.MembersFundsRedistributionsParser",
"eactivities.parsers.documentation.RiskAssessmentParser",
"os.getenv",
"nose.plugins.attrib.attr",
"eactivities.parsers.documentation.InventoryParser",
"eactivities.parsers.finances.TransactionCorrectionsParser",
"eactivities.parsers.fina... | [((365, 397), 'os.getenv', 'os.getenv', (['"""EHACK_TEST_USERNAME"""'], {}), "('EHACK_TEST_USERNAME')\n", (374, 397), False, 'import os\n'), ((410, 433), 'os.getenv', 'os.getenv', (['"""<PASSWORD>"""'], {}), "('<PASSWORD>')\n", (419, 433), False, 'import os\n'), ((575, 587), 'nose.plugins.attrib.attr', 'attr', (['"""li... |
import pickle
import csv
from gensim.parsing import preprocessing
import re
import os
from tqdm import tqdm
import psycopg2
import psycopg2.extras
conn = psycopg2.connect("dbname=MAG19 user=mag password=<PASSWORD>$ host=shetland.informatik.uni-freiburg.de")
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCurso... | [
"psycopg2.connect"
] | [((154, 267), 'psycopg2.connect', 'psycopg2.connect', (['"""dbname=MAG19 user=mag password=<PASSWORD>$ host=shetland.informatik.uni-freiburg.de"""'], {}), "(\n 'dbname=MAG19 user=mag password=<PASSWORD>$ host=shetland.informatik.uni-freiburg.de'\n )\n", (170, 267), False, 'import psycopg2\n')] |
import unittest
from class_weights import gen_class_weights
class TestGenClassWeights(unittest.TestCase):
"""
Test class_weigths module
"""
def test_gen_class_weights_1(self):
"""
'mel' attribute has weight 3.0 and 'bbc' attribute does not has weight 2... | [
"unittest.main",
"class_weights.gen_class_weights"
] | [((696, 711), 'unittest.main', 'unittest.main', ([], {}), '()\n', (709, 711), False, 'import unittest\n'), ((482, 528), 'class_weights.gen_class_weights', 'gen_class_weights', ([], {'class_indices': 'class_indices'}), '(class_indices=class_indices)\n', (499, 528), False, 'from class_weights import gen_class_weights\n')... |
from indexd import get_app
import os
os.environ["INDEXD_SETTINGS"] = "/var/www/indexd/"
application = get_app()
| [
"indexd.get_app"
] | [((103, 112), 'indexd.get_app', 'get_app', ([], {}), '()\n', (110, 112), False, 'from indexd import get_app\n')] |
import json
import logging
import os
import time
from datetime import datetime
import torch
from tqdm import tqdm
import configs
from functions.metrics import calculate_mAP
from scripts.train_helper import prepare_dataloader, prepare_model
from utils import io
from utils.logger import setup_logging
def get_codes(mo... | [
"utils.io.join_save_queue",
"datetime.datetime.today",
"utils.logger.setup_logging",
"logging.info",
"scripts.train_helper.prepare_model",
"utils.io.fast_save",
"json.dumps",
"utils.io.init_save_queue",
"os.path.isdir",
"functions.metrics.calculate_mAP",
"configs.seeding",
"time.time",
"torc... | [((416, 495), 'tqdm.tqdm', 'tqdm', (['test_loader'], {'desc': '"""Test"""', 'ascii': '(True)', 'bar_format': '"""{l_bar}{bar:10}{r_bar}"""'}), "(test_loader, desc='Test', ascii=True, bar_format='{l_bar}{bar:10}{r_bar}')\n", (420, 495), False, 'from tqdm import tqdm\n'), ((955, 992), 'torch.load', 'torch.load', (['path'... |
"""mastercode_films_api URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home'... | [
"django.urls.path"
] | [((754, 780), 'django.urls.path', 'path', (['"""post_v2"""', 'moviePost'], {}), "('post_v2', moviePost)\n", (758, 780), False, 'from django.urls import path\n'), ((830, 852), 'django.urls.path', 'path', (['"""get"""', 'movieList'], {}), "('get', movieList)\n", (834, 852), False, 'from django.urls import path\n'), ((858... |
from dataclasses import dataclass
from object2dataclass import Object2Dataclass
@dataclass
class Color:
red: int = None
green: int = None
blue: int = None
@dataclass
class Rectangle:
width: int = None
height: int = None
color: Color = Color()
try:
obj = {'width': 50, 'height': 42, 'co... | [
"object2dataclass.Object2Dataclass.convert_object_to_dataclass",
"object2dataclass.Object2Dataclass.can_be_convert_to_dataclass"
] | [((397, 457), 'object2dataclass.Object2Dataclass.can_be_convert_to_dataclass', 'Object2Dataclass.can_be_convert_to_dataclass', (['obj', 'Rectangle'], {}), '(obj, Rectangle)\n', (441, 457), False, 'from object2dataclass import Object2Dataclass\n'), ((565, 625), 'object2dataclass.Object2Dataclass.convert_object_to_datacl... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import frappe
__version__ = '0.0.1'
@frappe.whitelist()
def download_backup(filename):
from frappe.utils.response import download_backup
return download_backup("/backups/"+filename)
| [
"frappe.whitelist",
"frappe.utils.response.download_backup"
] | [((104, 122), 'frappe.whitelist', 'frappe.whitelist', ([], {}), '()\n', (120, 122), False, 'import frappe\n'), ((213, 252), 'frappe.utils.response.download_backup', 'download_backup', (["('/backups/' + filename)"], {}), "('/backups/' + filename)\n", (228, 252), False, 'from frappe.utils.response import download_backup\... |
"""
semaphore是用于控制进入数量的锁, 内部使用了condition实现.
如文件可读, 可写. 在写入时应该为一个线程写, 但是读时可以有多个线程读.
我们希望在读取时, 仅为10个线程读.
"""
import time
import threading
class Spider(threading.Thread):
def __init__(self, url: str, semaphore: threading.Semaphore):
super().__init__()
self.__url = url
self.semaphore = semaph... | [
"threading.Semaphore",
"time.sleep"
] | [((875, 897), 'threading.Semaphore', 'threading.Semaphore', (['(5)'], {}), '(5)\n', (894, 897), False, 'import threading\n'), ((360, 373), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (370, 373), False, 'import time\n')] |
import os, django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings")
django.setup()
import argparse, contextlib
import json
from django.utils import timezone
from datetime import timedelta
from core.settings import DATABASES
from django.contrib.auth.models import User
from teams.models import Team
from u... | [
"os.environ.setdefault",
"django.contrib.auth.models.User.objects.create_superuser",
"django.setup",
"teams.models.Team",
"uauth.models.Profile",
"contextlib.suppress",
"os.system",
"os.remove"
] | [((18, 82), 'os.environ.setdefault', 'os.environ.setdefault', (['"""DJANGO_SETTINGS_MODULE"""', '"""core.settings"""'], {}), "('DJANGO_SETTINGS_MODULE', 'core.settings')\n", (39, 82), False, 'import os, django\n'), ((83, 97), 'django.setup', 'django.setup', ([], {}), '()\n', (95, 97), False, 'import os, django\n'), ((5... |
"""
Connection module.
"""
from lib import connect
DB = connect()
| [
"lib.connect"
] | [((57, 66), 'lib.connect', 'connect', ([], {}), '()\n', (64, 66), False, 'from lib import connect\n')] |
import logging
from django.core.management import call_command
from math import ceil
from multiprocessing import Pool, Event
from time import perf_counter
from typing import Generator, List
from usaspending_api.broker.helpers.last_load_date import update_last_load_date
from usaspending_api.common.elasticsearch.client... | [
"logging.getLogger",
"usaspending_api.etl.elasticsearch_loader_helpers.load_data",
"time.perf_counter",
"usaspending_api.etl.elasticsearch_loader_helpers.toggle_refresh_on",
"usaspending_api.etl.elasticsearch_loader_helpers.deleted_awards",
"usaspending_api.etl.elasticsearch_loader_helpers.set_final_index... | [((713, 740), 'logging.getLogger', 'logging.getLogger', (['"""script"""'], {}), "('script')\n", (730, 740), False, 'import logging\n'), ((5532, 5546), 'time.perf_counter', 'perf_counter', ([], {}), '()\n', (5544, 5546), False, 'from time import perf_counter\n'), ((5693, 5727), 'usaspending_api.common.elasticsearch.clie... |
import pickle
import greentest
from gevent.ares import ares_host_result
class TestPickle(greentest.TestCase):
# Issue 104: ares.ares_host_result unpickleable
def _test(self, protocol):
r = ares_host_result('family', ('arg1', 'arg2', ))
dumped = pickle.dumps(r, protocol)
loaded = pickl... | [
"pickle.dumps",
"pickle.loads",
"gevent.ares.ares_host_result",
"greentest.main"
] | [((791, 807), 'greentest.main', 'greentest.main', ([], {}), '()\n', (805, 807), False, 'import greentest\n'), ((208, 252), 'gevent.ares.ares_host_result', 'ares_host_result', (['"""family"""', "('arg1', 'arg2')"], {}), "('family', ('arg1', 'arg2'))\n", (224, 252), False, 'from gevent.ares import ares_host_result\n'), (... |
from typing import Tuple
import torch
from torch import nn
class MixUp(nn.Module):
r"""
Implementation of mixup: BEYOND EMPIRICAL RISK MINIMIZATION (https://arxiv.org/abs/1710.09412)
Official implementation: https://github.com/facebookresearch/mixup-cifar10
Note: Can sit inside a model as a method o... | [
"torch.distributions.beta",
"torch.empty",
"torch.randperm"
] | [((550, 563), 'torch.empty', 'torch.empty', ([], {}), '()\n', (561, 563), False, 'import torch\n'), ((586, 599), 'torch.empty', 'torch.empty', ([], {}), '()\n', (597, 599), False, 'import torch\n'), ((920, 933), 'torch.empty', 'torch.empty', ([], {}), '()\n', (931, 933), False, 'import torch\n'), ((956, 969), 'torch.em... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: <NAME>(<EMAIL>)
from model.backbones.vgg.vgg_backbone import VGGBackbone
from model.backbones.darknet.darknet_backbone import DarkNetBackbone
from model.backbones.resnet.resnet_backbone import ResNetBackbone
from model.backbones.mobilenet.mobilenet_backbone impor... | [
"model.backbones.squeezenet.squeezenet_backbone.SqueezeNetBackbone",
"model.backbones.mobilenet.mobilenet_backbone.MobileNetBackbone",
"model.backbones.densenet.densenet_backbone.DenseNetBackbone",
"model.backbones.resnet.resnet_backbone.ResNetBackbone",
"model.backbones.darknet.darknet_backbone.DarkNetBack... | [((807, 833), 'model.backbones.vgg.vgg_backbone.VGGBackbone', 'VGGBackbone', (['self.configer'], {}), '(self.configer)\n', (818, 833), False, 'from model.backbones.vgg.vgg_backbone import VGGBackbone\n'), ((901, 931), 'model.backbones.darknet.darknet_backbone.DarkNetBackbone', 'DarkNetBackbone', (['self.configer'], {})... |
"""
相比于原始的plot.py文件,增加了如下的功能:
1.可以直接在pycharm或者vscode执行,也可以用命令行传参;
2.按exp_name排序,而不是按时间排序;
3.固定好每个exp_name的颜色;
4.可以调节曲线的线宽,便于观察;
5.保存图片到本地,便于远程ssh画图~
6.自动显示全屏
7.图片自适应
8.针对颜色不敏感的人群,可以在每条legend上注明性能值,和性能序号
9.对图例legend根据性能从高到低排序,便于分析比较
10.提供clip_xaxis值,对训练程度进行统一截断,图看起来更整洁。
seaborn版本0.8.1
"""
import seaborn as sns
import p... | [
"numpy.convolve",
"numpy.array",
"os.walk",
"seaborn.set",
"os.listdir",
"argparse.ArgumentParser",
"numpy.asarray",
"os.path.isdir",
"numpy.round",
"numpy.ones",
"matplotlib.pyplot.gcf",
"matplotlib.pyplot.gca",
"os.path.dirname",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show",
... | [((3104, 3146), 'seaborn.set', 'sns.set', ([], {'style': '"""darkgrid"""', 'font_scale': '(1.75)'}), "(style='darkgrid', font_scale=1.75)\n", (3111, 3146), True, 'import seaborn as sns\n'), ((5142, 5285), 'matplotlib.pyplot.legend', 'plt.legend', (['sorted_handles', 'sorted_labels'], {'loc': '"""upper center"""', 'labe... |
import argparse
import os
import numpy as np
from rsgd.common.dat import load_dat
from rsgd.common.logistic import logistic_grad
from rsgd.common.logistic import logistic_loss
from rsgd.common.logistic import logistic_test
from rsgd.common.utils import get_batch_index
from sklearn.utils import shuffle
def sgd_restart... | [
"numpy.abs",
"numpy.mean",
"argparse.ArgumentParser",
"rsgd.common.dat.load_dat",
"rsgd.common.utils.get_batch_index",
"os.path.join",
"numpy.zeros",
"rsgd.common.logistic.logistic_test",
"numpy.linalg.norm"
] | [((530, 560), 'rsgd.common.utils.get_batch_index', 'get_batch_index', (['N', 'batch_size'], {}), '(N, batch_size)\n', (545, 560), False, 'from rsgd.common.utils import get_batch_index\n'), ((675, 697), 'numpy.zeros', 'np.zeros', (['(niter, dim)'], {}), '((niter, dim))\n', (683, 697), True, 'import numpy as np\n'), ((70... |
import sys
from floyd_warshall.simulate_production_environment import SimulateProductionEnvironment
def main():
"""" Run this script to push data from stdin into the proof of concept production system """
system_simulator = SimulateProductionEnvironment()
for msg_line in sys.stdin:
response = sys... | [
"floyd_warshall.simulate_production_environment.SimulateProductionEnvironment"
] | [((234, 265), 'floyd_warshall.simulate_production_environment.SimulateProductionEnvironment', 'SimulateProductionEnvironment', ([], {}), '()\n', (263, 265), False, 'from floyd_warshall.simulate_production_environment import SimulateProductionEnvironment\n')] |
#!/usr/bin/env python
try:
from setuptools import setup, find_packages
from setuptools.command.test import test
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
from setuptools.command.test import test
class mytest(test):
... | [
"setuptools.find_packages",
"ez_setup.use_setuptools",
"runtests.runtests"
] | [((185, 201), 'ez_setup.use_setuptools', 'use_setuptools', ([], {}), '()\n', (199, 201), False, 'from ez_setup import use_setuptools\n'), ((399, 409), 'runtests.runtests', 'runtests', ([], {}), '()\n', (407, 409), False, 'from runtests import runtests\n'), ((621, 636), 'setuptools.find_packages', 'find_packages', ([], ... |
from math import sqrt
def divisors(number: int) -> List[int]:
solutions = []
number = int(number)
for i in range(1, int(sqrt(number)) + 1):
if number % i == 0:
if number // i == i:
solutions.append(i)
else:
solutions.append(i)
s... | [
"math.sqrt"
] | [((132, 144), 'math.sqrt', 'sqrt', (['number'], {}), '(number)\n', (136, 144), False, 'from math import sqrt\n')] |
from datetime import datetime
from uuid import uuid4
import pytz
from freezegun.api import freeze_time
from ee.clickhouse.models.event import create_event
from ee.clickhouse.queries.util import get_earliest_timestamp
def _create_event(**kwargs):
pk = uuid4()
kwargs.update({"event_uuid": pk})
create_even... | [
"datetime.datetime",
"ee.clickhouse.queries.util.get_earliest_timestamp",
"freezegun.api.freeze_time",
"uuid.uuid4",
"ee.clickhouse.models.event.create_event"
] | [((335, 360), 'freezegun.api.freeze_time', 'freeze_time', (['"""2021-01-21"""'], {}), "('2021-01-21')\n", (346, 360), False, 'from freezegun.api import freeze_time\n'), ((694, 719), 'freezegun.api.freeze_time', 'freeze_time', (['"""2021-01-21"""'], {}), "('2021-01-21')\n", (705, 719), False, 'from freezegun.api import ... |
#!/usr/bin/env python
# Electrum - lightweight Bitcoin client
# Copyright (C) 2014 <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... | [
"electrum_ltc.logging.get_logger",
"base64.b64decode",
"time.sleep",
"xmlrpc.client.ServerProxy",
"electrum_ltc.plugin.BasePlugin.__init__"
] | [((1336, 1356), 'electrum_ltc.logging.get_logger', 'get_logger', (['__name__'], {}), '(__name__)\n', (1346, 1356), False, 'from electrum_ltc.logging import get_logger\n'), ((1366, 1428), 'xmlrpc.client.ServerProxy', 'ServerProxy', (['"""https://cosigner.electrum.org/"""'], {'allow_none': '(True)'}), "('https://cosigner... |
"""Shared command functions."""
from __future__ import absolute_import, division, print_function
import difflib
import logging
import os
import sys
from functools import update_wrapper
import click
from pkg_resources import iter_entry_points
from drifter.providers import get_providers
def validate_name(ctx, name)... | [
"logging.getLogger",
"os.path.exists",
"click.argument",
"click.option",
"pkg_resources.iter_entry_points",
"click.style",
"os.path.join",
"drifter.providers.get_providers",
"os.environ.get",
"click.utils.make_str",
"os.path.dirname",
"sys.exit",
"click.exceptions.UsageError",
"functools.u... | [((852, 863), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (860, 863), False, 'import sys\n'), ((4448, 4478), 'functools.update_wrapper', 'update_wrapper', (['new_func', 'func'], {}), '(new_func, func)\n', (4462, 4478), False, 'from functools import update_wrapper\n'), ((4880, 4916), 'pkg_resources.iter_entry_points... |
import numpy as np
from urllib import request
import gzip
import os
import boto3
import json
dirname = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(dirname, "config.json"), "r") as f:
CONFIG = json.load(f)
def mnist_to_numpy(data_dir='/tmp/data', train=True):
"""Download MNIST dataset a... | [
"numpy.mean",
"os.path.exists",
"boto3.client",
"os.makedirs",
"numpy.std",
"os.path.join",
"json.load",
"numpy.expand_dims",
"numpy.finfo",
"os.path.abspath",
"numpy.transpose"
] | [((121, 146), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (136, 146), False, 'import os\n'), ((221, 233), 'json.load', 'json.load', (['f'], {}), '(f)\n', (230, 233), False, 'import json\n'), ((877, 895), 'boto3.client', 'boto3.client', (['"""s3"""'], {}), "('s3')\n", (889, 895), False, 'im... |
from profil3r.app.search import search_get
from bs4 import BeautifulSoup
import time
class Hackernews:
def __init__(self, config, permutations_list):
# 1000 ms
self.delay = config['plateform']['hackernews']['rate_limit'] / 1000
# https://news.ycombinator.com/user?id={username}
self... | [
"bs4.BeautifulSoup",
"profil3r.app.search.search_get",
"time.sleep"
] | [((1072, 1092), 'profil3r.app.search.search_get', 'search_get', (['username'], {}), '(username)\n', (1082, 1092), False, 'from profil3r.app.search import search_get\n'), ((2260, 2282), 'time.sleep', 'time.sleep', (['self.delay'], {}), '(self.delay)\n', (2270, 2282), False, 'import time\n'), ((1488, 1524), 'bs4.Beautifu... |
import sqlite3, csv, sys, time, os
class ContainsIDException(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return repr(self.message)
def convert(csv_name, db_name, table_name, external_header_row=[], commit=False, dev=False): #checktablename for injection, ... | [
"os.path.isfile",
"csv.reader",
"sqlite3.connect",
"os.remove"
] | [((1253, 1276), 'os.path.isfile', 'os.path.isfile', (['db_name'], {}), '(db_name)\n', (1267, 1276), False, 'import sqlite3, csv, sys, time, os\n'), ((1278, 1296), 'os.remove', 'os.remove', (['db_name'], {}), '(db_name)\n', (1287, 1296), False, 'import sqlite3, csv, sys, time, os\n'), ((1306, 1330), 'sqlite3.connect', '... |
from cnoid.Util import *
from cnoid.Base import *
from cnoid.Body import *
from cnoid.BodyPlugin import *
from cnoid.SimpleControllerPlugin import *
import math;
worldItem = WorldItem()
RootItem.instance().addChildItem(worldItem)
timeBar = TimeBar.instance()
timeBar.setFrameRate(500)
timeBar.setTimeRange(0.0, 15.0)
... | [
"math.radians"
] | [((750, 768), 'math.radians', 'math.radians', (['q[i]'], {}), '(q[i])\n', (762, 768), False, 'import math\n')] |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import torch
from torch import nn, optim
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
from ignite.engine import Events, create_supervised_trainer, create_supervised_evaluato... | [
"ignite.engine.create_supervised_evaluator",
"ignite.metrics.Loss",
"torch.nn.ReLU",
"ignite.metrics.Accuracy",
"ignite.handlers.ModelCheckpoint",
"torch.cuda.is_available",
"ignite.engine.create_supervised_trainer",
"torch.nn.BatchNorm2d",
"ignite.metrics.ConfusionMatrix",
"torchvision.transforms... | [((667, 746), 'torchvision.datasets.FashionMNIST', 'datasets.FashionMNIST', (['"""./data"""'], {'download': '(True)', 'train': '(True)', 'transform': 'transform'}), "('./data', download=True, train=True, transform=transform)\n", (688, 746), False, 'from torchvision import datasets, transforms\n'), ((762, 811), 'torch.u... |
import functools
from dtlib.tornado.utils import save_api_counts
def get_callback_result(callback, res_str):
"""
根据callback后的jsonp语句
:param callback:
:param res_str:
:return:
"""
if callback is None:
return res_str
else:
return '%s(%s)' % (callback.encode("utf-8"), res... | [
"dtlib.tornado.utils.save_api_counts",
"functools.wraps"
] | [((478, 501), 'functools.wraps', 'functools.wraps', (['method'], {}), '(method)\n', (493, 501), False, 'import functools\n'), ((600, 621), 'dtlib.tornado.utils.save_api_counts', 'save_api_counts', (['self'], {}), '(self)\n', (615, 621), False, 'from dtlib.tornado.utils import save_api_counts\n')] |
# Search function
# Prior to running this, a model must first be loaded and vectors must first be built for documents
import pandas as pd
import re
import spacy
from rank_bm25 import BM25Okapi
from tqdm import tqdm
import pickle
import numpy as np
from gensim.models.fasttext import FastText
import os
import nmslib
imp... | [
"pandas.DataFrame",
"numpy.mean",
"pandas.merge",
"time.time"
] | [((615, 637), 'numpy.mean', 'np.mean', (['query'], {'axis': '(0)'}), '(query, axis=0)\n', (622, 637), True, 'import numpy as np\n'), ((644, 655), 'time.time', 'time.time', ([], {}), '()\n', (653, 655), False, 'import time\n'), ((732, 743), 'time.time', 'time.time', ([], {}), '()\n', (741, 743), False, 'import time\n'),... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
from __future__ import with_statement
import os
import sys
import six
import shlex
import tempfile
import functools
from io import StringIO
from collections import Sequence
from os.path import dirname, exists
from tw... | [
"txtorcon.util.delete_file_or_tree",
"shlex.split",
"txtorcon.torconfig.TorConfig",
"txtorcon.endpoints._create_socks_endpoint",
"txtorcon.util.find_tor_binary",
"txtorcon.onion.EphemeralOnionService.create",
"txtorcon.onion._validate_ports",
"twisted.internet.interfaces.IStreamClientEndpoint.provided... | [((17138, 17155), 'zope.interface.implementer', 'implementer', (['ITor'], {}), '(ITor)\n', (17149, 17155), False, 'from zope.interface import implementer\n'), ((10743, 10754), 'os.getpid', 'os.getpid', ([], {}), '()\n', (10752, 10754), False, 'import os\n'), ((13022, 13088), 'twisted.python.log.msg', 'log.msg', (['"""S... |
from researchutils import files
import chainer.serializers
def save_model(path, model):
"""
Save model as an npz file to given path
Parameters
-------
path : string
path of the model to be saved
model : chainer.Link
model to save parameters
Raises
-------
ValueEr... | [
"researchutils.files.file_exists"
] | [((367, 390), 'researchutils.files.file_exists', 'files.file_exists', (['path'], {}), '(path)\n', (384, 390), False, 'from researchutils import files\n'), ((880, 903), 'researchutils.files.file_exists', 'files.file_exists', (['path'], {}), '(path)\n', (897, 903), False, 'from researchutils import files\n'), ((1379, 140... |
# Copyright 2019 <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 in writing, softw... | [
"torch.nn.Linear"
] | [((1176, 1208), 'torch.nn.Linear', 'nn.Linear', (['dataset.in_dim', 'h_dim'], {}), '(dataset.in_dim, h_dim)\n', (1185, 1208), True, 'import torch.nn as nn\n'), ((1264, 1298), 'torch.nn.Linear', 'nn.Linear', (['self.total_z_dim', 'h_dim'], {}), '(self.total_z_dim, h_dim)\n', (1273, 1298), True, 'import torch.nn as nn\n'... |
# -*- coding: utf-8 -*-
"""Bytecode Interpreter operations base class
Note: this is subclassed. Later versions use operations from here.
"""
from __future__ import print_function, division
import inspect
import operator
import logging
import sys
from xdis import PYTHON_VERSION
from xpython.pyobj import Function
from ... | [
"logging.getLogger",
"inspect.isbuiltin",
"xpython.pyobj.Function",
"xpython.builtins.build_class",
"operator.imatmul",
"inspect.isfunction"
] | [((363, 390), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (380, 390), False, 'import logging\n'), ((4308, 4331), 'inspect.isbuiltin', 'inspect.isbuiltin', (['func'], {}), '(func)\n', (4325, 4331), False, 'import inspect\n'), ((10259, 10283), 'inspect.isfunction', 'inspect.isfunction', ... |