code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import numpy as np
import tensorflow as tf
import tensorflow.contrib.slim as slim
from config import cfg
# TODO: argscope for detailed setting in fpn and rpn
def create_anchors(feats, stride, scales, aspect_ratios=[0.5, 1, 2], base_size=16):
feat_size = cfg.image_size / stride
num_ratios = len(aspect_ratios)
... | [
"numpy.maximum",
"config.cfg.bbox_mean.reshape",
"tensorflow.maximum",
"tensorflow.gather_nd",
"tensorflow.reshape",
"tensorflow.image.crop_and_resize",
"numpy.arange",
"tensorflow.sqrt",
"tensorflow.split",
"tensorflow.nn.softmax",
"tensorflow.contrib.slim.conv2d",
"tensorflow.logical_and",
... | [((384, 407), 'numpy.array', 'np.array', (['aspect_ratios'], {}), '(aspect_ratios)\n', (392, 407), True, 'import numpy as np\n'), ((453, 478), 'numpy.zeros', 'np.zeros', (['(num_ratios, 2)'], {}), '((num_ratios, 2))\n', (461, 478), True, 'import numpy as np\n'), ((746, 801), 'numpy.hstack', 'np.hstack', (['(ctr - 0.5 *... |
from contextlib import nullcontext as does_not_raise
from typing import Any
import pytest
from _mock_data.url.test_set_1 import INVALID_URL, VALID_URL
from _mock_data.xpath.test_set_2 import VALID_XPATH
from browserist.exception.url import URLSyntaxError
from browserist.model.combo_settings.search import SearchSettin... | [
"pytest.raises",
"contextlib.nullcontext",
"browserist.model.combo_settings.search.SearchSettings"
] | [((582, 750), 'browserist.model.combo_settings.search.SearchSettings', 'SearchSettings', ([], {'input_xpath': 'VALID_XPATH', 'button_xpath': 'VALID_XPATH', 'url': 'url', 'await_search_results_url_contains': 'VALID_URL', 'await_search_results_xpath': 'VALID_XPATH'}), '(input_xpath=VALID_XPATH, button_xpath=VALID_XPATH, ... |
# Generated by Django 2.0.5 on 2018-09-27 11:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('registration', '0003_invoice_fix'),
]
operations = [
migrations.AddField(
model_name='courseattendee',
name='attende... | [
"django.db.models.BooleanField"
] | [((342, 376), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (361, 376), False, 'from django.db import migrations, models\n')] |
# see https://www.codewars.com/kata/5659c6d896bc135c4c00021e
def next_smaller(n):
s = list(str(n))
i = j = len(s) - 1
while i > 0 and s[i - 1] <= s[i]: i -= 1
if i <= 0: return -1
while s[j] >= s[i - 1]: j -= 1
s[i - 1], s[j] = s[j], s[i - 1]
s[i:] = reversed(s[i:])
if s[0] == '0': retu... | [
"TestFunction.Test",
"TestFunction.Test.it"
] | [((391, 401), 'TestFunction.Test', 'Test', (['None'], {}), '(None)\n', (395, 401), False, 'from TestFunction import Test\n'), ((402, 428), 'TestFunction.Test.it', 'Test.it', (['"""Smaller numbers"""'], {}), "('Smaller numbers')\n", (409, 428), False, 'from TestFunction import Test\n')] |
# Generated by Django 3.0.5 on 2020-08-14 15:43
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Lessons',
fields=[
... | [
"django.db.models.TextField",
"django.db.models.CharField",
"django.db.models.BooleanField",
"django.db.models.AutoField",
"django.db.models.DateTimeField"
] | [((332, 425), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (348, 425), False, 'from django.db import migrations, models\... |
# Generated with SortBy
#
from enum import Enum
from enum import auto
class SortBy(Enum):
""""""
X_AXIS = auto()
Y_AXIS = auto()
def label(self):
if self == SortBy.X_AXIS:
return "X Axis"
if self == SortBy.Y_AXIS:
return "Y Axis" | [
"enum.auto"
] | [((116, 122), 'enum.auto', 'auto', ([], {}), '()\n', (120, 122), False, 'from enum import auto\n'), ((136, 142), 'enum.auto', 'auto', ([], {}), '()\n', (140, 142), False, 'from enum import auto\n')] |
import requests
class GitHub(object):
action = None
_action = None
user = None
BASE_URL = 'https://api.github.com'
repo = None
def __init__(self):
self.headers = {
"Accept": "application/vnd.github.v3+json"
}
def __make_call(self, endpoint, method='GET'):
... | [
"requests.get"
] | [((356, 400), 'requests.get', 'requests.get', (['endpoint'], {'headers': 'self.headers'}), '(endpoint, headers=self.headers)\n', (368, 400), False, 'import requests\n')] |
from utils import get_input_lines
jolts = []
for line in get_input_lines(__file__):
jolts.append(int(line))
jolts.sort()
diff_count = [0, 0, 0]
jolt = 0
for j in jolts:
diff = j - jolt
if 0 < diff < len(diff_count) + 1:
diff_count[diff - 1] += 1
jolt = j
# Add another difference of 3
diff_co... | [
"utils.get_input_lines"
] | [((58, 83), 'utils.get_input_lines', 'get_input_lines', (['__file__'], {}), '(__file__)\n', (73, 83), False, 'from utils import get_input_lines\n')] |
import pytest
from tutorial.dictish_step_4 import Dictish
DICTISH = Dictish([("a", 1), ("b", 2), ("c", 3)])
def test_a_dictish_is_subscriptable():
assert DICTISH["b"] == 2
def test_subscript_with_a_missing_key():
with pytest.raises(KeyError, match="missing"):
DICTISH["missing"]
| [
"pytest.raises",
"tutorial.dictish_step_4.Dictish"
] | [((69, 108), 'tutorial.dictish_step_4.Dictish', 'Dictish', (["[('a', 1), ('b', 2), ('c', 3)]"], {}), "([('a', 1), ('b', 2), ('c', 3)])\n", (76, 108), False, 'from tutorial.dictish_step_4 import Dictish\n'), ((231, 271), 'pytest.raises', 'pytest.raises', (['KeyError'], {'match': '"""missing"""'}), "(KeyError, match='mis... |
import shortuuid
from models import Article, Tag
class Record():
tags = []
sources = {
'zanoza': 1,
'kloop': 2,
'akipress': 3,
'twentyfour': 4,
'knews': 5,
}
def __init__(self, source, title, url):
self.url = url
self.title = title
self.source_id = self.sources[source]
def se... | [
"shortuuid.uuid",
"models.Article.first_or_new"
] | [((449, 527), 'models.Article.first_or_new', 'Article.first_or_new', ([], {'source_id': 'self.source_id', 'url': 'self.url', 'title': 'self.title'}), '(source_id=self.source_id, url=self.url, title=self.title)\n', (469, 527), False, 'from models import Article, Tag\n'), ((758, 774), 'shortuuid.uuid', 'shortuuid.uuid', ... |
from django.conf import settings
from django.conf.urls import url
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import include, path
from django.views.static import serve
urlpatterns = [
path("admin/", admin.site.urls),
# app urls
path("", include("b... | [
"django.conf.urls.static.static",
"django.conf.urls.url",
"django.urls.path",
"django.urls.include"
] | [((247, 278), 'django.urls.path', 'path', (['"""admin/"""', 'admin.site.urls'], {}), "('admin/', admin.site.urls)\n", (251, 278), False, 'from django.urls import include, path\n'), ((653, 727), 'django.conf.urls.url', 'url', (['"""^media/(?P<path>.*)$"""', 'serve', "{'document_root': settings.MEDIA_ROOT}"], {}), "('^me... |
#
# Copyright (C) 2020-2021 Arm Limited or its affiliates and Contributors. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
from unittest import TestCase
from continuous_delivery_scripts.utils.configuration import configuration, ConfigurationVariable
from continuous_delivery_scripts.utils.git_helpers impo... | [
"uuid.uuid4",
"continuous_delivery_scripts.utils.git_helpers.ProjectGitWrapper",
"continuous_delivery_scripts.utils.git_helpers.GitTempClone",
"pathlib.Path",
"continuous_delivery_scripts.utils.configuration.configuration.get_value",
"continuous_delivery_scripts.utils.git_helpers.ProjectTempClone"
] | [((577, 596), 'continuous_delivery_scripts.utils.git_helpers.ProjectGitWrapper', 'ProjectGitWrapper', ([], {}), '()\n', (594, 596), False, 'from continuous_delivery_scripts.utils.git_helpers import ProjectTempClone, GitTempClone, GitWrapper, ProjectGitWrapper\n'), ((1534, 1553), 'continuous_delivery_scripts.utils.git_h... |
"""
Here we do inference on a DICOM volume, constructing the volume first, and then sending it to the
clinical archive
This code will do the following:
1. Identify the series to run HippoCrop.AI algorithm on from a folder containing multiple studies
2. Construct a NumPy volume from a set of DICOM files
3. ... | [
"PIL.Image.new",
"numpy.sum",
"os.walk",
"pydicom.Dataset",
"os.path.join",
"numpy.max",
"pydicom.filewriter.dcmwrite",
"numpy.random.choice",
"PIL.ImageDraw.Draw",
"datetime.datetime.now",
"numpy.stack",
"subprocess.Popen",
"os.stat",
"datetime.date.today",
"time.sleep",
"os.listdir",... | [((1621, 1638), 'numpy.sum', 'np.sum', (['(pred == 1)'], {}), '(pred == 1)\n', (1627, 1638), True, 'import numpy as np\n'), ((1657, 1674), 'numpy.sum', 'np.sum', (['(pred == 2)'], {}), '(pred == 2)\n', (1663, 1674), True, 'import numpy as np\n'), ((1694, 1710), 'numpy.sum', 'np.sum', (['(pred > 0)'], {}), '(pred > 0)\n... |
import django_tables2 as tables
from django_tables2.utils import Accessor
from tenancy.tables import COL_TENANT
from utilities.tables import BaseTable, ToggleColumn
from .models import Payment
PAYMENT_ACTIONS = """
{% if perms.payment.change_payment %}
<a href="{% url 'plugins:payment:payment_edit' pk=record.pk %}... | [
"django_tables2.TemplateColumn",
"django_tables2.LinkColumn",
"utilities.tables.ToggleColumn"
] | [((692, 706), 'utilities.tables.ToggleColumn', 'ToggleColumn', ([], {}), '()\n', (704, 706), False, 'from utilities.tables import BaseTable, ToggleColumn\n'), ((719, 738), 'django_tables2.LinkColumn', 'tables.LinkColumn', ([], {}), '()\n', (736, 738), True, 'import django_tables2 as tables\n'), ((755, 875), 'django_tab... |
from paukenator.nlp import WSWordAnnotator, WSWord
def test_text_has_correct_number_of_wswords(text_deu_1):
wswords = text_deu_1.wswords()
exp = 293 # counted using: wc -w
assert exp == len(wswords), \
f"Text must contain {exp} lines but got {len(wswords)}"
def test_has_property_type():
ass... | [
"paukenator.nlp.WSWordAnnotator"
] | [((501, 518), 'paukenator.nlp.WSWordAnnotator', 'WSWordAnnotator', ([], {}), '()\n', (516, 518), False, 'from paukenator.nlp import WSWordAnnotator, WSWord\n')] |
# Generated by Django 3.2.2 on 2021-10-04 14:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("api_meeting", "0002_auto_20201118_2210"),
]
operations = [
migrations.RemoveField(
model_name="meeting",
name="group... | [
"django.db.migrations.RemoveField",
"django.db.models.CharField",
"django.db.models.AutoField"
] | [((239, 297), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""meeting"""', 'name': '"""group"""'}), "(model_name='meeting', name='group')\n", (261, 297), False, 'from django.db import migrations, models\n'), ((440, 491), 'django.db.models.AutoField', 'models.AutoField', ([], {'prim... |
from flask import request
from flask_restful import Resource
from models.user import User
from models.db import db
from sqlalchemy.orm import joinedload
from sqlalchemy import select
class Users(Resource):
def get(self):
users = User.find_all()
return [u.json() for u in users]
def post(self):... | [
"models.user.User.find_all",
"models.db.db.session.commit",
"models.db.db.session.delete",
"models.user.User.find_by_email",
"sqlalchemy.orm.joinedload",
"models.user.User",
"flask.request.get_json",
"models.user.User.find_by_id"
] | [((243, 258), 'models.user.User.find_all', 'User.find_all', ([], {}), '()\n', (256, 258), False, 'from models.user import User\n'), ((336, 354), 'flask.request.get_json', 'request.get_json', ([], {}), '()\n', (352, 354), False, 'from flask import request\n'), ((370, 382), 'models.user.User', 'User', ([], {}), '(**data)... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('groups', '0002_auto_20150122_0754'),
... | [
"django.db.models.ManyToManyField",
"django.db.migrations.swappable_dependency",
"django.db.models.BooleanField"
] | [((210, 267), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (241, 267), False, 'from django.db import models, migrations\n'), ((451, 527), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(True... |
# ------------------------------------------------------------
# Copyright (c) 2017-present, SeetaTech, Co.,Ltd.
#
# Licensed under the BSD 2-Clause License.
# You should have received a copy of the BSD 2-Clause License
# along with the software. If not, See,
#
# <https://opensource.org/licenses/BSD-2-Clause>
#
# ... | [
"numpy.random.uniform",
"numpy.random.randn",
"dragon.Tensor.Ref",
"numpy.linalg.qr",
"numpy.zeros",
"numpy.prod",
"dragon.config.GetRandomSeed",
"dragon.operators.rnn.rnn_param.RNNParamSet",
"dragon.workspace.RunOperator",
"numpy.sign",
"numpy.diag",
"numpy.sqrt",
"warnings.warn",
"dragon... | [((2918, 3013), 'dragon.core.tensor_utils.FromShape', 'FromShape', ([], {'shape': '[self._weights_count]', 'name': "(self.name + '/weights' if self.name else None)"}), "(shape=[self._weights_count], name=self.name + '/weights' if self.\n name else None)\n", (2927, 3013), False, 'from dragon.core.tensor_utils import ... |
"""
Routines for plotting time-dependent vertical profiles.
"""
import numpy
import matplotlib.pyplot as plt
import cf_units
import matplotlib
import os
import iris
from . import utility
import matplotlib.dates as mdates
__all__ = [
'plot_timeprofile',
'make_timeprofile_plot',
'save_timeprofile_figure',
]
... | [
"matplotlib.dates.MonthLocator",
"numpy.abs",
"matplotlib.dates.epoch2num",
"iris.analysis.Nearest",
"matplotlib.pyplot.figure",
"matplotlib.colors.LogNorm",
"matplotlib.dates.HourLocator",
"cf_units.Unit",
"matplotlib.pyplot.close",
"matplotlib.pyplot.colorbar",
"matplotlib.dates.DateFormatter"... | [((1139, 1196), 'numpy.hstack', 'numpy.hstack', (['(coord.bounds[:, 0], coord.bounds[[-1], 1])'], {}), '((coord.bounds[:, 0], coord.bounds[[-1], 1]))\n', (1151, 1196), False, 'import numpy\n'), ((1260, 1335), 'cf_units.Unit', 'cf_units.Unit', (['"""seconds since 1970-01-01 00:00:00-00"""'], {'calendar': '"""gregorian""... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2019 the HERA Project
# Licensed under the MIT License
from hera_qm import utils
from hera_qm import ant_metrics
import sys
ap = utils.get_metrics_ArgumentParser('ant_metrics')
args = ap.parse_args()
history = ' '.join(sys.argv)
ant_metrics.ant_metrics_run... | [
"hera_qm.utils.get_metrics_ArgumentParser",
"hera_qm.ant_metrics.ant_metrics_run"
] | [((193, 240), 'hera_qm.utils.get_metrics_ArgumentParser', 'utils.get_metrics_ArgumentParser', (['"""ant_metrics"""'], {}), "('ant_metrics')\n", (225, 240), False, 'from hera_qm import utils\n'), ((293, 667), 'hera_qm.ant_metrics.ant_metrics_run', 'ant_metrics.ant_metrics_run', (['args.sum_files'], {'diff_files': 'args.... |
# coding=utf-8
# Copyright 2021 The IDEA Authors. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by a... | [
"transformers.BertTokenizer.from_pretrained"
] | [((1054, 1150), 'transformers.BertTokenizer.from_pretrained', 'BertTokenizer.from_pretrained', (['vocab_path'], {'additional_special_tokens': 'self.T5_special_tokens'}), '(vocab_path, additional_special_tokens=self.\n T5_special_tokens)\n', (1083, 1150), False, 'from transformers import BertTokenizer\n')] |
# #%L
# Copyright (c) 2016-2017 Cell Migration Standardisation Organization
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of co... | [
"pandas.DataFrame",
"datapackage.pushpull._convert_path",
"datapackage.push_datapackage"
] | [((2026, 2081), 'datapackage.push_datapackage', 'dp.push_datapackage', ([], {'descriptor': 'descr', 'backend': '"""pandas"""'}), "(descriptor=descr, backend='pandas')\n", (2045, 2081), True, 'import datapackage as dp\n'), ((3569, 3583), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (3581, 3583), True, 'import p... |
import json
import lambda_prototype_module as Module
def lambda_handler(event, context):
parameter_error = "[Parameter Error] 잘못된 파라미터가 전달되었습니다."
try:
if event.get('body') is None:
raise Exception(parameter_error)
request_body = json.loads(event['body'])
param = request_body[... | [
"json.loads",
"json.dumps",
"lambda_prototype_module.s3IOEvent.upload_meal",
"lambda_prototype_module.s3IOEvent.read_meal",
"lambda_prototype_module.CrawlingFunction.random_meal"
] | [((265, 290), 'json.loads', 'json.loads', (["event['body']"], {}), "(event['body'])\n", (275, 290), False, 'import json\n'), ((2065, 2083), 'json.dumps', 'json.dumps', (['result'], {}), '(result)\n', (2075, 2083), False, 'import json\n'), ((3444, 3462), 'json.dumps', 'json.dumps', (['result'], {}), '(result)\n', (3454,... |
#
# nuna_sql_tools: Copyright 2022 Nuna Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | [
"pyarrow.types.is_uint8",
"pyarrow.types.is_float64",
"dataschema.Schema_pb2.ColumnInfo.DecimalInfo",
"pyarrow.types.is_signed_integer",
"pyarrow.types.is_string",
"pyarrow.types.is_fixed_size_binary",
"pyarrow.types.is_uint16",
"pyarrow.types.is_map",
"pyarrow.types.is_large_binary",
"pyarrow.typ... | [((858, 893), 'pyarrow.types.is_signed_integer', 'pyarrow.types.is_signed_integer', (['dt'], {}), '(dt)\n', (889, 893), False, 'import pyarrow\n'), ((1884, 1912), 'pyarrow.types.is_float64', 'pyarrow.types.is_float64', (['dt'], {}), '(dt)\n', (1908, 1912), False, 'import pyarrow\n'), ((2104, 2139), 'pyarrow.types.is_da... |
import os
import uuid
import random
import time
import copy
from imagineiff.engine.player import Player
from imagineiff.engine.questions import Questions
from imagineiff.engine.questions.question import Question
from imagineiff.engine.states.pregame import StatePregame
from imagineiff.engine.states.statequestion impo... | [
"copy.deepcopy",
"imagineiff.engine.states.winner.StateWinner",
"random.choice",
"time.time",
"imagineiff.engine.states.results.StateResults",
"imagineiff.engine.states.statequestion.StateQuestion",
"os.urandom",
"imagineiff.words.generate_sentence",
"imagineiff.engine.states.pregame.StatePregame"
] | [((618, 642), 'copy.deepcopy', 'copy.deepcopy', (['Questions'], {}), '(Questions)\n', (631, 642), False, 'import copy\n'), ((689, 709), 'imagineiff.words.generate_sentence', 'generate_sentence', (['(2)'], {}), '(2)\n', (706, 709), False, 'from imagineiff.words import generate_sentence\n'), ((926, 940), 'imagineiff.engi... |
from datetime import datetime
from django.db import models
from django.db.models import Sum
from company.models import PaymentTypeEnum
from core.enums import OrderStateEnum, OrderTypeEnum
from core.models import CoreModel
# def get_list_price(id):
# return
# class KoliAdedi(CoreModel):
# adet = models.Inte... | [
"datetime.datetime.strftime",
"company.models.PaymentTypeEnum.choose_list",
"django.db.models.ForeignKey",
"django.db.models.CharField",
"django.db.models.Sum",
"django.db.models.FloatField",
"core.enums.OrderStateEnum.choose_list",
"django.db.models.DateTimeField",
"core.enums.OrderTypeEnum.choose_... | [((421, 495), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'null': '(True)', 'blank': '(True)', 'verbose_name': '"""Sipariş Tarihi"""'}), "(null=True, blank=True, verbose_name='Sipariş Tarihi')\n", (441, 495), False, 'from django.db import models\n'), ((548, 661), 'django.db.models.ForeignKey', 'mode... |
from django.shortcuts import render
from django.http import HttpResponse
from listings.models import Listing
from realtors.models import Realtor
from listings.choices import price_choices, bedroom_choices, state_choices
def index(request):
listings = Listing.objects.order_by('-list_date').filter(is_published=Tru... | [
"django.shortcuts.render",
"realtors.models.Realtor.objects.all",
"listings.models.Listing.objects.order_by",
"realtors.models.Realtor.objects.order_by"
] | [((390, 434), 'django.shortcuts.render', 'render', (['request', '"""pages/index.html"""', 'context'], {}), "(request, 'pages/index.html', context)\n", (396, 434), False, 'from django.shortcuts import render\n'), ((494, 532), 'realtors.models.Realtor.objects.order_by', 'Realtor.objects.order_by', (['"""-hire_date"""'], ... |
from setuptools import setup
import fastentrypoints
setup(
name='dummypkg',
version='0.0.0',
py_modules=['dummy'],
description='dummy package for the test',
entry_points={'console_scripts': ['hello=dummy:main']},
)
| [
"setuptools.setup"
] | [((53, 222), 'setuptools.setup', 'setup', ([], {'name': '"""dummypkg"""', 'version': '"""0.0.0"""', 'py_modules': "['dummy']", 'description': '"""dummy package for the test"""', 'entry_points': "{'console_scripts': ['hello=dummy:main']}"}), "(name='dummypkg', version='0.0.0', py_modules=['dummy'], description=\n 'du... |
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from pm4py.objects.log.exporter.xes.factory import export_log
from pm4py.objects.log.importer.xes.factory import import_log
from pm4py.objects.log.log import EventLog
from src.logs.models import Log
from src.utils.file... | [
"pm4py.objects.log.exporter.xes.factory.export_log",
"src.logs.models.Log.objects.create",
"src.utils.file_service.create_unique_name",
"pm4py.objects.log.importer.xes.factory.import_log",
"src.utils.log_metrics.resources_by_date",
"src.utils.log_metrics.new_trace_start",
"src.utils.log_metrics.max_even... | [((624, 648), 'src.utils.file_service.create_unique_name', 'create_unique_name', (['name'], {}), '(name)\n', (642, 648), False, 'from src.utils.file_service import create_unique_name\n'), ((890, 953), 'src.logs.models.Log.objects.create', 'Log.objects.create', ([], {'name': 'name', 'path': 'path', 'properties': 'proper... |
"""Unit tests for port knocker module."""
import asyncio
from ipaddress import ip_address
import time
import pytest
from pyatv.support.knock import knock, knocker
from pyatv.support.net import unused_port
from tests.fake_knock import create_knock_server
from tests.utils import until
LOCALHOST = ip_address("127.0.0... | [
"ipaddress.ip_address",
"time.monotonic",
"pyatv.support.knock.knock",
"pyatv.support.knock.knocker",
"tests.utils.until"
] | [((301, 324), 'ipaddress.ip_address', 'ip_address', (['"""127.0.0.1"""'], {}), "('127.0.0.1')\n", (311, 324), False, 'from ipaddress import ip_address\n'), ((338, 363), 'ipaddress.ip_address', 'ip_address', (['"""169.254.0.0"""'], {}), "('169.254.0.0')\n", (348, 363), False, 'from ipaddress import ip_address\n'), ((379... |
from time import sleep
import requests, subprocess, sys
import main
import config
import stats
import gc
url = "http://localhost:5000/"
def test_plainresponse():
params = {'paste': 'test', 'raw': 'true'}
r = requests.post(url, data=params)
response = r.text.split(" | ")
r = requests.get(response[0])
assert r.h... | [
"subprocess.run",
"time.sleep",
"requests.delete",
"requests.get",
"requests.post"
] | [((214, 245), 'requests.post', 'requests.post', (['url'], {'data': 'params'}), '(url, data=params)\n', (227, 245), False, 'import requests, subprocess, sys\n'), ((283, 308), 'requests.get', 'requests.get', (['response[0]'], {}), '(response[0])\n', (295, 308), False, 'import requests, subprocess, sys\n'), ((399, 430), '... |
from EasyTrainerCore import EasyTrain
if __name__ == "__main__":
# after training, the EasyTrain.start() will return the latest model
model = EasyTrain.start(
train=True, # True: train the model, False: test the model you choose to resume
train_and_val_split=0.8,
# ↑ train and validat... | [
"EasyTrainerCore.EasyTrain.start"
] | [((151, 457), 'EasyTrainerCore.EasyTrain.start', 'EasyTrain.start', ([], {'train': '(True)', 'train_and_val_split': '(0.8)', 'gpu_nums': '(1)', 'model_name': '"""densenet169"""', 'froze_front_layers': '(True)', 'lr': '(0.001)', 'lr_adjust_strategy': '"""cosine"""', 'optimizer': '"""Adam"""', 'loss_function': '"""CrossE... |
from fastapi import APIRouter
from .messages import router as messages
from .message import router as message
messages_router = APIRouter()
messages_router.include_router(messages, tags=[])
messages_router.include_router(message, tags=[])
| [
"fastapi.APIRouter"
] | [((130, 141), 'fastapi.APIRouter', 'APIRouter', ([], {}), '()\n', (139, 141), False, 'from fastapi import APIRouter\n')] |
import matplotlib
from utils.data_reader import Personas_CVAE
from model.CVAE.model import Model
from model.CVAE.util.config import Model_Config
matplotlib.use('Agg')
from utils.data_reader import Personas
from model.transformer import Transformer
import pickle
from utils import config
import torch
import torch.nn as ... | [
"tqdm.tqdm",
"utils.data_reader.Personas_CVAE",
"model.CVAE.util.config.Model_Config",
"pprint.PrettyPrinter",
"matplotlib.use",
"pickle.load",
"model.CVAE.model.Model"
] | [((146, 167), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (160, 167), False, 'import matplotlib\n'), ((397, 427), 'pprint.PrettyPrinter', 'pprint.PrettyPrinter', ([], {'indent': '(1)'}), '(indent=1)\n', (417, 427), False, 'import pprint\n'), ((2379, 2393), 'model.CVAE.util.config.Model_Config'... |
import sys
import numpy
def solve(M, call, value, end, garments, mat):
aux = []
M -= value
if M < 0:
return sys.maxsize
if call == end:
return M
if(mat[M][call] != -1):
return mat[M][call]
aux = [int(solve(M, call+1, a, end, garments, mat)) for a in garments[call]]... | [
"numpy.zeros",
"numpy.place"
] | [((535, 563), 'numpy.zeros', 'numpy.zeros', ([], {'shape': '(201, 21)'}), '(shape=(201, 21))\n', (546, 563), False, 'import numpy\n'), ((572, 602), 'numpy.place', 'numpy.place', (['mat', '(mat == 0)', '(-1)'], {}), '(mat, mat == 0, -1)\n', (583, 602), False, 'import numpy\n')] |
print('='*8,'Seno, Cosseno e Tangente','='*8)
a = float(input('Digite o seu angulo:'))
from math import radians, sin, cos, tan
s = sin(radians(a))
c = cos(radians(a))
t = tan(radians(a))
print('''Para o angulo analisado {}, temos:
Seno igual a {:.2f}
Cosseno igual a {:.2f}
Tangente igual a {:.2f}'''.format(a,s,c,t))
| [
"math.radians"
] | [((135, 145), 'math.radians', 'radians', (['a'], {}), '(a)\n', (142, 145), False, 'from math import radians, sin, cos, tan\n'), ((155, 165), 'math.radians', 'radians', (['a'], {}), '(a)\n', (162, 165), False, 'from math import radians, sin, cos, tan\n'), ((175, 185), 'math.radians', 'radians', (['a'], {}), '(a)\n', (18... |
from flask import jsonify
from . import api
@api.route('/', methods=['GET'])
def index():
return jsonify("Welcome to the fmeca API. Check out '/api/facilities/'.")
| [
"flask.jsonify"
] | [((103, 169), 'flask.jsonify', 'jsonify', (['"""Welcome to the fmeca API. Check out \'/api/facilities/\'."""'], {}), '("Welcome to the fmeca API. Check out \'/api/facilities/\'.")\n', (110, 169), False, 'from flask import jsonify\n')] |
import os
from flask import Flask, flash, request, redirect, url_for,make_response, render_template, send_from_directory, send_file
from werkzeug.utils import secure_filename
from tempfile import NamedTemporaryFile
from shutil import copyfileobj
from os import remove
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gi... | [
"tempfile.NamedTemporaryFile",
"os.remove",
"flask.Flask",
"werkzeug.utils.secure_filename",
"flask.url_for",
"shutil.copyfileobj",
"flask.send_file"
] | [((332, 347), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (337, 347), False, 'from flask import Flask, flash, request, redirect, url_for, make_response, render_template, send_from_directory, send_file\n'), ((1614, 1658), 'tempfile.NamedTemporaryFile', 'NamedTemporaryFile', ([], {'mode': '"""w+b"""', 'su... |
from os.path import join, dirname
from setuptools import setup, find_packages
base = dirname(__file__)
README = join(base, 'README.rst')
def lines(filename):
with open(filename) as lines:
return [line.rstrip() for line in lines]
setup(
name='sparrow',
version='1.0.1-SNAPSHOT',
author='<NAM... | [
"os.path.dirname",
"os.path.join",
"setuptools.find_packages"
] | [((87, 104), 'os.path.dirname', 'dirname', (['__file__'], {}), '(__file__)\n', (94, 104), False, 'from os.path import join, dirname\n'), ((114, 138), 'os.path.join', 'join', (['base', '"""README.rst"""'], {}), "(base, 'README.rst')\n", (118, 138), False, 'from os.path import join, dirname\n'), ((833, 880), 'setuptools.... |
import random
import unittest
import numpy as np
from scipy.stats import norm
from ..StoneModel import StoneModel, ReqFuncSolver, logpdf_sum, StoneMod
def get_random_vars():
kai = random.random()
kx = random.random()
vi = random.randint(1, 30)
R = random.random()
Li = random.random()
return (k... | [
"unittest.main",
"random.randint",
"scipy.stats.norm.logpdf",
"numpy.isinf",
"numpy.isnan",
"random.random",
"numpy.array",
"numpy.log10"
] | [((185, 200), 'random.random', 'random.random', ([], {}), '()\n', (198, 200), False, 'import random\n'), ((210, 225), 'random.random', 'random.random', ([], {}), '()\n', (223, 225), False, 'import random\n'), ((235, 256), 'random.randint', 'random.randint', (['(1)', '(30)'], {}), '(1, 30)\n', (249, 256), False, 'import... |
"""
"""
import os
import re
from unittest.mock import MagicMock
import pytest
from acc2tax.database import int2bool
from acc2tax.database import bool2int
from acc2tax.database import Base
from acc2tax.database import BaseTable
from acc2tax.database import Acc2Tax
from acc2tax.database import Nodes
from acc2tax.datab... | [
"acc2tax.database.Nodes.from_file",
"acc2tax.database.Base.metadata.create_all",
"acc2tax.database.BaseTable.string_fmt",
"acc2tax.database.BaseTable.to_table",
"unittest.mock.MagicMock",
"acc2tax.database.BaseTable.from_file",
"acc2tax.database.Nodes.get_parents",
"acc2tax.database.bool2int",
"pyte... | [((433, 449), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (447, 449), False, 'import pytest\n'), ((846, 862), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (860, 862), False, 'import pytest\n'), ((967, 1033), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""expected,i"""', "[(True, '1'), (F... |
import battlecode as bc
import random
import sys
import traceback
import collections as fast
import time
import math
print("pystarting")
# A GameController is the main type that you talk to the game with.
# Its constructor will connect to a running game.
gc = bc.GameController()
print("pystarted")
# It's a good ide... | [
"traceback.print_exc",
"math.sqrt",
"random.choice",
"time.time",
"random.seed",
"sys.stdout.flush",
"battlecode.UnitType.Factory.blueprint_cost",
"battlecode.GameController",
"sys.stderr.flush",
"collections.deque"
] | [((262, 281), 'battlecode.GameController', 'bc.GameController', ([], {}), '()\n', (279, 281), True, 'import battlecode as bc\n'), ((563, 580), 'random.seed', 'random.seed', (['(6137)'], {}), '(6137)\n', (574, 580), False, 'import random\n'), ((5863, 5875), 'collections.deque', 'fast.deque', ([], {}), '()\n', (5873, 587... |
#! /usr/bin/env python
from __future__ import print_function
from collections import defaultdict
import build_model
import pddl_to_prolog
import pddl
import timers
def get_fluent_facts(task, model):
fluent_predicates = set()
for action in task.actions:
for effect in action.effects:
fluen... | [
"pddl_to_prolog.translate",
"pddl.open",
"pddl.Atom",
"build_model.compute_model",
"collections.defaultdict",
"timers.timing"
] | [((592, 609), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (603, 609), False, 'from collections import defaultdict\n'), ((1230, 1247), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (1241, 1247), False, 'from collections import defaultdict\n'), ((2909, 2952), 'pddl_to_pro... |
import numpy as np
import os.path
import os
from io import BytesIO
from zipfile import ZipFile
from urllib.request import urlopen
from word_knn.closest_words import inverse_dict
from word_knn.closest_words import ClosestWords
from word_knn.closest_words import build_knn_index
from pathlib import Path
home = str(Path.h... | [
"io.BytesIO",
"zipfile.ZipFile",
"pathlib.Path.home",
"os.makedirs",
"os.path.exists",
"word_knn.closest_words.ClosestWords.from_disk_cache",
"urllib.request.urlopen",
"word_knn.closest_words.ClosestWords",
"word_knn.closest_words.inverse_dict",
"word_knn.closest_words.build_knn_index"
] | [((314, 325), 'pathlib.Path.home', 'Path.home', ([], {}), '()\n', (323, 325), False, 'from pathlib import Path\n'), ((1358, 1373), 'word_knn.closest_words.inverse_dict', 'inverse_dict', (['d'], {}), '(d)\n', (1370, 1373), False, 'from word_knn.closest_words import inverse_dict\n'), ((1796, 1811), 'word_knn.closest_word... |
import os
import glob
import torch
import random
import logging
import argparse
import zipfile
import numpy as np
from tqdm import tqdm, trange
from torch.utils.data import DataLoader
from transformers import (BertConfig, BertTokenizer)
from modeling import MonoBERT
from dataset import RelevantDataset, get_collate_fun... | [
"dataset.get_collate_function",
"tqdm.tqdm",
"dataset.RelevantDataset",
"argparse.ArgumentParser",
"logging.basicConfig",
"os.makedirs",
"os.path.exists",
"torch.cuda.device_count",
"transformers.BertTokenizer.from_pretrained",
"torch.cuda.is_available",
"numpy.array",
"transformers.BertConfig... | [((336, 363), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (353, 363), False, 'import logging\n'), ((364, 494), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s-%(levelname)s-%(name)s- %(message)s"""', 'datefmt': '"""%d %H:%M:%S"""', 'level': 'logging.INFO'}... |
from fastapi import Depends, FastAPI, HTTPException, status, Security
from functools import lru_cache
from datetime import datetime, timedelta
from sqlalchemy.orm import Session
from fastapi.security import (
OAuth2PasswordBearer,
SecurityScopes,
)
from jose import JWTError, jwt
from passlib.context im... | [
"jose.jwt.decode",
"fastapi.security.OAuth2PasswordBearer",
"fastapi.HTTPException",
"datetime.datetime.utcnow",
"datetime.timedelta",
"fastapi.Depends",
"functools.lru_cache",
"passlib.context.CryptContext",
"jose.jwt.encode",
"fastapi.FastAPI"
] | [((490, 541), 'passlib.context.CryptContext', 'CryptContext', ([], {'schemes': "['bcrypt']", 'deprecated': '"""auto"""'}), "(schemes=['bcrypt'], deprecated='auto')\n", (502, 541), False, 'from passlib.context import CryptContext\n'), ((561, 599), 'fastapi.security.OAuth2PasswordBearer', 'OAuth2PasswordBearer', ([], {'t... |
# dataset.py
import audformat
import pandas as pd
import ast
import os
from random import sample
from util import Util
from plots import Plots
import glob_conf
class Dataset:
""" Class to represent datasets"""
name = '' # An identifier for the dataset
config = None # The configuration
db = None # The ... | [
"pandas.DataFrame",
"util.Util",
"ast.literal_eval",
"pandas.read_pickle",
"plots.Plots",
"audformat.Database.load",
"os.path.join"
] | [((648, 654), 'util.Util', 'Util', ([], {}), '()\n', (652, 654), False, 'from util import Util\n'), ((675, 682), 'plots.Plots', 'Plots', ([], {}), '()\n', (680, 682), False, 'from plots import Plots\n'), ((886, 915), 'audformat.Database.load', 'audformat.Database.load', (['root'], {}), '(root)\n', (909, 915), False, 'i... |
from django.urls import path
from app.views import index
app_name = 'app'
urlpatterns = [
path('index/', index, name='index'),
]
| [
"django.urls.path"
] | [((97, 132), 'django.urls.path', 'path', (['"""index/"""', 'index'], {'name': '"""index"""'}), "('index/', index, name='index')\n", (101, 132), False, 'from django.urls import path\n')] |
"""
Execute: python tsp.py -f filename.tsp -m METHOD
Where METHOD:
- GREEDY
- GREEDY_2OPT
- GENETIC
Other options:
-s seed
-t time limit
-v verbose
"""
import argparse
import matplotlib.pyplot as plt
import math
import time
import random
from heapq import *
#TSP instance
class instance:
def __init__(se... | [
"matplotlib.pyplot.show",
"argparse.ArgumentParser",
"matplotlib.pyplot.plot",
"math.ceil",
"random.randint",
"matplotlib.pyplot.scatter",
"time.time",
"math.acos",
"random.random",
"random.seed",
"math.cos",
"matplotlib.pyplot.savefig"
] | [((1457, 1479), 'matplotlib.pyplot.scatter', 'plt.scatter', (['X', 'Y'], {'s': '(1)'}), '(X, Y, s=1)\n', (1468, 1479), True, 'import matplotlib.pyplot as plt\n'), ((1854, 1864), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1862, 1864), True, 'import matplotlib.pyplot as plt\n'), ((2052, 2100), 'argparse.Arg... |
#!/usr/bin/env python3.5
# -*- coding: utf-8 -*-
import re
import numpy as np
__author__ = '<NAME>'
kb = 8.617e-5 # unit eV / K
class ReadInput(object):
def __init__(self, filename='formation energy input.txt'):
with open(filename, 'r') as fp:
lines = fp.readlines()
fo... | [
"numpy.savetxt",
"numpy.array",
"numpy.loadtxt",
"numpy.linspace",
"numpy.dot",
"numpy.vstack"
] | [((2320, 2365), 'numpy.linspace', 'np.linspace', (['order.vbm', 'order.cbm'], {'num': 'points'}), '(order.vbm, order.cbm, num=points)\n', (2331, 2365), True, 'import numpy as np\n'), ((2982, 3028), 'numpy.vstack', 'np.vstack', (['(fermi_level, min_formation_energy)'], {}), '((fermi_level, min_formation_energy))\n', (29... |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 12 15:01:44 2017
@author:
"""
import sys
reload(sys)
sys.setdefaultencoding('cp932')
tes = sys.getdefaultencoding()
import os
import cv2
import numpy as np
import pyws as m
import winxpgui
from PIL import ImageGrab
from PyQt4 import QtGui, QtCore
... | [
"PyQt4.QtCore.QTimer",
"PyQt4.QtGui.QWidget",
"PyQt4.QtGui.QLabel",
"sys.getdefaultencoding",
"PyQt4.QtGui.QVBoxLayout",
"PyQt4.QtGui.QLineEdit",
"cv2.cvtColor",
"PyQt4.QtGui.QMainWindow",
"sys.setdefaultencoding",
"datetime.datetime.now",
"PIL.ImageGrab.grab",
"numpy.asarray",
"PyQt4.QtGui.... | [((114, 145), 'sys.setdefaultencoding', 'sys.setdefaultencoding', (['"""cp932"""'], {}), "('cp932')\n", (136, 145), False, 'import sys\n'), ((153, 177), 'sys.getdefaultencoding', 'sys.getdefaultencoding', ([], {}), '()\n', (175, 177), False, 'import sys\n'), ((4044, 4107), 'ConfigParser.RawConfigParser', 'ConfigParser.... |
import argparse
from td import OneStepTD
from off_pol_td import OffPolicyTD
from driving import DrivingEnv, TRAVEL_TIME
from sarsa import Sarsa
from windy_gridworld import WindyGridworld
import numpy as np
from randomwalk import RandomWalk, NotSoRandomWalk, LEFT, RIGHT
from cliff import TheCliff
import matplotlib.pyplo... | [
"seaborn.heatmap",
"argparse.ArgumentParser",
"td_afterstate.TDAfterstate",
"td.OneStepTD",
"off_pol_td.OffPolicyTD",
"max_bias_mdp.MaxBiasMDP",
"matplotlib.pyplot.figure",
"numpy.mean",
"car_rental_afterstate.CarRentalAfterstateEnv",
"numpy.linalg.norm",
"driving.DrivingEnv",
"matplotlib.pypl... | [((2297, 2309), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2307, 2309), True, 'import matplotlib.pyplot as plt\n'), ((2347, 2359), 'driving.DrivingEnv', 'DrivingEnv', ([], {}), '()\n', (2357, 2359), False, 'from driving import DrivingEnv, TRAVEL_TIME\n'), ((2535, 2586), 'td.OneStepTD', 'OneStepTD', ([... |
# coding=utf-8
from __future__ import unicode_literals
from datetime import datetime
from django.db import models
class Activity(models.Model):
name = models.CharField(max_length=50, verbose_name='活动名')
score = models.DecimalField(max_digits=5, decimal_places=2, verbose_name='分数')
desc = models.CharField... | [
"django.db.models.CharField",
"django.db.models.DecimalField",
"django.db.models.DateTimeField",
"django.db.models.BooleanField"
] | [((158, 209), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)', 'verbose_name': '"""活动名"""'}), "(max_length=50, verbose_name='活动名')\n", (174, 209), False, 'from django.db import models\n'), ((222, 292), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(5)', 'decim... |
# Reference: https://www.blakeporterneuro.com/learning-python-project-3-scrapping-data-from-steams-community-market/
import json
def get_steam_cookie_file_name() -> str:
steam_cookie_file_name = 'personal_info.json'
return steam_cookie_file_name
def load_steam_cookie_from_disk(file_name_with_personal_info... | [
"json.dump",
"json.load"
] | [((574, 586), 'json.load', 'json.load', (['f'], {}), '(f)\n', (583, 586), False, 'import json\n'), ((1104, 1124), 'json.dump', 'json.dump', (['cookie', 'f'], {}), '(cookie, f)\n', (1113, 1124), False, 'import json\n')] |
'''Constructs project specific dictionary containing prior model related objects
To construct the dictionary, the code will create an instance of the PriorHandler
class. Utilizing the methods of this class then loads the covariance related
objects.
Inputs:
- hyperp: dictionary storing set hyperparameter values
... | [
"utils_data.prior_handler.PriorHandler",
"numpy.expand_dims"
] | [((1113, 1183), 'utils_data.prior_handler.PriorHandler', 'PriorHandler', (['hyperp', 'options', 'filepaths', 'options.parameter_dimensions'], {}), '(hyperp, options, filepaths, options.parameter_dimensions)\n', (1125, 1183), False, 'from utils_data.prior_handler import PriorHandler\n'), ((1341, 1370), 'numpy.expand_dim... |
import numpy as np
A=np.array([[1,-2j],[2j,5]])
print(A)
#A=L.dot(L^H) with A is positive definite matrix and L is lower triangular matrix.
L=np.linalg.cholesky(A)
print(L)
print(L.dot(L.T.conj()))
a=np.array([[4,12,-16],[12,37,-43],[-16,-43,98]])
L=np.linalg.cholesky(a)
print(L)
L_T=L.transpose()
print(L.dot(L_T)... | [
"numpy.array",
"numpy.linalg.cholesky"
] | [((22, 55), 'numpy.array', 'np.array', (['[[1, -2.0j], [2.0j, 5]]'], {}), '([[1, -2.0j], [2.0j, 5]])\n', (30, 55), True, 'import numpy as np\n'), ((145, 166), 'numpy.linalg.cholesky', 'np.linalg.cholesky', (['A'], {}), '(A)\n', (163, 166), True, 'import numpy as np\n'), ((204, 259), 'numpy.array', 'np.array', (['[[4, 1... |
"""CLI main runner"""
from py_greet import hello
def main():
"""main runner"""
print(hello('World'))
if __name__ == '__main__':
main()
| [
"py_greet.hello"
] | [((92, 106), 'py_greet.hello', 'hello', (['"""World"""'], {}), "('World')\n", (97, 106), False, 'from py_greet import hello\n')] |
# =============================================================================
# PROJECT CHRONO - http://projectchrono.org
#
# Copyright (c) 2019 projectchrono.org
# All rights reserved.
#
# Use of this source code is governed by a BSD-style license that can be found
# in the LICENSE file at the top level of the distr... | [
"pychrono.core.ChFrameD",
"pychrono.core.ChBodyEasyCylinder",
"pychrono.irrlicht.ChVisualSystemIrrlicht",
"pychrono.core.ChLinkMotorRotationSpeed",
"pychrono.core.ChSystemNSC",
"pychrono.core.ChVectorD",
"pychrono.core.ChFunction_Const",
"pychrono.core.ChLinkLockPrismatic",
"numpy.linspace",
"pych... | [((1084, 1104), 'pychrono.core.ChSystemNSC', 'chrono.ChSystemNSC', ([], {}), '()\n', (1102, 1104), True, 'import pychrono.core as chrono\n'), ((1157, 1185), 'pychrono.core.ChVectorD', 'chrono.ChVectorD', (['(-1)', '(0.5)', '(0)'], {}), '(-1, 0.5, 0)\n', (1173, 1185), True, 'import pychrono.core as chrono\n'), ((1349, 1... |
#!/usr/bin/env python
# coding: utf-8
# # Accessing an AutoAI Model
# In this notebook, we use the Watson Machine Learning (WML) API to find the available models available, and find the availablr deployments.
#
# We then score some records using a Churn model.
#
# Finally, we show how a deployment could be removed.
... | [
"watson_machine_learning_client.WatsonMachineLearningAPIClient"
] | [((916, 963), 'watson_machine_learning_client.WatsonMachineLearningAPIClient', 'WatsonMachineLearningAPIClient', (['wml_credentials'], {}), '(wml_credentials)\n', (946, 963), False, 'from watson_machine_learning_client import WatsonMachineLearningAPIClient\n')] |
import dataclasses
import logging
from typing import ClassVar
import numpy as np
import torch
from .annrescaler import AnnRescaler
from .. import headmeta
from ..visualizer import Cif as CifVisualizer
from ..utils import create_sink, mask_valid_area
LOG = logging.getLogger(__name__)
@dataclasses.dataclass
class Ci... | [
"numpy.full",
"numpy.logical_and",
"numpy.zeros",
"numpy.expand_dims",
"numpy.isnan",
"numpy.linalg.norm",
"numpy.round",
"logging.getLogger"
] | [((259, 286), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (276, 286), False, 'import logging\n'), ((2145, 2201), 'numpy.zeros', 'np.zeros', (['(n_fields, field_h, field_w)'], {'dtype': 'np.float32'}), '((n_fields, field_h, field_w), dtype=np.float32)\n', (2153, 2201), True, 'import num... |
import os
import os.path
import matplotlib.pyplot as plt
import numpy as np
def get_points():
"""
Function: get_points\n
Parameters: None\n
Returns: list of tuples containing coordinate points\n
"""
parent_dir = os.getcwd()
dir_name = 'analysis_output_files'
file_name = 'scenario_analy... | [
"matplotlib.pyplot.title",
"os.mkdir",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.clf",
"os.getcwd",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"os.path.join",
"matplotlib.pyplot.savefig"
] | [((238, 249), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (247, 249), False, 'import os\n'), ((345, 390), 'os.path.join', 'os.path.join', (['parent_dir', 'dir_name', 'file_name'], {}), '(parent_dir, dir_name, file_name)\n', (357, 390), False, 'import os\n'), ((874, 885), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (883... |
# Imports
from algorithm import *
from get_response import get_price
from trade import *
import time
import datetime
import sys
# Send all print()s to stdout
sys.stdout = open("./CryptoBot.txt", "w")
# Timestamp
def timestamp():
print("Time:",
datetime.datetime.fromtimestamp(
int(time.t... | [
"time.time",
"get_response.get_price",
"time.sleep"
] | [((1620, 1633), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (1630, 1633), False, 'import time\n'), ((760, 771), 'get_response.get_price', 'get_price', ([], {}), '()\n', (769, 771), False, 'from get_response import get_price\n'), ((1220, 1231), 'get_response.get_price', 'get_price', ([], {}), '()\n', (1229, 1231... |
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.exceptions import ObjectDoesNotExist
# Create your models here.
class NeighbourHood(models.Model):
neighbourhood_name = models.CharField(max... | [
"django.db.models.OneToOneField",
"django.db.models.TextField",
"django.db.models.CharField",
"django.db.models.ForeignKey",
"django.dispatch.receiver",
"django.db.models.EmailField",
"django.db.models.ImageField",
"django.db.models.DateTimeField"
] | [((300, 331), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(90)'}), '(max_length=90)\n', (316, 331), False, 'from django.db import models\n'), ((363, 394), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(90)'}), '(max_length=90)\n', (379, 394), False, 'from django.db im... |
import argparse
import asyncio
import sys
import uuid
import uvicorn
import controller as controller
import logger as logger
from fastapi import FastAPI, Request, Header, Query
from fastapi.responses import JSONResponse
from typing import List, Optional
app = FastAPI()
# Sets the certificate registry URL for the wo... | [
"uuid.uuid4",
"controller.handle_fi_request",
"argparse.ArgumentParser",
"controller.handle_fi_fetch",
"controller.setup_certificate",
"fastapi.Header",
"controller.get_consent_artifact",
"controller.handle_consent_handle",
"controller.get_current_timestamp",
"fastapi.Query",
"fastapi.FastAPI",
... | [((263, 272), 'fastapi.FastAPI', 'FastAPI', ([], {}), '()\n', (270, 272), False, 'from fastapi import FastAPI, Request, Header, Query\n'), ((796, 808), 'fastapi.Header', 'Header', (['None'], {}), '(None)\n', (802, 808), False, 'from fastapi import FastAPI, Request, Header, Query\n'), ((1107, 1133), 'fastapi.responses.J... |
import random
import os
from data.art import Colours
from data.item_rarity import Item_Rarity
class Loot:
def __init__(self, gold, item):
self.forest_mob_drops = {}
self.gold = gold
self.item = item
# loot1
Loot.forest_mob_drops = {"[Wooden Sword] + (10 ATK)": 50,
... | [
"data.menu.game_menu",
"os.system",
"random.randint"
] | [((1448, 1468), 'random.randint', 'random.randint', (['(1)', '(3)'], {}), '(1, 3)\n', (1462, 1468), False, 'import random\n'), ((1577, 1599), 'random.randint', 'random.randint', (['(1)', '(101)'], {}), '(1, 101)\n', (1591, 1599), False, 'import random\n'), ((3970, 3990), 'random.randint', 'random.randint', (['(3)', '(6... |
import config
def create_screen():
if config.virtual_hardware:
from screen.virtualscreen import VirtualScreen
return VirtualScreen()
else:
from screen.screen import Screen
return Screen() | [
"screen.screen.Screen",
"screen.virtualscreen.VirtualScreen"
] | [((123, 138), 'screen.virtualscreen.VirtualScreen', 'VirtualScreen', ([], {}), '()\n', (136, 138), False, 'from screen.virtualscreen import VirtualScreen\n'), ((190, 198), 'screen.screen.Screen', 'Screen', ([], {}), '()\n', (196, 198), False, 'from screen.screen import Screen\n')] |
"""Requests adapter implementing a JSON-RPC protocol for LSP"""
from requests import Response
from requests.adapters import BaseAdapter
from urllib3.util import parse_url, connection
class LSPAdapter(BaseAdapter):
"""
A requests adapter for JSON-RPC used in LSP.
Uses urllib3 helpers for connecting and p... | [
"urllib3.util.parse_url",
"requests.Response",
"urllib3.util.connection.create_connection"
] | [((1373, 1395), 'urllib3.util.parse_url', 'parse_url', (['request.url'], {}), '(request.url)\n', (1382, 1395), False, 'from urllib3.util import parse_url, connection\n'), ((2133, 2143), 'requests.Response', 'Response', ([], {}), '()\n', (2141, 2143), False, 'from requests import Response\n'), ((1541, 1593), 'urllib3.ut... |
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from swagger_server.models.base_model_ import Model
from swagger_server import util
class Notification(Model):
"""NOTE: This class is auto generated by the swagge... | [
"swagger_server.util.deserialize_model"
] | [((1770, 1803), 'swagger_server.util.deserialize_model', 'util.deserialize_model', (['dikt', 'cls'], {}), '(dikt, cls)\n', (1792, 1803), False, 'from swagger_server import util\n')] |
"""
This class represent a Salesman object
The path is determined by his DNA
1.) fitness is performance of path
2.) dna is the path
"""
import DNA
import random as r
from itertools import cycle
import math as m
#-------------------------------------------------------------------... | [
"itertools.cycle",
"DNA.Dna",
"math.pow"
] | [((983, 993), 'DNA.Dna', 'DNA.Dna', (['x'], {}), '(x)\n', (990, 993), False, 'import DNA\n'), ((2106, 2124), 'itertools.cycle', 'cycle', (['listOfPoint'], {}), '(listOfPoint)\n', (2111, 2124), False, 'from itertools import cycle\n'), ((3091, 3128), 'math.pow', 'm.pow', (['(1.0 / (self.distance * 1.0))', '(2)'], {}), '(... |
import uproot
#from get_tree import getit, featmap_vars
from getit_getter import getit_featmapvars_getter
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--model","-m", help="",required=True)
parser.add_argument("--split_ext_nu", help="",default=None)
args = parser.parse_args()
getit, featmap_v... | [
"uproot.open",
"getit_getter.getit_featmapvars_getter",
"argparse.ArgumentParser"
] | [((132, 157), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (155, 157), False, 'import argparse\n'), ((326, 381), 'getit_getter.getit_featmapvars_getter', 'getit_featmapvars_getter', (['args.model', 'args.split_ext_nu'], {}), '(args.model, args.split_ext_nu)\n', (350, 381), False, 'from getit_... |
"""Test functions."""
import pprint
from kalibrate import fn
kal_scan_sample = b"""Found 1 device(s):
0: Generic RTL2832U OEM
Using device 0: Generic RTL2832U OEM
Found Rafael Micro R820T tuner
Exact sample rate is: 270833.002142 Hz
Setting gain: 45.0 dB
kal: Scanning for GSM-850 base stations.
channel detect thre... | [
"kalibrate.fn.build_kal_scan_band_string",
"kalibrate.fn.parse_kal_scan",
"kalibrate.fn.to_eng",
"kalibrate.fn.parse_kal_channel",
"kalibrate.fn.determine_final_freq",
"pprint.pprint",
"kalibrate.fn.herz_me"
] | [((3350, 3400), 'kalibrate.fn.build_kal_scan_band_string', 'fn.build_kal_scan_band_string', (['kal_bin', 'band', 'args'], {}), '(kal_bin, band, args)\n', (3379, 3400), False, 'from kalibrate import fn\n'), ((3641, 3691), 'kalibrate.fn.build_kal_scan_band_string', 'fn.build_kal_scan_band_string', (['kal_bin', 'band', 'a... |
# -*- coding: utf-8 -*-
import os,re,netaddr,requests
from netaddr import *
r = requests.get('https://raw.githubusercontent.com/CNMan/chinaroute/master/cnroute_merged.txt')
cnroute_merged = open('cnroute_merged.txt', 'w')
cnroute_merged.write(r.text)
cnroute_merged.close()
# 将所有/12-/32替换为/11
mergedlines = [line.rstr... | [
"os.remove",
"requests.get"
] | [((82, 184), 'requests.get', 'requests.get', (['"""https://raw.githubusercontent.com/CNMan/chinaroute/master/cnroute_merged.txt"""'], {}), "(\n 'https://raw.githubusercontent.com/CNMan/chinaroute/master/cnroute_merged.txt'\n )\n", (94, 184), False, 'import os, re, netaddr, requests\n'), ((3478, 3506), 'os.remove'... |
import sys
import time
from orangewidget import gui
from orangewidget.settings import Setting
from oasys.widgets import gui as oasysgui
from oasys.widgets import congruence
from oasys.util.oasys_util import EmittingStream
from orangecontrib.shadow4.widgets.gui.ow_electron_beam import OWElectronBeam
from orangecontr... | [
"orangewidget.settings.Setting",
"shadow4.beamline.s4_beamline.S4Beamline",
"oasys.util.oasys_util.EmittingStream",
"oasys.widgets.gui.widgetBox",
"oasys.widgets.gui.lineEdit",
"oasys.widgets.congruence.checkPositiveNumber",
"syned.widget.widget_decorator.WidgetDecorator.append_syned_input_data",
"sha... | [((968, 1015), 'syned.widget.widget_decorator.WidgetDecorator.append_syned_input_data', 'WidgetDecorator.append_syned_input_data', (['inputs'], {}), '(inputs)\n', (1007, 1015), False, 'from syned.widget.widget_decorator import WidgetDecorator\n'), ((1136, 1148), 'orangewidget.settings.Setting', 'Setting', (['(4.0)'], {... |
from core.utils import set_logger, signal_term_handler
from core.database import DatabaseHandler
from core.cep import RegexsHandler, create_rules_handler, ConfigHandler, PayloadConsumer, create_rule
from core.mqtt_client import create_mqtt_client
from threading import Thread
import signal
import json
import logging
fro... | [
"core.cep.PayloadConsumer",
"json.load",
"core.cep.create_rule",
"core.cep.ConfigHandler",
"flask.Flask",
"core.cep.create_rules_handler",
"time.sleep",
"core.utils.set_logger",
"logging.info",
"apis.api.init_app",
"core.cep.RegexsHandler",
"signal.signal",
"core.database.DatabaseHandler",
... | [((397, 435), 'core.utils.set_logger', 'set_logger', (['"""light-cep"""', 'logging.DEBUG'], {}), "('light-cep', logging.DEBUG)\n", (407, 435), False, 'from core.utils import set_logger, signal_term_handler\n'), ((443, 458), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (448, 458), False, 'from flask impor... |
import keras
import matplotlib.pyplot as plt
from keras.models import Sequential, load_model
from keras.layers.core import Dense, Dropout, Activation
import numpy as np
from skimage.transform import resize
def draw(image):
fig = plt.figure(figsize=(4, 4))
ax = fig.add_subplot(111)
ax.set_aspect('equal')
... | [
"keras.layers.core.Dense",
"numpy.zeros",
"matplotlib.pyplot.figure",
"skimage.transform.resize",
"keras.layers.core.Dropout",
"keras.models.Sequential",
"matplotlib.pyplot.savefig"
] | [((234, 260), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(4, 4)'}), '(figsize=(4, 4))\n', (244, 260), True, 'import matplotlib.pyplot as plt\n'), ((597, 619), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""fig.png"""'], {}), "('fig.png')\n", (608, 619), True, 'import matplotlib.pyplot as plt\n'), ((... |
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib.ticker import MaxNLocator
from typing import Union, List
import numpy as np
from ..storage import History
from .util import to_lists_or_default
def plot_epsilons(
histories: Union[List, History],
labels: Union[List, str] = None,... | [
"numpy.log10",
"matplotlib.ticker.MaxNLocator",
"matplotlib.pyplot.subplots",
"numpy.log"
] | [((1646, 1660), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1658, 1660), True, 'import matplotlib.pyplot as plt\n'), ((2307, 2332), 'matplotlib.ticker.MaxNLocator', 'MaxNLocator', ([], {'integer': '(True)'}), '(integer=True)\n', (2318, 2332), False, 'from matplotlib.ticker import MaxNLocator\n'), (... |
#!/usr/bin/env python3
import socket
import numpy as np
import cv2
import os
import time
import struct
class Camera(object):
def __init__(self):
# Data options (change me)
self.im_height = 720 # 848x480, 1280x720
self.im_width = 1280
# self.resize_height = 720
# self.res... | [
"socket.socket",
"numpy.isinf",
"numpy.fromstring",
"numpy.isnan"
] | [((537, 586), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (550, 586), False, 'import socket\n'), ((1900, 1987), 'numpy.fromstring', 'np.fromstring', (['data[9 * 4 + 9 * 4 + 16 * 4:9 * 4 + 9 * 4 + 16 * 4 + 4]', 'np.float32'], {}), '(data[9 *... |
# SPDX-License-Identifier: BSD-3-Clause
"""Test Database and VersionedDatabase functionality.
Every test case checks both the in-memory database (same db object on which
operations were performed) and the on-disk database (call to createDB()
after operations were performed).
"""
from pytest import fixture, mark, rai... | [
"random.Random",
"softfab.xmlgen.xml.record",
"time.time",
"pytest.raises",
"pytest.mark.parametrize"
] | [((3636, 3710), 'pytest.mark.parametrize', 'mark.parametrize', (['"""createDB"""', '[Database, VersionedDatabase]'], {'indirect': '(True)'}), "('createDB', [Database, VersionedDatabase], indirect=True)\n", (3652, 3710), False, 'from pytest import fixture, mark, raises\n'), ((3883, 3957), 'pytest.mark.parametrize', 'mar... |
import ctapipe
import traitlets
from ctapipe.io import EventSourceFactory
from ctapipe.io import event_source
from ctapipe.calib import CameraCalibrator
from enum import Enum
from ctapipe.visualization import CameraDisplay
import time
import copy
import pickle
from matplotlib import pyplot as plt
import PreprocessingF... | [
"ctapipe.calib.CameraCalibrator",
"copy.deepcopy",
"ctapipe.io.EventSourceFactory.produce",
"traitlets.config.Config",
"pathlib.Path",
"pickle.load"
] | [((593, 607), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (604, 607), False, 'import pickle\n'), ((1563, 1588), 'traitlets.config.Config', 'traitlets.config.Config', ([], {}), '()\n', (1586, 1588), False, 'import traitlets\n'), ((1615, 1729), 'ctapipe.calib.CameraCalibrator', 'CameraCalibrator', ([], {'r1_produ... |
from typing import Dict, Optional, TextIO
from aoc2019.intcode import Computer, read_program
def run_robot(data: TextIO, painted: Optional[Dict[complex, int]] = None) -> Dict[complex, int]:
if painted is None:
painted = {}
computer = Computer(read_program(data))
pos = 0j
direction = 1j
... | [
"aoc2019.intcode.read_program"
] | [((263, 281), 'aoc2019.intcode.read_program', 'read_program', (['data'], {}), '(data)\n', (275, 281), False, 'from aoc2019.intcode import Computer, read_program\n')] |
#OKOKOKOK
########### Python 3.2 #############
import http.client, urllib.request, urllib.parse, urllib.error, base64, sys
import json
import numpy
import cv2
headers = {
# Request headers. Replace the placeholder key below with your subscription key.
'Content-Type': 'application/json',
'Ocp-Apim-Subscrip... | [
"cv2.putText",
"json.loads",
"cv2.waitKey",
"cv2.imwrite",
"cv2.destroyAllWindows",
"cv2.imdecode",
"json.dumps",
"cv2.rectangle",
"cv2.imshow"
] | [((3016, 3037), 'cv2.imdecode', 'cv2.imdecode', (['arr', '(-1)'], {}), '(arr, -1)\n', (3028, 3037), False, 'import cv2\n'), ((5567, 5599), 'cv2.imshow', 'cv2.imshow', (['"""Faces found"""', 'image'], {}), "('Faces found', image)\n", (5577, 5599), False, 'import cv2\n'), ((5599, 5639), 'cv2.imwrite', 'cv2.imwrite', (['"... |
import boto3
import json
import os
import urllib3
from botocore.exceptions import ClientError
API_KEY = os.environ['CRYPTOCOMPARE_API_KEY']
FROM_EMAIL = os.environ['FROM_EMAIL']
TO_EMAIL = os.environ['TO_EMAIL']
def send_email(client, message):
SUBJECT = 'Crypto Price Alert'
response = None
try:
... | [
"urllib3.PoolManager",
"boto3.client"
] | [((1047, 1068), 'urllib3.PoolManager', 'urllib3.PoolManager', ([], {}), '()\n', (1066, 1068), False, 'import urllib3\n'), ((1364, 1409), 'boto3.client', 'boto3.client', (['"""ses"""'], {'region_name': '"""ap-south-1"""'}), "('ses', region_name='ap-south-1')\n", (1376, 1409), False, 'import boto3\n')] |
"""Tests for the mllaunchpad.logutil module"""
# Stdlib imports
from unittest import mock
# Project imports
import mllaunchpad.logutil as lu
def test_init_logging():
_ = lu.init_logging()
# pytest itself interferes with log level, need to find workaround
# import logging
# logger = logging.getLogge... | [
"unittest.mock.patch",
"mllaunchpad.logutil.init_logging",
"unittest.mock.mock_open"
] | [((178, 195), 'mllaunchpad.logutil.init_logging', 'lu.init_logging', ([], {}), '()\n', (193, 195), True, 'import mllaunchpad.logutil as lu\n'), ((417, 446), 'mllaunchpad.logutil.init_logging', 'lu.init_logging', ([], {'verbose': '(True)'}), '(verbose=True)\n', (432, 446), True, 'import mllaunchpad.logutil as lu\n'), ((... |
import json
from fixtures import blue_service_one, blue_service_two, red_service_one, \
rediscloud_service
import unittest
from cf_app_utils.service_locator import ServiceLocator
class TestServiceLocator(unittest.TestCase):
def setUp(self):
with open("fixtures/vcap_services_example.json") as json_fil... | [
"fixtures.blue_service_one",
"fixtures.rediscloud_service",
"json.loads",
"fixtures.red_service_one",
"cf_app_utils.service_locator.ServiceLocator",
"fixtures.blue_service_two"
] | [((393, 420), 'json.loads', 'json.loads', (['services_string'], {}), '(services_string)\n', (403, 420), False, 'import json\n'), ((448, 481), 'cf_app_utils.service_locator.ServiceLocator', 'ServiceLocator', ([], {'services': 'services'}), '(services=services)\n', (462, 481), False, 'from cf_app_utils.service_locator im... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import random
import string
import txnats
from twisted.logger import globalLogPublisher
from simple_log_observer import simpleObserver
from twisted.logger import Logger
log = Logger()
from twisted.internet import reactor
from twisted.internet import defe... | [
"argparse.ArgumentParser",
"twisted.logger.globalLogPublisher.addObserver",
"twisted.internet.endpoints.TCP4ClientEndpoint",
"twisted.internet.defer.DeferredSemaphore",
"sense_hat.SenseHat",
"random.choice",
"twisted.logger.Logger",
"twisted.internet.endpoints.connectProtocol",
"socket.gethostname",... | [((240, 248), 'twisted.logger.Logger', 'Logger', ([], {}), '()\n', (246, 248), False, 'from twisted.logger import Logger\n'), ((612, 637), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (635, 637), False, 'import argparse\n'), ((1083, 1109), 'twisted.internet.defer.DeferredSemaphore', 'defer.De... |
from collections import defaultdict
import json
def collect_autologistic_results(file_paths):
results = defaultdict(list)
for file_path in file_paths:
jdata = None
with open(file_path, 'r') as f:
jdata = json.load(f)
if jdata is None:
continue
feature = ... | [
"collections.defaultdict",
"json.load"
] | [((110, 127), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (121, 127), False, 'from collections import defaultdict\n'), ((242, 254), 'json.load', 'json.load', (['f'], {}), '(f)\n', (251, 254), False, 'import json\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) Copyright IBM Corp. 2010, 2020. All Rights Reserved.
"""Custom Jinja2 Filters"""
import sys
import json
import re
from jinja2 import Undefined
if sys.version_info.major < 3:
# Handle PY 2 specific imports
from base64 import encodestring as b64encode
else:
... | [
"base64.encodebytes",
"re.sub",
"json.dumps"
] | [((765, 817), 're.sub', 're.sub', ([], {'pattern': '"""[\\\\W^_]"""', 'repl': '""""""', 'string': 'titlecase'}), "(pattern='[\\\\W^_]', repl='', string=titlecase)\n", (771, 817), False, 'import re\n'), ((546, 561), 'json.dumps', 'json.dumps', (['val'], {}), '(val)\n', (556, 561), False, 'import json\n'), ((589, 601), '... |
from django.test import TestCase
from uriredirect.models import RewriteRule, UriRegister
class UriRegisterTestCase(TestCase):
fixtures = ['test_mediatype.json', 'test_uriregister.json', 'test_rewriterule.json']
def test_find_matching_rules_correct_match(self):
usginRegister = UriRegister.objects.g... | [
"uriredirect.models.RewriteRule.objects.get",
"uriredirect.models.UriRegister.objects.get"
] | [((299, 339), 'uriredirect.models.UriRegister.objects.get', 'UriRegister.objects.get', ([], {'label': '"""uri-gin"""'}), "(label='uri-gin')\n", (322, 339), False, 'from uriredirect.models import RewriteRule, UriRegister\n'), ((372, 418), 'uriredirect.models.RewriteRule.objects.get', 'RewriteRule.objects.get', ([], {'la... |
from pydantic import BaseModel
from pydantic.fields import Field
from pydantic.networks import EmailStr
from typing import List, Optional
class User(BaseModel):
userID: int=Field(...)
name: Optional[str]
email: Optional[EmailStr]
username: str=Field(...)
password: str=Field(...)
listOfProjects:... | [
"pydantic.fields.Field"
] | [((178, 188), 'pydantic.fields.Field', 'Field', (['...'], {}), '(...)\n', (183, 188), False, 'from pydantic.fields import Field\n'), ((261, 271), 'pydantic.fields.Field', 'Field', (['...'], {}), '(...)\n', (266, 271), False, 'from pydantic.fields import Field\n'), ((290, 300), 'pydantic.fields.Field', 'Field', (['...']... |
from collections import Counter
TEST = """NNCB
CH -> B
HH -> N
CB -> H
NH -> C
HB -> C
HC -> B
HN -> C
NN -> C
BH -> H
NC -> B
NB -> B
BN -> B
BB -> N
BC -> B
CC -> N
CN -> C"""
class Polymer:
def __init__(self, input: str) -> None:
template, ruleText = input.split("\n\n")
# When we count elemen... | [
"collections.Counter"
] | [((528, 537), 'collections.Counter', 'Counter', ([], {}), '()\n', (535, 537), False, 'from collections import Counter\n'), ((873, 882), 'collections.Counter', 'Counter', ([], {}), '()\n', (880, 882), False, 'from collections import Counter\n'), ((1219, 1228), 'collections.Counter', 'Counter', ([], {}), '()\n', (1226, 1... |
from fastai import tabular
import numpy as np
import pandas as pd
from pathlib import Path
from typing import Any, Dict
def preprocess(inp_df: pd.DataFrame) -> pd.DataFrame:
"""Preprocess the dataframe for modeling. The data, along with the data
from the gather_args() function will get passed to either the tra... | [
"pathlib.Path",
"fastai.tabular.add_datepart"
] | [((1072, 1127), 'fastai.tabular.add_datepart', 'tabular.add_datepart', (['df', '"""date"""'], {'drop': '(True)', 'time': '(False)'}), "(df, 'date', drop=True, time=False)\n", (1092, 1127), False, 'from fastai import tabular\n'), ((1535, 1555), 'pathlib.Path', 'Path', (['"""../../models"""'], {}), "('../../models')\n", ... |
# -*- coding: utf-8 -*-
"""
# Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
#
# This file was generated and any changes will be overwritten.
"""
from __future__ import unicode_literals
from ..request.directory_ob... | [
"asyncio.new_event_loop"
] | [((2330, 2354), 'asyncio.new_event_loop', 'asyncio.new_event_loop', ([], {}), '()\n', (2352, 2354), False, 'import asyncio\n')] |
"""
======================
DMP as Potential Field
======================
A Dynamical Movement Primitive defines a potential field that superimposes
several components: transformation system (goal-directed movement), forcing
term (learned shape), and coupling terms (e.g., obstacle avoidance).
"""
print(__doc__)
impor... | [
"matplotlib.pyplot.subplot",
"numpy.zeros_like",
"matplotlib.pyplot.show",
"movement_primitives.dmp.CouplingTermObstacleAvoidance2D",
"numpy.copy",
"matplotlib.pyplot.plot",
"movement_primitives.dmp_potential_field.plot_potential_field_2d",
"matplotlib.pyplot.setp",
"numpy.random.RandomState",
"mo... | [((527, 556), 'numpy.array', 'np.array', (['[0, 0]'], {'dtype': 'float'}), '([0, 0], dtype=float)\n', (535, 556), True, 'import numpy as np\n'), ((566, 595), 'numpy.array', 'np.array', (['[1, 1]'], {'dtype': 'float'}), '([1, 1], dtype=float)\n', (574, 595), True, 'import numpy as np\n'), ((607, 628), 'numpy.array', 'np... |
import bs4
import csv
import piexif
import math
import pathlib
import glob
import pandas as pd
from datetime import datetime
from fractions import Fraction
from dateutil import tz
# sets UTC
JST = tz.gettz('Asia/Tokyo')
UTC = tz.gettz("UTC")
# sets type alias
NumSexagesimal = tuple[int, int, float, str]
LocSexagesima... | [
"csv.writer",
"pandas.read_csv",
"math.modf",
"dateutil.tz.gettz",
"piexif.load",
"pathlib.Path",
"pandas.to_datetime",
"datetime.datetime.strptime",
"bs4.BeautifulSoup",
"piexif.dump"
] | [((198, 220), 'dateutil.tz.gettz', 'tz.gettz', (['"""Asia/Tokyo"""'], {}), "('Asia/Tokyo')\n", (206, 220), False, 'from dateutil import tz\n'), ((227, 242), 'dateutil.tz.gettz', 'tz.gettz', (['"""UTC"""'], {}), "('UTC')\n", (235, 242), False, 'from dateutil import tz\n'), ((507, 527), 'piexif.load', 'piexif.load', (['i... |
import io
import re
from setuptools import setup
with io.open("README.md", "rt", encoding="utf8") as f:
readme = f.read()
with io.open("starter/__init__.py", "rt", encoding="utf8") as f:
version = re.search(r'__version__ = "(.*?)"', f.read()).group(1)
setup(
name="starter",
version=version,
url=... | [
"setuptools.setup",
"io.open"
] | [((264, 1415), 'setuptools.setup', 'setup', ([], {'name': '"""starter"""', 'version': 'version', 'url': '"""https://github.com/senntyou/python-starter"""', 'project_urls': "{'Documentation': 'https://github.com/senntyou/python-starter', 'Code':\n 'https://github.com/senntyou/python-starter', 'Issue tracker':\n 'h... |
# Copyright (c) 2021, <NAME>.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | [
"cugraph.louvain",
"cugraph.dask.get_chunksize",
"cugraph.Graph",
"cugraph.sssp",
"cugraph.pagerank",
"cugraph.weakly_connected_components",
"numpy.random.default_rng",
"cugraph.katz_centrality",
"cugraph.generators.rmat",
"cugraph.bfs",
"cugraph.DiGraph"
] | [((1534, 1677), 'cugraph.generators.rmat', 'rmat', (['scale', '(2 ** scale * edgefactor)', '(0.1)', '(0.2)', '(0.3)', '(seed or 42)'], {'clip_and_flip': '(False)', 'scramble_vertex_ids': '(True)', 'create_using': 'None', 'mg': '(False)'}), '(scale, 2 ** scale * edgefactor, 0.1, 0.2, 0.3, seed or 42,\n clip_and_flip=... |
import unittest
from ds2.tree import Tree
class TestTree(unittest.TestCase):
def testinit(self):
Tree(['root'])
Tree([1, [2, [3], [4]], [5, [6], [7], [8]]])
def teststr(self):
self.assertEqual(str(Tree([1, [2], [3]])), "1\n 2\n 3")
self.assertEqual(str(Tree([1, [2, [3]]])), "... | [
"unittest.main",
"ds2.tree.Tree"
] | [((2374, 2389), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2387, 2389), False, 'import unittest\n'), ((110, 124), 'ds2.tree.Tree', 'Tree', (["['root']"], {}), "(['root'])\n", (114, 124), False, 'from ds2.tree import Tree\n'), ((133, 177), 'ds2.tree.Tree', 'Tree', (['[1, [2, [3], [4]], [5, [6], [7], [8]]]'], {... |
import os
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfparser import PDFParser
from spacy.tokens import Doc, Span
def _filter_doc_by_page(doc: Doc, page_number: str) -> Span:
"""Filter the doc by page number.
Args:
doc: The doc to filter.
... | [
"pdfminer.pdfpage.PDFPage.create_pages",
"pdfminer.pdfdocument.PDFDocument",
"pdfminer.pdfparser.PDFParser",
"os.path.normpath"
] | [((1389, 1407), 'pdfminer.pdfparser.PDFParser', 'PDFParser', (['in_file'], {}), '(in_file)\n', (1398, 1407), False, 'from pdfminer.pdfparser import PDFParser\n'), ((1422, 1441), 'pdfminer.pdfdocument.PDFDocument', 'PDFDocument', (['parser'], {}), '(parser)\n', (1433, 1441), False, 'from pdfminer.pdfdocument import PDFD... |
from django.contrib import admin
from django.core.urlresolvers import reverse
from django.utils.html import format_html
from django.utils.translation import ugettext_lazy as _
from parler.admin import TranslatableAdmin
from bluebottle.tasks.models import Skill
class SkillAdmin(TranslatableAdmin):
list_display = ... | [
"django.utils.translation.ugettext_lazy",
"django.contrib.admin.site.register",
"django.core.urlresolvers.reverse"
] | [((1543, 1581), 'django.contrib.admin.site.register', 'admin.site.register', (['Skill', 'SkillAdmin'], {}), '(Skill, SkillAdmin)\n', (1562, 1581), False, 'from django.contrib import admin\n'), ((1191, 1217), 'django.utils.translation.ugettext_lazy', '_', (['"""Tasks with this skill"""'], {}), "('Tasks with this skill')... |