code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
from rest_framework.renderers import JSONRenderer
from django.utils import simplejson
def prepare_for_emit(obj):
"""
Prepare the object for emit() by Tornadio2's (too simple) JSON renderer
- render to JSON using Django REST Framework 2's JSON renderer
- convert back to _simple_ Python object using Dja... | [
"django.utils.simplejson.loads",
"rest_framework.renderers.JSONRenderer"
] | [((396, 418), 'django.utils.simplejson.loads', 'simplejson.loads', (['json'], {}), '(json)\n', (412, 418), False, 'from django.utils import simplejson\n'), ((357, 371), 'rest_framework.renderers.JSONRenderer', 'JSONRenderer', ([], {}), '()\n', (369, 371), False, 'from rest_framework.renderers import JSONRenderer\n')] |
from pwn import *
import sys
import os
from pathlib import Path
from threading import Thread
from clients.GhidraCommandClient import GhidraCommandClient
class GhidraGdb:
"""The main class which encapsulates the whole GhidraGdb framework
"""
def __init__(self, process=None):
self.fifo = No... | [
"threading.Thread",
"clients.GhidraCommandClient.GhidraCommandClient",
"pathlib.Path",
"os.mkfifo"
] | [((613, 638), 'clients.GhidraCommandClient.GhidraCommandClient', 'GhidraCommandClient', (['self'], {}), '(self)\n', (632, 638), False, 'from clients.GhidraCommandClient import GhidraCommandClient\n'), ((416, 436), 'os.mkfifo', 'os.mkfifo', (['self.FIFO'], {}), '(self.FIFO)\n', (425, 436), False, 'import os\n'), ((3300,... |
from dataclasses import make_dataclass
from fractal.core.specifications.object_of_account_specification import (
ObjectOfAccountSpecification,
)
def test_object_of_account_specification():
spec = ObjectOfAccountSpecification("abc", "def")
DC = make_dataclass("DC", [("id", str), ("account_id", str)])
... | [
"fractal.core.specifications.object_of_account_specification.ObjectOfAccountSpecification",
"dataclasses.make_dataclass"
] | [((207, 249), 'fractal.core.specifications.object_of_account_specification.ObjectOfAccountSpecification', 'ObjectOfAccountSpecification', (['"""abc"""', '"""def"""'], {}), "('abc', 'def')\n", (235, 249), False, 'from fractal.core.specifications.object_of_account_specification import ObjectOfAccountSpecification\n'), ((... |
import json
import imports.fileReader as reader
class dataBase:
def __init__(self, path, key):
self.file = reader.efile(path, key);
if(len(self.file.data) > 0):
self.json = json.loads(self.file.data)
else:
self.json = json.loads("{}")
self.json["key"] = k... | [
"imports.fileReader.efile",
"json.dumps",
"json.loads"
] | [((120, 143), 'imports.fileReader.efile', 'reader.efile', (['path', 'key'], {}), '(path, key)\n', (132, 143), True, 'import imports.fileReader as reader\n'), ((382, 403), 'json.dumps', 'json.dumps', (['self.json'], {}), '(self.json)\n', (392, 403), False, 'import json\n'), ((206, 232), 'json.loads', 'json.loads', (['se... |
"""
This is where all the general routes and controllers are defined.
"""
from flask import Blueprint
from flask import current_app as app
from flask import make_response
main_blueprint = Blueprint('main_blueprint', __name__)
@main_blueprint.route('/')
def index():
return make_response()
@main_blueprint.route... | [
"flask.make_response",
"flask.current_app.prom_init.up_gauge.set",
"flask.Blueprint"
] | [((190, 227), 'flask.Blueprint', 'Blueprint', (['"""main_blueprint"""', '__name__'], {}), "('main_blueprint', __name__)\n", (199, 227), False, 'from flask import Blueprint\n'), ((281, 296), 'flask.make_response', 'make_response', ([], {}), '()\n', (294, 296), False, 'from flask import make_response\n'), ((350, 379), 'f... |
from django.urls import path
from . import views
app_name = "trade"
urlpatterns = [
path('start/<str:receiver_username>/', views.start, name="start"),
path('<str:other_username>/', views.see_trade, name="see"),
path('change/<str:other_username>', views.change_trade, name="change"),
]
| [
"django.urls.path"
] | [((92, 157), 'django.urls.path', 'path', (['"""start/<str:receiver_username>/"""', 'views.start'], {'name': '"""start"""'}), "('start/<str:receiver_username>/', views.start, name='start')\n", (96, 157), False, 'from django.urls import path\n'), ((163, 221), 'django.urls.path', 'path', (['"""<str:other_username>/"""', '... |
#!/usr/bin/python3
# ******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a c... | [
"unittest.TextTestRunner",
"unittest.TestSuite",
"coverage.coverage",
"os.path.dirname",
"unittest.defaultTestLoader.discover",
"os.path.join",
"sys.exit"
] | [((873, 893), 'unittest.TestSuite', 'unittest.TestSuite', ([], {}), '()\n', (891, 893), False, 'import unittest\n'), ((999, 1030), 'os.path.join', 'os.path.join', (['BASE_PATH', '"""test"""'], {}), "(BASE_PATH, 'test')\n", (1011, 1030), False, 'import os\n'), ((1038, 1163), 'coverage.coverage', 'coverage.coverage', ([]... |
import numpy as np
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
import torch
from torch.autograd import Variable
from load_memmap import *
class AxonDataset(Dataset):
"""" Inherits pytorch Dataset class to load Axon Dataset """
def __init__(self, data_name='crops64... | [
"numpy.load",
"torch.autograd.Variable",
"numpy.zeros",
"numpy.expand_dims",
"numpy.nonzero",
"numpy.max",
"torch.Tensor",
"numpy.array",
"numpy.arange",
"torch.cuda.is_available",
"torch.max",
"torch.min",
"numpy.unique"
] | [((2945, 2972), 'torch.Tensor', 'torch.Tensor', (['sample_x_data'], {}), '(sample_x_data)\n', (2957, 2972), False, 'import torch\n'), ((2997, 3024), 'torch.Tensor', 'torch.Tensor', (['sample_y_data'], {}), '(sample_y_data)\n', (3009, 3024), False, 'import torch\n'), ((5674, 5701), 'torch.Tensor', 'torch.Tensor', (['sam... |
import os
from library.connecter.ansible.yaml import Yaml_Base
from library.utils.file import read_file
from library.utils.path import get_pathlist
class Read_File(Yaml_Base):
def router(self, this_path, this_basedir=None, yaml_tpye='main', preserve=True, together=False, name='', describe=''):
... | [
"os.path.basename",
"os.path.dirname",
"library.utils.file.read_file",
"library.utils.path.get_pathlist"
] | [((2954, 2979), 'os.path.dirname', 'os.path.dirname', (['filename'], {}), '(filename)\n', (2969, 2979), False, 'import os\n'), ((9110, 9171), 'library.utils.path.get_pathlist', 'get_pathlist', (['temp_dir'], {'get_death': '(0)', 'max_size': '(4 * 1024 * 1024)'}), '(temp_dir, get_death=0, max_size=4 * 1024 * 1024)\n', (... |
import json
from urllib import request
import requests
#for rest api
repository_url = 'http://10.3.100.22:8080'
restpath = '/rest'
xmlpath = '/xmlui'
def get_communities():
communities = request.urlopen(repository_url + restpath + '/communities')
communities_json = communities.read().decode('utf-8')
comm... | [
"requests.get",
"urllib.request.urlopen",
"json.dumps",
"json.loads"
] | [((193, 252), 'urllib.request.urlopen', 'request.urlopen', (["(repository_url + restpath + '/communities')"], {}), "(repository_url + restpath + '/communities')\n", (208, 252), False, 'from urllib import request\n'), ((335, 363), 'json.loads', 'json.loads', (['communities_json'], {}), '(communities_json)\n', (345, 363)... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for Truthcoin's consensus functions.
Verifies that the consensus algorithm works as expected.
Check test_answers.txt for expected results.
"""
from __future__ import division, unicode_literals, absolute_import
import os
import sys
import platform
import json
impo... | [
"platform.python_version",
"unittest.TextTestRunner",
"os.path.realpath",
"json.dumps",
"numpy.isnan",
"numpy.array",
"unittest.TestLoader",
"os.path.join",
"consensus.Factory"
] | [((360, 385), 'platform.python_version', 'platform.python_version', ([], {}), '()\n', (383, 385), False, 'import platform\n'), ((484, 510), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (500, 510), False, 'import os\n'), ((531, 560), 'os.path.join', 'os.path.join', (['HERE', 'os.pardir'], ... |
from rest_framework import status
from rest_framework.test import APISimpleTestCase
from rest_framework_jwt.settings import api_settings
from happ.models import User, Interest, LogEntry
from happ.factories import (
UserFactory,
InterestFactory,
CityFactory,
)
from happ.tests import *
class Tests(APISimpl... | [
"happ.factories.InterestFactory",
"happ.models.LogEntry.objects.count",
"happ.models.Interest.objects.delete",
"happ.models.Interest.objects.get",
"happ.factories.CityFactory",
"happ.factories.UserFactory",
"happ.models.Interest.objects.count"
] | [((768, 781), 'happ.factories.UserFactory', 'UserFactory', ([], {}), '()\n', (779, 781), False, 'from happ.factories import UserFactory, InterestFactory, CityFactory\n'), ((1519, 1551), 'happ.factories.UserFactory', 'UserFactory', ([], {'role': 'User.MODERATOR'}), '(role=User.MODERATOR)\n', (1530, 1551), False, 'from h... |
import sys
from PyQt5 import QtGui
import PyQt5.QtWidgets as qw
class Mensaje(qw.QWidget):
def __init__(self, parent=None):
qw.QWidget.__init__(self, parent)
self.setGeometry(700, 300, 640, 640)
self.setWindowTitle("Basico 03")
self.setWindowIcon(QtGui.QIcon("Recursos/Icon-Python_P... | [
"PyQt5.QtWidgets.QApplication",
"PyQt5.QtGui.QIcon",
"PyQt5.QtWidgets.QWidget.__init__",
"PyQt5.QtGui.QFont"
] | [((537, 562), 'PyQt5.QtWidgets.QApplication', 'qw.QApplication', (['sys.argv'], {}), '(sys.argv)\n', (552, 562), True, 'import PyQt5.QtWidgets as qw\n'), ((137, 170), 'PyQt5.QtWidgets.QWidget.__init__', 'qw.QWidget.__init__', (['self', 'parent'], {}), '(self, parent)\n', (156, 170), True, 'import PyQt5.QtWidgets as qw\... |
import os
import psutil
class InfoOS:
'''
This class retrieves and prints information on the current OS.
Public methods:
Attributes:
os: the current OS,
kernel: the current release,
arch: the current architecture,
threads: the number of available CPU t... | [
"psutil.cpu_freq",
"psutil.virtual_memory",
"os.uname",
"psutil.cpu_count"
] | [((775, 793), 'psutil.cpu_count', 'psutil.cpu_count', ([], {}), '()\n', (791, 793), False, 'import psutil\n'), ((649, 659), 'os.uname', 'os.uname', ([], {}), '()\n', (657, 659), False, 'import os\n'), ((691, 701), 'os.uname', 'os.uname', ([], {}), '()\n', (699, 701), False, 'import os\n'), ((733, 743), 'os.uname', 'os.... |
from fsspec.implementations.local import LocalFileSystem
from s3fs import S3FileSystem
def is_s3_path(path: str) -> bool:
if path.startswith("s3://"):
return True
return False
def bucket_name_from_path(path: str) -> str:
path_parts = path.replace("s3://", "").split("/")
return path_parts.pop... | [
"s3fs.S3FileSystem",
"fsspec.implementations.local.LocalFileSystem"
] | [((415, 449), 'fsspec.implementations.local.LocalFileSystem', 'LocalFileSystem', ([], {'auto_mkdir': '"""True"""'}), "(auto_mkdir='True')\n", (430, 449), False, 'from fsspec.implementations.local import LocalFileSystem\n'), ((389, 403), 's3fs.S3FileSystem', 'S3FileSystem', ([], {}), '()\n', (401, 403), False, 'from s3f... |
from django.db import models
from django.contrib.auth.models import User
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(User)
| [
"django.db.models.CharField",
"django.db.models.ForeignKey"
] | [((113, 145), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)'}), '(max_length=100)\n', (129, 145), False, 'from django.db import models\n'), ((159, 182), 'django.db.models.ForeignKey', 'models.ForeignKey', (['User'], {}), '(User)\n', (176, 182), False, 'from django.db import models\n')] |
from flask import Flask, redirect, url_for, render_template
#import ip_finder
app = Flask(__name__)
@app.route("/<name>")
def home(name):
return render_template("index.html", content=name)
# @app.route("/<name>")
# def user(name):
# return f"Hello {name}!"
# # Working on it!
# @app.route("/<ipF>")
# def ip(i... | [
"flask.Flask",
"flask.render_template"
] | [((84, 99), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (89, 99), False, 'from flask import Flask, redirect, url_for, render_template\n'), ((150, 193), 'flask.render_template', 'render_template', (['"""index.html"""'], {'content': 'name'}), "('index.html', content=name)\n", (165, 193), False, 'from flas... |
from django.conf.urls.defaults import patterns, include, url
from django.contrib.auth import views as authviews
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# favicon
(r'^favicon\.ico$', 'django.views.generic.simp... | [
"django.contrib.admin.autodiscover",
"django.conf.urls.defaults.include"
] | [((203, 223), 'django.contrib.admin.autodiscover', 'admin.autodiscover', ([], {}), '()\n', (221, 223), False, 'from django.contrib import admin\n'), ((612, 634), 'django.conf.urls.defaults.include', 'include', (['"""projdb.urls"""'], {}), "('projdb.urls')\n", (619, 634), False, 'from django.conf.urls.defaults import pa... |
import subprocess as sp
import platform
import os.path
import logging
def install_prerequisites(os_platform):
"""
Installs prerequisites for the landscape CLI tool
Returns: None
"""
install_gsed(os_platform)
install_minikube(os_platform)
install_lastpass(os_platform)
install_vault(os_p... | [
"logging.info",
"subprocess.call"
] | [((690, 724), 'logging.info', 'logging.info', (['"""installing gnu-sed"""'], {}), "('installing gnu-sed')\n", (702, 724), False, 'import logging\n'), ((733, 779), 'subprocess.call', 'sp.call', (['install_cmds[os_platform]'], {'shell': '(True)'}), '(install_cmds[os_platform], shell=True)\n', (740, 779), True, 'import su... |
# -*- encoding: utf-8 -*-
import os
import subprocess
import settings
import git
import requests
def clone_challenge(challenge_repository, challenge_name):
try:
git.Git().clone(challenge_repository)
if not os.path.exists(challenge_name):
return "Can't download this repository", True
... | [
"git.Git",
"subprocess.Popen",
"subprocess.check_output",
"os.path.exists",
"os.environ.get",
"requests.post"
] | [((1283, 1327), 'requests.post', 'requests.post', (['settings.API_URL', 'status_json'], {}), '(settings.API_URL, status_json)\n', (1296, 1327), False, 'import requests\n'), ((1394, 1416), 'os.environ.get', 'os.environ.get', (['"""REPO"""'], {}), "('REPO')\n", (1408, 1416), False, 'import os\n'), ((230, 260), 'os.path.e... |
# Copyright (c) 2015 Ansible, Inc.
# All Rights Reserved
import os
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from django.conf import settings
from awx.main.models import Instance
class Command(BaseCommand):
"""
Internal tower command.
Register t... | [
"os.environ.get",
"awx.main.models.Instance.objects.register",
"django.core.management.base.CommandError",
"awx.main.management.commands.register_queue.RegisterQueue"
] | [((1928, 2004), 'awx.main.models.Instance.objects.register', 'Instance.objects.register', ([], {'hostname': 'hostname', 'node_type': 'node_type', 'uuid': 'uuid'}), '(hostname=hostname, node_type=node_type, uuid=uuid)\n', (1953, 2004), False, 'from awx.main.models import Instance\n'), ((1225, 1326), 'django.core.managem... |
# reduced from https://github.com/blainegarrett/urequests2
import binascii
always_safe = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
'abcdefghijklmnopqrstuvwxyz'
'0123456789' '_.-')
def quote(s):
res = []
for c in s:
if c in always_safe:
res.append(c)
continue
... | [
"binascii.b2a_base64"
] | [((1033, 1055), 'binascii.b2a_base64', 'binascii.b2a_base64', (['s'], {}), '(s)\n', (1052, 1055), False, 'import binascii\n')] |
from django.http import HttpResponse
from fluent_pages.extensions import PageTypePlugin, page_type_pool
from .models import TextFile
@page_type_pool.register
class TextFilePlugin(PageTypePlugin):
model = TextFile
is_file = True
def get_response(self, request, textfile, **kwargs):
content_type =... | [
"django.http.HttpResponse"
] | [((479, 544), 'django.http.HttpResponse', 'HttpResponse', ([], {'content': 'textfile.content', 'content_type': 'content_type'}), '(content=textfile.content, content_type=content_type)\n', (491, 544), False, 'from django.http import HttpResponse\n')] |
"""
Comparing different kernels using cv2.filter2D()
"""
# Import required packages:
import cv2
import numpy as np
import matplotlib.pyplot as plt
def show_with_matplotlib(color_img, title, pos):
"""Shows an image using matplotlib capabilities"""
# Convert BGR image to RGB
img_RGB = color_img[:, :, ::-1... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show",
"cv2.filter2D",
"matplotlib.pyplot.suptitle",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.axis",
"cv2.imread",
"matplotlib.pyplot.figure",
"numpy.array"
] | [((475, 502), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 6)'}), '(figsize=(12, 6))\n', (485, 502), True, 'import matplotlib.pyplot as plt\n'), ((503, 604), 'matplotlib.pyplot.suptitle', 'plt.suptitle', (['"""Comparing different kernels using cv2.filter2D()"""'], {'fontsize': '(14)', 'fontweight': ... |
from flask import Flask,render_template
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
@app.route("/welcome")
def welcome():
return render_template("welcome.html")
if __name__ == '__main__':
app.run(host='0.0.0.0',debug=True)
| [
"flask.Flask",
"flask.render_template"
] | [((47, 62), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (52, 62), False, 'from flask import Flask, render_template\n'), ((168, 199), 'flask.render_template', 'render_template', (['"""welcome.html"""'], {}), "('welcome.html')\n", (183, 199), False, 'from flask import Flask, render_template\n')] |
from collections import defaultdict
from .metrics import calculate_metrics_list
class Graph:
"""
The code for this class is based on geeksforgeeks.com
"""
def __init__(self, vertices):
self.graph = defaultdict(list)
self.V = vertices
def addEdge(self, u, v):
self.graph[u... | [
"collections.defaultdict"
] | [((226, 243), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (237, 243), False, 'from collections import defaultdict\n')] |
import sys
from sqlalchemy import create_engine
import pg_copy
if __name__ == "__main__":
engine = create_engine(sys.argv[1])
target_table = 'example_table'
objs = [
{
'id': i,
'description': f'record description {i}'
} for i in range(100_000)
]
pg_copy.i... | [
"sqlalchemy.create_engine",
"pg_copy.insert_with_copy"
] | [((106, 132), 'sqlalchemy.create_engine', 'create_engine', (['sys.argv[1]'], {}), '(sys.argv[1])\n', (119, 132), False, 'from sqlalchemy import create_engine\n'), ((311, 363), 'pg_copy.insert_with_copy', 'pg_copy.insert_with_copy', (['engine', 'objs', 'target_table'], {}), '(engine, objs, target_table)\n', (335, 363), ... |
import os
import re
import sys
import argparse
import json
import numpy as np
from glob import glob
import cv2
from utils.plot_utils import RandomColor
def parse_args():
parser = argparse.ArgumentParser(
description='Monocular 3D Tracking Visualizer',
formatter_class=argpa... | [
"numpy.random.seed",
"cv2.VideoWriter_fourcc",
"argparse.ArgumentParser",
"os.makedirs",
"os.path.isdir",
"utils.plot_utils.RandomColor",
"cv2.imread",
"os.path.isfile",
"os.path.splitext",
"cv2.VideoWriter",
"os.listdir",
"re.compile"
] | [((2253, 2284), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["*'mp4v'"], {}), "(*'mp4v')\n", (2275, 2284), False, 'import cv2\n'), ((2295, 2314), 'numpy.random.seed', 'np.random.seed', (['(777)'], {}), '(777)\n', (2309, 2314), True, 'import numpy as np\n'), ((2326, 2341), 'utils.plot_utils.RandomColor', 'Rando... |
# --------------
#Importing header files
import pandas as pd
from sklearn.model_selection import train_test_split as tts
# Code starts here
data= pd.read_csv(path)
X= data.drop(['customer.id','paid.back.loan'],1)
y=data['paid.back.loan']
X_train, X_test, y_train, y_test = tts(X,y,random_state=0,test_size=0.3)
# C... | [
"sklearn.model_selection.GridSearchCV",
"matplotlib.pyplot.show",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"sklearn.metrics.accuracy_score",
"matplotlib.pyplot.axis",
"sklearn.tree.DecisionTreeClassifier",
"sklearn.tree.export_graphviz",
"sklearn.preprocessing.LabelEncoder",
... | [((150, 167), 'pandas.read_csv', 'pd.read_csv', (['path'], {}), '(path)\n', (161, 167), True, 'import pandas as pd\n'), ((279, 319), 'sklearn.model_selection.train_test_split', 'tts', (['X', 'y'], {'random_state': '(0)', 'test_size': '(0.3)'}), '(X, y, random_state=0, test_size=0.3)\n', (282, 319), True, 'from sklearn.... |
# Copyright (c) 2012-2014 OpenStack Foundation.
#
# 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 agre... | [
"pkg_resources.Requirement.parse"
] | [((983, 1024), 'pkg_resources.Requirement.parse', 'pkg_resources.Requirement.parse', (['"""swift3"""'], {}), "('swift3')\n", (1014, 1024), False, 'import pkg_resources\n')] |
# Copyright 2021 Uber Technologies, Inc. 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 applica... | [
"horovod.runner.common.util.secret.make_secret_key",
"horovod.runner.common.service.task_service.BasicTaskService",
"re.sub",
"io.StringIO"
] | [((1583, 1607), 'horovod.runner.common.util.secret.make_secret_key', 'secret.make_secret_key', ([], {}), '()\n', (1605, 1607), False, 'from horovod.runner.common.util import secret\n'), ((1626, 1688), 'horovod.runner.common.service.task_service.BasicTaskService', 'BasicTaskService', (['"""test service"""', '(0)', 'key'... |
from collections import namedtuple
from anchore_engine.services.policy_engine.engine.policy.params import InputValidator
from anchore_engine.services.policy_engine.engine.policy.gate import Gate, GateMeta, BaseTrigger
class AttributeListValidator(InputValidator):
def __init__(self, attrs):
self.attrs = at... | [
"collections.namedtuple"
] | [((681, 747), 'collections.namedtuple', 'namedtuple', (['"""CheckOperation"""', "['requires_rvalue', 'eval_function']"], {}), "('CheckOperation', ['requires_rvalue', 'eval_function'])\n", (691, 747), False, 'from collections import namedtuple\n')] |
# -*- coding: utf-8 -*-
# @Time : 19-11-19 22:25
# @Author : <NAME>
# @Reference : None
# @File : cut_twist_join.py
# @IDE : PyCharm Community Edition
"""
将身份证正反面从原始图片中切分出来。
需要的参数有:
1.图片所在路径。
输出结果为:
切分后的身份证正反面图片。
"""
import os
import cv2
import numpy ... | [
"cv2.getPerspectiveTransform",
"cv2.adaptiveThreshold",
"numpy.argsort",
"cv2.boxPoints",
"cv2.minAreaRect",
"cv2.erode",
"os.path.join",
"cv2.contourArea",
"cv2.subtract",
"cv2.dilate",
"cv2.cvtColor",
"os.path.exists",
"cv2.convertScaleAbs",
"cv2.morphologyEx",
"os.listdir",
"cv2.Sob... | [((1470, 1507), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (1482, 1507), False, 'import cv2\n'), ((2259, 2312), 'cv2.Sobel', 'cv2.Sobel', (['img_blurred'], {'ddepth': 'cv2.CV_32F', 'dx': '(1)', 'dy': '(0)'}), '(img_blurred, ddepth=cv2.CV_32F, dx=1, dy=0)\n', (226... |
import time
import concurrent
import asyncio
import bleak
async def main():
loop = asyncio.new_event_loop()
client = bleak.BleakClient('D8:A9:8B:7E:1E:D2')
is_connected = await client.connect()
print(is_connected)
response = await client.write_gatt_char('0000ffe1-0000-1000-8000-00805f9b34fb', b'MO... | [
"bleak.BleakClient",
"asyncio.new_event_loop"
] | [((88, 112), 'asyncio.new_event_loop', 'asyncio.new_event_loop', ([], {}), '()\n', (110, 112), False, 'import asyncio\n'), ((127, 165), 'bleak.BleakClient', 'bleak.BleakClient', (['"""D8:A9:8B:7E:1E:D2"""'], {}), "('D8:A9:8B:7E:1E:D2')\n", (144, 165), False, 'import bleak\n')] |
#!/usr/bin/env python3
import re
CCNUM = re.compile(r'(?!.*(\d)(?:\D?\1){3})[456]\d{3}(-?)(?:\d{4}\2){2}\d{4}')
for _ in range(int(input())):
print('Valid' if CCNUM.fullmatch(input().strip()) else 'Invalid')
| [
"re.compile"
] | [((43, 119), 're.compile', 're.compile', (['"""(?!.*(\\\\d)(?:\\\\D?\\\\1){3})[456]\\\\d{3}(-?)(?:\\\\d{4}\\\\2){2}\\\\d{4}"""'], {}), "('(?!.*(\\\\d)(?:\\\\D?\\\\1){3})[456]\\\\d{3}(-?)(?:\\\\d{4}\\\\2){2}\\\\d{4}')\n", (53, 119), False, 'import re\n')] |
from m5stack import *
from m5ui import *
import espnow
import wifiCfg
import hat
joy_pos = None
paired = False
addr = None
data = None
setScreenColor(0x000000)
axp.setLDO2Volt(2.8)
hat_joyc0 = hat.get(hat.JOYC)
label0 = M5TextBox(22, 48, "Text", lcd.FONT_Default, 0xFFFFFF, rotate=0)
label1 = M5TextBox(22, 62, "Text"... | [
"espnow.init",
"wifiCfg.wlan_sta.active",
"espnow.recv_data",
"hat.get",
"espnow.recv_cb",
"wifiCfg.wlan_ap.active"
] | [((195, 212), 'hat.get', 'hat.get', (['hat.JOYC'], {}), '(hat.JOYC)\n', (202, 212), False, 'import hat\n'), ((710, 738), 'wifiCfg.wlan_ap.active', 'wifiCfg.wlan_ap.active', (['(True)'], {}), '(True)\n', (732, 738), False, 'import wifiCfg\n'), ((741, 770), 'wifiCfg.wlan_sta.active', 'wifiCfg.wlan_sta.active', (['(True)'... |
# -*- coding:utf-8 -*-
# --------------------------------------------------------
# Copyright (C), 2016-2021, lizhe, All rights reserved
# --------------------------------------------------------
# @Name: gui.py.py
# @Author: lizhe
# @Created: 2021/12/15 - 21:24
# --------------------------------... | [
"copy.deepcopy",
"tkinter.ttk.Separator",
"automotive.core.can.can_service.CANService",
"automotive.logger.logger.logger.info",
"automotive.logger.logger.logger.debug",
"tkinter.Entry",
"tkinter.messagebox.showerror",
"tkinter.messagebox.showinfo",
"time.sleep",
"tkinter.ttk.Combobox",
"tkinter.... | [((1809, 1864), 'automotive.logger.logger.logger.debug', 'logger.debug', (['f"""check_buttons = {self.__check_buttons}"""'], {}), "(f'check_buttons = {self.__check_buttons}')\n", (1821, 1864), False, 'from automotive.logger.logger import logger\n'), ((1989, 2046), 'automotive.logger.logger.logger.debug', 'logger.debug'... |
# coding=utf-8
#
# pylint: disable = wildcard-import, unused-wildcard-import
# pylint: disable = missing-docstring, invalid-name
# pylint: disable = unused-argument, no-member, attribute-defined-outside-init
# pylint: disable = too-many-lines, too-many-branches, too-many-statements
"""
Copyright (c) 2020, <NAME>. Al... | [
"zipfile.is_zipfile"
] | [((1086, 1103), 'zipfile.is_zipfile', 'iszip', (['zipAppPath'], {}), '(zipAppPath)\n', (1091, 1103), True, 'from zipfile import is_zipfile as iszip\n')] |
# -*- coding: utf-8 -*-
import json
from django.http import Http404, HttpResponse
from django.views.decorators.csrf import csrf_protect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout as lgout, authenticate, login as lgin
from django.shortcuts import render, redirect
fro... | [
"Forum.signals.positive_score_event.send",
"Forum.signals.downvote.send",
"Forum.signals.upvote.send",
"Forum.signals.thread_published.send",
"django.shortcuts.redirect",
"Forum.signals.negative_score_event.send",
"json.dumps",
"datetime.datetime.now",
"django.contrib.auth.logout",
"Forum.signals.... | [((1330, 1344), 'django.contrib.auth.logout', 'lgout', (['request'], {}), '(request)\n', (1335, 1344), True, 'from django.contrib.auth import logout as lgout, authenticate, login as lgin\n'), ((1201, 1234), 'django.shortcuts.render', 'render', (['request', 'template_ajax', 'c'], {}), '(request, template_ajax, c)\n', (1... |
#!/usr/bin/env python
# coding: utf-8
# # Desafio 4
#
# Neste desafio, vamos praticar um pouco sobre testes de hipóteses. Utilizaremos o _data set_ [2016 Olympics in Rio de Janeiro](https://www.kaggle.com/rio2016/olympic-games/), que contém dados sobre os atletas das Olimpíadas de 2016 no Rio de Janeiro.
#
# Esse _d... | [
"matplotlib.pyplot.show",
"numpy.log",
"numpy.random.seed",
"scipy.stats.shapiro",
"pandas.read_csv",
"scipy.stats.normaltest",
"scipy.stats.ttest_ind",
"IPython.core.pylabtools.figsize",
"seaborn.boxplot",
"seaborn.distplot",
"statsmodels.api.qqplot",
"scipy.stats.t.sf",
"scipy.stats.jarque... | [((944, 958), 'IPython.core.pylabtools.figsize', 'figsize', (['(12)', '(8)'], {}), '(12, 8)\n', (951, 958), False, 'from IPython.core.pylabtools import figsize\n'), ((960, 969), 'seaborn.set', 'sns.set', ([], {}), '()\n', (967, 969), True, 'import seaborn as sns\n'), ((994, 1021), 'pandas.read_csv', 'pd.read_csv', (['"... |
from __future__ import absolute_import
import itertools
import datetime
from django.utils import timezone
from django.test.client import Client
from django.template.defaultfilters import slugify
from bulbs.content.models import Content, Tag, FeatureType
from elastimorphic.tests.base import BaseIndexableTestCase
fro... | [
"bulbs.content.models.FeatureType.objects.create",
"bulbs.content.models.Tag.search_objects.query",
"tests.testcontent.models.TestContentObj.objects.count",
"django.utils.timezone.now",
"bulbs.content.models.Tag.search_objects.refresh",
"bulbs.content.models.Content.objects.count",
"datetime.timedelta",... | [((1078, 1136), 'bulbs.content.models.FeatureType.objects.create', 'FeatureType.objects.create', ([], {'name': '"""Obj one"""', 'slug': '"""obj-one"""'}), "(name='Obj one', slug='obj-one')\n", (1104, 1136), False, 'from bulbs.content.models import Content, Tag, FeatureType\n'), ((1154, 1212), 'bulbs.content.models.Feat... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 24 16:03:28 2018
@author: dimitricoukos
Test: in command line:
python RetrieveUniProt.py 'Unit Tests/sample_brenda_parameters.json'
"""
import sys
import cobra_services as CS
from multiprocessing import Pool
from urllib.error import HTTPError
f... | [
"cobra_services.kegggene_to_uniprotid",
"cobra_services.sequence_weight",
"cobra_services.kegggene_to_sequence",
"cobra_services.ecnumber_to_genes",
"DataTreatment.openJson",
"multiprocessing.Pool",
"DataTreatment.write"
] | [((5395, 5437), 'cobra_services.kegggene_to_sequence', 'CS.kegggene_to_sequence', (['organism', 'address'], {}), '(organism, address)\n', (5418, 5437), True, 'import cobra_services as CS\n'), ((5451, 5479), 'cobra_services.sequence_weight', 'CS.sequence_weight', (['sequence'], {}), '(sequence)\n', (5469, 5479), True, '... |
import argparse
import datetime
import json
import logging
import pickle
import time
import shutil
from kite.graph_data.data_feeder import EndpointDataFeeder
from kite.graph_data.session import RequestInit
from kite.graph_data.graph_feed import GraphFeedConfig
from kite.infer_expr.config import MetaInfo, Config
from... | [
"kite.graph_data.data_feeder.EndpointDataFeeder",
"pickle.dump",
"argparse.ArgumentParser",
"logging.basicConfig",
"kite.infer_call.request.Request",
"kite.infer_call.request.KwargRequest",
"kite.infer_call.request.ArgPlaceholderRequest",
"kite.infer_expr.config.Config",
"kite.graph_data.graph_feed.... | [((613, 708), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG', 'format': '"""%(asctime)s %(levelname)-8s %(message)s"""'}), "(level=logging.DEBUG, format=\n '%(asctime)s %(levelname)-8s %(message)s')\n", (632, 708), False, 'import logging\n'), ((960, 985), 'argparse.ArgumentParser', 'arg... |
from collections import OrderedDict
from django.utils.module_loading import import_string
from django.conf import settings
from django.urls.resolvers import URLResolver, URLPattern
import re
def check_url_exclude(url):
for regex in settings.AUTO_DISCOVER_EXCLUDE:
if re.match(regex, url):
retur... | [
"collections.OrderedDict",
"django.utils.module_loading.import_string",
"re.match"
] | [((1787, 1800), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (1798, 1800), False, 'from collections import OrderedDict\n'), ((1812, 1848), 'django.utils.module_loading.import_string', 'import_string', (['settings.ROOT_URLCONF'], {}), '(settings.ROOT_URLCONF)\n', (1825, 1848), False, 'from django.utils.mo... |
# This file is part of spot_motion_monitor.
#
# Developed for LSST System Integration, Test and Commissioning.
#
# See the LICENSE file at the top-level directory of this distribution
# for details of code ownership.
#
# Use of this source code is governed by a 3-clause BSD-style
# license that can be found in the LICE... | [
"spot_motion_monitor.views.camera_control_widget.CameraControlWidget"
] | [((741, 762), 'spot_motion_monitor.views.camera_control_widget.CameraControlWidget', 'CameraControlWidget', ([], {}), '()\n', (760, 762), False, 'from spot_motion_monitor.views.camera_control_widget import CameraControlWidget\n'), ((1829, 1850), 'spot_motion_monitor.views.camera_control_widget.CameraControlWidget', 'Ca... |
"""
Copyright (c) 2015 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
from __future__ import print_function
import os
try:
from collections import OrderedDict
except ImportError:
# Python 2.6
from o... | [
"dock.plugins.pre_inject_yum_repo.alter_yum_commands",
"dock.util.ImageName",
"dock.inner.DockerBuildWorkflow",
"dock.core.DockerTasker",
"dock.plugin.PreBuildPluginsRunner",
"ordereddict.OrderedDict"
] | [((922, 936), 'dock.core.DockerTasker', 'DockerTasker', ([], {}), '()\n', (934, 936), False, 'from dock.core import DockerTasker\n'), ((952, 1001), 'dock.inner.DockerBuildWorkflow', 'DockerBuildWorkflow', (['DOCKERFILE_GIT', '"""test-image"""'], {}), "(DOCKERFILE_GIT, 'test-image')\n", (971, 1001), False, 'from dock.in... |
# -*- coding: utf-8 -*-
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from .hrv_time import hrv_time
from .hrv_frequency import hrv_frequency
from .hrv_frequency import _hrv_frequency_show
from .hrv_nonlinear import hrv_nonlinear
from .hrv_nonlinear import _hrv_nonlinear_show
from .hrv_utils im... | [
"matplotlib.gridspec.GridSpec",
"matplotlib.pyplot.figure",
"pandas.concat"
] | [((2670, 2692), 'pandas.concat', 'pd.concat', (['out'], {'axis': '(1)'}), '(out, axis=1)\n', (2679, 2692), True, 'import pandas as pd\n'), ((2840, 2876), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'constrained_layout': '(False)'}), '(constrained_layout=False)\n', (2850, 2876), True, 'import matplotlib.pyplot as pl... |
import math
import tensorflow as tf
import unittest
from tensorstream.helpers.any_nan import any_nan
def in_tf(x):
with tf.Session() as sess:
return sess.run(x)
class AnyNanSpec(unittest.TestCase):
def test_any_nan_scalar(self):
x = any_nan(tf.constant(4.0))
self.assertEqual(in_tf(x), False)
y =... | [
"tensorflow.Session",
"tensorflow.constant"
] | [((124, 136), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (134, 136), True, 'import tensorflow as tf\n'), ((256, 272), 'tensorflow.constant', 'tf.constant', (['(4.0)'], {}), '(4.0)\n', (267, 272), True, 'import tensorflow as tf\n'), ((329, 350), 'tensorflow.constant', 'tf.constant', (['math.nan'], {}), '(math... |
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.core.urlresolvers import reverse
from django.contrib import messages
from django.views.generic import ListView, CreateView, DetailView, FormView
from django.forms import ValidationError
from .models import Candidate... | [
"texaslan.site_settings.models.SiteSettingService.is_voting_applications_open",
"texaslan.site_settings.models.SiteSettingService.is_voting_closed",
"django.core.urlresolvers.reverse",
"texaslan.site_settings.models.SiteSettingService.is_voting_currently",
"django.contrib.messages.add_message"
] | [((954, 991), 'texaslan.site_settings.models.SiteSettingService.is_voting_closed', 'SiteSettingService.is_voting_closed', ([], {}), '()\n', (989, 991), False, 'from texaslan.site_settings.models import SiteSettingService\n'), ((1090, 1130), 'texaslan.site_settings.models.SiteSettingService.is_voting_currently', 'SiteSe... |
from multiprocessing import Process
import os
import time
def run_proc(process_name):
print('running subprocess %s(%s)......' % (process_name, os.getpid()))
count = 100
for i in range(count):
print("*** {} ***".format(i))
time.sleep(1)
os.mkdir(str(count))
print('sub process end')
... | [
"multiprocessing.Process",
"os.getpid",
"time.sleep"
] | [((394, 434), 'multiprocessing.Process', 'Process', ([], {'target': 'run_proc', 'args': "('test',)"}), "(target=run_proc, args=('test',))\n", (401, 434), False, 'from multiprocessing import Process\n'), ((251, 264), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (261, 264), False, 'import time\n'), ((373, 384), 'o... |
from django.db import models
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _
__all__ = ['ModelWithDateRange', 'ModelWithDateTimeRange',]
class ModelWithDateRange(models.Model):
# Attributes
start_date = models.DateField()
end_date = models.DateField(... | [
"django.db.models.DateField",
"django.db.models.DateTimeField",
"django.utils.translation.ugettext"
] | [((269, 287), 'django.db.models.DateField', 'models.DateField', ([], {}), '()\n', (285, 287), False, 'from django.db import models\n'), ((303, 321), 'django.db.models.DateField', 'models.DateField', ([], {}), '()\n', (319, 321), False, 'from django.db import models\n'), ((720, 742), 'django.db.models.DateTimeField', 'm... |
from django.urls.conf import path, include
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(
r"transactions",
views.TransactionViewSet,
)
user_transaction_urls = [
path(
"transactions/",
views.UserTransactionListCreateView.as_view(),
... | [
"rest_framework.routers.DefaultRouter",
"django.urls.conf.include"
] | [((109, 132), 'rest_framework.routers.DefaultRouter', 'routers.DefaultRouter', ([], {}), '()\n', (130, 132), False, 'from rest_framework import routers\n'), ((552, 582), 'django.urls.conf.include', 'include', (['user_transaction_urls'], {}), '(user_transaction_urls)\n', (559, 582), False, 'from django.urls.conf import ... |
#!/usr/bin/env python3
# cardinal_pythonlib/openxml/pause_process_by_disk_space.py
"""
===============================================================================
Original code copyright (C) 2009-2021 <NAME> (<EMAIL>).
This file is part of cardinal_pythonlib.
Licensed under the Apache License, Versi... | [
"subprocess.Popen",
"subprocess.check_call",
"argparse.ArgumentParser",
"cardinal_pythonlib.sizeformatter.human2bytes",
"sys.getdefaultencoding",
"cardinal_pythonlib.sizeformatter.sizeof_fmt",
"time.sleep",
"shutil.disk_usage",
"cardinal_pythonlib.logs.main_only_quicksetup_rootlogger",
"sys.exit",... | [((1325, 1352), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1342, 1352), False, 'import logging\n'), ((1520, 1544), 'sys.getdefaultencoding', 'sys.getdefaultencoding', ([], {}), '()\n', (1542, 1544), False, 'import sys\n'), ((1553, 1613), 'subprocess.Popen', 'subprocess.Popen', (["['p... |
from turtle import forward
import torch
import torch.nn as nn
class Normalize(nn.Module):
def __init__(self, mean, std, *args, **kwargs):
super().__init__()
self.register_buffer('mean', torch.tensor(mean)[None, :, None, None])
self.register_buffer('std', torch.tensor(std)[None, :, None, No... | [
"torch.tensor"
] | [((208, 226), 'torch.tensor', 'torch.tensor', (['mean'], {}), '(mean)\n', (220, 226), False, 'import torch\n'), ((285, 302), 'torch.tensor', 'torch.tensor', (['std'], {}), '(std)\n', (297, 302), False, 'import torch\n')] |
#!/usr/bin/env python
# coding: utf-8
#########################################################################
#########################################################################
"""
File Name: level2hbase.py
Author: <NAME>
E-mail: <EMAIL>
Created on: Sat Jun 7 13:36:03 2014 CST
"""
DESCRIPTI... | [
"sys.stdout.write",
"thrift.transport.TSocket.TSocket",
"hbase.Hbase.Client",
"leveldb.LevelDB",
"sys.path.append",
"argparse.ArgumentParser",
"thrift.protocol.TBinaryProtocol.TBinaryProtocol",
"os.system",
"sys.stdout.flush",
"sys.stderr.write",
"sys.stderr.flush",
"sys.exit",
"thrift.trans... | [((652, 680), 'sys.stderr.write', 'sys.stderr.write', (["('%s' % msg)"], {}), "('%s' % msg)\n", (668, 680), False, 'import sys\n'), ((685, 703), 'sys.stderr.flush', 'sys.stderr.flush', ([], {}), '()\n', (701, 703), False, 'import sys\n'), ((770, 798), 'sys.stdout.write', 'sys.stdout.write', (["('%s' % msg)"], {}), "('%... |
import numpy as np
from tensorflow import keras
import pandas as pd
import os
class DcmDataGenerator(keras.utils.Sequence):
"""Generates data for Keras
Sequence based data generator. Suitable for building data generator for training and prediction.
"""
def __init__(self, images_path, dim=(15, 512, 51... | [
"numpy.moveaxis",
"numpy.load",
"numpy.random.seed",
"pandas.read_csv",
"numpy.empty",
"numpy.any",
"numpy.array",
"os.path.join",
"os.listdir"
] | [((519, 542), 'os.listdir', 'os.listdir', (['images_path'], {}), '(images_path)\n', (529, 542), False, 'import os\n'), ((1054, 1074), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (1068, 1074), True, 'import numpy as np\n'), ((1791, 1833), 'numpy.empty', 'np.empty', (['(1, *self.dim)'], {'dtype': '... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
License for BK-BASE 蓝鲸基础平台:
------------------------------------------... | [
"common.transaction.auto_meta_sync",
"datahub.databus.task.task_utils.check_task_auth",
"datahub.databus.migration.create_task",
"datahub.databus.migration.stop_task",
"datahub.databus.models.DatabusMigrateTask.objects.exclude",
"rest_framework.response.Response",
"datahub.databus.migration.get_task_sta... | [((7680, 7727), 'common.decorators.detail_route', 'detail_route', ([], {'methods': "['get']", 'url_path': '"""start"""'}), "(methods=['get'], url_path='start')\n", (7692, 7727), False, 'from common.decorators import detail_route, list_route\n'), ((8499, 8545), 'common.decorators.detail_route', 'detail_route', ([], {'me... |
from fastkml import kml
from .utils import haversine
class GraphFromKmlDoc:
def __init__(self, filename='pracas'):
self._filename = filename
def _get_document(self):
doc = open("pracas.kml", "r").read().encode('utf-8')
self._document = kml.KML()
self._document.from_... | [
"fastkml.kml.KML"
] | [((273, 282), 'fastkml.kml.KML', 'kml.KML', ([], {}), '()\n', (280, 282), False, 'from fastkml import kml\n')] |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from pyuploadcare.dj.models import ImageField
from taggit_autosuggest.managers import Tagga... | [
"pyuploadcare.dj.models.ImageField",
"django.db.models.CharField",
"django.utils.timezone.now",
"taggit_autosuggest.managers.TaggableManager",
"django.db.models.DateTimeField"
] | [((399, 431), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(255)'}), '(max_length=255)\n', (415, 431), False, 'from django.db import models\n'), ((444, 482), 'pyuploadcare.dj.models.ImageField', 'ImageField', ([], {'blank': '(True)', 'manual_crop': '""""""'}), "(blank=True, manual_crop='')\n",... |
from typing import Callable
import sys
import os
from copy import deepcopy
from io import StringIO
import click
from click.core import MultiCommand, _check_multicommand
from colorama import Style
from . import globals as globs
from . import _colors as colors
from .chars import IGNORE_LINE
from .pretty import Pretty... | [
"io.StringIO",
"copy.deepcopy",
"click.core._check_multicommand",
"click.echo",
"click.Context",
"click.clear",
"click.core.MultiCommand.invoke"
] | [((3549, 3600), 'click.core._check_multicommand', '_check_multicommand', (['self', 'name', 'cmd'], {'register': '(True)'}), '(self, name, cmd, register=True)\n', (3568, 3600), False, 'from click.core import MultiCommand, _check_multicommand\n'), ((4182, 4212), 'click.core.MultiCommand.invoke', 'MultiCommand.invoke', ([... |
from django.http import HttpRequest, HttpResponse
from main.util import render_template
TEMPLATE = "tasks/lesson03/task301.html"
def handler(request: HttpRequest) -> HttpResponse:
name = request.GET.get("name")
context = {
"input_name": name,
"greeting_name": name or "anonymous",
}
... | [
"main.util.render_template",
"django.http.HttpResponse"
] | [((331, 365), 'main.util.render_template', 'render_template', (['TEMPLATE', 'context'], {}), '(TEMPLATE, context)\n', (346, 365), False, 'from main.util import render_template\n'), ((382, 412), 'django.http.HttpResponse', 'HttpResponse', ([], {'content': 'document'}), '(content=document)\n', (394, 412), False, 'from dj... |
import unittest
from config import Config as cfg
import requests
class Camera(unittest.TestCase):
routeUrl = cfg.serverUrl + "gallery/camera"
camerasList = [1,2,3]
def test_IsAllCamerasAvailable(self):
for camera in self.camerasList:
r = requests.get(f"{self.routeUrl}/{camera}")
... | [
"unittest.main",
"requests.get"
] | [((398, 413), 'unittest.main', 'unittest.main', ([], {}), '()\n', (411, 413), False, 'import unittest\n'), ((274, 315), 'requests.get', 'requests.get', (['f"""{self.routeUrl}/{camera}"""'], {}), "(f'{self.routeUrl}/{camera}')\n", (286, 315), False, 'import requests\n')] |
from typing import Any, Dict, Optional, Union, List
from fastapi.encoders import jsonable_encoder
from sqlalchemy.orm import Session
from app.crud.base import CRUDBase
from app.models.debit import Debit
from app.schemas.debit import DebitCreate, DebitUpdate
class CRUDDebit(CRUDBase[Debit, DebitCreate, DebitUpdate])... | [
"fastapi.encoders.jsonable_encoder"
] | [((464, 488), 'fastapi.encoders.jsonable_encoder', 'jsonable_encoder', (['obj_in'], {}), '(obj_in)\n', (480, 488), False, 'from fastapi.encoders import jsonable_encoder\n')] |
import argparse
import json
import os
from scipy.sparse import csr_matrix
from tqdm import tqdm
import numpy as np
from multiprocessing import Pool, Manager
def token_dict_to_sparse_vector(token_dict, token2id):
matrix_row, matrix_col, matrix_data = [], [], []
tokens = token_dict.keys()
col = []
data... | [
"tqdm.tqdm",
"argparse.ArgumentParser",
"json.loads",
"multiprocessing.Manager",
"multiprocessing.Pool",
"os.path.join",
"os.listdir"
] | [((670, 695), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (693, 695), False, 'import argparse\n'), ((2427, 2436), 'multiprocessing.Manager', 'Manager', ([], {}), '()\n', (2434, 2436), False, 'from multiprocessing import Pool, Manager\n'), ((1344, 1367), 'os.listdir', 'os.listdir', (['args.co... |
from googlesearch import search
import requests
import re
import csv
data=[]
a=[]
student="Mam"
def swap(text,j):
temp1=text[j]
temp2=text[j+1]
temp3=text[j+2]
temp4=text[j+3]
text[j]=text[j+4]
text[j+1]=text[j+5]
text[j+2]=text[j+6]
text[j+3]=text[j+7]
text[j+4]=temp1
text[j+5]=... | [
"requests.get",
"re.findall",
"csv.writer",
"googlesearch.search"
] | [((3261, 3297), 'csv.writer', 'csv.writer', (['f'], {'quoting': 'csv.QUOTE_ALL'}), '(f, quoting=csv.QUOTE_ALL)\n', (3271, 3297), False, 'import csv\n'), ((3964, 3997), 'googlesearch.search', 'search', (['query'], {'tld': '"""com"""', 'stop': '(10)'}), "(query, tld='com', stop=10)\n", (3970, 3997), False, 'from googlese... |
"""
generate periodic boundary condition (PBC).
Two methods to detect and partition the surface-nodes:
1. graph-method: (recommended, can deal with arbitrary deformed shape):
use dictionary-data-structure to map facet-nodes to element-number,
where the surface-facet is shared ... | [
"numpy.array"
] | [((9765, 9790), 'numpy.array', 'np.array', (['obj.nodes[node]'], {}), '(obj.nodes[node])\n', (9773, 9790), True, 'import numpy as np\n'), ((11978, 12003), 'numpy.array', 'np.array', (['obj.nodes[node]'], {}), '(obj.nodes[node])\n', (11986, 12003), True, 'import numpy as np\n')] |
# Copyright 2019 Adobe
# All Rights Reserved.
#
# NOTICE: Adobe permits you to use, modify, and distribute this file in
# accordance with the terms of the Adobe license agreement accompanying
# it. If you have received this file from a source other than Adobe,
# then your use, modification, or distribution of it ... | [
"protector.query.query.OpenTSDBResponse",
"json.dumps"
] | [((6536, 6568), 'protector.query.query.OpenTSDBResponse', 'OpenTSDBResponse', (['self.response1'], {}), '(self.response1)\n', (6552, 6568), False, 'from protector.query.query import OpenTSDBQuery, OpenTSDBResponse\n'), ((6665, 6697), 'protector.query.query.OpenTSDBResponse', 'OpenTSDBResponse', (['self.response2'], {})... |
import morepath
from .app import App
def run():
print('Running app...')
morepath.autoscan()
App.commit()
morepath.run(App())
if __name__ == '__main__':
run()
| [
"morepath.autoscan"
] | [((81, 100), 'morepath.autoscan', 'morepath.autoscan', ([], {}), '()\n', (98, 100), False, 'import morepath\n')] |
#!/usr/bin/env python
#
# Copyright 2007 Google 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 o... | [
"google.appengine.runtime.apiproxy_errors.ApplicationError",
"google.appengine.api.datastore_errors.BadRequestError",
"google.appengine.api.datastore_types.FromReferenceProperty"
] | [((8759, 8808), 'google.appengine.api.datastore_errors.BadRequestError', 'BadRequestError', (['"""invalid Key for __kind__ table"""'], {}), "('invalid Key for __kind__ table')\n", (8774, 8808), False, 'from google.appengine.api.datastore_errors import BadRequestError\n'), ((10112, 10166), 'google.appengine.api.datastor... |
import json
import logging
from datetime import datetime
from typing import Any, Dict
from flask import current_app, g, jsonify, request
from flask_cors import cross_origin
from alerta.auth.decorators import permission
from alerta.exceptions import ApiError, RejectException
from alerta.models.alert import Alert
from... | [
"alerta.utils.api.process_alert",
"alerta.utils.api.add_remote_ip",
"json.loads",
"flask_cors.cross_origin",
"datetime.datetime.utcfromtimestamp",
"flask.current_app._get_current_object",
"flask.jsonify",
"alerta.utils.api.assign_customer",
"alerta.auth.decorators.permission",
"alerta.exceptions.A... | [((510, 537), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (527, 537), False, 'import logging\n'), ((2438, 2452), 'flask_cors.cross_origin', 'cross_origin', ([], {}), '()\n', (2450, 2452), False, 'from flask_cors import cross_origin\n'), ((2454, 2486), 'alerta.auth.decorators.permission... |
import pytest
from wemake_python_styleguide.logic.tree import functions
@pytest.mark.parametrize(('function_call', 'function_name'), [
# Simple builtin functions
('print("Hello world!")', 'print'),
('int("10")', 'int'),
('bool(1)', 'bool'),
('open("/tmp/file.txt", "r")', 'open'),
('str(10)', ... | [
"pytest.mark.parametrize",
"wemake_python_styleguide.logic.tree.functions.given_function_called"
] | [((76, 458), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (["('function_call', 'function_name')", '[(\'print("Hello world!")\', \'print\'), (\'int("10")\', \'int\'), (\'bool(1)\',\n \'bool\'), (\'open("/tmp/file.txt", "r")\', \'open\'), (\'str(10)\', \'str\'), (\n \'datetime.timedelta(days=1)\', \'dateti... |
from django.shortcuts import render
# Create your views here.
from django.shortcuts import render, HttpResponse
from utils.tools.tools import unique
from devops_backend.settings import TMP_DIR
from rest_framework import viewsets, filters, mixins, status
from rest_framework.permissions import IsAuthenticated
from rest... | [
"utils.tools.tools.unique",
"django.shortcuts.HttpResponse",
"os.path.isfile",
"rest_framework.response.Response",
"django.shortcuts.render",
"servers.models.Server.objects.filter",
"os.path.join"
] | [((1830, 1868), 'django.shortcuts.render', 'render', (['request', '"""index.html"""', 'content'], {}), "(request, 'index.html', content)\n", (1836, 1868), False, 'from django.shortcuts import render, HttpResponse\n'), ((2349, 2371), 'django.shortcuts.HttpResponse', 'HttpResponse', (['filename'], {}), '(filename)\n', (2... |
from collections import OrderedDict as OD
from lxml import etree
# parser = etree.XMLParser(remove_blank_text=True)
import db.objects
import db.api
db_session = db.api.start_db_session() # need independent connection for reading
import os.path
import __main__
schema_path = os.path.join(os.path.dirname(__main__.__fil... | [
"common.AibError",
"lxml.etree.tostring",
"lxml.etree.Element",
"lxml.etree.SubElement"
] | [((735, 756), 'lxml.etree.Element', 'etree.Element', (['"""form"""'], {}), "('form')\n", (748, 756), False, 'from lxml import etree\n'), ((823, 863), 'lxml.etree.SubElement', 'etree.SubElement', (['form_xml', '"""db_objects"""'], {}), "(form_xml, 'db_objects')\n", (839, 863), False, 'from lxml import etree\n'), ((868, ... |
from .command import Command
from .connection import Connection
from .client_base import ClientBase
from amcp_pylib.response import ResponseBase, ResponseFactory
class Client(ClientBase):
""" Simple connection client class. """
def connect(self, host: str = "127.0.0.1", port: int = 5250):
if not... | [
"amcp_pylib.response.ResponseFactory.create_from_bytes"
] | [((724, 763), 'amcp_pylib.response.ResponseFactory.create_from_bytes', 'ResponseFactory.create_from_bytes', (['data'], {}), '(data)\n', (757, 763), False, 'from amcp_pylib.response import ResponseBase, ResponseFactory\n')] |
from lebanese_channels.channel import Channel
# noinspection PyUnresolvedReferences
from lebanese_channels.services import *
CHANNEL_LIST = []
for cls in Channel.__subclasses__():
CHANNEL_LIST.append(cls())
CHANNEL_LIST = sorted(CHANNEL_LIST, key=lambda x: x.get_name())
| [
"lebanese_channels.channel.Channel.__subclasses__"
] | [((156, 180), 'lebanese_channels.channel.Channel.__subclasses__', 'Channel.__subclasses__', ([], {}), '()\n', (178, 180), False, 'from lebanese_channels.channel import Channel\n')] |
import torch
import torch.nn as nn
import torch.nn.functional as F
from layer import GATLayer
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class GAT(nn.Module):
def __init__(self, num_features, hidden_size, embedding_size, alpha):
super(GAT, self).__init__()
self.hidden_s... | [
"torch.randn",
"torch.cuda.is_available",
"torch.nn.Linear",
"layer.GATLayer",
"torch.nn.functional.normalize"
] | [((127, 152), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (150, 152), False, 'import torch\n'), ((431, 473), 'layer.GATLayer', 'GATLayer', (['num_features', 'hidden_size', 'alpha'], {}), '(num_features, hidden_size, alpha)\n', (439, 473), False, 'from layer import GATLayer\n'), ((495, 539), ... |
# Generated by Django 2.1.12 on 2019-10-14 14:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('frontend', '0002_auto_20191010_0025'),
]
operations = [
migrations.AddField(
model_name='page',
name='js',
... | [
"django.db.models.TextField"
] | [((330, 401), 'django.db.models.TextField', 'models.TextField', ([], {'blank': '(True)', 'help_text': '"""会被放入 <code>script</code> 的 JS"""'}), "(blank=True, help_text='会被放入 <code>script</code> 的 JS')\n", (346, 401), False, 'from django.db import migrations, models\n')] |
import time
from functools import partial
from pathlib import Path
import toml
import torch
import colorful
import numpy as np
import matplotlib.pyplot as plt
from joblib import Parallel, delayed
from torch.cuda.amp import GradScaler
from sklearn.metrics import DetCurveDisplay
import src.util.metrics as metrics
from... | [
"matplotlib.pyplot.switch_backend",
"functools.partial",
"src.util.metrics.REGISTERED_METRICS.keys",
"toml.dumps",
"src.util.utils.ExecutionTime",
"time.strftime",
"src.util.metrics.compute_thresholds",
"pathlib.Path",
"torch.cuda.amp.GradScaler",
"sklearn.metrics.DetCurveDisplay",
"matplotlib.p... | [((460, 485), 'matplotlib.pyplot.switch_backend', 'plt.switch_backend', (['"""agg"""'], {}), "('agg')\n", (478, 485), True, 'import matplotlib.pyplot as plt\n'), ((1174, 1206), 'torch.cuda.amp.GradScaler', 'GradScaler', ([], {'enabled': 'self.use_amp'}), '(enabled=self.use_amp)\n', (1184, 1206), False, 'from torch.cuda... |
import numpy as np
import torch
from torchvision import datasets, transforms
DEFAULT_DATA_DIR = "/is/rg/al/Projects/prob-models/data/"
class ReconstructionDataset(torch.utils.data.Dataset):
def __init__(
self, name, split="train", flatten=True, train_split=0.8, data_dir=None
):
assert split i... | [
"torch.stack",
"numpy.random.RandomState",
"torchvision.transforms.ToTensor"
] | [((1027, 1071), 'torch.stack', 'torch.stack', (['[x[0] for x in dataset]'], {'axis': '(0)'}), '([x[0] for x in dataset], axis=0)\n', (1038, 1071), False, 'import torch\n'), ((1201, 1226), 'numpy.random.RandomState', 'np.random.RandomState', (['(45)'], {}), '(45)\n', (1222, 1226), True, 'import numpy as np\n'), ((656, 6... |
from typing import Iterator
from _pytest.fixtures import FixtureRequest
from pytest import fixture
from nextcloud_notes_api import Note
def _example_note() -> Note:
return Note(
title='Spam',
content='Bacon',
category='Todo',
favorite=True,
id=1337,
# https://stac... | [
"nextcloud_notes_api.Note"
] | [((180, 277), 'nextcloud_notes_api.Note', 'Note', ([], {'title': '"""Spam"""', 'content': '"""Bacon"""', 'category': '"""Todo"""', 'favorite': '(True)', 'id': '(1337)', 'modified': '(100000)'}), "(title='Spam', content='Bacon', category='Todo', favorite=True, id=1337,\n modified=100000)\n", (184, 277), False, 'from ... |
import sqlite3
from sqlite3 import Error
import time
import datetime
db = "/home/pi/projects/pigrow/db.sqlite3"
def create_table(conn):
create_table_query = """ CREATE TABLE IF NOT EXISTS dht_data (
id integer PRIMARY KEY,
humidity real ,
... | [
"Adafruit_DHT.read_retry",
"sqlite3.connect",
"datetime.datetime.now",
"time.sleep"
] | [((594, 613), 'sqlite3.connect', 'sqlite3.connect', (['db'], {}), '(db)\n', (609, 613), False, 'import sqlite3\n'), ((1123, 1166), 'Adafruit_DHT.read_retry', 'Adafruit_DHT.read_retry', (['sensor', 'sensor_pin'], {}), '(sensor, sensor_pin)\n', (1146, 1166), False, 'import Adafruit_DHT\n'), ((1373, 1387), 'time.sleep', '... |
import sys
sys.path.append("../")
from VideoTools import *
import subprocess
import os
import scipy.misc
MAXHEIGHT = 160
MINWIDTH = 120
def saveVideoID(I, IDims, fileprefix, ID, FrameRate = 30, NumberFrames = 30):
N = I.shape[0]
print(I.shape)
if I.shape[0] > FrameRate*5:
I = I[0:FrameRate*5, :]
... | [
"sys.path.append",
"os.remove",
"os.path.exists",
"subprocess.call",
"os.listdir"
] | [((11, 33), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (26, 33), False, 'import sys\n'), ((1187, 1211), 'subprocess.call', 'subprocess.call', (['command'], {}), '(command)\n', (1202, 1211), False, 'import subprocess\n'), ((1393, 1417), 'os.path.exists', 'os.path.exists', (['filename'], {}),... |
from flask import Blueprint, render_template
site_admin = Blueprint("admin_site", __name__, url_prefix="/admin",template_folder="template", static_folder="static", static_url_path="/admin/static")
@site_admin.route("/")
def admin():
return render_template("index.html")
| [
"flask.Blueprint",
"flask.render_template"
] | [((59, 203), 'flask.Blueprint', 'Blueprint', (['"""admin_site"""', '__name__'], {'url_prefix': '"""/admin"""', 'template_folder': '"""template"""', 'static_folder': '"""static"""', 'static_url_path': '"""/admin/static"""'}), "('admin_site', __name__, url_prefix='/admin', template_folder=\n 'template', static_folder=... |
import time
from threading import Timer
from typing import Callable
from pydispatch import dispatcher
from zacoby import global_logger
from zacoby.exceptions import ElementDoesNotExist, MethodError
# from zacoby.pipeline import Pipeline
from zacoby.settings import settings
from zacoby.signals import signal
class Dr... | [
"threading.Timer",
"time.time",
"time.sleep",
"zacoby.exceptions.MethodError",
"zacoby.global_logger.info"
] | [((890, 969), 'zacoby.global_logger.info', 'global_logger.info', (['f"""Waiting for element [{self.name}] - ({self.timeout}s)..."""'], {}), "(f'Waiting for element [{self.name}] - ({self.timeout}s)...')\n", (908, 969), False, 'from zacoby import global_logger\n'), ((2432, 2492), 'zacoby.global_logger.info', 'global_log... |
# -*- coding: utf-8 -*-
import sys
from redis import Redis
from rq import Queue, Connection, Worker
from mailhook.config import config
# Preload libraries
import twilio
# Provide queue names to listen to as arguments to this script,
# similar to rqworker
redis_conn = Redis(config.REDIS_HOST)
with Connection(redis_... | [
"redis.Redis",
"rq.Worker",
"rq.Connection",
"rq.Queue"
] | [((272, 296), 'redis.Redis', 'Redis', (['config.REDIS_HOST'], {}), '(config.REDIS_HOST)\n', (277, 296), False, 'from redis import Redis\n'), ((303, 325), 'rq.Connection', 'Connection', (['redis_conn'], {}), '(redis_conn)\n', (313, 325), False, 'from rq import Queue, Connection, Worker\n'), ((382, 392), 'rq.Worker', 'Wo... |
'''
Created on 5 janv. 2022
@author: slinux
'''
import sys
# The answer is that the module xmlrpc is part of python3
import xmlrpc.client
import os
import logging
class IPFS_RPC_Client(object):
#Put your server IP here
_ip='0.0.0.0'
_port=1234
_url = ""
_client = None
def _... | [
"os.path.realpath",
"os.path.split",
"os.path.exists",
"logging.getLogger"
] | [((448, 476), 'logging.getLogger', 'logging.getLogger', (['"""wxRaven"""'], {}), "('wxRaven')\n", (465, 476), False, 'import logging\n'), ((1080, 1103), 'os.path.split', 'os.path.split', (['filename'], {}), '(filename)\n', (1093, 1103), False, 'import os\n'), ((927, 953), 'os.path.realpath', 'os.path.realpath', (['__fi... |
import datetime
import inspect
import os
import sys
class Puzzle:
# The delimiter to use to separate the input data into a list for subsequent
# processing. E.g. '\n', ',', etc. Delimited items can be processed prior to
# being added to the input list by overriding _process_input_item().
# Set to... | [
"inspect.getfile",
"os.path.join",
"datetime.datetime.now",
"sys.getsizeof"
] | [((798, 826), 'os.path.join', 'os.path.join', (['path', 'filename'], {}), '(path, filename)\n', (810, 826), False, 'import os\n'), ((2573, 2596), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (2594, 2596), False, 'import datetime\n'), ((3824, 3847), 'datetime.datetime.now', 'datetime.datetime.now'... |
# create a credentials.py file with the following keys
from credentials import ckey, csecret, atoken, asecret
from tweepy import Stream, OAuthHandler
from tweepy.streaming import StreamListener
class listener(StreamListener):
def on_data(self, data):
print(data)
return True
def on_error(self,... | [
"tweepy.OAuthHandler"
] | [((360, 387), 'tweepy.OAuthHandler', 'OAuthHandler', (['ckey', 'csecret'], {}), '(ckey, csecret)\n', (372, 387), False, 'from tweepy import Stream, OAuthHandler\n')] |
## l2_attack.py -- attack a network optimizing for l_2 distance
##
## Copyright (C) 2016, <NAME> <<EMAIL>>.
##
## This program is licenced under the BSD 2-Clause licence,
## contained in the LICENCE file in this directory.
## Modified by <NAME> 2017
import tensorflow as tf
import numpy as np
BINARY_SEARCH_STEPS = 9 ... | [
"numpy.arctanh",
"tensorflow.reduce_sum",
"tensorflow.add_n",
"numpy.copy",
"numpy.argmax",
"tensorflow.maximum",
"tensorflow.variables_initializer",
"numpy.zeros",
"numpy.ones",
"tensorflow.placeholder",
"tensorflow.global_variables",
"numpy.array",
"tensorflow.tanh",
"numpy.dot",
"tens... | [((3887, 3920), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', 'shape'], {}), '(tf.float32, shape)\n', (3901, 3920), True, 'import tensorflow as tf\n'), ((3948, 4000), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '(batch_size, num_labels)'], {}), '(tf.float32, (batch_size, num_labels))\n', (... |
# =========================================
# IMPORTS
# --------------------------------------
import rootpath
rootpath.append()
# =========================================
# EXPORTS
# --------------------------------------
from inspecta.inspector import *
| [
"rootpath.append"
] | [((120, 137), 'rootpath.append', 'rootpath.append', ([], {}), '()\n', (135, 137), False, 'import rootpath\n')] |
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
def index(request):
return HttpResponse("Desde la vista App")
def sumar(request, numero1, numero2):
sum = numero1 + numero2
return HttpResponse("La suma de %s + %s = %s" % (numero1, numero2, sum))
... | [
"django.http.HttpResponse"
] | [((132, 166), 'django.http.HttpResponse', 'HttpResponse', (['"""Desde la vista App"""'], {}), "('Desde la vista App')\n", (144, 166), False, 'from django.http import HttpResponse\n'), ((245, 310), 'django.http.HttpResponse', 'HttpResponse', (["('La suma de %s + %s = %s' % (numero1, numero2, sum))"], {}), "('La suma de ... |
import django.core.validators
import django.db.models.deletion
import django.utils.timezone
from django.db import migrations, models
import model_utils.fields
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="Car",
... | [
"django.db.models.CharField",
"django.db.models.ForeignKey",
"django.db.models.AutoField"
] | [((405, 498), '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", (421, 498), False, 'from django.db import migrations, models\... |
import os
import json
from .exceptions import DataLoadException
class JsonDataLoader:
"""
Load base calculation data
from provided JSON file.
"""
def __init__(self, path):
self._path = path
def load(self):
if not os.path.exists(self._path):
raise DataLoadExceptio... | [
"json.load",
"os.path.exists"
] | [((258, 284), 'os.path.exists', 'os.path.exists', (['self._path'], {}), '(self._path)\n', (272, 284), False, 'import os\n'), ((412, 424), 'json.load', 'json.load', (['f'], {}), '(f)\n', (421, 424), False, 'import json\n')] |
from rest_framework import viewsets, permissions
import ippon.cup_fight.permissions as cfp
import ippon.cup_fight.serializers as cfs
import ippon.models.cup_fight as cfm
class CupFightViewSet(viewsets.ModelViewSet):
queryset = cfm.CupFight.objects.all()
serializer_class = cfs.CupFightSerializer
permissio... | [
"ippon.models.cup_fight.CupFight.objects.all"
] | [((234, 260), 'ippon.models.cup_fight.CupFight.objects.all', 'cfm.CupFight.objects.all', ([], {}), '()\n', (258, 260), True, 'import ippon.models.cup_fight as cfm\n')] |
"""
.. module:: evaluator
:synopsis: Holding all evaluator classes!
.. moduleauthor:: <NAME>
"""
from typing import List, Union, Dict
from abc import ABC, abstractmethod
import numpy as np
import pandas as pd
from scipy.stats import pearsonr
from sklearn.metrics import classification_report
from mtc.core.sentence... | [
"scipy.stats.pearsonr"
] | [((2137, 2171), 'scipy.stats.pearsonr', 'pearsonr', (['y_eval_predicted', 'y_eval'], {}), '(y_eval_predicted, y_eval)\n', (2145, 2171), False, 'from scipy.stats import pearsonr\n')] |
from django.contrib import admin
from django.urls import path, include
from .views import documentation
from .router import router
from rest_framework_jwt.views import obtain_jwt_token
urlpatterns = [
path('tokenAuth/', obtain_jwt_token),
path('', documentation, name='documentation'),
path('', include('m... | [
"django.urls.path",
"django.urls.include"
] | [((208, 244), 'django.urls.path', 'path', (['"""tokenAuth/"""', 'obtain_jwt_token'], {}), "('tokenAuth/', obtain_jwt_token)\n", (212, 244), False, 'from django.urls import path, include\n'), ((250, 295), 'django.urls.path', 'path', (['""""""', 'documentation'], {'name': '"""documentation"""'}), "('', documentation, nam... |
from queue import Queue
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
@staticmethod
def from_array(array):
# bfs construct binary tree
root = TreeNode(array[0])
q = Queue()
q.put(root)
i = 1
... | [
"queue.Queue"
] | [((273, 280), 'queue.Queue', 'Queue', ([], {}), '()\n', (278, 280), False, 'from queue import Queue\n')] |
from beerbackend.user.models import Beer, families, User
from flask_restful import Resource, Api, reqparse, fields, marshal_with
from flask.json import jsonify
import os
import json
beer_get_parse = reqparse.RequestParser()
beer_get_parse.add_argument('beer_name', dest='beer_name',
type=str, re... | [
"json.load",
"beerbackend.user.models.Beer.create",
"beerbackend.user.models.Beer.query.all",
"os.getcwd",
"flask_restful.reqparse.RequestParser",
"beerbackend.user.models.families.values",
"beerbackend.user.models.Beer.query.filter"
] | [((201, 225), 'flask_restful.reqparse.RequestParser', 'reqparse.RequestParser', ([], {}), '()\n', (223, 225), False, 'from flask_restful import Resource, Api, reqparse, fields, marshal_with\n'), ((965, 981), 'beerbackend.user.models.Beer.query.all', 'Beer.query.all', ([], {}), '()\n', (979, 981), False, 'from beerbacke... |
from vanilla import *
from mojo.extensions import getExtensionDefault, setExtensionDefault
class DrawBotSettingsController(object):
def __init__(self):
self.w = Window((250, 45), "DrawBot Settings")
self.w.openPythonFilesInDrawBot = CheckBox((10, 10, -10, 22),
"Open .py files direct... | [
"mojo.extensions.getExtensionDefault"
] | [((355, 415), 'mojo.extensions.getExtensionDefault', 'getExtensionDefault', (['"""com.drawBot.openPyFileDirectly"""', '(False)'], {}), "('com.drawBot.openPyFileDirectly', False)\n", (374, 415), False, 'from mojo.extensions import getExtensionDefault, setExtensionDefault\n')] |
# -*- encoding:utf-8 -*-
"""
买入择时示例因子:动态自适应双均线策略
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import math
import numpy as np
from .ABuFactorBuyBase import AbuFactorBuyXD, BuyCallMixin
from ..IndicatorBu.ABuNDMa import calc_ma_from_prices
from .... | [
"numpy.arange",
"math.ceil"
] | [((4463, 4513), 'numpy.arange', 'np.arange', (['self.resample_min', 'self.resample_max', '(5)'], {}), '(self.resample_min, self.resample_max, 5)\n', (4472, 4513), True, 'import numpy as np\n'), ((2821, 2851), 'math.ceil', 'math.ceil', (['(self.ma_slow * 0.15)'], {}), '(self.ma_slow * 0.15)\n', (2830, 2851), False, 'imp... |