code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import argparse
import json
import re
import subprocess
import sys
from time import sleep
from typing import Any
def run_command(cmd: str, print_all: bool = False) -> str:
# return subprocess.run([cmd], stdout=subprocess.PIPE, shell=True).stdout.decode(
# "utf-8"
# )
process = subprocess.Popen([cm... | [
"json.loads",
"argparse.ArgumentParser",
"subprocess.Popen",
"time.sleep",
"sys.exit",
"re.findall"
] | [((300, 359), 'subprocess.Popen', 'subprocess.Popen', (['[cmd]'], {'stdout': 'subprocess.PIPE', 'shell': '(True)'}), '([cmd], stdout=subprocess.PIPE, shell=True)\n', (316, 359), False, 'import subprocess\n'), ((810, 825), 'json.loads', 'json.loads', (['out'], {}), '(out)\n', (820, 825), False, 'import json\n'), ((1349,... |
# Copyright (c) <NAME>. All Rights Reserved.
import torch
import torch.nn as nn
from .backbones import get_backbone
BLOCKNAMES = {
"resnet": {
"stem": ["conv1", "bn1", "relu", "maxpool"],
"block1": ["layer1"],
"block2": ["layer2"],
"block3": ["layer3"],
"block4": ["layer4"... | [
"torch.nn.ModuleList",
"torch.nn.Identity",
"torch.nn.Dropout"
] | [((1561, 1576), 'torch.nn.ModuleList', 'nn.ModuleList', ([], {}), '()\n', (1574, 1576), True, 'import torch.nn as nn\n'), ((3190, 3227), 'torch.nn.Dropout', 'nn.Dropout', (["hparams['resnet_dropout']"], {}), "(hparams['resnet_dropout'])\n", (3200, 3227), True, 'import torch.nn as nn\n'), ((3269, 3282), 'torch.nn.Identi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup, find_packages
except:
from distutils.core import setup, find_packages
setup(
name='yaml-resume',
version='0.0.1',
description='Generates multiple resume/CV formats from a single YAML source.',
long_description=''.... | [
"distutils.core.find_packages"
] | [((470, 485), 'distutils.core.find_packages', 'find_packages', ([], {}), '()\n', (483, 485), False, 'from distutils.core import setup, find_packages\n')] |
#
# Copyright (c) 2018 ISP RAS (http://www.ispras.ru)
# Ivannikov Institute for System Programming of the Russian Academy of Sciences
#
# 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
#
# h... | [
"core.vtg.emg.processGenerator.linuxModule.interface.Resource",
"core.vtg.emg.common.get_conf_property"
] | [((1668, 1738), 'core.vtg.emg.common.get_conf_property', 'get_conf_property', (['collection.conf', '"""generate new resource interfaces"""'], {}), "(collection.conf, 'generate new resource interfaces')\n", (1685, 1738), False, 'from core.vtg.emg.common import get_conf_property\n'), ((3613, 3643), 'core.vtg.emg.processG... |
import re
email_pattern: 'Pattern' = re.compile(r'^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w+$')
| [
"re.compile"
] | [((39, 94), 're.compile', 're.compile', (['"""^[a-z0-9]+[\\\\._]?[a-z0-9]+[@]\\\\w+[.]\\\\w+$"""'], {}), "('^[a-z0-9]+[\\\\._]?[a-z0-9]+[@]\\\\w+[.]\\\\w+$')\n", (49, 94), False, 'import re\n')] |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-02-03 19:43
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('datapoint', '0002_auto_20160203_1929'),... | [
"datetime.datetime",
"django.db.models.TextField"
] | [((714, 742), 'django.db.models.TextField', 'models.TextField', ([], {'blank': '(True)'}), '(blank=True)\n', (730, 742), False, 'from django.db import migrations, models\n'), ((492, 553), 'datetime.datetime', 'datetime.datetime', (['(2016)', '(2)', '(3)', '(19)', '(43)', '(23)', '(995365)'], {'tzinfo': 'utc'}), '(2016,... |
from keras.models import load_model
import numpy as np
import cv2
import pickle
from image_segmentation import segment_image
from neural_network import resize_to_fit
MODEL_FILENAME = "captcha_model.hdf5"
MODEL_LABELS_FILENAME = "model_labels.dat"
def solve_captcha(image):
# Load up the model labels
with open... | [
"cv2.rectangle",
"cv2.merge",
"keras.models.load_model",
"pickle.load",
"cv2.putText",
"numpy.expand_dims",
"image_segmentation.segment_image",
"neural_network.resize_to_fit"
] | [((429, 455), 'keras.models.load_model', 'load_model', (['MODEL_FILENAME'], {}), '(MODEL_FILENAME)\n', (439, 455), False, 'from keras.models import load_model\n'), ((520, 544), 'image_segmentation.segment_image', 'segment_image', (['image', '(-1)'], {}), '(image, -1)\n', (533, 544), False, 'from image_segmentation impo... |
import wx
app = wx.App(False)
frame = wx.Frame(None, wx.ID_ANY, "Hello, World")
frame.Show(True)
app.MainLoop()
| [
"wx.Frame",
"wx.App"
] | [((17, 30), 'wx.App', 'wx.App', (['(False)'], {}), '(False)\n', (23, 30), False, 'import wx\n'), ((39, 80), 'wx.Frame', 'wx.Frame', (['None', 'wx.ID_ANY', '"""Hello, World"""'], {}), "(None, wx.ID_ANY, 'Hello, World')\n", (47, 80), False, 'import wx\n')] |
import matplotlib.pyplot as plt
def apply():
"""Apply all MPL settings
"""
# print(plt.style.available)
# plt.style.use('seaborn-paper')
plt.style.use('seaborn-notebook')
plt.rcParams['figure.max_open_warning'] = 1000
plt.rcParams['figure.figsize'] = (12, 6)
| [
"matplotlib.pyplot.style.use"
] | [((161, 194), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""seaborn-notebook"""'], {}), "('seaborn-notebook')\n", (174, 194), True, 'import matplotlib.pyplot as plt\n')] |
#!/usr/bin/env python3
import discord, configparser, random, re, requests, random
from time import sleep
class InvalidDieException(Exception):
def __init__(self, die, error='invalid'):
self.die = die
self.error = error
def __str__(self):
if self.error == 'too many die':
retu... | [
"random.choice",
"configparser.ConfigParser",
"re.match",
"requests.get",
"time.sleep",
"discord.Client",
"random.randint"
] | [((712, 739), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (737, 739), False, 'import discord, configparser, random, re, requests, random\n'), ((3099, 3115), 'discord.Client', 'discord.Client', ([], {}), '()\n', (3113, 3115), False, 'import discord, configparser, random, re, requests, ran... |
from bs4 import BeautifulSoup as bs
import threading
import time
import numpy as np
import sys
from io import StringIO
import scrapeconfig as cng
import consoleconfig as ccng
import os
def print_html(html_test):
'''To print html containers returned by beautifulsoup4'''
try:
strhtml = st... | [
"threading.activeCount",
"time.sleep",
"numpy.random.randint",
"threading.Thread",
"sys.stdout.flush",
"sys.stdout.write"
] | [((820, 845), 'sys.stdout.write', 'sys.stdout.write', (['basemsg'], {}), '(basemsg)\n', (836, 845), False, 'import sys\n'), ((1388, 1433), 'sys.stdout.write', 'sys.stdout.write', (["f'\\r{space * basemsglen}\\r'"], {}), "(f'\\r{space * basemsglen}\\r')\n", (1404, 1433), False, 'import sys\n'), ((1441, 1478), 'sys.stdou... |
from PIL import Image
import random
newImage = []
width=200
height=200
for i in range(0,width,1):
for j in range(0,height,1):
newImage.append((random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
newIm = Image.new('RGB', (width, height))
newIm.putdata(newImage)
newIm.show()
| [
"PIL.Image.new",
"random.randint"
] | [((237, 270), 'PIL.Image.new', 'Image.new', (['"""RGB"""', '(width, height)'], {}), "('RGB', (width, height))\n", (246, 270), False, 'from PIL import Image\n'), ((156, 178), 'random.randint', 'random.randint', (['(0)', '(255)'], {}), '(0, 255)\n', (170, 178), False, 'import random\n'), ((180, 202), 'random.randint', 'r... |
from xgboost import XGBClassifier
class SimpleModel():
def __init__(self):
self.model = XGBClassifier()
def fit(self, x, y, val_x, val_y):
eval_set = [(val_x,val_y)]
self.model.fit(x, y, early_stopping_rounds=10, eval_metric="logloss", eval_set=eval_set, verbose=True)
def... | [
"xgboost.XGBClassifier"
] | [((110, 125), 'xgboost.XGBClassifier', 'XGBClassifier', ([], {}), '()\n', (123, 125), False, 'from xgboost import XGBClassifier\n')] |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
=================================================
@Project :span-aste
@IDE :PyCharm
@Author :<NAME>
@Date :2022/1/19 9:10
@Desc :
==================================================
"""
import argparse
import torch
from torch.utils.data import DataLoader
fr... | [
"torch.manual_seed",
"utils.dataset.CustomDataset",
"models.model.SpanAsteModel",
"argparse.ArgumentParser",
"torch.load",
"torch.cuda.manual_seed",
"torch.cuda.is_available",
"torch.utils.data.DataLoader",
"models.tokenizers.tokenizer.BasicTokenizer",
"trainer.SpanAsteTrainer",
"models.embeddin... | [((751, 774), 'torch.manual_seed', 'torch.manual_seed', (['SEED'], {}), '(SEED)\n', (768, 774), False, 'import torch\n'), ((775, 803), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['SEED'], {}), '(SEED)\n', (797, 803), False, 'import torch\n'), ((814, 839), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ... |
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free... | [
"django.contrib.gis.db.models.CharField",
"django.contrib.gis.db.models.IntegerField",
"django.contrib.gis.db.models.GeoManager",
"django.contrib.gis.db.models.MultiPolygonField",
"django.contrib.gis.db.models.FloatField",
"django.contrib.gis.db.models.DateField"
] | [((658, 707), 'django.contrib.gis.db.models.CharField', 'models.CharField', ([], {'primary_key': '(True)', 'max_length': '(-1)'}), '(primary_key=True, max_length=-1)\n', (674, 707), False, 'from django.contrib.gis.db import models\n'), ((719, 777), 'django.contrib.gis.db.models.MultiPolygonField', 'models.MultiPolygonF... |
# Copyright 2018 Deep Air. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | [
"os.path.splitext",
"os.path.basename",
"json.load",
"json.dump",
"os.remove"
] | [((1537, 1549), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1546, 1549), False, 'import json\n'), ((1573, 1589), 'os.path.basename', 'basename', (['infile'], {}), '(infile)\n', (1581, 1589), False, 'from os.path import basename\n'), ((1632, 1660), 'json.dump', 'json.dump', (['data', 'f'], {'indent': '(2)'}), '(dat... |
# Generated by Django 3.1.1 on 2020-09-25 11:37
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('posts', '0002_post_likes'),
]
operations = [
... | [
"django.db.migrations.swappable_dependency",
"django.db.models.ManyToManyField"
] | [((194, 251), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (225, 251), False, 'from django.db import migrations, models\n'), ((424, 510), 'django.db.models.ManyToManyField', 'models.ManyToManyField', ([], {'related_na... |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(context='talk')
palette = sns.color_palette()
beta = 1
landa = 1./beta
reps = 25
pois = np.random.exponential(beta, reps)
pois = pois.cumsum()
psra = np.arange(reps)*beta + np.random.exponential(beta, reps) - landa
psra.sort()
f, ax =... | [
"seaborn.set",
"matplotlib.pyplot.savefig",
"seaborn.color_palette",
"numpy.random.exponential",
"numpy.zeros",
"matplotlib.pyplot.subplots",
"numpy.arange"
] | [((74, 97), 'seaborn.set', 'sns.set', ([], {'context': '"""talk"""'}), "(context='talk')\n", (81, 97), True, 'import seaborn as sns\n'), ((108, 127), 'seaborn.color_palette', 'sns.color_palette', ([], {}), '()\n', (125, 127), True, 'import seaborn as sns\n'), ((172, 205), 'numpy.random.exponential', 'np.random.exponent... |
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.12
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info >= (2, 7, 0):
def swig_im... | [
"_modulated.OverSampledDFTAnalysisBankPtr_name",
"_modulated.PerfectReconstructionFFTAnalysisBankPtr_current",
"_modulated.new_OverSampledDFTAnalysisBankPtr",
"_modulated.DelayFeaturePtr___deref__",
"_modulated.NormalFFTAnalysisBankPtr___iter__",
"_modulated.design_f",
"_modulated.PerfectReconstructionF... | [((16883, 16913), '_modulated.design_f', '_modulated.design_f', (['v', 'params'], {}), '(v, params)\n', (16902, 16913), False, 'import _modulated\n'), ((16987, 17022), '_modulated.design_df', '_modulated.design_df', (['v', 'params', 'df'], {}), '(v, params, df)\n', (17007, 17022), False, 'import _modulated\n'), ((17102... |
"""
SunPy
=====
An open-source Python library for Solar Physics data analysis.
Web Links
---------
Homepage: http://sunpy.org
Documentation: http://docs.sunpy.org/en/stable/
"""
from __future__ import absolute_import
try:
from .version import version as __version__
except ImportError:
__version__ = ''
try:
... | [
"os.path.dirname",
"sunpy.util.config.load_config"
] | [((670, 683), 'sunpy.util.config.load_config', 'load_config', ([], {}), '()\n', (681, 683), False, 'from sunpy.util.config import load_config, print_config\n'), ((607, 632), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (622, 632), False, 'import os\n')] |
import classy.datasets
from .Struct import Struct
import numpy as np
from numpy import sqrt,sum,exp,pi,min,max,linspace
def normal(x,mu,sd):
return 1.0/sqrt(2*pi*sd**2)*exp(-(x-mu)**2/(2*sd**2))
def overlap(means_,covars_):
# http://en.wikipedia.org/wiki/Bhattacharyya_distance
# overlap is a dot product
... | [
"numpy.sqrt",
"numpy.exp",
"numpy.array",
"numpy.linspace",
"numpy.min",
"sklearn.mixture.GMM"
] | [((365, 396), 'numpy.min', 'min', (['[m1 - 4 * s1, m2 - 4 * s2]'], {}), '([m1 - 4 * s1, m2 - 4 * s2])\n', (368, 396), False, 'from numpy import sqrt, sum, exp, pi, min, max, linspace\n'), ((397, 428), 'numpy.min', 'min', (['[m1 + 4 * s1, m2 + 4 * s2]'], {}), '([m1 + 4 * s1, m2 + 4 * s2])\n', (400, 428), False, 'from nu... |
"""
Setup script for the Gimbal package
"""
from setuptools import setup
from setuptools import find_packages
def readme():
"""Returns the contents of the README without the header image."""
header = '======\nGimbal\n======\n'
with open('README.rst', 'r') as f:
f.readline()
return header +... | [
"setuptools.find_packages"
] | [((1020, 1035), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (1033, 1035), False, 'from setuptools import find_packages\n')] |
import pandas as pd
import numpy as np
import sys
import matplotlib.pyplot as plt
import seaborn as sns
def plot_conservation(out_path):
"""
Plotting the fraction of conserved binding sites for Brn2, Ebf2 and
Onecut2, based on multiGPS and edgeR results from Aydin et al., 2019
(Nature Neurosciece: PMI... | [
"pandas.read_csv",
"matplotlib.pyplot.ylabel",
"seaborn.set_style",
"numpy.array",
"seaborn.violinplot",
"seaborn.despine",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.scatter",
"pandas.DataFrame",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.savefig",
"seaborn... | [((589, 687), 'pandas.DataFrame', 'pd.DataFrame', (["[['shared', 6776], ['iA>iN', 2432], ['iN>iA', 1242]]"], {'columns': "['category', '#']"}), "([['shared', 6776], ['iA>iN', 2432], ['iN>iA', 1242]], columns=\n ['category', '#'])\n", (601, 687), True, 'import pandas as pd\n'), ((774, 873), 'pandas.DataFrame', 'pd.Da... |
import pyperclip
import unittest
from credential import Credential
class TestCredentials(unittest.TestCase):
def setUp(self):
'''
function to run before each test
'''
self.new_credential=Credential("Instagram","mimoh","<PASSWORD>")
def test_init(self):
'''
... | [
"unittest.main",
"credential.Credential.credential_exists",
"credential.Credential",
"credential.Credential.display_credentials"
] | [((1904, 1919), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1917, 1919), False, 'import unittest\n'), ((223, 269), 'credential.Credential', 'Credential', (['"""Instagram"""', '"""mimoh"""', '"""<PASSWORD>"""'], {}), "('Instagram', 'mimoh', '<PASSWORD>')\n", (233, 269), False, 'from credential import Credential... |
from kektrade.exceptions import UnsupportedExchange
from kektrade.exchange.backtest_inverse import BacktestInverse
from kektrade.exchange.backtest_linear import BacktestLinear
from kektrade.exchange.dryrun_inverse import DryrunInverse
from kektrade.exchange.dryrun_linear import DryrunLinear
from kektrade.misc import E... | [
"kektrade.exchange.backtest_linear.BacktestLinear",
"kektrade.exceptions.UnsupportedExchange",
"kektrade.exchange.dryrun_inverse.DryrunInverse",
"kektrade.exchange.dryrun_linear.DryrunLinear",
"kektrade.exchange.backtest_inverse.BacktestInverse"
] | [((970, 987), 'kektrade.exchange.backtest_inverse.BacktestInverse', 'BacktestInverse', ([], {}), '()\n', (985, 987), False, 'from kektrade.exchange.backtest_inverse import BacktestInverse\n'), ((1065, 1081), 'kektrade.exchange.backtest_linear.BacktestLinear', 'BacktestLinear', ([], {}), '()\n', (1079, 1081), False, 'fr... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-02-03 14:10
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('web', '0010_auto_20160203_1406'),
]
operations = [
migrations.RenameField(
... | [
"django.db.migrations.RenameField"
] | [((287, 382), 'django.db.migrations.RenameField', 'migrations.RenameField', ([], {'model_name': '"""resource"""', 'old_name': '"""event_date"""', 'new_name': '"""event_time"""'}), "(model_name='resource', old_name='event_date',\n new_name='event_time')\n", (309, 382), False, 'from django.db import migrations\n')] |
"""
refer to https://github.com/jfzhang95/pytorch-deeplab-xception/blob/master/utils/metrics.py
"""
import numpy as np
__all__ = ['SegmentationMetric']
"""
confusionMetric
P\L P N
P TP FP
N FN TN
"""
class SegmentationMetric(object):
def __init__(self, numClass):
self.numClass = n... | [
"numpy.diag",
"numpy.array",
"numpy.zeros",
"numpy.nanmean",
"numpy.sum",
"numpy.bincount"
] | [((2630, 2658), 'numpy.array', 'np.array', (['[0, 0, 1, 1, 2, 2]'], {}), '([0, 0, 1, 1, 2, 2])\n', (2638, 2658), True, 'import numpy as np\n'), ((2674, 2702), 'numpy.array', 'np.array', (['[0, 0, 1, 1, 2, 2]'], {}), '([0, 0, 1, 1, 2, 2])\n', (2682, 2702), True, 'import numpy as np\n'), ((359, 389), 'numpy.zeros', 'np.z... |
from app import app
from flask_socketio import SocketIO
from flask_failsafe import failsafe
socketio = SocketIO(app)
@failsafe
def create_app():
return app
import eventlet
eventlet.monkey_patch()
if __name__ == '__main__':
socketio.run(create_app(), debug=True, use_reloader=True, port=app.config['PORT']) | [
"flask_socketio.SocketIO",
"eventlet.monkey_patch"
] | [((103, 116), 'flask_socketio.SocketIO', 'SocketIO', (['app'], {}), '(app)\n', (111, 116), False, 'from flask_socketio import SocketIO\n'), ((178, 201), 'eventlet.monkey_patch', 'eventlet.monkey_patch', ([], {}), '()\n', (199, 201), False, 'import eventlet\n')] |
import orjson
import pytest
from faker import Faker
from restapi.env import Env
from restapi.services.authentication import BaseAuthentication
from restapi.tests import API_URI, AUTH_URI, BaseTests, FlaskClient
from restapi.utilities.logs import Events, log
class TestApp(BaseTests):
def test_admin_groups(self, c... | [
"pytest.fail",
"restapi.env.Env.get_bool",
"restapi.utilities.logs.log.warning",
"orjson.dumps"
] | [((461, 502), 'restapi.utilities.logs.log.warning', 'log.warning', (['"""Skipping admin/users tests"""'], {}), "('Skipping admin/users tests')\n", (472, 502), False, 'from restapi.utilities.logs import Events, log\n'), ((1667, 1697), 'pytest.fail', 'pytest.fail', (['"""Group not found"""'], {}), "('Group not found')\n"... |
import re
from collections import defaultdict
def bitand(x, y):
return x & y
def bitor(x, y):
return x | y
def lshift(x, y):
return x << y
def rshift(x, y):
return x >> y
def bitnot(x):
return x ^ 65535
BIN_OPERATORS = {"AND": bitand, "OR": bitor, "LSHIFT": lshift, "RSHIFT": rshift}
UN_O... | [
"collections.defaultdict",
"re.search"
] | [((2304, 2326), 'collections.defaultdict', 'defaultdict', (['Container'], {}), '(Container)\n', (2315, 2326), False, 'from collections import defaultdict\n'), ((3076, 3098), 'collections.defaultdict', 'defaultdict', (['Container'], {}), '(Container)\n', (3087, 3098), False, 'from collections import defaultdict\n'), ((3... |
from django.shortcuts import render,redirect
from django.http import JsonResponse
from .models import *
from django.views import View
from django.db.models import Q
from django.forms import model_to_dict
from django.contrib.auth import get_user_model
# Create your views here.
from .models import *
from .forms import *
... | [
"django.shortcuts.render",
"django.http.JsonResponse",
"ajax_datatable.views.AjaxDatatableView.render_row_tools_column_def",
"django.shortcuts.redirect",
"django.db.models.Q",
"django.forms.model_to_dict"
] | [((404, 432), 'django.shortcuts.render', 'render', (['request', '"""home.html"""'], {}), "(request, 'home.html')\n", (410, 432), False, 'from django.shortcuts import render, redirect\n'), ((18501, 18551), 'django.shortcuts.render', 'render', (['request', '"""po/po_print_input.html"""', 'context'], {}), "(request, 'po/p... |
'''
@inproceedings{golestaneh2017spatially,
title={Spatially-Varying Blur Detection Based on Multiscale Fused and Sorted Transform Coefficients of Gradient Magnitudes},
author={<NAME> and Karam, <NAME>},
booktitle={Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition},
year={2017}
}
'''... | [
"numpy.sqrt",
"numpy.hstack",
"numpy.array",
"copy.deepcopy",
"numpy.multiply",
"numpy.where",
"numpy.diff",
"numpy.max",
"numpy.linspace",
"numpy.matmul",
"skimage.morphology.square",
"cv2.resize",
"cv2.GaussianBlur",
"numpy.shape",
"numpy.transpose",
"numpy.int",
"numpy.median",
... | [((2361, 2424), 'cv2.Sobel', 'cv2.Sobel', (['img', 'cv2.CV_64F', '(1)', '(0)'], {'borderType': 'cv2.BORDER_REFLECT'}), '(img, cv2.CV_64F, 1, 0, borderType=cv2.BORDER_REFLECT)\n', (2370, 2424), False, 'import cv2\n'), ((2470, 2533), 'cv2.Sobel', 'cv2.Sobel', (['img', 'cv2.CV_64F', '(0)', '(1)'], {'borderType': 'cv2.BORD... |
import os
from rlib.streamio import open_file_as_stream
from rlib.string_stream import StringStream
from som.compiler.class_generation_context import ClassGenerationContext
from som.interp_type import is_ast_interpreter
if is_ast_interpreter():
from som.compiler.ast.parser import Parser
else:
from som.compile... | [
"som.vm.universe.error_println",
"som.interp_type.is_ast_interpreter",
"som.compiler.bc.parser.Parser",
"som.compiler.class_generation_context.ClassGenerationContext",
"rlib.string_stream.StringStream",
"rlib.streamio.open_file_as_stream"
] | [((225, 245), 'som.interp_type.is_ast_interpreter', 'is_ast_interpreter', ([], {}), '()\n', (243, 245), False, 'from som.interp_type import is_ast_interpreter\n'), ((1320, 1352), 'som.compiler.class_generation_context.ClassGenerationContext', 'ClassGenerationContext', (['universe'], {}), '(universe)\n', (1342, 1352), F... |
import matplotlib.pyplot as plt
import matplotlib.axes
class PlotCreator:
"creates a plot of experiment results"
def __init__(self):
"""initialize
basex is the logarithm base scale of the x axis
basey is the logarithm base scale of the y axis
default is linear axes
""... | [
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend"
] | [((1364, 1382), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['xlabel'], {}), '(xlabel)\n', (1374, 1382), True, 'import matplotlib.pyplot as plt\n'), ((1391, 1409), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['ylabel'], {}), '(ylabel)\n', (1401, 1409), True, 'import matplotlib.pyplot as plt\n'), ((1419, 1431), 'matplotli... |
#! /usr/bin/env python3
"""A module which provides a unified CLI to all the functionality.
This module serves as a single entry point for a user. It exposes a CLI
which can be use to call the different commands and set their properties.
This CLI replaces `__main__.py` files scattered around the project with
a single,... | [
"click.Choice",
"evacsim.bench.BenchResults.for_benchfile",
"click.group",
"click.option",
"evacsim.expansion.plan_evacuation",
"pathlib.Path",
"click.File",
"evacsim.grid.start",
"evacsim.bench.parse_benchfile",
"evacsim.lcmae.plan_evacuation",
"click.Path"
] | [((811, 824), 'click.group', 'click.group', ([], {}), '()\n', (822, 824), False, 'import click\n'), ((1039, 1153), 'click.option', 'click.option', (['"""--visualize/--no-visualize"""'], {'default': '(False)', 'help': '"""Start visualization after creating the plan"""'}), "('--visualize/--no-visualize', default=False, h... |
#!/usr/bin/env python3
# Copyright 2016 <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 ... | [
"potty_oh.common.get_cmd_line_parser",
"potty_oh.common.ParserArguments.tempo",
"potty_oh.common.ParserArguments.filename",
"potty_oh.waveform.Waveform",
"potty_oh.common.call_main",
"potty_oh.common.ParserArguments.set_defaults",
"potty_oh.signal_generator.Generator",
"potty_oh.waveform.quarter_note_... | [((1528, 1568), 'potty_oh.common.get_cmd_line_parser', 'get_cmd_line_parser', ([], {'description': '__doc__'}), '(description=__doc__)\n', (1547, 1568), False, 'from potty_oh.common import get_cmd_line_parser\n'), ((1573, 1605), 'potty_oh.common.ParserArguments.filename', 'ParserArguments.filename', (['parser'], {}), '... |
from flask import Blueprint
jobs_bp = Blueprint("jobs", __name__)
from demo.api.jobs import views
| [
"flask.Blueprint"
] | [((39, 66), 'flask.Blueprint', 'Blueprint', (['"""jobs"""', '__name__'], {}), "('jobs', __name__)\n", (48, 66), False, 'from flask import Blueprint\n')] |
"""search.py
인자값을 전달한 키워드 기반으로 상위 n개 링크
웹 브라우저 실행"""
import sys
import requests, webbrowser, bs4
URLS = {
'google': 'https://google.com/search?q=',
'duckduckgo': 'https://duckduckgo.com/?q='
}
def parse_args() -> list:
if len(sys.argv) < 2:
print(f'python {__file__} <search query>')
sys.... | [
"bs4.BeautifulSoup",
"requests.get",
"sys.exit"
] | [((572, 618), 'requests.get', 'requests.get', (['f"""{url}{query}"""'], {'headers': 'headers'}), "(f'{url}{query}', headers=headers)\n", (584, 618), False, 'import requests, webbrowser, bs4\n'), ((706, 742), 'bs4.BeautifulSoup', 'bs4.BeautifulSoup', (['resp.text', '"""lxml"""'], {}), "(resp.text, 'lxml')\n", (723, 742)... |
"""
This module contains all the functions needed for extracting satellite-derived
shorelines (SDS)
Author: <NAME>, Water Research Laboratory, University of New South Wales
"""
# load modules
import os
import numpy as np
import matplotlib.pyplot as plt
import pdb
# image processing modules
import skimage.filters as... | [
"coastsat.SDS_tools.get_filepath",
"skimage.filters.threshold_otsu",
"numpy.array",
"coastsat.SDS_preprocess.preprocess_single",
"coastsat.SDS_tools.merge_output",
"numpy.linalg.norm",
"numpy.nanmin",
"matplotlib.lines.Line2D",
"numpy.arange",
"skimage.morphology.binary_dilation",
"os.path.exist... | [((874, 897), 'numpy.seterr', 'np.seterr', ([], {'all': '"""ignore"""'}), "(all='ignore')\n", (883, 897), True, 'import numpy as np\n'), ((3131, 3194), 'os.path.join', 'os.path.join', (['filepath_data', 'sitename', '"""jpg_files"""', '"""detection"""'], {}), "(filepath_data, sitename, 'jpg_files', 'detection')\n", (314... |
from django.db import models
from taggit.models import TagBase, ItemBase, GenericTaggedItemBase
from taggit.managers import TaggableManager
from treebeard.mp_tree import MP_Node
class Site(models.Model):
slug = models.SlugField(max_length=250, unique=True)
url = models.CharField(max_length=2083)
def __st... | [
"django.db.models.ForeignKey",
"django.db.models.BooleanField",
"taggit.managers.TaggableManager",
"django.db.models.SlugField",
"django.db.models.DateTimeField",
"django.db.models.CharField"
] | [((217, 262), 'django.db.models.SlugField', 'models.SlugField', ([], {'max_length': '(250)', 'unique': '(True)'}), '(max_length=250, unique=True)\n', (233, 262), False, 'from django.db import models\n'), ((273, 306), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(2083)'}), '(max_length=2083)\n'... |
"""
Bosons.
Package:
RoadNarrows elemenpy package.
File:
boson.py
Link:
https://github.com/roadnarrows-robotics/
Copyright:
(c) 2019. RoadNarrows LLC
http://www.roadnarrows.com
All Rights Reserved
License:
MIT
"""
from copy import copy
from enum import Enum
from elemenpy.core.common import (isderive... | [
"elemenpy.core.format.default_encoder",
"elemenpy.sm.electriccharge.ElectricCharge",
"elemenpy.sm.colorcharge.ColorCharge",
"elemenpy.sm.spin.SpinQuantumNumber",
"elemenpy.core.prettyprint.print2cols",
"elemenpy.sm.standardmodel.SubatomicParticle.print_state",
"tests.utboson.utmain",
"elemenpy.core.co... | [((4312, 4341), 'elemenpy.core.format.default_encoder', 'default_encoder', (['"""$sm(gamma)"""'], {}), "('$sm(gamma)')\n", (4327, 4341), False, 'from elemenpy.core.format import Format, default_encoder\n'), ((4378, 4395), 'elemenpy.sm.electriccharge.ElectricCharge', 'ElectricCharge', (['(0)'], {}), '(0)\n', (4392, 4395... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File name: tool_func.py
"""
Created on Thu Apr 23 17:39:40 2020
@author: Neo(<EMAIL>)
Some tool functions. The comment will be added when I am free.
"""
from myprogs.vsh.vsh_fit import rotgli_fit_4_table
from myprogs.catalog.pos_diff import radio_cat_diff_calc
from ... | [
"numpy.mean",
"numpy.random.random_sample",
"astropy.table.Table",
"numpy.hstack",
"astropy.stats.sigma_clip",
"numpy.random.random",
"numpy.log",
"myprogs.vsh.vsh_fit.rotgli_fit_4_table",
"numpy.exp",
"numpy.empty",
"numpy.vstack",
"numpy.concatenate",
"numpy.std",
"numpy.arange"
] | [((1757, 1799), 'myprogs.vsh.vsh_fit.rotgli_fit_4_table', 'rotgli_fit_4_table', (['pos_oft'], {'verbose': '(False)'}), '(pos_oft, verbose=False)\n', (1775, 1799), False, 'from myprogs.vsh.vsh_fit import rotgli_fit_4_table\n'), ((2098, 2122), 'numpy.hstack', 'np.hstack', (['(pmt, [g, w])'], {}), '((pmt, [g, w]))\n', (21... |
# | Copyright 2017 Karlsruhe Institute of Technology
# |
# | 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 ... | [
"get_file_list.get_file_list",
"ast.NodeVisitor.__init__",
"logging.warning",
"ast.NodeVisitor.generic_visit",
"python_compat.imap",
"python_compat.lmap",
"linecache.getline",
"json.dump"
] | [((803, 935), 'get_file_list.get_file_list', 'get_file_list.get_file_list', ([], {'show_external': '(False)', 'show_aux': '(False)', 'show_script': '(False)', 'show_testsuite': '(False)', 'show_type_list': "['py']"}), "(show_external=False, show_aux=False,\n show_script=False, show_testsuite=False, show_type_list=['... |
import numpy as np
from opytimizer.optimizers.swarm import sso
from opytimizer.spaces import search
def test_sso_params():
params = {
'C_w': 0.1,
'C_p': 0.4,
'C_g': 0.9
}
new_sso = sso.SSO(params=params)
assert new_sso.C_w == 0.1
assert new_sso.C_p == 0.4
assert ne... | [
"numpy.sum",
"opytimizer.spaces.search.SearchSpace",
"numpy.array",
"opytimizer.optimizers.swarm.sso.SSO"
] | [((221, 243), 'opytimizer.optimizers.swarm.sso.SSO', 'sso.SSO', ([], {'params': 'params'}), '(params=params)\n', (228, 243), False, 'from opytimizer.optimizers.swarm import sso\n'), ((383, 392), 'opytimizer.optimizers.swarm.sso.SSO', 'sso.SSO', ([], {}), '()\n', (390, 392), False, 'from opytimizer.optimizers.swarm impo... |
from barbie.barbie import *
import barbie.susy_interface as susy
import subprocess
import os.path
import sys
from shutil import rmtree
from threading import Timer
constant_DirectoryDuration = 36
# Pode ser removido depois dos testes
import time
def barbiefy(dir, codes, disc, turma, lab):
# Try to compile the sour... | [
"barbie.susy_interface.discover_susy_url",
"barbie.susy_interface.get_susy_files",
"threading.Timer",
"barbie.susy_interface.download_tests",
"shutil.rmtree"
] | [((1223, 1263), 'barbie.susy_interface.discover_susy_url', 'susy.discover_susy_url', (['disc', 'turma', 'lab'], {}), '(disc, turma, lab)\n', (1245, 1263), True, 'import barbie.susy_interface as susy\n'), ((1324, 1348), 'barbie.susy_interface.get_susy_files', 'susy.get_susy_files', (['url'], {}), '(url)\n', (1343, 1348)... |
import numpy as np
from agents import Agent
from connectboard import ConnectBoard
import time
import math
class AlphaBeta(Agent):
"""Agent that implements minimax with alpha-beta pruning to select its next move."""
def get_move(self, game_board: np.ndarray) -> np.ndarray:
"""Recursively runs minimax ... | [
"numpy.delete",
"time.time",
"connectboard.ConnectBoard.get_legal_moves"
] | [((833, 844), 'time.time', 'time.time', ([], {}), '()\n', (842, 844), False, 'import time\n'), ((921, 932), 'time.time', 'time.time', ([], {}), '()\n', (930, 932), False, 'import time\n'), ((2759, 2799), 'connectboard.ConnectBoard.get_legal_moves', 'ConnectBoard.get_legal_moves', (['game_board'], {}), '(game_board)\n',... |
import matplotlib.pyplot as plt
import netomaton as ntm
import numpy as np
if __name__ == '__main__':
# NKS page 443 - Rule 122R
network = ntm.topology.cellular_automaton(n=100)
# carefully chosen initial conditions
previous_state = [1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, ... | [
"netomaton.rules.nks_ca_rule",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.plot",
"numpy.array",
"netomaton.average_node_entropy",
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplot",
"netomaton.get_activities_over_time_as_list",
"netomaton.topology.cellular_automaton"
] | [((150, 188), 'netomaton.topology.cellular_automaton', 'ntm.topology.cellular_automaton', ([], {'n': '(100)'}), '(n=100)\n', (181, 188), True, 'import netomaton as ntm\n'), ((1346, 1394), 'netomaton.get_activities_over_time_as_list', 'ntm.get_activities_over_time_as_list', (['trajectory'], {}), '(trajectory)\n', (1382,... |
import argparse
import csv
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from modules.metric import mean_reciprocal_rank
def main(csv_path):
acc = 0
num = 0
with open(csv_path, "r") as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count ... | [
"os.path.dirname",
"csv.reader",
"argparse.ArgumentParser"
] | [((838, 863), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (861, 863), False, 'import argparse\n'), ((81, 106), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (96, 106), False, 'import os\n'), ((265, 300), 'csv.reader', 'csv.reader', (['csv_file'], {'delimiter': '""... |
from django.urls import path, include
from rest_framework import routers
from . import views
app_name = "invoice_creator"
router = routers.DefaultRouter()
router.register(r"invoice", views.InvoiceViewSet)
urlpatterns = [
path("", include(router.urls), name="api"),
]
| [
"rest_framework.routers.DefaultRouter",
"django.urls.include"
] | [((133, 156), 'rest_framework.routers.DefaultRouter', 'routers.DefaultRouter', ([], {}), '()\n', (154, 156), False, 'from rest_framework import routers\n'), ((237, 257), 'django.urls.include', 'include', (['router.urls'], {}), '(router.urls)\n', (244, 257), False, 'from django.urls import path, include\n')] |
# Generated by Django 4.0.2 on 2022-03-17 10:39
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import petstagram.main_app.validators
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(set... | [
"django.db.models.DateField",
"django.db.models.TextField",
"django.db.models.ForeignKey",
"django.db.models.ManyToManyField",
"django.db.models.BigAutoField",
"django.db.models.ImageField",
"django.db.migrations.swappable_dependency",
"django.db.models.CharField"
] | [((285, 342), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (316, 342), False, 'from django.db import migrations, models\n'), ((511, 607), 'django.db.models.BigAutoField', 'models.BigAutoField', ([], {'auto_created': '... |
import os
import logging
import requests
import telegram
from telegram.error import NetworkError, Unauthorized
from time import sleep
from imageGenerator import generate_random_emoji_cover
update_id = None
def main():
"""Run the bot."""
global update_id
# Telegram Bot Authorization Token
bot = telegr... | [
"logging.basicConfig",
"imageGenerator.generate_random_emoji_cover",
"telegram.Bot",
"time.sleep"
] | [((314, 356), 'telegram.Bot', 'telegram.Bot', (["os.environ['TELEGRAM_TOKEN']"], {}), "(os.environ['TELEGRAM_TOKEN'])\n", (326, 356), False, 'import telegram\n'), ((591, 678), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s - %(name)s - %(levelname)s - %(message)s"""'}), "(format=\n '%(... |
import pytest
from notifications_utils.validate_html import check_if_string_contains_valid_html
@pytest.mark.parametrize(
"good_content",
(
"<div>abc</div>",
'<div style="display: none;">abc</div>',
"""<div style="margin: 20px auto 30px auto;">
<img
src="http://google.com"
a... | [
"pytest.mark.parametrize",
"notifications_utils.validate_html.check_if_string_contains_valid_html"
] | [((100, 384), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""good_content"""', '(\'<div>abc</div>\', \'<div style="display: none;">abc</div>\',\n """<div style="margin: 20px auto 30px auto;">\n <img\n src="http://google.com"\n alt="alt text"\n height="10"\n width="10"\n />\n</div>"""\n ... |
"""
This test is applicable while InnoSchedule bot instance is running
In order to run the test, you have to:
1.1 Create your bot in telegram:
Write @BotFather the command "/newbot", follow instructions
1.2 In admin/permanent.py put your token
2.1 Run the bot: Python Innoschedule.py
3.1 Contact you bot, find ou... | [
"modules.core.source.bot.send_message",
"telebot.types.KeyboardButton",
"modules.electives_schedule.controller.get_electives_course",
"modules.electives_schedule.controller.check_electives_course",
"parameterized.parameterized_class",
"modules.electives_schedule.controller.set_electives_user",
"telebot.... | [((780, 881), 'parameterized.parameterized_class', 'parameterized_class', (["[{'test_message': '/add_course', 'elective': 'Advanced Python Programming'}]"], {}), "([{'test_message': '/add_course', 'elective':\n 'Advanced Python Programming'}])\n", (799, 881), False, 'from parameterized import parameterized, paramete... |
# Used functions for data preparation
from __future__ import print_function
import sys
import warnings
import traceback
import numpy as np
import shutil
import os
from os import remove
from os import listdir
import os.path
from os.path import join
from datetime import datetime
from scipy.misc import imread, imresize
f... | [
"os.path.exists",
"os.listdir",
"PIL.Image.open",
"os.path.join",
"sys.exc_info",
"scipy.misc.imread",
"os.path.isdir",
"os.mkdir",
"scipy.misc.imresize",
"warnings.filterwarnings",
"os.remove"
] | [((1139, 1160), 'os.listdir', 'os.listdir', (['directory'], {}), '(directory)\n', (1149, 1160), False, 'import os\n'), ((1753, 1771), 'os.listdir', 'listdir', (['directory'], {}), '(directory)\n', (1760, 1771), False, 'from os import listdir\n'), ((1904, 1936), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"... |
import numpy as np
__all__ = ["plot_spectrum_datasets_off_regions", "plot_contour_line"]
def plot_spectrum_datasets_off_regions(datasets, ax=None):
"""Plot spectrum datasets of regions.
Parameters
----------
datasets : list of `SpectrumDatasetOnOff`
List of spectrum on-off datasets
"""
... | [
"scipy.interpolate.CubicSpline",
"matplotlib.pyplot.gca",
"numpy.diff",
"numpy.append",
"numpy.linspace",
"matplotlib.patches.Patch",
"numpy.cumsum",
"matplotlib.pyplot.legend"
] | [((892, 919), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'handles': 'handles'}), '(handles=handles)\n', (902, 919), True, 'import matplotlib.pyplot as plt\n'), ((1090, 1108), 'numpy.append', 'np.append', (['x', 'x[0]'], {}), '(x, x[0])\n', (1099, 1108), True, 'import numpy as np\n'), ((1118, 1136), 'numpy.append',... |
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 11 15:05:10 2019
The Simple Linear Regression model
@author: Dr. Dr. <NAME>
@web : https://dannyvanpoucke.be
"""
import pandas as pd
import numpy as np
from TModelClass import TModelClass
from TModelResults import TModelResults
from Bootstrap import TBootstrap
from TMo... | [
"numpy.mean",
"Bootstrap.TBootstrap",
"numpy.asarray",
"numpy.array",
"numpy.zeros",
"sys.exit",
"pandas.concat",
"sklearn.linear_model.LinearRegression",
"TModelQualityData.TModelQualityData"
] | [((2265, 2344), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {'fit_intercept': '(True)', 'normalize': '(False)', 'copy_X': '(True)', 'n_jobs': 'None'}), '(fit_intercept=True, normalize=False, copy_X=True, n_jobs=None)\n', (2281, 2344), False, 'from sklearn.linear_model import LinearRegression\n'), ... |
# Copyright 2015 Ufora 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 agreed to i... | [
"ufora.test.PerformanceTestReporter.PerfTest",
"sys.setcheckinterval",
"ufora.test.PerformanceTestReporter.RecordAsPerfTest"
] | [((1471, 1542), 'ufora.test.PerformanceTestReporter.PerfTest', 'PerformanceTestReporter.PerfTest', (['"""pyfora.string_indexing.large_string"""'], {}), "('pyfora.string_indexing.large_string')\n", (1503, 1542), True, 'import ufora.test.PerformanceTestReporter as PerformanceTestReporter\n'), ((1629, 1700), 'ufora.test.P... |
import logging
from zentral.core.events.base import BaseEvent, register_event_type
logger = logging.getLogger('zentral.contrib.audit.events')
ALL_EVENTS_SEARCH_DICT = {"tag": "audit"}
class AuditEvent(BaseEvent):
event_type = "audit"
tags = ["audit"]
payload_aggregations = [
("event_id", {"type... | [
"logging.getLogger",
"zentral.core.events.base.register_event_type"
] | [((93, 142), 'logging.getLogger', 'logging.getLogger', (['"""zentral.contrib.audit.events"""'], {}), "('zentral.contrib.audit.events')\n", (110, 142), False, 'import logging\n'), ((385, 416), 'zentral.core.events.base.register_event_type', 'register_event_type', (['AuditEvent'], {}), '(AuditEvent)\n', (404, 416), False... |
import sys
import configparser
import json
import logging
if __name__ == "__main__":
sys.exit()
config = configparser.ConfigParser(allow_no_value=True)
config.read("conf/config.ini")
mimes_file = config['server']['MIMES_FILE']
mime_file = open(mimes_file,"r")
mimes = mime_file.read()
mime_file.close()
MIME_TYPES ... | [
"json.loads",
"configparser.ConfigParser",
"sys.exit"
] | [((110, 156), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {'allow_no_value': '(True)'}), '(allow_no_value=True)\n', (135, 156), False, 'import configparser\n'), ((322, 339), 'json.loads', 'json.loads', (['mimes'], {}), '(mimes)\n', (332, 339), False, 'import json\n'), ((89, 99), 'sys.exit', 'sys.exit... |
"""
AUTOR: Juanjo
FECHA DE CREACIÓN: 24/05/2019
"""
from flask import render_template, redirect, url_for
from flask_login import login_required, current_user
from app.models import Post
from . import admin_bp
from .forms import PostForm
@admin_bp.route("/admin/post/", methods=['GET', 'POST'], defaults={'post_id'... | [
"flask.render_template",
"app.models.Post",
"flask.url_for"
] | [((721, 771), 'flask.render_template', 'render_template', (['"""admin/post_form.html"""'], {'form': 'form'}), "('admin/post_form.html', form=form)\n", (736, 771), False, 'from flask import render_template, redirect, url_for\n'), ((580, 639), 'app.models.Post', 'Post', ([], {'user_id': 'current_user.id', 'title': 'title... |
"""
Views which deal with Bookmarks, allowing them to be added, removed,
and viewed according to various criteria.
"""
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from django.views.generic import list_detail... | [
"django.http.HttpResponseRedirect",
"cab.models.Bookmark.objects.distinct_list",
"cab.models.Bookmark.objects.get_by_author",
"cab.models.Bookmark.objects.get_for_user",
"django.shortcuts.get_object_or_404",
"cab.models.Bookmark.objects.get",
"cab.models.Bookmark.objects.create",
"django.contrib.auth.... | [((1186, 1214), 'django.contrib.auth.decorators.login_required', 'login_required', (['add_bookmark'], {}), '(add_bookmark)\n', (1200, 1214), False, 'from django.contrib.auth.decorators import login_required\n'), ((1725, 1750), 'django.contrib.auth.decorators.login_required', 'login_required', (['bookmarks'], {}), '(boo... |
import unittest as ut
from chunker_dm.lexicon import Lexicon, ProbabilityLexicon, ComplexityLexicon
class TestLexicon(ut.TestCase):
def test_lexicon_adds_tokens_from_text(self):
lex = Lexicon()
lex.add("Isso é uma frase")
self.assertEqual(lex.total(), 4)
def test_lexicon_counts_frequency_of_word(self... | [
"chunker_dm.lexicon.Lexicon",
"chunker_dm.lexicon.ComplexityLexicon",
"chunker_dm.lexicon.ProbabilityLexicon"
] | [((192, 201), 'chunker_dm.lexicon.Lexicon', 'Lexicon', ([], {}), '()\n', (199, 201), False, 'from chunker_dm.lexicon import Lexicon, ProbabilityLexicon, ComplexityLexicon\n'), ((333, 342), 'chunker_dm.lexicon.Lexicon', 'Lexicon', ([], {}), '()\n', (340, 342), False, 'from chunker_dm.lexicon import Lexicon, ProbabilityL... |
"""
TODO docstring
"""
import os
from datetime import timedelta, datetime
from typing import Optional
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from fastapi import APIRouter, Depends, HTTPException, status
from tinydb import TinyDB, where
from passlib.hash import bcrypt
... | [
"tinydb.TinyDB",
"requests.post",
"fastapi.security.OAuth2PasswordBearer",
"os.getenv",
"fastapi.HTTPException",
"datetime.datetime.utcnow",
"jose.jwt.decode",
"passlib.hash.bcrypt.verify",
"dotenv.load_dotenv",
"jose.jwt.encode",
"fastapi.APIRouter",
"datetime.timedelta",
"tinydb.where",
... | [((403, 416), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (414, 416), False, 'from dotenv import load_dotenv\n'), ((471, 492), 'tinydb.TinyDB', 'TinyDB', (['USERS_DB_PATH'], {}), '(USERS_DB_PATH)\n', (477, 492), False, 'from tinydb import TinyDB, where\n'), ((619, 654), 'os.getenv', 'os.getenv', (['"""SECRET... |
from __future__ import absolute_import, division, print_function
from abc import abstractmethod, abstractproperty
import numpy as np
from keras import __version__ as __keras_version__
from keras import backend as K
from keras.layers import Dense, Dot, Dropout, Input, Lambda, TimeDistributed
from keras.models import ... | [
"keras.backend.dtype",
"energyflow.archs.archbase._get_act_layer",
"keras.backend.function",
"keras.layers.Lambda",
"keras.__version__.split",
"keras.layers.TimeDistributed",
"keras.layers.Dot",
"keras.backend.not_equal",
"numpy.asarray",
"keras.layers.Input",
"numpy.linspace",
"energyflow.uti... | [((1477, 1522), 'keras.layers.Input', 'Input', ([], {'batch_shape': '(None, None)', 'name': 'zs_name'}), '(batch_shape=(None, None), name=zs_name)\n', (1482, 1522), False, 'from keras.layers import Dense, Dot, Dropout, Input, Lambda, TimeDistributed\n'), ((1541, 1600), 'keras.layers.Input', 'Input', ([], {'batch_shape'... |
from setuptools import find_packages, setup
setup(
name='src',
packages=find_packages(),
version='0.1.0',
description='repo for https://www.kaggle.com/c/house-prices-advanced-regression-techniques',
author='<NAME>',
license='MIT',
)
| [
"setuptools.find_packages"
] | [((81, 96), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (94, 96), False, 'from setuptools import find_packages, setup\n')] |
import itertools
def find_nb(m):
sum = 0
for i in itertools.count(1):
sum += i ** 3
if sum == m:
return i
elif sum > m:
return -1 | [
"itertools.count"
] | [((59, 77), 'itertools.count', 'itertools.count', (['(1)'], {}), '(1)\n', (74, 77), False, 'import itertools\n')] |
# Generated by Django 2.2.4 on 2019-12-03 19:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('scholar', '0003_auto_20191203_0243'),
]
operations = [
migrations.AlterModelOptions(
name='scholar',
options={'order... | [
"django.db.migrations.AlterModelOptions",
"django.db.models.IntegerField"
] | [((235, 324), 'django.db.migrations.AlterModelOptions', 'migrations.AlterModelOptions', ([], {'name': '"""scholar"""', 'options': "{'ordering': ['award_amount']}"}), "(name='scholar', options={'ordering': [\n 'award_amount']})\n", (263, 324), False, 'from django.db import migrations, models\n'), ((472, 502), 'django... |
# coding: utf-8
from os import path
from . import directives
from . import __version__
def setup(app):
app.add_html_theme("sphinx_scality", path.abspath(path.dirname(__file__)))
directives.setup(app)
return {
"version": __version__.VERSION,
"parallel_read_safe": True,
"parallel... | [
"os.path.dirname"
] | [((161, 183), 'os.path.dirname', 'path.dirname', (['__file__'], {}), '(__file__)\n', (173, 183), False, 'from os import path\n')] |
import tensorflow as tf
import numpy as np
from blackbox_mpc.optimizers.optimizer_base import OptimizerBase
class PSOOptimizer(OptimizerBase):
def __init__(self, env_action_space, env_observation_space,
planning_horizon=50, max_iterations=5, population_size=500,
num_agents=5, c1=... | [
"tensorflow.random.uniform",
"tensorflow.math.argmax",
"tensorflow.random.normal",
"tensorflow.reduce_prod",
"tensorflow.transpose",
"numpy.square",
"tensorflow.range",
"tensorflow.where",
"tensorflow.sqrt",
"tensorflow.constant",
"tensorflow.clip_by_value",
"tensorflow.gather",
"tensorflow.... | [((320, 354), 'tensorflow.constant', 'tf.constant', (['(0.3)'], {'dtype': 'tf.float32'}), '(0.3, dtype=tf.float32)\n', (331, 354), True, 'import tensorflow as tf\n'), ((376, 410), 'tensorflow.constant', 'tf.constant', (['(0.5)'], {'dtype': 'tf.float32'}), '(0.5, dtype=tf.float32)\n', (387, 410), True, 'import tensorflo... |
from search import *
import heapq
# Predicados usados para descrever estado, pre-condições e efeitos
class Predicate:
def __str__(self):
return type(self).__name__ + "(" + str(self.args[0]) + "," + str(self.args[1]) + ")"
def __repr__(self):
return str(self)
def __eq__(self, predicate):
... | [
"heapq.heappush",
"heapq.heappop",
"heapq.heapify"
] | [((15099, 15124), 'heapq.heapify', 'heapq.heapify', (['open_nodes'], {}), '(open_nodes)\n', (15112, 15124), False, 'import heapq\n'), ((15163, 15188), 'heapq.heappop', 'heapq.heappop', (['open_nodes'], {}), '(open_nodes)\n', (15176, 15188), False, 'import heapq\n'), ((16029, 16064), 'heapq.heappush', 'heapq.heappush', ... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import show_and_tell_model
from inference_utils import inference_wrapper_base
class InferenceWrapper(inference_wrapper_base.InferenceWrapperBase):
def __init__(self):
super(InferenceWr... | [
"show_and_tell_model.ShowAndTellModel"
] | [((388, 456), 'show_and_tell_model.ShowAndTellModel', 'show_and_tell_model.ShowAndTellModel', (['model_config'], {'mode': '"""inference"""'}), "(model_config, mode='inference')\n", (424, 456), False, 'import show_and_tell_model\n')] |
from logging import getLogger
from os import getpid
from infi.exceptools import chain
from infi.pyutils.contexts import contextmanager
from infi.pyutils.decorators import wraps
CHECK_CONDITIONS_NOT_WORTH_RETRY = [
('ILLEGAL_REQUEST', 'LOGICAL UNIT NOT SUPPORTED'),
('ILLEGAL_REQUEST', 'INVALID FIELD IN CDB'),
... | [
"logging.getLogger",
"infi.asi.create_platform_command_executer",
"infi.pyutils.decorators.wraps",
"infi.execute.execute_async",
"os.getpid"
] | [((452, 471), 'logging.getLogger', 'getLogger', (['__name__'], {}), '(__name__)\n', (461, 471), False, 'from logging import getLogger\n'), ((855, 866), 'infi.pyutils.decorators.wraps', 'wraps', (['func'], {}), '(func)\n', (860, 866), False, 'from infi.pyutils.decorators import wraps\n'), ((1642, 1661), 'infi.execute.ex... |
from pathlib import Path, PureWindowsPath
from PIL import Image
class dotdict(dict):
"""dot.notation access to dictionary attributes"""
__getattr__ = dict.get
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
def openSingleAndCheck(path, resized_path, resize=False):
"""
Check if pa... | [
"PIL.Image.open",
"pathlib.PureWindowsPath",
"pathlib.Path"
] | [((427, 443), 'PIL.Image.open', 'Image.open', (['path'], {}), '(path)\n', (437, 443), False, 'from PIL import Image\n'), ((1165, 1188), 'pathlib.PureWindowsPath', 'PureWindowsPath', (['output'], {}), '(output)\n', (1180, 1188), False, 'from pathlib import Path, PureWindowsPath\n'), ((1123, 1141), 'pathlib.Path', 'Path'... |
from django.db import models
from cms.models import CMSPlugin
from embed_video.fields import EmbedVideoField
class VideoPluginModel(CMSPlugin):
video_url = EmbedVideoField()
max_width = models.IntegerField(blank=True, null=True, help_text="in px")
def __str__(self):
return self.video_url
| [
"embed_video.fields.EmbedVideoField",
"django.db.models.IntegerField"
] | [((162, 179), 'embed_video.fields.EmbedVideoField', 'EmbedVideoField', ([], {}), '()\n', (177, 179), False, 'from embed_video.fields import EmbedVideoField\n'), ((196, 257), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'blank': '(True)', 'null': '(True)', 'help_text': '"""in px"""'}), "(blank=True, nul... |
"""
Generate all synonymous mutants for a input protein
<NAME>
"""
# Ensure Python 2/3 compatibility
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import itertools
import argparse
import sys
from signal import signa... | [
"argparse.FileType",
"signal.signal",
"itertools.groupby",
"argparse.ArgumentParser",
"itertools.chain.from_iterable"
] | [((458, 482), 'signal.signal', 'signal', (['SIGPIPE', 'SIG_DFL'], {}), '(SIGPIPE, SIG_DFL)\n', (464, 482), False, 'from signal import signal, SIGPIPE, SIG_DFL\n'), ((5607, 5713), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Generate all single synonymous mutations for an input sequence... |
"""Functions to manipulate and validate configurations."""
import jsonschema
import six
def merge_config(a, b):
"""Merges config b in a."""
for k, v in six.iteritems(b):
if k in a and isinstance(v, dict) and type(a[k]) == type(v):
merge_config(a[k], v)
else:
a[k] = v
... | [
"jsonschema.validate",
"six.iteritems",
"jsonschema.Draft7Validator.check_schema"
] | [((163, 179), 'six.iteritems', 'six.iteritems', (['b'], {}), '(b)\n', (176, 179), False, 'import six\n'), ((2067, 2119), 'jsonschema.Draft7Validator.check_schema', 'jsonschema.Draft7Validator.check_schema', (['json_schema'], {}), '(json_schema)\n', (2106, 2119), False, 'import jsonschema\n'), ((3524, 3586), 'jsonschema... |
import os
from factory import create_app
app = create_app()
app.app_context().push()
@app.teardown_request
def teardown_request(*args, **kwargs):
'Expire and remove the session after each request'
from database import db
db.session.expire_all()
db.session.remove()
if 'Development' in os.environ.g... | [
"database.db.session.remove",
"tests.conftest.create_dev_data",
"os.environ.get",
"factory.create_app",
"database.db.session.expire_all"
] | [((50, 62), 'factory.create_app', 'create_app', ([], {}), '()\n', (60, 62), False, 'from factory import create_app\n'), ((238, 261), 'database.db.session.expire_all', 'db.session.expire_all', ([], {}), '()\n', (259, 261), False, 'from database import db\n'), ((266, 285), 'database.db.session.remove', 'db.session.remove... |
# Copyright 2020 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | [
"skynet.endpoints.ephttp.simple_post_server",
"skynet.seq2seq.Generator"
] | [((729, 750), 'skynet.seq2seq.Generator', 'Generator', (['model_name'], {}), '(model_name)\n', (738, 750), False, 'from skynet.seq2seq import Generator\n'), ((1810, 1854), 'skynet.endpoints.ephttp.simple_post_server', 'simple_post_server', (['"""0.0.0.0"""', 'port', 'handler'], {}), "('0.0.0.0', port, handler)\n", (182... |
#
# Copyright (c) 2018 LabKey Corporation
#
# 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... | [
"labkey.experiment.Run",
"labkey.experiment.Batch",
"labkey.api_wrapper.APIWrapper"
] | [((794, 862), 'labkey.api_wrapper.APIWrapper', 'APIWrapper', (['labkey_server', 'project_name', 'context_path'], {'use_ssl': '(False)'}), '(labkey_server, project_name, context_path, use_ssl=False)\n', (804, 862), False, 'from labkey.api_wrapper import APIWrapper\n'), ((1016, 1021), 'labkey.experiment.Run', 'Run', ([],... |
import numpy as np
import porespy as ps
import matplotlib.pyplot as plt
import openpnm as op
np.random.seed(0)
def test_snow_example_script():
plot = False
im1 = ps.generators.blobs(shape=[600, 400], porosity=None, blobiness=1) < 0.4
im2 = ps.generators.blobs(shape=[600, 400], porosity=None, blobiness=1)... | [
"openpnm.topotools.plot_coordinates",
"porespy.generators.blobs",
"porespy.networks.snow2",
"openpnm.io.from_porespy",
"numpy.array",
"openpnm.topotools.plot_connections",
"numpy.random.seed",
"matplotlib.pyplot.axis",
"porespy.tools.randomize_colors",
"matplotlib.pyplot.subplots"
] | [((93, 110), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (107, 110), True, 'import numpy as np\n'), ((401, 528), 'porespy.networks.snow2', 'ps.networks.snow2', (['phases'], {'phase_alias': "{(1): 'solid', (2): 'void'}", 'boundary_width': '(5)', 'accuracy': '"""high"""', 'parallelization': 'None'}), "... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import appier
class BaseController(appier.Controller):
@appier.route("/", "GET")
@appier.route("/index", "GET")
def index(self):
return self.redirect(
self.url_for("base.simple")
)
@appier.route("/simple", "GET")
... | [
"appier.route",
"appier.conf"
] | [((112, 136), 'appier.route', 'appier.route', (['"""/"""', '"""GET"""'], {}), "('/', 'GET')\n", (124, 136), False, 'import appier\n'), ((143, 172), 'appier.route', 'appier.route', (['"""/index"""', '"""GET"""'], {}), "('/index', 'GET')\n", (155, 172), False, 'import appier\n'), ((286, 316), 'appier.route', 'appier.rout... |
from itertools import permutations
from string import ascii_lowercase
INPUT_PATH = 'input.txt'
def get_input(path=INPUT_PATH):
"""Get the input for day 5.
This should all be one long string. I tested with the given input and we don't need to join
the lines but it's just a bit less brittle this way."""
... | [
"itertools.permutations"
] | [((640, 711), 'itertools.permutations', 'permutations', (['"""abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"""', '(2)'], {}), "('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 2)\n", (652, 711), False, 'from itertools import permutations\n')] |
#!/usr/bin/env python3
"""Module with FourSquare API usage to get data"""
import os
import logging
import requests
import pandas as pd
LIMIT = 50
VERSION = "20180323"
CLIENT_ID = os.environ['FOURSQ_ID']
CLIENT_SECRET = os.environ['FOURSQ_SECRET']
HYDEPARK_LATITUDE = 51.5052
HYDEPARK_LONGTITUDE = -0.1582
def get_nea... | [
"pandas.DataFrame",
"logging.error",
"logging.info",
"requests.get"
] | [((1380, 1405), 'pandas.DataFrame', 'pd.DataFrame', (['venues_list'], {}), '(venues_list)\n', (1392, 1405), True, 'import pandas as pd\n'), ((2149, 2210), 'logging.error', 'logging.error', (['"""foursquare : get_venue_rating : %s"""', 'res_dict'], {}), "('foursquare : get_venue_rating : %s', res_dict)\n", (2162, 2210),... |
# Generated by Django 2.0.3 on 2018-03-25 20:28
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('emails', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='mailoutuser',
... | [
"django.db.models.ForeignKey"
] | [((364, 460), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.PROTECT', 'to': '"""emails.MailoutCategory"""'}), "(on_delete=django.db.models.deletion.PROTECT, to=\n 'emails.MailoutCategory')\n", (381, 460), False, 'from django.db import migrations, models\n')] |
from collections import namedtuple
from typing import Dict
import pytest
from pyocle.service.core import BaseForm
FormTestFixture = namedtuple(typename='FormTestFixture', field_names='value,dict')
class DummyBaseForm(BaseForm):
def __init__(self, name: str = None, items: Dict[str, str] = None):
self.na... | [
"collections.namedtuple"
] | [((135, 199), 'collections.namedtuple', 'namedtuple', ([], {'typename': '"""FormTestFixture"""', 'field_names': '"""value,dict"""'}), "(typename='FormTestFixture', field_names='value,dict')\n", (145, 199), False, 'from collections import namedtuple\n')] |
# -*- coding: utf-8 -*-
import time, random
def qsort(q_list):
if len(q_list) < 2:
return q_list
mid = len(q_list) // 2
mid_value = q_list[mid]
del q_list[mid]
left = []
right = []
for i in q_list:
if i <= mid_value:
left.append(i)
else:
right.... | [
"time.time",
"random.randint"
] | [((517, 528), 'time.time', 'time.time', ([], {}), '()\n', (526, 528), False, 'import time, random\n'), ((572, 583), 'time.time', 'time.time', ([], {}), '()\n', (581, 583), False, 'import time, random\n'), ((476, 498), 'random.randint', 'random.randint', (['(1)', '(100)'], {}), '(1, 100)\n', (490, 498), False, 'import t... |
# Copyright (c) 2022 <NAME>
"""
构造top矩阵
日志
2022-01-11
- init
2022-01-20
- 更新:生成普通top时需要剔除ST股
"""
import numpy as np
import pandas as pd
import pickle
# 生成某个指数的top
def generate_index_top(dates: np.array, date_position_dic: dict,
code_order_dic: dict, data_path: str, top_type: str = 'ZZ1000')... | [
"pickle.load"
] | [((676, 690), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (687, 690), False, 'import pickle\n')] |
import airflow
from airflow.operators.bash_operator import BashOperator
from airflow.operators.sensors import ExternalTaskSensor
from airflow.models import DAG
from datetime import datetime, timedelta
args = {
'owner': 'airflow',
"depends_on_past": False,
'start_date': airflow.utils.dates.days_ago(1),
... | [
"airflow.models.DAG",
"datetime.timedelta",
"airflow.utils.dates.days_ago",
"airflow.operators.bash_operator.BashOperator"
] | [((439, 513), 'airflow.models.DAG', 'DAG', ([], {'dag_id': '"""ll_test_2"""', 'default_args': 'args', 'schedule_interval': '"""28 8 * * *"""'}), "(dag_id='ll_test_2', default_args=args, schedule_interval='28 8 * * *')\n", (442, 513), False, 'from airflow.models import DAG\n'), ((682, 748), 'airflow.operators.bash_opera... |
"""Test improved pipeline."""
from textwrap import dedent
from unittest.mock import patch
import pandas as pd
import yaml
from pytest import fixture
from nitinat.pipeline2 import pipeline
READ_CONFIG = "nitinat.pipeline2._read_config"
READER_SHORTENED_LEN = 3
def simple_df():
return pd.DataFrame(
{
... | [
"textwrap.dedent",
"nitinat.pipeline2.pipeline",
"yaml.safe_load",
"pandas.DataFrame",
"unittest.mock.patch"
] | [((294, 473), 'pandas.DataFrame', 'pd.DataFrame', (["{'red': [0.1, 0.2, 0.3], 'green': [0.4, 0.5, 0.6], 'blue': [0.7, 0.8, 0.9],\n 'orange': [1.1, 1.2, 1.3], 'yellow': [1.4, 1.5, 1.6], 'purple': [1.7, \n 1.8, 1.9]}"], {}), "({'red': [0.1, 0.2, 0.3], 'green': [0.4, 0.5, 0.6], 'blue': [\n 0.7, 0.8, 0.9], 'orange... |
"""
MIT License
Copyright(c) 2021 <NAME>
"""
from flask import abort
from . import testing_bp
from flog.utils import redirect_back
@testing_bp.route("/400")
def trigger_bad_request():
abort(400)
@testing_bp.route("/403")
def trigger_forbidden():
abort(403)
@testing_bp.route("/404")
def... | [
"flask.abort",
"flog.utils.redirect_back"
] | [((201, 211), 'flask.abort', 'abort', (['(400)'], {}), '(400)\n', (206, 211), False, 'from flask import abort\n'), ((274, 284), 'flask.abort', 'abort', (['(403)'], {}), '(403)\n', (279, 284), False, 'from flask import abort\n'), ((347, 357), 'flask.abort', 'abort', (['(404)'], {}), '(404)\n', (352, 357), False, 'from f... |
import tensorflow as tf
import sys
from configs import DEFINES
# 엘에스티엠(LSTM) 단층 네트워크 구성하는 부분
def make_lstm_cell(mode, hiddenSize, index):
cell = tf.nn.rnn_cell.BasicLSTMCell(hiddenSize, name = "lstm"+str(index))
if mode == tf.estimator.ModeKeys.TRAIN:
# 트레이닝 모드에서 드랍아웃 추가
cell = tf.contrib.rnn.... | [
"tensorflow.one_hot",
"tensorflow.nn.embedding_lookup",
"tensorflow.train.AdamOptimizer",
"tensorflow.eye",
"tensorflow.contrib.rnn.MultiRNNCell",
"tensorflow.get_variable",
"tensorflow.variable_scope",
"tensorflow.nn.softmax_cross_entropy_with_logits_v2",
"tensorflow.estimator.EstimatorSpec",
"te... | [((1510, 1573), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', ([], {'params': 'embedding', 'ids': "features['input']"}), "(params=embedding, ids=features['input'])\n", (1532, 1573), True, 'import tensorflow as tf\n'), ((1625, 1689), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', ([], {'params... |
#!/usr/bin/python3
import os
import random
import string
from nephele2.pipelines.pipebase import PipeBase
import nephele2.pipelines.pipeline_error
class picrust(PipeBase):
"""
PICRUSt (pronounced pie crust) is a bioinformatics software package designed
to predict metagenome functional content from marker... | [
"os.path.join",
"random.choice",
"os.join.path"
] | [((2339, 2383), 'os.join.path', 'os.join.path', (['self.out_dir', 'picrust.otus_dir'], {}), '(self.out_dir, picrust.otus_dir)\n', (2351, 2383), False, 'import os\n'), ((3787, 3831), 'os.path.join', 'os.path.join', (['self.out_dir', 'picrust.otus_dir'], {}), '(self.out_dir, picrust.otus_dir)\n', (3799, 3831), False, 'im... |
import towers_of_hanoi as towers
import pytest
def test_tower_exception_type():
"""Test TypeError in tower function."""
with pytest.raises(TypeError):
towers.towers_of_hanoi('n')
def test_tower_return_three():
"""Test tower of hanoi function returns correct last move with three."""
temp = to... | [
"pytest.raises",
"towers_of_hanoi.towers_of_hanoi"
] | [((318, 343), 'towers_of_hanoi.towers_of_hanoi', 'towers.towers_of_hanoi', (['(3)'], {}), '(3)\n', (340, 343), True, 'import towers_of_hanoi as towers\n'), ((506, 531), 'towers_of_hanoi.towers_of_hanoi', 'towers.towers_of_hanoi', (['(2)'], {}), '(2)\n', (528, 531), True, 'import towers_of_hanoi as towers\n'), ((618, 64... |
from bagua.torch_api.contrib.cached_dataset import CachedDataset
from torch.utils.data.dataset import Dataset
import numpy as np
import logging
import unittest
from tests import skip_if_cuda_available
logging.basicConfig(level=logging.DEBUG)
class MyDataset(Dataset):
def __init__(self, size):
self.size =... | [
"logging.basicConfig",
"numpy.random.rand",
"bagua.torch_api.contrib.cached_dataset.CachedDataset",
"tests.skip_if_cuda_available",
"unittest.main"
] | [((202, 242), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG'}), '(level=logging.DEBUG)\n', (221, 242), False, 'import logging\n'), ((921, 945), 'tests.skip_if_cuda_available', 'skip_if_cuda_available', ([], {}), '()\n', (943, 945), False, 'from tests import skip_if_cuda_available\n'), ((16... |
# -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import formats
from django.contrib.auth.models import User
from jsonfield import JSONField
from mbase.models import MetaBaseModel, MetaBaseStatusModel
from mcat.models import Product
from mcat... | [
"django.utils.translation.ugettext_lazy",
"django.utils.formats.date_format"
] | [((1160, 1174), 'django.utils.translation.ugettext_lazy', '_', (['u"""Customer"""'], {}), "(u'Customer')\n", (1161, 1174), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((1205, 1220), 'django.utils.translation.ugettext_lazy', '_', (['u"""Customers"""'], {}), "(u'Customers')\n", (1206, 1220), True,... |
import argparse
import math
import sys
import timeit
def load_file(fname: str):
with open(fname, 'r') as file:
code = file.read()
return code
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='time fibonacci implementations')
parser.add_argument('-n', '--nth', type=int, h... | [
"timeit.Timer",
"argparse.ArgumentParser",
"math.log",
"sys.getrecursionlimit",
"sys.exit"
] | [((200, 269), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""time fibonacci implementations"""'}), "(description='time fibonacci implementations')\n", (223, 269), False, 'import argparse\n'), ((701, 711), 'sys.exit', 'sys.exit', ([], {}), '()\n', (709, 711), False, 'import sys\n'), ((111... |
# Copyright (c) 2020, <NAME>.
# All rights reserved. Distributed under the BSD License.
import csv
import gzip
import json
import logging
import os.path
import time
from enum import Enum
from typing import Optional, Generator, Dict, Callable, Tuple, Set, Any
import requests
_MEGABYTE = 1048576
#: Logger for all outp... | [
"logging.getLogger",
"csv.DictReader",
"gzip.open",
"requests.get",
"json.load",
"time.time",
"json.dump"
] | [((350, 376), 'logging.getLogger', 'logging.getLogger', (['"""pimdb"""'], {}), "('pimdb')\n", (367, 376), False, 'import logging\n'), ((5517, 5554), 'requests.get', 'requests.get', (['source_url'], {'stream': '(True)'}), '(source_url, stream=True)\n', (5529, 5554), False, 'import requests\n'), ((5063, 5124), 'json.dump... |
import os # path
import sys # path
import yaml # safe_load, YAMLError
import glob # glob
import importlib # import_module
import pytest # skip
import warnings # warn
# For type hints only:
from typing import Union
from types import ModuleType
from _pytest.config import C... | [
"importlib.import_module",
"os.path.join",
"os.path.isfile",
"os.path.dirname",
"yaml.safe_load",
"os.path.abspath",
"pytest.skip",
"glob.glob"
] | [((544, 585), 'glob.glob', 'glob.glob', (['recursive_path'], {'recursive': '(True)'}), '(recursive_path, recursive=True)\n', (553, 585), False, 'import glob\n'), ((1093, 1114), 'os.path.abspath', 'os.path.abspath', (['path'], {}), '(path)\n', (1108, 1114), False, 'import os\n'), ((488, 521), 'os.path.join', 'os.path.jo... |
# Generated by Django 3.1.7 on 2021-04-01 06:35
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import mptt.fields
import nautobot.extras.models.statuses
import taggit.managers
class Migration(migrations.Migration):
initial = True
dependencies = [
... | [
"django.db.models.OneToOneField",
"django.db.migrations.swappable_dependency",
"django.db.models.ManyToManyField",
"django.db.models.ForeignKey"
] | [((387, 444), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (418, 444), False, 'from django.db import migrations, models\n'), ((748, 844), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.... |
from glyphNameFormatter.data.scriptPrefixes import scriptPrefixes
def process(self):
if self.has("LATIN"):
self.scriptTag = scriptPrefixes['latin']
if self.has("ARMENIAN"):
# self.scriptTag = scriptPrefixes['armenian']
self.processAs("Armenian")
elif self.has("HEBREW"):
# s... | [
"glyphNameFormatter.exporters.printRange"
] | [((854, 897), 'glyphNameFormatter.exporters.printRange', 'printRange', (['"""Alphabetic Presentation Forms"""'], {}), "('Alphabetic Presentation Forms')\n", (864, 897), False, 'from glyphNameFormatter.exporters import printRange\n')] |