code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
from collections import defaultdict
import logging
from django.db import transaction
from django.utils import six
logger = logging.getLogger(__name__)
class Importer(object):
'''
Imports objects from source database to dest database.
It respects ForeignKey and OneToOne relationships, so it
recursiv... | [
"logging.getLogger",
"django.utils.six.iteritems",
"django.utils.six.iterkeys",
"django.db.transaction.atomic",
"collections.defaultdict"
] | [((126, 153), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (143, 153), False, 'import logging\n'), ((721, 737), 'collections.defaultdict', 'defaultdict', (['set'], {}), '(set)\n', (732, 737), False, 'from collections import defaultdict\n'), ((1012, 1042), 'django.utils.six.iterkeys', 's... |
from dataclasses import dataclass
import datetime
@dataclass
class Object:
confidence: int
@dataclass
class Dimension:
width: int
height: int
depth: int
@dataclass
class Annotation:
class_id: int
top: int
left: int
width: int
height: int
@dataclass
class BoundingBox:
imag... | [
"datetime.datetime.now"
] | [((561, 584), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (582, 584), False, 'import datetime\n')] |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 23 15:57:53 2016
@author: jone0208
"""
import Body
import matplotlib.pyplot as plt
import Solver
import Simulation
def main():
skull = Body.GravBody(5,5,5)
solver = Solver.RK2(0.001)
def stop_condition(skull):
return skull.velocity > 0
sim = Simu... | [
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"Solver.RK2",
"Body.GravBody",
"matplotlib.pyplot.title",
"Simulation.TrajectorySim"
] | [((189, 211), 'Body.GravBody', 'Body.GravBody', (['(5)', '(5)', '(5)'], {}), '(5, 5, 5)\n', (202, 211), False, 'import Body\n'), ((223, 240), 'Solver.RK2', 'Solver.RK2', (['(0.001)'], {}), '(0.001)\n', (233, 240), False, 'import Solver\n'), ((316, 371), 'Simulation.TrajectorySim', 'Simulation.TrajectorySim', (['stop_co... |
from twilio.rest import Client
class _Notifier:
def __init__(self, twilio_account_sid, twilio_auth_token, twilio_phone_number):
self.client = Client(twilio_account_sid, twilio_auth_token)
self.phone_number = twilio_phone_number
pass
class Messenger(_Notifier):
def _send_sms(self, pho... | [
"twilio.rest.Client"
] | [((156, 201), 'twilio.rest.Client', 'Client', (['twilio_account_sid', 'twilio_auth_token'], {}), '(twilio_account_sid, twilio_auth_token)\n', (162, 201), False, 'from twilio.rest import Client\n')] |
from typing import List, Dict, Optional
from myutils.registrar import Registrar
from myutils import dictionaries
import os, yaml
from os import path
import json
from .exceptions import FeatureConfigException
reg_plots = Registrar()
reg_features = Registrar()
KEY_SAMPLE = 'smp'
KEY_AVERAGE = 'avg'
KEY_TICKS = 'tck'
K... | [
"myutils.registrar.Registrar",
"yaml.dump",
"os.path.expandvars",
"json.dumps",
"os.path.join",
"yaml.load",
"myutils.dictionaries.validate_config",
"os.path.splitext",
"os.path.isdir",
"os.walk"
] | [((222, 233), 'myutils.registrar.Registrar', 'Registrar', ([], {}), '()\n', (231, 233), False, 'from myutils.registrar import Registrar\n'), ((249, 260), 'myutils.registrar.Registrar', 'Registrar', ([], {}), '()\n', (258, 260), False, 'from myutils.registrar import Registrar\n'), ((619, 643), 'os.path.expandvars', 'pat... |
from di.container import Container
from di.dependant import Dependant, Injectable
from di.executors import SyncExecutor
class UsersRepo(Injectable, scope="app"):
pass
def endpoint(repo: UsersRepo) -> UsersRepo:
return repo
def framework():
container = Container()
solved = container.solve(
... | [
"di.dependant.Dependant",
"di.container.Container",
"di.executors.SyncExecutor"
] | [((270, 281), 'di.container.Container', 'Container', ([], {}), '()\n', (279, 281), False, 'from di.container import Container\n'), ((405, 419), 'di.executors.SyncExecutor', 'SyncExecutor', ([], {}), '()\n', (417, 419), False, 'from di.executors import SyncExecutor\n'), ((320, 356), 'di.dependant.Dependant', 'Dependant'... |
import cv2
import numpy as np
def class_name(classid):
id_dict = {1:'Scratch', 2:'Dent', 3:'Shatter', 4:'Dislocation'}
return id_dict[classid]
def damage_cost(classid):
# cost_dict = {1: [800, 1400], 2:[1200, 3000],3:19000, 4:17000}
cost_dict = {1: 900, 2:1600, 3:19000, 4:17000}
return... | [
"numpy.float32"
] | [((500, 521), 'numpy.float32', 'np.float32', (['crop_mask'], {}), '(crop_mask)\n', (510, 521), True, 'import numpy as np\n')] |
from re import findall
from json import loads
from ethereum import utils
opening_brackets = ["(", "{", "[", "<"]
closing_brackets = [")", "}", "]", ">"]
newlines_reg = r'(\r\n|\r|\n)'
newlines = ['\r\n', '\r', '\n']
def count_lines(text):
if text == "":
return 0
return 1 + len(findall(newlines_reg, t... | [
"re.findall",
"json.loads",
"ethereum.utils.sha3"
] | [((938, 957), 'json.loads', 'loads', (['contract.abi'], {}), '(contract.abi)\n', (943, 957), False, 'from json import loads\n'), ((297, 324), 're.findall', 'findall', (['newlines_reg', 'text'], {}), '(newlines_reg, text)\n', (304, 324), False, 'from re import findall\n'), ((381, 408), 're.findall', 'findall', (['newlin... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
from nose.tools import eq_, ok_
from werkzeug.test import Client
from werkzeug.wrappers import BaseResponse
from clastic import Application
from clastic.render import JSONRender, JSONPRender, render_basic
from common import (hello_world_str,
... | [
"json.loads",
"os.path.dirname",
"clastic.render.JSONPRender",
"werkzeug.test.Client",
"clastic.render.JSONRender",
"clastic.Application"
] | [((457, 482), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (472, 482), False, 'import os\n'), ((611, 762), 'clastic.Application', 'Application', (["[('/', hello_world_ctx, render_json), ('/<name>/', hello_world_ctx,\n render_json), ('/beta/<name>/', complex_context, render_json)]"], {}),... |
# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\server_commands\inventory_commands.py
# Compiled at: 2020-07-22 20:32:56
# Size of source mod 2**32:... | [
"distributor.ops.SendUIMessage",
"protocolbuffers.UI_pb2.InventorySellRequest",
"protocolbuffers.SimObjectAttributes_pb2.PersistenceMaster",
"services.sim_info_manager",
"objects.system.create_object",
"distributor.system.Distributor.instance",
"services.definition_manager",
"server_commands.argument_... | [((1099, 1120), 'services.active_lot', 'services.active_lot', ([], {}), '()\n', (1118, 1120), False, 'import services, sims4.commands\n'), ((1359, 1380), 'services.active_lot', 'services.active_lot', ([], {}), '()\n', (1378, 1380), False, 'import services, sims4.commands\n'), ((1852, 1877), 'services.object_manager', '... |
"""My2h JOP Transform Utility
Usage:
loco.py convert <input.lok> <output.2lok>
loco.py (-h | --help)
loco.py --version
Options:
-h --help Show this screen.
--version Show version.
"""
import os
import logging
import configparser
from docopt import docopt
#Tady je soubor specifikace hnacíh... | [
"logging.basicConfig",
"os.path.exists",
"configparser.ConfigParser",
"os.path.abspath",
"logging.info",
"docopt.docopt",
"os.remove"
] | [((541, 562), 'os.path.exists', 'os.path.exists', (['fname'], {}), '(fname)\n', (555, 562), False, 'import os\n'), ((2022, 2054), 'docopt.docopt', 'docopt', (['__doc__'], {'version': '"""0.0.1"""'}), "(__doc__, version='0.0.1')\n", (2028, 2054), False, 'from docopt import docopt\n'), ((2348, 2424), 'logging.basicConfig... |
"""
Test utilities
"""
import os
import pytest
import factory
from django.test.html import HTMLParseError, parse_html
from cms.api import add_plugin
from cms.models import Placeholder
from cms.test_utils.testcases import CMSTestCase
from cmsplugin_blocks.utils.factories import create_image_file
def get_fake_words(... | [
"django.test.html.parse_html",
"os.path.join",
"factory.Faker",
"pytest.fixture",
"cmsplugin_blocks.utils.factories.create_image_file",
"cms.api.add_plugin",
"cms.models.Placeholder.objects.create"
] | [((449, 482), 'factory.Faker', 'factory.Faker', (['"""words"""'], {'nb': 'length'}), "('words', nb=length)\n", (462, 482), False, 'import factory\n'), ((1498, 1532), 'cmsplugin_blocks.utils.factories.create_image_file', 'create_image_file', (['*args'], {}), '(*args, **kwargs)\n', (1515, 1532), False, 'from cmsplugin_bl... |
import os
import sys
import argparse
import configparser
import random
import string
import subprocess
from godaddypy import Client, Account
def get_parser():
parser = argparse.ArgumentParser(description='Python script to generate certificate for name.suffix.domain on Godaddy', add_help=True)
parser.add_argum... | [
"random.choice",
"configparser.ConfigParser",
"argparse.ArgumentParser",
"os.path.isabs",
"subprocess.run",
"os.environ.copy",
"os.getcwd",
"argparse.Namespace",
"godaddypy.Client"
] | [((174, 308), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Python script to generate certificate for name.suffix.domain on Godaddy"""', 'add_help': '(True)'}), "(description=\n 'Python script to generate certificate for name.suffix.domain on Godaddy',\n add_help=True)\n", (197, 3... |
#!/usr/bin/env python
# Licensed under a 3-clause BSD style license - see LICENSE.rst
#
# Imports
#
import sys
from os.path import exists
#
# setuptools' sdist command ignores MANIFEST.in
#
from distutils.command.sdist import sdist as DistutilsSdist
# from ez_setup import use_setuptools
# use_setuptools()
from setuptoo... | [
"os.path.exists",
"setuptools.find_packages",
"setuptools.setup",
"importlib.import_module"
] | [((1523, 1543), 'os.path.exists', 'exists', (['"""README.rst"""'], {}), "('README.rst')\n", (1529, 1543), False, 'from os.path import exists\n'), ((2095, 2110), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (2108, 2110), False, 'from setuptools import setup, find_packages\n'), ((2596, 2619), 'setuptool... |
import os
from parsers.baseline_parser import parse_baseline_file
class AddStatus:
def __init__(self, path):
self.path = path
def __call__(self, dic):
packages = dic["packages"]
baseline_path = self.path
if os.path.isfile(baseline_path):
packageStatus = parse_base... | [
"os.path.isfile",
"parsers.baseline_parser.parse_baseline_file"
] | [((251, 280), 'os.path.isfile', 'os.path.isfile', (['baseline_path'], {}), '(baseline_path)\n', (265, 280), False, 'import os\n'), ((310, 344), 'parsers.baseline_parser.parse_baseline_file', 'parse_baseline_file', (['baseline_path'], {}), '(baseline_path)\n', (329, 344), False, 'from parsers.baseline_parser import pars... |
from LoopStructural.utils import LoopImportError, LoopTypeError, LoopValueError
try:
from LoopProjectFile import ProjectFile
except ImportError:
raise LoopImportError("LoopProjectFile cannot be imported")
from .process_data import ProcessInputData
import numpy as np
import pandas as pd
import networkx
from L... | [
"LoopStructural.utils.LoopImportError",
"LoopStructural.utils.getLogger",
"LoopStructural.utils.LoopTypeError"
] | [((366, 385), 'LoopStructural.utils.getLogger', 'getLogger', (['__name__'], {}), '(__name__)\n', (375, 385), False, 'from LoopStructural.utils import getLogger\n'), ((159, 212), 'LoopStructural.utils.LoopImportError', 'LoopImportError', (['"""LoopProjectFile cannot be imported"""'], {}), "('LoopProjectFile cannot be im... |
from PyQt5 import QtWidgets, QtCore, QtGui
class AlbumButton(QtWidgets.QFrame):
selected = QtCore.pyqtSignal(str)
def __init__(self, image, audio):
super().__init__()
self.audio = audio
self.background_image = QtGui.QPixmap(image).scaled(100, 100,
... | [
"PyQt5.QtCore.pyqtSignal",
"PyQt5.QtWidgets.QLabel",
"PyQt5.QtGui.QPixmap"
] | [((98, 120), 'PyQt5.QtCore.pyqtSignal', 'QtCore.pyqtSignal', (['str'], {}), '(str)\n', (115, 120), False, 'from PyQt5 import QtWidgets, QtCore, QtGui\n'), ((414, 436), 'PyQt5.QtWidgets.QLabel', 'QtWidgets.QLabel', (['self'], {}), '(self)\n', (430, 436), False, 'from PyQt5 import QtWidgets, QtCore, QtGui\n'), ((246, 266... |
#! /bin/python
import sys
import os
import time
import glob
import simplejson as json
import subprocess
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
import config
import utils
#---------------------------------------------------------------------------------------
def main(dirlis... | [
"os.path.exists",
"config.clonedDataDir",
"time.clock",
"utils.getListOfFiles",
"utils.newerFile",
"os.makedirs",
"os.chdir",
"simplejson.dump",
"sys.exit",
"os.path.abspath",
"utils.getWinPath",
"utils.spawnProcess"
] | [((338, 350), 'time.clock', 'time.clock', ([], {}), '()\n', (348, 350), False, 'import time\n'), ((1758, 1780), 'config.clonedDataDir', 'config.clonedDataDir', ([], {}), '()\n', (1778, 1780), False, 'import config\n'), ((2011, 2024), 'sys.exit', 'sys.exit', (['ret'], {}), '(ret)\n', (2019, 2024), False, 'import sys\n')... |
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Wongkar and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class Rule(Document):
def validate(self):
frappe.msgprint("after_insert")
# manufacture = frapp... | [
"frappe.throw",
"frappe.db.get_value",
"frappe.msgprint"
] | [((265, 296), 'frappe.msgprint', 'frappe.msgprint', (['"""after_insert"""'], {}), "('after_insert')\n", (280, 296), False, 'import frappe\n'), ((897, 1021), 'frappe.db.get_value', 'frappe.db.get_value', (['"""Rule"""', "{'item_code': self.item_code, 'besar_dp': self.besar_dp, 'tenor': self.tenor}", '"""item_code"""'], ... |
import pandas as pd
import numpy as np
from datetime import datetime
import seaborn
import matplotlib.pyplot as plt
seaborn.set_style('darkgrid')
def __to_percent1(y, position):
y = y * 100.0
return "{:.1f}%".format(y)
def plot_roc(target, predicted_proba, title, save_png=''):
import matplotlib.pyplot... | [
"matplotlib.pyplot.text",
"matplotlib.pyplot.savefig",
"matplotlib.ticker.FuncFormatter",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"sklearn.metrics.roc_auc_score",
"seaborn.set_style",
"matplotlib.pyplot.figure",
"sklearn.metrics.... | [((116, 145), 'seaborn.set_style', 'seaborn.set_style', (['"""darkgrid"""'], {}), "('darkgrid')\n", (133, 145), False, 'import seaborn\n'), ((454, 488), 'sklearn.metrics.roc_curve', 'roc_curve', (['target', 'predicted_proba'], {}), '(target, predicted_proba)\n', (463, 488), False, 'from sklearn.metrics import roc_curve... |
#!/usr/bin/env python
import argparse, sys, math
# covalent radius to decide a bond. bond length: r1+r2
radius = {" H": 0.25,
" N": 0.65,
" C": 0.70,
" O": 0.60,
" P": 1.00,
" S": 1.00,
"NA": 1.80,
"CL": 1.00
}
elebd_radius = {" N": 1.5,... | [
"sys.exit",
"math.sqrt",
"argparse.ArgumentParser",
"math.acos"
] | [((966, 1016), 'math.sqrt', 'math.sqrt', (['(v[0] * v[0] + v[1] * v[1] + v[2] * v[2])'], {}), '(v[0] * v[0] + v[1] * v[1] + v[2] * v[2])\n', (975, 1016), False, 'import argparse, sys, math\n'), ((1349, 1361), 'math.acos', 'math.acos', (['t'], {}), '(t)\n', (1358, 1361), False, 'import argparse, sys, math\n'), ((1498, 1... |
from WebsiteDescriptor import *
import googlemaps
from googlemaps import places
from tqdm import tqdm
import time
gmaps = googlemaps.Client(key='AIzaSyAFjRuP86SUl9EtuNOjjr12rY646RSp2Vo')
def find_station(browser, place_id: str) -> Website:
"""Finds a single station given a place_id and returns a website"""
... | [
"googlemaps.Client",
"tqdm.tqdm",
"selenium.webdriver.Firefox",
"time.sleep",
"googlemaps.places.places_nearby",
"googlemaps.places.place"
] | [((125, 189), 'googlemaps.Client', 'googlemaps.Client', ([], {'key': '"""AIzaSyAFjRuP86SUl9EtuNOjjr12rY646RSp2Vo"""'}), "(key='AIzaSyAFjRuP86SUl9EtuNOjjr12rY646RSp2Vo')\n", (142, 189), False, 'import googlemaps\n'), ((739, 752), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (749, 752), False, 'import time\n'), ((... |
from twisted.internet import reactor
from twisted.trial import unittest
from comet.utility import coerce_to_client_endpoint, coerce_to_server_endpoint
class coerce_to_client_endpoint_TestCase(unittest.TestCase):
HOST, PORT, DEFAULT_PORT = "test", 1234, 4321
def test_good_tcp_parse(self):
ep = coerce... | [
"comet.utility.coerce_to_client_endpoint",
"comet.utility.coerce_to_server_endpoint"
] | [((314, 404), 'comet.utility.coerce_to_client_endpoint', 'coerce_to_client_endpoint', (['reactor', 'f"""tcp:{self.HOST}:{self.PORT}"""', 'self.DEFAULT_PORT'], {}), "(reactor, f'tcp:{self.HOST}:{self.PORT}', self.\n DEFAULT_PORT)\n", (339, 404), False, 'from comet.utility import coerce_to_client_endpoint, coerce_to_s... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.project_select, name='project_select'),
url(r'^project/add$', views.project_edit, name='project_add'),
url(r'^project/edit/(?P<edit_project_id>\d+)$', views.project_edit, name='project_edit'),
url(r'^project/del/(?P<d... | [
"django.conf.urls.url"
] | [((74, 128), 'django.conf.urls.url', 'url', (['"""^$"""', 'views.project_select'], {'name': '"""project_select"""'}), "('^$', views.project_select, name='project_select')\n", (77, 128), False, 'from django.conf.urls import url\n'), ((135, 195), 'django.conf.urls.url', 'url', (['"""^project/add$"""', 'views.project_edit... |
from ftplib import FTP
from ..config import FTP_SERVER_URL
from ..globals import globals as g
class FTPClient:
def __init__(self, host, user, passwd):
self.ftp = FTP(host)
# self.ftp.set_debuglevel(2)
self.ftp.set_pasv(True)
self.ftp.login(user, passwd)
def download(self, fil... | [
"ftplib.FTP"
] | [((177, 186), 'ftplib.FTP', 'FTP', (['host'], {}), '(host)\n', (180, 186), False, 'from ftplib import FTP\n')] |
import sys
import time
import requests
def send_request(keyword):
headers = {
"Accept": "application/json, text/javascript, */*; q=0.01",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "zh-CN,zh;q=0.9",
"Connection": "keep-alive",
"Content-Length": "275",
... | [
"requests.post",
"time.time"
] | [((2051, 2108), 'requests.post', 'requests.post', (['url'], {'data': 'data', 'headers': 'headers', 'timeout': '(3)'}), '(url, data=data, headers=headers, timeout=3)\n', (2064, 2108), False, 'import requests\n'), ((1988, 1999), 'time.time', 'time.time', ([], {}), '()\n', (1997, 1999), False, 'import time\n')] |
import os
import pickle
import radical.pilot as rp
import radical.utils as ru
from radical.entk import Task
from radical.entk import exceptions as ree
# ------------------------------------------------------------------------------
#
def resolve_placeholders(path, placeholders, logger):
"""
**Purpose**: Su... | [
"radical.pilot.TaskDescription",
"radical.utils.Url",
"pickle.dump",
"radical.entk.exceptions.ValueError",
"radical.entk.Task",
"radical.utils.generate_id"
] | [((15614, 15634), 'radical.pilot.TaskDescription', 'rp.TaskDescription', ([], {}), '()\n', (15632, 15634), True, 'import radical.pilot as rp\n'), ((19289, 19295), 'radical.entk.Task', 'Task', ([], {}), '()\n', (19293, 19295), False, 'from radical.entk import Task\n'), ((15794, 15833), 'radical.utils.generate_id', 'ru.g... |
import re
import numpy as np
def compounddic2atomsfraction(compounds):
def createNewDic(dic, multiplyby):
values = list(dic.values())
keys = dic.keys()
newValues = np.array(values)*multiplyby
newDic = dict(zip(keys, newValues))
return newDic
def composition2atoms(cstr)... | [
"numpy.array",
"re.findall"
] | [((336, 383), 're.findall', 're.findall', (['"""([A-Z][a-z]?)(\\\\d*\\\\.?\\\\d*)"""', 'cstr'], {}), "('([A-Z][a-z]?)(\\\\d*\\\\.?\\\\d*)', cstr)\n", (346, 383), False, 'import re\n'), ((194, 210), 'numpy.array', 'np.array', (['values'], {}), '(values)\n', (202, 210), True, 'import numpy as np\n')] |
"""utilities to speedup calculations with jit
Author: <NAME>
Affiliation: TokyoTech & OSX
"""
import numpy as np
import torch
from numba import f8, jit
@jit(f8[:, :](f8[:, :]), nopython=True)
def get_normed_vec_mag(arr_vec: np.ndarray) -> np.ndarray:
"""compute
from [[x1, y1], [x2, y2], ...]
to [... | [
"numpy.hstack",
"numpy.where",
"numpy.sum",
"numpy.zeros",
"numpy.empty"
] | [((669, 703), 'numpy.where', 'np.where', (['(vec_mag == 0)', '(1)', 'vec_mag'], {}), '(vec_mag == 0, 1, vec_mag)\n', (677, 703), True, 'import numpy as np\n'), ((758, 787), 'numpy.hstack', 'np.hstack', (['(arr_vec, vec_mag)'], {}), '((arr_vec, vec_mag))\n', (767, 787), True, 'import numpy as np\n'), ((1706, 1752), 'num... |
import csv
import copy
import matplotlib.pyplot as plt
def getCsv(txtFileName='twentyfourth.txt'):
with open(txtFileName) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=' ')
return list(csv_reader)
def parseLineList(csvFile):
instructionList = []
for row in csvFile:
ins... | [
"csv.reader",
"copy.deepcopy"
] | [((2272, 2297), 'copy.deepcopy', 'copy.deepcopy', (['blackTiles'], {}), '(blackTiles)\n', (2285, 2297), False, 'import copy\n'), ((162, 197), 'csv.reader', 'csv.reader', (['csv_file'], {'delimiter': '""" """'}), "(csv_file, delimiter=' ')\n", (172, 197), False, 'import csv\n')] |
import os
import os.path as op
import numpy as np
from numpy.testing import assert_almost_equal
from ..core import ShootingPoint, find_and_replace
def test_read_cv_values():
test_file_loc = op.join(op.dirname(op.abspath(__file__)),
'test_data', 'COLVAR2')
sp = ShootingPoint(name=... | [
"numpy.testing.assert_almost_equal",
"numpy.array",
"os.path.abspath",
"os.remove"
] | [((432, 457), 'numpy.array', 'np.array', (['[1.0, 2.0, 3.0]'], {}), '([1.0, 2.0, 3.0])\n', (440, 457), True, 'import numpy as np\n'), ((1616, 1637), 'os.remove', 'os.remove', (['"""test.log"""'], {}), "('test.log')\n", (1625, 1637), False, 'import os\n'), ((534, 565), 'numpy.testing.assert_almost_equal', 'assert_almost... |
import requests
import matplotlib.pyplot as plt
URL = "https://api.github.com/orgs/alibaba/repos"
repos_json = requests.get(URL).json()
star_data_repos = {}
for repo in repos_json:
star_data_repos[repo['name']] = repo['stargazers_count']
print(star_data_repos)
fig = plt.figure()
plt.bar(star_data_repos.keys()... | [
"matplotlib.pyplot.figure",
"requests.get",
"matplotlib.pyplot.show"
] | [((277, 289), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (287, 289), True, 'import matplotlib.pyplot as plt\n'), ((348, 358), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (356, 358), True, 'import matplotlib.pyplot as plt\n'), ((111, 128), 'requests.get', 'requests.get', (['URL'], {}), '(URL... |
import os
def print_fonts():
"""
Prints all available font names
"""
fonts = load_fonts()
print_num = 0
# for every 5 colours printed, the next colour will go to a new line.
print('\nAvailable fonts:')
for font in fonts:
font = font.split('/')[2][:-4]
p... | [
"os.walk"
] | [((672, 691), 'os.walk', 'os.walk', (['"""../fonts"""'], {}), "('../fonts')\n", (679, 691), False, 'import os\n')] |
import sys
import haystack
import contentmanager
# A bit of a hack but it seems to work for my use-cases
if len(sys.argv)>1 \
and sys.argv[1] in ('clear_index', 'rebuild_index', 'update_index'):
contentmanager.autodiscover()
haystack.autodiscover()
| [
"haystack.autodiscover",
"contentmanager.autodiscover"
] | [((241, 264), 'haystack.autodiscover', 'haystack.autodiscover', ([], {}), '()\n', (262, 264), False, 'import haystack\n'), ((210, 239), 'contentmanager.autodiscover', 'contentmanager.autodiscover', ([], {}), '()\n', (237, 239), False, 'import contentmanager\n')] |
import random
from aco import SolveTSPUsingACO
## Gerando cidades aleatórias
cities_size = 15
nodes = [(random.uniform(-400, 400), random.uniform(-400, 400)) for i in range(cities_size)]
## Definindo parametros do ACO
colony_size = 10 # Número de formigas
steps = 100 # Número de interações
alpha = 1.0 # Se α = 0, ... | [
"random.uniform",
"aco.SolveTSPUsingACO"
] | [((597, 704), 'aco.SolveTSPUsingACO', 'SolveTSPUsingACO', ([], {'mode': 'mode', 'colony_size': 'colony_size', 'steps': 'steps', 'alpha': 'alpha', 'beta': 'beta', 'nodes': 'nodes'}), '(mode=mode, colony_size=colony_size, steps=steps, alpha=\n alpha, beta=beta, nodes=nodes)\n', (613, 704), False, 'from aco import Solv... |
import math
import os
import pandas as pd
import numpy as np
import matplotlib as plt
def csv_to_df(csv_path, dtypes, skiprows):
df = pd.read_csv(csv_path, dtype=dtypes, skiprows=skiprows)
return df
def onehot_encode(df, dtypes):
categoricals = [column for (column, dtype) in dtypes.items() if dtype == "... | [
"pandas.get_dummies",
"os.path.splitext",
"pandas.read_csv",
"math.floor"
] | [((140, 194), 'pandas.read_csv', 'pd.read_csv', (['csv_path'], {'dtype': 'dtypes', 'skiprows': 'skiprows'}), '(csv_path, dtype=dtypes, skiprows=skiprows)\n', (151, 194), True, 'import pandas as pd\n'), ((376, 417), 'pandas.get_dummies', 'pd.get_dummies', ([], {'data': 'df', 'columns': '[column]'}), '(data=df, columns=[... |
import sys
import versioneer
import setuptools
if sys.version_info < (3,6):
print("Soundlab requires Python 3.6 or higher please upgrade")
sys.exit(1)
long_description = \
"""
Soundlab is a python package to analyze and visualize sound data. Created
with scientific use in mind. It is in its early stages of ... | [
"versioneer.get_cmdclass",
"versioneer.get_version",
"sys.exit"
] | [((148, 159), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (156, 159), False, 'import sys\n'), ((405, 429), 'versioneer.get_version', 'versioneer.get_version', ([], {}), '()\n', (427, 429), False, 'import versioneer\n'), ((444, 469), 'versioneer.get_cmdclass', 'versioneer.get_cmdclass', ([], {}), '()\n', (467, 469),... |
from unittest.mock import patch
import slack
from harvey.messages import Message
@patch('harvey.messages.SLACK_CHANNEL', 'mock-channel')
@patch('harvey.messages.SLACK_BOT_TOKEN', '<PASSWORD>')
@patch('logging.Logger.debug')
@patch('slack.WebClient.chat_postMessage')
def test_send_slack_message_success(mock_slack, m... | [
"slack.errors.SlackApiError",
"unittest.mock.patch",
"harvey.messages.Message.send_slack_message"
] | [((86, 140), 'unittest.mock.patch', 'patch', (['"""harvey.messages.SLACK_CHANNEL"""', '"""mock-channel"""'], {}), "('harvey.messages.SLACK_CHANNEL', 'mock-channel')\n", (91, 140), False, 'from unittest.mock import patch\n'), ((142, 196), 'unittest.mock.patch', 'patch', (['"""harvey.messages.SLACK_BOT_TOKEN"""', '"""<PA... |
class Vertex:
def __init__(self, left = 0, right = 0):
self.sum = 0
self.left = left
self.right = right
self.left_child = None
self.right_child = None
def extend(self):
if (not self.left_child) and self.left < self.right:
mid = (self.left + self.r... | [
"random.randint"
] | [((1398, 1419), 'random.randint', 'random.randint', (['(0)', '(17)'], {}), '(0, 17)\n', (1412, 1419), False, 'import random\n'), ((1459, 1481), 'random.randint', 'random.randint', (['(0)', '(100)'], {}), '(0, 100)\n', (1473, 1481), False, 'import random\n'), ((1553, 1576), 'random.randint', 'random.randint', (['tmp', '... |
from tqdm import tqdm
import pandas as pd
import numpy as np
from pathlib import Path
from hashlib import md5
from sklearn.feature_extraction.text import TfidfVectorizer
from scipy import sparse as sp
import argparse
def break_text(raw):
return np.array([ i for i, t in enumerate(raw) if t == '¶' ][::2])
def ma... | [
"pandas.Series",
"argparse.ArgumentParser",
"pathlib.Path",
"numpy.array",
"sklearn.feature_extraction.text.TfidfVectorizer"
] | [((616, 634), 'pathlib.Path', 'Path', (['args.dataset'], {}), '(args.dataset)\n', (620, 634), False, 'from pathlib import Path\n'), ((2296, 2321), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2319, 2321), False, 'import argparse\n'), ((874, 887), 'numpy.array', 'np.array', (['idx'], {}), '(i... |
from django.shortcuts import render, get_object_or_404
from .models import Post
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.views.generic import ListView
from .forms import EmailPostForm, CommentForm
from django.core.mail import send_mail
class PostListView(ListView):
query... | [
"django.shortcuts.render",
"django.shortcuts.get_object_or_404",
"django.core.mail.send_mail",
"django.core.paginator.Paginator"
] | [((524, 560), 'django.core.paginator.Paginator', 'Paginator', (['object_list', '(3)'], {'orphans': '(2)'}), '(object_list, 3, orphans=2)\n', (533, 560), False, 'from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\n'), ((790, 860), 'django.shortcuts.render', 'render', (['request', '"""blog/post/list... |
from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate, logout
from .forms import UserLoginForm
def home_view(request):
context = {'name': 'Dave'}
return render(request, 'home.html',context)
def login_view(request):
form = UserLoginForm(request.POST or None)
... | [
"django.shortcuts.render",
"django.shortcuts.redirect",
"django.contrib.auth.login",
"django.contrib.auth.logout"
] | [((206, 243), 'django.shortcuts.render', 'render', (['request', '"""home.html"""', 'context'], {}), "(request, 'home.html', context)\n", (212, 243), False, 'from django.shortcuts import render, redirect\n'), ((756, 801), 'django.shortcuts.render', 'render', (['request', '"""login.html"""', "{'form': form}"], {}), "(req... |
import secrets
def getToken():
return secrets.token_urlsafe(32) | [
"secrets.token_urlsafe"
] | [((43, 68), 'secrets.token_urlsafe', 'secrets.token_urlsafe', (['(32)'], {}), '(32)\n', (64, 68), False, 'import secrets\n')] |
from rx import Observable, Observer
letters = Observable.from_(["tocho", "tochez", "tochisimo", "tochine"])
class MySubscriber(Observer):
def on_next(self, value):
print(value)
def on_completed(self):
print("done")
def on_error(self, error):
print(error)
letters.subscribe(MySub... | [
"rx.Observable.from_"
] | [((47, 108), 'rx.Observable.from_', 'Observable.from_', (["['tocho', 'tochez', 'tochisimo', 'tochine']"], {}), "(['tocho', 'tochez', 'tochisimo', 'tochine'])\n", (63, 108), False, 'from rx import Observable, Observer\n')] |
import json
import logging
import tempfile
import shapely.geometry as sgeo
import shapely.ops as ops
from pyproj.crs import CRS
from pywps import FORMATS, ComplexOutput, LiteralInput, Process
from ravenpy.utilities.analysis import dem_prop
from ravenpy.utilities.checks import boundary_check, single_file_check
from rav... | [
"logging.getLogger",
"pywps.LiteralInput",
"pywps.ComplexOutput",
"shapely.ops.unary_union",
"ravenpy.utilities.geo.generic_raster_clip",
"ravenpy.utilities.checks.boundary_check",
"json.dumps",
"ravenpy.utilities.geo.generic_raster_warp",
"ravenpy.utilities.io.archive_sniffer",
"json.load",
"py... | [((566, 592), 'logging.getLogger', 'logging.getLogger', (['"""PYWPS"""'], {}), "('PYWPS')\n", (583, 592), False, 'import logging\n'), ((2735, 2771), 'pyproj.crs.CRS.from_user_input', 'CRS.from_user_input', (['destination_crs'], {}), '(destination_crs)\n', (2754, 2771), False, 'from pyproj.crs import CRS\n'), ((3309, 33... |
"""A module for testing Coding DNA DelIns tokenization."""
import unittest
from variation.tokenizers.caches import AminoAcidCache, NucleotideCache
from variation.tokenizers import CodingDNADelIns
from .tokenizer_base import TokenizerBase
class TestCodingDNADelInsTokenizer(TokenizerBase, unittest.TestCase):
"""A ... | [
"variation.tokenizers.caches.NucleotideCache",
"variation.tokenizers.caches.AminoAcidCache"
] | [((488, 504), 'variation.tokenizers.caches.AminoAcidCache', 'AminoAcidCache', ([], {}), '()\n', (502, 504), False, 'from variation.tokenizers.caches import AminoAcidCache, NucleotideCache\n'), ((506, 523), 'variation.tokenizers.caches.NucleotideCache', 'NucleotideCache', ([], {}), '()\n', (521, 523), False, 'from varia... |
# -*- coding: utf-8 -*-
import uuid
import unittest
import logging
from __init__ import LogTrace
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
logger = logging.getLogger(__name__)
logger.setLevel(logging.I... | [
"logging.basicConfig",
"logging.getLogger",
"uuid.uuid4",
"__init__.LogTrace",
"unittest.main"
] | [((98, 221), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'format': '"""%(asctime)s %(levelname)-8s %(message)s"""', 'datefmt': '"""%Y-%m-%d %H:%M:%S"""'}), "(level=logging.INFO, format=\n '%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%M:%S')\n", (117, 221), False, '... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('silver', '0044_auto_20171115_1809'),
]
operations = [
migrations.AlterField(
model_name='customer',
... | [
"django.db.models.CharField"
] | [((351, 406), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(128)', 'null': '(True)', 'blank': '(True)'}), '(max_length=128, null=True, blank=True)\n', (367, 406), False, 'from django.db import migrations, models\n'), ((533, 632), 'django.db.models.CharField', 'models.CharField', ([], {'help_te... |
import os
from plugins import gf
users_dir = os.path.join(r"users/")
def profiles(sourceText, id):
get_data = gf.loadjson(users_dir + str(id) + ".json")
own_housing = int(get_data['own_housing'])
own_car = int(get_data['own_car'])
own_yacht = int(get_data['own_yacht'])
own_air = int(ge... | [
"plugins.gf.check_own_profile",
"plugins.gf.check_nick",
"plugins.gf.check_own_car",
"plugins.gf.check_group",
"os.path.join",
"plugins.gf.check_own_air",
"plugins.gf.check_own_comp",
"plugins.gf.check_own_yacht",
"plugins.gf.check_own_farm",
"plugins.gf.check_own_housing",
"plugins.gf.check_own... | [((49, 71), 'os.path.join', 'os.path.join', (['"""users/"""'], {}), "('users/')\n", (61, 71), False, 'import os\n'), ((1207, 1234), 'plugins.gf.check_own_farm', 'gf.check_own_farm', (['own_farm'], {}), '(own_farm)\n', (1224, 1234), False, 'from plugins import gf\n'), ((1170, 1199), 'plugins.gf.check_own_smart', 'gf.che... |
#!/usr/bin/env python
# encoding: utf-8
####### todo:
# reverse compliment #
### input fasta file
### input gRNA.bed, design file
### output count number for next step.
from signal import signal, SIGPIPE, SIG_DFL
signal(SIGPIPE,SIG_DFL)
from sys import stdin, stderr
import argparse
parser = argparse.ArgumentParser... | [
"signal.signal",
"argparse.ArgumentParser",
"re.compile",
"sys.stdin.readlines",
"collections.Counter",
"sys.stderr.write"
] | [((218, 242), 'signal.signal', 'signal', (['SIGPIPE', 'SIG_DFL'], {}), '(SIGPIPE, SIG_DFL)\n', (224, 242), False, 'from signal import signal, SIGPIPE, SIG_DFL\n'), ((297, 322), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (320, 322), False, 'import argparse\n'), ((2893, 2942), 'sys.stderr.wri... |
from django.urls import include, path
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register("owners", views.OwnerViewSet)
router.register("accounts", views.AccountViewSet)
router.register("payments", views.PaymentViewSet)
urlpatterns = [
path("", include(route... | [
"rest_framework.routers.DefaultRouter",
"django.urls.include"
] | [((106, 129), 'rest_framework.routers.DefaultRouter', 'routers.DefaultRouter', ([], {}), '()\n', (127, 129), False, 'from rest_framework import routers\n'), ((307, 327), 'django.urls.include', 'include', (['router.urls'], {}), '(router.urls)\n', (314, 327), False, 'from django.urls import include, path\n')] |
"""Test the graphical display of a CodeBlock."""
import time
from concurrent.futures import ThreadPoolExecutor
import cocos
from shimmer.programmable.code_block import (
CodeBlockDisplay,
CodeBlock,
CodeBlockDisplayDefinition,
)
from shimmer.programmable.logic.definition import Instruction
def test_code... | [
"shimmer.programmable.code_block.CodeBlockDisplayDefinition",
"shimmer.programmable.logic.definition.Instruction",
"concurrent.futures.ThreadPoolExecutor",
"time.sleep"
] | [((448, 476), 'shimmer.programmable.code_block.CodeBlockDisplayDefinition', 'CodeBlockDisplayDefinition', ([], {}), '()\n', (474, 476), False, 'from shimmer.programmable.code_block import CodeBlockDisplay, CodeBlock, CodeBlockDisplayDefinition\n'), ((752, 767), 'time.sleep', 'time.sleep', (['(0.5)'], {}), '(0.5)\n', (7... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File: software/utils/loop.py
# By: <NAME>
# For: Myself
# Description: This file implements the main loop for object detection with OpenCV.
IS_ARDUCAM = False
if IS_ARDUCAM:
from utils_arducam import ArducamUtils
from utils.inference impor... | [
"utils.inference.ObjectCenter",
"cv2.imwrite",
"copy.deepcopy",
"cv2.imshow",
"cv2.waitKey",
"cv2.destroyAllWindows",
"cv2.VideoCapture",
"cv2.VideoWriter_fourcc",
"utils_arducam.ArducamUtils",
"utils.display.set_display",
"utils.display.show_fps",
"time.time",
"utils.display.open_window",
... | [((2502, 2520), 'utils.inference.ObjectCenter', 'ObjectCenter', (['args'], {}), '(args)\n', (2514, 2520), False, 'from utils.inference import ObjectCenter\n'), ((4262, 4273), 'time.time', 'time.time', ([], {}), '()\n', (4271, 4273), False, 'import cv2, time\n'), ((2591, 2613), 'cv2.imread', 'cv2.imread', (['args.image'... |
from hashlib import blake2s
def hash(x):
return blake2s(x).digest()[:32]
def get_primes(givenNumber):
# Initialize a list
primes = []
for possiblePrime in range(2, givenNumber + 1):
# Assume number is prime until shown it is not.
isPrime = True
for num in range(2, int(possibleP... | [
"hashlib.blake2s"
] | [((53, 63), 'hashlib.blake2s', 'blake2s', (['x'], {}), '(x)\n', (60, 63), False, 'from hashlib import blake2s\n')] |
#
# Author: <NAME>
# created Date: 14-11-2019
from time import sleep
from sys import exit
from cunsumer.consumerhandler import ConsumerHandler
from message_handler.messagehandler import MessageHandler
from publisher.publisher import Publisher
PAUSE = 5
class KafkaPuller:
def __init__(self, settings, client_id, ... | [
"cunsumer.consumerhandler.ConsumerHandler",
"publisher.publisher.Publisher",
"time.sleep",
"message_handler.messagehandler.MessageHandler",
"sys.exit"
] | [((440, 504), 'cunsumer.consumerhandler.ConsumerHandler', 'ConsumerHandler', (['self._settings', 'client_id', 'timeout', 'auto_commit'], {}), '(self._settings, client_id, timeout, auto_commit)\n', (455, 504), False, 'from cunsumer.consumerhandler import ConsumerHandler\n'), ((538, 582), 'message_handler.messagehandler.... |
import magma as m
import magma.testing
def test_2d_array_from_verilog():
main = m.define_from_verilog(f"""
module transpose_buffer (
input logic clk,
output logic [2:0] index_inner,
output logic [2:0] index_outer,
input logic [3:0] input_data [63:0],
input logic [2:0] range_inner,
input logic [2:0] ra... | [
"magma.compile",
"magma.define_from_verilog",
"magma.testing.check_files_equal"
] | [((833, 897), 'magma.compile', 'm.compile', (['"""build/2d_array_from_verilog"""', 'main'], {'output': '"""verilog"""'}), "('build/2d_array_from_verilog', main, output='verilog')\n", (842, 897), True, 'import magma as m\n'), ((909, 1017), 'magma.testing.check_files_equal', 'm.testing.check_files_equal', (['__file__', '... |
import os
from .notebook import KindleNotebook
from .parser import MyHTMLParser
from .md_renderer import render_md_from_notebook
def convert_kindle_html_to_md(html_file):
if not os.path.exists(html_file):
raise ValueError("no such file: " + html_file)
note = KindleNotebook()
parser = MyHTMLParse... | [
"os.path.exists"
] | [((185, 210), 'os.path.exists', 'os.path.exists', (['html_file'], {}), '(html_file)\n', (199, 210), False, 'import os\n')] |
import torch
import os
from glob import glob
import numpy as np
from torch.nn import functional as F
import time
class Generator(object):
def __init__(self, model, exp_name, threshold = 0.1, checkpoint = None, device = torch.device("cuda")):
self.model = model.to(device)
self.model.eval()
s... | [
"torch.rand",
"torch.load",
"numpy.sort",
"torch.nn.functional.normalize",
"os.path.dirname",
"numpy.zeros",
"torch.randint",
"numpy.array",
"os.path.basename",
"time.time",
"torch.randn",
"glob.glob",
"torch.device"
] | [((224, 244), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (236, 244), False, 'import torch\n'), ((645, 656), 'time.time', 'time.time', ([], {}), '()\n', (654, 656), False, 'import time\n'), ((844, 860), 'numpy.zeros', 'np.zeros', (['(0, 3)'], {}), '((0, 3))\n', (852, 860), True, 'import numpy as... |
from algo import Algorithm
from lagom.experiment import Config
from lagom.experiment import BaseExperimentWorker
from lagom.experiment import BaseExperimentMaster
class ExperimentWorker(BaseExperimentWorker):
def make_algo(self):
algo = Algorithm(name='VAE on MNIST')
return algo
cla... | [
"lagom.experiment.Config",
"algo.Algorithm"
] | [((252, 282), 'algo.Algorithm', 'Algorithm', ([], {'name': '"""VAE on MNIST"""'}), "(name='VAE on MNIST')\n", (261, 282), False, 'from algo import Algorithm\n'), ((498, 506), 'lagom.experiment.Config', 'Config', ([], {}), '()\n', (504, 506), False, 'from lagom.experiment import Config\n')] |
"""
Created on 2012-12-22
@author: Administrator
"""
from socket import socket
from time import ctime
HOST = ''
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST, PORT)
sock = socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(ADDR)
sock.listen(5)
while True:
print('Waiting ...')
sock_c, addr = sock.accept()
... | [
"time.ctime",
"socket.socket"
] | [((171, 213), 'socket.socket', 'socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (177, 213), False, 'from socket import socket\n'), ((471, 478), 'time.ctime', 'ctime', ([], {}), '()\n', (476, 478), False, 'from time import ctime\n')] |
import numpy as np
def process_actions(actions, l_action):
n_steps = len(actions)
actions_1hot = np.zeros([n_steps, l_action], dtype=int)
actions_1hot[np.arange(n_steps), actions] = 1
return actions_1hot
def get_action_others_1hot(action_all, agent_id, l_action):
action_all = list(a... | [
"numpy.reshape",
"numpy.ones",
"numpy.delete",
"numpy.indices",
"numpy.stack",
"numpy.zeros",
"numpy.cumsum",
"numpy.arange"
] | [((112, 152), 'numpy.zeros', 'np.zeros', (['[n_steps, l_action]'], {'dtype': 'int'}), '([n_steps, l_action], dtype=int)\n', (120, 152), True, 'import numpy as np\n'), ((415, 458), 'numpy.zeros', 'np.zeros', (['[num_others, l_action]'], {'dtype': 'int'}), '([num_others, l_action], dtype=int)\n', (423, 458), True, 'impor... |
import json, requests
from events import TickEvent
from enviro import STREAM_DOMAIN, GrabToken, GrabID
class GrabPrice(object):
def __init__(self, domain, token, ID_num, instru, event_queue):
self.domain = domain
self.token = token
self.ID_num = ID_num
self.instru = instru
... | [
"json.loads",
"requests.Session"
] | [((410, 428), 'requests.Session', 'requests.Session', ([], {}), '()\n', (426, 428), False, 'import json, requests\n'), ((1287, 1311), 'json.loads', 'json.loads', (['decoded_line'], {}), '(decoded_line)\n', (1297, 1311), False, 'import json, requests\n')] |
#!/usr/bin/env python3
import argparse
import configparser
import getpass
import logging
import os
import requests
import requests_toolbelt
import sys
import urllib3
from scapy.all import *
import ipaddress
import json
from scapy.layers.http import HTTPRequest # import HTTP packet
from scapy.layers.http import HTTP
CU... | [
"logging.basicConfig",
"os.path.exists",
"logging.getLogger",
"ipaddress.ip_address",
"configparser.ConfigParser",
"argparse.ArgumentParser",
"os.getenv",
"os.path.join",
"os.getcwd",
"urllib3.disable_warnings",
"os.mkdir",
"os.path.abspath",
"sys.path.append"
] | [((402, 440), 'os.path.join', 'os.path.join', (['CURRENT_DIRECTORY', '"""src"""'], {}), "(CURRENT_DIRECTORY, 'src')\n", (414, 440), False, 'import os\n'), ((443, 476), 'sys.path.append', 'sys.path.append', (['SOURCE_DIRECTORY'], {}), '(SOURCE_DIRECTORY)\n', (458, 476), False, 'import sys\n'), ((610, 677), 'urllib3.disa... |
"""
Copyright (c) 2020 Cisco and/or its affiliates.
This software is licensed to you under the terms of the Cisco Sample
Code License, Version 1.1 (the "License"). You may obtain a copy of the
License at
https://developer.cisco.com/docs/licenses
All use of the material herein must be in accordance wit... | [
"flask.render_template",
"src.db.get_db",
"flask.flash",
"pandas.read_csv",
"flask.request.form.getlist",
"flask.request.form.get",
"flask.url_for",
"urllib3.disable_warnings",
"flask.Blueprint"
] | [((945, 971), 'urllib3.disable_warnings', 'urllib3.disable_warnings', ([], {}), '()\n', (969, 971), False, 'import urllib3\n'), ((977, 1006), 'flask.Blueprint', 'Blueprint', (['"""portal"""', '__name__'], {}), "('portal', __name__)\n", (986, 1006), False, 'from flask import Blueprint, flash, g, redirect, render_templat... |
# import the necessary packages
from imutils.video import VideoStream
from imutils import face_utils
import argparse
import imutils
import time
import dlib
import cv2
import tensorflow as tf
from tensorflow.keras.models import load_model
import numpy as np
from matplotlib import pyplot as plt
import os
... | [
"argparse.ArgumentParser",
"dlib.shape_predictor",
"time.perf_counter",
"time.sleep",
"cv2.putText",
"dlib.get_frontal_face_detector",
"imutils.resize",
"cv2.imshow",
"tensorflow.keras.models.load_model",
"cv2.destroyAllWindows",
"cv2.VideoCapture",
"imutils.face_utils.shape_to_np",
"numpy.a... | [((421, 446), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (444, 446), False, 'import argparse\n'), ((863, 895), 'dlib.get_frontal_face_detector', 'dlib.get_frontal_face_detector', ([], {}), '()\n', (893, 895), False, 'import dlib\n'), ((909, 954), 'dlib.shape_predictor', 'dlib.shape_predicto... |
"""Tests related to template reading."""
from configparser import ConfigParser
import pytest
import flatware.template_reading as reading
def test_template_splits():
"""Test that templates split in the required method."""
template = """[name]
type=str
default=<NAME>
---
Hello {{ name }}!"""
config, templ... | [
"configparser.ConfigParser",
"flatware.template_reading.parse_template_config",
"flatware.template_reading.build_template_argparser",
"pytest.raises",
"flatware.template_reading.make_argparse_from_template",
"flatware.template_reading.get_template_arguments"
] | [((326, 365), 'flatware.template_reading.parse_template_config', 'reading.parse_template_config', (['template'], {}), '(template)\n', (355, 365), True, 'import flatware.template_reading as reading\n'), ((676, 715), 'flatware.template_reading.parse_template_config', 'reading.parse_template_config', (['template'], {}), '... |
import pandas as pd
import os, sys
from pandas.tseries.holiday import USFederalHolidayCalendar
from pandas.tseries.offsets import CustomBusinessDay
from sklearn.utils import check_array
import numpy as np
from datetime import timedelta
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))+'/'
def mean_absolute_pe... | [
"numpy.fabs",
"pandas.tseries.holiday.USFederalHolidayCalendar",
"pandas.DatetimeIndex",
"pandas.to_datetime",
"os.path.join",
"os.path.dirname",
"datetime.timedelta",
"pandas.date_range"
] | [((800, 850), 'pandas.DatetimeIndex', 'pd.DatetimeIndex', ([], {'start': 'start', 'end': 'end', 'freq': 'us_bd'}), '(start=start, end=end, freq=us_bd)\n', (816, 850), True, 'import pandas as pd\n'), ((1011, 1075), 'pandas.date_range', 'pd.date_range', ([], {'start': 'date', 'periods': '(2)', 'freq': '"""1d"""', 'tz': '... |
"""
UKPDS
See:
"""
import numpy as np
from cvdm.score import BaseRisk
from cvdm.score import clean_age, clean_hba1c, clean_bp, clean_tchdl
# coefficients for survival
BETA = np.array([ 1.059, # age at diagnosis of diabetes
0.525, # risk for females
0.390, # Afro-Carribean ethnic... | [
"numpy.power",
"cvdm.score.clean_age",
"numpy.log",
"numpy.exp",
"numpy.array",
"cvdm.score.clean_hba1c",
"cvdm.score.clean_tchdl",
"cvdm.score.clean_bp"
] | [((179, 236), 'numpy.array', 'np.array', (['[1.059, 0.525, 0.39, 1.35, 1.183, 1.088, 3.845]'], {}), '([1.059, 0.525, 0.39, 1.35, 1.183, 1.088, 3.845])\n', (187, 236), True, 'import numpy as np\n'), ((1134, 1196), 'numpy.exp', 'np.exp', (['(-q * D ** (age - ageDiab) * (1 - D ** tYear) / (1 - D))'], {}), '(-q * D ** (age... |
import numpy as np
import pandas as pd
from shapely.geometry import Point
import folium
import geopandas as gpd
from shapely.wkt import loads
from math import isnan
import gspread
from oauth2client.service_account import ServiceAccountCredentials
wgs84 = {'init': 'epsg:4326'}
scope = ['https://spreadsheets.google.com... | [
"gspread.authorize",
"folium.GeoJson",
"folium.Icon",
"shapely.wkt.loads",
"folium.Map",
"shapely.geometry.Point",
"oauth2client.service_account.ServiceAccountCredentials.from_json_keyfile_name",
"folium.Popup",
"pandas.DataFrame",
"geopandas.GeoDataFrame"
] | [((393, 464), 'oauth2client.service_account.ServiceAccountCredentials.from_json_keyfile_name', 'ServiceAccountCredentials.from_json_keyfile_name', (['"""gsheets.json"""', 'scope'], {}), "('gsheets.json', scope)\n", (441, 464), False, 'from oauth2client.service_account import ServiceAccountCredentials\n'), ((470, 500), ... |
"""
Simple socket helper to handle large data frames and
ensure complete data frames are received.
"""
import struct
def send_msg(sock, msg):
"""
sock: socket
msg: byte string
send data packet with length prefix
"""
# Prefix each message with a 4-byte length (network byte order)
msg = str... | [
"struct.unpack"
] | [((769, 800), 'struct.unpack', 'struct.unpack', (['""">I"""', 'raw_msglen'], {}), "('>I', raw_msglen)\n", (782, 800), False, 'import struct\n')] |
#!/usr/bin/env python
import webapp2
from google.appengine.api import app_identity
from google.appengine.api import mail
from conference import ConferenceApi
from google.appengine.api import app_identity
from google.appengine.api import mail
from google.appengine.api import memcache
from google.appengine.ext import ndb... | [
"models.Session.query",
"google.appengine.api.memcache.set",
"webapp2.WSGIApplication",
"conference.ConferenceApi._cacheAnnouncement",
"google.appengine.api.app_identity.get_application_id"
] | [((1858, 2077), 'webapp2.WSGIApplication', 'webapp2.WSGIApplication', (["[('/crons/set_announcement', SetAnnouncementHandler), (\n '/tasks/send_confirmation_email', SendConfirmationEmailHandler), (\n '/tasks/set_featured_speaker', SetFeaturedSpeaker)]"], {'debug': '(True)'}), "([('/crons/set_announcement', SetAnn... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
# 根目录配置
# 要求将浏览的文件目录挂载到statics/mountfile目录,没有对任意位置的目录做兼容性测试,因为我准备使用docker容器运行程序,正好是挂载方式。
# 使用normpath对windows和linux的路径分隔符做兼容
baseroot = os.path.normpath(os.path.join(os.path.dirname(__file__), 'statics/mountfile'))
def root():
return baseroot
# 数据库配置
dbconf... | [
"os.path.dirname"
] | [((223, 248), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (238, 248), False, 'import os\n')] |
"""
Module contenant les classes utiles à la modélisation sous forme de graphe :
Sommet, Arc, Graphe
auteur : cmarichal
"""
from typing import Tuple, List
from math import floor
import numpy as np
from classes_traitement_plan import CouleurSpeciale, Plan
class Sommet:
"""Sommet ayant une position et un numéro""... | [
"numpy.array",
"numpy.sqrt"
] | [((895, 907), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (903, 907), True, 'import numpy as np\n'), ((2004, 2016), 'numpy.array', 'np.array', (['Gr'], {}), '(Gr)\n', (2012, 2016), True, 'import numpy as np\n'), ((1730, 1754), 'numpy.sqrt', 'np.sqrt', (['(x ** 2 + y ** 2)'], {}), '(x ** 2 + y ** 2)\n', (1737, 17... |
import os
import sys
import json
import datetime
import numpy as np
import skimage.draw
from mrcnn.visualize import display_images
import mrcnn.model as modellib
from mrcnn.model import log
from config.fashion_config import FashionConfig
from config.dataset import FashionDataset
# Path to trained weights file
COCO_W... | [
"mrcnn.model.MaskRCNN",
"argparse.ArgumentParser",
"config.fashion_config.FashionConfig",
"os.path.join",
"config.dataset.FashionDataset"
] | [((334, 378), 'os.path.join', 'os.path.join', (['""""""', '"""weight/mask_rcnn_coco.h5"""'], {}), "('', 'weight/mask_rcnn_coco.h5')\n", (346, 378), False, 'import os\n'), ((422, 450), 'os.path.join', 'os.path.join', (['""""""', '"""datasets"""'], {}), "('', 'datasets')\n", (434, 450), False, 'import os\n'), ((514, 538)... |
# Simple hangman game using Python --- <NAME>
# Import getpass function from getpass module
from getpass import getpass
# Function that returns the current hangman board
def hangmanStages(attempts):
display = ['''
-------
| |
| O
| /|\\
| / \\
|
----- ''','''
-------
| |
| ... | [
"getpass.getpass"
] | [((3441, 3478), 'getpass.getpass', 'getpass', (['"""Your word will be hidden: """'], {}), "('Your word will be hidden: ')\n", (3448, 3478), False, 'from getpass import getpass\n'), ((3966, 4003), 'getpass.getpass', 'getpass', (['"""Your word will be hidden: """'], {}), "('Your word will be hidden: ')\n", (3973, 4003), ... |
import bourgeon
import ragnarok_client as client
from bourgeon import ui
from ragnarok_client import Mode
class BasicInfoWindow:
def __init__(self, name: str) -> None:
self._hp_text = ui.Text("--")
self._sp_text = ui.Text("--")
self.window = ui.Window(name, [[
ui.Text("HP"),
... | [
"ragnarok_client.get_max_hp",
"ragnarok_client.get_max_sp",
"bourgeon.register_callback",
"ragnarok_client.get_hp",
"bourgeon.ui.unregister_window",
"ragnarok_client.get_sp",
"bourgeon.ui.register_window",
"ragnarok_client.get_char_name",
"bourgeon.ui.Text"
] | [((1379, 1424), 'bourgeon.register_callback', 'bourgeon.register_callback', (['"""OnTick"""', 'on_tick'], {}), "('OnTick', on_tick)\n", (1405, 1424), False, 'import bourgeon\n'), ((1425, 1483), 'bourgeon.register_callback', 'bourgeon.register_callback', (['"""OnModeSwitch"""', 'on_mode_switch'], {}), "('OnModeSwitch', ... |
from dnn_schedules.per_layer.hwcf_schedule import HWCFSchedule
# from dnn_schedules.cfhw.cfhw_eyeriss import run_tangram
from attrdict import AttrDict
class FCHWScheduleCFHWTangram2(HWCFSchedule):
def __init__(self, net, model_name, result_dir, verbose, hardware_yaml=None, hardware_dict=None):
super().__... | [
"attrdict.AttrDict"
] | [((7312, 7522), 'attrdict.AttrDict', 'AttrDict', (["{'hin': 0, 'win': 0, 'cin': cin_start_2, 'hout': 0, 'wout': 0, 'cout': 0,\n 'end_hin': second_layer.Hin, 'end_win': second_layer.Win, 'end_cin': \n cin_end_2_idx + 1, 'end_cout': second_layer.Cout}"], {}), "({'hin': 0, 'win': 0, 'cin': cin_start_2, 'hout': 0, 'w... |
# ---------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ---------------------------------------------------------
"""Contains functionality used to submit experiments and manage experiment history in Azure Machine Learning."""
import logging
imp... | [
"logging.getLogger",
"azureml.exceptions.UserErrorException",
"collections.OrderedDict",
"os.getenv",
"azureml.core._experiment_method.check_for_lock_file",
"azureml._logging.ChainedIdentity.DELIM.join",
"azureml._html.utilities.to_html",
"functools.wraps",
"azureml._base_sdk_common.common.check_val... | [((987, 1014), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1004, 1014), False, 'import logging\n'), ((1062, 1073), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (1067, 1073), False, 'from functools import wraps\n'), ((4917, 4959), 'azureml._restclient.workspace_client.Worksp... |
# Copyright 2018 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softwa... | [
"logging.getLogger",
"itertools.chain",
"qtoml.load",
"pathlib.Path",
"pathlib.Path.cwd",
"os.environ.get",
"pendulum.parse",
"getpass.getuser",
"qtoml.dump"
] | [((707, 734), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (724, 734), False, 'import logging\n'), ((1138, 1175), 'os.environ.get', 'os.environ.get', (['CONFIG_STORE_ENV_NAME'], {}), '(CONFIG_STORE_ENV_NAME)\n', (1152, 1175), False, 'import os\n'), ((3747, 3764), 'getpass.getuser', 'get... |
#! /usr/bin/env python3
#
# power_wrangler.py -- Copyright (C) 2016-2017 <NAME>
#
import os, sys, platform, daemon, time, minimalmodbus
from datetime import datetime
if len(sys.argv) != 2:
print()
print('USAGE: %s [serial-device - e.g.: /dev/ttyACM0]' % (sys.argv[0]))
print()
exit(1)
dev = sys.arg... | [
"datetime.datetime.fromtimestamp",
"minimalmodbus.Instrument",
"time.sleep",
"time.time",
"daemon.DaemonContext"
] | [((415, 437), 'daemon.DaemonContext', 'daemon.DaemonContext', ([], {}), '()\n', (435, 437), False, 'import os, sys, platform, daemon, time, minimalmodbus\n'), ((631, 642), 'time.time', 'time.time', ([], {}), '()\n', (640, 642), False, 'import os, sys, platform, daemon, time, minimalmodbus\n'), ((771, 797), 'datetime.da... |
"""Support routines for the qdyn_prop_gate utility"""
import re
import numpy as np
from .units import UnitFloat
def _isqrt(n):
"""Integer square root of n > 0
>>> _isqrt(1024**2)
1024
>>> _isqrt(10)
3
"""
assert n >= 0
x = n
y = (x + 1) // 2
while y < x:
x = y
... | [
"numpy.reshape",
"re.search"
] | [((1834, 1874), 'numpy.reshape', 'np.reshape', (['vals[1::2]', 'shape'], {'order': '"""F"""'}), "(vals[1::2], shape, order='F')\n", (1844, 1874), True, 'import numpy as np\n'), ((1920, 1960), 'numpy.reshape', 'np.reshape', (['vals[2::2]', 'shape'], {'order': '"""F"""'}), "(vals[2::2], shape, order='F')\n", (1930, 1960)... |
import os
import types
class Config:
"""
Dictionary-like class for holding configuration values.
Normalizes all keys to lowercase, and allows you to use `config.foo` just
like you would `config['foo']`.
"""
def __init__(self, data=None):
super().__setattr__("_data", {}) # avoid recu... | [
"os.environ.items",
"json.load",
"types.ModuleType",
"toml.load"
] | [((876, 894), 'os.environ.items', 'os.environ.items', ([], {}), '()\n', (892, 894), False, 'import os\n'), ((1169, 1181), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1178, 1181), False, 'import json\n'), ((1424, 1439), 'toml.load', 'toml.load', (['path'], {}), '(path)\n', (1433, 1439), False, 'import toml\n'), ((1... |
# -*- coding: utf-8 -*-
# @Time : 2017/7/27 13:47
# @Author : play4fun
# @File : HoughCircles_camera.py
# @Software: PyCharm
"""
HoughCircles_camera.py:
用围棋-棋子来测试
"""
import cv2
import numpy as np
from skimage.measure import compare_mse as mse
import string, random
def id_generator(size=6, chars=string.asci... | [
"cv2.rectangle",
"random.choice",
"cv2.line",
"cv2.HoughCircles",
"cv2.imshow",
"cv2.circle",
"cv2.destroyAllWindows",
"cv2.VideoCapture",
"cv2.cvtColor",
"cv2.waitKey"
] | [((420, 439), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (436, 439), False, 'import cv2\n'), ((2804, 2827), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (2825, 2827), False, 'import cv2\n'), ((647, 703), 'cv2.line', 'cv2.line', (['frame', '(half, 0)', '(half, rows)', '(0, 0, ... |
"""This script is used for doing off-line meta testing."""
from metaworld.benchmarks import ML45WithPinnedGoal
from metarl.experiment.meta_test_helper import MetaTestHelper
if __name__ == "__main__":
MetaTestHelper.read_cmd(ML45WithPinnedGoal.get_test_tasks)
| [
"metarl.experiment.meta_test_helper.MetaTestHelper.read_cmd"
] | [((206, 264), 'metarl.experiment.meta_test_helper.MetaTestHelper.read_cmd', 'MetaTestHelper.read_cmd', (['ML45WithPinnedGoal.get_test_tasks'], {}), '(ML45WithPinnedGoal.get_test_tasks)\n', (229, 264), False, 'from metarl.experiment.meta_test_helper import MetaTestHelper\n')] |
import os
from typing import List, Dict
from collections import namedtuple, deque
Vec = namedtuple('Vec', 'x, y')
class Cart:
"""
Represents a single cart using a position vector and a direction vector
"""
def __init__(self, pos: Vec, dir_: Vec) -> None:
self.pos = pos
self.dir = di... | [
"os.path.join",
"collections.namedtuple",
"collections.deque"
] | [((91, 116), 'collections.namedtuple', 'namedtuple', (['"""Vec"""', '"""x, y"""'], {}), "('Vec', 'x, y')\n", (101, 116), False, 'from collections import namedtuple, deque\n'), ((676, 712), 'collections.deque', 'deque', (["('left', 'straight', 'right')"], {}), "(('left', 'straight', 'right'))\n", (681, 712), False, 'fro... |
import tcp
import random
class ServerData(object):
def __init__(self):
self._data = ""
def receive(self, data):
print("input data = {}".format(data))
self._data = data
def send(self):
data = self._data + "{}".format(random.randint(0, 10))
print("make data = {}".fo... | [
"tcp.TcpServer",
"random.randint",
"time.sleep"
] | [((390, 482), 'tcp.TcpServer', 'tcp.TcpServer', (['"""localhost"""', '(999)', 'server_data.receive', 'server_data.send'], {'send_first': '(False)'}), "('localhost', 999, server_data.receive, server_data.send,\n send_first=False)\n", (403, 482), False, 'import tcp\n'), ((623, 638), 'time.sleep', 'time.sleep', (['(100... |
# -*- coding: utf-8 -*-
from __future__ import print_function, division
import autograd.numpy as np
from lifelines.fitters import KnownModelParametericUnivariateFitter
class WeibullFitter(KnownModelParametericUnivariateFitter):
r"""
This class implements a Weibull model for univariate data. The model has p... | [
"autograd.numpy.log"
] | [((1637, 1646), 'autograd.numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (1643, 1646), True, 'import autograd.numpy as np\n')] |
# import the necessary packages
from tensorflow.keras.applications import imagenet_utils
import imutils
def sliding_window(image, step, ws):
# slide a window across the image
for y in range(0, image.shape[0] - ws[1], step):
for x in range(0, image.shape[1] - ws[0], step):
# yield the current window
yield (x,... | [
"tensorflow.keras.applications.imagenet_utils.decode_predictions",
"imutils.resize"
] | [((1088, 1137), 'tensorflow.keras.applications.imagenet_utils.decode_predictions', 'imagenet_utils.decode_predictions', (['preds'], {'top': 'top'}), '(preds, top=top)\n', (1121, 1137), False, 'from tensorflow.keras.applications import imagenet_utils\n'), ((613, 643), 'imutils.resize', 'imutils.resize', (['image'], {'wi... |
# Generated by Django 3.0.4 on 2020-03-15 20:15
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('books', '0008_auto_20200312_2222'),
]
operations = [
migrations.AlterField(
model_name='book',
name=... | [
"datetime.datetime",
"django.db.models.FileField",
"django.db.models.CharField"
] | [((351, 393), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)', 'null': '(True)'}), '(max_length=50, null=True)\n', (367, 393), False, 'from django.db import migrations, models\n'), ((517, 585), 'django.db.models.FileField', 'models.FileField', ([], {'null': '(True)', 'upload_to': '""""""', ... |
import os
import ssl
import socket
from tempfile import NamedTemporaryFile
try:
from httplib import HTTPSConnection
except ImportError:
from http.client import HTTPSConnection
class ValidatedHTTPSConnection(HTTPSConnection):
CA_ROOT_CERT_FALLBACK = '''
DigiCert Global Root G2
-----BEGIN ... | [
"socket.create_connection",
"os.path.exists",
"os.getenv",
"ssl.wrap_socket",
"tempfile.NamedTemporaryFile"
] | [((1279, 1305), 'os.getenv', 'os.getenv', (['"""SSL_CERT_FILE"""'], {}), "('SSL_CERT_FILE')\n", (1288, 1305), False, 'import os\n'), ((1726, 1814), 'socket.create_connection', 'socket.create_connection', (['(self.host, self.port)', 'self.timeout', 'self.source_address'], {}), '((self.host, self.port), self.timeout, sel... |
import os
import code
from flask_script import Manager
from flask_migrate import MigrateCommand
from whitebearbake import create_app
port = int(os.environ.get('PORT', 5000))
app = create_app()
def run():
app.run(host='0.0.0.0', port=port)
def cli():
""" Interactive CLI session entrypoint """
with app.a... | [
"flask_script.Manager",
"os.environ.get",
"whitebearbake.create_app"
] | [((183, 195), 'whitebearbake.create_app', 'create_app', ([], {}), '()\n', (193, 195), False, 'from whitebearbake import create_app\n'), ((147, 175), 'os.environ.get', 'os.environ.get', (['"""PORT"""', '(5000)'], {}), "('PORT', 5000)\n", (161, 175), False, 'import os\n'), ((447, 459), 'flask_script.Manager', 'Manager', ... |
import logging
import numpy as np
from collections import Counter
from imblearn.base import SamplerMixin
from imblearn.utils import check_target_type, hash_X_y
from sklearn.utils import check_X_y, check_random_state, safe_indexing
__all__ = ['RandomUnderSampler']
def check_ratio(ratio, y):
"""check and returns ... | [
"logging.getLogger",
"sklearn.utils.check_random_state",
"numpy.unique",
"sklearn.utils.check_X_y",
"numpy.hstack",
"numpy.flatnonzero",
"sklearn.utils.safe_indexing",
"collections.Counter",
"imblearn.utils.check_target_type",
"imblearn.utils.hash_X_y"
] | [((365, 375), 'collections.Counter', 'Counter', (['y'], {}), '(y)\n', (372, 375), False, 'from collections import Counter\n'), ((1916, 1943), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1933, 1943), False, 'import logging\n'), ((2390, 2435), 'sklearn.utils.check_X_y', 'check_X_y', (['... |
# Copyright 2021 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, ... | [
"data_utils.generate_training_points",
"data_utils.read_data",
"trainer.validated",
"trainer.OUTPUTS_SPEC.keys",
"os.listdir",
"data_utils.read_labels",
"trainer.deserialize",
"tensorflow.TensorSpec",
"pytest.raises",
"trainer.run",
"tempfile.TemporaryDirectory",
"trainer.INPUTS_SPEC.keys",
... | [((2461, 2501), 'unittest.mock.patch.object', 'mock.patch.object', (['trainer', '"""PADDING"""', '(2)'], {}), "(trainer, 'PADDING', 2)\n", (2478, 2501), False, 'from unittest import mock\n'), ((1674, 1717), 'trainer.validated', 'trainer.validated', (['tensor_dict', 'values_spec'], {}), '(tensor_dict, values_spec)\n', (... |
import copy as _copy
import json as _json
import os
import sys as _sys
import coinstac_computation.utils as _ut
import datetime as _dt
import multiprocessing as _mp
class COINSTACPyNode:
_VALID_MODES_ = [_ut.MODE_LOCAL, _ut.MODE_REMOTE]
def __init__(self, mode: str, debug=False):
self.cache = {}
... | [
"json.dumps",
"coinstac_computation.utils.PhasePipeline",
"datetime.datetime.now",
"copy.deepcopy",
"sys.stdin.read",
"coinstac_computation.utils.check"
] | [((481, 521), 'coinstac_computation.utils.PhasePipeline', '_ut.PhasePipeline', (['self.mode', 'self.cache'], {}), '(self.mode, self.cache)\n', (498, 521), True, 'import coinstac_computation.utils as _ut\n'), ((1909, 1935), 'copy.deepcopy', '_copy.deepcopy', (['self.input'], {}), '(self.input)\n', (1923, 1935), True, 'i... |
'''
<NAME>
simple ray trace - tools and classes to specify and instantiate rays
'''
import numpy as np
from srt_modules.useful_math import euler1232C
class Ray:
def __init__(self, pos=None, dirs=None):
self.X = pos # 3 x N position vectors of rays
self.d = dirs # direction vectors of rays in same... | [
"numpy.array",
"numpy.dot",
"numpy.cos",
"numpy.sin",
"srt_modules.useful_math.euler1232C",
"numpy.shape"
] | [((2083, 2104), 'numpy.dot', 'np.dot', (['DCM', 'ray_dirs'], {}), '(DCM, ray_dirs)\n', (2089, 2104), True, 'import numpy as np\n'), ((2585, 2604), 'numpy.array', 'np.array', (['[x, y, z]'], {}), '([x, y, z])\n', (2593, 2604), True, 'import numpy as np\n'), ((1869, 1883), 'numpy.array', 'np.array', (['rays'], {}), '(ray... |
# -*- coding: utf-8 -*-
"""
This script copies the examples under tests to
the standard example directory and processes
certain setting variables. Under the tests, the
examples do not plot and save data. In examples
directory they do.
"""
import os
from shutil import copyfile
def get_example_file... | [
"shutil.copyfile",
"os.listdir",
"os.path.join"
] | [((1378, 1432), 'os.path.join', 'os.path.join', (['""".."""', '"""quantarhei"""', '"""wizard"""', '"""examples"""'], {}), "('..', 'quantarhei', 'wizard', 'examples')\n", (1390, 1432), False, 'import os\n'), ((1172, 1200), 'os.path.join', 'os.path.join', (['from_loc', 'file'], {}), '(from_loc, file)\n', (1184, 1200), Fa... |
import time
import dgl
import numpy as np
import torch
from se3_transformer_pytorch import SE3Transformer
from se3_transformer_pytorch.irr_repr import rot
from project.lit_egnn import LitEGNN
from project.lit_set import LitSET
# Instantiate different models to be compared
original_se3_transformer = LitSET(num_layers... | [
"dgl.graph",
"project.lit_egnn.LitEGNN",
"se3_transformer_pytorch.SE3Transformer",
"se3_transformer_pytorch.irr_repr.rot",
"project.lit_set.LitSET",
"time.time",
"torch.randn",
"torch.ones"
] | [((303, 393), 'project.lit_set.LitSET', 'LitSET', ([], {'num_layers': '(3)', 'atom_feature_size': '(16)', 'num_channels': '(16)', 'num_degrees': '(2)', 'edge_dim': '(3)'}), '(num_layers=3, atom_feature_size=16, num_channels=16, num_degrees=2,\n edge_dim=3)\n', (309, 393), False, 'from project.lit_set import LitSET\n... |
from pygame import *
from GameSprite import GameSprite
from Player import Player
def game():
back = (200, 255, 255)
win_width = 600
win_height = 500
window = display.set_mode((win_width, win_height))
window.fill(back)
run = True
finish = True
clock = time.Clock()
FP... | [
"Player.Player"
] | [((344, 385), 'Player.Player', 'Player', (['"""racket.png"""', '(30)', '(200)', '(4)', '(50)', '(150)'], {}), "('racket.png', 30, 200, 4, 50, 150)\n", (350, 385), False, 'from Player import Player\n'), ((401, 443), 'Player.Player', 'Player', (['"""racket.png"""', '(520)', '(200)', '(4)', '(50)', '(150)'], {}), "('racke... |
# -*- coding: utf-8 -*-
from jinja2 import Environment, FileSystemLoader
import yaml
env = Environment(loader=FileSystemLoader('.'))
template = env.get_template('index_template.html')
heading_list = ['research', 'engineering', 'illustration']
with open('research_pub.yml') as f:
research_pub_list = yaml.load(f)
w... | [
"jinja2.FileSystemLoader",
"yaml.load"
] | [((306, 318), 'yaml.load', 'yaml.load', (['f'], {}), '(f)\n', (315, 318), False, 'import yaml\n'), ((381, 393), 'yaml.load', 'yaml.load', (['f'], {}), '(f)\n', (390, 393), False, 'import yaml\n'), ((460, 472), 'yaml.load', 'yaml.load', (['f'], {}), '(f)\n', (469, 472), False, 'import yaml\n'), ((533, 545), 'yaml.load',... |
# ------------------------------------------------------------------------
# GroupFromer
# Copyright (c) 2020 SenseTime. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
# ------------------------------------------------------------------------
# Modified from DETR (https:... | [
"torch.nn.Dropout",
"torch.randperm",
"torch.max",
"torch.nn.functional.pad",
"functools.wraps",
"torch.randint",
"torch.finfo",
"torch.zeros_like",
"torch.randn",
"torch.distributed.get_world_size",
"torch.ones_like",
"torch.nn.functional.mse_loss",
"functools.reduce",
"torch.nn.functiona... | [((996, 1004), 'functools.wraps', 'wraps', (['f'], {}), '(f)\n', (1001, 1004), False, 'from functools import partial, reduce, wraps\n'), ((2976, 3016), 'torch.einsum', 'torch.einsum', (['"""bhld,hcd->bhlc"""', 'x', 'means'], {}), "('bhld,hcd->bhlc', x, means)\n", (2988, 3016), False, 'import torch\n'), ((3101, 3125), '... |