code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
#/usr/bin/env python
# Script to read the result of the benchmark program and plot the results.
# Options:
# `-i arg` : input file (benchmark result)
# `-o arg` : html output for the plot
# Notes: After the script runs the plot will automatically be shown in a browser.
# Tested with python 3 only.
import a... | [
"bokeh.plotting.figure",
"argparse.ArgumentParser",
"bokeh.layouts.gridplot",
"pandas.DataFrame",
"re.sub",
"bokeh.plotting.output_file"
] | [((1218, 1278), 'pandas.DataFrame', 'pd.DataFrame', (['d'], {'columns': 'column_labels[1:]', 'index': 'columns[0]'}), '(d, columns=column_labels[1:], index=columns[0])\n', (1230, 1278), True, 'import pandas as pd\n'), ((1861, 1957), 'bokeh.plotting.figure', 'figure', ([], {'width': '(500)', 'height': '(400)', 'title': ... |
import torch
import torch.nn as nn
def channel_split(z, dim=1, odd=False):
C = z.size(dim)
z0, z1 = torch.split(z, C // 2, dim=dim)
if odd:
z0, z1 = z1, z0
return z0, z1
def channel_merge(z0, z1, dim=1, odd=False):
if odd:
z0, z1 = z1, z0
z = torch.cat([z0, z1], dim=dim)
... | [
"torch.split",
"torch.stack",
"torch.cat",
"torch.meshgrid",
"torch.arange"
] | [((110, 141), 'torch.split', 'torch.split', (['z', '(C // 2)'], {'dim': 'dim'}), '(z, C // 2, dim=dim)\n', (121, 141), False, 'import torch\n'), ((287, 315), 'torch.cat', 'torch.cat', (['[z0, z1]'], {'dim': 'dim'}), '([z0, z1], dim=dim)\n', (296, 315), False, 'import torch\n'), ((482, 506), 'torch.meshgrid', 'torch.mes... |
from __future__ import absolute_import
import os.path
import argparse
import logging
import json
from six import iteritems
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.externals import joblib
from keras.models import load_model
from tensorflow.python.client import device_lib
f... | [
"preprocessing.split_data",
"logging.getLogger",
"tensorflow.python.client.device_lib.list_local_devices",
"utils.load_data",
"numpy.array",
"models.CatBoost",
"preprocessing.clean_text",
"argparse.ArgumentParser",
"json.dumps",
"metrics.get_metrics",
"features.catboost_features",
"utils.embed... | [((697, 903), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""-f TRAIN_FILE -t TEST_FILE -o OUTPUT_FILE -e EMBEDS_FILE [-l LOGGER_FILE] [--swear-words SWEAR_FILE] [--wrong-words WRONG_WORDS_FILE] [--format-embeds FALSE]"""'}), "(description=\n '-f TRAIN_FILE -t TEST_FILE -o OUTPUT_FILE... |
from django.conf.urls import url
from . import views
app_name = "restapi"
timestamp_regex = '\\d{4}[-]?\\d{1,2}[-]?\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}'
urlpatterns = [
url(r'^about/$', views.AboutView.as_view(), name='about'),
url(r'^centralized-oracles/$', views.CentralizedOracleListView.as_view(), name='c... | [
"django.conf.urls.url"
] | [((1735, 1794), 'django.conf.urls.url', 'url', (['"""^factories/$"""', 'views.factories_view'], {'name': '"""factories"""'}), "('^factories/$', views.factories_view, name='factories')\n", (1738, 1794), False, 'from django.conf.urls import url\n')] |
import logging
from django.core.cache import cache
from django.db.models import Q
from libscampi.contrib.cms.communism.models import Javascript, StyleSheet
from libscampi.contrib.cms.communism.views.mixins import html_link_refs
logger = logging.getLogger("libscampi.contrib.cms.newsengine.views")
def story_stylesheet... | [
"logging.getLogger",
"libscampi.contrib.cms.communism.views.mixins.html_link_refs",
"libscampi.contrib.cms.communism.models.Javascript.objects.filter",
"django.core.cache.cache.delete",
"libscampi.contrib.cms.communism.models.StyleSheet.objects.filter",
"django.core.cache.cache.set",
"django.db.models.Q... | [((239, 298), 'logging.getLogger', 'logging.getLogger', (['"""libscampi.contrib.cms.newsengine.views"""'], {}), "('libscampi.contrib.cms.newsengine.views')\n", (256, 298), False, 'import logging\n'), ((642, 673), 'django.core.cache.cache.get', 'cache.get', (['cached_css_key', 'None'], {}), '(cached_css_key, None)\n', (... |
from inspect import signature
from questionary import Style
from pytz import reference
import math, os, datetime
from typing import Callable
from pandas import DataFrame
############################## CONSTANTS
ROOT_PATH = os.path.expanduser('~') + os.sep + '.yuzu'
STRATS_PATH = ROOT_PATH + os.sep + 'strategies'
ENV_... | [
"pandas.DataFrame",
"math.floor",
"inspect.signature",
"questionary.Style",
"pytz.reference.LocalTimezone",
"os.path.expanduser"
] | [((650, 951), 'questionary.Style', 'Style', (["[('qmark', 'fg:#673ab7 bold'), ('question', 'bold'), ('answer',\n 'fg:#f44336 bold'), ('pointer', 'fg:#673ab7 bold'), ('highlighted',\n 'fg:#673ab7 bold'), ('selected', 'fg:#cc5454'), ('separator',\n 'fg:#cc5454'), ('instruction', ''), ('text', ''), ('disabled',\n... |
from __future__ import annotations
import torch
import torch.nn as nn
from typing import Optional
import warnings
warnings.simplefilter("ignore")
class ConvNormRelu(nn.Module):
def __init__(self, in_channels: int, out_channels: int, upsample: Optional[bool] = False) -> None:
super(ConvNormRe... | [
"torch.nn.GroupNorm",
"torch.nn.ReLU",
"torch.sigmoid",
"torch.nn.Conv2d",
"torch.nn.MaxPool2d",
"torch.cuda.is_available",
"torch.nn.Upsample",
"warnings.simplefilter",
"torch.rand"
] | [((119, 150), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (140, 150), False, 'import warnings\n'), ((406, 470), 'torch.nn.Upsample', 'nn.Upsample', ([], {'scale_factor': '(2)', 'mode': '"""bilinear"""', 'align_corners': '(True)'}), "(scale_factor=2, mode='bilinear', align_c... |
# Write your k-means unit tests here
from cluster import (KMeans, make_clusters)
import pytest
import numpy as np
def test_kmeans_zero():
"""
Start out with a basic test: Model should not run if k = 0
"""
with pytest.raises(ValueError) as error_message:
km = KMeans(k = 0)
assert "K must be greater than 0!" in ... | [
"cluster.make_clusters",
"pytest.raises",
"cluster.KMeans"
] | [((851, 878), 'cluster.make_clusters', 'make_clusters', ([], {'k': '(4)', 'scale': '(1)'}), '(k=4, scale=1)\n', (864, 878), False, 'from cluster import KMeans, make_clusters\n'), ((907, 934), 'cluster.make_clusters', 'make_clusters', ([], {'k': '(8)', 'scale': '(2)'}), '(k=8, scale=2)\n', (920, 934), False, 'from clust... |
import cv2
import time
# Open Camera
camera = cv2.VideoCapture(0)
# Set definition
camera.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
camera.set(cv2.CAP_PROP_FRAME_HEIGHT, 1024)
time.sleep(2)
# camera.set(15, -8.0)
def get_image():
retval, im = camera.read()
return im
def get_warm_up_image():
# Warmup
for i in range(10... | [
"cv2.imwrite",
"time.sleep",
"cv2.putText",
"cv2.minMaxLoc",
"cv2.circle",
"cv2.VideoCapture",
"cv2.cvtColor",
"cv2.GaussianBlur"
] | [((47, 66), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (63, 66), False, 'import cv2\n'), ((172, 185), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (182, 185), False, 'import time\n'), ((1073, 1102), 'cv2.imwrite', 'cv2.imwrite', (['file', 'base_image'], {}), '(file, base_image)\n', (1084, 11... |
#!/usr/bin/env python
#import standard libraries
import obspy.imaging.beachball
import datetime
import os
import csv
import pandas as pd
import numpy as np
import fnmatch
from geopy.distance import geodesic
from math import *
#from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
from matplotlib imp... | [
"pandas.read_csv",
"pandas.datetime.strptime",
"numpy.isfinite",
"datetime.timedelta",
"numpy.arange",
"pandas.to_datetime",
"datetime.datetime",
"matplotlib.path.Path",
"numpy.dot",
"fnmatch.fnmatch",
"numpy.vstack",
"pandas.DataFrame",
"csv.reader",
"numpy.size",
"os.path.isfile",
"n... | [((12234, 12263), 'datetime.datetime', 'datetime.datetime', (['(1900)', '(1)', '(1)'], {}), '(1900, 1, 1)\n', (12251, 12263), False, 'import datetime\n'), ((12274, 12300), 'datetime.datetime.utcnow', 'datetime.datetime.utcnow', ([], {}), '()\n', (12298, 12300), False, 'import datetime\n'), ((15450, 15469), 'numpy.size'... |
import json
def confirm():
print("")
# custom function
def rowPrint(xrow=-1,yrow=-1,xpos=-1,ypos=-1,width=9,height=9):
rows = [["O"]*width for _ in range(height)]
for list in rows:
if yrow != -1:
list[yrow]="X"
if xrow != -1:
rows[xrow] = ["X"]*width
if ypos != -1:
... | [
"pymouse.PyMouse",
"keyboard.wait",
"json.dumps"
] | [((1645, 1654), 'pymouse.PyMouse', 'PyMouse', ([], {}), '()\n', (1652, 1654), False, 'from pymouse import PyMouse\n'), ((2282, 2291), 'pymouse.PyMouse', 'PyMouse', ([], {}), '()\n', (2289, 2291), False, 'from pymouse import PyMouse\n'), ((2924, 2933), 'pymouse.PyMouse', 'PyMouse', ([], {}), '()\n', (2931, 2933), False,... |
import sys
import nni
from sklearn.metrics import r2_score
sys.path.append('../..')
from model_layer.model_hub import GRU
from model_layer.model_tuner import RecurrentModelTuner
from utils import base_io
def main(model_class, future_index, params):
target_metric_func = r2_score
metric_name = 'R... | [
"nni.get_next_parameter",
"sys.path.append",
"model_layer.model_tuner.RecurrentModelTuner"
] | [((66, 90), 'sys.path.append', 'sys.path.append', (['"""../.."""'], {}), "('../..')\n", (81, 90), False, 'import sys\n'), ((347, 506), 'model_layer.model_tuner.RecurrentModelTuner', 'RecurrentModelTuner', ([], {'model_class': 'model_class', 'future_index': 'future_index', 'target_metric_func': 'target_metric_func', 'me... |
import sys
from PyQt4 import QtGui, QtCore
class TopWindow(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.setWindowFlags(
QtCore.Qt.WindowStaysOnTopHint |
QtCore.Qt.FramelessWindowHint |
QtCore.Qt.X11BypassWindowManagerHint
... | [
"PyQt4.QtGui.QApplication",
"PyQt4.QtGui.qApp.desktop",
"PyQt4.QtGui.QApplication.desktop",
"PyQt4.QtCore.QTimer",
"PyQt4.QtGui.QLabel",
"PyQt4.QtGui.qApp.quit",
"PyQt4.QtGui.QMainWindow.__init__",
"PyQt4.QtCore.QSize"
] | [((982, 1010), 'PyQt4.QtGui.QApplication', 'QtGui.QApplication', (['sys.argv'], {}), '(sys.argv)\n', (1000, 1010), False, 'from PyQt4 import QtGui, QtCore\n'), ((112, 144), 'PyQt4.QtGui.QMainWindow.__init__', 'QtGui.QMainWindow.__init__', (['self'], {}), '(self)\n', (138, 144), False, 'from PyQt4 import QtGui, QtCore\n... |
import numpy as np
import matplotlib.pyplot as plt
import math
from scipy.optimize import linprog
from cvxpy import *
class CuttingPlaneModel:
def __init__(self, dim, bounds):
self.dim = dim
self.bounds = bounds
self.coefficients = np.empty((0,dim+1))
def __call__(self, x):#REMOVE
... | [
"numpy.abs",
"numpy.eye",
"numpy.multiply",
"numpy.hstack",
"matplotlib.pyplot.colorbar",
"numpy.asarray",
"matplotlib.pyplot.plot",
"numpy.max",
"numpy.append",
"matplotlib.pyplot.contour",
"matplotlib.pyplot.figure",
"numpy.linspace",
"numpy.empty",
"test_function.TestFunction",
"matpl... | [((261, 283), 'numpy.empty', 'np.empty', (['(0, dim + 1)'], {}), '((0, dim + 1))\n', (269, 283), True, 'import numpy as np\n'), ((501, 554), 'numpy.asarray', 'np.asarray', (['[[c[1], c[2]] for c in self.coefficients]'], {}), '([[c[1], c[2]] for c in self.coefficients])\n', (511, 554), True, 'import numpy as np\n'), ((6... |
from gekko import GEKKO
import numpy as np
import matplotlib.pyplot as plt
# generate training data
x = np.linspace(0.0,2*np.pi,20)
y = np.sin(x)
# option for fitting function
select = True # True / False
if select:
# Size with cosine function
nin = 1 # inputs
n1 = 1 # hidden layer 1 (linear)
n2 ... | [
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"gekko.GEKKO",
"numpy.linspace",
"matplotlib.pyplot.figure",
"numpy.sin",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show"
] | [((107, 138), 'numpy.linspace', 'np.linspace', (['(0.0)', '(2 * np.pi)', '(20)'], {}), '(0.0, 2 * np.pi, 20)\n', (118, 138), True, 'import numpy as np\n'), ((139, 148), 'numpy.sin', 'np.sin', (['x'], {}), '(x)\n', (145, 148), True, 'import numpy as np\n'), ((660, 667), 'gekko.GEKKO', 'GEKKO', ([], {}), '()\n', (665, 66... |
import argparse
import os
import sys
import numpy as np
import pdb
from tqdm import tqdm
import cv2
import glob
import numpy as np
from numpy import *
import matplotlib
#matplotlib.use("Agg")
#matplotlib.use("wx")
#matplotlib.use('tkagg')
import matplotlib.pyplot as plt
import scipy
from scipy.special import softmax
... | [
"modeling.sync_batchnorm.replicate.patch_replication_callback",
"numpy.mean",
"PIL.Image.open",
"numpy.logical_and",
"argparse.ArgumentParser",
"torch.load",
"numpy.bitwise_xor",
"numpy.logical_or",
"numpy.subtract",
"torch.nn.DataParallel",
"torch.from_numpy",
"numpy.sum",
"numpy.array",
... | [((1440, 1463), 'torch.load', 'torch.load', (['args.resume'], {}), '(args.resume)\n', (1450, 1463), False, 'import torch\n'), ((1961, 1990), 'numpy.expand_dims', 'np.expand_dims', (['image'], {'axis': '(0)'}), '(image, axis=0)\n', (1975, 1990), True, 'import numpy as np\n'), ((2333, 2360), 'numpy.logical_or', 'np.logic... |
# import library socket karena menggunakan IPC socket
import socket
# definisikan IP untuk binding
TCP_IP = '127.0.0.1'
# definisikan port untuk binding
TCP_PORT = 5005
# definisikan ukuran buffer untuk menerima pesan
BUFFER_SIZE = 4096
# buat socket (bertipe UDP atau TCP?)
s = socket.socket(socket.AF_INET, socke... | [
"socket.socket"
] | [((285, 334), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (298, 334), False, 'import socket\n')] |
import numpy as np
from scipy.integrate import odeint
class MorrisLecar:
"""
Creates a MorrisLecar model.
"""
def __init__(self, C=20, VL=-60, VCa=120, VK=-84, gL=2, gCa=4, gK=8,
V1=-1.2, V2=18, V3=12, V4=17.4, phi=0.06):
"""
Initializes the model.
Args:
... | [
"scipy.integrate.odeint",
"numpy.tanh",
"numpy.cosh",
"numpy.arange"
] | [((2678, 2707), 'numpy.arange', 'np.arange', (['(0)', 'self.t', 'self.dt'], {}), '(0, self.t, self.dt)\n', (2687, 2707), True, 'import numpy as np\n'), ((2720, 2777), 'scipy.integrate.odeint', 'odeint', (['self._system_equations', 'X0', 'self.tvec', '(current,)'], {}), '(self._system_equations, X0, self.tvec, (current,... |
"""Abstract Base Class for Keras Models."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
import tensorflow as tf
from keras import models
from tf_trainer.common import types
from tf_trainer.common import base_model
class BaseKerasModel(base... | [
"tensorflow.metrics.auc",
"tensorflow.keras.estimator.model_to_estimator",
"tensorflow.estimator.Estimator",
"tensorflow.greater"
] | [((1264, 1371), 'tensorflow.keras.estimator.model_to_estimator', 'tf.keras.estimator.model_to_estimator', ([], {'keras_model': 'keras_model', 'model_dir': 'BaseKerasModel.TMP_MODEL_DIR'}), '(keras_model=keras_model, model_dir=\n BaseKerasModel.TMP_MODEL_DIR)\n', (1301, 1371), True, 'import tensorflow as tf\n'), ((16... |
import game.shared.gamecontants as gameconstants
from game.casting.cast import Cast
from game.casting.cycle import Cycle
from game.directing.director import Director
from game.services.keyboard_service import KeyboardService
from game.services.display_service import DisplayService
from game.shared.color import Colo... | [
"game.shared.point.Point",
"game.casting.cycle.Cycle",
"game.shared.gamecontants.CAPTION.format",
"game.casting.cast.Cast",
"game.services.keyboard_service.KeyboardService",
"game.directing.director.Director",
"game.shared.color.Color"
] | [((405, 411), 'game.casting.cast.Cast', 'Cast', ([], {}), '()\n', (409, 411), False, 'from game.casting.cast import Cast\n'), ((933, 951), 'game.casting.cycle.Cycle', 'Cycle', (['position', '(1)'], {}), '(position, 1)\n', (938, 951), False, 'from game.casting.cycle import Cycle\n'), ((1221, 1239), 'game.casting.cycle.C... |
import logging
import numpy as np
from .transformer import Transformer, FFTTransformer
logger = logging.getLogger(__name__)
class MapScaler:
def __init__(self, xmap, scattering='xray'):
self.xmap = xmap
self.scattering = scattering
self._model_map = xmap.zeros_like(xmap)
def subtr... | [
"logging.getLogger",
"numpy.dot"
] | [((99, 126), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (116, 126), False, 'import logging\n'), ((1942, 1975), 'numpy.dot', 'np.dot', (['model_masked', 'xmap_masked'], {}), '(model_masked, xmap_masked)\n', (1948, 1975), True, 'import numpy as np\n'), ((1989, 2021), 'numpy.dot', 'np.do... |
import time
from django.conf import settings
from Harvest.utils import get_logger
from monitoring.decorators import update_component_status
from monitoring.models import ComponentStatus
from plugins.bibliotik.client import BibliotikClient
from plugins.bibliotik.exceptions import BibliotikTorrentNotFoundException
from... | [
"plugins.bibliotik_archiver.utils.get_bibliotik_torrent_for_archiving",
"torrents.add_torrent.add_torrent_from_tracker",
"torrents.models.Realm.objects.get",
"plugins.bibliotik_archiver.models.BibliotikArchiverState.objects.get",
"task_queue.task_queue.TaskQueue.periodic_task",
"monitoring.decorators.upda... | [((797, 817), 'Harvest.utils.get_logger', 'get_logger', (['__name__'], {}), '(__name__)\n', (807, 817), False, 'from Harvest.utils import get_logger\n'), ((821, 891), 'task_queue.task_queue.TaskQueue.periodic_task', 'TaskQueue.periodic_task', (['settings.BIBLIOTIK_ARCHIVER_METADATA_INTERVAL'], {}), '(settings.BIBLIOTIK... |
from flask import request,json
from werkzeug.exceptions import HTTPException
class ApiException(HTTPException):
code = 500
error_code = 500
msg = 'sorry, made a mistake'
def __init__(self,code=None, error_code=None, msg=None, header=None):
if code:
self.code = code
if msg:... | [
"flask.json.dumps"
] | [((682, 698), 'flask.json.dumps', 'json.dumps', (['body'], {}), '(body)\n', (692, 698), False, 'from flask import request, json\n')] |
from robot.thymio_robot import ThymioII
from robot.vrep_robot import VrepRobot
from aseba.aseba import Aseba
from utility.util_functions import normalize
import numpy as np
T_SEN_MIN = 0
T_SEN_MAX = 4500
class EvolvedRobot(VrepRobot, ThymioII):
def __init__(self, name, client_id, id, op_mode, chromosome, robot_... | [
"numpy.array",
"robot.vrep_robot.VrepRobot.__init__",
"utility.util_functions.normalize",
"robot.thymio_robot.ThymioII.__init__"
] | [((335, 395), 'robot.vrep_robot.VrepRobot.__init__', 'VrepRobot.__init__', (['self', 'client_id', 'id', 'op_mode', 'robot_type'], {}), '(self, client_id, id, op_mode, robot_type)\n', (353, 395), False, 'from robot.vrep_robot import VrepRobot\n'), ((404, 433), 'robot.thymio_robot.ThymioII.__init__', 'ThymioII.__init__',... |
import argparse
import json
import os
try:
import cv2
def get_image_dims(im_file):
im = cv2.imread(im_file,0)
im_h, im_w = im.shape
return im_h, im_w
Exception.Modu
except ModuleNotFoundError as e:
from PIL import Image
def get_image_dims(im_file):
im = Image.open(im_file)
im_w, im_h = im.size
return ... | [
"os.listdir",
"PIL.Image.open",
"argparse.ArgumentParser",
"os.path.join",
"os.path.isfile",
"os.path.isdir",
"os.mkdir",
"cv2.imread"
] | [((486, 522), 'os.path.join', 'os.path.join', (['data_path', '"""meta.json"""'], {}), "(data_path, 'meta.json')\n", (498, 522), False, 'import os\n'), ((1047, 1080), 'os.path.join', 'os.path.join', (['data_path', '"""images"""'], {}), "(data_path, 'images')\n", (1059, 1080), False, 'import os\n'), ((1093, 1131), 'os.pa... |
#
# Copyright The NOMAD Authors.
#
# This file is part of NOMAD. See https://nomad-lab.eu for further info.
#
# 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/licen... | [
"datetime.datetime",
"numpy.abs",
"nomad.datamodel.metainfo.simulation.method.BasisSet",
"os.path.isfile",
"numpy.array",
"os.path.dirname",
"nomad.datamodel.metainfo.simulation.system.Atoms",
"nomad.parsing.file_parser.Quantity"
] | [((2539, 2557), 'os.path.isfile', 'path.isfile', (['fname'], {}), '(fname)\n', (2550, 2557), False, 'from os import path\n'), ((4514, 4532), 'os.path.isfile', 'path.isfile', (['fname'], {}), '(fname)\n', (4525, 4532), False, 'from os import path\n'), ((7185, 7199), 'numpy.array', 'np.array', (['coxp'], {}), '(coxp)\n',... |
##
# Fabric module to deploy MaaS. Run as root user.
#
import os
import sys
import time
import logging
from fabric.api import *
from fabric.operations import reboot
from fabric.colors import cyan, green, red
from fabric.context_managers import shell_env
from fabric.contrib.files import append, sed, comment
from fabri... | [
"logging.basicConfig",
"logging.getLogger",
"fabric.colors.green",
"fabric.colors.red",
"fabric.contrib.files.sed",
"fabric.contrib.files.append",
"fabric.colors.cyan"
] | [((365, 405), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.ERROR'}), '(level=logging.ERROR)\n', (384, 405), False, 'import logging\n'), ((417, 456), 'logging.getLogger', 'logging.getLogger', (['"""paramiko.transport"""'], {}), "('paramiko.transport')\n", (434, 456), False, 'import logging\n'), ... |
import re
from dateutil.parser import parse
from vessel import Vessel,Forum,InvalidVesselException,engine,session
from tqdm import tqdm
import urllib.request
import codecs
program_to_jinja={
"children count": "vessel.children|length",
"children random":"(vessel.children|random).name",
"children list":"('\n ... | [
"dateutil.parser.parse",
"vessel.Vessel.update",
"vessel.Vessel.metadata.drop_all",
"vessel.Forum.update",
"vessel.Vessel.metadata.create_all",
"vessel.Vessel",
"vessel.Forum",
"re.finditer"
] | [((2819, 2851), 'vessel.Vessel.metadata.drop_all', 'Vessel.metadata.drop_all', (['engine'], {}), '(engine)\n', (2843, 2851), False, 'from vessel import Vessel, Forum, InvalidVesselException, engine, session\n'), ((2852, 2886), 'vessel.Vessel.metadata.create_all', 'Vessel.metadata.create_all', (['engine'], {}), '(engine... |
from __future__ import print_function # Python 2/3 compatibility
import boto3
dynamodb = boto3.resource('dynamodb', endpoint_url="http://localhost:8000")
table = dynamodb.Table('Election')
table.delete()
table = dynamodb.Table('Vote')
table.delete() | [
"boto3.resource"
] | [((90, 154), 'boto3.resource', 'boto3.resource', (['"""dynamodb"""'], {'endpoint_url': '"""http://localhost:8000"""'}), "('dynamodb', endpoint_url='http://localhost:8000')\n", (104, 154), False, 'import boto3\n')] |
import setuptools
# read the contents of your README file
from pathlib import Path
this_directory = Path(__file__).parent
long_description = (this_directory / "README.md").read_text()
setuptools.setup(
name='pybgpkit',
version='0.1.0',
description='BGPKIT tools Python bindings',
url='https://github.co... | [
"setuptools.find_packages",
"pathlib.Path"
] | [((101, 115), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (105, 115), False, 'from pathlib import Path\n'), ((402, 428), 'setuptools.find_packages', 'setuptools.find_packages', ([], {}), '()\n', (426, 428), False, 'import setuptools\n')] |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui/chain_creation.ui'
#
# Created by: PyQt5 UI code generator 5.9
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.se... | [
"PyQt5.QtWidgets.QTextEdit",
"PyQt5.QtWidgets.QDialogButtonBox",
"PyQt5.QtWidgets.QComboBox",
"PyQt5.QtCore.QMetaObject.connectSlotsByName",
"PyQt5.QtCore.QRect"
] | [((400, 427), 'PyQt5.QtWidgets.QTextEdit', 'QtWidgets.QTextEdit', (['Dialog'], {}), '(Dialog)\n', (419, 427), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((571, 598), 'PyQt5.QtWidgets.QComboBox', 'QtWidgets.QComboBox', (['Dialog'], {}), '(Dialog)\n', (590, 598), False, 'from PyQt5 import QtCore, QtGui, QtWi... |
from sklearn.base import BaseEstimator
from sklearn.multiclass import OneVsRestClassifier
from sklearn.linear_model import LogisticRegression as SKLearnLR
class LogisticRegression(BaseEstimator):
def __init__(self):
pass
def fit(self, X, y):
# TODO: Consider pure (no penalty) LR
# TODO... | [
"sklearn.linear_model.LogisticRegression"
] | [((484, 513), 'sklearn.linear_model.LogisticRegression', 'SKLearnLR', ([], {'solver': '"""liblinear"""'}), "(solver='liblinear')\n", (493, 513), True, 'from sklearn.linear_model import LogisticRegression as SKLearnLR\n')] |
import numpy as np
MAX = 10000
matrix = np.full((MAX, MAX), False)
def pretty_print(matrix):
print_matrix = np.full(matrix.shape, ".")
print_matrix[matrix] = "#"
for row in print_matrix:
for symb in row:
print(symb, end="")
print()
def fold_once(matrix, axis, value):
if ... | [
"numpy.full",
"numpy.logical_or"
] | [((41, 67), 'numpy.full', 'np.full', (['(MAX, MAX)', '(False)'], {}), '((MAX, MAX), False)\n', (48, 67), True, 'import numpy as np\n'), ((115, 141), 'numpy.full', 'np.full', (['matrix.shape', '"""."""'], {}), "(matrix.shape, '.')\n", (122, 141), True, 'import numpy as np\n'), ((502, 559), 'numpy.logical_or', 'np.logica... |
from ckeditor.fields import RichTextField
from django.conf import settings
from django.db import models
from django.urls import reverse
from django.utils import timezone
from django.utils.html import strip_tags
from django.utils.text import Truncator
from django.utils.translation import gettext_lazy as _
from html_sani... | [
"django.utils.translation.gettext_lazy",
"django.utils.html.strip_tags",
"html_sanitizer.django.get_sanitizer",
"django.urls.reverse"
] | [((864, 879), 'django.utils.translation.gettext_lazy', '_', (['"""created at"""'], {}), "('created at')\n", (865, 879), True, 'from django.utils.translation import gettext_lazy as _\n'), ((1103, 1125), 'django.utils.translation.gettext_lazy', '_', (['"""moderation status"""'], {}), "('moderation status')\n", (1104, 112... |
from django.urls import path
from account import views as account_views
urlpatterns = [
path('begin/', account_views.BeginView.as_view(), name='begin'),
path('signup/', account_views.SignUpView.as_view(), name='signup'),
path('login/', account_views.LoginView.as_view(), name='login'),
path('logout/', ... | [
"account.views.BeginView.as_view",
"account.views.LogoutView.as_view",
"account.views.LoginView.as_view",
"account.views.SignUpView.as_view",
"django.urls.path",
"account.views.ResetPasswordView.as_view"
] | [((471, 567), 'django.urls.path', 'path', (['"""password-reset-sent/"""', 'account_views.password_reset_sent'], {'name': '"""password-reset-sent"""'}), "('password-reset-sent/', account_views.password_reset_sent, name=\n 'password-reset-sent')\n", (475, 567), False, 'from django.urls import path\n'), ((569, 676), 'd... |
"""MEG system lockfile parser
Can be used to parse the lock file and preform operations on the lockfile
Only interacts with the lockfile, does not preform any git actions
Does not check permissions before actions are taken
All file paths are relitive to the repository directory
Working directory should be changed by ... | [
"json.dumps",
"time.time"
] | [((997, 1008), 'time.time', 'time.time', ([], {}), '()\n', (1006, 1008), False, 'import time\n'), ((2626, 2649), 'json.dumps', 'json.dumps', (['self._locks'], {}), '(self._locks)\n', (2636, 2649), False, 'import json\n')] |
# Generated by Django 3.1.3 on 2020-12-08 11:34
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('artist', '0006_auto_20201208_1052'),
]
operations = [
migrations.AlterModelOptions(
name='comme... | [
"django.db.migrations.AlterModelOptions",
"django.db.models.ForeignKey",
"django.db.migrations.RemoveField",
"django.db.models.SlugField"
] | [((267, 323), 'django.db.migrations.AlterModelOptions', 'migrations.AlterModelOptions', ([], {'name': '"""comment"""', 'options': '{}'}), "(name='comment', options={})\n", (295, 323), False, 'from django.db import migrations, models\n'), ((368, 425), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'... |
from pathlib import Path
from ontopy import get_ontology, World
# Setup dlite paths
thisdir = Path(__file__).parent.absolute()
rootdir = thisdir.parent.parent
# Note install emmopython from github, not pypi.
world = World()
mapsTo_onto = world.get_ontology(f'{rootdir}/ontology/mapsTo.ttl').load(
EMMObased=Fals... | [
"ontopy.World",
"pathlib.Path"
] | [((220, 227), 'ontopy.World', 'World', ([], {}), '()\n', (225, 227), False, 'from ontopy import get_ontology, World\n'), ((97, 111), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (101, 111), False, 'from pathlib import Path\n')] |
from distutils.version import StrictVersion
import logging
def __get_version(version):
if 'dev' in str(version):
version = version[:version.find('.dev')]
return StrictVersion(version)
# Detect pandas and use a mock if missing
PANDAS_MIN_VERSION = '0.13.0'
try:
import pandas
if __get_version... | [
"distutils.version.StrictVersion"
] | [((180, 202), 'distutils.version.StrictVersion', 'StrictVersion', (['version'], {}), '(version)\n', (193, 202), False, 'from distutils.version import StrictVersion\n'), ((343, 376), 'distutils.version.StrictVersion', 'StrictVersion', (['PANDAS_MIN_VERSION'], {}), '(PANDAS_MIN_VERSION)\n', (356, 376), False, 'from distu... |
from pyspark import SparkConf, SparkContext
from pyspark import SQLContext
from pyspark.sql.functions import udf
import string
conf = SparkConf().setAppName('MovieRating')
sc = SparkContext(conf = conf)
sqlContext = SQLContext(sc)
df = sqlContext.read.format("com.databricks.spark.csv").option("header", "true").optio... | [
"pyspark.SparkContext",
"pyspark.SparkConf",
"pyspark.SQLContext"
] | [((179, 202), 'pyspark.SparkContext', 'SparkContext', ([], {'conf': 'conf'}), '(conf=conf)\n', (191, 202), False, 'from pyspark import SparkConf, SparkContext\n'), ((218, 232), 'pyspark.SQLContext', 'SQLContext', (['sc'], {}), '(sc)\n', (228, 232), False, 'from pyspark import SQLContext\n'), ((136, 147), 'pyspark.Spark... |
#!/usr/bin/env python3
################################################################################
# INTRODUCTION
################################################################################
# Encoder Title: ASCII shellcode encoder via AND, SUB, PUSH
# Date: 26.6.2019
# Encoder Author: <NAME>, www.mmquant.ne... | [
"random.choice",
"struct.iter_unpack",
"struct.pack",
"random.choices",
"itertools.combinations_with_replacement"
] | [((5369, 5409), 'struct.iter_unpack', 'struct.iter_unpack', (['"""<L"""', 'self.shellcode'], {}), "('<L', self.shellcode)\n", (5387, 5409), False, 'import struct\n'), ((5324, 5346), 'random.choice', 'random.choice', (['results'], {}), '(results)\n', (5337, 5346), False, 'import random\n'), ((5603, 5631), 'struct.pack',... |
from __future__ import print_function, unicode_literals
from datetime import datetime
from netmiko import ConnectHandler
from my_devices import device_list
def Netmiko_connect(device,command):
"""Execute show version command using Netmiko."""
print()
print("#" * 80)
remote_conn = ConnectHandler(**dev... | [
"netmiko.ConnectHandler",
"datetime.datetime.now"
] | [((300, 324), 'netmiko.ConnectHandler', 'ConnectHandler', ([], {}), '(**device)\n', (314, 324), False, 'from netmiko import ConnectHandler\n'), ((465, 479), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (477, 479), False, 'from datetime import datetime\n'), ((630, 644), 'datetime.datetime.now', 'datetime.n... |
# https://adventofcode.com/2021/day/9
from math import prod
from src.util.types import Data, Point2, Solution
def prepare_data(data: str) -> tuple[tuple[tuple[int, ...], ...], list[Point2]]:
heightmap = tuple(tuple(int(x) for x in list(line)) for line in data.splitlines())
low_points = get_low_points(height... | [
"src.util.types.Point2",
"src.util.types.Solution",
"math.prod"
] | [((1976, 1997), 'math.prod', 'prod', (['basin_sizes[:3]'], {}), '(basin_sizes[:3])\n', (1980, 1997), False, 'from math import prod\n'), ((2050, 2060), 'src.util.types.Solution', 'Solution', ([], {}), '()\n', (2058, 2060), False, 'from src.util.types import Data, Point2, Solution\n'), ((457, 473), 'src.util.types.Point2... |
# Copyright 2018 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, ... | [
"argparse.ArgumentParser",
"cv2.threshold",
"cv2.HoughCircles",
"cv2.imshow",
"cv2.waitKey",
"cv2.circle",
"cv2.destroyAllWindows",
"numpy.around",
"cv2.cvtColor",
"cv2.GaussianBlur",
"cv2.imread"
] | [((632, 657), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (655, 657), False, 'import argparse\n'), ((733, 758), 'cv2.imread', 'cv2.imread', (['args.filename'], {}), '(args.filename)\n', (743, 758), False, 'import cv2\n'), ((766, 802), 'cv2.cvtColor', 'cv2.cvtColor', (['im', 'cv2.COLOR_BGR2GR... |
from setuptools import find_packages, setup
import re
# parse dyneusr/_version.py
try:
version_fn = 'dyneusr/_version.py'
with open(version_fn) as version_fd:
version = version_fd.read()
version_re = r"^__version__ = ['\"]([^'\"]*)['\"]"
version = re.findall(version_re, version, re.M)[0]
except... | [
"re.findall",
"setuptools.find_packages"
] | [((273, 310), 're.findall', 're.findall', (['version_re', 'version', 're.M'], {}), '(version_re, version, re.M)\n', (283, 310), False, 'import re\n'), ((1008, 1023), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (1021, 1023), False, 'from setuptools import find_packages, setup\n')] |
from flask import Flask, render_template, request
from api_hh_skills import parsing_skills
from api_hh_salary import parsing_av_salary
from db_sqlalchemy_creator import Vacancy_info, City, Vacancy, Contacts
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm ... | [
"flask.render_template",
"sqlalchemy.orm.sessionmaker",
"flask.Flask",
"sqlalchemy.create_engine",
"api_hh_salary.parsing_av_salary",
"db_sqlalchemy_creator.City",
"db_sqlalchemy_creator.Vacancy",
"sqlalchemy.ext.declarative.declarative_base",
"datetime.datetime.today",
"api_hh_skills.parsing_skil... | [((403, 418), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (408, 418), False, 'from flask import Flask, render_template, request\n'), ((428, 478), 'sqlalchemy.create_engine', 'create_engine', (['"""sqlite:///orm1.sqlite"""'], {'echo': '(False)'}), "('sqlite:///orm1.sqlite', echo=False)\n", (441, 478), Fa... |
import sys
import dimod
import dwave.inspector
from minorminer import find_embedding
from dwave.cloud import Client
from dwave.embedding import embed_bqm, unembed_sampleset
from dwave.embedding.utils import edgelist_to_adjacency
# define problem
bqm = dimod.BQM.from_ising({}, {'ab': 1, 'bc': 1, 'ca': 1})
# or, load ... | [
"dwave.embedding.unembed_sampleset",
"dwave.embedding.utils.edgelist_to_adjacency",
"dimod.BQM.from_ising",
"dwave.cloud.Client.from_config",
"minorminer.find_embedding",
"dwave.embedding.embed_bqm",
"dimod.BinaryQuadraticModel.from_coo"
] | [((254, 307), 'dimod.BQM.from_ising', 'dimod.BQM.from_ising', (['{}', "{'ab': 1, 'bc': 1, 'ca': 1}"], {}), "({}, {'ab': 1, 'bc': 1, 'ca': 1})\n", (274, 307), False, 'import dimod\n'), ((522, 542), 'dwave.cloud.Client.from_config', 'Client.from_config', ([], {}), '()\n', (540, 542), False, 'from dwave.cloud import Clien... |
#!/usr/bin/env python
from __future__ import print_function
import os
import requests
import subprocess
import sys
import re
from cli.appconfig import AppConfig
from cli.settings import Settings
requests.packages.urllib3.disable_warnings()
class ProxyParser:
path_begin_values = {}
backend_services_tcp_ports... | [
"cli.appconfig.AppConfig",
"cli.settings.Settings",
"requests.packages.urllib3.disable_warnings",
"requests.get"
] | [((196, 240), 'requests.packages.urllib3.disable_warnings', 'requests.packages.urllib3.disable_warnings', ([], {}), '()\n', (238, 240), False, 'import requests\n'), ((419, 429), 'cli.settings.Settings', 'Settings', ([], {}), '()\n', (427, 429), False, 'from cli.settings import Settings\n'), ((447, 458), 'cli.appconfig.... |
"""Implementation Vibrator for Android."""
from jnius import autoclass, cast
from plyer.facades import Vibrator
from plyer.platforms.android import activity
from plyer.platforms.android import SDK_INT
Context = autoclass("android.content.Context")
vibrator_service = activity.getSystemService(Context.VIBRATOR_SERVICE)... | [
"jnius.autoclass",
"plyer.platforms.android.activity.getSystemService",
"jnius.cast"
] | [((213, 249), 'jnius.autoclass', 'autoclass', (['"""android.content.Context"""'], {}), "('android.content.Context')\n", (222, 249), False, 'from jnius import autoclass, cast\n'), ((269, 320), 'plyer.platforms.android.activity.getSystemService', 'activity.getSystemService', (['Context.VIBRATOR_SERVICE'], {}), '(Context.... |
from secml.ml.features.normalization.tests import CNormalizerTestCases
from sklearn.preprocessing import StandardScaler
from secml.ml.features.normalization import CNormalizerMeanStd
class TestCNormalizerMeanStd(CNormalizerTestCases):
"""Unittests for CNormalizerMeanStd."""
def test_transform(self):
... | [
"sklearn.preprocessing.StandardScaler",
"secml.ml.features.normalization.CNormalizerMeanStd",
"secml.ml.features.normalization.tests.CNormalizerTestCases.main"
] | [((3128, 3155), 'secml.ml.features.normalization.tests.CNormalizerTestCases.main', 'CNormalizerTestCases.main', ([], {}), '()\n', (3153, 3155), False, 'from secml.ml.features.normalization.tests import CNormalizerTestCases\n'), ((553, 586), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {'with_std': 'wi... |
# coding=utf8
from base import ApiBase
from tornado.gen import coroutine, Return
from service.user import ServiceUser
class ApiUserBase(ApiBase):
def __init__(self, *args, **kwargs):
super(ApiUserBase, self).__init__(*args, **kwargs)
self.srv_user = ServiceUser()
class ApiUserLogin(ApiUserBase):... | [
"service.user.ServiceUser"
] | [((272, 285), 'service.user.ServiceUser', 'ServiceUser', ([], {}), '()\n', (283, 285), False, 'from service.user import ServiceUser\n')] |
# Copyright 2021 sunehabose
# MIT License
import sys
import unittest
from unittest.mock import patch
sys.path.insert(0, 'code')
import code.user_cli
class TestUserCLI(unittest.TestCase):
@patch('builtins.input', return_value='1')
def test_user_menu_1(self, mock_input) -> None:
code.user_cli.user_men... | [
"sys.path.insert",
"unittest.mock.patch"
] | [((102, 128), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""code"""'], {}), "(0, 'code')\n", (117, 128), False, 'import sys\n'), ((196, 237), 'unittest.mock.patch', 'patch', (['"""builtins.input"""'], {'return_value': '"""1"""'}), "('builtins.input', return_value='1')\n", (201, 237), False, 'from unittest.mock imp... |
from itertools import combinations
import numpy as np
from PlanningCore.core.constants import State
from PlanningCore.core.physics import (
ball_ball_collision,
ball_cushion_collision,
cue_strike,
evolve_ball_motion,
get_ball_ball_collision_time,
get_ball_cushion_collision_time,
get_roll_t... | [
"PlanningCore.core.utils.get_rel_velocity",
"numpy.all",
"PlanningCore.core.physics.get_ball_cushion_collision_time",
"PlanningCore.core.physics.get_ball_ball_collision_time",
"PlanningCore.core.physics.get_roll_time",
"PlanningCore.core.physics.evolve_ball_motion",
"PlanningCore.core.physics.get_slide_... | [((7095, 7130), 'PlanningCore.core.physics.cue_strike', 'cue_strike', (['v_cue', 'phi', 'theta', 'a', 'b'], {}), '(v_cue, phi, theta, a, b)\n', (7105, 7130), False, 'from PlanningCore.core.physics import ball_ball_collision, ball_cushion_collision, cue_strike, evolve_ball_motion, get_ball_ball_collision_time, get_ball_... |
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.template import Context, loader
from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib.auth import authenticate
from django.contrib.auth im... | [
"django.shortcuts.render",
"django.contrib.auth.authenticate",
"django.http.HttpResponseRedirect",
"core.models.Category.objects.all",
"core.models.Post.objects.create",
"django.http.HttpResponse",
"django.contrib.auth.login",
"django.contrib.auth.models.User.objects.create_user",
"core.forms.PostFo... | [((603, 613), 'core.forms.PostForm', 'PostForm', ([], {}), '()\n', (611, 613), False, 'from core.forms import CreateAccForm, ForgotPasswordForm, PostForm\n'), ((1252, 1272), 'django.contrib.auth.logout', 'logout_user', (['request'], {}), '(request)\n', (1263, 1272), True, 'from django.contrib.auth import logout as logo... |
import argparse
import logging
import sys
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import ProgrammingError, OperationalError
import models
from seat_info_proxy import __version__
import yaml
__author__ = "<NAME>"
__copyright__ = "Ci4Rail GmbH"
__lic... | [
"logging.getLogger",
"logging.basicConfig",
"sqlalchemy.orm.sessionmaker",
"models.SeatReservation.__table__.create",
"models.SeatReservation",
"argparse.ArgumentParser",
"os.getenv",
"sqlalchemy.create_engine",
"yaml.safe_load",
"models.SeatReservation.__table__.drop"
] | [((346, 373), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (363, 373), False, 'import logging\n'), ((411, 487), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Preload DB with seat reservation data"""'}), "(description='Preload DB with seat reservation dat... |
#!/usr/bin/env python3
import os
import jsii
import aws_cdk as cdk
from aws_cdk import (
Aspects,
CfnResource
)
@jsii.implements(cdk.IAspect)
class ForceDeletion:
def visit(self, scope):
if isinstance(scope, CfnResource):
scope.apply_removal_policy(cdk.RemovalPolicy.DESTROY)
from ste... | [
"aws_cdk.Aspects.of",
"aws_cdk.App",
"jsii.implements",
"step_functions_example.step_functions_example_stack.StepFunctionsExampleStack"
] | [((124, 152), 'jsii.implements', 'jsii.implements', (['cdk.IAspect'], {}), '(cdk.IAspect)\n', (139, 152), False, 'import jsii\n'), ((410, 419), 'aws_cdk.App', 'cdk.App', ([], {}), '()\n', (417, 419), True, 'import aws_cdk as cdk\n'), ((431, 469), 'step_functions_example.step_functions_example_stack.StepFunctionsExample... |
#!/usr/bin/env python
# Copyright 2015-2017 ARM Limited
#
# 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... | [
"argparse.FileType",
"argparse.ArgumentParser",
"json.load",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show"
] | [((4410, 4426), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(211)'], {}), '(211)\n', (4421, 4426), True, 'import matplotlib.pyplot as plt\n'), ((6153, 6169), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(212)'], {}), '(212)\n', (6164, 6169), True, 'import matplotlib.pyplot as plt\n'), ((7955, 8268), 'argparse.Argu... |
# vim: set ts=8 sts=4 sw=4 tw=99 et:
#
# This file is part of AMBuild.
#
# AMBuild is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ... | [
"os.path.isabs",
"os.path.splitdrive",
"os.path.join",
"os.path.splitext",
"os.path.split",
"os.path.normcase",
"os.path.relpath"
] | [((2781, 2807), 'os.path.isabs', 'os.path.isabs', (['output_path'], {}), '(output_path)\n', (2794, 2807), False, 'import os\n'), ((2831, 2860), 'os.path.normcase', 'os.path.normcase', (['output_path'], {}), '(output_path)\n', (2847, 2860), False, 'import os\n'), ((3062, 3096), 'os.path.normcase', 'os.path.normcase', ([... |
import wikipedia
from pprint import pprint
import json, os
class WikipediaScraper:
def __init__(self):
pass
def get(self, term):
try:
results = wikipedia.search(term)
if len(results) == 0:
raise RuntimeError(f'No wikipedia page for: {term}')
... | [
"wikipedia.page",
"wikipedia.search"
] | [((183, 205), 'wikipedia.search', 'wikipedia.search', (['term'], {}), '(term)\n', (199, 205), False, 'import wikipedia\n'), ((333, 379), 'wikipedia.page', 'wikipedia.page', (['results[0]'], {'auto_suggest': '(False)'}), '(results[0], auto_suggest=False)\n', (347, 379), False, 'import wikipedia\n')] |
"""
The :mod:`fatf.utils.models.models` module holds custom models.
The models implemented in this module are mainly used for used for
FAT Forensics package testing and the examples in the documentation.
"""
# Author: <NAME> <<EMAIL>>
# License: new BSD
import abc
from typing import Optional
import numpy as np
imp... | [
"fatf.exceptions.IncorrectShapeError",
"fatf.exceptions.UnfittedModelError",
"fatf.utils.array.validation.is_structured_array",
"numpy.argsort",
"fatf.utils.array.validation.is_1d_array",
"numpy.array",
"fatf.utils.array.validation.is_2d_array",
"fatf.exceptions.PrefittedModelError",
"numpy.where",
... | [((6935, 6953), 'numpy.ndarray', 'np.ndarray', (['(0, 0)'], {}), '((0, 0))\n', (6945, 6953), True, 'import numpy as np\n'), ((7004, 7020), 'numpy.ndarray', 'np.ndarray', (['(0,)'], {}), '((0,))\n', (7014, 7020), True, 'import numpy as np\n'), ((7105, 7121), 'numpy.ndarray', 'np.ndarray', (['(0,)'], {}), '((0,))\n', (71... |
import tensorflow as tf
from noise import cropout
class CropoutTest(tf.test.TestCase):
def setUp(self):
self.layer = cropout.Cropout()
def testCropProportions(self):
shapes = [(1, 28, 28, 1), (2, 28, 28, 1),
(1, 28, 28, 3), (2, 28, 28, 3),
(2, 33, 33, 3)]... | [
"tensorflow.ones",
"tensorflow.reduce_sum",
"tensorflow.sqrt",
"noise.cropout.Cropout",
"tensorflow.cast",
"tensorflow.zeros"
] | [((133, 150), 'noise.cropout.Cropout', 'cropout.Cropout', ([], {}), '()\n', (148, 150), False, 'from noise import cropout\n'), ((475, 489), 'tensorflow.ones', 'tf.ones', (['shape'], {}), '(shape)\n', (482, 489), True, 'import tensorflow as tf\n'), ((520, 535), 'tensorflow.zeros', 'tf.zeros', (['shape'], {}), '(shape)\n... |
import cv2
import numpy as np
import sys
import haar_cascade as cascade
from datetime import datetime
import os.path
output_dir = "../images"
class SmileDetectStatus:
def __init__(self):
self.begin_take_photo = False
self.face_found = False
self.smile_detected = False
self.restart ... | [
"cv2.rectangle",
"numpy.copy",
"cv2.imwrite",
"cv2.flip",
"cv2.imshow",
"haar_cascade.detect_faces",
"datetime.datetime.now",
"cv2.destroyAllWindows",
"cv2.VideoCapture",
"sys.exit",
"haar_cascade.detect_mouth",
"cv2.waitKey",
"haar_cascade.detect_eyes"
] | [((3573, 3592), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (3589, 3592), False, 'import cv2\n'), ((645, 661), 'cv2.flip', 'cv2.flip', (['img', '(1)'], {}), '(img, 1)\n', (653, 661), False, 'import cv2\n'), ((687, 709), 'numpy.copy', 'np.copy', (['self.captured'], {}), '(self.captured)\n', (694, 709... |
from unittest import TestCase
from sublime_lib import ResourcePath
from package_util import TemporaryPackage
class TestTemporaryPackage(TestCase):
def test_temporary_package_name(self):
expected_resource_path = ResourcePath('Packages/TemporaryPackageTest')
expected_file_path = expected_resource_... | [
"sublime_lib.ResourcePath",
"package_util.TemporaryPackage"
] | [((227, 272), 'sublime_lib.ResourcePath', 'ResourcePath', (['"""Packages/TemporaryPackageTest"""'], {}), "('Packages/TemporaryPackageTest')\n", (239, 272), False, 'from sublime_lib import ResourcePath\n'), ((389, 411), 'package_util.TemporaryPackage', 'TemporaryPackage', (['name'], {}), '(name)\n', (405, 411), False, '... |
"""
Base functionality of meshed
"""
from collections import Counter
from dataclasses import dataclass, field
from functools import partial
from typing import Callable, MutableMapping, Iterable, Union, Sized, Sequence
from i2 import Sig, call_somewhat_forgivingly
from meshed.util import ValidationError, NameValidation... | [
"i2.Sig",
"meshed.util.mk_func_name",
"i2.call_somewhat_forgivingly",
"collections.Counter",
"meshed.util.NameValidationError",
"functools.partial",
"meshed.itools.add_edge",
"meshed.util.ValidationError",
"dataclasses.field"
] | [((7642, 7661), 'dataclasses.field', 'field', ([], {'default': 'None'}), '(default=None)\n', (7647, 7661), False, 'from dataclasses import dataclass, field\n'), ((7679, 7706), 'dataclasses.field', 'field', ([], {'default_factory': 'dict'}), '(default_factory=dict)\n', (7684, 7706), False, 'from dataclasses import datac... |
#!/usr/bin/env python3
"""Hangman game"""
import argparse
import io
import random
import re
import sys
# --------------------------------------------------
def get_args():
"""parse arguments"""
parser = argparse.ArgumentParser(
description='Hangman',
formatter_class=argparse.ArgumentDefaults... | [
"argparse.FileType",
"random.choice",
"argparse.ArgumentParser",
"re.match",
"random.seed"
] | [((215, 322), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Hangman"""', 'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), "(description='Hangman', formatter_class=argparse.\n ArgumentDefaultsHelpFormatter)\n", (238, 322), False, 'import argparse\n'), ((2396, 2418), 'ran... |
from flask import Flask, request, jsonify
from sqlalchemy import create_engine
app = Flask(__name__)
engine = create_engine("mysql+pymysql://root:admin@db:3306/mydb")
@app.route("/members", methods=["POST"])
def members():
body = request.json
with engine.connect() as connection:
connection.execute(... | [
"flask.jsonify",
"sqlalchemy.create_engine",
"flask.Flask"
] | [((87, 102), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (92, 102), False, 'from flask import Flask, request, jsonify\n'), ((112, 168), 'sqlalchemy.create_engine', 'create_engine', (['"""mysql+pymysql://root:admin@db:3306/mydb"""'], {}), "('mysql+pymysql://root:admin@db:3306/mydb')\n", (125, 168), False... |
# -*- encoding: utf-8 -*-
from . import FixtureTest
class AustraliaShieldTextPrefixesTest(FixtureTest):
def test_m(self):
import dsl
z, x, y = (16, 60295, 39334)
self.generate_fixtures(
dsl.is_in('AU', z, x, y),
# https://www.openstreetmap.org/way/170318728
... | [
"dsl.tile_diagonal",
"dsl.is_in",
"dsl.relation"
] | [((231, 255), 'dsl.is_in', 'dsl.is_in', (['"""AU"""', 'z', 'x', 'y'], {}), "('AU', z, x, y)\n", (240, 255), False, 'import dsl\n'), ((924, 1094), 'dsl.relation', 'dsl.relation', (['(1)', "{'addr:country': u'AU', 'addr:state': u'NSW', 'ref': u'M1', 'route':\n u'road', 'source': u'openstreetmap.org', 'type': u'route'}... |
from kubernetes_informers import Reflector, CoalescingQueue
from kubernetes_informers.reflector import Delta
import asyncio
import pytest
from kubernetes_asyncio import client
def make_pod(ns, name, rv):
return client.V1Pod(
metadata=client.V1ObjectMeta(namespace=ns, resource_version=rv, name=name),
)
... | [
"kubernetes_informers.Reflector",
"kubernetes_informers.CoalescingQueue",
"kubernetes_asyncio.client.V1ObjectMeta",
"kubernetes_asyncio.client.V1PodList"
] | [((1635, 1652), 'kubernetes_informers.CoalescingQueue', 'CoalescingQueue', ([], {}), '()\n', (1650, 1652), False, 'from kubernetes_informers import Reflector, CoalescingQueue\n'), ((1661, 1716), 'kubernetes_informers.Reflector', 'Reflector', (['q', 'fake_list_method', '"""ns"""'], {'resync_period': '(0.1)'}), "(q, fake... |
# cython: auto_pickle=False,embedsignature=True,always_allow_keywords=False
# -*- coding: utf-8 -*
"""
Datastructures to help externalization.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# There are a *lot* of fixme (XXX and the like) in this file.
... | [
"zope.interface.providedBy",
"zope.interface.classImplements",
"zope.component.getUtility",
"zope.schema.getValidationErrors",
"six.iteritems"
] | [((5448, 5542), 'zope.interface.classImplements', 'interface.classImplements', (['StandardInternalObjectExternalizer', 'IInternalObjectExternalizer'], {}), '(StandardInternalObjectExternalizer,\n IInternalObjectExternalizer)\n', (5473, 5542), False, 'from zope import interface\n'), ((14681, 14756), 'zope.interface.c... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from server import server_model_pb2 as server_dot_server__model__pb2
from server import server_pb2 as server_dot_server__pb2
class MruVServerServiceStub(object... | [
"grpc.unary_stream_rpc_method_handler",
"grpc.method_handlers_generic_handler",
"grpc.unary_unary_rpc_method_handler",
"grpc.experimental.unary_stream",
"grpc.experimental.unary_unary"
] | [((5640, 5734), 'grpc.method_handlers_generic_handler', 'grpc.method_handlers_generic_handler', (['"""mruv.server.MruVServerService"""', 'rpc_method_handlers'], {}), "('mruv.server.MruVServerService',\n rpc_method_handlers)\n", (5676, 5734), False, 'import grpc\n'), ((3974, 4200), 'grpc.unary_unary_rpc_method_handle... |
# Copyright (c) 2018 <NAME> & Company, Inc.
#
# 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 ag... | [
"json.loads",
"json.dumps",
"requests.Session",
"copy.deepcopy"
] | [((1252, 1270), 'requests.Session', 'requests.Session', ([], {}), '()\n', (1268, 1270), False, 'import requests\n'), ((1332, 1346), 'copy.deepcopy', 'deepcopy', (['URLS'], {}), '(URLS)\n', (1340, 1346), False, 'from copy import deepcopy\n'), ((2521, 2546), 'json.loads', 'json.loads', (['response.text'], {}), '(response... |
import logging
import time
from torch.utils.data import DataLoader
import torch.nn as nn
import torch.optim as optim
import torch.backends.cudnn as cudnn
import torch
import torch.nn.functional as functional
import numpy as np
from DTI import models, dataset, cli, utils, analyse
import os
device = torch.device('cuda:0... | [
"logging.getLogger",
"os.path.exists",
"logging.basicConfig",
"DTI.dataset.get_hcp_s1200",
"DTI.models.HARmodel",
"torch.nn.CrossEntropyLoss",
"DTI.utils.setup_seed",
"torch.load",
"numpy.append",
"torch.cuda.is_available",
"DTI.analyse.analyse_3class",
"DTI.cli.create_parser",
"torch.utils.... | [((381, 401), 'DTI.utils.setup_seed', 'utils.setup_seed', (['(18)'], {}), '(18)\n', (397, 401), False, 'from DTI import models, dataset, cli, utils, analyse\n'), ((419, 430), 'time.time', 'time.time', ([], {}), '()\n', (428, 430), False, 'import time\n'), ((615, 747), 'torch.utils.data.DataLoader', 'DataLoader', (['tra... |
from marshmallow import fields, validate
from marshmallow_enum import EnumField
from bigeye.models.base import ma
from bigeye.models.user import UserRoles
from bigeye.models.challenge import ChallengeDifficulty
class ChallengeCategorySchema(ma.Schema):
id = fields.Integer(dump_only=True)
name = fields.String... | [
"marshmallow.validate.URL",
"marshmallow.validate.Email",
"marshmallow.validate.Regexp",
"marshmallow_enum.EnumField",
"marshmallow.fields.Nested",
"marshmallow.fields.Integer",
"marshmallow.fields.String",
"marshmallow.fields.DateTime",
"marshmallow.fields.Boolean"
] | [((265, 295), 'marshmallow.fields.Integer', 'fields.Integer', ([], {'dump_only': '(True)'}), '(dump_only=True)\n', (279, 295), False, 'from marshmallow import fields, validate\n'), ((409, 439), 'marshmallow.fields.Integer', 'fields.Integer', ([], {'dump_only': '(True)'}), '(dump_only=True)\n', (423, 439), False, 'from ... |
import os
import pytest
from tradier_python import TradierAPI
from tradier_python.models import *
@pytest.fixture
def t():
token = os.environ["TRADIER_TOKEN"]
account_id = os.environ["TRADIER_ACCOUNT_ID"]
base_url = os.environ.get("TRADIER_BASE_URL")
return TradierAPI(token=token, default_account_id... | [
"os.environ.get",
"tradier_python.TradierAPI"
] | [((232, 266), 'os.environ.get', 'os.environ.get', (['"""TRADIER_BASE_URL"""'], {}), "('TRADIER_BASE_URL')\n", (246, 266), False, 'import os\n'), ((278, 351), 'tradier_python.TradierAPI', 'TradierAPI', ([], {'token': 'token', 'default_account_id': 'account_id', 'endpoint': 'base_url'}), '(token=token, default_account_id... |
import unittest
# O(1). Bit manipulation.
class Solution:
def hasAlternatingBits(self, n):
"""
:type n: int
:rtype: bool
"""
prev = n & 1
n >>= 1
while n:
if n & 1 ^ prev:
prev ^= 1
n >>= 1
else:
... | [
"unittest.main"
] | [((722, 737), 'unittest.main', 'unittest.main', ([], {}), '()\n', (735, 737), False, 'import unittest\n')] |
import matplotlib as mpl
import matplotlib.pyplot as plt
import networkx as nx
import sbadmin.convertGraph as convert
G = nx.generators.directed.random_k_out_graph(10, 3, 0.5)
pos = nx.layout.spring_layout(G)
node_sizes = [3 + 10 * i for i in range(len(G))]
M = G.number_of_edges()
edge_colors = range(2, M + 2)
edge_a... | [
"networkx.layout.spring_layout",
"matplotlib.pyplot.gca",
"sbadmin.convertGraph.cytoscape_data",
"matplotlib.pyplot.colorbar",
"matplotlib.collections.PatchCollection",
"networkx.draw_networkx_nodes",
"networkx.readwrite.json_graph.cytoscape_data",
"networkx.generators.directed.random_k_out_graph",
... | [((123, 176), 'networkx.generators.directed.random_k_out_graph', 'nx.generators.directed.random_k_out_graph', (['(10)', '(3)', '(0.5)'], {}), '(10, 3, 0.5)\n', (164, 176), True, 'import networkx as nx\n'), ((183, 209), 'networkx.layout.spring_layout', 'nx.layout.spring_layout', (['G'], {}), '(G)\n', (206, 209), True, '... |
import os # system()
def can_build(env, platform):
if platform == "x11":
has_pulse = os.system("pkg-config --exists libpulse-simple") == 0
has_alsa = os.system("pkg-config --exists alsa") == 0
return has_pulse or has_alsa
elif platform in ["windows", "osx", "iphone", "android"]:
... | [
"os.system"
] | [((100, 148), 'os.system', 'os.system', (['"""pkg-config --exists libpulse-simple"""'], {}), "('pkg-config --exists libpulse-simple')\n", (109, 148), False, 'import os\n'), ((173, 210), 'os.system', 'os.system', (['"""pkg-config --exists alsa"""'], {}), "('pkg-config --exists alsa')\n", (182, 210), False, 'import os\n'... |
from collections import namedtuple
import torch
import torch.nn as nn
from rlpyt.algos.dqn.dsr.dsr import DSR
from rlpyt.algos.utils import valid_from_done
from rlpyt.utils.tensor import select_at_indexes, valid_mean
OptInfo = namedtuple("OptInfo", ["dsrLoss", "dsrGradNorm", "tdAbsErr"])
class ActionDSR(DSR):
... | [
"collections.namedtuple",
"torch.mean",
"rlpyt.algos.utils.valid_from_done",
"torch.randint",
"rlpyt.utils.tensor.select_at_indexes",
"rlpyt.utils.tensor.valid_mean",
"torch.no_grad",
"torch.clamp",
"torch.where"
] | [((230, 291), 'collections.namedtuple', 'namedtuple', (['"""OptInfo"""', "['dsrLoss', 'dsrGradNorm', 'tdAbsErr']"], {}), "('OptInfo', ['dsrLoss', 'dsrGradNorm', 'tdAbsErr'])\n", (240, 291), False, 'from collections import namedtuple\n'), ((584, 599), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (597, 599), False... |
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
class UserCreationForm(UserCreationForm):
"""A form that creates a user."""
class Meta(UserCreationForm.Meta):
model = get_user_model()
fields = ('username', 'email')
| [
"django.contrib.auth.get_user_model"
] | [((240, 256), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (254, 256), False, 'from django.contrib.auth import get_user_model\n')] |
# coding=utf-8
def process_qq_history(path, skip_system=True, encoding="utf-8", strip=None, output_path=None):
"""
Process QQ chat history export text file to sentences.
:param path: Path to QQ history txt file.
:param skip_system: Skip system message if set.
:param encoding: Encoding of the tx... | [
"jieba.cut",
"jieba.posseg.cut",
"os.path.split",
"unicodedata.category",
"re.sub"
] | [((572, 591), 'os.path.split', 'os.path.split', (['path'], {}), '(path)\n', (585, 591), False, 'import os\n'), ((3715, 3734), 'os.path.split', 'os.path.split', (['path'], {}), '(path)\n', (3728, 3734), False, 'import os\n'), ((4796, 4813), 'jieba.posseg.cut', 'pseg.cut', (['content'], {}), '(content)\n', (4804, 4813), ... |
""" Copyright start
Copyright (C) 2008 - 2021 Fortinet Inc.
All rights reserved.
FORTINET CONFIDENTIAL & FORTINET PROPRIETARY SOURCE CODE
Copyright end """
import base64
import requests
from connectors.core.connector import ConnectorError, get_logger
logger = get_logger('riskiq-whoisiq')
class RiskIQWHOIS... | [
"connectors.core.connector.ConnectorError",
"connectors.core.connector.get_logger",
"requests.request"
] | [((272, 300), 'connectors.core.connector.get_logger', 'get_logger', (['"""riskiq-whoisiq"""'], {}), "('riskiq-whoisiq')\n", (282, 300), False, 'from connectors.core.connector import ConnectorError, get_logger\n'), ((1137, 1237), 'requests.request', 'requests.request', (['method', 'url'], {'params': 'params', 'data': 'd... |
import http.client
import urllib
import requests
from scripts.poc.poc_interface import PocInterface
class Structs2_45(PocInterface):
'''
Structs2 漏洞验证及利用实现
'''
def validate(self,url):
'''
验证指定URL是否存在Structs2 45漏洞
:param url: 需要验证的URL地址
:return: True-存在漏洞 False-不存在漏洞
... | [
"urllib.urlopen",
"requests.get",
"urllib.Request"
] | [((947, 981), 'requests.get', 'requests.get', (['url'], {'headers': 'headers'}), '(url, headers=headers)\n', (959, 981), False, 'import requests\n'), ((2539, 2575), 'urllib.Request', 'urllib.Request', (['url'], {'headers': 'headers'}), '(url, headers=headers)\n', (2553, 2575), False, 'import urllib\n'), ((2595, 2618), ... |
#!/usr/bin/env python3
'''
Continuously reads data on stdin until there is no more data. Records how many
bytes there were and how long it took to read them. Prints this information.
'''
import time
import sys
import threading
write_lock = threading.Lock()
thread_done = threading.Event()
def report(stop_ev, start_tim... | [
"threading.Event",
"threading.Lock",
"sys.stderr.flush",
"time.time"
] | [((241, 257), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (255, 257), False, 'import threading\n'), ((272, 289), 'threading.Event', 'threading.Event', ([], {}), '()\n', (287, 289), False, 'import threading\n'), ((863, 880), 'threading.Event', 'threading.Event', ([], {}), '()\n', (878, 880), False, 'import thr... |
# -*- coding: utf-8 -*-
# Aufgaben 6, 7, 20, 21, 24, 30, 34, 39, 38, 41, 43 <NAME>
# -----------------
# 43 detect language
# -----------------
import nltk, re
from nltk import word_tokenize
languages = ['Chickasaw', 'English', 'German_Deutsch', 'Greenlandic_Inuktikut', 'Hungarian_Magyar', 'Ibibio_Efik']
def word_f... | [
"nltk.corpus.udhr.words",
"re.findall",
"nltk.word_tokenize"
] | [((407, 426), 'nltk.word_tokenize', 'word_tokenize', (['text'], {}), '(text)\n', (420, 426), False, 'from nltk import word_tokenize\n'), ((597, 641), 'nltk.corpus.udhr.words', 'nltk.corpus.udhr.words', (["(language + '-Latin1')"], {}), "(language + '-Latin1')\n", (619, 641), False, 'import nltk, re\n'), ((976, 1002), '... |
from fastapi import APIRouter, Request
from starlette.status import HTTP_200_OK
from deciphon_api.api import dbs, hmms, jobs, prods, scans, sched, seqs
from deciphon_api.core.responses import PrettyJSONResponse
router = APIRouter()
router.include_router(dbs.router)
router.include_router(hmms.router)
router.include_r... | [
"fastapi.APIRouter",
"deciphon_api.core.responses.PrettyJSONResponse"
] | [((222, 233), 'fastapi.APIRouter', 'APIRouter', ([], {}), '()\n', (231, 233), False, 'from fastapi import APIRouter, Request\n'), ((805, 829), 'deciphon_api.core.responses.PrettyJSONResponse', 'PrettyJSONResponse', (['urls'], {}), '(urls)\n', (823, 829), False, 'from deciphon_api.core.responses import PrettyJSONRespons... |
import numpy as np
from io import BytesIO
import wave
import struct
from dcase_models.util.gui import encode_audio
#from .utils import save_model_weights,save_model_json, get_data_train, get_data_test
#from .utils import init_model, evaluate_model, load_scaler, save, load
#from .model import debugg_model, pr... | [
"dash_html_components.Button",
"dcase_models.util.files.save_pickle",
"numpy.array",
"plotly.graph_objects.layout.Title",
"dash_audio_components.DashAudioComponents",
"dash_html_components.Div",
"librosa.core.load",
"dash_html_components.Br",
"plotly.graph_objects.Scatter",
"numpy.argmin",
"plot... | [((1746, 1769), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""viridis"""'], {}), "('viridis')\n", (1758, 1769), True, 'import matplotlib.pyplot as plt\n'), ((4152, 4181), 'plotly.subplots.make_subplots', 'make_subplots', ([], {'rows': '(1)', 'cols': '(1)'}), '(rows=1, cols=1)\n', (4165, 4181), False, 'from plotly... |
import json
from flask import Flask, Response
from flask import render_template, request
from bson.json_util import dumps
from flask.ext.pymongo import PyMongo
app = Flask( __name__,
static_folder="view",
)
app.config['MONGO_DBNAME'] = 'cars_db'
mongo = PyMongo(app)
@app.route("/")
def home():
return... | [
"flask.render_template",
"flask.Flask",
"flask.request.get_json",
"flask.Response",
"flask.ext.pymongo.PyMongo",
"bson.json_util.dumps"
] | [((167, 204), 'flask.Flask', 'Flask', (['__name__'], {'static_folder': '"""view"""'}), "(__name__, static_folder='view')\n", (172, 204), False, 'from flask import Flask, Response\n'), ((268, 280), 'flask.ext.pymongo.PyMongo', 'PyMongo', (['app'], {}), '(app)\n', (275, 280), False, 'from flask.ext.pymongo import PyMongo... |
import urllib.request, urllib.parse, urllib.error
# http://www.py4e.com/code3/bs4.zip
# and unzip it in the same directory as this file
from urllib.request import urlopen
import re
from bs4 import BeautifulSoup
import ssl
import sqlite3
conn = sqlite3.connect('wiki2.sqlite')
cur = conn.cursor()
cur.executescript(... | [
"ssl.create_default_context",
"sqlite3.connect"
] | [((248, 279), 'sqlite3.connect', 'sqlite3.connect', (['"""wiki2.sqlite"""'], {}), "('wiki2.sqlite')\n", (263, 279), False, 'import sqlite3\n'), ((524, 552), 'ssl.create_default_context', 'ssl.create_default_context', ([], {}), '()\n', (550, 552), False, 'import ssl\n')] |
'''
NPSN Support Vector Regression Class
'''
import os
from joblib import dump, load
# Base model
from .base import BaseModel
# Import for SVR
from sklearn.multioutput import MultiOutputRegressor as MOR
from sklearn.metrics import mean_squared_error as sklmse
from sklearn.svm import NuSVR
# hyperopt imports
from hy... | [
"hyperopt.hp.quniform",
"os.getcwd",
"sklearn.metrics.mean_squared_error",
"hyperopt.hp.uniform",
"hyperopt.hp.choice",
"joblib.load",
"sklearn.svm.NuSVR",
"joblib.dump"
] | [((2136, 2162), 'sklearn.metrics.mean_squared_error', 'sklmse', (['y_te_fl', 'y_predict'], {}), '(y_te_fl, y_predict)\n', (2142, 2162), True, 'from sklearn.metrics import mean_squared_error as sklmse\n'), ((3870, 3898), 'joblib.dump', 'dump', (['pickle_dict', 'modelpath'], {}), '(pickle_dict, modelpath)\n', (3874, 3898... |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 22 09:00:08 2020
@author: SKD-HiTMAN
"""
import pandas as pd
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
ratings = pd.read_csv('../Dataset/MovieLens/ml-latest-small/ratings.csv')
songs = pd.read_csv('../Dataset/MovieLens/ml-la... | [
"pandas.DataFrame",
"pandas.merge",
"sklearn.metrics.pairwise.cosine_similarity",
"pandas.read_csv"
] | [((208, 271), 'pandas.read_csv', 'pd.read_csv', (['"""../Dataset/MovieLens/ml-latest-small/ratings.csv"""'], {}), "('../Dataset/MovieLens/ml-latest-small/ratings.csv')\n", (219, 271), True, 'import pandas as pd\n'), ((281, 367), 'pandas.read_csv', 'pd.read_csv', (['"""../Dataset/MovieLens/ml-latest-small/songs.csv"""']... |
import numpy as np
import matplotlib.pyplot as plt
# documentation
# https://matplotlib.org/3.1.3/api/pyplot_summary.html
# scatter plot
x = np.random.randint(100, size=(100))
y = np.random.randint(100, size=(100))
plt.scatter(x, y, c='tab:blue', label='stuff')
plt.legend(loc=2)
# plt.show()
# line plot
x = np.a... | [
"numpy.random.normal",
"matplotlib.pyplot.xticks",
"numpy.arange",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.array",
"numpy.random.randint",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.leg... | [((145, 177), 'numpy.random.randint', 'np.random.randint', (['(100)'], {'size': '(100)'}), '(100, size=100)\n', (162, 177), True, 'import numpy as np\n'), ((184, 216), 'numpy.random.randint', 'np.random.randint', (['(100)'], {'size': '(100)'}), '(100, size=100)\n', (201, 216), True, 'import numpy as np\n'), ((219, 265)... |
from . import core
import io
import re
import requests
import pytz
import time
import datetime as dt
import dateutil.parser as du
import numpy as np
import pandas as pd
from typing import Tuple, Dict, List, Union, ClassVar, Any, Optional, Type
import types
class ... | [
"datetime.datetime.utcfromtimestamp",
"requests.cookies.cookiejar_from_dict",
"dateutil.parser.isoparse",
"re.compile",
"time.sleep",
"requests.get",
"datetime.datetime.now",
"numpy.array",
"pandas.DataFrame",
"io.StringIO"
] | [((12645, 12704), 'requests.get', 'requests.get', (['"""https://finance.yahoo.com/quote/SPY/history"""'], {}), "('https://finance.yahoo.com/quote/SPY/history')\n", (12657, 12704), False, 'import requests\n'), ((12733, 12792), 'requests.cookies.cookiejar_from_dict', 'requests.cookies.cookiejar_from_dict', (["{'B': r.coo... |
import numpy as np
import matplotlib.pyplot as plt
from copy import deepcopy
from ..measure import ConditionedLognormalSampler
class ScalarImage:
"""
Class containing a scalar image.
"""
def __init__(self, height=1000, width=1000):
""" Instantiate scalar image with shape (<height>, <width>).... | [
"numpy.zeros",
"numpy.log",
"matplotlib.pyplot.subplots",
"copy.deepcopy"
] | [((1067, 1120), 'numpy.zeros', 'np.zeros', (['(self.height, self.width)'], {'dtype': 'np.float64'}), '((self.height, self.width), dtype=np.float64)\n', (1075, 1120), True, 'import numpy as np\n'), ((3047, 3059), 'copy.deepcopy', 'deepcopy', (['xy'], {}), '(xy)\n', (3055, 3059), False, 'from copy import deepcopy\n'), ((... |
from ...Renderer.Buffer import VertexBuffer, IndexBuffer, BufferLayout
from OpenGL.GL import glGenBuffers, glBufferData, glDeleteBuffers, glBindBuffer, glBufferSubData
from OpenGL.GL import GL_ARRAY_BUFFER, GL_STATIC_DRAW, GL_ELEMENT_ARRAY_BUFFER, GL_DYNAMIC_DRAW
import ctypes
import numpy as np
from multipledispatch... | [
"OpenGL.GL.glBufferData",
"OpenGL.GL.glGenBuffers",
"numpy.array",
"numpy.zeros",
"multipledispatch.dispatch",
"ctypes.c_void_p",
"OpenGL.GL.glBindBuffer",
"OpenGL.GL.glDeleteBuffers"
] | [((451, 465), 'multipledispatch.dispatch', 'dispatch', (['list'], {}), '(list)\n', (459, 465), False, 'from multipledispatch import dispatch\n'), ((815, 828), 'multipledispatch.dispatch', 'dispatch', (['int'], {}), '(int)\n', (823, 828), False, 'from multipledispatch import dispatch\n'), ((545, 581), 'numpy.array', 'np... |
"""Meter Parser Image Processing component and sensor."""
# Copyright 2021 <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... | [
"logging.getLogger",
"homeassistant.helpers.entity.generate_entity_id",
"voluptuous.Required",
"os.path.exists",
"traceback.format_exc",
"homeassistant.core.split_entity_id",
"os.makedirs",
"homeassistant.components.sensor.SensorEntityDescription",
"homeassistant.helpers.entity_registry.async_get",
... | [((3565, 3595), 'logging.getLogger', 'logging.getLogger', (['__package__'], {}), '(__package__)\n', (3582, 3595), False, 'import logging\n'), ((2482, 2510), 'voluptuous.Required', 'vol.Required', (['CONF_ENTITY_ID'], {}), '(CONF_ENTITY_ID)\n', (2494, 2510), True, 'import voluptuous as vol\n'), ((2553, 2576), 'voluptuou... |
from irf import estimate_exposure_time, build_exposure_map
import click
import fact.io as fio
import pandas as pd
from astroquery.skyview import SkyView
from astropy.wcs import WCS
from astropy.visualization import ImageNormalize, ZScaleInterval, AsinhStretch
import astropy.units as u
from astropy.coordinates import Sk... | [
"astropy.visualization.AsinhStretch",
"astroquery.skyview.SkyView.get_images",
"pandas.to_datetime",
"astropy.units.quantity_input",
"click.option",
"click.command",
"fact.io.read_data",
"matplotlib.pyplot.savefig",
"astropy.coordinates.SkyCoord.from_name",
"pandas.merge",
"irf.estimate_exposure... | [((363, 390), 'astropy.units.quantity_input', 'u.quantity_input', ([], {'fov': 'u.deg'}), '(fov=u.deg)\n', (379, 390), True, 'import astropy.units as u\n'), ((847, 862), 'click.command', 'click.command', ([], {}), '()\n', (860, 862), False, 'import click\n'), ((1057, 1167), 'click.option', 'click.option', (['"""-n"""',... |
""" Class to serialize data for multiprocessing.
Inspired by: https://github.com/openai/baselines/blob/master/baselines/common/vec_env/__init__.py
"""
import cloudpickle
import pickle
class CloudpickleWrapper(object):
""" Uses `cloudpickle` to serialize contents. """
def __init__(self, data):
self.d... | [
"cloudpickle.dumps",
"pickle.loads"
] | [((375, 400), 'cloudpickle.dumps', 'cloudpickle.dumps', (['self.x'], {}), '(self.x)\n', (392, 400), False, 'import cloudpickle\n'), ((456, 474), 'pickle.loads', 'pickle.loads', (['data'], {}), '(data)\n', (468, 474), False, 'import pickle\n')] |
import numpy as np
import cv2
from semantic_segmentation.data_structure.image_handler import ImageHandler
class Preprocessor:
def __init__(self, image_size):
self.image_size = image_size
self.min_height = 16
self.min_width = 16
self.max_height = 900
self.max_width = 900
... | [
"numpy.mean",
"numpy.reshape",
"numpy.ones",
"semantic_segmentation.data_structure.image_handler.ImageHandler",
"numpy.max",
"numpy.zeros",
"numpy.expand_dims",
"numpy.min",
"numpy.var"
] | [((389, 408), 'semantic_segmentation.data_structure.image_handler.ImageHandler', 'ImageHandler', (['image'], {}), '(image)\n', (401, 408), False, 'from semantic_segmentation.data_structure.image_handler import ImageHandler\n'), ((687, 701), 'numpy.mean', 'np.mean', (['image'], {}), '(image)\n', (694, 701), True, 'impor... |
import socket
import time
from tron import g, hub
from tron.Hub.Command.Decoders.ASCIICmdDecoder import ASCIICmdDecoder
from tron.Hub.Nub.Commanders import AuthStdinNub
from tron.Hub.Nub.Listeners import SocketListener
from tron.Hub.Reply.Encoders.ASCIIReplyEncoder import ASCIIReplyEncoder
name = 'TUI'
listenPort = ... | [
"tron.hub.findAcceptor",
"tron.Hub.Command.Decoders.ASCIICmdDecoder.ASCIICmdDecoder",
"tron.g.nubIDs.gimme",
"socket.getfqdn",
"tron.Hub.Nub.Commanders.AuthStdinNub",
"tron.hub.addCommander",
"time.sleep",
"tron.hub.addAcceptor",
"tron.Hub.Reply.Encoders.ASCIIReplyEncoder.ASCIIReplyEncoder",
"tron... | [((485, 501), 'tron.g.nubIDs.gimme', 'g.nubIDs.gimme', ([], {}), '()\n', (499, 501), False, 'from tron import g, hub\n'), ((853, 904), 'tron.Hub.Command.Decoders.ASCIICmdDecoder.ASCIICmdDecoder', 'ASCIICmdDecoder', ([], {'needCID': '(False)', 'EOL': "'\\r\\n'", 'debug': '(1)'}), "(needCID=False, EOL='\\r\\n', debug=1)\... |
from unittest import TestCase
from pathlib import Path
from src.markdown_converter import MarkdownConverter
class TestMarkdownHeader(TestCase):
def setUp(self):
self.converter = MarkdownConverter("test/dokuwiki_example.txt")
def test_acceptance_test_case(self):
# python 3.5 and up
e... | [
"src.markdown_converter.MarkdownConverter",
"pathlib.Path"
] | [((194, 240), 'src.markdown_converter.MarkdownConverter', 'MarkdownConverter', (['"""test/dokuwiki_example.txt"""'], {}), "('test/dokuwiki_example.txt')\n", (211, 240), False, 'from src.markdown_converter import MarkdownConverter\n'), ((330, 371), 'pathlib.Path', 'Path', (['"""test/expected_markdown_output.txt"""'], {}... |