code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import pytorch_lightning as pl
import torch.nn as nn
from loguru import logger
from torch.optim import Adam
from torchnlp.datasets import imdb_dataset # type: ignore
from slp.data.collators import SequenceClassificationCollator
from slp.modules.classifier import RNNTokenSequenceClassifier
from slp.plbind.dm import PL... | [
"torch.nn.CrossEntropyLoss",
"slp.plbind.trainer.make_trainer",
"slp.modules.classifier.RNNTokenSequenceClassifier",
"torchnlp.datasets.imdb_dataset",
"slp.plbind.trainer.watch_model",
"pytorch_lightning.metrics.classification.Accuracy",
"slp.data.collators.SequenceClassificationCollator",
"pytorch_li... | [((557, 624), 'slp.data.collators.SequenceClassificationCollator', 'SequenceClassificationCollator', ([], {'device': '"""cpu"""', 'max_length': 'MAX_LENGTH'}), "(device='cpu', max_length=MAX_LENGTH)\n", (587, 624), False, 'from slp.data.collators import SequenceClassificationCollator\n'), ((718, 760), 'pytorch_lightnin... |
import json
import sys
# Given a time in seconds, returns the number of whole months represented.
def months(t):
return int(t / 60 / 60 / 24 / 30)
# Given a time in seconds, returns the number of whole days represented.
def days(t):
return int(t / 60 / 60 / 24)
def hours(t):
return int(t / 60 / 60)
def ... | [
"sys.stdin.read",
"json.dumps"
] | [((1047, 1073), 'json.dumps', 'json.dumps', (['data'], {'indent': '(4)'}), '(data, indent=4)\n', (1057, 1073), False, 'import json\n'), ((1140, 1156), 'sys.stdin.read', 'sys.stdin.read', ([], {}), '()\n', (1154, 1156), False, 'import sys\n')] |
import sympy as sp #math library to represent functions, we will write our own problem solving expressions
from sympy import cos, cosh, sin, sinh
import numpy as np
import matplotlib.pyplot as mplot
x = sp.Symbol('x')
s = sp.Symbol('s')
r1 = 1.87527632324985
r2 = 4.69409122046058
r3 = 7.855
#Superimpose plots
q... | [
"sympy.sin",
"sympy.Symbol",
"matplotlib.pyplot.grid",
"sympy.cos",
"matplotlib.pyplot.ylabel",
"sympy.cosh",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.array",
"matplotlib.pyplot.title",
"sympy.sinh",
"numpy.arange",
"matplotlib.pyplot.show"
] | [((209, 223), 'sympy.Symbol', 'sp.Symbol', (['"""x"""'], {}), "('x')\n", (218, 223), True, 'import sympy as sp\n'), ((228, 242), 'sympy.Symbol', 'sp.Symbol', (['"""s"""'], {}), "('s')\n", (237, 242), True, 'import sympy as sp\n'), ((2044, 2068), 'numpy.arange', 'np.arange', (['(0)', '(1.01)', '(0.01)'], {}), '(0, 1.01,... |
from unetgan.train_big import train_ubiggan
from unetgan.test_model import test_model
from unetgan.test_single import test_single
if __name__ == "__main__":
# Only for 100k iters
train_ubiggan(train_path=".", latent_dim=140, num_epochs=80)
# test_model()
# test_single()
| [
"unetgan.train_big.train_ubiggan"
] | [((188, 248), 'unetgan.train_big.train_ubiggan', 'train_ubiggan', ([], {'train_path': '"""."""', 'latent_dim': '(140)', 'num_epochs': '(80)'}), "(train_path='.', latent_dim=140, num_epochs=80)\n", (201, 248), False, 'from unetgan.train_big import train_ubiggan\n')] |
from tkinter import *
from tkinter import ttk
from .tab0 import job
from .tab1 import stattistics
from .bar_menu import BarMenu
from .json_access import save_global_vars
save_global_vars() # Устанавливаем значения по умолчанию
root = Tk() # Основной класс
root.title("Клиент состояния бота.") # Задаём название дл... | [
"tkinter.ttk.Frame",
"tkinter.ttk.Notebook"
] | [((479, 497), 'tkinter.ttk.Notebook', 'ttk.Notebook', (['root'], {}), '(root)\n', (491, 497), False, 'from tkinter import ttk\n'), ((596, 618), 'tkinter.ttk.Frame', 'ttk.Frame', (['tab_control'], {}), '(tab_control)\n', (605, 618), False, 'from tkinter import ttk\n'), ((626, 648), 'tkinter.ttk.Frame', 'ttk.Frame', (['t... |
#!../../../../virtualenv/bin/python3
# -*- coding: utf-8 -*-
# NB: The shebang line above assumes you've installed a python virtual environment alongside your working copy of the
# <4most-4gp-scripts> git repository. It also only works if you invoke this python script from the directory where it
# is located. If these... | [
"os.path.abspath",
"fourgp_speclib.SpectrumLibrarySqlite.open_and_search",
"os.path.join",
"argparse.ArgumentParser"
] | [((746, 790), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '__doc__'}), '(description=__doc__)\n', (769, 790), False, 'import argparse\n'), ((2150, 2262), 'fourgp_speclib.SpectrumLibrarySqlite.open_and_search', 'SpectrumLibrarySqlite.open_and_search', ([], {'library_spec': 'args.library', ... |
from setuptools import setup, find_packages
__version__ = '0.0.1'
setup(
name='aiomailserver',
version=__version__,
description='aiomailserver - asyncio based simple mail server',
long_description="",
author='https://github.com/kozzztik',
url='https://github.com/kozzztik/aiomailserver',
... | [
"setuptools.find_packages"
] | [((351, 366), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (364, 366), False, 'from setuptools import setup, find_packages\n')] |
"""empty message
Revision ID: <KEY>8
Revises:
Create Date: 2021-05-16 17:09:44.853004
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():... | [
"sqlalchemy.ForeignKeyConstraint",
"sqlalchemy.DateTime",
"alembic.op.drop_table",
"sqlalchemy.Text",
"sqlalchemy.Boolean",
"sqlalchemy.PrimaryKeyConstraint",
"sqlalchemy.dialects.postgresql.UUID",
"sqlalchemy.UniqueConstraint",
"sqlalchemy.String",
"sqlalchemy.Enum"
] | [((3480, 3510), 'alembic.op.drop_table', 'op.drop_table', (['"""user_calendar"""'], {}), "('user_calendar')\n", (3493, 3510), False, 'from alembic import op\n'), ((3515, 3542), 'alembic.op.drop_table', 'op.drop_table', (['"""sync_flows"""'], {}), "('sync_flows')\n", (3528, 3542), False, 'from alembic import op\n'), ((3... |
# -*- coding: utf-8 -*-
import os
import asyncio
from hashlib import md5
from pathlib import Path
from tempfile import mkstemp
from base64 import b64decode, b64encode
from collections import namedtuple
from lxml import etree
from .. import getLogger
from ..errors import (BadRequestStanzaError, XmppError,
... | [
"lxml.etree.Element",
"collections.namedtuple",
"hashlib.md5",
"pathlib.Path",
"os.close",
"os.write",
"base64.b64encode",
"base64.b64decode",
"os.path.isfile",
"os.remove"
] | [((788, 830), 'collections.namedtuple', 'namedtuple', (['"""RangeTuple"""', '"""offset, length"""'], {}), "('RangeTuple', 'offset, length')\n", (798, 830), False, 'from collections import namedtuple\n'), ((897, 962), 'collections.namedtuple', 'namedtuple', (['"""FileInfo"""', '"""name, size, desc, date, md5, range, sid... |
import numpy as np
import torch
import numpy.linalg as linalg
import scipy.stats as stats
import pickle
from sys import exit
m = 20
n = 40
K = 5
np.random.seed(0)
U = stats.ortho_group.rvs(m)[:, 0:K]
V = stats.ortho_group.rvs(n)[:, 0:K]
mu_mn = np.sqrt(m + n + 2*np.sqrt(m*n))
D = np.random.uniform(low = 1/2*mu_mn, h... | [
"numpy.random.normal",
"numpy.copy",
"pickle.dump",
"numpy.sqrt",
"numpy.random.poisson",
"scipy.stats.ortho_group.rvs",
"numpy.random.binomial",
"numpy.exp",
"numpy.array",
"numpy.matmul",
"numpy.random.seed",
"numpy.random.uniform",
"numpy.arange",
"numpy.random.shuffle"
] | [((147, 164), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (161, 164), True, 'import numpy as np\n'), ((284, 348), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(1 / 2 * mu_mn)', 'high': '(3 / 2 * mu_mn)', 'size': 'K'}), '(low=1 / 2 * mu_mn, high=3 / 2 * mu_mn, size=K)\n', (301, 348), Tru... |
import asyncio
from aiogram import types
from loader import dp,db
@dp.message_handler(commands=['count'])
async def send_phone(message: types.Message):
first_name = message.from_user.first_name
users_count = await db.count_users()
if users_count >= 4:
await message.answer(f"{first_name},наразі кі... | [
"loader.dp.message_handler",
"loader.db.count_users"
] | [((70, 108), 'loader.dp.message_handler', 'dp.message_handler', ([], {'commands': "['count']"}), "(commands=['count'])\n", (88, 108), False, 'from loader import dp, db\n'), ((225, 241), 'loader.db.count_users', 'db.count_users', ([], {}), '()\n', (239, 241), False, 'from loader import dp, db\n')] |
from cg import *
from random import randint
n = 50
m = 1000
c = CG()
a = [Var("int") for i in range(n)]
b = [Var("int") for i in range(n)]
for v in a:
c.init(v, randint(0,m))
for v in b:
c.init(v, randint(0,m))
s = Var("int")
c.init(s, 0)
for u in a:
for v in b:
tmp = Var("int")
c.op_mul... | [
"random.randint"
] | [((167, 180), 'random.randint', 'randint', (['(0)', 'm'], {}), '(0, m)\n', (174, 180), False, 'from random import randint\n'), ((207, 220), 'random.randint', 'randint', (['(0)', 'm'], {}), '(0, m)\n', (214, 220), False, 'from random import randint\n')] |
#!/usr/bin/python
from jinja2 import Template, Environment, FileSystemLoader
import json
import autopep8
import os
import re
import sys
def replaceSpecialChars(str):
return str.replace('-', '_').replace('.', '_').replace('+', 'plus')
def getModuleName(path, name):
return replaceSpecialChars(path.lower()) + "... | [
"os.path.exists",
"json.loads",
"jinja2.Environment",
"os.makedirs",
"os.popen",
"jinja2.FileSystemLoader",
"re.sub",
"generate_modules_utility.generate_cofiguration_fact_rst"
] | [((3344, 3378), 're.sub', 're.sub', (['regex', '"""\\\\g<1>\\\\g<4>"""', 'str'], {}), "(regex, '\\\\g<1>\\\\g<4>', str)\n", (3350, 3378), False, 'import re\n'), ((3414, 3442), 're.sub', 're.sub', (['regex', '"""\\\\g<1>"""', 'str'], {}), "(regex, '\\\\g<1>', str)\n", (3420, 3442), False, 'import re\n'), ((3625, 3662), ... |
from django.db import models
from server.settings import AUTH_USER_MODEL
def post_file_path(instance, filename):
return f'user_{instance.user.id}/posts/{filename}'
class Category(models.Model):
name = models.CharField(max_length=255)
avatar = models.ImageField(default="", upload_to="category_images")
... | [
"django.db.models.TextField",
"django.db.models.ForeignKey",
"django.db.models.DateTimeField",
"django.db.models.ImageField",
"django.db.models.CharField"
] | [((214, 246), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(255)'}), '(max_length=255)\n', (230, 246), False, 'from django.db import models\n'), ((260, 318), 'django.db.models.ImageField', 'models.ImageField', ([], {'default': '""""""', 'upload_to': '"""category_images"""'}), "(default='', upl... |
# Generated by Django 2.2.2 on 2019-07-07 09:09
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('research', '0002_auto_20... | [
"django.db.migrations.swappable_dependency",
"django.db.migrations.RenameField",
"django.db.models.ForeignKey"
] | [((227, 284), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (258, 284), False, 'from django.db import migrations, models\n'), ((369, 447), 'django.db.migrations.RenameField', 'migrations.RenameField', ([], {'model_name... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
from setuptools import setup, find_packages
requirements = ('numpy', 'opencv-python', 'solt==0.1.8', 'pyyaml',
'torch>=1.3.1', 'tqdm', 'scikit-learn', 'tensorboard', 'dill', 'matplotlib',
'pandas', 'pretrainedmodels... | [
"setuptools.find_packages"
] | [((1351, 1386), 'setuptools.find_packages', 'find_packages', ([], {'include': "['collagen']"}), "(include=['collagen'])\n", (1364, 1386), False, 'from setuptools import setup, find_packages\n')] |
# -*- coding: utf-8 -*-
try:
# Python 2.7
from collections import OrderedDict
except:
# Python 2.6
from gluon.contrib.simplejson.ordered_dict import OrderedDict
from gluon import current
from gluon.storage import Storage
def config(settings):
"""
Template settings for MAVC
"""
T ... | [
"gluon.H2",
"gluon.current.deployment_settings.get_hrm_staff_label",
"gluon.current.auth.is_logged_in",
"s3.s3_rheader_resource",
"s3.s3_rheader_tabs",
"s3.S3LocationSelector",
"gluon.contrib.simplejson.ordered_dict.OrderedDict",
"gluon.H1"
] | [((2142, 2193), 'gluon.contrib.simplejson.ordered_dict.OrderedDict', 'OrderedDict', (["[('en', 'English'), ('tl', 'Tagalog')]"], {}), "([('en', 'English'), ('tl', 'Tagalog')])\n", (2153, 2193), False, 'from gluon.contrib.simplejson.ordered_dict import OrderedDict\n'), ((17477, 17499), 's3.s3_rheader_resource', 's3_rhea... |
import re
from emoji.unicode_codes import UNICODE_EMOJI
from nonebot import on_regex
from nonebot.params import RegexDict
from nonebot.plugin import PluginMetadata
from nonebot.adapters.onebot.v11 import MessageSegment
from .config import Config
from .data_source import mix_emoji
__plugin_meta__ = PluginM... | [
"nonebot.plugin.PluginMetadata",
"re.escape",
"nonebot.adapters.onebot.v11.MessageSegment.image",
"nonebot.params.RegexDict",
"nonebot.on_regex"
] | [((313, 538), 'nonebot.plugin.PluginMetadata', 'PluginMetadata', ([], {'name': '"""emoji合成"""', 'description': '"""将两个emoji合成为一张图片"""', 'usage': '"""{emoji1}+{emoji2},如:😎+😁"""', 'config': 'Config', 'extra': "{'unique_name': 'emojimix', 'example': '😎+😁', 'author': 'meetwq <<EMAIL>>',\n 'version': '0.1.7'}"}), "(n... |
"""Bioconda Bot"""
import logging
import subprocess
import time
import aiohttp
from .config import BOT_NAME, APP_KEY, APP_ID
from .views import web_routes
from .. import utils
from ..githubhandler import GitHubAppHandler
from .. import __version__ as VERSION
logger = logging.getLogger(__name__) # pylint: disable=... | [
"logging.getLogger",
"aiohttp.ClientSession",
"subprocess.Popen",
"aiohttp.web.Application",
"time.sleep"
] | [((273, 300), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (290, 300), False, 'import logging\n'), ((757, 782), 'aiohttp.web.Application', 'aiohttp.web.Application', ([], {}), '()\n', (780, 782), False, 'import aiohttp\n'), ((852, 875), 'aiohttp.ClientSession', 'aiohttp.ClientSession', ... |
#============================================================================
#
# Copyright (c) Kitware 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... | [
"RegisterWidget.RegisterWidget"
] | [((1314, 1349), 'RegisterWidget.RegisterWidget', 'RegisterWidget.RegisterWidget', (['self'], {}), '(self)\n', (1343, 1349), False, 'import RegisterWidget\n'), ((1659, 1694), 'RegisterWidget.RegisterWidget', 'RegisterWidget.RegisterWidget', (['self'], {}), '(self)\n', (1688, 1694), False, 'import RegisterWidget\n')] |
import numpy as np
from tensorflow import keras
from tensorflow.keras import backend as K
class WarmUpLearningRateScheduler(keras.callbacks.Callback):
"""Warmup learning rate scheduler
"""
def __init__(self, warmup_batches, init_lr, verbose=0):
"""Constructor for warmup learning rate scheduler
... | [
"tensorflow.keras.utils.to_categorical",
"numpy.random.random",
"tensorflow.keras.backend.get_value",
"numpy.random.randint",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.backend.set_value",
"tensorflow.keras.models.Sequential"
] | [((1553, 1565), 'tensorflow.keras.models.Sequential', 'Sequential', ([], {}), '()\n', (1563, 1565), False, 'from tensorflow.keras.models import Sequential\n'), ((2087, 2124), 'numpy.random.random', 'np.random.random', (['(sample_count, 100)'], {}), '((sample_count, 100))\n', (2103, 2124), True, 'import numpy as np\n'),... |
from astropy.cosmology import WMAP7 as cosmo
from astropy.constants import c as C
from astropy import units as u
from astropy.table import Table
from astropy.io import ascii
import numpy as np
from linetools import utils as ltu
from linetools.isgm.abscomponent import AbsComponent
from linetools.spectra.io import readsp... | [
"numpy.alltrue",
"numpy.sqrt",
"linetools.spectra.xspectrum1d.XSpectrum1D.from_tuple",
"pyntejos.io.table_from_marzfile",
"scipy.stats.sigmaclip",
"numpy.argsort",
"numpy.array",
"linetools.utils.dz_from_dv",
"linetools.utils.is_local_minima",
"numpy.mean",
"linetools.isgm.abscomponent.AbsCompon... | [((1342, 1354), 'numpy.array', 'np.array', (['z1'], {}), '(z1)\n', (1350, 1354), True, 'import numpy as np\n'), ((1364, 1376), 'numpy.array', 'np.array', (['z2'], {}), '(z2)\n', (1372, 1376), True, 'import numpy as np\n'), ((1386, 1398), 'numpy.array', 'np.array', (['dv'], {}), '(dv)\n', (1394, 1398), True, 'import num... |
from django import forms
from .models import Comment,Profile ,Pic
class ProfileForm(forms.ModelForm):
model = Profile
username = forms.CharField(label='Username', max_length=40)
bio = forms.CharField(label='Image Caption', max_length=500)
profile_pic = forms.ImageField(label='Image Field')
class Pr... | [
"django.forms.ImageField",
"django.forms.CharField"
] | [((140, 188), 'django.forms.CharField', 'forms.CharField', ([], {'label': '"""Username"""', 'max_length': '(40)'}), "(label='Username', max_length=40)\n", (155, 188), False, 'from django import forms\n'), ((200, 254), 'django.forms.CharField', 'forms.CharField', ([], {'label': '"""Image Caption"""', 'max_length': '(500... |
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('core.urls', namespace='core')),
path('accounts/', include('accounts.urls', namespace=... | [
"django.conf.urls.static.static",
"django.urls.path",
"django.urls.include"
] | [((174, 205), 'django.urls.path', 'path', (['"""admin/"""', 'admin.site.urls'], {}), "('admin/', admin.site.urls)\n", (178, 205), False, 'from django.urls import path, include\n'), ((449, 512), 'django.conf.urls.static.static', 'static', (['settings.STATIC_URL'], {'document_root': 'settings.STATIC_ROOT'}), '(settings.S... |
from functools import reduce
from pairs.ir.ast_node import ASTNode
from pairs.ir.data_types import Type_Vector
from pairs.ir.lit import as_lit_ast
from pairs.ir.vector_expr import VectorExpression
class Assign(ASTNode):
def __init__(self, sim, dest, src):
super().__init__(sim)
self.type = dest.typ... | [
"functools.reduce",
"pairs.ir.lit.as_lit_ast"
] | [((338, 358), 'pairs.ir.lit.as_lit_ast', 'as_lit_ast', (['sim', 'src'], {}), '(sim, src)\n', (348, 358), False, 'from pairs.ir.lit import as_lit_ast\n'), ((967, 1035), 'functools.reduce', 'reduce', (['(lambda x, y: x + y)', '[[a[0], a[1]] for a in self.assignments]'], {}), '(lambda x, y: x + y, [[a[0], a[1]] for a in s... |
#!/usr/bin/env python
# coding: utf-8
import os
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_table as dt
import plotly as py
import plotly.graph_objects as go
import pandas as pd
import numpy as np
# init dash app
from dash.dependencies import Input, Output
from src.... | [
"plotly.graph_objects.Layout",
"pandas.read_csv",
"dash_html_components.P",
"dash.dependencies.Output",
"os.path.join",
"dash.dependencies.Input",
"plotly.graph_objects.Figure",
"dash_html_components.H2",
"dash_html_components.H1",
"dash_table.DataTable",
"dash.Dash",
"dash_core_components.Gra... | [((415, 477), 'dash.Dash', 'dash.Dash', (['__name__'], {'external_stylesheets': 'external_stylesheets'}), '(__name__, external_stylesheets=external_stylesheets)\n', (424, 477), False, 'import dash\n'), ((852, 907), 'os.path.join', 'os.path.join', (['__file__', '"""../../data/movies_cleaned.csv"""'], {}), "(__file__, '.... |
import os
import unittest
import pandas as pd
from dataverk import Datapackage
from dataverk.views.json_spec import JsonSpecView
DP_NAME = "Test"
BUCKET_NAME = "bucket-name"
VISUALIZATION_NAME = "plotlyviz"
DATATABLE_VIZ_NAME = "thetable"
DATATABLE_SPEC = pd.DataFrame()
class TestRemoteSpecViews(unittest.TestCase... | [
"pandas.DataFrame",
"dataverk.views.json_spec.JsonSpecView",
"dataverk.Datapackage"
] | [((260, 274), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (272, 274), True, 'import pandas as pd\n'), ((565, 596), 'dataverk.Datapackage', 'Datapackage', (["{'title': DP_NAME}"], {}), "({'title': DP_NAME})\n", (576, 596), False, 'from dataverk import Datapackage\n'), ((940, 1051), 'dataverk.views.json_spec.Js... |
from __future__ import print_function
from urllib import request
import datetime
import hashlib
import json
import os
import re
from io import BytesIO
import gzip
HEADERS = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', # noqa
'Accept-Charset': 'UTF-8,*;q=0.5',
'Accept-Enc... | [
"json.loads",
"re.compile",
"urllib.request.Request",
"os.getcwd",
"gzip.GzipFile",
"re.sub",
"urllib.request.urlopen",
"re.search"
] | [((541, 586), 're.sub', 're.sub', (['"""[\\\\\\\\\\\\/:\\\\*\\\\?"<>|]"""', '"""_"""', 'filename'], {}), '(\'[\\\\\\\\\\\\/:\\\\*\\\\?"<>|]\', \'_\', filename)\n', (547, 586), False, 'import re\n'), ((1899, 1928), 'gzip.GzipFile', 'gzip.GzipFile', ([], {'fileobj': 'buffer'}), '(fileobj=buffer)\n', (1912, 1928), False, ... |
import glob, os
def rename(dir, pattern, titlePattern):
for pathAndFilename in glob.iglob(os.path.join(dir, pattern)):
title, ext = os.path.splitext(os.path.basename(pathAndFilename))
os.rename(pathAndFilename,
os.path.join(dir, titlePattern % title + ext))
if __name__=='__mai... | [
"os.path.join",
"os.path.basename",
"os.getcwd"
] | [((96, 122), 'os.path.join', 'os.path.join', (['dir', 'pattern'], {}), '(dir, pattern)\n', (108, 122), False, 'import glob, os\n'), ((163, 196), 'os.path.basename', 'os.path.basename', (['pathAndFilename'], {}), '(pathAndFilename)\n', (179, 196), False, 'import glob, os\n'), ((252, 297), 'os.path.join', 'os.path.join',... |
from fenics import *
import numpy as np
import matplotlib.pyplot as plt
parameters["form_compiler"]["quadrature_degree"] = 4
parameters["form_compiler"]["cpp_optimize"] = True
def load_ellipsoid_data():
"""Returns 4-tuple:
mesh - the mesh,
mf - MeshFunction defining boundary markers,
numbering - dic... | [
"dolfin.Function",
"dolfin.Mesh",
"dolfin.MeshFunction",
"dolfin.FunctionSpace"
] | [((432, 483), 'dolfin.Mesh', 'dolfin.Mesh', (['dolfin.MPI.comm_world', '"""data/mesh.xml"""'], {}), "(dolfin.MPI.comm_world, 'data/mesh.xml')\n", (443, 483), False, 'import dolfin\n'), ((493, 555), 'dolfin.MeshFunction', 'dolfin.MeshFunction', (['"""size_t"""', 'mesh', '"""data/facet_function.xml"""'], {}), "('size_t',... |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 23 18:44:48 2019
把轨迹数据填充到轨迹网格中,然后利用cnn深度学习的方法预测
@author: dell
"""
import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers.convolutional import Convolution2D, MaxPooling2D
fro... | [
"keras.layers.Flatten",
"pandas.read_csv",
"keras.layers.convolutional.Convolution2D",
"sklearn.model_selection.train_test_split",
"numpy.asarray",
"keras.models.Sequential",
"numpy.zeros",
"keras.layers.convolutional.MaxPooling2D",
"keras.layers.Dense",
"keras.layers.Dropout"
] | [((385, 487), 'pandas.read_csv', 'pd.read_csv', (['"""F:\\\\python and machine learning\\\\track data and travel prediction\\\\sample_cnn"""'], {}), "(\n 'F:\\\\python and machine learning\\\\track data and travel prediction\\\\sample_cnn'\n )\n", (396, 487), True, 'import pandas as pd\n'), ((1299, 1338), 'numpy.... |
from datetime import datetime, timedelta
from collections import defaultdict
import os
import glob
import yaml
from airflow import DAG
from airflow.operators.data_quality_threshold_check_operator import DataQualityThresholdCheckOperator
from airflow.operators.data_quality_threshold_sql_check_operator import DataQualit... | [
"datetime.datetime",
"airflow.operators.data_quality_threshold_check_operator.DataQualityThresholdCheckOperator",
"airflow.operators.dummy_operator.DummyOperator",
"yaml.safe_load",
"collections.defaultdict",
"airflow.DAG",
"datetime.timedelta",
"airflow.operators.data_quality_threshold_sql_check_oper... | [((683, 776), 'airflow.DAG', 'DAG', (['"""yaml_data_quality_check_dag"""'], {'default_args': 'default_args', 'schedule_interval': '"""@daily"""'}), "('yaml_data_quality_check_dag', default_args=default_args,\n schedule_interval='@daily')\n", (686, 776), False, 'from airflow import DAG\n'), ((2485, 2550), 'airflow.op... |
# -*- coding: utf-8 -*-
"""Test working of extension."""
import os
import pytest
from tests import TEST_DOCS_SRC
from sphinx_search.extension import ASSETS_FILES
@pytest.mark.sphinx(srcdir=TEST_DOCS_SRC)
def test_static_files_exists(app, status, warning):
"""Test if the static files are present in the _build f... | [
"pytest.mark.sphinx",
"os.path.exists",
"os.path.join"
] | [((168, 208), 'pytest.mark.sphinx', 'pytest.mark.sphinx', ([], {'srcdir': 'TEST_DOCS_SRC'}), '(srcdir=TEST_DOCS_SRC)\n', (186, 208), False, 'import pytest\n'), ((653, 757), 'pytest.mark.sphinx', 'pytest.mark.sphinx', ([], {'srcdir': 'TEST_DOCS_SRC', 'confoverrides': "{'rtd_sphinx_search_file_type': 'minified'}"}), "(sr... |
# Copyright 2020 University Of Delhi.
#
# 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 wr... | [
"datetime.datetime.strptime",
"logging.getLogger"
] | [((816, 870), 'datetime.datetime.strptime', 'dt.strptime', (["report['start_date']", '"""%Y-%m-%d %H:%M:%S"""'], {}), "(report['start_date'], '%Y-%m-%d %H:%M:%S')\n", (827, 870), True, 'from datetime import datetime as dt\n'), ((887, 940), 'datetime.datetime.strptime', 'dt.strptime', (["report['stop_date']", '"""%Y-%m-... |
from __future__ import absolute_import, division, print_function
from concurrent.futures import Future
from dask import delayed
from daskos.delayed import MesosDelayed, MesosDelayedLeaf, mesos
from daskos.utils import key_split
from satyr.proxies.messages import Cpus, Disk, Mem
# tests are not modules, so these are ... | [
"dask.delayed",
"daskos.delayed.mesos",
"satyr.proxies.messages.Mem",
"daskos.utils.key_split",
"satyr.proxies.messages.Disk",
"satyr.proxies.messages.Cpus"
] | [((335, 375), 'daskos.delayed.mesos', 'mesos', ([], {'cpus': '(0.1)', 'mem': '(256)', 'docker': '"""test1"""'}), "(cpus=0.1, mem=256, docker='test1')\n", (340, 375), False, 'from daskos.delayed import MesosDelayed, MesosDelayedLeaf, mesos\n'), ((411, 451), 'daskos.delayed.mesos', 'mesos', ([], {'cpus': '(0.2)', 'mem': ... |
#!/usr/bin/env python3
import itertools
from os.path import join, exists
from os import mkdir
from sys import stderr
import argparse
# command for finding the best configuration from log*.err files
# for X in log.*.err ; do cat $X | grep acc | sed "s/\(epoch [^ ]*\)\(.* acc: \)\([^ ]*\).*/\3 \1 $X/" ; done | sort -n... | [
"os.path.exists",
"argparse.ArgumentParser",
"itertools.product",
"os.path.join",
"os.mkdir"
] | [((6164, 6189), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (6187, 6189), False, 'import argparse\n'), ((2623, 2648), 'itertools.product', 'itertools.product', (['*confs'], {}), '(*confs)\n', (2640, 2648), False, 'import itertools\n'), ((4625, 4640), 'os.path.exists', 'exists', (['dirname'],... |
'''
Function:
stackoverflow模拟登录
Author:
Charles
微信公众号:
Charles的皮卡丘
更新日期:
2022-03-10
'''
import re
import requests
'''PC端登录stackoverflow'''
class stackoverflowPC():
is_callable = True
def __init__(self, **kwargs):
for key, value in kwargs.items(): setattr(self, key, value)
self.... | [
"re.findall",
"requests.Session"
] | [((386, 404), 'requests.Session', 'requests.Session', ([], {}), '()\n', (402, 404), False, 'import requests\n'), ((1965, 2010), 're.findall', 're.findall', (['""""fkey":"([^"]+)\\""""', 'response.text'], {}), '(\'"fkey":"([^"]+)"\', response.text)\n', (1975, 2010), False, 'import re\n'), ((1293, 1354), 're.findall', 'r... |
# Generated by Django 3.0.7 on 2022-02-24 20:36
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("clientes", "0005_auto_20190408_1309")]
operations = [
migrations.AlterModelOptions(
name="cliente",
options={"verbose_name": "Cliente", "... | [
"django.db.migrations.AlterModelOptions",
"django.db.migrations.AlterModelTable"
] | [((213, 333), 'django.db.migrations.AlterModelOptions', 'migrations.AlterModelOptions', ([], {'name': '"""cliente"""', 'options': "{'verbose_name': 'Cliente', 'verbose_name_plural': 'Clientes'}"}), "(name='cliente', options={'verbose_name':\n 'Cliente', 'verbose_name_plural': 'Clientes'})\n", (241, 333), False, 'fro... |
from pydantic import BaseModel, Field, PositiveInt
try:
# this won't work since PositiveInt takes precedence over the
# constraints defined in Field meaning they're ignored
class Model(BaseModel):
foo: PositiveInt = Field(..., lt=10)
except ValueError as e:
print(e)
# but you can set the sche... | [
"pydantic.Field"
] | [((442, 473), 'pydantic.Field', 'Field', (['...'], {'exclusiveMaximum': '(10)'}), '(..., exclusiveMaximum=10)\n', (447, 473), False, 'from pydantic import BaseModel, Field, PositiveInt\n'), ((795, 818), 'pydantic.Field', 'Field', (['...'], {'gt': '(0)', 'lt': '(10)'}), '(..., gt=0, lt=10)\n', (800, 818), False, 'from p... |
from numba import autojit
from time import time
LIMIT = pow(10, 6)
def primes(limit):
# Keep only odd numbers in sieve, mapping from index to number is
# num = 2 * idx + 3
# The square of the number corresponding to idx then corresponds to:
# idx2 = 2*idx*idx + 6*idx + 3
sieve = [True] * (limit /... | [
"numba.autojit",
"time.time"
] | [((635, 650), 'numba.autojit', 'autojit', (['primes'], {}), '(primes)\n', (642, 650), False, 'from numba import autojit\n'), ((660, 666), 'time.time', 'time', ([], {}), '()\n', (664, 666), False, 'from time import time\n'), ((693, 699), 'time.time', 'time', ([], {}), '()\n', (697, 699), False, 'from time import time\n'... |
import roots
def test_quadroots_result():
assert roots.quad_roots(1.0, 1.0, -12.0) == ((3+0j), (-4+0j))
def test_quadroots_types():
try:
roots.quad_roots("", "green", "hi")
except TypeError as err:
assert(type(err) == TypeError)
def test_quadroots_zerocoeff():
try:
roots.quad_... | [
"roots.quad_roots",
"roots.linear_roots"
] | [((54, 87), 'roots.quad_roots', 'roots.quad_roots', (['(1.0)', '(1.0)', '(-12.0)'], {}), '(1.0, 1.0, -12.0)\n', (70, 87), False, 'import roots\n'), ((155, 190), 'roots.quad_roots', 'roots.quad_roots', (['""""""', '"""green"""', '"""hi"""'], {}), "('', 'green', 'hi')\n", (171, 190), False, 'import roots\n'), ((309, 332)... |
import datetime
import django
from django import db
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.shortcuts import _get_queryset
from django.utils import six
from django.utils.text import slugify
try:
from django.utils import timezone
except ImportError:
t... | [
"django.shortcuts._get_queryset",
"django.http.HttpResponse",
"django.db.models.get_model",
"django.utils.timezone.get_current_timezone",
"django.core.serializers.get_serializer",
"datetime.datetime.now",
"unidecode.unidecode",
"django.utils.functional.lazy",
"django.core.urlresolvers.resolve",
"d... | [((6667, 6693), 'django.shortcuts._get_queryset', '_get_queryset', (['model_class'], {}), '(model_class)\n', (6680, 6693), False, 'from django.shortcuts import _get_queryset\n'), ((10337, 10402), 'django.http.HttpResponse', 'HttpResponse', ([], {'mimetype': '_JSON_MIME_TYPE', 'content_type': 'content_type'}), '(mimetyp... |
import socket
import threading
FORMAT = 'utf-8'
HEADER = 64
PORT = 5050
# SERVER = '<ip_here>
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
DISCONNECT_MESSAGE = "$$__DISCONNECT"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def handle_client(conn, addr):
... | [
"threading.active_count",
"threading.Thread",
"socket.gethostname",
"socket.socket"
] | [((217, 266), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (230, 266), False, 'import socket\n'), ((125, 145), 'socket.gethostname', 'socket.gethostname', ([], {}), '()\n', (143, 145), False, 'import socket\n'), ((934, 991), 'threading.Threa... |
"""main application and routing logic for twitoff."""
from decouple import config
from flask import Flask, render_template, request
from .models import DB, User
from .twitter import add_user
def create_app():
"""create/configure flask application."""
app = Flask(__name__)
# config link to database an... | [
"flask.render_template",
"decouple.config",
"flask.Flask"
] | [((267, 282), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (272, 282), False, 'from flask import Flask, render_template, request\n'), ((466, 488), 'decouple.config', 'config', (['"""DATABASE_URL"""'], {}), "('DATABASE_URL')\n", (472, 488), False, 'from decouple import config\n'), ((513, 526), 'decouple.c... |
import inspect
from datetime import datetime
import csv
from pathlib import Path
from typing import List, Set, Dict, Tuple, Optional, Iterable, Mapping, Union, Callable
import warnings
def now2str():
print("ho")
now = datetime.now()
now_str = now.strftime("%Y%m%d-%H%M%S")
return now_str
def print_mro(... | [
"csv.DictWriter",
"datetime.datetime.now",
"inspect.isclass"
] | [((227, 241), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (239, 241), False, 'from datetime import datetime\n'), ((425, 443), 'inspect.isclass', 'inspect.isclass', (['x'], {}), '(x)\n', (440, 443), False, 'import inspect\n'), ((972, 1016), 'csv.DictWriter', 'csv.DictWriter', (['csv_f'], {'fieldnames': 'f... |
# mypy: allow-untyped-defs, no-strict-optional
import pytest
from advpipe.language_model.label_classification import OrganismLabelClassifier
@pytest.fixture
def organism_label_classifier():
return OrganismLabelClassifier()
organism_labels = [
'Arctic Wolf',
'Basilisk',
'Black panther',
'Bobolin... | [
"pytest.mark.parametrize",
"advpipe.language_model.label_classification.OrganismLabelClassifier"
] | [((3785, 3843), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""organism_label"""', 'organism_labels'], {}), "('organism_label', organism_labels)\n", (3808, 3843), False, 'import pytest\n'), ((3992, 4046), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""object_label"""', 'object_labels'], {}), "... |
import logging
from .api import daily # noqa
from .api import monthly # noqa
from .api import daily # noqa
from .api import monthly # noqa
from .api import monthly_rates_of_change # noqa
from .api import climatology_average_rates_of_change # noqa
from .api import nday_average # noqa
from .api import scale # no... | [
"logging.NullHandler",
"logging.getLogger"
] | [((605, 626), 'logging.NullHandler', 'logging.NullHandler', ([], {}), '()\n', (624, 626), False, 'import logging\n'), ((566, 593), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (583, 593), False, 'import logging\n')] |
# -*- coding: utf-8 -*-
from openerp import models, fields
class LibraryBook(models.Model):
_name = 'library.book'
name = fields.Char('Title', required=True)
date_release = fields.Date('Release Date')
author_ids = fields.Many2many('res.partner', string='Authors')
publisher_id = fields.Many2one(
... | [
"openerp.fields.Many2one",
"openerp.fields.Date",
"openerp.fields.Char",
"openerp.fields.Many2many"
] | [((132, 167), 'openerp.fields.Char', 'fields.Char', (['"""Title"""'], {'required': '(True)'}), "('Title', required=True)\n", (143, 167), False, 'from openerp import models, fields\n'), ((187, 214), 'openerp.fields.Date', 'fields.Date', (['"""Release Date"""'], {}), "('Release Date')\n", (198, 214), False, 'from openerp... |
#Imports the modules required
from covid_data_handler import *
import covid_news_handling
import logging_code as log
def test_parse_csv_data():
'''
tests if the data returns the correct information
by checking the length of the file when using the
function
'''
data = parse_csv_data('nation_202... | [
"logging_code.logger.error",
"logging_code.logger.debug",
"covid_news_handling.news_API_request"
] | [((1236, 1274), 'covid_news_handling.news_API_request', 'covid_news_handling.news_API_request', ([], {}), '()\n', (1272, 1274), False, 'import covid_news_handling\n'), ((395, 430), 'logging_code.logger.debug', 'log.logger.debug', (['"""Test Successful"""'], {}), "('Test Successful')\n", (411, 430), True, 'import loggin... |
# Generated by Django 2.2.3 on 2019-08-03 02:26
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('quotes', '0007_auto_20190730_2313'),
]
operations = [
migrations.RemoveField(
model_name='quote',
name='user_favourited',
... | [
"django.db.migrations.RemoveField"
] | [((226, 292), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""quote"""', 'name': '"""user_favourited"""'}), "(model_name='quote', name='user_favourited')\n", (248, 292), False, 'from django.db import migrations\n'), ((337, 398), 'django.db.migrations.RemoveField', 'migrations.Remov... |
import csv
import numpy as np
from lightfm import LightFM
import scipy.sparse
from sklearn.metrics import label_ranking_average_precision_score
import math
import random
import pickle
def loadUserFeatures(i_file, n_users):
print('Loading user graph...')
A = scipy.sparse.lil_matrix((n_users, n_users), dtype=in... | [
"random.sample",
"sklearn.metrics.label_ranking_average_precision_score",
"pickle.dump",
"lightfm.LightFM",
"numpy.array",
"numpy.random.seed",
"csv.reader",
"numpy.random.permutation"
] | [((3429, 3449), 'numpy.array', 'np.array', (['[sub_pred]'], {}), '([sub_pred])\n', (3437, 3449), True, 'import numpy as np\n'), ((3463, 3481), 'numpy.array', 'np.array', (['[labels]'], {}), '([labels])\n', (3471, 3481), True, 'import numpy as np\n'), ((3542, 3596), 'sklearn.metrics.label_ranking_average_precision_score... |
import os
import argparse
from packages.SIP import SubmissionInformationPackage
argParse = argparse.ArgumentParser()
argParse.add_argument("package", help="Package ID in Processing directory.")
args = argParse.parse_args()
if os.name == 'nt':
raise ("ERROR: Must be run from processing server.")
else:
... | [
"os.listdir",
"argparse.ArgumentParser",
"os.path.join",
"packages.SIP.SubmissionInformationPackage",
"os.rmdir"
] | [((96, 121), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (119, 121), False, 'import argparse\n'), ((428, 469), 'os.path.join', 'os.path.join', (['sipDir', 'colID', 'args.package'], {}), '(sipDir, colID, args.package)\n', (440, 469), False, 'import os\n'), ((479, 509), 'packages.SIP.Submissio... |
import time
from raspi_io import TVService
import raspi_io.utility as utility
if __name__ == "__main__":
tv = TVService(utility.scan_server()[0])
# Get status
print(tv.get_status())
# Get preferred mode
print(tv.get_preferred_mode())
# Get support modes
for group in (TVService.DMT, TVSe... | [
"raspi_io.utility.scan_server",
"time.sleep"
] | [((502, 515), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (512, 515), False, 'import time\n'), ((126, 147), 'raspi_io.utility.scan_server', 'utility.scan_server', ([], {}), '()\n', (145, 147), True, 'import raspi_io.utility as utility\n')] |
# -*- coding: utf-8 -*-
import json
import os
import click
import logging
from pathlib import Path
from dotenv import find_dotenv, load_dotenv
import pandas as pd
from sklearn.model_selection import train_test_split
import csv
import pickle
import src.data.unify_datasets as unify
@click.command()
@click.option('--d... | [
"logging.getLogger",
"logging.basicConfig",
"os.path.exists",
"json.loads",
"dotenv.find_dotenv",
"pickle.dump",
"os.getenv",
"pathlib.Path",
"click.option",
"sklearn.model_selection.train_test_split",
"pandas.DataFrame.from_dict",
"src.data.unify_datasets.reduce_schema",
"os.mkdir",
"pand... | [((286, 301), 'click.command', 'click.command', ([], {}), '()\n', (299, 301), False, 'import click\n'), ((303, 373), 'click.option', 'click.option', (['"""--dataset"""'], {'help': '"""Dataset which you like to preprocess"""'}), "('--dataset', help='Dataset which you like to preprocess')\n", (315, 373), False, 'import c... |
#!/usr/bin/env python2
import cv2
import sys, random, socket, struct
import numpy as np
from math import sqrt, sin, cos, pi, atan2, fmod
#################
# Choose camera #
#################
camera = ' '.join(sys.argv[1:])
try:
v = int(camera)
camera = v
except ValueError:
pass
if camera == '':
camera = 0
#####... | [
"numpy.uint8",
"cv2.__version__.split",
"cv2.SimpleBlobDetector_create",
"socket.socket",
"math.sqrt",
"cv2.SimpleBlobDetector",
"cv2.imshow",
"math.cos",
"struct.pack",
"cv2.SimpleBlobDetector_Params",
"struct.unpack",
"cv2.VideoCapture",
"math.atan2",
"random.random",
"math.sin",
"cv... | [((420, 444), 'cv2.VideoCapture', 'cv2.VideoCapture', (['camera'], {}), '(camera)\n', (436, 444), False, 'import cv2\n'), ((2897, 2928), 'cv2.SimpleBlobDetector_Params', 'cv2.SimpleBlobDetector_Params', ([], {}), '()\n', (2926, 2928), False, 'import cv2\n'), ((3352, 3378), 'cv2.__version__.split', 'cv2.__version__.spli... |
from ecc.curve import (
P256, secp256k1, Curve25519, M383, E222, E382
)
from ecc.cipher import ElGamal
from ecc.key import gen_keypair
CURVES = [P256, secp256k1, Curve25519, M383, E222, E382]
PLAINTEXT = b"Rini yang cantiiik"
# Generate key pair
pri_key, pub_key = gen_keypair(E382)
# Initiate ElGam... | [
"ecc.key.gen_keypair",
"ecc.cipher.ElGamal"
] | [((283, 300), 'ecc.key.gen_keypair', 'gen_keypair', (['E382'], {}), '(E382)\n', (294, 300), False, 'from ecc.key import gen_keypair\n'), ((337, 350), 'ecc.cipher.ElGamal', 'ElGamal', (['E382'], {}), '(E382)\n', (344, 350), False, 'from ecc.cipher import ElGamal\n')] |
from datetime import datetime
from json import loads
from typing import TYPE_CHECKING, Any, Dict, List, TypeAlias, Union
import aiohttp
from base_wrapper.client import Client as BaseClient
from .errors import CoinNotExists, HTTPException
from .results import CurrencyResult
from .route import Route
if TYPE_CHECKING:
... | [
"json.loads"
] | [((695, 706), 'json.loads', 'loads', (['text'], {}), '(text)\n', (700, 706), False, 'from json import loads\n')] |
import os
import psycopg2
try:
conn = psycopg2.connect("dbname=webstatus user=postgres")
except psycopg2.OperationalError:
if (input("Create database 'webstatus' (Y/n)? ") != 'n'):
print("Creating database...")
r = os.system("createdb -U postgres webstatus")
if r != 0:
print... | [
"psycopg2.connect",
"os.system"
] | [((43, 93), 'psycopg2.connect', 'psycopg2.connect', (['"""dbname=webstatus user=postgres"""'], {}), "('dbname=webstatus user=postgres')\n", (59, 93), False, 'import psycopg2\n'), ((240, 283), 'os.system', 'os.system', (['"""createdb -U postgres webstatus"""'], {}), "('createdb -U postgres webstatus')\n", (249, 283), Fa... |
"""AyudaEnPython: https://www.facebook.com/groups/ayudapython
"""
def _es_primo(n: int) -> bool:
"""
>>> _es_primo(7)
True
>>> _es_primo(8)
False
"""
for i in range(2, n):
if n % i == 0:
return False
return True
def proximo_primo(n: int) -> int:
"""
>>> pr... | [
"doctest.testmod"
] | [((618, 635), 'doctest.testmod', 'doctest.testmod', ([], {}), '()\n', (633, 635), False, 'import doctest\n')] |
import os
import sys
import time
import pdb
import argparse
import logging
import utils
from yaml import load, dump
from logging import handlers
from parser import operations_parser
from local_runner import LocalRunner
from docker_runner import DockerRunner
DEFAULT_IMAGE = "milvusdb/milvus:latest"
LOG_FOLDER = "benchm... | [
"logging.getLogger",
"os.path.exists",
"logging.basicConfig",
"utils.pull_image",
"sys.exit",
"argparse.ArgumentParser",
"logging.Formatter",
"os.path.join",
"yaml.load",
"argparse.ArgumentTypeError",
"utils.remove_all_containers",
"local_runner.LocalRunner",
"parser.operations_parser",
"o... | [((339, 376), 'logging.getLogger', 'logging.getLogger', (['"""milvus_benchmark"""'], {}), "('milvus_benchmark')\n", (356, 376), False, 'import logging\n'), ((390, 485), 'logging.Formatter', 'logging.Formatter', (['"""[%(asctime)s] [%(levelname)-4s] [%(pathname)s:%(lineno)d] %(message)s"""'], {}), "(\n '[%(asctime)s]... |
# vim: expandtab:ts=4:sw=4
import numpy as np
import scipy.linalg
import pdb
"""
Table for the 0.95 quantile of the chi-square distribution with N degrees of
freedom (contains values for N=1, ..., 9). Taken from MATLAB/Octave's chi2inv
function and used as Mahalanobis gating threshold.
"""
chi2inv95 = {
1: 3.8415,... | [
"numpy.linalg.multi_dot",
"numpy.dot",
"numpy.zeros",
"numpy.outer",
"numpy.linalg.inv"
] | [((5839, 5858), 'numpy.zeros', 'np.zeros', (['self.ndim'], {}), '(self.ndim)\n', (5847, 5858), True, 'import numpy as np\n'), ((5885, 5917), 'numpy.zeros', 'np.zeros', (['(self.ndim, self.ndim)'], {}), '((self.ndim, self.ndim))\n', (5893, 5917), True, 'import numpy as np\n'), ((6846, 6879), 'numpy.dot', 'np.dot', (['in... |
import pygame
class Font(object):
"""@brief Hold a set of fonts and allow for user defined fonts.
"""
def __init__(self, font, scale):
pygame.font.init()
# details about the font created
self.name = font
# scale is the ratio of screen width / number of grids wide the scre... | [
"pygame.font.init"
] | [((158, 176), 'pygame.font.init', 'pygame.font.init', ([], {}), '()\n', (174, 176), False, 'import pygame\n')] |
# Authors: <NAME> <<EMAIL>>
# + All contributors to <https://github.com/smarie/python-odsclient>
#
# License: 3-clause BSD, <https://github.com/smarie/python-odsclient/blob/master/LICENSE>
from subprocess import call
try:
import click
except ImportError as e:
raise Exception("`click` is required f... | [
"keyring.get_keyring",
"click.group",
"click.option",
"odsclient.core.ODSClient",
"odsclient.shortcuts.get_apikey_from_keyring",
"click.echo",
"subprocess.call",
"odsclient.shortcuts.remove_apikey_from_keyring",
"odsclient.shortcuts.store_apikey_in_keyring"
] | [((558, 571), 'click.group', 'click.group', ([], {}), '()\n', (569, 571), False, 'import click\n'), ((1101, 1210), 'click.option', 'click.option', (['"""-p"""', '"""--platform_id"""'], {'default': '"""public"""', 'help': '"""Specific ODS platform id. Default \'public\'"""'}), '(\'-p\', \'--platform_id\', default=\'publ... |
from pathlib import Path
import torch
import pandas as pd
import numpy as np
def load_train_data(root: Path):
train_data_path = root / "train.csv"
train_data = pd.read_csv(train_data_path)
labels = train_data["label"].values
data = train_data.drop("label", axis=1).values.reshape(-1, 1, 28, 28)
... | [
"torch.FloatTensor",
"pandas.read_csv",
"numpy.arange"
] | [((171, 199), 'pandas.read_csv', 'pd.read_csv', (['train_data_path'], {}), '(train_data_path)\n', (182, 199), True, 'import pandas as pd\n'), ((330, 353), 'torch.FloatTensor', 'torch.FloatTensor', (['data'], {}), '(data)\n', (347, 353), False, 'import torch\n'), ((611, 639), 'torch.FloatTensor', 'torch.FloatTensor', ([... |
import os
import re
import warnings
import numpy as np
from typing import Tuple, Dict, Generator, Optional, Union
# Custom types
Map_File_Type = Tuple[
np.ndarray, Union[Dict[str, np.ndarray], dict], np.ndarray, Optional[np.ndarray]
]
def load_3d_map_from_file(file_name: str) -> Map_File_Type:
"""map loader... | [
"re.split",
"os.path.splitext",
"os.path.isfile",
"numpy.zeros",
"warnings.warn"
] | [((878, 903), 'os.path.isfile', 'os.path.isfile', (['file_name'], {}), '(file_name)\n', (892, 903), False, 'import os\n'), ((994, 1021), 'os.path.splitext', 'os.path.splitext', (['file_name'], {}), '(file_name)\n', (1010, 1021), False, 'import os\n'), ((3599, 3650), 'warnings.warn', 'warnings.warn', (['"""start not giv... |
#!/usr/bin/env python
from time import time
import numpy as np
from metrics import Metrics
from model import Model
from utils import flatten
class TwoWayMetrics(Metrics):
# pylint: disable=too-many-instance-attributes
def __init__(self, epoch, n_low_level_fids):
self.first_gen_loss = []
self.first_gen... | [
"numpy.mean",
"time.time",
"numpy.std"
] | [((7106, 7121), 'numpy.mean', 'np.mean', (['values'], {}), '(values)\n', (7113, 7121), True, 'import numpy as np\n'), ((7145, 7159), 'numpy.std', 'np.std', (['values'], {}), '(values)\n', (7151, 7159), True, 'import numpy as np\n'), ((7948, 7954), 'time.time', 'time', ([], {}), '()\n', (7952, 7954), False, 'from time i... |
from email.mime.image import MIMEImage
from email.utils import unquote
from pathlib import Path
from django.core.mail import EmailMessage, EmailMultiAlternatives, make_msgid
from .utils import UNSET
class AnymailMessageMixin(EmailMessage):
"""Mixin for EmailMessage that exposes Anymail features.
Use of thi... | [
"email.mime.image.MIMEImage",
"django.core.mail.make_msgid",
"email.utils.unquote",
"pathlib.Path"
] | [((2243, 2253), 'pathlib.Path', 'Path', (['path'], {}), '(path)\n', (2247, 2253), False, 'from pathlib import Path\n'), ((2865, 2893), 'django.core.mail.make_msgid', 'make_msgid', (['idstring', 'domain'], {}), '(idstring, domain)\n', (2875, 2893), False, 'from django.core.mail import EmailMessage, EmailMultiAlternative... |
import pandas as pd
import numpy as np
import argparse
from plotnine import ggplot, scale_x_continuous, theme_bw, element_rect, element_line, geom_line, scale_color_brewer, \
annotate, \
element_blank, element_text, scale_x_discrete,geom_errorbar,position_dodge, scale_y_continuous, aes, theme, facet_grid, labs,... | [
"plotnine.element_blank",
"plotnine.element_line",
"sys.path.insert",
"argparse.ArgumentParser",
"pandas.read_csv",
"numpy.size",
"plotnine.theme_bw",
"plotnine.geom_line",
"plotnine.aes",
"plotnine.element_text",
"plotnine.facet_wrap",
"numpy.array",
"plotnine.scale_x_continuous",
"plotni... | [((387, 411), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""./"""'], {}), "(0, './')\n", (402, 411), False, 'import sys\n'), ((435, 503), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Effect_of_sigma_smooth_figure"""'}), "(description='Effect_of_sigma_smooth_figure')\n", (458, 503)... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2016-12-20 05:50
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('news', '0003_sponsers'),
]
operations = [
migr... | [
"django.db.migrations.DeleteModel",
"django.db.models.SlugField"
] | [((316, 355), 'django.db.migrations.DeleteModel', 'migrations.DeleteModel', ([], {'name': '"""Sponsers"""'}), "(name='Sponsers')\n", (338, 355), False, 'from django.db import migrations, models\n'), ((483, 534), 'django.db.models.SlugField', 'models.SlugField', ([], {'default': 'django.utils.timezone.now'}), '(default=... |
import numpy as np
import json
import sys
import os
from subprocess import call
from jio_filestore.io.azure_filestore import ObjectStoreFactory
from .configs import file_store_config
fs = ObjectStoreFactory(file_store_config)
# connect to database
# list all items in file store
items = fs.list()
# | [
"jio_filestore.io.azure_filestore.ObjectStoreFactory"
] | [((189, 226), 'jio_filestore.io.azure_filestore.ObjectStoreFactory', 'ObjectStoreFactory', (['file_store_config'], {}), '(file_store_config)\n', (207, 226), False, 'from jio_filestore.io.azure_filestore import ObjectStoreFactory\n')] |
import logging; module_logger = logging.getLogger(__name__)
from pathlib import Path
import sys, re, subprocess, datetime, collections, itertools, pprint, json
from acmacs_base.json import read_json
from . import latex
from .map import sLabDisplayName
# ================================================================... | [
"logging.getLogger",
"acmacs_base.json.read_json",
"re.compile",
"pathlib.Path",
"datetime.datetime.strptime",
"subprocess.run",
"datetime.datetime.now",
"collections.defaultdict",
"datetime.date",
"datetime.timedelta"
] | [((32, 59), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (49, 59), False, 'import logging\n'), ((499, 530), 'acmacs_base.json.read_json', 'read_json', (['report_settings_file'], {}), '(report_settings_file)\n', (508, 530), False, 'from acmacs_base.json import read_json\n'), ((1359, 1395... |
from xrudderai.board import Board
from xrudderai.player.player import Player
from xrudderai.place_command import PlaceCommand
from xrudderai.move_command import MoveCommand
from xrudderai.token import Token
import random
import sys
import time
class AIPlayer(Player):
def __init__(self, symbol, colour, board, oppon... | [
"xrudderai.token.Token",
"time.time"
] | [((469, 480), 'time.time', 'time.time', ([], {}), '()\n', (478, 480), False, 'import time\n'), ((802, 813), 'xrudderai.token.Token', 'Token', (['self'], {}), '(self)\n', (807, 813), False, 'from xrudderai.token import Token\n'), ((1220, 1231), 'xrudderai.token.Token', 'Token', (['self'], {}), '(self)\n', (1225, 1231), ... |
import numpy as np
import logging
max_seed = 2147483647
#logging.basicConfig(level="DEBUG")
logger = logging.getLogger("TUMOR2D")
#logger.setLevel("ERROR")
class Tumor2dExperiment:
def __init__(self, mean_gc, mean_ecm, mean_prolif, std_gc, std_ecm, std_prolif, full_data_gc=None,
full_data_ecm=N... | [
"logging.getLogger",
"numpy.mean",
"numpy.floor",
"numpy.random.randint",
"numpy.empty",
"numpy.random.seed",
"numpy.isnan",
"numpy.std",
"tumor2d.src.nixTumor2d.tumor2d_interface"
] | [((103, 131), 'logging.getLogger', 'logging.getLogger', (['"""TUMOR2D"""'], {}), "('TUMOR2D')\n", (120, 131), False, 'import logging\n'), ((1802, 2050), 'tumor2d.src.nixTumor2d.tumor2d_interface', 'nixTumor2d.tumor2d_interface', (['initial_radius', 'initial_quiescent_fraction', 'max_celldivision_rate', 'division_depth'... |
from datetime import datetime
from django.db import models
from django.contrib.auth.models import User
from django.db.models.deletion import DO_NOTHING
from django.db.models.fields.reverse_related import ManyToOneRel
from django.db.models.signals import post_save
from django.dispatch import receiver
class Tournament... | [
"django.db.models.OneToOneField",
"django.db.models.DateField",
"django.db.models.TextField",
"django.db.models.IntegerField",
"django.db.models.ForeignKey",
"django.db.models.DateTimeField",
"django.dispatch.receiver",
"django.db.models.CharField"
] | [((1382, 1414), 'django.dispatch.receiver', 'receiver', (['post_save'], {'sender': 'User'}), '(post_save, sender=User)\n', (1390, 1414), False, 'from django.dispatch import receiver\n'), ((1541, 1573), 'django.dispatch.receiver', 'receiver', (['post_save'], {'sender': 'User'}), '(post_save, sender=User)\n', (1549, 1573... |
token = '<KEY>'
import lyricsgenius
genius = lyricsgenius.Genius(token)
muzik = input("Şarkı sözü ara:")
song = genius.search_song(muzik)
print(song.lyrics) | [
"lyricsgenius.Genius"
] | [((49, 75), 'lyricsgenius.Genius', 'lyricsgenius.Genius', (['token'], {}), '(token)\n', (68, 75), False, 'import lyricsgenius\n')] |
from django.http import Http404
from django.http import HttpResponseRedirect
from django.shortcuts import render,redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.contrib.auth.models import User
from .models import Image, Profile,Comment,Likes,Follow
from... | [
"django.shortcuts.render",
"django.shortcuts.redirect",
"django.contrib.auth.models.User.objects.get",
"django.contrib.auth.decorators.login_required"
] | [((412, 456), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'login_url': '"""/accounts/login/"""'}), "(login_url='/accounts/login/')\n", (426, 456), False, 'from django.contrib.auth.decorators import login_required\n'), ((781, 825), 'django.contrib.auth.decorators.login_required', 'login_requ... |
import pandas as pd
import sys
pgefile=sys.argv[1]
df = pd.read_csv(pgefile, delim_whitespace=True)
df2 = df[sys.argv[2:]]
pge = df2.groupby("problem")
for name, grp in pge:
# print(name)
# print(grp)
ac_t = grp["elapsed_seconds"].iloc[2]/grp["elapsed_seconds"].iloc[0]
ac_m = grp["evald_models"].iloc[2]/grp... | [
"pandas.read_csv"
] | [((59, 102), 'pandas.read_csv', 'pd.read_csv', (['pgefile'], {'delim_whitespace': '(True)'}), '(pgefile, delim_whitespace=True)\n', (70, 102), True, 'import pandas as pd\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import binascii
import os
import json
import time
import unittest
from ontology.ont_sdk import OntologySdk
from ontology.utils.contract_data_parser import ContractDataParser
from ontology.utils.contract_event_parser import ContractEventParser
from ontology.wallet.wallet_m... | [
"src.invoke_hello_ontology.InvokeHelloPython",
"ontology.utils.contract_data_parser.ContractDataParser.to_b58_address",
"ontology.utils.contract_data_parser.ContractDataParser.to_dict",
"ontology.utils.contract_data_parser.ContractDataParser.to_utf8_str",
"ontology.wallet.wallet_manager.WalletManager",
"o... | [((417, 430), 'ontology.ont_sdk.OntologySdk', 'OntologySdk', ([], {}), '()\n', (428, 430), False, 'from ontology.ont_sdk import OntologySdk\n'), ((592, 642), 'os.path.join', 'os.path.join', (['root_folder', '"""wallet"""', '"""wallet.json"""'], {}), "(root_folder, 'wallet', 'wallet.json')\n", (604, 642), False, 'import... |
from django.contrib import admin
from comment.models import Comment
# Register your models here.
admin.site.register(Comment)
| [
"django.contrib.admin.site.register"
] | [((98, 126), 'django.contrib.admin.site.register', 'admin.site.register', (['Comment'], {}), '(Comment)\n', (117, 126), False, 'from django.contrib import admin\n')] |
import sqlite3
import psycopg2
from bs4 import BeautifulSoup
import requests
from sqlalchemy import create_engine # db engine
import pandas as pd
"""
delays = [12, 3, 9, 21, 5, 6, 19, 7, 33, 11, 2, 17, 4]
def get_random_ua():
random_ua = ''
ua_file = 'ua_file.txt'
try:
with open(ua_file) as f:
... | [
"bs4.BeautifulSoup",
"sqlalchemy.create_engine",
"pandas.DataFrame",
"requests.get"
] | [((1367, 1439), 'requests.get', 'requests.get', (['"""https://covid19.ncdc.gov.ng"""'], {'headers': 'headers', 'timeout': '(15)'}), "('https://covid19.ncdc.gov.ng', headers=headers, timeout=15)\n", (1379, 1439), False, 'import requests\n'), ((1494, 1523), 'bs4.BeautifulSoup', 'BeautifulSoup', (['r.text', '"""lxml"""'],... |
# -*- coding: utf-8 -*-
import requests
from urlparse import urlparse
from tests.integration import TestsBase
MAX_RETRIES = 3
TIMEOUT = 10
class TestLinks(TestsBase):
def test_external_links(self):
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.3... | [
"requests.adapters.HTTPAdapter",
"requests.Session",
"urlparse.urlparse"
] | [((773, 791), 'requests.Session', 'requests.Session', ([], {}), '()\n', (789, 791), False, 'import requests\n'), ((812, 866), 'requests.adapters.HTTPAdapter', 'requests.adapters.HTTPAdapter', ([], {'max_retries': 'MAX_RETRIES'}), '(max_retries=MAX_RETRIES)\n', (841, 866), False, 'import requests\n'), ((931, 945), 'urlp... |
import gin
@gin.configurable
def inner(d=0, e=0):
return d + e
@gin.configurable
def build(a=0, b=0, c=0, inner=None):
s = inner()
print(a + b + c + s)
@gin.configurable
def build_other(inner=None):
print(inner())
if __name__ == "__main__":
gin.parse_config_file("main.gin")
build()
b... | [
"gin.parse_config_file"
] | [((269, 302), 'gin.parse_config_file', 'gin.parse_config_file', (['"""main.gin"""'], {}), "('main.gin')\n", (290, 302), False, 'import gin\n')] |
# tkinter snake demo
__author__ = "<NAME>"
__date__ = "22 August 2021"
import tkinter as tk
from random import choice
from collections import deque
from uColor import *
# ---------------------------------------------------------------------
dirs = ('Left', 'Up', 'Right', 'Down')
# pause control
control = False
... | [
"random.choice",
"collections.deque",
"tkinter.StringVar",
"tkinter.Canvas",
"tkinter.Tk",
"tkinter.Label"
] | [((342, 349), 'collections.deque', 'deque', ([], {}), '()\n', (347, 349), False, 'from collections import deque\n'), ((5353, 5360), 'tkinter.Tk', 'tk.Tk', ([], {}), '()\n', (5358, 5360), True, 'import tkinter as tk\n'), ((776, 790), 'tkinter.StringVar', 'tk.StringVar', ([], {}), '()\n', (788, 790), True, 'import tkinte... |
from django.contrib.auth import get_user_model
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.shortcuts import get_object_or_404, render
from django.urls import reverse_lazy
from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateVie... | [
"django.shortcuts.render",
"django.contrib.auth.get_user_model",
"djangoForum.forum.models.ForumThread.objects.filter",
"django.urls.reverse_lazy",
"djangoForum.forum.models.ForumPost.objects.filter",
"djangoForum.forum.models.ForumCategory.objects.get",
"djangoForum.forum.models.ForumPost.objects.get",... | [((542, 558), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (556, 558), False, 'from django.contrib.auth import get_user_model\n'), ((643, 673), 'django.shortcuts.render', 'render', (['request', 'template_name'], {}), '(request, template_name)\n', (649, 673), False, 'from django.shortcuts im... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import logging
import time
import unittest
import gc
from tests.sino.scom.paths import update_working_directory
from sino import scom
update_working_directory() # Needed when: 'pipenv run python -m unittest tests/sino/scom/{this_file}.py'
class ScomDeviceHe... | [
"logging.getLogger",
"logging.basicConfig",
"tests.sino.scom.paths.update_working_directory",
"sino.scom.dman.DeviceManager.instance",
"os.environ.get",
"time.sleep",
"sino.scom.device.ScomDevice.get_number_of_instances",
"sino.scom.Scom",
"sino.scom.dman.DeviceManager.destroy",
"sino.scom.dman.De... | [((194, 220), 'tests.sino.scom.paths.update_working_directory', 'update_working_directory', ([], {}), '()\n', (218, 220), False, 'from tests.sino.scom.paths import update_working_directory\n'), ((418, 445), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (435, 445), False, 'import logging\... |
import io
import os
import numpy as np
import requests as rq
import onnxruntime as ort
from PIL import Image
from app.utils import load_labels, softmax
class Predictor:
def __init__(self, mode_path) -> None:
self.model = ort.InferenceSession(f'{os.getcwd()}/{mode_path}', None)
def pre_process(self, input_data... | [
"PIL.Image.open",
"io.BytesIO",
"numpy.argmax",
"requests.get",
"os.getcwd",
"numpy.array",
"numpy.zeros"
] | [((568, 599), 'numpy.array', 'np.array', (['[0.485, 0.456, 0.406]'], {}), '([0.485, 0.456, 0.406])\n', (576, 599), True, 'import numpy as np\n'), ((617, 648), 'numpy.array', 'np.array', (['[0.229, 0.224, 0.225]'], {}), '([0.229, 0.224, 0.225])\n', (625, 648), True, 'import numpy as np\n'), ((1025, 1042), 'requests.get'... |
# Copyright (c) 2022 Serum
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, su... | [
"PyQt5.QtCore.QTemporaryFile",
"enum.auto",
"re.compile",
"PyQt5.QtGui.QColor",
"PyQt5.QtGui.QTextCharFormat"
] | [((3215, 3238), 're.compile', 're.compile', (['"""<[^<>@]*>"""'], {}), "('<[^<>@]*>')\n", (3225, 3238), False, 'import re\n'), ((3256, 3278), 're.compile', 're.compile', (['"""&#?\\\\w+;"""'], {}), "('&#?\\\\w+;')\n", (3266, 3278), False, 'import re\n'), ((3296, 3328), 're.compile', 're.compile', (['""""[^"<]*"(?=[^<]*... |
# Copyright 2016 Hewlett Packard Enterprise Development LP
#
# 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 ... | [
"numpy.convolve",
"opveclib.arange",
"opveclib.output",
"opveclib.position_in",
"numpy.array",
"itertools.repeat",
"numpy.random.random",
"tensorflow.Session",
"opveclib.if_",
"numpy.empty",
"opveclib.profile",
"tensorflow.ConfigProto",
"opveclib.operator",
"tensorflow.nn.conv2d",
"tenso... | [((692, 706), 'opveclib.operator', 'ovl.operator', ([], {}), '()\n', (704, 706), True, 'import opveclib as ovl\n'), ((3758, 3791), 'opveclib.output', 'ovl.output', (['output_shape', 'x.dtype'], {}), '(output_shape, x.dtype)\n', (3768, 3791), True, 'import opveclib as ovl\n'), ((4443, 4475), 'opveclib.position_in', 'ovl... |
from models import get_model
import tensorflow.keras as K
import tensorflow_datasets as tfds
import losses
import argparse
import os
import tensorflow as tf
physical_devices = tf.config.experimental.list_physical_devices("GPU")
tf.config.experimental.set_memory_growth(physical_devices[0], True)
args = argparse.Argume... | [
"losses.get_loss",
"tensorflow.GradientTape",
"argparse.ArgumentParser",
"models.get_model",
"tensorflow.keras.optimizers.SGD",
"tensorflow.keras.losses.categorical_crossentropy",
"tensorflow.summary.scalar",
"tensorflow.train.CheckpointManager",
"tensorflow.one_hot",
"tensorflow.Variable",
"ten... | [((176, 227), 'tensorflow.config.experimental.list_physical_devices', 'tf.config.experimental.list_physical_devices', (['"""GPU"""'], {}), "('GPU')\n", (220, 227), True, 'import tensorflow as tf\n'), ((228, 295), 'tensorflow.config.experimental.set_memory_growth', 'tf.config.experimental.set_memory_growth', (['physical... |
import asyncio
import os
import boto3
import botocore
import logging
from moto import mock_dynamodb2, mock_sts, mock_lambda, mock_iam
from moto_server import MotoService, patch_boto
from settings import CONNECT_TO_AWS
dynamodb = boto3.client('dynamodb')
lmbda = boto3.client('lambda')
iam = boto3.client('iam')
sts = b... | [
"logging.getLogger",
"moto.mock_sts",
"logging.StreamHandler",
"boto3.client",
"moto.mock_lambda",
"moto.mock_iam",
"moto_server.patch_boto",
"moto_server.MotoService",
"logging.Formatter",
"botocore.session.get_session",
"moto.mock_dynamodb2",
"asyncio.get_event_loop"
] | [((231, 255), 'boto3.client', 'boto3.client', (['"""dynamodb"""'], {}), "('dynamodb')\n", (243, 255), False, 'import boto3\n'), ((264, 286), 'boto3.client', 'boto3.client', (['"""lambda"""'], {}), "('lambda')\n", (276, 286), False, 'import boto3\n'), ((293, 312), 'boto3.client', 'boto3.client', (['"""iam"""'], {}), "('... |
import fiona
import numpy as np
import pandas as pd
import geopandas as gpd
import geojson
from shapely.geometry import Point, LineString
from six import iteritems
from six.moves import reduce
from itertools import chain, count, permutations
import os, sys
type_map = dict(MultiLineString="LineString",
... | [
"itertools.chain",
"os.path.exists",
"geopandas.read_file",
"six.moves.reduce",
"itertools.permutations",
"geojson.dump",
"os.path.join",
"shapely.geometry.Point",
"os.path.dirname",
"shapely.geometry.LineString",
"os.path.basename",
"os.unlink",
"geojson.load",
"six.iteritems"
] | [((1123, 1144), 'os.path.exists', 'os.path.exists', (['outfn'], {}), '(outfn)\n', (1137, 1144), False, 'import os, sys\n'), ((1222, 1239), 'geopandas.read_file', 'gpd.read_file', (['fn'], {}), '(fn)\n', (1235, 1239), True, 'import geopandas as gpd\n'), ((6071, 6090), 'six.iteritems', 'iteritems', (['features'], {}), '(... |
import numpy as np
from yt.testing import fake_random_ds, assert_equal
from yt.frontends.stream.data_structures import load_uniform_grid
def test_exclude_above():
the_ds = fake_random_ds(ndims=3)
all_data = the_ds.all_data()
new_ds = all_data.exclude_above('density', 1)
assert_equal(new_ds['density']... | [
"yt.testing.assert_equal",
"numpy.ones",
"yt.testing.fake_random_ds",
"yt.frontends.stream.data_structures.load_uniform_grid",
"numpy.all"
] | [((179, 202), 'yt.testing.fake_random_ds', 'fake_random_ds', ([], {'ndims': '(3)'}), '(ndims=3)\n', (193, 202), False, 'from yt.testing import fake_random_ds, assert_equal\n'), ((290, 342), 'yt.testing.assert_equal', 'assert_equal', (["new_ds['density']", "all_data['density']"], {}), "(new_ds['density'], all_data['dens... |
# std
import pathlib
import shutil
# 3rd
import pytest
# ours
from ankipandas.collection import Collection
from ankipandas.test.util import parameterized_paths
def _init_all_tables(col: Collection) -> None:
""" Access all attributes at least once to ensure that they are
initialized.
"""
_ = col.note... | [
"ankipandas.collection.Collection",
"ankipandas.test.util.parameterized_paths",
"pytest.raises"
] | [((459, 480), 'ankipandas.test.util.parameterized_paths', 'parameterized_paths', ([], {}), '()\n', (478, 480), False, 'from ankipandas.test.util import parameterized_paths\n'), ((635, 656), 'ankipandas.test.util.parameterized_paths', 'parameterized_paths', ([], {}), '()\n', (654, 656), False, 'from ankipandas.test.util... |
from django.urls import path
from posts import views
urlpatterns = [
path('', views.posts_index, name='postsIndex'),
path('tags/', views.posts_tags, name='postsTags'),
] | [
"django.urls.path"
] | [((74, 120), 'django.urls.path', 'path', (['""""""', 'views.posts_index'], {'name': '"""postsIndex"""'}), "('', views.posts_index, name='postsIndex')\n", (78, 120), False, 'from django.urls import path\n'), ((126, 175), 'django.urls.path', 'path', (['"""tags/"""', 'views.posts_tags'], {'name': '"""postsTags"""'}), "('t... |
from django.test import TestCase
from django.urls import reverse, resolve
class TestURLs(TestCase):
# Workshop URLs
def test_workshop_auth_url(self):
path = reverse("workshop_auth")
assert resolve(path).view_name == "workshop_auth"
def test_workshop_list_url(self):
path = revers... | [
"django.urls.resolve",
"django.urls.reverse"
] | [((177, 201), 'django.urls.reverse', 'reverse', (['"""workshop_auth"""'], {}), "('workshop_auth')\n", (184, 201), False, 'from django.urls import reverse, resolve\n'), ((314, 338), 'django.urls.reverse', 'reverse', (['"""workshop_list"""'], {}), "('workshop_list')\n", (321, 338), False, 'from django.urls import reverse... |
from ctapipe.instrument.optics import OpticsDescription
from astropy import units as u
import pytest
def test_guess_optics():
od = OpticsDescription.guess(28.0 * u.m)
od.info()
assert od.tel_type == 'LST'
assert od.tel_subtype == ''
assert od.mirror_type == 'DC'
with pytest.raises(KeyError):... | [
"ctapipe.instrument.optics.OpticsDescription",
"pytest.raises",
"ctapipe.instrument.optics.OpticsDescription.guess"
] | [((137, 172), 'ctapipe.instrument.optics.OpticsDescription.guess', 'OpticsDescription.guess', (['(28.0 * u.m)'], {}), '(28.0 * u.m)\n', (160, 172), False, 'from ctapipe.instrument.optics import OpticsDescription\n'), ((296, 319), 'pytest.raises', 'pytest.raises', (['KeyError'], {}), '(KeyError)\n', (309, 319), False, '... |
from flask import Flask
from flask import render_template
from flask import request
import json
import dbconfig
if dbconfig.test:
from mockdbhelper import MockDBHelper as DBHelper
else:
from dbhelper import DBHelper
app = Flask(__name__)
DB = DBHelper()
@app.route("/")
def home():
crimes = DB.get_all_cri... | [
"flask.render_template",
"flask.Flask",
"json.dumps",
"flask.request.form.get",
"dbhelper.DBHelper"
] | [((231, 246), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (236, 246), False, 'from flask import Flask\n'), ((252, 262), 'dbhelper.DBHelper', 'DBHelper', ([], {}), '()\n', (260, 262), False, 'from dbhelper import DBHelper\n'), ((339, 357), 'json.dumps', 'json.dumps', (['crimes'], {}), '(crimes)\n', (349,... |
from os import remove
from unittest import TestCase
from ..curve import P256
from ..keys import export_key, import_key, gen_keypair
class TestAsn1(TestCase):
def test_generate_and_parse_pem(self):
d, Q = gen_keypair(P256)
export_key(d, curve=P256, filepath='p256.key')
export_key(Q, curve=... | [
"os.remove"
] | [((618, 636), 'os.remove', 'remove', (['"""p256.key"""'], {}), "('p256.key')\n", (624, 636), False, 'from os import remove\n'), ((645, 663), 'os.remove', 'remove', (['"""p256.pub"""'], {}), "('p256.pub')\n", (651, 663), False, 'from os import remove\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import setuptools, os
import kicost
import re
SHOW_LAST_HISTORY=3
try:
from setuptools import setup
from setuptools.command.develop import develop
from setuptools.command.install import install
except ImportError:
from distutils.core import ... | [
"distutils.core.command.develop.develop.run",
"setuptools.find_packages",
"sys.platform.startswith",
"os.path.join",
"subprocess.call",
"distutils.core.command.install.install.run",
"re.findall",
"pip.main"
] | [((553, 585), 'sys.platform.startswith', 'sys.platform.startswith', (['"""win32"""'], {}), "('win32')\n", (576, 585), False, 'import sys\n'), ((1740, 1757), 'distutils.core.command.develop.develop.run', 'develop.run', (['self'], {}), '(self)\n', (1751, 1757), False, 'from distutils.core.command.develop import develop\n... |
import subprocess
Import("env")
gitref = subprocess.run(['git', 'rev-parse', '--short=8', 'HEAD'], stdout=subprocess.PIPE).stdout.decode('utf-8').strip()
print("Building gitref: ", gitref)
env.Append(CPPDEFINES=[('PIO_SRC_REV', f'\\"{gitref}\\"')])
| [
"subprocess.run"
] | [((42, 128), 'subprocess.run', 'subprocess.run', (["['git', 'rev-parse', '--short=8', 'HEAD']"], {'stdout': 'subprocess.PIPE'}), "(['git', 'rev-parse', '--short=8', 'HEAD'], stdout=subprocess\n .PIPE)\n", (56, 128), False, 'import subprocess\n')] |