code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
"""
https://docs.djangoproject.com/en/dev/ref/django-admin/#inspectdb
The meaning is to load a sqlite table and create the static model for django with django
"""
from django.core.management.commands import inspectdb
import os
def create_static_model():
current_dir = os.path.dirname(os.path.abspath(__file__))
... | [
"os.path.abspath",
"os.path.dirname",
"django.core.management.commands.inspectdb.Command"
] | [((336, 355), 'django.core.management.commands.inspectdb.Command', 'inspectdb.Command', ([], {}), '()\n', (353, 355), False, 'from django.core.management.commands import inspectdb\n'), ((291, 316), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (306, 316), False, 'import os\n'), ((530, 558), ... |
# -*- coding: utf-8 -*-
# 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... | [
"proto.RepeatedField",
"proto.Field",
"proto.module",
"proto.MapField"
] | [((762, 1273), 'proto.module', 'proto.module', ([], {'package': '"""google.cloud.osconfig.v1beta"""', 'manifest': "{'ExecutePatchJobRequest', 'GetPatchJobRequest',\n 'ListPatchJobInstanceDetailsRequest',\n 'ListPatchJobInstanceDetailsResponse', 'PatchJobInstanceDetails',\n 'ListPatchJobsRequest', 'ListPatchJob... |
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# <NAME> <<EMAIL>>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either ... | [
"logging.getLogger",
"threading.Lock",
"datetime.date.today",
"datetime.timedelta",
"threading.Event",
"datetime.datetime.now",
"weakref.proxy",
"queue.PriorityQueue",
"threading.Thread",
"warnings.warn",
"time.time"
] | [((1747, 1762), 'queue.PriorityQueue', 'PriorityQueue', ([], {}), '()\n', (1760, 1762), False, 'from queue import PriorityQueue, Empty\n'), ((1808, 1850), 'logging.getLogger', 'logging.getLogger', (['self.__class__.__name__'], {}), '(self.__class__.__name__)\n', (1825, 1850), False, 'import logging\n'), ((1879, 1885), ... |
from PIL import Image, ImageColor
from Manip import *
import sys
print('Welcome to the quick image editor. Enter "help" for command options. ')
manip = Manip()
if(len(sys.argv) == 2):
try:
im = Image.open(sys.argv[1])
manip.path = sys.argv[1]
except FileNotFoundError:
print("Invalid in... | [
"PIL.Image.open"
] | [((208, 231), 'PIL.Image.open', 'Image.open', (['sys.argv[1]'], {}), '(sys.argv[1])\n', (218, 231), False, 'from PIL import Image, ImageColor\n'), ((2182, 2198), 'PIL.Image.open', 'Image.open', (['path'], {}), '(path)\n', (2192, 2198), False, 'from PIL import Image, ImageColor\n')] |
from math import sqrt
from hypothesis import assume, given, note
from ppb_vector import Vector
from utils import angles, floats, isclose, vector_likes, vectors
@given(vector=vectors())
def test_dot_axis(vector: Vector):
assert vector * (1, 0) == vector.x
assert vector * (0, 1) == vector.y
@given(x=vectors... | [
"hypothesis.note",
"utils.vectors",
"utils.angles",
"math.sqrt",
"ppb_vector.Vector._trig",
"utils.isclose",
"utils.vector_likes"
] | [((473, 508), 'utils.isclose', 'isclose', (['(x * x)', '(x.length * x.length)'], {}), '(x * x, x.length * x.length)\n', (480, 508), False, 'from utils import angles, floats, isclose, vector_likes, vectors\n'), ((940, 955), 'ppb_vector.Vector._trig', 'Vector._trig', (['t'], {}), '(t)\n', (952, 955), False, 'from ppb_vec... |
from delfick_project.addons import addon_hook
@addon_hook()
def hook(collector, result_maker, **kwargs):
collector.configuration["resolved"].append((__name__,))
@addon_hook(post_register=True)
def post_hook(collector, **kwargs):
collector.configuration["post_register"].append((__name__, kwargs))
| [
"delfick_project.addons.addon_hook"
] | [((49, 61), 'delfick_project.addons.addon_hook', 'addon_hook', ([], {}), '()\n', (59, 61), False, 'from delfick_project.addons import addon_hook\n'), ((170, 200), 'delfick_project.addons.addon_hook', 'addon_hook', ([], {'post_register': '(True)'}), '(post_register=True)\n', (180, 200), False, 'from delfick_project.addo... |
import _curses
_capability_names = {_curses.KEY_A1: 'ka1', _curses.KEY_A3: 'ka3', _curses.
KEY_B2: 'kb2', _curses.KEY_BACKSPACE: 'kbs', _curses.KEY_BEG: 'kbeg',
_curses.KEY_BTAB: 'kcbt', _curses.KEY_C1: 'kc1', _curses.KEY_C3: 'kc3',
_curses.KEY_CANCEL: 'kcan', _curses.KEY_CATAB: 'ktbc', _curses.
KEY_CLE... | [
"_curses.tigetstr",
"_curses.initscr",
"_curses.keyname",
"_curses.endwin",
"_curses.has_key"
] | [((4304, 4337), '_curses.tigetstr', '_curses.tigetstr', (['capability_name'], {}), '(capability_name)\n', (4320, 4337), False, 'import _curses\n'), ((4451, 4468), '_curses.initscr', '_curses.initscr', ([], {}), '()\n', (4466, 4468), False, 'import _curses\n'), ((4776, 4792), '_curses.endwin', '_curses.endwin', ([], {})... |
"""Classes for representing properties of STIX Objects and Cyber Observables."""
import base64
import binascii
import copy
import inspect
import re
import uuid
from .base import _STIXBase
from .exceptions import (
CustomContentError, DictionaryKeyError, MissingPropertiesError,
MutuallyExclusivePropertiesError... | [
"uuid.UUID",
"re.compile",
"re.match",
"base64.b64decode",
"uuid.uuid4",
"copy.deepcopy",
"inspect.isclass"
] | [((647, 693), 're.compile', 're.compile', (['"""^\\\\-?[a-z0-9]+(-[a-z0-9]+)*\\\\-?$"""'], {}), "('^\\\\-?[a-z0-9]+(-[a-z0-9]+)*\\\\-?$')\n", (657, 693), False, 'import re\n'), ((709, 759), 're.compile', 're.compile', (['"""^([a-z][a-z0-9]*)+(-[a-z0-9]+)*\\\\-?$"""'], {}), "('^([a-z][a-z0-9]*)+(-[a-z0-9]+)*\\\\-?$')\n"... |
"""
This example solicits that apple devices that provide notifications connect to it, initiates
pairing, prints existing notifications and then prints any new ones as they arrive.
"""
import time
import adafruit_ble
from adafruit_ble.advertising.standard import SolicitServicesAdvertisement
import adafruit_ble_apple_n... | [
"adafruit_ble.advertising.standard.SolicitServicesAdvertisement",
"adafruit_ble.BLERadio",
"time.sleep"
] | [((426, 449), 'adafruit_ble.BLERadio', 'adafruit_ble.BLERadio', ([], {}), '()\n', (447, 449), False, 'import adafruit_ble\n'), ((483, 513), 'adafruit_ble.advertising.standard.SolicitServicesAdvertisement', 'SolicitServicesAdvertisement', ([], {}), '()\n', (511, 513), False, 'from adafruit_ble.advertising.standard impor... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# <NAME> <<EMAIL>> <https://hanxiao.github.io>
import multiprocessing
import os
import random
import sys
import threading
import time
from collections import defaultdict
from datetime import datetime
from itertools import chain
from multiprocessing import Process
from multi... | [
"termcolor.colored",
"zmq.utils.jsonapi.dumps",
"os.path.join",
"numpy.ascontiguousarray",
"zmq.utils.jsonapi.loads"
] | [((5715, 5737), 'zmq.utils.jsonapi.loads', 'jsonapi.loads', (['raw_msg'], {}), '(raw_msg)\n', (5728, 5737), False, 'from zmq.utils import jsonapi\n'), ((1294, 1326), 'termcolor.colored', 'colored', (['"""VENTILATOR"""', '"""magenta"""'], {}), "('VENTILATOR', 'magenta')\n", (1301, 1326), False, 'from termcolor import co... |
import requests
from pprint import pprint
import json
import os
import sys
sys.path.append("..")
from server import app
from model import Hospital, db, connect_to_db
#Request response object with results
def load_hospitals(url):
#Replace URL with string variable to use with other requests in the future
#ur... | [
"model.Hospital",
"model.db.session.commit",
"model.db.create_all",
"model.connect_to_db",
"model.Hospital.query.filter_by",
"requests.get",
"model.db.session.add",
"server.app.app_context",
"sys.path.append",
"server.app"
] | [((76, 97), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (91, 97), False, 'import sys\n'), ((448, 465), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (460, 465), False, 'import requests\n'), ((3554, 3559), 'server.app', 'app', ([], {}), '()\n', (3557, 3559), False, 'from server impo... |
# Credits By @VckyouuBitch From Geez-Project
# Tolong Haragai ya:)
# Kalo emg <NAME> seseorang pasti pahamm la ya:)
# Credits © Geez - Projects
import os
import moviepy.editor as m
from userbot import CMD_HELP, bot
from userbot.events import geezbot_cmd
from userbot import CUSTOM_CMD as geez
@bot.on(geezbot_cmd(ou... | [
"moviepy.editor.AudioFileClip",
"os.listdir",
"os.path.join",
"userbot.events.geezbot_cmd",
"userbot.CMD_HELP.update",
"moviepy.editor.VideoFileClip",
"os.remove"
] | [((1799, 2039), 'userbot.CMD_HELP.update', 'CMD_HELP.update', (['{\'specialtools\':\n f"""𝘾𝙤𝙢𝙢𝙖𝙣𝙙: `{geez}getaudio` \n↳ : Download Audio To put in ur Desired Video/Gif.. \n𝘾𝙤𝙢𝙢𝙖𝙣𝙙: `{geez}addaudio` \n↳ : It will put the above audio to the replied video/gif.."""\n }'], {}), '(... |
from typing import Dict, List, Tuple, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
from kornia.constants import pi
from kornia.filters import GaussianBlur2d, SpatialGradient
from kornia.geometry.conversions import cart2pol
from kornia.utils import create_meshgrid
# Precomputed coefficient... | [
"kornia.geometry.conversions.cart2pol",
"torch.nn.Sequential",
"torch.sqrt",
"torch.sin",
"torch.exp",
"torch.pow",
"torch.cos",
"torch.arange",
"torch.eye",
"torch.hub.load_state_dict_from_url",
"kornia.utils.create_meshgrid",
"torch.abs",
"torch.sign",
"torch.nn.functional.normalize",
... | [((992, 1078), 'kornia.utils.create_meshgrid', 'create_meshgrid', ([], {'height': 'patch_size', 'width': 'patch_size', 'normalized_coordinates': '(True)'}), '(height=patch_size, width=patch_size, normalized_coordinates\n =True)\n', (1007, 1078), False, 'from kornia.utils import create_meshgrid\n'), ((1141, 1155), 'k... |
import cv2
from pathlib import Path
# 分类器初始化
cascade_path = Path(__file__).absolute().parent / 'cat_face.xml'
cascade = cv2.CascadeClassifier(cascade_path.__str__())
def capture_cat_face(frame):
frame = cv2.resize(frame, (512, 512))
# 灰度处理
frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 猫脸检测
... | [
"cv2.resize",
"cv2.cvtColor",
"pathlib.Path"
] | [((211, 240), 'cv2.resize', 'cv2.resize', (['frame', '(512, 512)'], {}), '(frame, (512, 512))\n', (221, 240), False, 'import cv2\n'), ((269, 308), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2GRAY'], {}), '(frame, cv2.COLOR_BGR2GRAY)\n', (281, 308), False, 'import cv2\n'), ((62, 76), 'pathlib.Path', 'Path'... |
from application import create_app # pragma: no cover
app = create_app() # pragma: no cover
if __name__ == '__main__': # pragma: no cover
app.run()
| [
"application.create_app"
] | [((61, 73), 'application.create_app', 'create_app', ([], {}), '()\n', (71, 73), False, 'from application import create_app\n')] |
# Full tutorial - https://pythonprogramming.net/chinking-nltk-tutorial/
'''
Chinking is a lot like chunking, it is basically a way for you to remove a chunk from a chunk.
The chunk that you remove from your chunk is your chink.
The code is very similar, you just denote the chink, after the chunk, with }{ instead of t... | [
"nltk.tag.pos_tag",
"nltk.tokenize.PunktSentenceTokenizer",
"nltk.RegexpParser",
"nltk.tokenize.word_tokenize"
] | [((548, 572), 'nltk.tokenize.PunktSentenceTokenizer', 'PunktSentenceTokenizer', ([], {}), '()\n', (570, 572), False, 'from nltk.tokenize import PunktSentenceTokenizer, word_tokenize\n'), ((687, 703), 'nltk.tokenize.word_tokenize', 'word_tokenize', (['s'], {}), '(s)\n', (700, 703), False, 'from nltk.tokenize import Punk... |
#!/usr/bin/env python3
import pandas as pd
import sys
from tqdm import tqdm
# chr16 2547328 2549793 chr16 2652350 2654815 inv 107487
bedpeName = "chr16psv.bedpe"
bedpeName = "gridsearch1_head.txt"
#bedpe = pd.read_csv(bedpeName,sep="\t",)
#for row in bedpe.itertuples(index=True, name='Pandas'):
# print(row.achr,ro... | [
"pandas.read_csv"
] | [((430, 476), 'pandas.read_csv', 'pd.read_csv', (['bedpeName'], {'sep': '"""\t"""', 'chunksize': '(10)'}), "(bedpeName, sep='\\t', chunksize=10)\n", (441, 476), True, 'import pandas as pd\n')] |
from kivy.app import App
from kivy.clock import Clock
from kivy.core.window import Window
from kivy.graphics import BorderImage, Rectangle
from kivy.uix.label import Label
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.widget import Widget
class TextLabel(Label):
def __init__(self, text, **kwargs):
... | [
"kivy.clock.Clock.schedule_interval",
"kivy.graphics.BorderImage"
] | [((1340, 1386), 'kivy.clock.Clock.schedule_interval', 'Clock.schedule_interval', (['self.update', '(60 ** -1)'], {}), '(self.update, 60 ** -1)\n', (1363, 1386), False, 'from kivy.clock import Clock\n'), ((965, 1126), 'kivy.graphics.BorderImage', 'BorderImage', ([], {'size': '(self.label.width, self.label.height)', 'pos... |
"""
DuckDuckGo (Images)
@website https://duckduckgo.com/
@provide-api yes (https://duckduckgo.com/api),
but images are not supported
@using-api no
@results JSON (site requires js to get images)
@stable no (JSON can change)
@parse url, title, img_src
@todo avoid extra... | [
"json.loads",
"searx.url_utils.urlencode",
"searx.engines.duckduckgo.get_region_code"
] | [((1535, 1601), 'searx.engines.duckduckgo.get_region_code', 'get_region_code', (["params['language']"], {'lang_list': 'supported_languages'}), "(params['language'], lang_list=supported_languages)\n", (1550, 1601), False, 'from searx.engines.duckduckgo import _fetch_supported_languages, supported_languages_url, get_regi... |
"""The Media Source implementation for the Jellyfin integration."""
from __future__ import annotations
import logging
import mimetypes
from typing import Any
import urllib.parse
from jellyfin_apiclient_python.api import jellyfin_url
from jellyfin_apiclient_python.client import JellyfinClient
from homeassistant.compo... | [
"logging.getLogger",
"homeassistant.components.media_source.models.PlayMedia",
"jellyfin_apiclient_python.api.jellyfin_url",
"homeassistant.components.media_source.models.BrowseMediaSource",
"mimetypes.guess_type",
"homeassistant.components.media_player.errors.BrowseError"
] | [((1203, 1230), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1220, 1230), False, 'import logging\n'), ((11786, 11812), 'mimetypes.guess_type', 'mimetypes.guess_type', (['path'], {}), '(path)\n', (11806, 11812), False, 'import mimetypes\n'), ((11880, 11941), 'homeassistant.components.me... |
import torch.nn as nn
from torch.nn.functional import softmax
from torch.nn import CrossEntropyLoss
from typing import List, Any, Dict, Union
from sciwing.data.line import Line
from sciwing.data.label import Label
from wasabi import Printer
from sciwing.utils.class_nursery import ClassNursery
from sciwing.data.datasets... | [
"torch.nn.CrossEntropyLoss",
"wasabi.Printer",
"torch.tensor",
"torch.nn.Linear",
"torch.nn.functional.softmax",
"torch.device"
] | [((710, 729), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (722, 729), False, 'import torch\n'), ((1800, 1878), 'torch.nn.Linear', 'nn.Linear', (['self.encoding_dim', 'num_classes'], {'bias': 'self.classification_layer_bias'}), '(self.encoding_dim, num_classes, bias=self.classification_layer_bias)\... |
import os
if not os.path.exists('AdsorptionParameters.py'):
os.symlink('../AdsorptionParameters.py', 'AdsorptionParameters.py')
import matplotlib.pyplot as plt
import asap3.nanoparticle_mc.langmuirExpression as le
import numpy as np
#Test the CO Plot now
#Get one coverage for each CN for each temperature at 1mbar
... | [
"os.path.exists",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"os.symlink",
"numpy.linspace",
"asap3.nanoparticle_mc.langmuirExpression.getCoverages",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show"
] | [((324, 350), 'numpy.linspace', 'np.linspace', (['(0.1)', '(800)', '(100)'], {}), '(0.1, 800, 100)\n', (335, 350), True, 'import numpy as np\n'), ((602, 633), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'CN_4'], {'label': '"""CN 4"""'}), "(x, CN_4, label='CN 4')\n", (610, 633), True, 'import matplotlib.pyplot as plt\n... |
import os
import unittest
from streamlines.read_write import source, EXT_TO_OPEN
THIS_DIR = os.path.dirname(os.path.realpath(__file__))
FIXTURES_DIR = os.path.join(THIS_DIR, "fixtures")
def get_zen_of_python():
import codecs, sys
out = sys.stdout
with open(os.devnull, "w") as tmp_out:
sys.stdout ... | [
"os.path.realpath",
"codecs.encode",
"os.path.join",
"streamlines.read_write.source"
] | [((152, 186), 'os.path.join', 'os.path.join', (['THIS_DIR', '"""fixtures"""'], {}), "(THIS_DIR, 'fixtures')\n", (164, 186), False, 'import os\n'), ((109, 135), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (125, 135), False, 'import os\n'), ((406, 444), 'codecs.encode', 'codecs.encode', ([... |
from rpython.rtyper.lltypesystem import lltype, rffi
from rpython.rlib.objectmodel import specialize
from pypy.interpreter.error import oefmt
from pypy.interpreter.module import Module, init_extra_module_attrs
from pypy.module._hpy_universal.apiset import API, DEBUG
from pypy.module._hpy_universal import interp_extfunc... | [
"pypy.module._hpy_universal.apiset.API.func",
"rpython.rlib.objectmodel.specialize.arg",
"pypy.module._hpy_universal.apiset.DEBUG.func",
"rpython.rtyper.lltypesystem.rffi.constcharp2str",
"pypy.interpreter.module.init_extra_module_attrs",
"pypy.module._hpy_universal.state.State.get",
"pypy.module._hpy_u... | [((454, 522), 'pypy.module._hpy_universal.apiset.API.func', 'API.func', (['"""HPy HPyModule_Create(HPyContext *ctx, HPyModuleDef *def)"""'], {}), "('HPy HPyModule_Create(HPyContext *ctx, HPyModuleDef *def)')\n", (462, 522), False, 'from pypy.module._hpy_universal.apiset import API, DEBUG\n'), ((622, 732), 'pypy.module.... |
# Copyright 2013 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | [
"oslo_serialization.jsonutils.dumps",
"tempest.lib.common.rest_client.ResponseBody",
"oslo_serialization.jsonutils.loads"
] | [((1069, 1085), 'oslo_serialization.jsonutils.loads', 'json.loads', (['body'], {}), '(body)\n', (1079, 1085), True, 'from oslo_serialization import jsonutils as json\n'), ((1101, 1137), 'tempest.lib.common.rest_client.ResponseBody', 'rest_client.ResponseBody', (['resp', 'body'], {}), '(resp, body)\n', (1125, 1137), Fal... |
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Game(models.Model): #Overall Game Object
name = models.CharField(max_length=200) #name of the game
start_time = models.DateTimeField() #time to start
end_time = models.DateTimeField() #time game ends
... | [
"django.db.models.OneToOneField",
"django.db.models.ForeignKey",
"django.db.models.IntegerField",
"django.db.models.DateTimeField",
"django.db.models.CharField"
] | [((162, 194), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(200)'}), '(max_length=200)\n', (178, 194), False, 'from django.db import models\n'), ((228, 250), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {}), '()\n', (248, 250), False, 'from django.db import models\n'), ((279,... |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 28 11:46:55 2013
@author: Craig
"""
# standard modules
import json
import logging
import pprint
import urllib
import urllib2
# site modules
# local modules
# CONSTANTS
# CKAN structure:
# A CKAN site has a number of datasets
# Each dataset is a collection of datafil... | [
"urllib2.Request",
"json.dumps",
"urllib2.urlopen",
"pprint.pformat"
] | [((1275, 1295), 'urllib2.Request', 'urllib2.Request', (['url'], {}), '(url)\n', (1290, 1295), False, 'import urllib2\n'), ((1438, 1478), 'urllib2.urlopen', 'urllib2.urlopen', (['request', 'request_string'], {}), '(request, request_string)\n', (1453, 1478), False, 'import urllib2\n'), ((1393, 1417), 'json.dumps', 'json.... |
from sample_factory.envs.env_registry import global_env_registry
def create_env(full_env_name, cfg=None, env_config=None):
"""
Factory function that creates environment instances.
Matches full_env_name with env family prefixes registered in the REGISTRY and calls make_env_func()
for the first match.
... | [
"sample_factory.envs.env_registry.global_env_registry"
] | [((945, 966), 'sample_factory.envs.env_registry.global_env_registry', 'global_env_registry', ([], {}), '()\n', (964, 966), False, 'from sample_factory.envs.env_registry import global_env_registry\n')] |
# Copyright 2021 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | [
"cirq.devices.LineQid.for_gate"
] | [((1721, 1762), 'cirq.devices.LineQid.for_gate', 'devices.LineQid.for_gate', (['gate_controlled'], {}), '(gate_controlled)\n', (1745, 1762), False, 'from cirq import devices, ops\n')] |
import numpy as np
import cv2
import glob
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from queue import Queue
from moviepy.editor import VideoFileClip
# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((6*9,3), np.float32)
objp[:,:2] = np.mgrid[0:9,0... | [
"cv2.rectangle",
"numpy.hstack",
"numpy.polyfit",
"numpy.array",
"cv2.warpPerspective",
"cv2.destroyAllWindows",
"cv2.calibrateCamera",
"cv2.findChessboardCorners",
"matplotlib.pyplot.imshow",
"numpy.mean",
"matplotlib.pyplot.plot",
"cv2.undistort",
"numpy.max",
"cv2.addWeighted",
"numpy... | [((262, 294), 'numpy.zeros', 'np.zeros', (['(6 * 9, 3)', 'np.float32'], {}), '((6 * 9, 3), np.float32)\n', (270, 294), True, 'import numpy as np\n'), ((574, 616), 'glob.glob', 'glob.glob', (['"""./camera_cal/calibration*.jpg"""'], {}), "('./camera_cal/calibration*.jpg')\n", (583, 616), False, 'import glob\n'), ((1576, ... |
#!python
# To run from the root folder:
# trial tests/
import sys
import os
# When executed from the root folder
sys.path.append(os.path.abspath("./tests"))
sys.path.append(os.path.abspath("./src/vmcontroller.common"))
sys.path.append(os.path.abspath("./src/vmcontroller.host"))
sys.path.append(os.path.abspath("./src... | [
"os.path.abspath"
] | [((132, 158), 'os.path.abspath', 'os.path.abspath', (['"""./tests"""'], {}), "('./tests')\n", (147, 158), False, 'import os\n'), ((176, 220), 'os.path.abspath', 'os.path.abspath', (['"""./src/vmcontroller.common"""'], {}), "('./src/vmcontroller.common')\n", (191, 220), False, 'import os\n'), ((238, 280), 'os.path.abspa... |
import numpy as np
import cv2
circle_directions = ('north', 'north-northeast', 'northeast', 'east-northeast', 'east', 'east-southeast',
'southeast', 'south-southeast', 'south', 'south-southwest', 'southwest', 'west-southwest',
'west', 'west-northwest', 'northwest', 'north-nort... | [
"numpy.sum",
"numpy.array",
"cv2.boundingRect"
] | [((904, 929), 'cv2.boundingRect', 'cv2.boundingRect', (['contour'], {}), '(contour)\n', (920, 929), False, 'import cv2\n'), ((2161, 2177), 'numpy.sum', 'np.sum', (['validate'], {}), '(validate)\n', (2167, 2177), True, 'import numpy as np\n'), ((1314, 1330), 'numpy.array', 'np.array', (['radius'], {}), '(radius)\n', (13... |
# Generated by Django 3.0.11 on 2021-03-26 16:15
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import model_utils.fields
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
migra... | [
"django.db.models.TextField",
"django.db.models.ForeignKey",
"django.db.models.IntegerField",
"django.db.models.CharField",
"django.db.migrations.swappable_dependency",
"django.db.models.UUIDField"
] | [((315, 372), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (346, 372), False, 'from django.db import migrations, models\n'), ((507, 598), 'django.db.models.UUIDField', 'models.UUIDField', ([], {'default': 'uuid.uuid4'... |
from ..utils import constants, utils
import folium
from folium.plugins import HeatMap
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import shapely
from geojson import LineString
import geopandas as gpd
import json
import warnings
STACKLEVEL = 2
# COLOR = {
# 0: '#FF0000', # Red
# 1: '... | [
"geojson.LineString",
"numpy.median",
"folium.Icon",
"numpy.round",
"folium.Circle",
"json.dumps",
"folium.RegularPolygonMarker",
"operator.itemgetter",
"folium.Map",
"numpy.random.randint",
"folium.CircleMarker",
"folium.Popup",
"warnings.warn",
"folium.plugins.HeatMap",
"matplotlib.pyp... | [((16118, 16156), 'matplotlib.pyplot.xlim', 'plt.xlim', (['start_datetime', 'end_datetime'], {}), '(start_datetime, end_datetime)\n', (16126, 16156), True, 'import matplotlib.pyplot as plt\n'), ((1695, 1720), 'numpy.random.randint', 'np.random.randint', (['(0)', '(255)'], {}), '(0, 255)\n', (1712, 1720), True, 'import ... |
# Generated by Django 3.1.14 on 2022-01-21 14:34
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
("polio", "0041_move_preparedness_polio"),
]
operations = [
migrations.AlterField(
model_name="c... | [
"django.db.models.OneToOneField"
] | [((378, 524), 'django.db.models.OneToOneField', 'models.OneToOneField', ([], {'blank': '(True)', 'null': '(True)', 'on_delete': 'django.db.models.deletion.PROTECT', 'related_name': '"""campaign_round_one"""', 'to': '"""polio.round"""'}), "(blank=True, null=True, on_delete=django.db.models.\n deletion.PROTECT, relate... |
from decimal import Decimal
from django.utils.timezone import FixedOffset
from dynamic_preferences.types import *
from dynamic_preferences.registries import global_preferences_registry
from dynamic_preferences.users.registries import user_preferences_registry
from dynamic_preferences.preferences import Section
from d... | [
"dynamic_preferences.preferences.Section",
"django.utils.timezone.FixedOffset",
"decimal.Decimal",
"django.forms.ValidationError"
] | [((1995, 2005), 'decimal.Decimal', 'Decimal', (['(0)'], {}), '(0)\n', (2002, 2005), False, 'from decimal import Decimal\n'), ((4304, 4363), 'dynamic_preferences.preferences.Section', 'Section', (['"""child"""'], {'verbose_name': '"""Child Section Verbose Name"""'}), "('child', verbose_name='Child Section Verbose Name')... |
#!/usr/bin/env python3
from sys import stderr, exit, argv
import string
import random
from multilanguage import Env, Lang, TALcolors
from hash_and_cipher import hash_value
# METADATA OF THIS TAL_SERVICE:
problem="morra"
service="compute_hash"
args_list = [
('hash_type',str),
('white_string',str),
('lang... | [
"multilanguage.Env",
"sys.exit",
"hash_and_cipher.hash_value",
"multilanguage.TALcolors"
] | [((357, 389), 'multilanguage.Env', 'Env', (['problem', 'service', 'args_list'], {}), '(problem, service, args_list)\n', (360, 389), False, 'from multilanguage import Env, Lang, TALcolors\n'), ((395, 409), 'multilanguage.TALcolors', 'TALcolors', (['ENV'], {}), '(ENV)\n', (404, 409), False, 'from multilanguage import Env... |
import json
from datetime import datetime
import requests
from requests_oauthlib import OAuth2Session, OAuth2
from xero import Xero
from xero.constants import XERO_BASE_URL
# Use service discovery to find the endpoints we're going to use
connections_url = "https://api.xero.com/connections"
discovery_url = "https://id... | [
"datetime.datetime.utcfromtimestamp",
"requests.auth.HTTPBasicAuth",
"requests.get",
"requests_oauthlib.OAuth2",
"requests_oauthlib.OAuth2Session"
] | [((382, 409), 'requests.get', 'requests.get', (['discovery_url'], {}), '(discovery_url)\n', (394, 409), False, 'import requests\n'), ((851, 897), 'datetime.datetime.utcfromtimestamp', 'datetime.utcfromtimestamp', (["token['expires_at']"], {}), "(token['expires_at'])\n", (876, 897), False, 'from datetime import datetime... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.utils.translation import ugettext_lazy as _
from .models import CommentLike
class LikeForm(forms.ModelForm):
class Meta:
model = CommentLike
fields = []
def __init__(self, user=None, comme... | [
"django.utils.translation.ugettext_lazy"
] | [((883, 912), 'django.utils.translation.ugettext_lazy', '_', (['"""This like already exists"""'], {}), "('This like already exists')\n", (884, 912), True, 'from django.utils.translation import ugettext_lazy as _\n')] |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.20 on 2019-05-28 16:45
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('aldryn_people', '0037_rename_names_out_of_the_way'),
]
operations = [
migr... | [
"django.db.models.CharField"
] | [((419, 541), 'django.db.models.CharField', 'models.CharField', ([], {'default': '""""""', 'help_text': '"""Provide this person\'s first name."""', 'max_length': '(255)', 'verbose_name': '"""first name"""'}), '(default=\'\', help_text="Provide this person\'s first name.",\n max_length=255, verbose_name=\'first name\... |
import copy
import json
import logging
import os
import re
import shutil
from collections import defaultdict
from dataclasses import dataclass
from datetime import datetime
from json import JSONDecodeError
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Set, TextIO, Tuple, Type, Union, ... | [
"jinja2.Environment",
"click.File",
"os.path.sep.join",
"copy.deepcopy",
"copy.copy",
"pygments.formatters.html.HtmlFormatter",
"logging.info",
"os.path.exists",
"click.option",
"json.dumps",
"markdown2.Markdown",
"click.command",
"json.loads",
"htmlmin.minify",
"re.match",
"os.path.sp... | [((53933, 53948), 'click.command', 'click.command', ([], {}), '()\n', (53946, 53948), False, 'import click\n'), ((54274, 54486), 'click.option', 'click.option', (['"""--config"""'], {'multiple': '(True)', 'help': '"""Override generation parameters from the configuration file. Format is parameter_name=parameter_value. F... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2018 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... | [
"mock.patch",
"benchmarks.common.base_model_init.BaseModelInitializer",
"pytest.mark.skip",
"benchmarks.common.base_model_init.set_env_var",
"os.environ.get",
"pytest.mark.parametrize",
"io.StringIO",
"tempfile.mkstemp",
"mock.MagicMock"
] | [((2067, 2114), 'mock.patch', 'patch', (['"""benchmarks.common.base_model_init.open"""'], {}), "('benchmarks.common.base_model_init.open')\n", (2072, 2114), False, 'from mock import MagicMock, patch\n'), ((2117, 2149), 'mock.patch', 'patch', (['"""common.platform_util.os"""'], {}), "('common.platform_util.os')\n", (212... |
import src as ai
import numpy as np
import wandb
wandb.init(project='lstm-timeseries', config={'version' : 'new-a'})
model = ai.lstm(inshape=1, outshape=1, outactivation=ai.identity(), learningrate=0.01)
Data = np.genfromtxt(r"data/timeseries/airpassenger.csv", dtype=int)
Data = (Data - min(Data)) / (max(Data) - min... | [
"wandb.log",
"src.identity",
"wandb.init",
"numpy.sum",
"numpy.genfromtxt"
] | [((50, 116), 'wandb.init', 'wandb.init', ([], {'project': '"""lstm-timeseries"""', 'config': "{'version': 'new-a'}"}), "(project='lstm-timeseries', config={'version': 'new-a'})\n", (60, 116), False, 'import wandb\n'), ((214, 274), 'numpy.genfromtxt', 'np.genfromtxt', (['"""data/timeseries/airpassenger.csv"""'], {'dtype... |
from abc import abstractmethod
from pgmpy.extern.six.moves import reduce
class BaseFactor(object):
"""
Base class for Factors. Any Factor implementation should inherit this class.
"""
def __init__(self, *args, **kwargs):
pass
@abstractmethod
def is_valid_cpd(self):
pass
de... | [
"pgmpy.extern.six.moves.reduce"
] | [((1708, 1752), 'pgmpy.extern.six.moves.reduce', 'reduce', (['(lambda phi1, phi2: phi1 * phi2)', 'args'], {}), '(lambda phi1, phi2: phi1 * phi2, args)\n', (1714, 1752), False, 'from pgmpy.extern.six.moves import reduce\n')] |
import torch
from torch import nn
import torch.nn.functional as F
from torch.nn import BCEWithLogitsLoss
class DecoderLoss(nn.Module):
"""
Loss function for answer generation
computes the negative log-likelihood of the ground truth tokens
averaged per number of valid tokens
"""
def __init__(self, pad_idx, unk_... | [
"torch.nn.functional.softmax",
"torch.log",
"torch.device",
"torch.cuda.is_available",
"torch.nn.BCEWithLogitsLoss",
"torch.cuda.current_device",
"torch.ones"
] | [((3772, 3807), 'torch.nn.BCEWithLogitsLoss', 'BCEWithLogitsLoss', ([], {'reduction': '"""none"""'}), "(reduction='none')\n", (3789, 3807), False, 'from torch.nn import BCEWithLogitsLoss\n'), ((889, 914), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (912, 914), False, 'import torch\n'), ((920... |
from django.urls import include, path, register_converter as register
from .base import ID
from ..views import words
class Lemma(ID):
regex = f'{ID.regex}|[^/@][^/]*'
register(Lemma, 'lemma')
app_name = 'words'
urlpatterns = [
path('', words.List.as_view(), name='list'), # Includes new, search, and import
... | [
"django.urls.register_converter"
] | [((173, 197), 'django.urls.register_converter', 'register', (['Lemma', '"""lemma"""'], {}), "(Lemma, 'lemma')\n", (181, 197), True, 'from django.urls import include, path, register_converter as register\n')] |
import os
from GenericBase import GenericBase
from STAPLERerror import VirtualIOError
from STAPLERerror import STAPLERerror
import utils
class samtools_index(GenericBase):
"""Class for creating command lines for samtools index.
Parameters:
in_cmd: String containing a command line
in_dir... | [
"utils.infer_path_id",
"utils.splitext",
"utils.parse_config",
"os.path.join",
"STAPLERerror.VirtualIOError"
] | [((3358, 3410), 'utils.parse_config', 'utils.parse_config', (['self.name', '"""cmd_name"""', '"""execute"""'], {}), "(self.name, 'cmd_name', 'execute')\n", (3376, 3410), False, 'import utils\n'), ((7401, 7453), 'utils.parse_config', 'utils.parse_config', (['self.name', '"""cmd_name"""', '"""execute"""'], {}), "(self.na... |
import torch
def accuracy(preds, labels, ignore_index=None):
with torch.no_grad():
assert preds.shape[0] == len(labels)
correct = torch.sum(preds == labels)
total = torch.sum(torch.ones_like(labels))
if ignore_index is not None:
# 모델이 맞춘 것 가운데 ignore index에 해당하는 것 제외
... | [
"torch.no_grad",
"torch.ones_like",
"torch.sum",
"torch.logical_and"
] | [((72, 87), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (85, 87), False, 'import torch\n'), ((152, 178), 'torch.sum', 'torch.sum', (['(preds == labels)'], {}), '(preds == labels)\n', (161, 178), False, 'import torch\n'), ((205, 228), 'torch.ones_like', 'torch.ones_like', (['labels'], {}), '(labels)\n', (220, 22... |
from numpy.testing import assert_
from alns.Statistics import Statistics
def test_empty_new_statistics():
"""
Tests if a new Statistics object starts empty.
"""
statistics = Statistics()
assert_(len(statistics.objectives) == 0)
def test_collect_objectives():
"""
Tests if a Statistics ob... | [
"alns.Statistics.Statistics",
"numpy.testing.assert_"
] | [((193, 205), 'alns.Statistics.Statistics', 'Statistics', ([], {}), '()\n', (203, 205), False, 'from alns.Statistics import Statistics\n'), ((386, 398), 'alns.Statistics.Statistics', 'Statistics', ([], {}), '()\n', (396, 398), False, 'from alns.Statistics import Statistics\n'), ((550, 597), 'numpy.testing.assert_', 'as... |
#!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright (c) 2016--, Biota Technology.
# www.biota.com
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ---------------------... | [
"biom.load_table",
"tempfile.TemporaryDirectory",
"qiime2.Artifact.load",
"os.path.exists",
"pandas.read_csv",
"numpy.testing.assert_allclose",
"os.path.join",
"unittest.main",
"os.path.abspath",
"qiime2.plugins.sourcetracker2.actions.gibbs"
] | [((8970, 8985), 'unittest.main', 'unittest.main', ([], {}), '()\n', (8983, 8985), False, 'import unittest\n'), ((4888, 4913), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (4903, 4913), False, 'import os\n'), ((5230, 5284), 'os.path.join', 'os.path.join', (['tst_pth', '"""data/tiny-test/otu_... |
"""
Python for Windows
A lot of python object to help navigate windows stuff
Exported:
system : :class:`windows.winobject.System`
current_process : :class:`windows.winobject.CurrentProcess`
current_thread : :class:`windows.winobject.CurrentThread`
"""
# check we are on windows
import sys
if sys.platfor... | [
"sys.platform.capitalize",
"warnings.filterwarnings"
] | [((464, 541), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""once"""'], {'category': 'DeprecationWarning', 'module': '__name__'}), "('once', category=DeprecationWarning, module=__name__)\n", (487, 541), False, 'import warnings\n'), ((419, 444), 'sys.platform.capitalize', 'sys.platform.capitalize', ([], {})... |
from .typing import Any, Dict, Iterable, List, Mapping, Optional, TypedDict, Union
from .url import filename_to_uri
import os
import sublime
TextDocumentSyncKindNone = 0
TextDocumentSyncKindFull = 1
TextDocumentSyncKindIncremental = 2
class DiagnosticSeverity:
Error = 1
Warning = 2
Information = 3
H... | [
"os.path.basename"
] | [((14828, 14850), 'os.path.basename', 'os.path.basename', (['path'], {}), '(path)\n', (14844, 14850), False, 'import os\n')] |
from durable.lang import *
import durable.lang
import yaml
import os
import asyncio
import janus
import pytest
from queue import Queue
from pprint import pprint
from ansible_events.rules_parser import parse_rule_sets
from ansible_events.engine import run_rulesets, start_source
from ansible_events.messages import Shut... | [
"ansible_events.rule_types.EventSourceFilter",
"ansible_events.messages.Shutdown",
"asyncio.new_event_loop",
"asyncio.Queue",
"os.chdir",
"asyncio.set_event_loop",
"ansible_events.rules_parser.parse_rule_sets",
"ansible_events.util.load_inventory",
"os.path.abspath",
"queue.Queue",
"janus.Queue"... | [((465, 490), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (480, 490), False, 'import os\n'), ((523, 537), 'os.chdir', 'os.chdir', (['HERE'], {}), '(HERE)\n', (531, 537), False, 'import os\n'), ((551, 558), 'queue.Queue', 'Queue', ([], {}), '()\n', (556, 558), False, 'from queue import Queu... |
from spinta.utils.nestedstruct import flatten, build_select_tree
def test_flatten():
assert list(flatten([{'a': 1}])) == [{'a': 1}]
assert list(flatten([{'a': {'b': 1}}])) == [{'a.b': 1}]
assert list(flatten([{'a': {'b': [1, 2, 3]}}])) == [
{'a.b': 1},
{'a.b': 2},
{'a.b': 3},
]... | [
"spinta.utils.nestedstruct.build_select_tree",
"spinta.utils.nestedstruct.flatten"
] | [((1601, 1625), 'spinta.utils.nestedstruct.build_select_tree', 'build_select_tree', (["['a']"], {}), "(['a'])\n", (1618, 1625), False, 'from spinta.utils.nestedstruct import flatten, build_select_tree\n'), ((1669, 1697), 'spinta.utils.nestedstruct.build_select_tree', 'build_select_tree', (["['a.b.c']"], {}), "(['a.b.c'... |
from __future__ import division, print_function
from action_detector_diagnosis import ActionDetectorDiagnosis
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
import numpy as np
import pandas as pd
import os
from collections import OrderedDict
from utils import interpolated_prec_rec
from matplotlib i... | [
"action_detector_diagnosis.ActionDetectorDiagnosis",
"matplotlib.pyplot.GridSpec",
"numpy.nanmean",
"numpy.array",
"argparse.ArgumentParser",
"pandas.Categorical",
"numpy.linspace",
"matplotlib.pyplot.yticks",
"pandas.DataFrame",
"collections.OrderedDict",
"matplotlib.rcParams.update",
"matplo... | [((364, 378), 'matplotlib.use', 'mpl.use', (['"""Agg"""'], {}), "('Agg')\n", (371, 378), True, 'import matplotlib as mpl\n'), ((662, 689), 'matplotlib.rcParams.update', 'mpl.rcParams.update', (['params'], {}), '(params)\n', (681, 689), True, 'import matplotlib as mpl\n'), ((1970, 1983), 'collections.OrderedDict', 'Orde... |
import logging
import pandas as pd
import numpy as np
import json
from typing import List
from .. import instance_path
from . import DataSetInstance
logger = logging.getLogger(__name__)
class ZefDataFrame(DataSetInstance):
_linear_space = []
_multiselect_space = []
_text_space = []
def linear_ans... | [
"logging.getLogger",
"json.load",
"pandas.Series",
"pandas.DataFrame"
] | [((162, 189), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (179, 189), False, 'import logging\n'), ((682, 724), 'pandas.DataFrame', 'pd.DataFrame', ([], {'index': 'self.index', 'columns': '[]'}), '(index=self.index, columns=[])\n', (694, 724), True, 'import pandas as pd\n'), ((1056, 106... |
r"""
Variationally optimizing measurement protocols
==============================================
.. meta::
:property="og:description": Using a variational quantum algorithm to
optimize a quantum sensing protocol.
:property="og:image": https://pennylane.ai/qml/_images/illustration1.png
.. related::
... | [
"matplotlib.pyplot.grid",
"sympy.sqrt",
"matplotlib.pyplot.ylabel",
"pennylane.templates.ArbitraryStatePreparation",
"pennylane.device",
"pennylane.numpy.zeros_like",
"pennylane.numpy.array",
"pennylane.numpy.sum",
"matplotlib.pyplot.semilogy",
"pennylane.numpy.eye",
"pennylane.qnode",
"matplo... | [((7931, 7973), 'pennylane.device', 'qml.device', (['"""cirq.mixedsimulator"""'], {'wires': '(3)'}), "('cirq.mixedsimulator', wires=3)\n", (7941, 7973), True, 'import pennylane as qml\n'), ((9475, 9489), 'pennylane.qnode', 'qml.qnode', (['dev'], {}), '(dev)\n', (9484, 9489), True, 'import pennylane as qml\n'), ((11923,... |
import shlex
from unittest import TestCase, mock
from compose_flow.commands import Workflow
from tests import BaseTestCase
TEST_PROJECT_NAME = "test_project_name"
@mock.patch("compose_flow.commands.subcommands.env.utils")
@mock.patch("compose_flow.commands.subcommands.env.get_backend")
class WorkflowTestCase(Base... | [
"shlex.split",
"compose_flow.commands.Workflow",
"unittest.mock.patch",
"unittest.mock.Mock"
] | [((170, 227), 'unittest.mock.patch', 'mock.patch', (['"""compose_flow.commands.subcommands.env.utils"""'], {}), "('compose_flow.commands.subcommands.env.utils')\n", (180, 227), False, 'from unittest import TestCase, mock\n'), ((229, 292), 'unittest.mock.patch', 'mock.patch', (['"""compose_flow.commands.subcommands.env.... |
# Copyright (c) 2013 Yubico AB
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditi... | [
"setuptools.setup"
] | [((1430, 2353), 'setuptools.setup', 'setup', ([], {'name': '"""yubico-bitcoin"""', 'version': '"""0.0.1"""', 'author': '"""<NAME>"""', 'author_email': '"""<EMAIL>"""', 'maintainer': '"""Yubico Open Source Maintainers"""', 'maintainer_email': '"""<EMAIL>"""', 'url': '"""https://github.com/Yubico/yubico-bitcoin-python"""... |
"""
@FileName: lsb.py
@Description: Implement lsb
@Author: Ryuk
@CreateDate: 2021/06/27
@LastEditTime: 2021/06/27
@LastEditors: Please set LastEditors
@Version: v0.1
"""
import scipy.io.wavfile as wav
import numpy as np
np.random.seed(2020)
stop_mark = np.random.randint(0, 2, 128)
class LSBEmbedder:
def __init_... | [
"numpy.hstack",
"numpy.array",
"numpy.random.randint",
"scipy.io.wavfile.read",
"numpy.random.seed",
"numpy.concatenate",
"scipy.io.wavfile.write"
] | [((222, 242), 'numpy.random.seed', 'np.random.seed', (['(2020)'], {}), '(2020)\n', (236, 242), True, 'import numpy as np\n'), ((255, 283), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2)', '(128)'], {}), '(0, 2, 128)\n', (272, 283), True, 'import numpy as np\n'), ((822, 836), 'scipy.io.wavfile.read', 'wav.re... |
from __future__ import division, print_function, absolute_import
from torchreid import metrics
from torchreid.engine import Engine
from torchreid.losses import CrossEntropyLoss
class ImageSoftmaxNASEngine(Engine):
def __init__(
self,
datamanager,
model,
optimizer,
... | [
"torchreid.metrics.accuracy",
"torchreid.losses.CrossEntropyLoss"
] | [((1061, 1176), 'torchreid.losses.CrossEntropyLoss', 'CrossEntropyLoss', ([], {'num_classes': 'self.datamanager.num_train_pids', 'use_gpu': 'self.use_gpu', 'label_smooth': 'label_smooth'}), '(num_classes=self.datamanager.num_train_pids, use_gpu=self.\n use_gpu, label_smooth=label_smooth)\n', (1077, 1176), False, 'fr... |
from django.conf import settings
from dbag import dbag_manager
from dbag.metric_types import QueryMetric
class UserMetric(QueryMetric):
query_model = settings.AUTH_USER_MODEL
dbag_manager.register_metric_type('users_metric', UserMetric)
class ActiveUsersCount(UserMetric):
default_query_filter = {'key': 'i... | [
"dbag.dbag_manager.register_metric_type"
] | [((183, 244), 'dbag.dbag_manager.register_metric_type', 'dbag_manager.register_metric_type', (['"""users_metric"""', 'UserMetric'], {}), "('users_metric', UserMetric)\n", (216, 244), False, 'from dbag import dbag_manager\n'), ((347, 420), 'dbag.dbag_manager.register_metric_type', 'dbag_manager.register_metric_type', ([... |
import os
import getpass
import socket
import urllib
import asyncio
import asyncssh
import os
from contextlib import contextmanager
from .Config import cf
class Accession(object):
'''
From google: Definition (noun): a new item added to an existing collection
of books, paintings, or artifacts.
An Acc... | [
"urllib.parse.urlparse",
"getpass.getuser",
"asyncssh.connect",
"urllib.parse.urlunparse",
"asyncio.gather",
"os.path.abspath",
"asyncio.get_event_loop",
"socket.gethostname"
] | [((3317, 3344), 'urllib.parse.urlparse', 'urllib.parse.urlparse', (['path'], {}), '(path)\n', (3338, 3344), False, 'import urllib\n'), ((3968, 3996), 'urllib.parse.urlunparse', 'urllib.parse.urlunparse', (['url'], {}), '(url)\n', (3991, 3996), False, 'import urllib\n'), ((5356, 5382), 'urllib.parse.urlparse', 'urllib.p... |
from geocode.geocode import Geocode
from tqdm import tqdm
import pandas as pd
import numpy as np
import ast
from geopy.geocoders import Nominatim
from geopy.extra.rate_limiter import RateLimiter
import os
import logging
import time
logging.basicConfig(level=logging.INFO, format=',%(asctime)s [%(levelname)-5.5s] [%(nam... | [
"logging.basicConfig",
"logging.getLogger",
"geopy.extra.rate_limiter.RateLimiter",
"pandas.read_csv",
"geopy.geocoders.Nominatim",
"os.path.join",
"os.path.isfile",
"geocode.geocode.Geocode",
"ast.literal_eval",
"time.time"
] | [((233, 350), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'format': '""",%(asctime)s [%(levelname)-5.5s] [%(name)-12.12s]: %(message)s"""'}), "(level=logging.INFO, format=\n ',%(asctime)s [%(levelname)-5.5s] [%(name)-12.12s]: %(message)s')\n", (252, 350), False, 'import logging\n'), ... |
import json
import logging
import boto3
import botocore.exceptions
import zebr0
import zebr0_aws.sts
logger = logging.getLogger("zebr0-aws.iam")
logger.info("creating iam client")
class Client:
def __init__(self, zebr0_client: zebr0.Client, sts_client: zebr0_aws.sts.Client) -> None:
self.zebr0_client =... | [
"logging.getLogger",
"json.dumps",
"boto3.DEFAULT_SESSION.get_credentials"
] | [((113, 147), 'logging.getLogger', 'logging.getLogger', (['"""zebr0-aws.iam"""'], {}), "('zebr0-aws.iam')\n", (130, 147), False, 'import logging\n'), ((3326, 3365), 'boto3.DEFAULT_SESSION.get_credentials', 'boto3.DEFAULT_SESSION.get_credentials', ([], {}), '()\n', (3363, 3365), False, 'import boto3\n'), ((1342, 1585), ... |
'''
@author: deyan
@desc: 获取价格, 计算涨跌幅
'''
import api.stock as st
# 获取平安银行的行情数据 日K
data = st.get_single_price(code='000001.XSHE',
time_frequency='daily',
start_date='2020-01-01',
end_date='2020-02-01'
)
# print(... | [
"api.stock.get_single_price",
"api.stock.calculate_change_pct",
"api.stock.transfer_price_freq"
] | [((91, 207), 'api.stock.get_single_price', 'st.get_single_price', ([], {'code': '"""000001.XSHE"""', 'time_frequency': '"""daily"""', 'start_date': '"""2020-01-01"""', 'end_date': '"""2020-02-01"""'}), "(code='000001.XSHE', time_frequency='daily', start_date=\n '2020-01-01', end_date='2020-02-01')\n", (110, 207), Tr... |
from django.contrib.auth.models import (
Permission,
Group
)
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import ContentType
from papermerge.core.models import (
Access,
AccessDiff
)
# custom user is used - papermerge.core.models.User
User = get_user_model()
... | [
"django.contrib.auth.get_user_model",
"django.contrib.auth.models.Group.objects.get",
"papermerge.core.models.AccessDiff",
"django.contrib.contenttypes.models.ContentType.objects.get_or_create",
"papermerge.core.models.Access.objects.filter",
"django.contrib.auth.models.Permission.objects.filter",
"djan... | [((301, 317), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (315, 317), False, 'from django.contrib.auth import get_user_model\n'), ((440, 479), 'papermerge.core.models.AccessDiff', 'AccessDiff', ([], {'operation': 'AccessDiff.DELETE'}), '(operation=AccessDiff.DELETE)\n', (450, 479), False, ... |
from django.db import models
from general_business.models import Organization
# Create your models here.
class Campaign(models.Model):
title = models.CharField(
max_length = 300,
verbose_name = "Campaign Title"
)
subtitle = models.CharField(
max_length=300,
verbose_... | [
"django.db.models.ForeignKey",
"django.db.models.JSONField",
"django.db.models.ImageField",
"django.db.models.DateTimeField",
"django.db.models.URLField",
"django.db.models.CharField"
] | [((151, 214), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(300)', 'verbose_name': '"""Campaign Title"""'}), "(max_length=300, verbose_name='Campaign Title')\n", (167, 214), False, 'from django.db import models\n'), ((260, 326), 'django.db.models.CharField', 'models.CharField', ([], {'max_leng... |
"""A set of helper classes."""
import re
class Address(object):
"""A representation of a common address."""
def __init__(self, street=None, city=None, region=None, postcode=None,
country=None, extra=None, category=None):
"""Construct an address."""
self._category = category
... | [
"re.compile"
] | [((2802, 2835), 're.compile', 're.compile', (['"""[^@]+@[^@]+\\\\.[^@]+"""'], {}), "('[^@]+@[^@]+\\\\.[^@]+')\n", (2812, 2835), False, 'import re\n')] |
"""Initialize Config class to access environment variables."""
from dotenv import load_dotenv
import os
load_dotenv()
class Config(object):
"""Set environment variables."""
SQLALCHEMY_DATABASE_URI = os.getenv('SQLALCHEMY_DATABASE_URI')
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = os.getenv('SE... | [
"os.getenv",
"dotenv.load_dotenv"
] | [((105, 118), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (116, 118), False, 'from dotenv import load_dotenv\n'), ((210, 246), 'os.getenv', 'os.getenv', (['"""SQLALCHEMY_DATABASE_URI"""'], {}), "('SQLALCHEMY_DATABASE_URI')\n", (219, 246), False, 'import os\n'), ((307, 330), 'os.getenv', 'os.getenv', (['"""SE... |
import os
import random
import pickle as pk
import logging
from collections import defaultdict
from chemreader.readers.readmol2 import Mol2
import h5py
import numpy as np
from scipy import sparse
from tqdm import tqdm
from slgnn.config import PAD_ATOM, PAD_BOND
SEED = 1458907
random.seed(SEED)
class ZincToHdf5:
... | [
"random.sample",
"pickle.dump",
"random.shuffle",
"os.scandir",
"chemreader.readers.readmol2.Mol2",
"os.path.join",
"random.seed",
"h5py.File",
"tqdm.tqdm",
"pickle.load",
"numpy.array",
"collections.defaultdict",
"h5py.string_dtype",
"logging.info"
] | [((280, 297), 'random.seed', 'random.seed', (['SEED'], {}), '(SEED)\n', (291, 297), False, 'import random\n'), ((1515, 1535), 'os.scandir', 'os.scandir', (['dir_path'], {}), '(dir_path)\n', (1525, 1535), False, 'import os\n'), ((1822, 1848), 'random.shuffle', 'random.shuffle', (['mol2blocks'], {}), '(mol2blocks)\n', (1... |
#!/usr/bin/env python
"""
Script to set up report database
"""
import argparse
from sqlalchemy import create_engine
from gdcdatamodel.models.submission import Base
def setup(host, user, password, database):
engine = create_engine(
"postgres://{user}:{password}@{host}/{database}".format(
user=... | [
"argparse.ArgumentParser",
"gdcdatamodel.models.submission.Base.metadata.drop_all",
"gdcdatamodel.models.submission.Base.metadata.create_all"
] | [((394, 424), 'gdcdatamodel.models.submission.Base.metadata.drop_all', 'Base.metadata.drop_all', (['engine'], {}), '(engine)\n', (416, 424), False, 'from gdcdatamodel.models.submission import Base\n'), ((429, 461), 'gdcdatamodel.models.submission.Base.metadata.create_all', 'Base.metadata.create_all', (['engine'], {}), ... |
# -*- coding: utf-8 -*-
"""
debug.py - Functions to aid in debugging
Copyright 2010 <NAME>
Distributed under MIT/X11 license. See license.txt for more infomation.
"""
from acq4.pyqtgraph.debug import *
import acq4.pyqtgraph.debug as pgdebug
def printExc(msg='', indent=4, prefix='|', msgType='error'):
"""Print ... | [
"acq4.pyqtgraph.debug.printExc"
] | [((455, 492), 'acq4.pyqtgraph.debug.printExc', 'pgdebug.printExc', (['msg', 'indent', 'prefix'], {}), '(msg, indent, prefix)\n', (471, 492), True, 'import acq4.pyqtgraph.debug as pgdebug\n'), ((655, 712), 'acq4.pyqtgraph.debug.printExc', 'pgdebug.printExc', (['"""[failed to log this error to manager]"""'], {}), "('[fai... |
import sys
import Parser
def main():
with open(sys.argv[1], 'r') as file, open(sys.argv[2], 'w') as save:
fileName = sys.argv[1].split(".", 1)[0]
for line in file:
if (line.strip()).startswith("//") or not line.strip():
continue
else:
translatedLine = Parser.parser(line, fileName)
save.write(tra... | [
"Parser.parser"
] | [((272, 301), 'Parser.parser', 'Parser.parser', (['line', 'fileName'], {}), '(line, fileName)\n', (285, 301), False, 'import Parser\n')] |
# coding: utf-8
__author__ = "<NAME>"
from django.test import TestCase
from model_mommy import mommy
from core.models import ProcessedVideo
class ProcessedVideoModelTestCase(TestCase):
"""Class Testing Model processed """
def setUp(self):
"""
Initial Test Settings
"""
s... | [
"core.models.ProcessedVideo.objects.count",
"model_mommy.mommy.make",
"core.models.ProcessedVideo.objects.all"
] | [((342, 368), 'model_mommy.mommy.make', 'mommy.make', (['ProcessedVideo'], {}), '(ProcessedVideo)\n', (352, 368), False, 'from model_mommy import mommy\n'), ((983, 1013), 'core.models.ProcessedVideo.objects.count', 'ProcessedVideo.objects.count', ([], {}), '()\n', (1011, 1013), False, 'from core.models import Processed... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import session, Flask
import datetime
app = Flask(__name__)
app.config['SECRET_KEY'] = 'topsecret'
app.config['PERMANENT_SESSION_LIFETIME'] = datetime.timedelta(seconds=30)
@app.route('/')
def index():
session['foo'] = str(datetime.datetime.now())
ret... | [
"datetime.datetime.now",
"datetime.timedelta",
"flask.session.items",
"flask.Flask"
] | [((103, 118), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (108, 118), False, 'from flask import session, Flask\n'), ((201, 231), 'datetime.timedelta', 'datetime.timedelta', ([], {'seconds': '(30)'}), '(seconds=30)\n', (219, 231), False, 'import datetime\n'), ((288, 311), 'datetime.datetime.now', 'dateti... |
#-----------------------------------------------------------------------------
# Copyright (c) 2013-2020, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License (version 2
# or later) with exception for distributing the bootloader.
#
# The full license is in the file COPYING.txt... | [
"PyInstaller.utils.hooks.collect_data_files",
"PyInstaller.utils.hooks.collect_submodules"
] | [((840, 875), 'PyInstaller.utils.hooks.collect_submodules', 'collect_submodules', (['"""wx.lib.pubsub"""'], {}), "('wx.lib.pubsub')\n", (858, 875), False, 'from PyInstaller.utils.hooks import collect_submodules, collect_data_files\n'), ((1098, 1156), 'PyInstaller.utils.hooks.collect_data_files', 'collect_data_files', (... |
from itertools import product, starmap
from pytest import fixture, mark, raises
from loggingex.context import (
ContextChange,
ContextChangeAlreadyStartedException,
ContextChangeNotStartedException,
ContextInvalidNameException,
)
from .helpers import InitializedContextBase
def test_default_construct... | [
"loggingex.context.ContextChange.validate_context_variable_name",
"loggingex.context.ContextChange.validate_context_variable_names",
"itertools.product",
"pytest.mark.parametrize",
"pytest.raises",
"pytest.fixture",
"loggingex.context.ContextChange"
] | [((839, 909), 'pytest.mark.parametrize', 'mark.parametrize', (['"""value"""', "['?', '!', 'foo.bar', 'foo bar', 'foo-bar']"], {}), "('value', ['?', '!', 'foo.bar', 'foo bar', 'foo-bar'])\n", (855, 909), False, 'from pytest import fixture, mark, raises\n'), ((1119, 1190), 'pytest.mark.parametrize', 'mark.parametrize', (... |
# Copyright (c) Facebook, Inc. and its affiliates.
import logging
import warnings
from abc import ABC
import torch
from mmf.common.registry import registry
from mmf.utils.distributed import (
broadcast_xla_master_model_param,
get_world_size,
is_xla,
)
from omegaconf import open_dict
logger = logging.get... | [
"logging.getLogger",
"omegaconf.open_dict",
"torch.cuda.device_count",
"torch_xla.core.xla_model.xla_device",
"torch.cuda.is_available",
"torch.distributed.get_rank",
"torch_xla.core.xla_model.get_local_ordinal",
"torch.distributed.is_available",
"mmf.utils.distributed.broadcast_xla_master_model_par... | [((309, 336), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (326, 336), False, 'import logging\n'), ((1597, 1644), 'mmf.common.registry.registry.register', 'registry.register', (['"""global_device"""', 'self.device'], {}), "('global_device', self.device)\n", (1614, 1644), False, 'from mm... |
"""Testing Event object of cbc_sdk.platform"""
import pytest
import logging
from cbc_sdk.platform import Event, Process, EventFacet
from cbc_sdk.rest_api import CBCloudAPI
from cbc_sdk.errors import ApiError, TimeoutError
from tests.unit.fixtures.CBCSDKMock import CBCSDKMock
from tests.unit.fixtures.platform.mock_even... | [
"logging.basicConfig",
"pytest.raises",
"tests.unit.fixtures.CBCSDKMock.CBCSDKMock",
"pytest.fixture",
"cbc_sdk.rest_api.CBCloudAPI"
] | [((1272, 1385), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s %(levelname)s:%(message)s"""', 'level': 'logging.DEBUG', 'filename': '"""log.txt"""'}), "(format='%(asctime)s %(levelname)s:%(message)s', level=\n logging.DEBUG, filename='log.txt')\n", (1291, 1385), False, 'import logging\... |
import logging
import re
from collections import namedtuple
from datetime import time
import six
from six.moves.urllib.parse import (ParseResult, quote, urlparse,
urlunparse)
logger = logging.getLogger(__name__)
_Rule = namedtuple('Rule', ['field', 'value'])
RequestRate = namedtup... | [
"logging.getLogger",
"re.split",
"six.moves.urllib.parse.ParseResult",
"collections.namedtuple",
"re.escape",
"re.compile",
"six.moves.urllib.parse.urlparse",
"six.moves.urllib.parse.urlunparse",
"six.moves.urllib.parse.quote",
"re.sub"
] | [((222, 249), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (239, 249), False, 'import logging\n'), ((259, 297), 'collections.namedtuple', 'namedtuple', (['"""Rule"""', "['field', 'value']"], {}), "('Rule', ['field', 'value'])\n", (269, 297), False, 'from collections import namedtuple\n'... |
# Generated by Django 3.2.5 on 2021-07-24 11:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0002_alter_account_is_active'),
]
operations = [
migrations.AlterField(
model_name='account',
name='is_a... | [
"django.db.models.BooleanField"
] | [((346, 380), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (365, 380), False, 'from django.db import migrations, models\n')] |
"""Functions related to mapping parameter from model to parameter estimation
problem"""
import logging
import numbers
import os
import re
from typing import Tuple, Dict, Union, Any, List, Optional, Iterable
import libsbml
import numpy as np
import pandas as pd
from . import lint, measurements, sbml, core, observable... | [
"logging.getLogger",
"concurrent.futures.ThreadPoolExecutor",
"os.environ.get",
"re.compile"
] | [((406, 433), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (423, 433), False, 'import logging\n'), ((10833, 10882), 're.compile', 're.compile', (['"""^(noise|observable)Parameter[0-9]+_"""'], {}), "('^(noise|observable)Parameter[0-9]+_')\n", (10843, 10882), False, 'import re\n'), ((1820... |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
from datetime import datetime
import os
from unittest import TestCase
from unittest.mock import patch, MagicMock, call
with patch("boto3.client") as boto_client_mock:
from functions.usergamedata.UpdateItem i... | [
"datetime.datetime",
"functions.usergamedata.UpdateItem.index.ddb_client.update_item.assert_has_calls",
"unittest.mock.patch.dict",
"functions.usergamedata.UpdateItem.index.ddb_client.exceptions.ConditionalCheckFailedException",
"unittest.mock.MagicMock",
"unittest.mock.call",
"functions.usergamedata.Up... | [((515, 584), 'unittest.mock.patch.dict', 'patch.dict', (['os.environ', "{'BUNDLE_ITEMS_TABLE_NAME': ITEMS_TABLE_NAME}"], {}), "(os.environ, {'BUNDLE_ITEMS_TABLE_NAME': ITEMS_TABLE_NAME})\n", (525, 584), False, 'from unittest.mock import patch, MagicMock, call\n'), ((233, 254), 'unittest.mock.patch', 'patch', (['"""bot... |
# -*- coding: utf-8 -*-
import logging
from openprocurement.audit.api.constants import SCHEMA_VERSION, SCHEMA_DOC
LOGGER = logging.getLogger(__name__)
def get_db_schema_version(db):
schema_doc = db.get(SCHEMA_DOC, {"_id": SCHEMA_DOC})
return schema_doc.get("version", SCHEMA_VERSION - 1)
def set_db_schema_... | [
"logging.getLogger"
] | [((125, 152), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (142, 152), False, 'import logging\n')] |
"""Test the Firmata config flow."""
from unittest.mock import patch
from pymata_express.pymata_express_serial import serial
from homeassistant import config_entries, setup
from homeassistant.components.firmata.const import CONF_SERIAL_PORT, DOMAIN
from homeassistant.const import CONF_NAME
from homeassistant.core impo... | [
"homeassistant.setup.async_setup_component",
"unittest.mock.patch"
] | [((469, 533), 'homeassistant.setup.async_setup_component', 'setup.async_setup_component', (['hass', '"""persistent_notification"""', '{}'], {}), "(hass, 'persistent_notification', {})\n", (496, 533), False, 'from homeassistant import config_entries, setup\n'), ((544, 645), 'unittest.mock.patch', 'patch', (['"""homeassi... |
import time
from .. import jwt
import warnings
warnings.simplefilter('always', DeprecationWarning)
TASK_ROUTER_BASE_URL = 'https://taskrouter.twilio.com'
TASK_ROUTER_BASE_EVENTS_URL = 'https://event-bridge.twilio.com/v1/wschannels'
TASK_ROUTER_VERSION = "v1"
REQUIRED = {'required': True}
OPTIONAL = {'required': Fals... | [
"warnings.simplefilter",
"time.time"
] | [((48, 99), 'warnings.simplefilter', 'warnings.simplefilter', (['"""always"""', 'DeprecationWarning'], {}), "('always', DeprecationWarning)\n", (69, 99), False, 'import warnings\n'), ((6865, 6876), 'time.time', 'time.time', ([], {}), '()\n', (6874, 6876), False, 'import time\n')] |
import pytest
from flask import Flask, render_template_string
from flask_mobility import Mobility
from flask_mobility.decorators import mobile_template, mobilized
class TestDecorators(object):
@pytest.fixture()
def app(self):
app = Flask(__name__)
Mobility(app)
@app.route("/")
... | [
"flask_mobility.decorators.mobilized",
"flask.Flask",
"flask.render_template_string",
"flask_mobility.Mobility",
"pytest.fixture",
"flask_mobility.decorators.mobile_template"
] | [((201, 217), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (215, 217), False, 'import pytest\n'), ((251, 266), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (256, 266), False, 'from flask import Flask, render_template_string\n'), ((275, 288), 'flask_mobility.Mobility', 'Mobility', (['app'], {}), ... |
from ignite.metrics import Metric, Precision, Recall
from typing import Sequence, Callable, Optional, Union
import torch
from ignite.metrics.metric import reinit__is_reduced
__all__ = ["FbetaScore"]
class FbetaScore(Metric):
def __init__(
self,
beta: int = 1,
output_transform: Callable... | [
"torch.mean",
"ignite.metrics.Precision",
"ignite.metrics.Recall"
] | [((604, 719), 'ignite.metrics.Precision', 'Precision', ([], {'output_transform': 'output_transform', 'average': '_average_flag', 'is_multilabel': 'is_multilabel', 'device': 'device'}), '(output_transform=output_transform, average=_average_flag,\n is_multilabel=is_multilabel, device=device)\n', (613, 719), False, 'fr... |
import networkx as nx
import numpy as np
import math
from tqdm import tqdm
import numba
from numba.experimental import jitclass
from numba import jit
steadyspec = [
('adj_matrix',numba.float64[:,:]),
('graph_size',numba.int32),
('background_field',numba.float64[:]),
('fixed_point_iter',numba.int32)... | [
"numpy.identity",
"numpy.abs",
"numpy.sqrt",
"numpy.ones",
"numpy.arange",
"numpy.random.choice",
"numpy.sort",
"numba.experimental.jitclass",
"numpy.exp",
"numpy.array",
"numpy.zeros",
"numba.jit",
"numpy.sum",
"numpy.cumsum",
"numpy.maximum",
"networkx.to_numpy_matrix",
"math.tanh"... | [((361, 381), 'numba.experimental.jitclass', 'jitclass', (['steadyspec'], {}), '(steadyspec)\n', (369, 381), False, 'from numba.experimental import jitclass\n'), ((3349, 3367), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (3352, 3367), False, 'from numba import jit\n'), ((3451, 3469), 'numba.j... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Author: <NAME>
# Creation date: 2021-09-11 (year-month-day)
"""
Implements SGLD to sample from the input data distribution, and various buffers to
store the MCMC samples.
"""
import torch
import torch.nn as nn
from torch.distributions.bernoulli import Bernoulli as TorchBer... | [
"numpy.random.choice",
"torch.LongTensor",
"torch.stack",
"torch.distributions.bernoulli.Bernoulli",
"torch.randint",
"torch.argsort",
"torch.autograd.grad",
"numpy.setdiff1d",
"torch.no_grad",
"torch.zeros",
"numpy.arange",
"torch.randn"
] | [((2576, 2591), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2589, 2591), False, 'import torch\n'), ((1606, 1669), 'torch.autograd.grad', 'torch.autograd.grad', (['nrg_split', 'x_hat_split'], {'create_graph': '(False)'}), '(nrg_split, x_hat_split, create_graph=False)\n', (1625, 1669), False, 'import torch\n'), ... |
import os
import domain
import swagger
app = {
'URL_PREFIX': 'api',
'API_VERSION': 'v1',
'DEBUG': True,
'SWAGGER_INFO': swagger.api_doc_info,
'MONGO_URI': os.getenv('MONGO_URI'),
'ELASTICSEARCH_INDEX': 'chat',
'RESOURCE_METHODS': ['GET', 'POST', 'DELETE'],
'ITEM_METHODS': ['GET', 'PATCH... | [
"os.getenv"
] | [((176, 198), 'os.getenv', 'os.getenv', (['"""MONGO_URI"""'], {}), "('MONGO_URI')\n", (185, 198), False, 'import os\n')] |
# Copyright 2022 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, s... | [
"google.auth.credentials.AnonymousCredentials",
"os.environ.get",
"uuid.uuid4"
] | [((833, 897), 'os.environ.get', 'os.environ.get', (['"""STORAGE_EMULATOR_HOST"""', '"""http://localhost:9000"""'], {}), "('STORAGE_EMULATOR_HOST', 'http://localhost:9000')\n", (847, 897), False, 'import os\n'), ((1904, 1926), 'google.auth.credentials.AnonymousCredentials', 'AnonymousCredentials', ([], {}), '()\n', (192... |
import discord
from discord.ext import commands
import random
class EightBall(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(aliases=["8Ball", "Random8"])
async def _8Ball(self, ctx, *, question):
responses = [
"It is certain.",
"It is dec... | [
"random.choice",
"discord.ext.commands.command"
] | [((153, 199), 'discord.ext.commands.command', 'commands.command', ([], {'aliases': "['8Ball', 'Random8']"}), "(aliases=['8Ball', 'Random8'])\n", (169, 199), False, 'from discord.ext import commands\n'), ((996, 1020), 'random.choice', 'random.choice', (['responses'], {}), '(responses)\n', (1009, 1020), False, 'import ra... |
"""
Audience Handlers for Watchtower
"""
__author__ = ['<NAME>', '<NAME>']
import tornado.web
import tornado.escape
from logic.hashtags import topic_hashtag, get_hashtag_aggregations
from logic.helper import get_relevant_locations
from logic.topics import get_topic_list
from logic.users import get_current_topic, get... | [
"logic.hashtags.get_hashtag_aggregations",
"logic.hashtags.topic_hashtag",
"logic.topics.get_topic_list",
"logic.helper.get_relevant_locations"
] | [((737, 780), 'logic.hashtags.topic_hashtag', 'topic_hashtag', (['topic_id', 'hashtag', 'save_type'], {}), '(topic_id, hashtag, save_type)\n', (750, 780), False, 'from logic.hashtags import topic_hashtag, get_hashtag_aggregations\n'), ((1216, 1240), 'logic.helper.get_relevant_locations', 'get_relevant_locations', ([], ... |
"""
@author: <NAME>
@title: Third Activity - Binarization
"""
import skimage
from skimage.color import rgb2gray
from skimage import data
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['font.size'] = 18
import numpy as np
def Invert(image):
grayim = rgb2gray(image)
a, b = np.shape(... | [
"matplotlib.pyplot.imshow",
"skimage.color.rgb2gray",
"skimage.data.chelsea",
"matplotlib.pyplot.figure",
"numpy.empty",
"numpy.shape",
"matplotlib.pyplot.show"
] | [((788, 802), 'skimage.data.chelsea', 'data.chelsea', ([], {}), '()\n', (800, 802), False, 'from skimage import data\n'), ((803, 815), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (813, 815), True, 'import matplotlib.pyplot as plt\n'), ((816, 833), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image'], {}... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'interface.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import ... | [
"PyQt5.QtWidgets.QWidget",
"PyQt5.QtWidgets.QTextEdit",
"PyQt5.QtWidgets.QLineEdit",
"PyQt5.QtGui.QFont",
"PyQt5.QtWidgets.QListWidget",
"PyQt5.QtCore.QMetaObject.connectSlotsByName",
"PyQt5.QtWidgets.QProgressBar",
"PyQt5.QtWidgets.QHBoxLayout",
"PyQt5.QtWidgets.QVBoxLayout",
"PyQt5.QtWidgets.QGr... | [((531, 567), 'PyQt5.QtWidgets.QStackedWidget', 'QtWidgets.QStackedWidget', (['mainWindow'], {}), '(mainWindow)\n', (555, 567), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((720, 739), 'PyQt5.QtWidgets.QWidget', 'QtWidgets.QWidget', ([], {}), '()\n', (737, 739), False, 'from PyQt5 import QtCore, QtGui, QtWi... |
import json
from lib.solutions.CHK.checkout_solution import checkout
import string
import importlib.resources
class Test:
def test_k_functionality(self):
input_skus = "KK"
total_value = checkout(input_skus)
assert total_value == 120
def test_n_functionality(self):
input_skus ... | [
"json.load",
"lib.solutions.CHK.checkout_solution.checkout"
] | [((209, 229), 'lib.solutions.CHK.checkout_solution.checkout', 'checkout', (['input_skus'], {}), '(input_skus)\n', (217, 229), False, 'from lib.solutions.CHK.checkout_solution import checkout\n'), ((351, 371), 'lib.solutions.CHK.checkout_solution.checkout', 'checkout', (['input_skus'], {}), '(input_skus)\n', (359, 371),... |
################################################################################
# MIT License
#
# Copyright (c) 2017 <NAME> & <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... | [
"txpostgres.reconnection.DeadConnectionDetector.reconnect",
"txpostgres.reconnection.DeadConnectionDetector.startReconnecting",
"txpostgres.reconnection.DeadConnectionDetector.connectionRecovered",
"twisted.internet.defer.returnValue"
] | [((4127, 4146), 'twisted.internet.defer.returnValue', 'returnValue', (['answer'], {}), '(answer)\n', (4138, 4146), False, 'from twisted.internet.defer import inlineCallbacks, returnValue\n'), ((2207, 2256), 'txpostgres.reconnection.DeadConnectionDetector.startReconnecting', 'DeadConnectionDetector.startReconnecting', (... |
#-- GoldenFace 1.0 (Face Golden Ratio & Cosine Similarity Library)--
# Author : <NAME>
# Date : 15.05.2020
# Description : Facial Cosine Similarity,Face Golden Ratio Calculation And Facial Landmark Detecting/Drawing Library
# Website : http://umit.space
# Mail : <EMAIL>
# Github : https://gi... | [
"cv2.rectangle",
"cv2.imwrite",
"cv2.face.createFacemarkLBF",
"pkg_resources.resource_filename",
"cv2.cvtColor",
"cv2.CascadeClassifier",
"cv2.imread"
] | [((706, 722), 'cv2.imread', 'cv2.imread', (['path'], {}), '(path)\n', (716, 722), False, 'import cv2\n'), ((748, 790), 'cv2.cvtColor', 'cv2.cvtColor', (['self.img', 'cv2.COLOR_BGR2GRAY'], {}), '(self.img, cv2.COLOR_BGR2GRAY)\n', (760, 790), False, 'import cv2\n'), ((823, 851), 'cv2.face.createFacemarkLBF', 'cv2.face.cr... |