code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import errno
from json import loads as json_loads, dumps as json_dumps
try:
import requests
from requests.cookies import RequestsCookieJar
except ImportError:
print("Python module requests is required. Run this in your terminal:")
print("$ pip3 install requests")
exit(errno.ENOPKG)
try:
from r... | [
"requests.request",
"json.loads",
"json.dumps",
"requests.cookies.RequestsCookieJar"
] | [((4049, 4218), 'requests.request', 'requests.request', ([], {'method': 'method', 'url': 'url', 'params': 'params', 'headers': 'headers', 'cookies': 'cookies', 'data': 'data', 'timeout': 'timeout', 'allow_redirects': 'allow_redirects'}), '(method=method, url=url, params=params, headers=headers,\n cookies=cookies, da... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from service_spec import DSSMService_pb2 as service__spec_dot_DSSMService__pb2
class DSSMStub(object):
# missing associated documentation comment in .proto file
pass
def __init__(self, channel):
"""Constructor.
Args:
... | [
"grpc.method_handlers_generic_handler",
"grpc.unary_unary_rpc_method_handler"
] | [((1413, 1478), 'grpc.method_handlers_generic_handler', 'grpc.method_handlers_generic_handler', (['"""DSSM"""', 'rpc_method_handlers'], {}), "('DSSM', rpc_method_handlers)\n", (1449, 1478), False, 'import grpc\n'), ((1118, 1362), 'grpc.unary_unary_rpc_method_handler', 'grpc.unary_unary_rpc_method_handler', (['servicer.... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-10-22 17:13
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('accounts', '0003_user_assigned_room'),
]
operation... | [
"django.db.models.ForeignKey"
] | [((433, 545), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'blank': '(True)', 'null': '(True)', 'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""accounts.School"""'}), "(blank=True, null=True, on_delete=django.db.models.\n deletion.CASCADE, to='accounts.School')\n", (450, 545), False, 'from d... |
# Licensed under the terms of http://www.apache.org/licenses/LICENSE-2.0
# Author/s (©): <NAME>
from math import sqrt
import chunk
import logging
import colorsys
import mcpi.block
from mcpi.vec3 import Vec3
from mcthings.thing import Thing
class Voxel:
def __init__(self, bytes):
self.x = bytes[0]
... | [
"logging.info",
"mcpi.vec3.Vec3",
"chunk.Chunk"
] | [((10642, 10680), 'chunk.Chunk', 'chunk.Chunk', (['vox_file'], {'bigendian': '(False)'}), '(vox_file, bigendian=False)\n', (10653, 10680), False, 'import chunk\n'), ((11710, 11748), 'chunk.Chunk', 'chunk.Chunk', (['vox_file'], {'bigendian': '(False)'}), '(vox_file, bigendian=False)\n', (11721, 11748), False, 'import ch... |
from __future__ import division, print_function, absolute_import, unicode_literals
import pytz
import httplib2
from apiclient import discovery
import oauth2client.file
from calendar_cli.model import Event
MAX_RESULTS = 100
class GoogleCalendarService(object):
def __init__(self, credential_path):
store =... | [
"httplib2.Http",
"apiclient.discovery.build",
"calendar_cli.model.Event.parse_dict"
] | [((796, 840), 'apiclient.discovery.build', 'discovery.build', (['"""calendar"""', '"""v3"""'], {'http': 'http'}), "('calendar', 'v3', http=http)\n", (811, 840), False, 'from apiclient import discovery\n'), ((761, 776), 'httplib2.Http', 'httplib2.Http', ([], {}), '()\n', (774, 776), False, 'import httplib2\n'), ((1461, ... |
import mock
def test_setup(GPIO, ST7789, displayhatmini):
display = displayhatmini.DisplayHATMini(bytearray())
GPIO.setup.assert_has_calls((
mock.call(display.BUTTON_A, GPIO.IN, pull_up_down=GPIO.PUD_UP),
mock.call(display.BUTTON_B, GPIO.IN, pull_up_down=GPIO.PUD_UP),
mock.call(displa... | [
"mock.call"
] | [((160, 222), 'mock.call', 'mock.call', (['display.BUTTON_A', 'GPIO.IN'], {'pull_up_down': 'GPIO.PUD_UP'}), '(display.BUTTON_A, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n', (169, 222), False, 'import mock\n'), ((232, 294), 'mock.call', 'mock.call', (['display.BUTTON_B', 'GPIO.IN'], {'pull_up_down': 'GPIO.PUD_UP'}), '(display... |
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
def plot_images(images, targets, n_plot=30):
n_rows = n_plot // 10 + ((n_plot % 10) > 0)
fig, axes = plt.subplots(n_rows, 10, figsize=(15, 1.5 * n_rows))
axes = np.atleast_2d(axes)
for i, (image, target) in enumerate(z... | [
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.style.use",
"matplotlib.pyplot.subplots",
"numpy.atleast_2d"
] | [((51, 83), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""fivethirtyeight"""'], {}), "('fivethirtyeight')\n", (64, 83), True, 'import matplotlib.pyplot as plt\n'), ((194, 246), 'matplotlib.pyplot.subplots', 'plt.subplots', (['n_rows', '(10)'], {'figsize': '(15, 1.5 * n_rows)'}), '(n_rows, 10, figsize=(15, 1.5 *... |
#!/usr/bin/python3
import json
from pathlib import Path
import pytest
test_source = """
def test_stuff(BrownieTester, accounts):
c = accounts[0].deploy(BrownieTester, True)
c.doNothing({'from': accounts[0]})"""
def test_update_no_isolation(plugintester):
result = plugintester.runpytest()
result.ass... | [
"json.dump",
"pytest.mark.parametrize",
"pathlib.Path",
"json.load"
] | [((425, 469), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""arg"""', "['', '-n 2']"], {}), "('arg', ['', '-n 2'])\n", (448, 469), False, 'import pytest\n'), ((688, 732), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""arg"""', "['', '-n 2']"], {}), "('arg', ['', '-n 2'])\n", (711, 732), False,... |
import os
import sys
import h5py
import numpy as np
import pandas as pd
import networkx as nx
from convert import make_adjacency, make_sparse_adjacency, save_problem, spadj2edgelist
np.random.seed(123)
def load_ages(path):
ages = pd.read_csv(path, header=None, sep='\t')
ages.columns = ('id', 'age')
a... | [
"numpy.random.seed",
"convert.make_adjacency",
"convert.save_problem",
"pandas.read_csv",
"pandas.merge",
"numpy.zeros",
"numpy.hstack",
"numpy.arange",
"numpy.array",
"numpy.random.choice",
"os.path.join",
"convert.spadj2edgelist",
"convert.make_sparse_adjacency"
] | [((183, 202), 'numpy.random.seed', 'np.random.seed', (['(123)'], {}), '(123)\n', (197, 202), True, 'import numpy as np\n'), ((848, 872), 'numpy.arange', 'np.arange', (['ages.shape[0]'], {}), '(ages.shape[0])\n', (857, 872), True, 'import numpy as np\n'), ((882, 933), 'pandas.merge', 'pd.merge', (['edges', 'ages'], {'le... |
from models import MADVAE, Classifier
from torchvision import datasets, transforms
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import argparse
import torch.optim as optim
import numpy as np
import os
import sys
import json
parser = argparse.ArgumentParser()
parser.add_argument('--epochs',
... | [
"json.dump",
"argparse.ArgumentParser",
"torch.utils.data.DataLoader",
"torch.sum",
"torch.load",
"torch.logical_not",
"torch.cat",
"models.MADVAE",
"models.Classifier",
"torch.cuda.is_available",
"torch.all",
"torchvision.transforms.CenterCrop",
"torch.no_grad",
"torchvision.datasets.MNIS... | [((256, 281), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (279, 281), False, 'import argparse\n'), ((2581, 2654), 'torchvision.datasets.MNIST', 'datasets.MNIST', (['"""./data"""'], {'train': '(False)', 'download': '(True)', 'transform': 'transform'}), "('./data', train=False, download=True, ... |
"""
You must follow the steps on: https://confluence.ecmwf.int/display/WEBAPI/Access+ECMWF+Public+Datasets
If you will face some problems, ecmwf provides reasons and solutions on their website for any problem.
Here is a short list of things you will need to do for this script to work:
1. Make an account on ecmwf.
... | [
"netCDF4.Dataset",
"matplotlib.pyplot.show",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"viroconcom.dataECMWF.ECMWF"
] | [((1128, 1193), 'viroconcom.dataECMWF.ECMWF', 'ECMWF', (['"""00:00:00"""', '"""0.75/0.75"""', '"""75/-20/10/60"""', '"""229.140/232.140"""'], {}), "('00:00:00', '0.75/0.75', '75/-20/10/60', '229.140/232.140')\n", (1133, 1193), False, 'from viroconcom.dataECMWF import ECMWF\n'), ((1318, 1357), 'netCDF4.Dataset', 'netCDF... |
import hive_config
import requests
import sys
import json
import time
import datetime
from thehive4py.api import TheHiveApi
from thehive4py.models import Case, CustomFieldHelper
def newcase(args):
api = TheHiveApi('http://'+hive_config.url+':'+hive_config.port, hive_config.apikey)
avlink="https:/... | [
"sys.exit",
"datetime.date.today",
"thehive4py.models.CustomFieldHelper",
"thehive4py.api.TheHiveApi"
] | [((221, 309), 'thehive4py.api.TheHiveApi', 'TheHiveApi', (["('http://' + hive_config.url + ':' + hive_config.port)", 'hive_config.apikey'], {}), "('http://' + hive_config.url + ':' + hive_config.port,\n hive_config.apikey)\n", (231, 309), False, 'from thehive4py.api import TheHiveApi\n'), ((1057, 1068), 'sys.exit', ... |
# coding: utf-8
from eve import Eve
from flask import request, jsonify
from pymongo import MongoClient
import dijkstra
client = MongoClient('mongodb://0.0.0.0:27017')
db = client.tsp_rest_api
collection = db.maps
app = Eve()
@app.route('/maps/shortest', methods=['GET'])
def getCollection():
mapName = request.a... | [
"pymongo.MongoClient",
"flask.request.args.get",
"eve.Eve",
"dijkstra.Graph",
"flask.jsonify",
"dijkstra.shortest"
] | [((131, 169), 'pymongo.MongoClient', 'MongoClient', (['"""mongodb://0.0.0.0:27017"""'], {}), "('mongodb://0.0.0.0:27017')\n", (142, 169), False, 'from pymongo import MongoClient\n'), ((222, 227), 'eve.Eve', 'Eve', ([], {}), '()\n', (225, 227), False, 'from eve import Eve\n'), ((311, 334), 'flask.request.args.get', 'req... |
"""
Create several custom encoders and test that they work
"""
# stdlib
import collections
from datetime import date, datetime, time, timedelta
from decimal import Decimal
from fractions import Fraction
# 3rd party
import pytest
import pytz # type: ignore
# this package
import sdjson
def test_decimal_float() -> N... | [
"datetime.date",
"datetime.datetime",
"sdjson.encoders.unregister",
"collections.namedtuple",
"datetime.timedelta",
"sdjson.encoders.register",
"datetime.time",
"fractions.Fraction",
"sdjson.dumps",
"pytest.mark.xfail"
] | [((5469, 5528), 'pytest.mark.xfail', 'pytest.mark.xfail', ([], {'reason': '"""Not implemented in CPython yet."""'}), "(reason='Not implemented in CPython yet.')\n", (5486, 5528), False, 'import pytest\n'), ((406, 439), 'sdjson.encoders.register', 'sdjson.encoders.register', (['Decimal'], {}), '(Decimal)\n', (430, 439),... |
# Generated by Django 3.2.6 on 2021-08-10 07:45
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... | [
"django.db.models.TextField",
"django.db.migrations.swappable_dependency",
"django.db.models.BigAutoField",
"django.db.models.CharField",
"django.db.models.ForeignKey",
"django.db.models.ImageField",
"django.db.models.DateTimeField"
] | [((247, 304), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (278, 304), False, 'from django.db import migrations, models\n'), ((437, 533), 'django.db.models.BigAutoField', 'models.BigAutoField', ([], {'auto_created': '... |
try:
from icecream import ic
except ImportError: # Graceful fallback if IceCream isn't installed.
ic = lambda *a: None if not a else (a[0] if len(a) == 1 else a) # noqa
from typing import List
import csv
from helpers import buildOutputTranslator
import gis
import osm
import translator_api
import pprint
impor... | [
"icecream.ic",
"gis.getBoundaries",
"decimal.Decimal",
"gis.getBaseGIScountryURL",
"osm.getOSMtags",
"helpers.buildOutputTranslator",
"time.time",
"pprint.PrettyPrinter",
"gis.getMaxADM",
"translator_api.getRequiredLang",
"translator_api.getVillages",
"time.localtime",
"csv.DictWriter"
] | [((448, 459), 'time.time', 'time.time', ([], {}), '()\n', (457, 459), False, 'import time\n'), ((850, 880), 'pprint.PrettyPrinter', 'pprint.PrettyPrinter', ([], {'indent': '(4)'}), '(indent=4)\n', (870, 880), False, 'import pprint\n'), ((379, 390), 'decimal.Decimal', 'Decimal', (['(10)'], {}), '(10)\n', (386, 390), Fal... |
# Generated by Django 2.2.12 on 2020-07-12 19:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0004_auto_20200712_2358'),
]
operations = [
migrations.AddField(
model_name='item',
name='discount_price',
... | [
"django.db.models.ImageField",
"django.db.models.DecimalField"
] | [((338, 448), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'blank': '(True)', 'decimal_places': '(2)', 'max_digits': '(20)', 'null': '(True)', 'verbose_name': '"""Discount Price"""'}), "(blank=True, decimal_places=2, max_digits=20, null=True,\n verbose_name='Discount Price')\n", (357, 448), False, '... |
"""Show number of new yt videos.
Requires the following library:
* ytrssil (from aur)
contributed by `<NAME> <>`_ - many thanks!
"""
import logging
from ytrssil.api import get_new_video_count
import core.module
import core.widget
import core.decorators
class Module(core.module.Module):
@core.decorators.e... | [
"ytrssil.api.get_new_video_count"
] | [((884, 905), 'ytrssil.api.get_new_video_count', 'get_new_video_count', ([], {}), '()\n', (903, 905), False, 'from ytrssil.api import get_new_video_count\n')] |
from fastapi import APIRouter, Depends
from price.coinmarketcap import get_latest_price
from price.models import Price
router = APIRouter(prefix="/price")
async def latest_price(symbol: str):
return get_latest_price(symbol)
@router.get("/", response_model=Price)
async def get_price(price: dict = Depends(lates... | [
"price.coinmarketcap.get_latest_price",
"fastapi.Depends",
"fastapi.APIRouter"
] | [((130, 156), 'fastapi.APIRouter', 'APIRouter', ([], {'prefix': '"""/price"""'}), "(prefix='/price')\n", (139, 156), False, 'from fastapi import APIRouter, Depends\n'), ((207, 231), 'price.coinmarketcap.get_latest_price', 'get_latest_price', (['symbol'], {}), '(symbol)\n', (223, 231), False, 'from price.coinmarketcap i... |
""".runzip"""
import asyncio
import os
import re
import time
import zipfile
from datetime import datetime
from zipfile import ZipFile
from pySmartDL import SmartDL
from remotezip import RemoteZip
from telethon import events
from telethon.tl.types import DocumentAttributeAudio, DocumentAttributeVideo
from uniborg.util... | [
"remotezip.RemoteZip",
"re.findall",
"telethon.events.NewMessage"
] | [((880, 907), 're.findall', 're.findall', (['"""\\\\.zip"""', 'textx'], {}), "('\\\\.zip', textx)\n", (890, 907), False, 'import re\n'), ((476, 511), 'telethon.events.NewMessage', 'events.NewMessage', ([], {'pattern': '"""runzip"""'}), "(pattern='runzip')\n", (493, 511), False, 'from telethon import events\n'), ((1030,... |
import geocoder
class geo_location:
myloc = geocoder.ip('me')
loc = myloc.address
lng = int(myloc.lng * 10 ** 4)
lat = int(myloc.lat * 10 ** 4)
ci = myloc.city
sta = myloc.state
| [
"geocoder.ip"
] | [((51, 68), 'geocoder.ip', 'geocoder.ip', (['"""me"""'], {}), "('me')\n", (62, 68), False, 'import geocoder\n')] |
import time
import seq2science
ascii_logo = (
f"""\
____ ____ __
/ ___)( __) / \
\___ \ ) _) ( O )
(____/(____) \__\)
____
(___ \
... | [
"time.sleep"
] | [((791, 804), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (801, 804), False, 'import time\n')] |
from unittest.mock import patch
from fastapi import HTTPException
from pytest import fixture, raises
@fixture
def check_signature():
with patch("fastapi_slack.check_signature") as check_signature:
check_signature.return_value = True
yield check_signature
def test_with_valid_signature(check_sign... | [
"unittest.mock.patch",
"pytest.raises",
"fastapi_slack.with_valid_signature"
] | [((394, 456), 'fastapi_slack.with_valid_signature', 'with_valid_signature', (["b'b o d y'", 'settings', '(12345)', '"""signature"""'], {}), "(b'b o d y', settings, 12345, 'signature')\n", (414, 456), False, 'from fastapi_slack import with_valid_signature\n'), ((145, 183), 'unittest.mock.patch', 'patch', (['"""fastapi_s... |
#!/usr/bin/env python
# Copyright 2015-2016 Yelp 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 ... | [
"sys.stdin.read",
"paasta_tools.utils._log",
"paasta_tools.marathon_tools.marathon_services_running_here",
"paasta_tools.kubernetes_tools.get_all_kubernetes_services_running_here",
"paasta_tools.tron_tools.tron_jobs_running_here",
"paasta_tools.utils.load_system_paasta_config"
] | [((1263, 1290), 'paasta_tools.utils.load_system_paasta_config', 'load_system_paasta_config', ([], {}), '()\n', (1288, 1290), False, 'from paasta_tools.utils import load_system_paasta_config\n'), ((1453, 1549), 'paasta_tools.utils._log', '_log', ([], {'line': 'line', 'service': 'service', 'instance': 'instance', 'compon... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 19 21:43:37 2020
@author: acer
"""
import numpy as np
import sys
import csv
import argparse
def step1(dec_matrix):
sqrtSum=np.sqrt(np.sum(np.square(dec_matrix),axis=0))
dec_matrix=dec_matrix/sqrtSum
return (dec_matrix)
def step2(dec_matrix,weights):
retu... | [
"numpy.size",
"csv.reader",
"argparse.ArgumentParser",
"numpy.square",
"numpy.zeros",
"numpy.min",
"numpy.max",
"numpy.array",
"sys.exit"
] | [((439, 465), 'numpy.min', 'np.min', (['dec_matrix'], {'axis': '(0)'}), '(dec_matrix, axis=0)\n', (445, 465), True, 'import numpy as np\n'), ((481, 507), 'numpy.max', 'np.max', (['dec_matrix'], {'axis': '(0)'}), '(dec_matrix, axis=0)\n', (487, 507), True, 'import numpy as np\n'), ((526, 544), 'numpy.zeros', 'np.zeros',... |
"""The tests for day11."""
from days import day11
from ddt import ddt, data, unpack
import unittest
import helpers
@ddt
class MyTestCase(unittest.TestCase): # noqa D101
@data(
[(3, 5, 8), 4],
[(122, 79, 57), -5],
[(217, 196, 39), 0],
[(101, 153, 71), 4])
@unpack
def test_ca... | [
"ddt.data",
"days.day11.part_a",
"days.day11.part_b",
"helpers.get_file_contents",
"days.day11.calc_power_level"
] | [((176, 264), 'ddt.data', 'data', (['[(3, 5, 8), 4]', '[(122, 79, 57), -5]', '[(217, 196, 39), 0]', '[(101, 153, 71), 4]'], {}), '([(3, 5, 8), 4], [(122, 79, 57), -5], [(217, 196, 39), 0], [(101, 153, \n 71), 4])\n', (180, 264), False, 'from ddt import ddt, data, unpack\n'), ((527, 569), 'ddt.data', 'data', (["[['18... |
from django.http import HttpResponse, HttpResponseNotFound
from django.shortcuts import render
from .api_handle import *
def coin_list(request):
api_url = 'https://api.coinmarketcap.com/v2/ticker/'
context = {
'crypto_data': get_data_by_api_url(api_url),
}
return render(request, 'coins/coin_l... | [
"django.shortcuts.render",
"django.http.HttpResponseNotFound"
] | [((291, 339), 'django.shortcuts.render', 'render', (['request', '"""coins/coin_list.html"""', 'context'], {}), "(request, 'coins/coin_list.html', context)\n", (297, 339), False, 'from django.shortcuts import render\n'), ((741, 791), 'django.shortcuts.render', 'render', (['request', '"""coins/coin_detail.html"""', 'cont... |
# from transformers import *
import transformers
from summarizer import Summarizer as summarizer_bert
from aylienapiclient import textapi
from nltk.tokenize import sent_tokenize
# Load model, model config and tokenizer via Transformers
custom_config = transformers.AutoConfig.from_pretrained('bert-base-cased')
custom_... | [
"transformers.AutoConfig.from_pretrained",
"aylienapiclient.textapi.Client",
"transformers.AutoModel.from_pretrained",
"summarizer.Summarizer",
"nltk.tokenize.sent_tokenize",
"transformers.AutoTokenizer.from_pretrained"
] | [((254, 312), 'transformers.AutoConfig.from_pretrained', 'transformers.AutoConfig.from_pretrained', (['"""bert-base-cased"""'], {}), "('bert-base-cased')\n", (293, 312), False, 'import transformers\n'), ((374, 435), 'transformers.AutoTokenizer.from_pretrained', 'transformers.AutoTokenizer.from_pretrained', (['"""bert-b... |
"""
DefaultHeaders downloader middleware
See documentation in docs/topics/downloader-middleware.rst
"""
from scrapy import conf
from scrapy.utils.python import WeakKeyCache
class DefaultHeadersMiddleware(object):
def __init__(self, settings=conf.settings):
self._headers = WeakKeyCache(self._default_head... | [
"scrapy.utils.python.WeakKeyCache"
] | [((289, 324), 'scrapy.utils.python.WeakKeyCache', 'WeakKeyCache', (['self._default_headers'], {}), '(self._default_headers)\n', (301, 324), False, 'from scrapy.utils.python import WeakKeyCache\n')] |
from __future__ import absolute_import
from __future__ import unicode_literals
import logging, time, os
from .runner import runner_registry
from optparse import OptionParser
parser_raw = OptionParser(usage = '%prog raw [options] <expr>',
add_help_option=False)
parser_raw.add_option('--workdi... | [
"os.remove",
"os.makedirs",
"optparse.OptionParser",
"os.system",
"time.time",
"time.localtime",
"os.chdir",
"logging.getLogger"
] | [((189, 260), 'optparse.OptionParser', 'OptionParser', ([], {'usage': '"""%prog raw [options] <expr>"""', 'add_help_option': '(False)'}), "(usage='%prog raw [options] <expr>', add_help_option=False)\n", (201, 260), False, 'from optparse import OptionParser\n'), ((1005, 1043), 'logging.getLogger', 'logging.getLogger', (... |
# -*- coding: utf-8 -*-
""" Test string comparisons
"""
from __future__ import unicode_literals
from __future__ import print_function
from unittest import TestCase
from wordweaver.log import logger
from wordweaver.fst.utils.compare_strings import compare_strings
class TestCompareString(TestCase):
def setUp(se... | [
"wordweaver.fst.utils.compare_strings.compare_strings",
"wordweaver.log.logger.info",
"wordweaver.log.logger.error"
] | [((349, 366), 'wordweaver.fst.utils.compare_strings.compare_strings', 'compare_strings', ([], {}), '()\n', (364, 366), False, 'from wordweaver.fst.utils.compare_strings import compare_strings\n'), ((2476, 2492), 'wordweaver.log.logger.info', 'logger.info', (['msg'], {}), '(msg)\n', (2487, 2492), False, 'from wordweaver... |
"""
cloudalbum/tests/test_photos.py
~~~~~~~~~~~~~~~~~~~~~~~
Test cases for photos REST API
:description: CloudAlbum is a fully featured sample application for 'Moving to AWS serverless' training course
:copyright: © 2019 written by <NAME>, <NAME>.
:license: MIT, see LICENSE for more details.
""... | [
"unittest.main",
"io.BytesIO",
"cloudalbum.database.model_ddb.Photo.filename_orig.startswith",
"pytest.fixture",
"flask_jwt_extended.create_access_token"
] | [((1155, 1183), 'pytest.fixture', 'pytest.fixture', ([], {'autouse': '(True)'}), '(autouse=True)\n', (1169, 1183), False, 'import pytest\n'), ((4476, 4491), 'unittest.main', 'unittest.main', ([], {}), '()\n', (4489, 4491), False, 'import unittest\n'), ((2184, 2228), 'flask_jwt_extended.create_access_token', 'create_acc... |
import cv2; # OpenCV
import os.path; # Path
import numpy as np; # Numpy
from matplotlib import pyplot as plt; # Matplotlib
# documentation: https://docs.opencv.org/4.5.4/
# Author: <NAME>
# Copyright (c) 2021, All rights reserved.
imagePath = "./images/human.jpg"; # 影像路徑
img = "" # 初始化 image 變數
# 確認影像是否存在
if os.p... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"cv2.cvtColor",
"matplotlib.pyplot.imshow",
"cv2.waitKey",
"cv2.destroyAllWindows",
"cv2.imread",
"cv2.imshow"
] | [((560, 584), 'cv2.imshow', 'cv2.imshow', (['"""image"""', 'img'], {}), "('image', img)\n", (570, 584), False, 'import cv2\n'), ((623, 660), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_RGB2GRAY'], {}), '(img, cv2.COLOR_RGB2GRAY)\n', (635, 660), False, 'import cv2\n'), ((716, 753), 'cv2.cvtColor', 'cv2.cvtColor'... |
import argparse
import json
import redis
from pystdlib import shell_cmd
from pystdlib.shell import tmux_create_window
from pystdlib.uishim import get_selection_rofi
from pystdlib.xlib import switch_named_desktop
parser = argparse.ArgumentParser(description="Two panes file manager selection")
parser.add_argument('--s... | [
"redis.Redis",
"pystdlib.shell.tmux_create_window",
"argparse.ArgumentParser"
] | [((224, 295), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Two panes file manager selection"""'}), "(description='Two panes file manager selection')\n", (247, 295), False, 'import argparse\n'), ((421, 467), 'redis.Redis', 'redis.Redis', ([], {'host': '"""localhost"""', 'port': '(6379)'... |
"""The NIDDK SICR model for estimating the fraction infected with SARS-CoV-2"""
import numexpr
numexpr.set_num_threads(numexpr.detect_number_of_cores())
from .io import *
from .stats import *
from .analysis import *
from .data import *
from .prep import *
| [
"numexpr.detect_number_of_cores"
] | [((120, 152), 'numexpr.detect_number_of_cores', 'numexpr.detect_number_of_cores', ([], {}), '()\n', (150, 152), False, 'import numexpr\n')] |
#!/usr/bin/env python
# -*- coding: utf8 -*-
# Copyright (c) 2019 Jean-Fabrice
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
from datetime import datetime, timezone
import subprocess
import setup
subprocess.call([
"docker",
"build",
"--build-arg",
"AUTHOR="+setup._... | [
"datetime.datetime.now"
] | [((361, 387), 'datetime.datetime.now', 'datetime.now', (['timezone.utc'], {}), '(timezone.utc)\n', (373, 387), False, 'from datetime import datetime, timezone\n')] |
# GNU MediaGoblin -- federated, autonomous media hosting
# Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either versio... | [
"mediagoblin.tools.translate.pass_to_ugettext",
"mediagoblin.db.util.check_collection_slug_used",
"webob.exc.HTTPForbidden",
"mediagoblin.db.util.check_media_slug_used",
"mediagoblin.tools.response.redirect",
"mediagoblin.tools.response.render_to_response",
"mediagoblin.messages.add_message",
"mediago... | [((1919, 1959), 'mediagoblin.edit.forms.EditForm', 'forms.EditForm', (['request.form'], {}), '(request.form, **defaults)\n', (1933, 1959), False, 'from mediagoblin.edit import forms\n'), ((3180, 3273), 'mediagoblin.tools.response.render_to_response', 'render_to_response', (['request', '"""mediagoblin/edit/edit.html"""'... |
from application import create_app as create_app_base
from mongoengine.connection import _get_db
import unittest
import json
from settings import MONGODB_HOST, MONGODB_DB
from pet.models import Pet
from application import fixtures
class PetTest(unittest.TestCase):
def create_app(self):
self.db_name = 'pe... | [
"mongoengine.connection._get_db",
"application.create_app",
"pet.models.Pet.objects.filter",
"application.fixtures"
] | [((348, 490), 'application.create_app', 'create_app_base', ([], {'MONGODB_SETTINGS': "{'DB': self.db_name, 'HOST': MONGODB_HOST}", 'TESTING': '(True)', 'WTF_CSRF_ENABLED': '(False)', 'SECRET_KEY': '"""mySecret!"""'}), "(MONGODB_SETTINGS={'DB': self.db_name, 'HOST': MONGODB_HOST},\n TESTING=True, WTF_CSRF_ENABLED=Fal... |
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2016 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the h... | [
"snapcraft.plugins.dump.DumpPlugin.build",
"os.path.join"
] | [((1788, 1815), 'snapcraft.plugins.dump.DumpPlugin.build', 'dump.DumpPlugin.build', (['self'], {}), '(self)\n', (1809, 1815), False, 'from snapcraft.plugins import dump, nodejs\n'), ((1971, 2008), 'os.path.join', 'os.path.join', (['self.installdir', 'npmdir'], {}), '(self.installdir, npmdir)\n', (1983, 2008), False, 'i... |
from __future__ import print_function
import cv2
import numpy as np
import os
import tkFileDialog, tkMessageBox
def lin_regress(x, y):
A = np.vstack([x]).T
return np.linalg.lstsq(A, y)[0]
def get_track(filename):
with open(filename, 'r') as f:
lines = f.readlines()
print(lines[0])
lines =... | [
"os.remove",
"numpy.abs",
"numpy.linalg.lstsq",
"cv2.waitKey",
"os.path.exists",
"numpy.zeros",
"tkMessageBox.showinfo",
"cv2.VideoCapture",
"cv2.namedWindow",
"numpy.mean",
"cv2.setMouseCallback",
"numpy.cos",
"cv2.destroyWindow",
"cv2.imshow",
"tkFileDialog.askopenfilename",
"numpy.v... | [((2243, 2274), 'os.path.exists', 'os.path.exists', (['config_filename'], {}), '(config_filename)\n', (2257, 2274), False, 'import os\n'), ((3728, 3759), 'os.path.exists', 'os.path.exists', (['config_filename'], {}), '(config_filename)\n', (3742, 3759), False, 'import os\n'), ((4397, 4420), 'os.path.exists', 'os.path.e... |
#!/usr/bin/python3
#-*- coding: utf-8 -*-
import time, sys, os
from sys import path
path.append('./')
def crear_fichero_resultados():
texto_cabecera = "cabecera"
file = open("./resultados.txt", "w")
file.write(texto_cabecera)
file.close()
return
def abrir_fichero_resultados():
file = open("./... | [
"sys.path.append"
] | [((85, 102), 'sys.path.append', 'path.append', (['"""./"""'], {}), "('./')\n", (96, 102), False, 'from sys import path\n')] |
#
# MIT License
#
# Copyright (c) 2020 <NAME>, @pablintino
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | [
"models.components.component_model.ComponentModel.query.get",
"services.component_service.get_component_footprint_relations",
"services.component_service.delete_component_symbol_relation",
"services.component_service.delete_component_footprint_relation",
"services.component_service.delete_component",
"ser... | [((1674, 1948), 'models.components.resistor_model.ResistorModel', 'ResistorModel', ([], {'power_max': '"""2 W"""', 'tolerance': '"""20 %"""', 'description': '"""Thin Film Resistor 392 Ohms 1%"""', 'value': '"""392 Ohms"""', 'package': '"""0603 (1608 Metric)"""', 'comment': '"""=Value"""', 'type': '"""resistor"""', 'is_... |
"""Sample code for recurrent layer based models
The model code is at line 42; rest are fillers and prerequisities
"""
# ---- Imports ----
import keras
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers import De... | [
"keras.Input",
"keras.preprocessing.sequence.pad_sequences",
"keras.layers.Dropout",
"keras.layers.LSTM",
"keras.preprocessing.text.Tokenizer",
"keras.callbacks.EarlyStopping",
"keras.layers.Embedding",
"keras.layers.Dense",
"keras.models.Sequential"
] | [((609, 648), 'keras.preprocessing.text.Tokenizer', 'Tokenizer', ([], {'num_words': 'vocab', 'oov_token': '(0)'}), '(num_words=vocab, oov_token=0)\n', (618, 648), False, 'from keras.preprocessing.text import Tokenizer\n'), ((1016, 1123), 'keras.preprocessing.sequence.pad_sequences', 'pad_sequences', (['train_sequences'... |
# Generated by Django 2.0.7 on 2018-12-01 08:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('news', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Word',
fields=[
('id', models... | [
"django.db.models.CharField",
"django.db.models.IntegerField",
"django.db.models.BooleanField",
"django.db.models.AutoField"
] | [((314, 407), '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", (330, 407), False, 'from django.db import migrations, models\... |
# Copyright (c) 2017 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, ... | [
"pytest.mark.parametrize"
] | [((2242, 2316), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""lavinder"""', '[ScratchPadBaseConfic]'], {'indirect': '(True)'}), "('lavinder', [ScratchPadBaseConfic], indirect=True)\n", (2265, 2316), False, 'import pytest\n')] |
from functools import wraps
import json
from os import environ as env
from werkzeug.exceptions import HTTPException
from dotenv import load_dotenv, find_dotenv
from flask import Flask
from flask import jsonify, request
from flask import session
from flask_cors import CORS, cross_origin
from deta import Deta
load_doten... | [
"flask.request.args.get",
"flask_cors.CORS",
"flask.Flask",
"flask_cors.cross_origin",
"dotenv.load_dotenv",
"flask.jsonify",
"flask.request.json.get",
"deta.Deta"
] | [((310, 323), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (321, 323), False, 'from dotenv import load_dotenv, find_dotenv\n'), ((332, 356), 'deta.Deta', 'Deta', (["env['PROJECT_KEY']"], {}), "(env['PROJECT_KEY'])\n", (336, 356), False, 'from deta import Deta\n'), ((457, 472), 'flask.Flask', 'Flask', (['__nam... |
"""Find type annotations from a docstring.
Do not actually try to parse the annotations, just return them as strings.
Also recognize some common non-PEP-484 aliases such as 'a string' for 'str'
and 'list of int' for 'List[int]'.
Based on original implementation by <NAME>.
TODO: Decide whether it makes sense to do t... | [
"collections.OrderedDict",
"re.match",
"re.compile"
] | [((1464, 1549), 're.compile', 're.compile', (['"""^\\\\s*(?P<name>[A-Za-z_][A-Za-z_0-9]*)(\\\\s+\\\\((?P<type>[^)]+)\\\\))?:"""'], {}), "('^\\\\s*(?P<name>[A-Za-z_][A-Za-z_0-9]*)(\\\\s+\\\\((?P<type>[^)]+)\\\\))?:'\n )\n", (1474, 1549), False, 'import re\n'), ((1605, 1634), 're.compile', 're.compile', (['"""\\\\(|\\... |
import os
from PIL import Image
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
def read_ct_scan(folder_name):
"""Read the CT scan image files from directory"""
images = []
# Construct path for two image file folders
filepaths = [os.path.join(folder_name,file) for file ... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show",
"numpy.nan_to_num",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"tensorflow.data.Dataset.from_tensor_slices",
"PIL.Image.open",
"matplotlib.pyplot.figure",
"numpy.array",
"tensorflow.image.resize",
"os.... | [((1033, 1067), 'numpy.array', 'np.array', (['history.history[keys[2]]'], {}), '(history.history[keys[2]])\n', (1041, 1067), True, 'import numpy as np\n'), ((1083, 1117), 'numpy.array', 'np.array', (['history.history[keys[3]]'], {}), '(history.history[keys[3]])\n', (1091, 1117), True, 'import numpy as np\n'), ((1135, 1... |
#!/bin/python3
import sys, subprocess, json
# Currently a prototype, needs to be improved for robustness/long-term security
# Check for arguments
if (sys.argv[1] == None) or (str(sys.argv[1]) == ""):
print("This script needs args! Pass it a json manifest.")
exit(1)
# Take arg 1 as the json file to read
fnam... | [
"subprocess.run"
] | [((919, 963), 'subprocess.run', 'subprocess.run', (["['/bin/bash', '-c', command]"], {}), "(['/bin/bash', '-c', command])\n", (933, 963), False, 'import sys, subprocess, json\n')] |
# Created by wangmeng at 2021/4/8 🍻🍻
from asyncio import gather
from typing import List
from toolkit.models.task import TaskBase
class AptSourceListUpdateTask(TaskBase):
name = "apt source list update"
desc = "更新目标主机的apt源"
scripts: List[str] = ["./toolkit/services/scripts/apt_source_update.sh"]
as... | [
"asyncio.gather"
] | [((832, 854), 'asyncio.gather', 'gather', (['*task_on_hosts'], {}), '(*task_on_hosts)\n', (838, 854), False, 'from asyncio import gather\n')] |
"""Notification tasks"""
import celery
from django.conf import settings
from open_discussions.celery import app
from open_discussions.utils import chunks
from channels.models import Channel
from notifications import api
def _gen_attempt_send_notification_batches(notification_settings):
"""
Generates the set... | [
"notifications.api.send_email_notification_batch",
"notifications.api.send_moderator_notifications",
"channels.models.Channel.objects.get",
"open_discussions.utils.chunks",
"notifications.api.get_daily_frontpage_settings_ids",
"notifications.api.get_weekly_frontpage_settings_ids",
"notifications.api.sen... | [((907, 926), 'open_discussions.celery.app.task', 'app.task', ([], {'bind': '(True)'}), '(bind=True)\n', (915, 926), False, 'from open_discussions.celery import app\n'), ((1287, 1306), 'open_discussions.celery.app.task', 'app.task', ([], {'bind': '(True)'}), '(bind=True)\n', (1295, 1306), False, 'from open_discussions.... |
from django.contrib import admin
from . import models
class TweetAdmin(admin.ModelAdmin):
list_per_page = 10
list_display = (
'text',
'sentiment',
'sent_accuracy',
'collected_at',
'created_at')
class SentimentAdmin(admin.ModelAdmin):
list_per_page = 10
list_di... | [
"django.contrib.admin.site.register"
] | [((462, 507), 'django.contrib.admin.site.register', 'admin.site.register', (['models.Tweet', 'TweetAdmin'], {}), '(models.Tweet, TweetAdmin)\n', (481, 507), False, 'from django.contrib import admin\n'), ((508, 561), 'django.contrib.admin.site.register', 'admin.site.register', (['models.Sentiment', 'SentimentAdmin'], {}... |
import requests
from datetime import datetime
import time
import argparse
import getpass
import json
from rich import print
import logging
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
logging.basicConfig(level=logging.DEBUG,
format=f'%(asctime)s %(levelname)s %(... | [
"argparse.ArgumentParser",
"logging.basicConfig",
"json.dumps",
"logging.info",
"rich.print",
"requests.get",
"datetime.datetime.now",
"urllib3.disable_warnings",
"datetime.datetime.timestamp"
] | [((154, 221), 'urllib3.disable_warnings', 'urllib3.disable_warnings', (['urllib3.exceptions.InsecureRequestWarning'], {}), '(urllib3.exceptions.InsecureRequestWarning)\n', (178, 221), False, 'import urllib3\n'), ((222, 342), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG', 'format': 'f"""%(... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__author__ = 'AJay'
__mtime__ = '2019/3/24 0024'
"""
from extract_img import SWFExtractor
swf =SWFExtractor(package='1.swf',rdpi=200,img_path='out_img',outfile='test.png')
swf.swf2Longimg() # 普通的拼接方式
# swf.swf2longimgNowhite() # 切除空白的拼接方式
# 拼接图片
print('print SWFEx... | [
"extract_img.SWFExtractor"
] | [((147, 226), 'extract_img.SWFExtractor', 'SWFExtractor', ([], {'package': '"""1.swf"""', 'rdpi': '(200)', 'img_path': '"""out_img"""', 'outfile': '"""test.png"""'}), "(package='1.swf', rdpi=200, img_path='out_img', outfile='test.png')\n", (159, 226), False, 'from extract_img import SWFExtractor\n')] |
# generated by datamodel-codegen:
# filename: https://example.com/refs.yaml
# timestamp: 2019-07-26T00:00:00+00:00
from __future__ import annotations
from typing import Optional
from pydantic import AnyUrl, BaseModel, Field, conint
class Problem(BaseModel):
detail: Optional[str] = Field(
None,
... | [
"pydantic.Field",
"pydantic.conint"
] | [((296, 559), 'pydantic.Field', 'Field', (['None'], {'description': '"""A human readable explanation specific to this occurrence of the\nproblem. You MUST NOT expose internal informations, personal\ndata or implementation details through this field.\n"""', 'example': '"""Request took too long to complete."""'}), '(None... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.tender_list, name='tender_list'),
url(r'^tender/(?P<pk>\d+)/$', views.tender_detail, name='tender_detail'),
url(r'^tender/new/$', views.tender_new, name='tender_new'),
url(r'^tender/(?P<pk>\d+)/edit/$', views.tender_e... | [
"django.conf.urls.url"
] | [((74, 122), 'django.conf.urls.url', 'url', (['"""^$"""', 'views.tender_list'], {'name': '"""tender_list"""'}), "('^$', views.tender_list, name='tender_list')\n", (77, 122), False, 'from django.conf.urls import url\n'), ((129, 201), 'django.conf.urls.url', 'url', (['"""^tender/(?P<pk>\\\\d+)/$"""', 'views.tender_detail... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 19 12:40:19 2019
@author: jamie.ross
"""
from requests import get
from requests.exceptions import RequestException
from contextlib import closing
import time
import os
#os.chdir('C:/Users/Jamie.Ross/Documents/Beer/')
def simple_get(url):
"""
Attempts to get th... | [
"requests.get",
"time.sleep"
] | [((1801, 1814), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (1811, 1814), False, 'import time\n'), ((522, 543), 'requests.get', 'get', (['url'], {'stream': '(True)'}), '(url, stream=True)\n', (525, 543), False, 'from requests import get\n')] |
import os
import time
from queue import Queue
import schedule
from IPProxyPool.core.db.mongo_pool import MongoPool
from gevent import monkey
from IPProxyPool.core.proxy_validate.httpbin_validator import check_proxy
from IPProxyPool.settings import TEST_PROXIES_ASYNC_COUNT, MAX_SCORE, TEST_PROXIES_INTERVAL
from max_t... | [
"schedule.run_pending",
"os.path.abspath",
"gevent.pool.Pool",
"max_toolbox.max_logging.MaxLogging.get_logger",
"os.path.dirname",
"IPProxyPool.core.proxy_validate.httpbin_validator.check_proxy",
"gevent.monkey.patch_all",
"os.path.exists",
"max_toolbox.max_logging.MaxLogging.init",
"time.sleep",
... | [((358, 376), 'gevent.monkey.patch_all', 'monkey.patch_all', ([], {}), '()\n', (374, 376), False, 'from gevent import monkey\n'), ((1268, 1303), 'max_toolbox.max_logging.MaxLogging.init', 'MaxLogging.init', (['log_file', 'log_name'], {}), '(log_file, log_name)\n', (1283, 1303), False, 'from max_toolbox.max_logging impo... |
from django.contrib.messages.views import SuccessMessageMixin
from django.shortcuts import *
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from ... | [
"django.forms.widgets.DateInput",
"csv.writer",
"django.http.HttpResponse",
"django.urls.reverse_lazy",
"django.forms.widgets.Textarea",
"datetime.datetime.strptime",
"tablib.Dataset"
] | [((2103, 2129), 'django.urls.reverse_lazy', 'reverse_lazy', (['"""staff-list"""'], {}), "('staff-list')\n", (2115, 2129), False, 'from django.urls import reverse_lazy\n'), ((2296, 2346), 'django.http.HttpResponse', 'HttpResponse', (['dataset.csv'], {'content_type': '"""text/csv"""'}), "(dataset.csv, content_type='text/... |
from pony.orm import Database, PrimaryKey, Set, Required, Optional, StrArray
database_object = Database()
class Namespace(database_object.Entity):
id = PrimaryKey(int, auto=True)
codes = Set('Code')
name = Required(str)
url = Optional(str)
wiki = Optional(str)
description = Optional(str)
class Region(databa... | [
"pony.orm.PrimaryKey",
"pony.orm.Database",
"pony.orm.Optional",
"pony.orm.Required",
"pony.orm.Set"
] | [((97, 107), 'pony.orm.Database', 'Database', ([], {}), '()\n', (105, 107), False, 'from pony.orm import Database, PrimaryKey, Set, Required, Optional, StrArray\n'), ((157, 183), 'pony.orm.PrimaryKey', 'PrimaryKey', (['int'], {'auto': '(True)'}), '(int, auto=True)\n', (167, 183), False, 'from pony.orm import Database, ... |
import numpy as np
from torchnlp.datasets import imdb_dataset # run pip install pytorch-nlp if you dont have this
from tamnun.bert import BertClassifier, BertVectorizer
from sklearn.pipeline import make_pipeline
from sklearn.metrics import classification_report
# Getting data
train_data, test_data = imdb_dataset(train... | [
"torchnlp.datasets.imdb_dataset",
"tamnun.bert.BertVectorizer",
"sklearn.metrics.classification_report",
"tamnun.bert.BertClassifier",
"numpy.array"
] | [((302, 337), 'torchnlp.datasets.imdb_dataset', 'imdb_dataset', ([], {'train': '(True)', 'test': '(True)'}), '(train=True, test=True)\n', (314, 337), False, 'from torchnlp.datasets import imdb_dataset\n'), ((683, 705), 'numpy.array', 'np.array', (['train_labels'], {}), '(train_labels)\n', (691, 705), True, 'import nump... |
# Copyright 2020 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | [
"os.path.dirname",
"fontTools.pens.transformPen.TransformPen",
"picosvg.svg.SVG.parse",
"picosvg.geometric_types.Rect",
"lxml.etree.SubElement"
] | [((1184, 1209), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (1199, 1209), False, 'import os\n'), ((1330, 1356), 'picosvg.svg.SVG.parse', 'SVG.parse', (['symbol_filepath'], {}), '(symbol_filepath)\n', (1339, 1356), False, 'from picosvg.svg import SVG\n'), ((2178, 2210), 'lxml.etree.SubEleme... |
from django.db import models
class EventType(models.Model):
name = models.CharField("Tip", max_length=50)
def __str__(self):
return self.name
class Meta:
verbose_name = "Etkinlik tipi"
verbose_name_plural = "Etkinlik tipleri"
class Event(models.Model):
title = models.CharFi... | [
"django.db.models.TextField",
"django.db.models.URLField",
"django.db.models.CharField",
"django.db.models.ForeignKey",
"django.db.models.BooleanField",
"django.db.models.DateTimeField"
] | [((73, 111), 'django.db.models.CharField', 'models.CharField', (['"""Tip"""'], {'max_length': '(50)'}), "('Tip', max_length=50)\n", (89, 111), False, 'from django.db import models\n'), ((307, 349), 'django.db.models.CharField', 'models.CharField', (['"""Başlık"""'], {'max_length': '(200)'}), "('Başlık', max_length=200)... |
import sys
from bs4 import BeautifulSoup
import os
article_name = sys.argv[1]
filename = "articles/"+article_name+".html"
with open(filename, encoding='utf-8') as article:
article_soup = BeautifulSoup(article, "html5lib")
title = str(article_soup.findAll("h2")[0])[4:-5]
with open("shared/recent-articles.js", "r... | [
"bs4.BeautifulSoup"
] | [((193, 227), 'bs4.BeautifulSoup', 'BeautifulSoup', (['article', '"""html5lib"""'], {}), "(article, 'html5lib')\n", (206, 227), False, 'from bs4 import BeautifulSoup\n')] |
from typing import Any, Callable, Sequence
import flax.linen as nn
import jax.numpy as jnp
from flax import linen as nn
ModuleDef = Any
class MLPResNetV2Block(nn.Module):
"""MLPResNet block."""
features: int
act: Callable
@nn.compact
def __call__(self, x):
residual = x
y = nn.La... | [
"flax.linen.LayerNorm",
"flax.linen.Dense",
"jax.numpy.asarray"
] | [((1106, 1132), 'jax.numpy.asarray', 'jnp.asarray', (['x', 'self.dtype'], {}), '(x, self.dtype)\n', (1117, 1132), True, 'import jax.numpy as jnp\n'), ((315, 329), 'flax.linen.LayerNorm', 'nn.LayerNorm', ([], {}), '()\n', (327, 329), True, 'from flax import linen as nn\n'), ((369, 392), 'flax.linen.Dense', 'nn.Dense', (... |
# ---------------------------------------------------------------------
# DLink.DxS.get_chassis_id
# ---------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
# Python... | [
"noc.core.validators.is_mac",
"noc.core.text.parse_table",
"re.compile"
] | [((717, 781), 're.compile', 're.compile', (['"""^MAC [Aa]ddress\\\\s+:\\\\s*(?P<id>\\\\S+)"""', 're.MULTILINE'], {}), "('^MAC [Aa]ddress\\\\s+:\\\\s*(?P<id>\\\\S+)', re.MULTILINE)\n", (727, 781), False, 'import re\n'), ((794, 964), 're.compile', 're.compile', (['"""^\\\\s*\\\\d+\\\\s+(?:\\\\S+\\\\s+)?([0-9A-F]{2}-[0-9A... |
"""
MIT License
Copyright (c) 2020 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distri... | [
"tensorflow.keras.activations.relu",
"tensorflow.keras.layers.MaxPool2D",
"tensorflow.keras.Sequential"
] | [((1916, 1944), 'tensorflow.keras.activations.relu', 'tf.keras.activations.relu', (['x'], {}), '(x)\n', (1941, 1944), True, 'import tensorflow as tf\n'), ((2531, 2559), 'tensorflow.keras.activations.relu', 'tf.keras.activations.relu', (['x'], {}), '(x)\n', (2556, 2559), True, 'import tensorflow as tf\n'), ((2977, 2998)... |
import copy
from unittest import mock
import pytest
from dateutil.parser import parse as date_parse
from onfido.models import Report
from onfido.models.base import BaseModel
from ..conftest import IDENTITY_REPORT_ID, TEST_REPORT_IDENTITY_ENHANCED
@pytest.mark.django_db
class TestReportManager:
@mock.patch.obje... | [
"unittest.mock.patch.object",
"copy.deepcopy",
"dateutil.parser.parse",
"onfido.models.Report",
"onfido.models.Report.objects.create_report"
] | [((305, 347), 'unittest.mock.patch.object', 'mock.patch.object', (['BaseModel', '"""full_clean"""'], {}), "(BaseModel, 'full_clean')\n", (322, 347), False, 'from unittest import mock\n'), ((476, 520), 'copy.deepcopy', 'copy.deepcopy', (['TEST_REPORT_IDENTITY_ENHANCED'], {}), '(TEST_REPORT_IDENTITY_ENHANCED)\n', (489, 5... |
import os, sys
from discord.ext import commands
from discord import Intents
import config
# add this directory to the python module path
sys.path.insert(1,os.path.dirname(os.path.realpath(__file__)))
class IgnoreBotsBot(commands.Bot):
async def on_message(self,message):
if message.author.bot: return
await self.pr... | [
"os.path.realpath",
"os.listdir",
"discord.Intents.all"
] | [((407, 425), 'os.listdir', 'os.listdir', (['"""cogs"""'], {}), "('cogs')\n", (417, 425), False, 'import os, sys\n'), ((171, 197), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (187, 197), False, 'import os, sys\n'), ((377, 390), 'discord.Intents.all', 'Intents.all', ([], {}), '()\n', (388... |
from ub.events import javes05
from ub import bot
from telethon.tl.types import User
from telethon.tl.functions.users import GetFullUserRequest
from telethon.tl import functions
l=[]
@javes05(pattern="^\!savemyinfo", outgoing=True)
async def fetch_info(event):
shivam=await bot.get_entity('me')
ruser=await event... | [
"telethon.tl.functions.account.UpdateProfileRequest",
"ub.events.javes05",
"ub.bot.get_entity",
"telethon.tl.functions.users.GetFullUserRequest"
] | [((183, 231), 'ub.events.javes05', 'javes05', ([], {'pattern': '"""^\\\\!savemyinfo"""', 'outgoing': '(True)'}), "(pattern='^\\\\!savemyinfo', outgoing=True)\n", (190, 231), False, 'from ub.events import javes05\n'), ((1016, 1063), 'ub.events.javes05', 'javes05', ([], {'pattern': '"""^\\\\!mereverse"""', 'outgoing': '(... |
import numpy as np
import time
import sys
from ServoMotor import *
from fns import *
# Initialize motor control library & USB Port
filename = "/dev/ttyUSB0"
motor = ServoMotor(filename)
IO = motor.IO_Init()
if IO < 0:
print('IO exit')
sys.exit()
# Call corresponding function to convert sim2real/real2sim
def convFns... | [
"numpy.zeros",
"time.sleep",
"numpy.sin",
"numpy.array",
"numpy.linspace",
"sys.exit"
] | [((2243, 2256), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (2253, 2256), False, 'import time\n'), ((2511, 2524), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (2521, 2524), False, 'import time\n'), ((238, 248), 'sys.exit', 'sys.exit', ([], {}), '()\n', (246, 248), False, 'import sys\n'), ((524, 536), 'nu... |
#test_re.py
import ure as re
r = re.compile(".+")
m = r.match("abc")
print(m.group(0))#abc
str(r)#'<re 2000b5c0>',正则表达式编译后所在的内存地址
str(m)#'<match num=1>'
r = re.compile("(.+)1")
m = r.match("xyz781")
print(m.group(0))#xyz781
print(m.group(1))#xyz78
r = re.compile("[a-cu-z]")
m = r.match("a")
print(m.group(0))#a
m = r.m... | [
"ure.search",
"ure.compile",
"ure.match",
"ure.sub"
] | [((34, 50), 'ure.compile', 're.compile', (['""".+"""'], {}), "('.+')\n", (44, 50), True, 'import ure as re\n'), ((158, 177), 'ure.compile', 're.compile', (['"""(.+)1"""'], {}), "('(.+)1')\n", (168, 177), True, 'import ure as re\n'), ((253, 275), 'ure.compile', 're.compile', (['"""[a-cu-z]"""'], {}), "('[a-cu-z]')\n", (... |
# Copyright (c) 2020 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, ... | [
"slimta.util.pycompat.reprlib.Repr"
] | [((1217, 1231), 'slimta.util.pycompat.reprlib.Repr', 'reprlib.Repr', ([], {}), '()\n', (1229, 1231), False, 'from slimta.util.pycompat import reprlib\n')] |
# -*- coding: utf-8 -*-
from __future__ import division
from __future__ import print_function
import os
import sys
import unittest
import shutil
# temporary solution for relative imports in case TDC is not installed
# if TDC is installed, no need to use the following line
sys.path.append(os.path.abspath(os.path.joi... | [
"os.getcwd",
"os.path.dirname",
"tdc.chem_utils.MolConvert",
"tdc.chem_utils.MolConvert.eligible_format"
] | [((611, 650), 'tdc.chem_utils.MolConvert', 'MolConvert', ([], {'src': '"""SMILES"""', 'dst': '"""Graph2D"""'}), "(src='SMILES', dst='Graph2D')\n", (621, 650), False, 'from tdc.chem_utils import MolConvert\n'), ((855, 883), 'tdc.chem_utils.MolConvert.eligible_format', 'MolConvert.eligible_format', ([], {}), '()\n', (881... |
"""Utilities for converting soundata Annotation classes to jams format.
"""
import logging
import os
from typing import Callable, List
from typing_extensions import ParamSpecKwargs
import jams
import librosa
from soundata import annotations
def jams_converter(
audio_path=None, spectrogram_path=None, metadata=No... | [
"jams.AnnotationMetadata",
"logging.warning",
"os.path.exists",
"jams.JAMS",
"jams.Sandbox",
"jams.Annotation",
"librosa.get_duration"
] | [((1268, 1279), 'jams.JAMS', 'jams.JAMS', ([], {}), '()\n', (1277, 1279), False, 'import jams\n'), ((4850, 4886), 'jams.Annotation', 'jams.Annotation', ([], {'namespace': 'namespace'}), '(namespace=namespace)\n', (4865, 4886), False, 'import jams\n'), ((4917, 5032), 'jams.AnnotationMetadata', 'jams.AnnotationMetadata',... |
import discord
from discord.ext import commands
import time
import datetime
class Errors(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
if isinstance(error, commands.NoPrivateMessage):
await ctx.... | [
"discord.ext.commands.Cog.listener"
] | [((167, 190), 'discord.ext.commands.Cog.listener', 'commands.Cog.listener', ([], {}), '()\n', (188, 190), False, 'from discord.ext import commands\n')] |
# -*- coding: utf-8 -*-
"""Console script for acl_stats."""
import sys
import click
from acl_stats import acl_stats
@click.group()
def main():
click.echo(click.style('ACL Stats', fg='blue', bold=True))
pass
@main.command()
@click.option('--acl-file', default=None, prompt='ACL File', help='File containing the... | [
"click.group",
"click.option",
"acl_stats.acl_stats.ACLStats",
"click.style"
] | [((119, 132), 'click.group', 'click.group', ([], {}), '()\n', (130, 132), False, 'import click\n'), ((235, 391), 'click.option', 'click.option', (['"""--acl-file"""'], {'default': 'None', 'prompt': '"""ACL File"""', 'help': '"""File containing the output of the show acess-list _name_ command"""', 'required': '(True)'})... |
from Module import AbstractModule
class Module(AbstractModule):
def __init__(self):
AbstractModule.__init__(self)
def run(
self, network, antecedents, out_attributes, user_options, num_cores,
outfile):
from genomicode import filelib
import os
import arrayio
... | [
"genomicode.filelib.read_row",
"genomicode.arrayplatformlib.score_all_platforms_of_matrix",
"arrayio.tab_delimited_format.write",
"os.path.exists",
"Betsy.module_utils.get_inputid",
"Module.AbstractModule.__init__",
"genomicode.filelib.exists_nz",
"arrayio.read"
] | [((97, 126), 'Module.AbstractModule.__init__', 'AbstractModule.__init__', (['self'], {}), '(self)\n', (120, 126), False, 'from Module import AbstractModule\n'), ((501, 524), 'os.path.exists', 'os.path.exists', (['mapfile'], {}), '(mapfile)\n', (515, 524), False, 'import os\n'), ((606, 644), 'genomicode.filelib.read_row... |
from curlylint import ast
from curlylint.check_node import CheckNode, build_tree
from curlylint.issue import Issue
META_VIEWPORT = "meta_viewport"
RULE = {
"id": "meta_viewport",
"type": "accessibility",
"docs": {
"description": "The `viewport` meta tag should not use `user-scalable=no`, and `maxi... | [
"curlylint.check_node.CheckNode",
"curlylint.check_node.build_tree",
"curlylint.issue.Issue.from_node"
] | [((2577, 2592), 'curlylint.check_node.CheckNode', 'CheckNode', (['None'], {}), '(None)\n', (2586, 2592), False, 'from curlylint.check_node import CheckNode, build_tree\n'), ((2597, 2624), 'curlylint.check_node.build_tree', 'build_tree', (['root', 'file.tree'], {}), '(root, file.tree)\n', (2607, 2624), False, 'from curl... |
# -*- coding: utf-8 -*-
import boto3
from cottonformation.core.template import Template
from cottonformation.core.model import (
Parameter, Output,
Ref, Sub, serialize,
)
from cottonformation.res import (
s3,
)
from cottonformation.core.env import Env
tpl = Template()
param_project_name = Parameter(
... | [
"cottonformation.core.env.Env",
"cottonformation.core.model.Output",
"cottonformation.core.template.Template",
"cottonformation.core.model.Parameter",
"boto3.session.Session"
] | [((272, 282), 'cottonformation.core.template.Template', 'Template', ([], {}), '()\n', (280, 282), False, 'from cottonformation.core.template import Template\n'), ((305, 397), 'cottonformation.core.model.Parameter', 'Parameter', (['"""ProjectName"""'], {'Type': 'Parameter.TypeEnum.String', 'Default': '"""cottonformation... |
import json, sys, uuid, random, re, time, math
from flask import Flask, request, jsonify
import sqlite3 as sql
from flask_cors import CORS, cross_origin
class Player:
def __init__(self,handle,token):
handle = re.sub(r"[^a-zA-Z0-9_]", "", handle)[:20]
if(len(handle) < 3):
handle = ''.joi... | [
"uuid.uuid4",
"random.randint",
"flask_cors.CORS",
"flask.Flask",
"random.choice",
"time.time",
"flask.jsonify",
"sqlite3.connect",
"re.search",
"flask.request.get_json",
"re.sub"
] | [((2097, 2112), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (2102, 2112), False, 'from flask import Flask, request, jsonify\n'), ((2113, 2122), 'flask_cors.CORS', 'CORS', (['app'], {}), '(app)\n', (2117, 2122), False, 'from flask_cors import CORS, cross_origin\n'), ((835, 852), 'sqlite3.connect', 'sql.c... |
#!/usr/bin/env python3
import re
import sys
import os
from collections import OrderedDict
import logging
from io import StringIO
import queue as Queue
#----------------------------------------------------------------------------------------------------------------------------------------------------------
def enco(s... | [
"io.StringIO",
"pykms_GuiBase.gui_redirector_setup",
"os.path.abspath",
"os.remove",
"pykms_GuiBase.gui_redirector_clear",
"logging.StreamHandler",
"logging.getLogger",
"logging.Formatter",
"re.findall",
"sys.stdout.isatty",
"io.StringIO.write",
"re.sub",
"queue.Queue",
"sys.exit",
"re.c... | [((9306, 9319), 'queue.Queue', 'Queue.Queue', ([], {}), '()\n', (9317, 9319), True, 'import queue as Queue\n'), ((7772, 7811), 're.compile', 're.compile', (['"""\\\\x1B\\\\[[0-?]*[ -/]*[@-~]"""'], {}), "('\\\\x1B\\\\[[0-?]*[ -/]*[@-~]')\n", (7782, 7811), False, 'import re\n'), ((7827, 7861), 're.findall', 're.findall',... |
import numpy
# ###############################################################
#
# ###############################################################
THRESHOLD = 0.00001
AREA_THRESHOLD = 0.01
def fequal(x1, x2, threshold=THRESHOLD):
d = x1 - x2
if d < 0.0:
d *= -1.0
if threshold >= d:
return... | [
"numpy.sqrt"
] | [((11063, 11116), 'numpy.sqrt', 'numpy.sqrt', (['((x1 - h) * (x1 - h) + (y1 - k) * (y1 - k))'], {}), '((x1 - h) * (x1 - h) + (y1 - k) * (y1 - k))\n', (11073, 11116), False, 'import numpy\n'), ((11289, 11326), 'numpy.sqrt', 'numpy.sqrt', (['(x_diff ** 2 + y_diff ** 2)'], {}), '(x_diff ** 2 + y_diff ** 2)\n', (11299, 113... |
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.3.3
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Materials
#
# This te... | [
"lmscene.bunny_with_area_light",
"lightmetrica.load_renderer",
"matplotlib.pyplot.show",
"lightmetrica.load_scene",
"lightmetrica.load_film",
"lightmetrica.progress.init",
"numpy.power",
"lightmetrica.init",
"lightmetrica.load_accel",
"lmenv.load",
"lightmetrica.info",
"matplotlib.pyplot.figur... | [((497, 517), 'lmenv.load', 'lmenv.load', (['""".lmenv"""'], {}), "('.lmenv')\n", (507, 517), False, 'import lmenv\n'), ((681, 690), 'lightmetrica.init', 'lm.init', ([], {}), '()\n', (688, 690), True, 'import lightmetrica as lm\n'), ((691, 713), 'lightmetrica.log.init', 'lm.log.init', (['"""jupyter"""'], {}), "('jupyte... |
import argparse
import logging
import multiprocessing as mp
import os
import pickle
import re
import sys
import warnings
from datetime import datetime
from itertools import product
import pandas as pd
import tabulate
from sklearn.model_selection import train_test_split
from tqdm import tqdm
from greenguard import get... | [
"pickle.dump",
"argparse.ArgumentParser",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"logging.getLogger",
"datetime.datetime.utcnow",
"os.path.isfile",
"pickle.load",
"greenguard.get_pipelines",
"os.path.join",
"greenguard.pipeline.generate_preprocessing",
"pandas.DataFrame... | [((714, 741), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (731, 741), False, 'import logging\n'), ((5116, 5133), 'datetime.datetime.utcnow', 'datetime.utcnow', ([], {}), '()\n', (5131, 5133), False, 'from datetime import datetime\n'), ((5325, 5403), 'sklearn.model_selection.train_test_... |
import torch
import torch.nn as nn
from transformers import AutoTokenizer
class TransformerDataset:
def __init__(self, text, target, max_len, transformer):
self.text = text
self.target = target
self.max_len = max_len
self.tokenizer = AutoTokenizer.from_pretrained(transformer)
... | [
"transformers.AutoTokenizer.from_pretrained",
"torch.tensor"
] | [((271, 313), 'transformers.AutoTokenizer.from_pretrained', 'AutoTokenizer.from_pretrained', (['transformer'], {}), '(transformer)\n', (300, 313), False, 'from transformers import AutoTokenizer\n'), ((940, 989), 'torch.tensor', 'torch.tensor', (['self.target[item]'], {'dtype': 'torch.long'}), '(self.target[item], dtype... |
import sys, gzip, logging
from collections import Counter
from .in_util import TimeReport, detectFileChrom, extendFileList, dumpReader
#========================================
# dbNSDP fields
#========================================
class FieldH:
sRolesLists = {role: [] for role in ("variant", "facet", "transcri... | [
"collections.Counter",
"logging.info",
"gzip.open",
"logging.root.setLevel"
] | [((14753, 14788), 'logging.root.setLevel', 'logging.root.setLevel', (['logging.INFO'], {}), '(logging.INFO)\n', (14774, 14788), False, 'import sys, gzip, logging\n'), ((10074, 10083), 'collections.Counter', 'Counter', ([], {}), '()\n', (10081, 10083), False, 'from collections import Counter\n'), ((13326, 13386), 'loggi... |
import os
import csv
csv_path = os.path.join('.','Resources', 'cereal.csv')
with open(csv_path, newline = '') as csvfile:
csv_reader = csv.reader(csvfile, delimiter = ',')
for row in csv_reader:
if(float(row[7]) >= 5):
print(row)
| [
"csv.reader",
"os.path.join"
] | [((34, 78), 'os.path.join', 'os.path.join', (['"""."""', '"""Resources"""', '"""cereal.csv"""'], {}), "('.', 'Resources', 'cereal.csv')\n", (46, 78), False, 'import os\n'), ((141, 175), 'csv.reader', 'csv.reader', (['csvfile'], {'delimiter': '""","""'}), "(csvfile, delimiter=',')\n", (151, 175), False, 'import csv\n')] |
import setuptools
DEPENDENCIES = [
'coverage==4.5.4',
'nose==1.3.7'
]
EXTRA_DEPENDENCIES = {
"avro": ["fastavro==0.22.7"],
"gcloud": ["google-cloud-storage==1.23.0", "backoff==1.10.0"],
"all": ["fastavro==0.22.7", "google-cloud-storage==1.23.0", "backoff==1.10.0"]
}
with open('README.md', encodin... | [
"setuptools.find_packages"
] | [((740, 766), 'setuptools.find_packages', 'setuptools.find_packages', ([], {}), '()\n', (764, 766), False, 'import setuptools\n')] |
import face_recognition
import cv2
import numpy as np
from PIL import Image,ImageDraw
import pickle
all_face_encodings = {}
shah_image = face_recognition.load_image_file("alexa.jpg")
np.save("shah",shah_image)
shah_encoding = face_recognition.face_encodings(shah_image)[0]
np.save("shah-en",shah_encoding)
all_fac... | [
"pickle.dump",
"numpy.save",
"face_recognition.compare_faces",
"cv2.cvtColor",
"cv2.waitKey",
"face_recognition.face_encodings",
"cv2.destroyAllWindows",
"cv2.imshow",
"PIL.ImageDraw.Draw",
"numpy.array",
"PIL.Image.fromarray",
"face_recognition.face_locations",
"face_recognition.load_image_... | [((139, 184), 'face_recognition.load_image_file', 'face_recognition.load_image_file', (['"""alexa.jpg"""'], {}), "('alexa.jpg')\n", (171, 184), False, 'import face_recognition\n'), ((185, 212), 'numpy.save', 'np.save', (['"""shah"""', 'shah_image'], {}), "('shah', shah_image)\n", (192, 212), True, 'import numpy as np\n... |
from utils.api import serializers
from utils.api._serializers import UsernameSerializer
from .models import FAQ
class CreateFAQSerializer(serializers.Serializer):
question = serializers.CharField(max_length=64)
answer = serializers.CharField(max_length=1024 * 1024 * 8)
visible = serializers.BooleanField(... | [
"utils.api._serializers.UsernameSerializer",
"utils.api.serializers.CharField",
"utils.api.serializers.IntegerField",
"utils.api.serializers.BooleanField"
] | [((181, 217), 'utils.api.serializers.CharField', 'serializers.CharField', ([], {'max_length': '(64)'}), '(max_length=64)\n', (202, 217), False, 'from utils.api import serializers\n'), ((231, 280), 'utils.api.serializers.CharField', 'serializers.CharField', ([], {'max_length': '(1024 * 1024 * 8)'}), '(max_length=1024 * ... |
import pandas as pd
import psycopg2
import plotly.graph_objs as go
from plotly.offline import plot
# Function to plot line chart
def generate_line_chart(df_train, df_pred, ticker):
layout = {'title': {'text':'Stock Price Prediction of '+ ticker,
'x': 0.5},
'xaxis':{'title':'Date'},
... | [
"pandas.io.sql.read_sql",
"plotly.graph_objs.Figure",
"plotly.graph_objs.Scatter",
"psycopg2.connect"
] | [((762, 828), 'psycopg2.connect', 'psycopg2.connect', ([], {'host': '"""localhost"""', 'port': '(5432)', 'database': '"""postgres"""'}), "(host='localhost', port=5432, database='postgres')\n", (778, 828), False, 'import psycopg2\n'), ((1382, 1418), 'pandas.io.sql.read_sql', 'pd.io.sql.read_sql', (['query_real', 'conn']... |
from django.shortcuts import render, HttpResponse, redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserChangeForm, PasswordChangeForm
from .forms import RegistrationForm, EditProfileForm
from django.contrib.auth import upd... | [
"django.contrib.auth.decorators.login_required",
"django.contrib.auth.models.User.objects.get",
"django.shortcuts.redirect",
"django.contrib.auth.forms.PasswordChangeForm",
"django.shortcuts.render",
"django.contrib.auth.update_session_auth_hash"
] | [((911, 954), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'login_url': '"""/account/login/"""'}), "(login_url='/account/login/')\n", (925, 954), False, 'from django.contrib.auth.decorators import login_required\n'), ((1161, 1204), 'django.contrib.auth.decorators.login_required', 'login_requ... |
# Python-SDL2 : Yet another SDL2 wrapper for Python
#
# * https://github.com/vaiorabbit/python-sdl2
#
# [NOTICE] This is an automatically generated file.
import ctypes
from .api import SDL2_API_NAMES, SDL2_API_ARGS_MAP, SDL2_API_RETVAL_MAP
# Define/Macro
SDL_MAX_LOG_MESSAGE = 4096
# Enum
SDL_LOG_CATEGORY_APPLICATION... | [
"ctypes.CFUNCTYPE"
] | [((1150, 1239), 'ctypes.CFUNCTYPE', 'ctypes.CFUNCTYPE', (['None', 'ctypes.c_void_p', 'ctypes.c_int', 'ctypes.c_int', 'ctypes.c_char_p'], {}), '(None, ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.\n c_char_p)\n', (1166, 1239), False, 'import ctypes\n')] |
from django import forms
from .models import User
class UserLoginForm(forms.Form):
email = forms.EmailField(
widget=forms.EmailInput(
attrs={'class': 'form-control', 'placeholder': 'email'}
)
)
password = forms.CharField(
widget=forms.PasswordInput(
attrs={... | [
"django.forms.EmailInput",
"django.forms.TextInput",
"django.forms.PasswordInput"
] | [((131, 204), 'django.forms.EmailInput', 'forms.EmailInput', ([], {'attrs': "{'class': 'form-control', 'placeholder': 'email'}"}), "(attrs={'class': 'form-control', 'placeholder': 'email'})\n", (147, 204), False, 'from django import forms\n'), ((280, 359), 'django.forms.PasswordInput', 'forms.PasswordInput', ([], {'att... |
# Python solution for 'The Millionth Fibonacci Kata' codewars question.
# Level: 3 kyu
# Tags: ALGORITHMS, MATHEMATICS, and NUMBERS.
# Author: <NAME>
# Date: 02/06/2020
import unittest
def matrix_multiply(A, B):
num_rows, num_cols = len(A), len(B[0])
C = [[0] * num_cols for _ in range(num_rows)]
for i in... | [
"unittest.main"
] | [((1740, 1755), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1753, 1755), False, 'import unittest\n')] |
import math
import unittest
import django
import django.test
from django.test import TestCase
try:
from django.urls import reverse
except ImportError:
from django.core.urlresolvers import reverse
from django.utils import translation
from django.utils.encoding import force_text
from composite_field_test.models... | [
"composite_field_test.models.Place",
"django.setup",
"django.core.urlresolvers.reverse",
"composite_field_test.models.Direction.objects.get",
"composite_field_test.models.PlaceWithDefaultCoord",
"unittest.skipIf",
"composite_field_test.models.PlaceWithDefaultCoord.objects.create",
"django.utils.transl... | [((8924, 9094), 'unittest.skipIf', 'unittest.skipIf', (['((1, 8) <= django.VERSION < (1, 10))', '"""Django introduced a infinite recursion bug for properties of deferred models that was fixed in Django 1.10"""'], {}), "((1, 8) <= django.VERSION < (1, 10),\n 'Django introduced a infinite recursion bug for properties ... |
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome import automation
from esphome.automation import Condition, maybe_simple_id
from esphome.components import mqtt
from esphome.const import (
CONF_ID,
CONF_ON_LOCK,
CONF_ON_UNLOCK,
CONF_TRIGGER_ID,
CONF_MQTT_ID,
)
from es... | [
"esphome.config_validation.use_id",
"esphome.core.CORE.has_id",
"esphome.codegen.App.register_lock",
"esphome.codegen.add_global",
"esphome.config_validation.GenerateID",
"esphome.config_validation.Optional",
"esphome.automation.register_action",
"esphome.config_validation.Required",
"esphome.codege... | [((485, 516), 'esphome.codegen.esphome_ns.namespace', 'cg.esphome_ns.namespace', (['"""lock"""'], {}), "('lock')\n", (508, 516), True, 'import esphome.codegen as cg\n'), ((2566, 2641), 'esphome.automation.register_action', 'automation.register_action', (['"""lock.unlock"""', 'UnlockAction', 'LOCK_ACTION_SCHEMA'], {}), ... |
import cv2
import pandas as pd
from glob import glob
from pandas.core.series import Series
from torch import Tensor
from torch.utils.data import Dataset
from torchvision import transforms
from tqdm import tqdm
class MaskedFaceTrainDataset(Dataset):
def __init__(self, transform: transforms.Compose) -> None:
... | [
"tqdm.tqdm",
"torchvision.transforms.RandomHorizontalFlip",
"pandas.read_csv",
"cv2.imread",
"torch.Tensor",
"glob.glob",
"torchvision.transforms.Normalize",
"torchvision.transforms.ToTensor"
] | [((1749, 1797), 'pandas.read_csv', 'pd.read_csv', (['f"""{data_root_path}/train/train.csv"""'], {}), "(f'{data_root_path}/train/train.csv')\n", (1760, 1797), True, 'import pandas as pd\n'), ((2899, 2938), 'glob.glob', 'glob', (['f"""{data_root_path}/eval/images/*"""'], {}), "(f'{data_root_path}/eval/images/*')\n", (290... |
import os
from django.db import models
from django.db.models import DO_NOTHING
from django.conf import settings
from tasks.models import Task
def task_instance_dc_file_path(instance, filename):
return os.path.join(settings.STORAGE_DIR, settings.DC_TASK_INSTANCE_CONFIGS_STORAGE_SUBDIR, f"{instance.id}.yml")
cla... | [
"django.db.models.FileField",
"django.db.models.TextField",
"django.db.models.CharField",
"django.db.models.ForeignKey",
"os.path.join"
] | [((208, 319), 'os.path.join', 'os.path.join', (['settings.STORAGE_DIR', 'settings.DC_TASK_INSTANCE_CONFIGS_STORAGE_SUBDIR', 'f"""{instance.id}.yml"""'], {}), "(settings.STORAGE_DIR, settings.\n DC_TASK_INSTANCE_CONFIGS_STORAGE_SUBDIR, f'{instance.id}.yml')\n", (220, 319), False, 'import os\n'), ((885, 943), 'django.... |