code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import markupfield.fields
import django.utils.timezone
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODE... | [
"django.db.models.URLField",
"django.db.models.TextField",
"django.db.migrations.swappable_dependency",
"django.db.models.CharField",
"django.db.models.ForeignKey",
"django.db.models.SlugField",
"django.db.models.AutoField",
"django.db.models.DateTimeField"
] | [((265, 322), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (296, 322), False, 'from django.db import models, migrations\n'), ((453, 546), 'django.db.models.AutoField', 'models.AutoField', ([], {'verbose_name': '"""ID"... |
# -*- coding: utf-8 -*-
"""
@Time : 2021/8/24 13:00
@Auth : apecode
@File :notice.py
@IDE :PyCharm
@Blog:https://liiuyangxiong.cn
"""
import json
import time
from email.mime.text import MIMEText
from email.header import Header
from smtplib import SMTP_SSL
import requests
import config
class Notic... | [
"email.header.Header",
"smtplib.SMTP_SSL",
"email.mime.text.MIMEText",
"time.time",
"requests.post"
] | [((1497, 1518), 'smtplib.SMTP_SSL', 'SMTP_SSL', (['host_server'], {}), '(host_server)\n', (1505, 1518), False, 'from smtplib import SMTP_SSL\n'), ((1620, 1654), 'email.mime.text.MIMEText', 'MIMEText', (['message', '"""html"""', '"""utf-8"""'], {}), "(message, 'html', 'utf-8')\n", (1628, 1654), False, 'from email.mime.t... |
#!/usr/bin/env python
"""
this calls test_executable_caller as it should be called for the test to work.
"""
import subprocess
if __name__ == '__main__':
process = subprocess.Popen(
['python', 'test_executable_caller.py','test_executable_callee.py'],
shell = False,
universal_newlines = T... | [
"subprocess.Popen"
] | [((171, 299), 'subprocess.Popen', 'subprocess.Popen', (["['python', 'test_executable_caller.py', 'test_executable_callee.py']"], {'shell': '(False)', 'universal_newlines': '(True)'}), "(['python', 'test_executable_caller.py',\n 'test_executable_callee.py'], shell=False, universal_newlines=True)\n", (187, 299), False... |
import datetime
from django.contrib.auth.models import User
from quiz.models import (
AnswerUser,
Category,
Grade,
Question,
QuestionScore,
Quiz,
Statistic,
SubCategory,
ThemeScore,
)
import pytest
### FIXTURES ###
@pytest.fixture
def category_m(db):
return Category.object... | [
"quiz.models.Grade.objects.create",
"quiz.models.Question.objects.create",
"quiz.models.ThemeScore.objects.create",
"quiz.models.Category.objects.create",
"quiz.models.AnswerUser.objects.create",
"quiz.models.QuestionScore.objects.create",
"django.contrib.auth.models.User.objects.create_user",
"quiz.m... | [((305, 342), 'quiz.models.Category.objects.create', 'Category.objects.create', ([], {'category': '"""m"""'}), "(category='m')\n", (328, 342), False, 'from quiz.models import AnswerUser, Category, Grade, Question, QuestionScore, Quiz, Statistic, SubCategory, ThemeScore\n'), ((408, 473), 'quiz.models.SubCategory.objects... |
'''
#Método 1 de calcular a hipotenusa (sem o módulo math)
co = float(input('comprimento do cateto oposto: '))
ca = float(input('comprimento do cateto adjacente: '))
h = (co ** 2) + (ca ** 2) ** (1/2)
print(f'a hipotenusa equivale a {h:.2f}')
'''
# Método 2 de calcular a hipotenusa (com o módulo math)
import math
c... | [
"math.hypot"
] | [((430, 448), 'math.hypot', 'math.hypot', (['co', 'ca'], {}), '(co, ca)\n', (440, 448), False, 'import math\n')] |
import csv
import json
from ofxtools.Parser import OFXTree
"""
statement schema:
{
"id":int,
"ref_no": int,
"date": string,
"account": int, account code,
"isincome": bool,
"countinbudget": bool,
"payee": string,
"notes": {
"bank": string,
"personal": string
},
"categories": [strings],
"t... | [
"ofxtools.Parser.OFXTree"
] | [((999, 1008), 'ofxtools.Parser.OFXTree', 'OFXTree', ([], {}), '()\n', (1006, 1008), False, 'from ofxtools.Parser import OFXTree\n'), ((1631, 1640), 'ofxtools.Parser.OFXTree', 'OFXTree', ([], {}), '()\n', (1638, 1640), False, 'from ofxtools.Parser import OFXTree\n'), ((2292, 2301), 'ofxtools.Parser.OFXTree', 'OFXTree',... |
import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name="django-trello-webhooks",
version="0.3",
packages=[
... | [
"os.path.abspath",
"os.path.dirname",
"setuptools.setup"
] | [((238, 1204), 'setuptools.setup', 'setup', ([], {'name': '"""django-trello-webhooks"""', 'version': '"""0.3"""', 'packages': "['trello_webhooks', 'trello_webhooks.management',\n 'trello_webhooks.management.commands', 'trello_webhooks.migrations',\n 'trello_webhooks.templatetags', 'trello_webhooks.tests']", 'inst... |
from lightfm import LightFM
from lightfm.datasets import fetch_movielens
from pgvector.sqlalchemy import Vector
from sqlalchemy import create_engine, text, Column, Float, Integer, String
from sqlalchemy.orm import declarative_base, Session
engine = create_engine('postgresql+psycopg2://localhost/pgvector_example', futu... | [
"pgvector.sqlalchemy.Vector",
"sqlalchemy.orm.declarative_base",
"lightfm.LightFM",
"sqlalchemy.orm.Session",
"sqlalchemy.text",
"sqlalchemy.Column",
"sqlalchemy.create_engine",
"lightfm.datasets.fetch_movielens"
] | [((250, 328), 'sqlalchemy.create_engine', 'create_engine', (['"""postgresql+psycopg2://localhost/pgvector_example"""'], {'future': '(True)'}), "('postgresql+psycopg2://localhost/pgvector_example', future=True)\n", (263, 328), False, 'from sqlalchemy import create_engine, text, Column, Float, Integer, String\n'), ((450,... |
# coding: utf-8
"""
BillForward REST API
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
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... | [
"six.iteritems"
] | [((4492, 4519), 'six.iteritems', 'iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (4501, 4519), False, 'from six import iteritems\n'), ((9178, 9205), 'six.iteritems', 'iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (9187, 9205), False, 'from six import iteritems\n'), ((14778, 14805), 's... |
from django.contrib import admin
from . import models
@admin.register(models.Reviewer)
class ReviewerAdmin(admin.ModelAdmin):
autocomplete_fields = ["user"]
list_display = ["username", "email"]
search_fields = ["username__istartswith"]
@admin.register(models.Album)
class AlbumAdmin(admin.ModelAdmin):
... | [
"django.contrib.admin.register"
] | [((57, 88), 'django.contrib.admin.register', 'admin.register', (['models.Reviewer'], {}), '(models.Reviewer)\n', (71, 88), False, 'from django.contrib import admin\n'), ((253, 281), 'django.contrib.admin.register', 'admin.register', (['models.Album'], {}), '(models.Album)\n', (267, 281), False, 'from django.contrib imp... |
import mxnet as mx
from mxnet import nd, autograd
import numpy as np
##################################3
# X, y - training data
# n - number of data points in dataset
# Py - desired label distribution
###################################
def tweak_dist(X, y, num_labels, n, Py):
shape = (n, *X.shape[1:])
Xsh... | [
"numpy.full",
"numpy.random.multinomial",
"numpy.zeros",
"numpy.random.choice"
] | [((326, 341), 'numpy.zeros', 'np.zeros', (['shape'], {}), '(shape)\n', (334, 341), True, 'import numpy as np\n'), ((355, 381), 'numpy.zeros', 'np.zeros', (['n'], {'dtype': 'np.int8'}), '(n, dtype=np.int8)\n', (363, 381), True, 'import numpy as np\n'), ((899, 948), 'numpy.full', 'np.full', (['num_labels', '((1.0 - p) / ... |
from selenium_controller.github import Github
from selenium_controller.gitlab import Gitlab
from utils.shell_executor.executor import execute_now
def main():
github = Github()
gitlab = Gitlab()
new_tags = list()
execute_now('git fetch --all')
gitlab_versions = gitlab.fetch_gitlab_map_versions()... | [
"utils.shell_executor.executor.execute_now",
"selenium_controller.gitlab.Gitlab",
"selenium_controller.github.Github"
] | [((173, 181), 'selenium_controller.github.Github', 'Github', ([], {}), '()\n', (179, 181), False, 'from selenium_controller.github import Github\n'), ((195, 203), 'selenium_controller.gitlab.Gitlab', 'Gitlab', ([], {}), '()\n', (201, 203), False, 'from selenium_controller.gitlab import Gitlab\n'), ((232, 262), 'utils.s... |
# -*-coding:utf-8 -*-
from openstack import connection
# create connection
username = "xxxxxx"
password = "<PASSWORD>"
projectId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx" # tenant ID
userDomainId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx" # user account ID
auth_url = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx" # endpoint url
conn = connecti... | [
"openstack.connection.Connection"
] | [((312, 445), 'openstack.connection.Connection', 'connection.Connection', ([], {'auth_url': 'auth_url', 'user_domain_id': 'userDomainId', 'project_id': 'projectId', 'username': 'username', 'password': 'password'}), '(auth_url=auth_url, user_domain_id=userDomainId,\n project_id=projectId, username=username, password=... |
#!/usr/bin/env python3
import os
from subprocess import CalledProcessError, run
from typing import Dict, List, Union
import json
from pathlib import Path
import click
__dir__ = Path(__file__).parent.absolute()
def github_repo_name() -> str:
if repo_full := os.environ.get("GITHUB_REPOSITORY"):
return re... | [
"subprocess.run",
"json.load",
"click.option",
"click.command",
"os.environ.get",
"pathlib.Path"
] | [((2916, 2931), 'click.command', 'click.command', ([], {}), '()\n', (2929, 2931), False, 'import click\n'), ((2933, 2976), 'click.option', 'click.option', (['"""-w"""', '"""--write"""'], {'is_flag': '(True)'}), "('-w', '--write', is_flag=True)\n", (2945, 2976), False, 'import click\n'), ((266, 301), 'os.environ.get', '... |
from django.db import models
from django.db.models.signals import post_save
from . import tasks
### Define Querysets
class TwitterProfileQuerySet(models.QuerySet):
def search(self, query):
return self.filter(name__icontains=query)
class TaskQuerySet(models.QuerySet):
def search(self, query):
... | [
"django.db.models.URLField",
"django.db.models.TextField",
"django.db.models.CharField",
"django.db.models.PositiveIntegerField",
"django.db.models.Manager",
"django.db.models.signals.post_save.connect"
] | [((2508, 2541), 'django.db.models.signals.post_save.connect', 'post_save.connect', (['Task.run', 'Task'], {}), '(Task.run, Task)\n', (2525, 2541), False, 'from django.db.models.signals import post_save\n'), ((619, 659), 'django.db.models.PositiveIntegerField', 'models.PositiveIntegerField', ([], {'unique': '(True)'}), ... |
from __future__ import print_function
import FWCore.ParameterSet.Config as cms
from Configuration.AlCa.autoCond import autoCond
process = cms.Process("TEST")
process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(100) )
process.source = cms.Source("EmptyIOVSource",
lastV... | [
"FWCore.ParameterSet.Config.string",
"FWCore.ParameterSet.Config.untracked.int32",
"FWCore.ParameterSet.Config.uint64",
"CondCore.ESSources.GlobalTag.GlobalTag",
"FWCore.ParameterSet.Config.Process",
"FWCore.ParameterSet.Config.Path"
] | [((140, 159), 'FWCore.ParameterSet.Config.Process', 'cms.Process', (['"""TEST"""'], {}), "('TEST')\n", (151, 159), True, 'import FWCore.ParameterSet.Config as cms\n'), ((737, 811), 'CondCore.ESSources.GlobalTag.GlobalTag', 'GlobalTag', (["autoCond['run2_data']", '"""frontier://FrontierProd/CMS_CONDITIONS"""'], {}), "(a... |
from django.contrib.messages.views import SuccessMessageMixin
from django.db.models import Q
from django.shortcuts import render
from django.views.generic import DetailView, ListView, UpdateView
from .forms import StaffUpdateForm
from .models import Staff
class SearchSearchView(ListView):
model = Staff
pagin... | [
"django.db.models.Q"
] | [((792, 820), 'django.db.models.Q', 'Q', ([], {'district__icontains': 'query'}), '(district__icontains=query)\n', (793, 820), False, 'from django.db.models import Q\n'), ((746, 773), 'django.db.models.Q', 'Q', ([], {'address__icontains': 'query'}), '(address__icontains=query)\n', (747, 773), False, 'from django.db.mode... |
#
# Copyright 2015-2016 IBM Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | [
"traceback.print_exc",
"flask.Flask",
"flask.abort",
"gevent.wsgi.WSGIServer",
"json.dumps",
"flask.jsonify",
"sys.stdout.flush",
"sys.stderr.flush",
"os.getenv",
"flask.request.get_json"
] | [((724, 745), 'flask.Flask', 'flask.Flask', (['__name__'], {}), '(__name__)\n', (735, 745), False, 'import flask\n'), ((852, 899), 'flask.request.get_json', 'flask.request.get_json', ([], {'force': '(True)', 'silent': '(True)'}), '(force=True, silent=True)\n', (874, 899), False, 'import flask\n'), ((1229, 1276), 'flask... |
# +
from model import common
import torch.nn as nn
import torch
from torch.autograd import Variable
import numpy.random as npr
import numpy as np
import torch.nn.functional as F
import random
import math
def make_model(args, parent=False):
return SRResNet(args)
class SRResNet(nn.Module):
def __init__(self, a... | [
"torch.nn.PReLU",
"torch.ones",
"random.randint",
"torch.nn.Sequential",
"model.common.ResBlock",
"torch.nn.L1Loss",
"torch.autograd.Variable",
"torch.nn.Conv2d",
"math.ceil",
"torch.nn.BatchNorm2d",
"model.common.Upsampler",
"torch.zeros",
"torch.sum",
"torch.sort",
"model.common.MeanSh... | [((508, 518), 'torch.nn.PReLU', 'nn.PReLU', ([], {}), '()\n', (516, 518), True, 'import torch.nn as nn\n'), ((552, 584), 'model.common.MeanShift', 'common.MeanShift', (['args.rgb_range'], {}), '(args.rgb_range)\n', (568, 584), False, 'from model import common\n'), ((609, 649), 'model.common.MeanShift', 'common.MeanShif... |
from django.http import HttpRequest
from django.test import SimpleTestCase
from django.urls import reverse
from .. import views
class HomePageTests(SimpleTestCase):
def test_home_page_status_code(self):
response = self.client.get("/")
self.assertEqual(response.status_code, 200)
def test_view... | [
"django.urls.reverse"
] | [((375, 390), 'django.urls.reverse', 'reverse', (['"""home"""'], {}), "('home')\n", (382, 390), False, 'from django.urls import reverse\n'), ((527, 542), 'django.urls.reverse', 'reverse', (['"""home"""'], {}), "('home')\n", (534, 542), False, 'from django.urls import reverse\n')] |
"""
Test functions for GEE
External comparisons are to R. The statmodels GEE implementation
should generally agree with the R GEE implementation for the
independence and exchangeable correlation structures. For other
correlation structures, the details of the correlation estimation
differ among implementations and t... | [
"numpy.random.seed",
"numpy.abs",
"pandas.read_csv",
"numpy.ones",
"statsmodels.genmod.generalized_estimating_equations.Multinomial",
"numpy.random.randint",
"numpy.arange",
"numpy.exp",
"numpy.random.normal",
"statsmodels.genmod.families.Gaussian",
"numpy.diag",
"os.path.join",
"pandas.Data... | [((21322, 21409), 'nose.runmodule', 'nose.runmodule', ([], {'argv': "[__file__, '-vvs', '-x', '--pdb', '--pdb-failure']", 'exit': '(False)'}), "(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],\n exit=False)\n", (21336, 21409), False, 'import nose\n'), ((1230, 1255), 'os.path.abspath', 'os.path.abspath', (['... |
# Generated by Django 2.2.20 on 2021-07-29 15:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('company', '0019_auto_20210512_1114'),
]
operations = [
migrations.AlterField(
model_name='company',
name='address_a... | [
"django.db.models.CharField"
] | [((356, 441), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(255)', 'verbose_name': '"""State (Abbreviated)"""'}), "(blank=True, max_length=255, verbose_name='State (Abbreviated)'\n )\n", (372, 441), False, 'from django.db import migrations, models\n'), ((588, 673), 'djang... |
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def index():
headline = "Hello World"
return render_template("index.html", headline=headline)
@app.route("/<string:name>")
def say_name(name):
return render_template("index.html", name=name)
if __name__ == "__main__":
... | [
"flask.Flask",
"flask.render_template"
] | [((48, 63), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (53, 63), False, 'from flask import Flask, render_template\n'), ((135, 183), 'flask.render_template', 'render_template', (['"""index.html"""'], {'headline': 'headline'}), "('index.html', headline=headline)\n", (150, 183), False, 'from flask import ... |
#!/usr/bin/env python3
"""Reddit Bot Common Routines
Contains common Reddit bot functions such as keyword comment retrieval,
processed comment caching, and comment posting.
Allows bot authors to concentrate on writing their custom bot functions.
"""
from collections import deque
from os import mkdir
import re
impor... | [
"os.mkdir",
"time.sleep",
"sys.exit",
"signal.signal",
"praw.Reddit",
"collections.deque",
"re.compile"
] | [((1729, 1769), 're.compile', 're.compile', (["(keyword + ' ([ \\\\w]+)')", 're.I'], {}), "(keyword + ' ([ \\\\w]+)', re.I)\n", (1739, 1769), False, 'import re\n'), ((2018, 2061), 'signal.signal', 'signal.signal', (['signal.SIGINT', 'self.bot_exit'], {}), '(signal.SIGINT, self.bot_exit)\n', (2031, 2061), False, 'import... |
from __future__ import unicode_literals
import logging
root_logger = logging.getLogger('autotweet')
logging.basicConfig(
format='%(asctime)s {%(module)s:%(levelname)s}: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
def set_level(level):
root_logger.setLevel(level)
get_logger = root_logger.getChild
| [
"logging.basicConfig",
"logging.getLogger"
] | [((71, 101), 'logging.getLogger', 'logging.getLogger', (['"""autotweet"""'], {}), "('autotweet')\n", (88, 101), False, 'import logging\n'), ((103, 223), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s {%(module)s:%(levelname)s}: %(message)s"""', 'datefmt': '"""%Y-%m-%d %H:%M:%S"""'}), "(fo... |
############################################## README #################################################
# This calculates threshold for an image depending upon its spiking activity.
########################################################################################################
import numpy as np
from snn.n... | [
"numpy.shape"
] | [((630, 648), 'numpy.shape', 'np.shape', (['train[0]'], {}), '(train[0])\n', (638, 648), True, 'import numpy as np\n')] |
# Generated by Django 3.1 on 2020-11-10 00:11
from __future__ import unicode_literals
from django.db import migrations, models
import csv
from datetime import datetime
def load_initial_data(apps, schema_editor):
Authority = apps.get_model("accounts", "Authority")
with open("assets/authority/authority_names.csv", ... | [
"django.db.migrations.RunPython",
"csv.reader"
] | [((342, 355), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (352, 355), False, 'import csv\n'), ((790, 843), 'django.db.migrations.RunPython', 'migrations.RunPython', (['load_initial_data', 'reverse_func'], {}), '(load_initial_data, reverse_func)\n', (810, 843), False, 'from django.db import migrations, models\n')] |
# all the data from train data set, k-fold validation
import numpy as np
import onnxruntime
import torch
from pandas import read_csv
from tensorflow.python.keras.utils.np_utils import to_categorical
from sklearn.metrics import f1_score, recall_score, precision_score, accuracy_score
# load a single file as a numpy ar... | [
"numpy.dstack",
"torch.utils.data.DataLoader",
"pandas.read_csv",
"numpy.std",
"numpy.transpose",
"tensorflow.python.keras.utils.np_utils.to_categorical",
"onnxruntime.InferenceSession",
"numpy.mean"
] | [((365, 419), 'pandas.read_csv', 'read_csv', (['filepath'], {'header': 'None', 'delim_whitespace': '(True)'}), '(filepath, header=None, delim_whitespace=True)\n', (373, 419), False, 'from pandas import read_csv\n'), ((746, 763), 'numpy.dstack', 'np.dstack', (['loaded'], {}), '(loaded)\n', (755, 763), True, 'import nump... |
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Div
from django import forms
from django.core.exceptions import ObjectDoesNotExist
from django.core.validators import RegexValidator, ValidationError
from django.forms import Form
from phonenumber_field.formfields import PhoneNumberField... | [
"project_core.models.PhysicalPerson.objects.get",
"django.forms.ModelChoiceField",
"django.forms.EmailField",
"django.core.validators.ValidationError",
"crispy_forms.layout.Div",
"crispy_forms.helper.FormHelper",
"project_core.models.CareerStage.objects.all",
"project_core.utils.orcid.field_set_read_o... | [((3745, 3979), 'django.forms.CharField', 'forms.CharField', ([], {'initial': 'first_name_initial', 'label': '"""First name(s)"""', 'help_text': '"""Your name is populated from your ORCID record. If you would like to change it please amend it in <a href="https://orcid.org/login">ORCID</a>"""'}), '(initial=first_name_in... |
# class derived from a GridLayout with a bunch of widgets
from PyQt5.QtWidgets import QLabel, QGridLayout, QLineEdit, \
QVBoxLayout, QHBoxLayout, QComboBox, QPushButton, QCheckBox
import numpy as np
import pandas as pd
class ParamWidget(QGridLayout):
'''
Collecting all the input boxes and labels to assign data.
... | [
"PyQt5.QtWidgets.QComboBox",
"PyQt5.QtWidgets.QLabel",
"PyQt5.QtWidgets.QLineEdit",
"PyQt5.QtWidgets.QHBoxLayout",
"PyQt5.QtWidgets.QPushButton",
"PyQt5.QtWidgets.QCheckBox"
] | [((1038, 1047), 'PyQt5.QtWidgets.QLabel', 'QLabel', (['k'], {}), '(k)\n', (1044, 1047), False, 'from PyQt5.QtWidgets import QLabel, QGridLayout, QLineEdit, QVBoxLayout, QHBoxLayout, QComboBox, QPushButton, QCheckBox\n'), ((1130, 1141), 'PyQt5.QtWidgets.QComboBox', 'QComboBox', ([], {}), '()\n', (1139, 1141), False, 'fr... |
from django.conf.urls import url, include
from django.contrib import admin
from rest_framework.documentation import include_docs_urls
from auth_api import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^docs/', include_docs_urls(title='Todo API', description='RESTful API for Todo')),
url(r... | [
"rest_framework.documentation.include_docs_urls",
"django.conf.urls.include",
"django.conf.urls.url"
] | [((183, 214), 'django.conf.urls.url', 'url', (['"""^admin/"""', 'admin.site.urls'], {}), "('^admin/', admin.site.urls)\n", (186, 214), False, 'from django.conf.urls import url, include\n'), ((315, 340), 'django.conf.urls.url', 'url', (['"""^$"""', 'views.api_root'], {}), "('^$', views.api_root)\n", (318, 340), False, '... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | [
"azure.profiles.ProfileDefinition",
"azure.mgmt.core.ARMPipelineClient"
] | [((2704, 3578), 'azure.profiles.ProfileDefinition', 'ProfileDefinition', (["{_PROFILE_TAG: {None: DEFAULT_API_VERSION, 'assets': '1.0.0',\n 'async_operations': 'v1.0', 'batch_job_deployment':\n '2020-09-01-dataplanepreview', 'batch_job_endpoint':\n '2020-09-01-dataplanepreview', 'data_call': '1.5.0', 'data_con... |
#!/usr/bin/python3 -B
# Copyright (c) 2020 <NAME>
# See README for details
# ================================================================
import sys
import os
import stat
import importlib
import pprint
from Gen_Bytevec_Mux_BSV import *
from Gen_Bytevec_Mux_C import *
pp = pprint.PrettyPrinter()
# =========... | [
"sys.stdout.write",
"pprint.PrettyPrinter",
"sys.exit",
"importlib.import_module"
] | [((285, 307), 'pprint.PrettyPrinter', 'pprint.PrettyPrinter', ([], {}), '()\n', (305, 307), False, 'import pprint\n'), ((3243, 3339), 'sys.stdout.write', 'sys.stdout.write', (['"""Computing all necessary byte-widths for packet formats and C structs.\n"""'], {}), "(\n 'Computing all necessary byte-widths for packet f... |
# Copyright 2017-2020 Lawrence Livermore National Security, LLC and other
# CallFlow Project Developers. See the top-level LICENSE file for details.
#
# SPDX-License-Identifier: MIT
import pandas as pd
class RankHistogram:
def __init__(self, state, name):
self.graph = state.new_gf.graph
self.df =... | [
"pandas.DataFrame"
] | [((1210, 1227), 'pandas.DataFrame', 'pd.DataFrame', (['ret'], {}), '(ret)\n', (1222, 1227), True, 'import pandas as pd\n')] |
import os
def read_test_case(file_path):
"""
reads one test case from file.
returns contents of test case
Parameters
----------
file_path : str
the path of the test case file to read.
Returns
-------
list
a list of contents of the test case.
"""
file = op... | [
"os.path.join"
] | [((927, 955), 'os.path.join', 'os.path.join', (['dir', 'file_name'], {}), '(dir, file_name)\n', (939, 955), False, 'import os\n')] |
# (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
from os.path import isfile
def test_ok(aggregator, check, instance_ok):
assert isfile(instance_ok['created_at_file'])
check.check(instance_ok)
aggregator.assert_service_check('system.reboot_required', st... | [
"os.path.isfile"
] | [((186, 224), 'os.path.isfile', 'isfile', (["instance_ok['created_at_file']"], {}), "(instance_ok['created_at_file'])\n", (192, 224), False, 'from os.path import isfile\n'), ((418, 465), 'os.path.isfile', 'isfile', (["instance_not_present['created_at_file']"], {}), "(instance_not_present['created_at_file'])\n", (424, 4... |
#! /usr/bin/enc python
# -*- coding: utf-8 -*-
# author: <NAME>
# email: <EMAIL>
"""
Swin Transformer
1. 类似CNN的层次化构建方法(Hierarchical Feature Maps),特征图尺寸中有对图像下采样4倍、8倍、以及16倍;
这样的Backbone有助于再此基础上构建目标检测、实例分割等任务。
2. 使用Windows Multi-Head Self-Attention (W-MSA)概念。减少计算量。计算复杂度从指数级降到线性级,Multi-head
Self-Attention只在每个Window... | [
"torch.nn.Dropout",
"BasicModule.Mlp",
"torch.jit.is_scripting",
"torch.roll",
"torch.nn.init.constant_",
"torch.nn.Softmax",
"torch.arange",
"torch.nn.functional.pad",
"torch.flatten",
"torch.nn.Linear",
"BasicModule.window_reverse",
"torch.zeros",
"BasicModule.DropPath",
"numpy.ceil",
... | [((6893, 7018), 'BasicModule.PatchEmbed', 'PatchEmbed', ([], {'patch_size': 'patch_size', 'in_c': 'in_chans', 'embed_dim': 'embed_dim', 'norm_layer': '(norm_layer if self.patch_norm else None)'}), '(patch_size=patch_size, in_c=in_chans, embed_dim=embed_dim,\n norm_layer=norm_layer if self.patch_norm else None)\n', (... |
# -*- coding: utf-8 -*-
import pdb, importlib, inspect, time, datetime, json
# from PyFin.api import advanceDateByCalendar
# from data.polymerize import DBPolymerize
from data.storage_engine import StorageEngine
import time
import pandas as pd
import numpy as np
from datetime import timedelta, datetime
from financial ... | [
"datetime.datetime.strftime",
"pandas.DataFrame",
"data.storage_engine.StorageEngine",
"pandas.merge",
"data.sqlengine.sqlEngine",
"time.time",
"datetime.datetime.strptime",
"datetime.timedelta",
"financial.factor_per_share_indicators.FactorPerShareIndicators",
"vision.table.valuation.Valuation.tr... | [((2402, 2443), 'datetime.datetime.strptime', 'datetime.strptime', (['trade_date', '"""%Y-%m-%d"""'], {}), "(trade_date, '%Y-%m-%d')\n", (2419, 2443), False, 'from datetime import timedelta, datetime\n'), ((2465, 2504), 'datetime.datetime.strftime', 'datetime.strftime', (['time_array', '"""%Y%m%d"""'], {}), "(time_arra... |
'''
Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree.
样例
Example 1:
Input: n = 5 edges = [[0, 1], [0, 2], [0, 3], [1, 4]]
Output: true.
Example 2:
Input: n = 5 edges = [[0, 1], [1, 2], [2, 3], [1, 3... | [
"collections.defaultdict",
"collections.deque"
] | [((911, 924), 'collections.defaultdict', 'defaultdict', ([], {}), '()\n', (922, 924), False, 'from collections import defaultdict, deque\n'), ((1238, 1245), 'collections.deque', 'deque', ([], {}), '()\n', (1243, 1245), False, 'from collections import defaultdict, deque\n')] |
# -*- coding:utf-8 -*-
import six
import numpy as np
from pyproj import Proj
import operator
from .exceptions import *
class NullProj(object):
"""
Similar to pyproj.Proj, but NullProj does not do actual conversion.
"""
@property
def srs(self):
return ''
def __call__(self, x, y, **kw... | [
"numpy.arctan2",
"numpy.floor",
"numpy.argmin",
"numpy.shape",
"numpy.sin",
"numpy.arange",
"numpy.round",
"numpy.meshgrid",
"numpy.ndim",
"numpy.arcsin",
"numpy.max",
"numpy.linspace",
"numpy.asarray",
"numpy.hypot",
"numpy.min",
"numpy.cos",
"numpy.alltrue",
"numpy.deg2rad",
"n... | [((1494, 1517), 'numpy.alltrue', 'np.alltrue', (['bad'], {'axis': '(0)'}), '(bad, axis=0)\n', (1504, 1517), True, 'import numpy as np\n'), ((1534, 1557), 'numpy.alltrue', 'np.alltrue', (['bad'], {'axis': '(1)'}), '(bad, axis=1)\n', (1544, 1557), True, 'import numpy as np\n'), ((2117, 2131), 'numpy.isscalar', 'np.isscal... |
#!/usr/bin/env python3
# Copyright 2004-present Facebook. All Rights Reserved.
import json
import unittest
from typing import List
from bidict import bidict
from scan_service.utils.hardware_config import HardwareConfig
class HardwareConfigTests(unittest.TestCase):
def setUp(self) -> None:
with open("tes... | [
"scan_service.utils.hardware_config.HardwareConfig.set_config",
"json.load",
"scan_service.utils.hardware_config.HardwareConfig.get_adjacent_beam_index",
"scan_service.utils.hardware_config.HardwareConfig.get_pwr_offset"
] | [((382, 394), 'json.load', 'json.load', (['f'], {}), '(f)\n', (391, 394), False, 'import json\n'), ((407, 449), 'scan_service.utils.hardware_config.HardwareConfig.set_config', 'HardwareConfig.set_config', (['hardware_config'], {}), '(hardware_config)\n', (432, 449), False, 'from scan_service.utils.hardware_config impor... |
import json
import os
from unittest.mock import patch, mock_open
import pytest
from signal_interpreter_server.json_parser import JsonParser
from signal_interpreter_server.exceptions import SignalError
@pytest.mark.parametrize("identifier, expected_result", [
("11", "ECU Reset"),
("99", "Not existing"),
])
... | [
"json.dump",
"signal_interpreter_server.json_parser.JsonParser",
"pytest.fixture",
"pytest.raises",
"unittest.mock.mock_open",
"pytest.mark.parametrize",
"os.path.join"
] | [((207, 312), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""identifier, expected_result"""', "[('11', 'ECU Reset'), ('99', 'Not existing')]"], {}), "('identifier, expected_result', [('11', 'ECU Reset'),\n ('99', 'Not existing')])\n", (230, 312), False, 'import pytest\n'), ((694, 725), 'pytest.fixture',... |
# web imports
from flask import Flask
from blinker import Namespace # or from flask.signals import Namespace
from flask_executor import Executor
from flask_executor.futures import Future
from flask_shell2http import Shell2HTTP
# Flask application instance
app = Flask(__name__)
# application factory
executor = Execut... | [
"blinker.Namespace",
"flask_executor.Executor",
"flask.Flask",
"flask_shell2http.Shell2HTTP"
] | [((264, 279), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (269, 279), False, 'from flask import Flask\n'), ((314, 327), 'flask_executor.Executor', 'Executor', (['app'], {}), '(app)\n', (322, 327), False, 'from flask_executor import Executor\n'), ((341, 391), 'flask_shell2http.Shell2HTTP', 'Shell2HTTP', ... |
__author__ = '<NAME>'
from threading import RLock
from bson.objectid import ObjectId
from pymongo import ASCENDING
from pymongo.errors import DuplicateKeyError as MongoDuplicateKeyError
from synergy.system import time_helper
from synergy.system.time_qualifier import *
from synergy.system.decorator import thread_safe... | [
"synergy.system.time_helper.cast_to_time_qualifier",
"bson.objectid.ObjectId",
"threading.RLock",
"synergy.db.manager.ds_manager.ds_factory",
"synergy.db.error.DuplicateKeyError",
"synergy.db.model.unit_of_work.UnitOfWork.from_json"
] | [((1138, 1145), 'threading.RLock', 'RLock', ([], {}), '()\n', (1143, 1145), False, 'from threading import RLock\n'), ((1164, 1193), 'synergy.db.manager.ds_manager.ds_factory', 'ds_manager.ds_factory', (['logger'], {}), '(logger)\n', (1185, 1193), False, 'from synergy.db.manager import ds_manager\n'), ((1750, 1780), 'sy... |
def main():
a=0
b=0
if(1<2):
a = 1
else:
a = 2
if(1>2):
b = 1
else:
b = 2
return a + b
# Boilerplate
if __name__ == "__main__":
import sys
ret=main()
sys.exit(ret)
| [
"sys.exit"
] | [((225, 238), 'sys.exit', 'sys.exit', (['ret'], {}), '(ret)\n', (233, 238), False, 'import sys\n')] |
import os
import time
import torch.optim as optim
import torch
import torch.nn.functional as F
import torch.nn as nn
from evaluation import evalFcn
from utils import myUtils
from .RawPSMNet import stackhourglass as rawPSMNet
from .RawPSMNet_TieCheng import stackhourglass as rawPSMNet_TieCheng
from ..Model import Model
... | [
"utils.myUtils.NameValues",
"utils.myUtils.assertBatchLen",
"collections.OrderedDict",
"torch.nn.AvgPool2d",
"torch.no_grad"
] | [((596, 616), 'torch.nn.AvgPool2d', 'nn.AvgPool2d', (['(2, 2)'], {}), '((2, 2))\n', (608, 616), True, 'import torch.nn as nn\n'), ((2835, 2867), 'utils.myUtils.assertBatchLen', 'myUtils.assertBatchLen', (['batch', '(8)'], {}), '(batch, 8)\n', (2857, 2867), False, 'from utils import myUtils\n'), ((2914, 2934), 'utils.my... |
# coding=utf-8
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... | [
"optax.adam",
"tensorflow_datasets.load",
"jax.nn.log_softmax",
"absl.logging.info",
"flax.serialization.register_serialization_state",
"flax.serialization.from_state_dict",
"jax.nn.one_hot",
"os.path.dirname",
"optax.apply_updates",
"haiku.data_structures.to_immutable_dict",
"haiku.Conv2D",
"... | [((1307, 1416), 'flax.serialization.register_serialization_state', 'serialization.register_serialization_state', (['HKTree', '_ty_to_state_dict', '_ty_from_state_dict'], {'override': '(True)'}), '(HKTree, _ty_to_state_dict,\n _ty_from_state_dict, override=True)\n', (1349, 1416), False, 'from flax import serializatio... |
"""
This example is for demonstartion purpose only.
No agent learns here anything useful, yet.
Well, maybe they do but it might take a long time to check.
Ain't nobody got time for that.
"""
from pettingzoo.sisl import waterworld_v3
from ai_traineree.agents.ppo import PPOAgent
from ai_traineree.multi_agents.independe... | [
"ai_traineree.tasks.PettingZooTask",
"ai_traineree.runners.multiagent_env_runner.MultiAgentCycleEnvRunner",
"pettingzoo.sisl.waterworld_v3.env",
"ai_traineree.agents.ppo.PPOAgent",
"ai_traineree.multi_agents.independent.IndependentAgents"
] | [((481, 500), 'pettingzoo.sisl.waterworld_v3.env', 'waterworld_v3.env', ([], {}), '()\n', (498, 500), False, 'from pettingzoo.sisl import waterworld_v3\n'), ((508, 531), 'ai_traineree.tasks.PettingZooTask', 'PettingZooTask', ([], {'env': 'env'}), '(env=env)\n', (522, 531), False, 'from ai_traineree.tasks import Petting... |
from unittest import TestCase
from src.PyWash import SharedDataFrame
from src.Exceptions import *
import pandas as pd
verbose = False
class TestDecorators(TestCase):
""" TestClass for SharedDataFrame methods """
def test_is_mergeable_column_names(self):
if verbose:
print("Testing: is_mer... | [
"pandas.DataFrame",
"src.PyWash.SharedDataFrame"
] | [((351, 475), 'pandas.DataFrame', 'pd.DataFrame', (["{'employee': ['Bob', 'Jake', 'Lisa', 'Sue'], 'group': ['Accounting',\n 'Engineering', 'Engineering', 'HR']}"], {}), "({'employee': ['Bob', 'Jake', 'Lisa', 'Sue'], 'group': [\n 'Accounting', 'Engineering', 'Engineering', 'HR']})\n", (363, 475), True, 'import pan... |
import os
import logging
import environ
from pathlib import Path
SUPPORTED_NONLOCALES = ['media', 'admin', 'static']
# Build paths inside the project like this: BASE_DIR / 'subdir'.
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__) + "../../../")
env = environ.Env()
# reading .env file
environ.Env.read_env(... | [
"os.path.dirname",
"os.path.join",
"environ.Env.read_env",
"environ.Env"
] | [((265, 278), 'environ.Env', 'environ.Env', ([], {}), '()\n', (276, 278), False, 'import environ\n'), ((299, 321), 'environ.Env.read_env', 'environ.Env.read_env', ([], {}), '()\n', (319, 321), False, 'import environ\n'), ((329, 360), 'environ.Env', 'environ.Env', ([], {'DEBUG': '(bool, True)'}), '(DEBUG=(bool, True))\n... |
# Generated by Django 3.1.2 on 2021-01-25 08:11
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='TwitterUser',
fields=[
... | [
"django.db.models.CharField",
"django.db.models.ForeignKey",
"django.db.models.JSONField",
"django.db.models.BooleanField",
"django.db.models.AutoField",
"django.db.models.IntegerField",
"django.db.models.DateTimeField"
] | [((340, 433), '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", (356, 433), False, 'from django.db import migrations, models\... |
from sanic import Blueprint
from sanic.response import json
info = Blueprint('info', url_prefix='/info')
@info.route("/ping")
async def ping(request):
"""
$ curl localhost:1700/info/ping
:param request:
:return:
"""
return json({ "hello": "world" })
@info.route('/env/<tag>')
async def env_han... | [
"os.environ.get",
"sanic.response.json",
"sanic.Blueprint"
] | [((68, 105), 'sanic.Blueprint', 'Blueprint', (['"""info"""'], {'url_prefix': '"""/info"""'}), "('info', url_prefix='/info')\n", (77, 105), False, 'from sanic import Blueprint\n'), ((249, 273), 'sanic.response.json', 'json', (["{'hello': 'world'}"], {}), "({'hello': 'world'})\n", (253, 273), False, 'from sanic.response ... |
from django.shortcuts import render
# Create your views here.
# -*- coding: utf-8 -*-
import json
import datetime
from DataBase import DBOPs
from django.http import HttpResponse
from chatbot import aimlKernel
def chat(request):
"""
Function:
对话接口
Args:
request: 请求
Returns:
返回... | [
"datetime.datetime.now",
"json.dumps"
] | [((809, 844), 'json.dumps', 'json.dumps', (['dic'], {'ensure_ascii': '(False)'}), '(dic, ensure_ascii=False)\n', (819, 844), False, 'import json\n'), ((917, 952), 'json.dumps', 'json.dumps', (['dic'], {'ensure_ascii': '(False)'}), '(dic, ensure_ascii=False)\n', (927, 952), False, 'import json\n'), ((662, 685), 'datetim... |
############### XML 1 - Find the Score ################
import sys
import xml.etree.ElementTree as etree
def get_attr_number(node):
# your code goes here
count = 0
for i in root.iter():
count += len(i.attrib)
return count
if __name__ == '__main__':
sys.stdin.readline()
... | [
"sys.stdin.read",
"sys.stdin.readline",
"xml.etree.ElementTree.fromstring"
] | [((298, 318), 'sys.stdin.readline', 'sys.stdin.readline', ([], {}), '()\n', (316, 318), False, 'import sys\n'), ((330, 346), 'sys.stdin.read', 'sys.stdin.read', ([], {}), '()\n', (344, 346), False, 'import sys\n'), ((377, 398), 'xml.etree.ElementTree.fromstring', 'etree.fromstring', (['xml'], {}), '(xml)\n', (393, 398)... |
#! /usr/bin/env python
from __future__ import unicode_literals
from PIL import Image
from subprocess import check_call
from concurrent import futures
import subprocess ... | [
"os.getpid",
"concurrent.futures.ProcessPoolExecutor",
"PIL.Image.open",
"subprocess.call",
"os.path.join",
"os.listdir",
"concurrent.futures.as_completed"
] | [((942, 993), 'subprocess.call', 'subprocess.call', (["('mkdir -p ' + temp_dir)"], {'shell': '(True)'}), "('mkdir -p ' + temp_dir, shell=True)\n", (957, 993), False, 'import subprocess\n'), ((1020, 1054), 'PIL.Image.open', 'Image.open', (['(in_img_dir + file_name)'], {}), '(in_img_dir + file_name)\n', (1030, 1054), Fal... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymongo
from scrapy.conf import settings
from scrapy.exceptions import DropItem
from scrapy import log
class Coinnews... | [
"pymongo.MongoClient",
"scrapy.log.msg",
"scrapy.exceptions.DropItem"
] | [((762, 797), 'pymongo.MongoClient', 'pymongo.MongoClient', (['self.mongo_uri'], {}), '(self.mongo_uri)\n', (781, 797), False, 'import pymongo\n'), ((1119, 1197), 'scrapy.log.msg', 'log.msg', (['"""Question added to MongoDB database!"""'], {'level': 'log.DEBUG', 'spider': 'spider'}), "('Question added to MongoDB databa... |
from __future__ import annotations
import asyncio
import datetime
import logging
from typing import TYPE_CHECKING
from pymongo import UpdateMany, InsertOne
from matchengine.internals.typing.matchengine_types import RunLogUpdateTask, UpdateTask, MongoQuery
from matchengine.internals.utilities.list_utils import chunk_... | [
"matchengine.internals.typing.matchengine_types.UpdateTask",
"logging.basicConfig",
"pymongo.UpdateMany",
"matchengine.internals.utilities.list_utils.chunk_list",
"matchengine.internals.typing.matchengine_types.RunLogUpdateTask",
"matchengine.internals.utilities.utilities.perform_db_call",
"matchengine.... | [((396, 435), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (415, 435), False, 'import logging\n'), ((442, 474), 'logging.getLogger', 'logging.getLogger', (['"""matchengine"""'], {}), "('matchengine')\n", (459, 474), False, 'import logging\n'), ((932, 955), 'da... |
import aquests
CONCURRENT = 50
MAX_REQ = 1000
_ID = 0
def makeload (response):
global _ID
print (response.meta ['_id'], response.code, response.msg, response.version)
if aquests.countreq () < MAX_REQ:
aquests.get ("http://127.0.0.1:5000/", meta = {'_id': _ID})
_ID += 1
def test_makeload ():
aquests.configu... | [
"aquests.fetchall",
"aquests.countreq",
"aquests.get",
"aquests.configure"
] | [((305, 353), 'aquests.configure', 'aquests.configure', (['CONCURRENT'], {'callback': 'makeload'}), '(CONCURRENT, callback=makeload)\n', (322, 353), False, 'import aquests\n'), ((479, 497), 'aquests.fetchall', 'aquests.fetchall', ([], {}), '()\n', (495, 497), False, 'import aquests\n'), ((175, 193), 'aquests.countreq',... |
import logging
import random
from . import formulas
from . import temperature
from .bond import Bond
from .bond import possible_group_bonds
from .coderack import coderack
from .correspondence import Correspondence
from .group import Group
from .letter import Letter
from .replacement import Replacement
from .slipnet im... | [
"logging.info",
"random.random",
"random.choice"
] | [((3144, 3217), 'logging.info', 'logging.info', (['f"""{weighted_strength1} > {rhs}: {weighted_strength1 > rhs}"""'], {}), "(f'{weighted_strength1} > {rhs}: {weighted_strength1 > rhs}')\n", (3156, 3217), False, 'import logging\n'), ((4100, 4139), 'logging.info', 'logging.info', (['f"""no incompatible {name}"""'], {}), ... |
import os
import math
import time
import functools
import random
from tqdm import tqdm
import cv2
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image, ImageDraw
from pylab import rcParams
rcParams['figure.figsize'] = 20, 20 # noqa
from consts import FONT_SIZE
from utils import (
make_contour... | [
"PIL.Image.new",
"grpc_utils.KuzuClassify",
"utils.make_contours",
"matplotlib.pyplot.imshow",
"utils.filter_polygons_points_intersection",
"utils.vis_pred_center",
"utils.vis_pred_bbox_polygon",
"PIL.ImageDraw.Draw",
"cv2.resize",
"functools.partial",
"math.ceil",
"numpy.asarray",
"os.listd... | [((720, 733), 'grpc_utils.KuzuSegment', 'KuzuSegment', ([], {}), '()\n', (731, 733), False, 'from grpc_utils import KuzuSegment, KuzuClassify\n'), ((749, 763), 'grpc_utils.KuzuClassify', 'KuzuClassify', ([], {}), '()\n', (761, 763), False, 'from grpc_utils import KuzuSegment, KuzuClassify\n'), ((947, 971), 'utils.make_... |
from inspect import Traceback
from signal import getsignal, SIG_IGN, SIGINT, signal as signal_, Signals
from types import FrameType
from typing import Type
class DelayedKeyboardInterrupt:
def __init__(self, in_thread: bool = False) -> None:
"""
:param in_thread: Whether or not we're living in a t... | [
"signal.signal",
"signal.getsignal"
] | [((1413, 1437), 'signal.signal', 'signal_', (['SIGINT', 'SIG_IGN'], {}), '(SIGINT, SIG_IGN)\n', (1420, 1437), True, 'from signal import getsignal, SIG_IGN, SIGINT, signal as signal_, Signals\n'), ((1168, 1185), 'signal.getsignal', 'getsignal', (['SIGINT'], {}), '(SIGINT)\n', (1177, 1185), False, 'from signal import get... |
#!/usr/bin/env python
import argparse
import os
import sys
from pathlib import Path
from typing import Any, Optional
try:
import pythoncom
from win32com.propsys import propsys
from win32com.shell import shell
except ImportError:
raise ImportError(
"pywin32 is required to run create_shell_link.... | [
"win32com.propsys.propsys.PSGetPropertyKeyFromName",
"argparse.ArgumentParser",
"win32com.propsys.propsys.PROPVARIANTType",
"pathlib.Path",
"pythoncom.CoCreateInstance",
"os.getenv",
"sys.exit"
] | [((878, 898), 'os.getenv', 'os.getenv', (['"""APPDATA"""'], {}), "('APPDATA')\n", (887, 898), False, 'import os\n'), ((1799, 1913), 'pythoncom.CoCreateInstance', 'pythoncom.CoCreateInstance', (['shell.CLSID_ShellLink', 'None', 'pythoncom.CLSCTX_INPROC_SERVER', 'shell.IID_IShellLink'], {}), '(shell.CLSID_ShellLink, None... |
from api.event import Event
from que import TT_DUMMY, TG_DC_UNBOUND
from que.utils import DEFAULT_DC, task_id_from_string
class NodeSystemRestarted(Event):
"""
Called from node_sysinfo_cb after erigonesd:fast is restarted on a compute node.
"""
_name_ = 'node_system_restarted'
def __init__(self, ... | [
"que.utils.task_id_from_string"
] | [((435, 535), 'que.utils.task_id_from_string', 'task_id_from_string', (['node.owner.id'], {'dummy': '(True)', 'dc_id': 'DEFAULT_DC', 'tt': 'TT_DUMMY', 'tg': 'TG_DC_UNBOUND'}), '(node.owner.id, dummy=True, dc_id=DEFAULT_DC, tt=\n TT_DUMMY, tg=TG_DC_UNBOUND)\n', (454, 535), False, 'from que.utils import DEFAULT_DC, ta... |
# TODO: In this module we'll start drawing a simple smiley face
# Yellow circle for the head
# Two black circle eyes
# Red rectangle (rect) mouth
# Red circle nose.
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((600, 600))
while True:
for event in pygame.event.get():
if even... | [
"pygame.draw.circle",
"pygame.event.get",
"pygame.display.set_mode",
"pygame.draw.rect",
"pygame.init",
"pygame.display.update",
"sys.exit"
] | [((197, 210), 'pygame.init', 'pygame.init', ([], {}), '()\n', (208, 210), False, 'import pygame\n'), ((220, 255), 'pygame.display.set_mode', 'pygame.display.set_mode', (['(600, 600)'], {}), '((600, 600))\n', (243, 255), False, 'import pygame\n'), ((285, 303), 'pygame.event.get', 'pygame.event.get', ([], {}), '()\n', (3... |
import os
from .cache import Cache
from .models import CacheEntry
from .utils import get_file_hash, save_file, load_file
import shutil
import io
from .compiler import ExpressionProcessor
from .expressions import stylesheets, scripts, html
import subprocess
import tempfile
class AssetCollection(object):
def __init... | [
"subprocess.Popen",
"os.remove",
"os.path.basename",
"os.path.dirname",
"os.path.exists",
"tempfile.mkdtemp",
"os.path.splitext",
"io.open",
"shutil.rmtree",
"os.path.join",
"shutil.copy"
] | [((6556, 6578), 'os.path.splitext', 'os.path.splitext', (['path'], {}), '(path)\n', (6572, 6578), False, 'import os\n'), ((7195, 7247), 'os.path.join', 'os.path.join', (['self._settings.partials', '"""stylesheets"""'], {}), "(self._settings.partials, 'stylesheets')\n", (7207, 7247), False, 'import os\n'), ((7836, 7854)... |
from itertools import product
alpha = ['A', 'T', 'C', 'G']
motifs = [a+b+c+d+e+f+g for a,b,c,d,e,f,g in product(alpha, repeat=7)]
with open('motifs7.txt', 'w') as f:
for item in motifs:
f.write("%s\n" % item)
| [
"itertools.product"
] | [((105, 129), 'itertools.product', 'product', (['alpha'], {'repeat': '(7)'}), '(alpha, repeat=7)\n', (112, 129), False, 'from itertools import product\n')] |
import networkx as nx
graph = nx.DiGraph()
nodes = [f"{i}" for i in range(1, 13)]
nodes.extend([chr(i) for i in range(1, 13)])
graph.add_nodes_from([])
class Node:
def __init__(self, name, direct, sig):
self.name = name
self.direct = direct
self.sig = sig
class Edge:
def __init__(se... | [
"networkx.DiGraph"
] | [((31, 43), 'networkx.DiGraph', 'nx.DiGraph', ([], {}), '()\n', (41, 43), True, 'import networkx as nx\n')] |
import unittest
from datastructure.links.Node import Node
def from_second(head):
if head is None:
raise ValueError("Linked list is empty")
return head._next
class MyTestCase(unittest.TestCase):
def test_something(self):
head = Node(0, None)
current = head
for i in range(1... | [
"unittest.main",
"datastructure.links.Node.Node"
] | [((697, 712), 'unittest.main', 'unittest.main', ([], {}), '()\n', (710, 712), False, 'import unittest\n'), ((259, 272), 'datastructure.links.Node.Node', 'Node', (['(0)', 'None'], {}), '(0, None)\n', (263, 272), False, 'from datastructure.links.Node import Node\n'), ((349, 362), 'datastructure.links.Node.Node', 'Node', ... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from numpy.testing import assert_allclose, assert_equal
import astropy.units as u
from astropy.table import Table
from gammapy.astro.population import (
add_observed_parameters,
add_pulsar_parameters,
add_pwn_parameters,
add_snr_parameters,... | [
"gammapy.astro.population.make_catalog_random_positions_cube",
"astropy.table.Table",
"astropy.units.Quantity",
"gammapy.astro.population.add_observed_parameters",
"gammapy.astro.population.make_base_catalog_galactic",
"gammapy.astro.population.add_pulsar_parameters",
"gammapy.astro.population.add_pwn_p... | [((498, 548), 'gammapy.astro.population.make_catalog_random_positions_cube', 'make_catalog_random_positions_cube', ([], {'random_state': '(0)'}), '(random_state=0)\n', (532, 548), False, 'from gammapy.astro.population import add_observed_parameters, add_pulsar_parameters, add_pwn_parameters, add_snr_parameters, make_ba... |
"""Class definition for the DataSetParser ABC and FeaturizerMixin."""
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Callable, Generator, List, Tuple, Type
import numpy as np
import pandas as pd
from sklearn.preprocessing import RobustScaler
class FeaturizerMixin:
"""Mixin to pr... | [
"pandas.concat",
"pandas.api.types.is_numeric_dtype"
] | [((8026, 8063), 'pandas.api.types.is_numeric_dtype', 'pd.api.types.is_numeric_dtype', (['series'], {}), '(series)\n', (8055, 8063), True, 'import pandas as pd\n'), ((2326, 2402), 'pandas.concat', 'pd.concat', (['[self.metafeatures, *sec_metafeatures]'], {'axis': '(1)', 'ignore_index': '(True)'}), '([self.metafeatures, ... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
class MLP(nn.Module):
def __init__(self, MLPInfo, activation='PReLU', PReLuInit=0.25, isUseBN=True, dropoutRate=0.0, initStd=0.0001):
super(MLP, self).__init__()
self.multiLayerPerceptro... | [
"torch.nn.Dropout",
"torch.repeat_interleave",
"torch.nn.PReLU",
"torch.nn.ModuleList",
"torch.nn.Embedding",
"torch.unsqueeze",
"torch.FloatTensor",
"torch.cat",
"torch.nn.BatchNorm1d",
"torch.mul",
"torch.nn.Linear",
"torch.nn.ModuleDict",
"torch.device",
"torch.zeros",
"torch.sum"
] | [((324, 339), 'torch.nn.ModuleList', 'nn.ModuleList', ([], {}), '()\n', (337, 339), True, 'import torch.nn as nn\n'), ((1162, 1181), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (1174, 1181), False, 'import torch\n'), ((1283, 1298), 'torch.nn.ModuleDict', 'nn.ModuleDict', ([], {}), '()\n', (1296, 1... |
#!/usr/bin/env python3
# Copyright 2020 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import re
import unittest
from cros.factory.probe.runtime_probe import probe_config_types
from cros.factory.utils import json_util... | [
"unittest.main",
"cros.factory.probe.runtime_probe.probe_config_types.ProbeStatementDefinitionBuilder",
"cros.factory.probe.runtime_probe.probe_config_types.ComponentProbeStatement",
"cros.factory.probe.runtime_probe.probe_config_types.ComponentProbeStatement.FromDict",
"cros.factory.probe.runtime_probe.pro... | [((15538, 15553), 'unittest.main', 'unittest.main', ([], {}), '()\n', (15551, 15553), False, 'import unittest\n'), ((447, 511), 'cros.factory.probe.runtime_probe.probe_config_types.ProbeStatementDefinitionBuilder', 'probe_config_types.ProbeStatementDefinitionBuilder', (['"""category_x"""'], {}), "('category_x')\n", (49... |
# Generated by Django 2.2.7 on 2019-11-19 21:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('submissions', '0006_merge_20191113_0542'),
]
operations = [
migrations.CreateModel(
name='SubmissionTag',
fields=[
... | [
"django.db.models.CharField",
"django.db.models.ManyToManyField",
"django.db.models.AutoField"
] | [((642, 717), 'django.db.models.ManyToManyField', 'models.ManyToManyField', ([], {'to': '"""submissions.SubmissionTag"""', 'verbose_name': '"""tags"""'}), "(to='submissions.SubmissionTag', verbose_name='tags')\n", (664, 717), False, 'from django.db import migrations, models\n'), ((342, 435), 'django.db.models.AutoField... |
import numpy as np
import matplotlib.pyplot as plt
PI = np.pi
# =========================define sinc
# ---------------normalized
def sinc1(x):
PI = np.pi
x = np.array(x)
y = np.where(np.abs(PI * x) < 1e-38, 1.0, np.sin(PI * x) / (PI * x))
return y
def sinc_interpolation(x, t, T):
ns = np.arange... | [
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show",
"numpy.abs",
"matplotlib.pyplot.plot",
"numpy.fft.fft",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.figure",
"numpy.sin",
"numpy.array",
"numpy.arange",
"numpy.linspace",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matp... | [((556, 580), 'numpy.linspace', 'np.linspace', (['(-10)', '(10)', 'Ns'], {}), '(-10, 10, Ns)\n', (567, 580), True, 'import numpy as np\n'), ((586, 614), 'numpy.linspace', 'np.linspace', (['(-10)', '(10)', '(Ns * 2)'], {}), '(-10, 10, Ns * 2)\n', (597, 614), True, 'import numpy as np\n'), ((640, 663), 'numpy.sin', 'np.s... |
from string import ascii_lowercase
import functools
from itertools import combinations
def generate_binary(n):
"""
Function returns generator with binary sequences of a set length
:param n: length of a binary sequence
:return: generator with binary sequence
"""
if n == 0:
yield ""
... | [
"functools.reduce",
"itertools.combinations"
] | [((5435, 5488), 'functools.reduce', 'functools.reduce', (["(lambda x, y: x + '^' + y)", 'variables'], {}), "(lambda x, y: x + '^' + y, variables)\n", (5451, 5488), False, 'import functools\n'), ((6496, 6529), 'itertools.combinations', 'combinations', (['expressions_list', 'a'], {}), '(expressions_list, a)\n', (6508, 65... |
# Generated by Django 3.2.6 on 2021-09-08 14:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bjorn', '0009_auto_20210908_1427'),
]
operations = [
migrations.AlterField(
model_name='certificate',
name='revocati... | [
"django.db.models.PositiveSmallIntegerField"
] | [((350, 675), 'django.db.models.PositiveSmallIntegerField', 'models.PositiveSmallIntegerField', ([], {'blank': '(True)', 'choices': "[(1, 'Unspecified'), (2, 'Key compromise'), (3, 'CA compromise'), (4,\n 'Affiliation changed'), (5, 'Superseded'), (6, 'Cessation of operation'\n ), (7, 'Certificate hold'), (8, 'Re... |
########################## THE TOON LAND PROJECT ##########################
# Filename: HackerCrypt.py
# Created by: Cody/Fd Green Cat Fd (January 31st, 2013)
####
# Description:
#
# Encryption method written by Team FD in 2011 for their personal releases.
# The script has been modified to meet Toon Land's coding stand... | [
"binascii.hexlify",
"base64.b64decode",
"bz2.compress",
"binascii.unhexlify",
"base64.b64encode",
"zlib.decompress",
"random.randrange",
"sha.sha"
] | [((1437, 1452), 'base64.b64encode', 'b64encode', (['data'], {}), '(data)\n', (1446, 1452), False, 'from base64 import b64encode, b64decode\n'), ((1467, 1479), 'binascii.hexlify', 'hexlify', (['b64'], {}), '(b64)\n', (1474, 1479), False, 'from binascii import hexlify, unhexlify\n'), ((1910, 1928), 'binascii.unhexlify', ... |
"""scrapli_cfg.platform.core.arista_eos.base"""
import json
import re
from datetime import datetime
from logging import LoggerAdapter
from typing import Iterable, List, Tuple, Union
from scrapli.driver import AsyncNetworkDriver, NetworkDriver
from scrapli.response import Response
from scrapli_cfg.exceptions import Scr... | [
"scrapli_cfg.response.ScrapliCfgResponse",
"json.loads",
"datetime.datetime.now",
"re.findall",
"re.search",
"re.sub"
] | [((1125, 1181), 're.search', 're.search', ([], {'pattern': 'VERSION_PATTERN', 'string': 'device_output'}), '(pattern=VERSION_PATTERN, string=device_output)\n', (1134, 1181), False, 'import re\n'), ((2794, 2862), 're.sub', 're.sub', ([], {'pattern': 'GLOBAL_COMMENT_LINE_PATTERN', 'repl': '"""!"""', 'string': 'config'}),... |
# -*- coding: utf-8 -*-
import time
# !! This is the configuration of Nikola. !! #
# !! You should edit it to your liking. !! #
# Data about this site
BLOG_AUTHOR = "<NAME>" # (translatable)
BLOG_TITLE = "My Nikola Site" # (translatable)
# This is the main URL for your site. It will be used
# in a prominent link... | [
"time.gmtime"
] | [((12867, 12880), 'time.gmtime', 'time.gmtime', ([], {}), '()\n', (12878, 12880), False, 'import time\n')] |
""" Tests for GSPDataSource """
import os
from datetime import datetime
import pandas as pd
import nowcasting_dataset
from nowcasting_dataset.data_sources.gsp.gsp_data_source import (
GSPDataSource,
drop_gsp_north_of_boundary,
)
from nowcasting_dataset.geospatial import osgb_to_lat_lon
def test_gsp_pv_data_... | [
"nowcasting_dataset.data_sources.gsp.gsp_data_source.drop_gsp_north_of_boundary",
"pandas.Timestamp",
"nowcasting_dataset.geospatial.osgb_to_lat_lon",
"os.path.dirname",
"datetime.datetime"
] | [((1572, 1613), 'nowcasting_dataset.geospatial.osgb_to_lat_lon', 'osgb_to_lat_lon', (['locations_x', 'locations_y'], {}), '(locations_x, locations_y)\n', (1587, 1613), False, 'from nowcasting_dataset.geospatial import osgb_to_lat_lon\n'), ((3490, 3510), 'datetime.datetime', 'datetime', (['(2020)', '(4)', '(1)'], {}), '... |
# coding=utf-8
# Copyright (C) 2019 Alibaba Group Holding Limited
#
# 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 app... | [
"torch.nn.functional.dropout"
] | [((1432, 1473), 'torch.nn.functional.dropout', 'f.dropout', (['x', 'self.dropout', 'self.training'], {}), '(x, self.dropout, self.training)\n', (1441, 1473), True, 'import torch.nn.functional as f\n'), ((1351, 1392), 'torch.nn.functional.dropout', 'f.dropout', (['x', 'self.dropout', 'self.training'], {}), '(x, self.dro... |
import argparse
import os
import draw_his
import train
import test
from get_data import import_data
from model_zoo import googLeNet, resnet, load_model
import utils
import ensembel_model
def str2bool(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f',... | [
"draw_his.draw_his",
"model_zoo.load_model.load_model",
"argparse.ArgumentParser",
"os.path.realpath",
"test.test",
"get_data.import_data.import_dataset",
"utils.ResNetUtils",
"model_zoo.load_model.save_model",
"train.train",
"argparse.ArgumentTypeError"
] | [((442, 467), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (465, 467), False, 'import argparse\n'), ((2142, 2161), 'utils.ResNetUtils', 'utils.ResNetUtils', ([], {}), '()\n', (2159, 2161), False, 'import utils\n'), ((2391, 2514), 'model_zoo.load_model.load_model', 'load_model.load_model', ([]... |
from subprocess import CalledProcessError, check_call, DEVNULL
from typing import Any, List, Sequence
import dotbot
class Apt(dotbot.Plugin):
def can_handle(self, directive: str) -> bool:
return directive == "apt"
def handle(self, directive: str, packages: List[str]) -> bool:
success = self.... | [
"subprocess.check_call"
] | [((782, 833), 'subprocess.check_call', 'check_call', (['command'], {'stdout': 'DEVNULL', 'stderr': 'DEVNULL'}), '(command, stdout=DEVNULL, stderr=DEVNULL)\n', (792, 833), False, 'from subprocess import CalledProcessError, check_call, DEVNULL\n')] |
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 10)
y = np.sin(x) #Función original
xvals = np.linspace(0, 2*np.pi, 50)
yinterp = np.interp(xvals, x, y)
plt.plot(x, y, 'o')
plt.plot(xvals, yinterp, '-x')
plt.show() | [
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"numpy.sin",
"numpy.linspace",
"numpy.interp"
] | [((56, 85), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * np.pi)', '(10)'], {}), '(0, 2 * np.pi, 10)\n', (67, 85), True, 'import numpy as np\n'), ((88, 97), 'numpy.sin', 'np.sin', (['x'], {}), '(x)\n', (94, 97), True, 'import numpy as np\n'), ((124, 153), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * np.pi)', '(50)... |
from django.conf.urls import patterns, include, url
from django.views.generic.simple import direct_to_template
from .views import SubmissionView, SubmissionListView, SubmissionSuccess
urlpatterns = patterns('',
url(r'^$',
SubmissionView.as_view(),
name='submission',
),
url(r'^success/$',
... | [
"django.conf.urls.url"
] | [((403, 490), 'django.conf.urls.url', 'url', (['"""^end/$"""', 'direct_to_template', "{'template': 'submission/end.html'}"], {'name': '"""end"""'}), "('^end/$', direct_to_template, {'template': 'submission/end.html'}, name\n ='end')\n", (406, 490), False, 'from django.conf.urls import patterns, include, url\n'), ((6... |
import pytest
from fixtures import get_title, get_url
from craigslist_meta import Site
selector = "area"
# use a site key with areas
site_key = "sfbay"
@pytest.fixture
def area():
"""Get an instance of Area."""
area = next(iter(Site(site_key)))
global area_key
area_key = area.key
yield area
def... | [
"fixtures.get_title",
"pytest.raises",
"fixtures.get_url",
"craigslist_meta.Site"
] | [((586, 615), 'fixtures.get_title', 'get_title', (['selector', 'area_key'], {}), '(selector, area_key)\n', (595, 615), False, 'from fixtures import get_title, get_url\n'), ((779, 806), 'fixtures.get_url', 'get_url', (['selector', 'area_key'], {}), '(selector, area_key)\n', (786, 806), False, 'from fixtures import get_t... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
import os
import argparse
import numpy as np
import mxnet as mx
ctx = mx.cpu(0)
image_size = (112, 112)
prefix = "../models/resnet-50"
epoch = 0
sym, arg_params, aux_params = mx.model.load_checkpoi... | [
"mxnet.model.save_checkpoint",
"mxnet.model.load_checkpoint",
"mxnet.cpu",
"mxnet.viz.plot_network"
] | [((193, 202), 'mxnet.cpu', 'mx.cpu', (['(0)'], {}), '(0)\n', (199, 202), True, 'import mxnet as mx\n'), ((298, 337), 'mxnet.model.load_checkpoint', 'mx.model.load_checkpoint', (['prefix', 'epoch'], {}), '(prefix, epoch)\n', (322, 337), True, 'import mxnet as mx\n'), ((594, 664), 'mxnet.model.save_checkpoint', 'mx.model... |
from flying_ioc import IocManager, IocFactory
class TSingleton1:
def __init__(self):
pass
class TSingleton2:
def __init__(self):
pass
class TSingleton3(TSingleton1):
def __init__(self, ts: TSingleton2):
super().__init__()
self.ts = ts
class TSingleton3dot2(TSingleton3... | [
"flying_ioc.IocManager"
] | [((966, 988), 'flying_ioc.IocManager', 'IocManager', ([], {'stats': '(True)'}), '(stats=True)\n', (976, 988), False, 'from flying_ioc import IocManager, IocFactory\n')] |
from time import time
from hashlib import md5
from datetime import datetime
## Hashing functions:
# Slower, 64 bytes
#sha256 = sha256('content').hexdigest()
# Faster, 32 bytes
#md5 = md5('content').hexdigest()
class Block:
timestamp = ''
prev_hash = ''
content = ''
nonce = 0
hash = ''
def _... | [
"datetime.datetime.now",
"time.time"
] | [((2495, 2501), 'time.time', 'time', ([], {}), '()\n', (2499, 2501), False, 'from time import time\n'), ((2551, 2557), 'time.time', 'time', ([], {}), '()\n', (2555, 2557), False, 'from time import time\n'), ((862, 876), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (874, 876), False, 'from datetime import ... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
class Distance:
def __init__(self):
self.graph = tf.Graph()
self.sess = tf.Session(graph=self.graph)
with self.graph.as_default():
self.b_tf = t... | [
"tensorflow.placeholder",
"tensorflow.Session",
"tensorflow.Graph",
"tensorflow.expand_dims"
] | [((197, 207), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (205, 207), True, 'import tensorflow as tf\n'), ((228, 256), 'tensorflow.Session', 'tf.Session', ([], {'graph': 'self.graph'}), '(graph=self.graph)\n', (238, 256), True, 'import tensorflow as tf\n'), ((319, 370), 'tensorflow.placeholder', 'tf.placeholder',... |
#!/usr/bin/env python
# Copyright (c) 2015 - 2017, Intel Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | [
"unittest.mock.MagicMock",
"testlib.linux.networkd.NetworkD"
] | [((838, 849), 'unittest.mock.MagicMock', 'MagicMock', ([], {}), '()\n', (847, 849), False, 'from unittest.mock import MagicMock\n'), ((862, 893), 'testlib.linux.networkd.NetworkD', 'NetworkD', (['run_command', "['test']"], {}), "(run_command, ['test'])\n", (870, 893), False, 'from testlib.linux.networkd import NetworkD... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: batch_get_tool_detail.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from googl... | [
"google.protobuf.symbol_database.Default",
"google.protobuf.descriptor.FieldDescriptor",
"google.protobuf.reflection.GeneratedProtocolMessageType"
] | [((475, 501), 'google.protobuf.symbol_database.Default', '_symbol_database.Default', ([], {}), '()\n', (499, 501), True, 'from google.protobuf import symbol_database as _symbol_database\n'), ((6824, 7010), 'google.protobuf.reflection.GeneratedProtocolMessageType', '_reflection.GeneratedProtocolMessageType', (['"""Batch... |
"""
TODO
"""
import io
import logging
import re
import string
import sys
import textwrap
import time
from datetime import timedelta
from pathlib import Path
from typing import List
import sublib
from deep_translator import GoogleTranslator
# https://pypi.org/project/sublib/
# https://pypi.org/project/deep-translator
... | [
"textwrap.dedent",
"logging.error",
"logging.debug",
"re.split",
"logging.basicConfig",
"re.finditer",
"deep_translator.GoogleTranslator",
"time.time",
"logging.info",
"pathlib.Path",
"datetime.timedelta",
"sublib.SubRip",
"sys.exit"
] | [((384, 409), 'pathlib.Path', 'Path', (['"""input/1_short.srt"""'], {}), "('input/1_short.srt')\n", (388, 409), False, 'from pathlib import Path\n'), ((435, 626), 'textwrap.dedent', 'textwrap.dedent', (['""" 1\n 00:00:00,123 --> 00:00:03,456\n Hi there\n \n 2\n 00:01:04,843 --> 00:01:05,428\n This ... |
import os
from src.ezcord import *
APP = 874663148374880287
TEST = 877399405056102431
bot = Bot(prefix='-', app_id=APP, guild_id=TEST, intents=Intents.members)
@bot.command(name='ping')
async def ping(ctx: Context):
emd = Embed(description=f'**Pong: {bot.latency}ms**')
await ctx.reply(embed=emd)
@bot.co... | [
"os.getenv"
] | [((527, 553), 'os.getenv', 'os.getenv', (['"""DISCORD_TOKEN"""'], {}), "('DISCORD_TOKEN')\n", (536, 553), False, 'import os\n')] |
from kaiba.models.kaiba_object import KaibaObject
def test_create_jsonschema_from_model():
"""Test that we can create jsonschema."""
assert KaibaObject.schema_json(indent=2)
| [
"kaiba.models.kaiba_object.KaibaObject.schema_json"
] | [((150, 183), 'kaiba.models.kaiba_object.KaibaObject.schema_json', 'KaibaObject.schema_json', ([], {'indent': '(2)'}), '(indent=2)\n', (173, 183), False, 'from kaiba.models.kaiba_object import KaibaObject\n')] |
import csv
import statistics
from matplotlib import pyplot as plt
from scipy.interpolate import interp1d
import numpy as np
with open('pknorlen_akcje.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
next(readCSV)
counter = 0
kursy_lista = []
for row in readCSV:
kursy_lista.app... | [
"csv.reader",
"matplotlib.pyplot.show",
"statistics.stdev",
"statistics.mean",
"scipy.interpolate.interp1d"
] | [((824, 859), 'scipy.interpolate.interp1d', 'interp1d', (['x_es', 'y_es'], {'kind': '"""linear"""'}), "(x_es, y_es, kind='linear')\n", (832, 859), False, 'from scipy.interpolate import interp1d\n'), ((990, 1000), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (998, 1000), True, 'from matplotlib import pyplot a... |
import os
import csv
from csv import reader
def read_data():
data = []
with open ("data.csv", "r") as f:
csv_reader = reader(f)
header = next(csv_reader)
if header != None:
for rows in csv_reader:
data.append(rows[0].replace(";",","))
print(data)
... | [
"csv.reader"
] | [((135, 144), 'csv.reader', 'reader', (['f'], {}), '(f)\n', (141, 144), False, 'from csv import reader\n')] |
from bs4 import BeautifulSoup as bs
import re
import mysql.connector
class Products_Infos():
def __init__(self, products):
self.products = products
self.productInfos = []
def insertSpaces(self):
for i in self.products:
self.productInfos.append([])
def get_product_lin... | [
"re.compile"
] | [((1082, 1113), 're.compile', 're.compile', (['"""pdp_options__text"""'], {}), "('pdp_options__text')\n", (1092, 1113), False, 'import re\n'), ((2126, 2166), 're.compile', 're.compile', (['"""https://http2.mlstatic.com"""'], {}), "('https://http2.mlstatic.com')\n", (2136, 2166), False, 'import re\n')] |
import re
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileAllowed, FileRequired
from wtforms import StringField, TextAreaField, SubmitField
from wtforms.validators import DataRequired, regexp
class ArticleForm(FlaskForm):
title = StringField('Название статьи', validators=[DataRequired()... | [
"wtforms.SubmitField",
"flask_wtf.file.FileAllowed",
"wtforms.validators.DataRequired",
"flask_wtf.file.FileRequired"
] | [((659, 685), 'wtforms.SubmitField', 'SubmitField', (['"""Подтвердить"""'], {}), "('Подтвердить')\n", (670, 685), False, 'from wtforms import StringField, TextAreaField, SubmitField\n'), ((320, 334), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (332, 334), False, 'from wtforms.validators import ... |
"""Wrapper around ZMQStream
"""
import sys
import time
import zmq
from zmq.eventloop import IOLoop
from zmq.eventloop.zmqstream import ZMQStream
import skytools
from cc.message import CCMessage, zmsg_size
from cc.util import stat_inc
__all__ = ['CCStream', 'CCReqStream']
#
# simple wrapper around ZMQStream
#
cla... | [
"time.time",
"skytools.getLogger",
"zmq.Context.instance",
"cc.util.stat_inc",
"cc.message.CCMessage",
"zmq.eventloop.IOLoop.instance",
"cc.message.zmsg_size"
] | [((1516, 1547), 'skytools.getLogger', 'skytools.getLogger', (['"""QueryInfo"""'], {}), "('QueryInfo')\n", (1534, 1547), False, 'import skytools\n'), ((2925, 2958), 'skytools.getLogger', 'skytools.getLogger', (['"""CCReqStream"""'], {}), "('CCReqStream')\n", (2943, 2958), False, 'import skytools\n'), ((5219, 5234), 'cc.... |