code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import cv2
# cv2 method to capture frames from live video
cap = cv2.VideoCapture(0)
# loop to get frames
while(1):
# read every frame from
ret, videoframe = cap.read()
# Display the frame
cv2.imshow('Camera',videoframe)
# delay
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# camera realesing
cap.re... | [
"cv2.waitKey",
"cv2.destroyAllWindows",
"cv2.VideoCapture",
"cv2.imshow"
] | [((65, 84), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (81, 84), False, 'import cv2\n'), ((355, 378), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (376, 378), False, 'import cv2\n'), ((199, 231), 'cv2.imshow', 'cv2.imshow', (['"""Camera"""', 'videoframe'], {}), "('Camera', vi... |
#!/usr/bin/env python3
# Author:: <NAME> (mailto:<EMAIL>)
"""
Project Configuration for Pushover Variables
"""
import logging
from os import environ
logger = logging.getLogger(__name__)
class PushoverConfig(object):
"""
Pushover Notification Config Class
"""
PUSHOVER_API_ENDPOINT: str = "http... | [
"logging.getLogger"
] | [((166, 193), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (183, 193), False, 'import logging\n')] |
import enum
import logging
from typing import Any, Dict, List, Optional, Set
import determined as det
from determined import tensorboard
from determined.common.api import errors
from determined.common.experimental.session import Session
logger = logging.getLogger("determined.core")
class EarlyExitReason(enum.Enum):... | [
"logging.getLogger",
"determined.util.json_encode"
] | [((248, 284), 'logging.getLogger', 'logging.getLogger', (['"""determined.core"""'], {}), "('determined.core')\n", (265, 284), False, 'import logging\n'), ((3274, 3300), 'determined.util.json_encode', 'det.util.json_encode', (['body'], {}), '(body)\n', (3294, 3300), True, 'import determined as det\n'), ((5462, 5488), 'd... |
import os
import pytest
import shutil
import flask
from flask import Flask
import graphene
import pprint
from graphene.test import Client
from mock import patch
import responses
from gtmcore.auth.identity import get_identity_manager_class
from gtmcore.configuration import Configuration
from gtmcore.gitlib import RepoL... | [
"flask.Flask",
"lmsrvcore.middleware.DataloaderMiddleware",
"gtmcore.files.FileOperations.insert_file",
"gtmcore.inventory.inventory.InventoryManager",
"gtmcore.files.FileOperations.makedir",
"responses.RequestsMock",
"pytest.fixture",
"pprint.pprint",
"os.path.exists",
"mock.patch",
"lmsrvlabbo... | [((987, 1003), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (1001, 1003), False, 'import pytest\n'), ((1110, 1128), 'gtmcore.inventory.inventory.InventoryManager', 'InventoryManager', ([], {}), '()\n', (1126, 1128), False, 'from gtmcore.inventory.inventory import InventoryManager\n'), ((1396, 1443), 'gtmcore.f... |
'''
Description: 构造一个数据集类,继承官方的torch.utils.data.Dataset
Author: HCQ
Company(School): UCAS
Email: <EMAIL>
Date: 2021-06-05 11:19:36
LastEditTime: 2021-06-10 10:40:49
FilePath: /pointnet-simple/framework/dataset.py
'''
import torch
import os
import json
from torch.utils.data import Dataset # 官方
from torch.utils.data impo... | [
"numpy.random.normal",
"numpy.mean",
"os.listdir",
"torch.utils.data.DataLoader",
"torch.Tensor",
"numpy.array",
"numpy.zeros",
"numpy.sum",
"numpy.cos",
"numpy.random.uniform",
"numpy.sin"
] | [((417, 428), 'numpy.zeros', 'np.zeros', (['(0)'], {}), '(0)\n', (425, 428), True, 'import numpy as np\n'), ((3954, 4004), 'torch.utils.data.DataLoader', 'DataLoader', (['train_data'], {'batch_size': '(2)', 'shuffle': '(True)'}), '(train_data, batch_size=2, shuffle=True)\n', (3964, 4004), False, 'from torch.utils.data ... |
# -*- coding: utf-8 -*-
"""
Illuminants Spectral Distributions
==================================
Defines *CIE* illuminants spectral distributions for the
*CIE 1931 2 Degree Standard Observer*.
The *CIE* illuminants data is in the form of a *dict* of
:class:`colour.SpectralDistribution` classes as follows::
{'na... | [
"colour.colorimetry.spectrum.SpectralDistribution"
] | [((74045, 74102), 'colour.colorimetry.spectrum.SpectralDistribution', 'SpectralDistribution', (["ILLUMINANTS_SDS_DATA['A']"], {'name': '"""A"""'}), "(ILLUMINANTS_SDS_DATA['A'], name='A')\n", (74065, 74102), False, 'from colour.colorimetry.spectrum import SpectralDistribution\n'), ((74121, 74178), 'colour.colorimetry.sp... |
import sys # --STRIP DURING BUILD
import re # --STRIP DURING BUILD
# --STRIP DURING BUILD
# --STRIP DURING BUILD
def register_vcs_handler(*args): # --STRIP DURING BUILD
def nil(f): # --STRIP DURING BUILD
return f # --STRIP DURING BUILD
return nil # --STRIP DURING BUILD
# --STRIP DURING BUILD... | [
"re.search"
] | [((2624, 2677), 're.search', 're.search', (['"""^(.+)-(\\\\d+)-g([0-9a-f]+)$"""', 'git_describe'], {}), "('^(.+)-(\\\\d+)-g([0-9a-f]+)$', git_describe)\n", (2633, 2677), False, 'import re\n')] |
import os
import gc
import sys
import click
import random
import sklearn
import numpy as np
import pandas as pd
from pprint import pprint
from config import read_config, KEY_FEATURE_MAP, KEY_MODEL_MAP
from utils import timer, reduce_mem_usage
from models import LightGBM
from features.base import Base
from features.fea... | [
"utils.timer",
"features.base.Base.get_df",
"click.option",
"config.read_config",
"features.stacking.StackingFeaturesWithPasses.set_result_dirs",
"random.random",
"features.stacking.StackingFeaturesWithPasses.get_df",
"gc.collect",
"warnings.simplefilter",
"features.feature_cleaner.clean_data",
... | [((425, 487), 'warnings.simplefilter', 'warnings.simplefilter', ([], {'action': '"""ignore"""', 'category': 'FutureWarning'}), "(action='ignore', category=FutureWarning)\n", (446, 487), False, 'import warnings\n'), ((2204, 2219), 'click.command', 'click.command', ([], {}), '()\n', (2217, 2219), False, 'import click\n')... |
# -*- coding: utf-8 -*-
import setuptools
import os
from io import open
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.rst'), encoding='utf-8') as f:
readme_contents = f.read()
setuptools.setup(
name='initmodule',
version='0.0.1',
description='Initialize a new Python ... | [
"os.path.dirname",
"setuptools.find_packages",
"os.path.join"
] | [((97, 122), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (112, 122), False, 'import os\n'), ((135, 167), 'os.path.join', 'os.path.join', (['here', '"""README.rst"""'], {}), "(here, 'README.rst')\n", (147, 167), False, 'import os\n'), ((715, 741), 'setuptools.find_packages', 'setuptools.fin... |
# -*- coding: utf-8 -*-
"""Tests the xonsh lexer."""
from __future__ import unicode_literals, print_function
import os
import pytest
from xonsh.wizard import (Node, Wizard, Pass, PrettyFormatter,
Message, Question, StateVisitor)
TREE0 = Wizard(children=[Pass(), Message(message='yo')])
TREE1 = Question('wakka?'... | [
"xonsh.wizard.StateVisitor",
"xonsh.wizard.PrettyFormatter",
"xonsh.wizard.Message",
"xonsh.wizard.Pass"
] | [((1039, 1053), 'xonsh.wizard.StateVisitor', 'StateVisitor', ([], {}), '()\n', (1051, 1053), False, 'from xonsh.wizard import Node, Wizard, Pass, PrettyFormatter, Message, Question, StateVisitor\n'), ((333, 339), 'xonsh.wizard.Pass', 'Pass', ([], {}), '()\n', (337, 339), False, 'from xonsh.wizard import Node, Wizard, P... |
import io
from pkg_resources import resource_filename
from starfish.codebook._format import CURRENT_VERSION, DocumentKeys
from .util import Fuzzer, SpaceTxValidator
package_name = "starfish"
codebook_schema_path = resource_filename(
package_name, "spacetx_format/schema/codebook/codebook.json")
experiment_schema_... | [
"io.StringIO",
"pkg_resources.resource_filename"
] | [((217, 296), 'pkg_resources.resource_filename', 'resource_filename', (['package_name', '"""spacetx_format/schema/codebook/codebook.json"""'], {}), "(package_name, 'spacetx_format/schema/codebook/codebook.json')\n", (234, 296), False, 'from pkg_resources import resource_filename\n'), ((327, 399), 'pkg_resources.resourc... |
import logging
from collections import OrderedDict
from pathlib import Path
import torch
def load_model_layers_from_path(path: Path, layer_names: set):
logger = logging.getLogger(__name__)
logger.info(f'Loading model from {path}')
if torch.cuda.is_available():
checkpoint = torch.load(path)
el... | [
"logging.getLogger",
"collections.OrderedDict",
"torch.cuda.is_available",
"torch.load"
] | [((168, 195), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (185, 195), False, 'import logging\n'), ((249, 274), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (272, 274), False, 'import torch\n'), ((410, 423), 'collections.OrderedDict', 'OrderedDict', ([], {}), ... |
import os
import simplejson as json
from getpass import getpass
from pytezos.crypto import Key
class Keychain:
def __init__(self, path='~/.tezos-client/secret_keys'):
self._path = os.path.expanduser(path)
self._secret_keys = list()
self._last_modified = 0
def reload(self):
l... | [
"pytezos.crypto.Key",
"getpass.getpass",
"simplejson.load",
"os.path.getmtime",
"os.path.expanduser"
] | [((196, 220), 'os.path.expanduser', 'os.path.expanduser', (['path'], {}), '(path)\n', (214, 220), False, 'import os\n'), ((335, 363), 'os.path.getmtime', 'os.path.getmtime', (['self._path'], {}), '(self._path)\n', (351, 363), False, 'import os\n'), ((813, 865), 'getpass.getpass', 'getpass', (['f"""Please, enter passphr... |
# No shebang line, this module is meant to be imported
#
# Copyright 2013 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless r... | [
"flask.render_template",
"pyfarm.master.application.db.session.add",
"pyfarm.master.application.db.session.commit",
"pyfarm.models.user.Role.query.filter_by",
"pyfarm.models.user.Role.create",
"wtforms.validators.Required",
"pyfarm.models.user.User.get",
"wtforms.ValidationError",
"pyfarm.models.use... | [((1170, 1204), 'pyfarm.models.user.User.get', 'User.get', (["request.form['username']"], {}), "(request.form['username'])\n", (1178, 1204), False, 'from pyfarm.models.user import User, Role\n'), ((1766, 1865), 'flask.render_template', 'render_template', (['"""pyfarm/setup.html"""'], {'form': 'form', 'admin_role': 'adm... |
from wagtail_editor_extensions.conf import get_setting
def get_feature_choices(feature_setting):
return tuple(get_setting(feature_setting).items())
def get_feature_name(feature_name, name):
feature = '%s_%s' % (feature_name, name)
return feature
def get_feature_name_upper(feature_name, name):
retu... | [
"wagtail_editor_extensions.conf.get_setting"
] | [((116, 144), 'wagtail_editor_extensions.conf.get_setting', 'get_setting', (['feature_setting'], {}), '(feature_setting)\n', (127, 144), False, 'from wagtail_editor_extensions.conf import get_setting\n'), ((495, 523), 'wagtail_editor_extensions.conf.get_setting', 'get_setting', (['feature_setting'], {}), '(feature_sett... |
from typing import Optional
from pydantic import BaseModel, Field
class Ping(BaseModel):
app_branch: Optional[str] = Field(None, example='test_branch')
build_date: Optional[str] = Field(None, example='02022022')
build_tag: Optional[str] = Field(None, example='test')
commit_id: Optional[str] = Field(No... | [
"pydantic.Field"
] | [((123, 157), 'pydantic.Field', 'Field', (['None'], {'example': '"""test_branch"""'}), "(None, example='test_branch')\n", (128, 157), False, 'from pydantic import BaseModel, Field\n'), ((190, 221), 'pydantic.Field', 'Field', (['None'], {'example': '"""02022022"""'}), "(None, example='02022022')\n", (195, 221), False, '... |
"""
Helpers for dealing with HTML input.
"""
import re
from django.utils.datastructures import MultiValueDict
def is_html_input(dictionary):
# MultiDict type datastructures are used to represent HTML form input,
# which may have more than one value for each key.
return hasattr(dictionary, 'getlist')
de... | [
"django.utils.datastructures.MultiValueDict",
"re.escape"
] | [((1966, 1982), 'django.utils.datastructures.MultiValueDict', 'MultiValueDict', ([], {}), '()\n', (1980, 1982), False, 'from django.utils.datastructures import MultiValueDict\n'), ((1061, 1078), 're.escape', 're.escape', (['prefix'], {}), '(prefix)\n', (1070, 1078), False, 'import re\n'), ((2022, 2039), 're.escape', 'r... |
# -*- coding: utf-8 -*-
#
# Copyright © 2013 The Spyder Development Team
# Licensed under the terms of the MIT License
# (see spyderlib/__init__.py for details)
"""
Jedi Introspection Plugin
"""
import re
import os.path as osp
import sys
import time
import threading
from spyderlib import dependencies
from spyderlib.b... | [
"spyderlib.utils.debug.log_dt",
"spyderlib.baseconfig.debug_print",
"jedi.Script",
"spyderlib.utils.programs.is_module_installed",
"re.match",
"os.path.splitext",
"time.sleep",
"sys.meta_path.remove",
"jedi.preload_module",
"os.path.dirname",
"spyderlib.utils.debug.log_last_error",
"spyderlib.... | [((751, 822), 'spyderlib.baseconfig._', '_', (['"""(Experimental) Editor\'s code completion, go-to-definition and help"""'], {}), '("(Experimental) Editor\'s code completion, go-to-definition and help")\n', (752, 822), False, 'from spyderlib.baseconfig import _, debug_print\n'), ((9229, 9240), 'time.time', 'time.time',... |
import pytest
import statey as st
from statey.syms import casters
RAISES = object()
@pytest.mark.parametrize(
"from_type, to_type, check",
[
pytest.param(int, int, lambda x: isinstance(x, casters.ForceCaster), id="int"),
pytest.param(~st.Integer, int, RAISES, id="int_from_nullable"),
... | [
"pytest.raises",
"pytest.param"
] | [((249, 311), 'pytest.param', 'pytest.param', (['(~st.Integer)', 'int', 'RAISES'], {'id': '"""int_from_nullable"""'}), "(~st.Integer, int, RAISES, id='int_from_nullable')\n", (261, 311), False, 'import pytest\n'), ((760, 821), 'pytest.param', 'pytest.param', (['(~st.String)', 'str', 'RAISES'], {'id': '"""str_from_nulla... |
#!/usr/bin/env python3
"""
Copyright (c) 2019-2021 Antmicro <www.antmicro.com>
Renode platform definition (repl) and script (resc) generator for LiteX SoC.
This script parses LiteX 'csr.json' file and generates scripts for Renode
necessary to emulate the given configuration of the LiteX SoC.
"""
import os
import sys... | [
"sys.exit",
"argparse.ArgumentParser",
"os.path.basename",
"zlib.crc32",
"json.load"
] | [((25849, 25874), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (25872, 25874), False, 'import argparse\n'), ((24566, 24577), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (24574, 24577), False, 'import sys\n'), ((27865, 27877), 'json.load', 'json.load', (['f'], {}), '(f)\n', (27874, 27877),... |
# MIT License
#
# Copyright (c) 2019 <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,... | [
"logging.getLogger",
"supporting.log",
"pathlib.Path"
] | [((1373, 1400), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1390, 1400), False, 'import supporting, logging\n'), ((1477, 1535), 'supporting.log', 'supporting.log', (['logger', 'logging.DEBUG', 'thisproc', '"""started"""'], {}), "(logger, logging.DEBUG, thisproc, 'started')\n", (1491, ... |
"""
Project Euler Problem 174: https://projecteuler.net/problem=174
We shall define a square lamina to be a square outline with a square "hole" so that
the shape possesses vertical and horizontal symmetry.
Given eight tiles it is possible to form a lamina in only one way: 3x3 square with a
1x1 hole in the midd... | [
"math.sqrt",
"collections.defaultdict"
] | [((950, 966), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (961, 966), False, 'from collections import defaultdict\n'), ((1137, 1178), 'math.sqrt', 'sqrt', (['(outer_width * outer_width - t_limit)'], {}), '(outer_width * outer_width - t_limit)\n', (1141, 1178), False, 'from math import ceil, sqrt... |
import numpy as np
import numpy.linalg as LA
import quaternion
from . import wind
from .launcher import Launcher
from .air import Air
class Enviroment:
def __init__(
self,
latitude,
longitude,
altitude=0
):
self.latitude = latitude
... | [
"numpy.dot",
"numpy.array",
"numpy.deg2rad",
"numpy.linalg.inv"
] | [((1043, 1171), 'numpy.array', 'np.array', (['[[-sinlon, -sinlat * coslon, coslat * coslon], [coslon, -sinlat * sinlon, \n coslat * sinlon], [0.0, coslat, sinlat]]'], {}), '([[-sinlon, -sinlat * coslon, coslat * coslon], [coslon, -sinlat *\n sinlon, coslat * sinlon], [0.0, coslat, sinlat]])\n', (1051, 1171), True... |
from topaz.module import ClassDef
from topaz.objects.objectobject import W_Object
from topaz.modules.ffi.function import W_FFIFunctionObject
from rpython.rlib import jit
class W_VariadicInvokerObject(W_Object):
classdef = ClassDef('VariadicInvoker', W_Object.classdef)
def __init__(self, space):
W_Ob... | [
"topaz.objects.objectobject.W_Object.__init__",
"topaz.module.ClassDef"
] | [((229, 275), 'topaz.module.ClassDef', 'ClassDef', (['"""VariadicInvoker"""', 'W_Object.classdef'], {}), "('VariadicInvoker', W_Object.classdef)\n", (237, 275), False, 'from topaz.module import ClassDef\n'), ((316, 346), 'topaz.objects.objectobject.W_Object.__init__', 'W_Object.__init__', (['self', 'space'], {}), '(sel... |
from recolor import Core
def main():
# Simulating Protanopia with diagnosed degree of 0.9 and saving the image to file.
Core.simulate(input_path='Examples_Check/ex_original.jpg',
return_type='save',
save_path='Examples_Check/ex_simulate_protanopia.png',
si... | [
"recolor.Core.correct",
"recolor.Core.simulate"
] | [((130, 329), 'recolor.Core.simulate', 'Core.simulate', ([], {'input_path': '"""Examples_Check/ex_original.jpg"""', 'return_type': '"""save"""', 'save_path': '"""Examples_Check/ex_simulate_protanopia.png"""', 'simulate_type': '"""protanopia"""', 'simulate_degree_primary': '(0.9)'}), "(input_path='Examples_Check/ex_orig... |
__author__ = 'sibirrer'
import numpy as np
from lenstronomy.LensModel.Profiles.base_profile import LensProfileBase
from lenstronomy.Util import derivative_util as calc_util
__all__ = ['CoredDensity']
class CoredDensity(LensProfileBase):
"""
class for a uniform cored density dropping steep in the outskirts
... | [
"lenstronomy.Util.derivative_util.d_x_diffr_dx",
"numpy.sqrt",
"lenstronomy.Util.derivative_util.d_r_dy",
"lenstronomy.Util.derivative_util.d_x_diffr_dy",
"numpy.log",
"lenstronomy.Util.derivative_util.d_r_dx",
"numpy.maximum",
"lenstronomy.Util.derivative_util.d_y_diffr_dy",
"numpy.arctan"
] | [((1301, 1327), 'numpy.sqrt', 'np.sqrt', (['(x_ ** 2 + y_ ** 2)'], {}), '(x_ ** 2 + y_ ** 2)\n', (1308, 1327), True, 'import numpy as np\n'), ((1340, 1362), 'numpy.maximum', 'np.maximum', (['r', 'self._s'], {}), '(r, self._s)\n', (1350, 1362), True, 'import numpy as np\n'), ((1996, 2022), 'numpy.sqrt', 'np.sqrt', (['(x... |
import logging
import sys
from datetime import datetime
from decimal import Decimal
from base_site.mainapp.google_service import Google
from base_site.mainapp.models import Category
from base_site.mainapp.models import FamilyMember
from base_site.mainapp.models import FullCommand
from base_site.mainapp.models import R... | [
"logging.basicConfig",
"pytz.timezone",
"base_site.mainapp.models.FamilyMember.objects.filter",
"dateutil.relativedelta.relativedelta",
"base_site.mainapp.google_service.Google",
"datetime.datetime.strptime",
"logging.warning",
"datetime.datetime.now",
"base_site.mainapp.models.TypeEntry.objects.fil... | [((450, 488), 'logging.basicConfig', 'logging.basicConfig', ([], {'stream': 'sys.stdout'}), '(stream=sys.stdout)\n', (469, 488), False, 'import logging\n'), ((3930, 3983), 'logging.warning', 'logging.warning', (['f"""Valores para a planilha: {values}"""'], {}), "(f'Valores para a planilha: {values}')\n", (3945, 3983), ... |
import json
from rest_framework.renderers import JSONRenderer
class NotificationJSONRenderer(JSONRenderer):
charset = 'utf-8'
def render(self, data, media_type=None, renderer_context=None):
"""
Check for errors key in data
"""
return json.dumps({
'notifications':... | [
"json.dumps"
] | [((279, 314), 'json.dumps', 'json.dumps', (["{'notifications': data}"], {}), "({'notifications': data})\n", (289, 314), False, 'import json\n')] |
#!/usr/bin/env python
"""
* *******************************************************
* Copyright (c) VMware, Inc. 2016. All Rights Reserved.
* SPDX-License-Identifier: MIT
* *******************************************************
*
* DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT
* WARRANTIES OR CONDITIONS... | [
"samples.vsphere.common.ssl_helper.get_unverified_session",
"tabulate.tabulate",
"vmware.vapi.vsphere.client.create_vsphere_client",
"samples.vsphere.common.sample_cli.build_arg_parser"
] | [((1315, 1344), 'samples.vsphere.common.sample_cli.build_arg_parser', 'sample_cli.build_arg_parser', ([], {}), '()\n', (1342, 1344), False, 'from samples.vsphere.common import sample_cli\n'), ((1653, 1764), 'vmware.vapi.vsphere.client.create_vsphere_client', 'create_vsphere_client', ([], {'server': 'args.server', 'user... |
import newsltd_etl
from birgitta.schema.fixtures import json as fx_json
fx_json.make(newsltd_etl)
| [
"birgitta.schema.fixtures.json.make"
] | [((74, 99), 'birgitta.schema.fixtures.json.make', 'fx_json.make', (['newsltd_etl'], {}), '(newsltd_etl)\n', (86, 99), True, 'from birgitta.schema.fixtures import json as fx_json\n')] |
from django.test import TestCase
from django_hats.bootstrap import Bootstrapper
class RolesTestCase(TestCase):
def setUp(self, *args, **kwargs):
'''Clears `Roles` cache for testing.
'''
for role in Bootstrapper.get_roles():
setattr(role, 'group', None)
return super(Rol... | [
"django_hats.bootstrap.Bootstrapper.get_roles"
] | [((229, 253), 'django_hats.bootstrap.Bootstrapper.get_roles', 'Bootstrapper.get_roles', ([], {}), '()\n', (251, 253), False, 'from django_hats.bootstrap import Bootstrapper\n')] |
'''
Copyright 2017, Fujitsu Network Communications, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in w... | [
"re.split",
"re.escape",
"xml.etree.ElementTree.parse",
"decimal.Decimal",
"warrior.Framework.Utils.data_Utils.sub_from_data_repo",
"warrior.Framework.Utils.data_Utils.sub_from_env_var",
"warrior.Framework.Utils.print_Utils.print_error"
] | [((3682, 3759), 'warrior.Framework.Utils.data_Utils.sub_from_env_var', 'Utils.data_Utils.sub_from_env_var', (['return_value', 'self.start_pat', 'self.end_pat'], {}), '(return_value, self.start_pat, self.end_pat)\n', (3715, 3759), False, 'from warrior.Framework import Utils\n'), ((3804, 3883), 'warrior.Framework.Utils.d... |
import os
import re
import cgi
import time
import asyncio
import sqlite3
import logging
from asyncio import Queue
from datetime import datetime
from urllib.parse import urlparse, parse_qsl, urlunparse, urlencode
import aiohttp
from elasticsearch_dsl import Q
from elasticsearch_dsl.connections import connections
from e... | [
"re.compile",
"config.ZHUANLAN_URL.format",
"elasticsearch_dsl.Q",
"urllib.parse.urlencode",
"models.Live.search",
"os.path.exists",
"models.Live.add",
"asyncio.Queue",
"os.mkdir",
"asyncio.sleep",
"asyncio.get_event_loop",
"models.live.init",
"elasticsearch_dsl.connections.connections.get_c... | [((943, 1009), 're.compile', 're.compile', (['"""<a href="https://(www.)?zhihu.com/lives/(\\\\d+)(.*)?\\""""'], {}), '(\'<a href="https://(www.)?zhihu.com/lives/(\\\\d+)(.*)?"\')\n', (953, 1009), False, 'import re\n'), ((1023, 1071), 'elasticsearch_dsl.connections.connections.get_connection', 'connections.get_connectio... |
from fastapi import FastAPI
from models import User, db
app = FastAPI()
db.init_app(app)
@app.get("/")
async def root():
# count number of users in DB
return {"hello": "Hello!"}
@app.get("/users")
async def users():
# count number of users in DB
return {"count_users": await db.func.count(User.id).... | [
"fastapi.FastAPI",
"models.db.func.count",
"models.db.init_app"
] | [((63, 72), 'fastapi.FastAPI', 'FastAPI', ([], {}), '()\n', (70, 72), False, 'from fastapi import FastAPI\n'), ((74, 90), 'models.db.init_app', 'db.init_app', (['app'], {}), '(app)\n', (85, 90), False, 'from models import User, db\n'), ((297, 319), 'models.db.func.count', 'db.func.count', (['User.id'], {}), '(User.id)\... |
"""
============================================================================
Comparing anomaly detection algorithms for outlier detection on toy datasets
============================================================================
This example shows characteristics of different anomaly detection algorithms
on 2D d... | [
"numpy.array",
"numpy.random.RandomState",
"sklearn.datasets.make_blobs",
"matplotlib.pyplot.contour",
"numpy.linspace",
"matplotlib.pyplot.yticks",
"sklearn.neighbors.LocalOutlierFactor",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.ylim",
"sklearn.svm.OneClassSVM",
"sklearn.covariance.Ellip... | [((4773, 4870), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'left': '(0.02)', 'right': '(0.98)', 'bottom': '(0.001)', 'top': '(0.96)', 'wspace': '(0.05)', 'hspace': '(0.01)'}), '(left=0.02, right=0.98, bottom=0.001, top=0.96, wspace=\n 0.05, hspace=0.01)\n', (4792, 4870), True, 'import matplotl... |
import os
import mistune
from datetime import datetime
from io import BytesIO
from zipfile import ZipFile
from django import http
from django.contrib import messages
from django.views import generic
from django.urls import reverse
from django.utils.timezone import make_aware
from django.shortcuts import redirect
from... | [
"editor.views.generic.forbidden_response",
"os.path.exists",
"datetime.datetime.fromtimestamp",
"editor.models.Extension.objects.get",
"zipfile.ZipFile",
"django.urls.reverse",
"django.http.HttpResponse",
"os.path.splitext",
"os.path.join",
"django.shortcuts.redirect",
"editor.forms.AddExtension... | [((881, 937), 'django.urls.reverse', 'reverse', (['"""extension_edit_source"""'], {'args': '(self.object.pk,)'}), "('extension_edit_source', args=(self.object.pk,))\n", (888, 937), False, 'from django.urls import reverse\n'), ((1324, 1383), 'django.urls.reverse', 'reverse', (['"""profile_extensions"""'], {'args': '(sel... |
from copy import deepcopy
xlim, ylim = 3, 2 # board dimensions
# The eight movement directions possible for a chess queen
RAYS = [(1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1), (0, 1), (1, 1)]
class GameState:
"""
Attributes
----------
_board: list(list)
Represent the board with a 2d... | [
"copy.deepcopy"
] | [((2097, 2111), 'copy.deepcopy', 'deepcopy', (['self'], {}), '(self)\n', (2105, 2111), False, 'from copy import deepcopy\n')] |
# Copyright (c) 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import contextlib
import logging
import threading
from infra.services.service_manager import service
from infra_libs import ts_mon
LOGGER = logging.get... | [
"logging.getLogger",
"logging.exception",
"infra_libs.ts_mon.StringField",
"threading.Condition",
"infra.services.service_manager.service.Service"
] | [((309, 336), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (326, 336), False, 'import logging\n'), ((2453, 2524), 'infra.services.service_manager.service.Service', 'service.Service', (['self._state_directory', 'service_config', 'self._cloudtail'], {}), '(self._state_directory, service_c... |
from flask import Blueprint, render_template, current_app, make_response
from webargs import fields, flaskparser
from ._utils import route
REFRESH_SECONDS = 60
blueprint = Blueprint('latest-page', __name__)
@blueprint.route("/latest")
@flaskparser.use_kwargs({'nsfw': fields.Bool(missing=False)})
def get(nsfw):
... | [
"flask.make_response",
"flask.Blueprint",
"webargs.fields.Bool"
] | [((175, 209), 'flask.Blueprint', 'Blueprint', (['"""latest-page"""', '__name__'], {}), "('latest-page', __name__)\n", (184, 209), False, 'from flask import Blueprint, render_template, current_app, make_response\n'), ((603, 622), 'flask.make_response', 'make_response', (['html'], {}), '(html)\n', (616, 622), False, 'fro... |
from numbers import Number
from typing import List
from typing import Union
import numpy as np
from error_propagation.core import Complex
def npv(
cash: Union[List[Number], List[Complex]],
discount_rate: Union[Number, Complex], # noqa
) -> Complex:
"""NPV accounts for the time value of money and can be... | [
"error_propagation.core.Complex",
"numpy.array"
] | [((1090, 1103), 'error_propagation.core.Complex', 'Complex', (['(1)', '(0)'], {}), '(1, 0)\n', (1097, 1103), False, 'from error_propagation.core import Complex\n'), ((1255, 1269), 'numpy.array', 'np.array', (['cash'], {}), '(cash)\n', (1263, 1269), True, 'import numpy as np\n'), ((1215, 1228), 'error_propagation.core.C... |
import numpy as np
import cPickle
import os
import pdb
import cv2
def unpickle(file):
fo = open(file, 'rb')
dict = cPickle.load(fo)
fo.close()
return dict
def load_data(train_path,order,nb_groups, nb_cl, nb_val,SubMean = False):
xs = []
ys = []
for j in range(1):
d = unpickle(train_p... | [
"numpy.mean",
"numpy.unique",
"numpy.random.random_integers",
"numpy.where",
"numpy.zeros",
"numpy.empty",
"numpy.concatenate",
"numpy.pad",
"cPickle.load",
"numpy.float32",
"numpy.random.shuffle"
] | [((124, 140), 'cPickle.load', 'cPickle.load', (['fo'], {}), '(fo)\n', (136, 140), False, 'import cPickle\n'), ((608, 626), 'numpy.concatenate', 'np.concatenate', (['ys'], {}), '(ys)\n', (622, 626), True, 'import numpy as np\n'), ((954, 981), 'numpy.mean', 'np.mean', (['x[0:50000]'], {'axis': '(0)'}), '(x[0:50000], axis... |
#!/usr/bin/env python
'''
1. tab file
2. header (y/n)
'''
from sys import argv, exit
from tabulate import tabulate
from os import system
from fpdf import FPDF
#print(tabulate([['Alice', 24], ['Bob', 19]], headers=['Name', 'Age']))
try:
fname = argv[1]
header = argv[2]
except:
exit(__doc__)
f = open(f... | [
"tabulate.tabulate",
"fpdf.FPDF",
"sys.exit"
] | [((524, 530), 'fpdf.FPDF', 'FPDF', ([], {}), '()\n', (528, 530), False, 'from fpdf import FPDF\n'), ((294, 307), 'sys.exit', 'exit', (['__doc__'], {}), '(__doc__)\n', (298, 307), False, 'from sys import argv, exit\n'), ((617, 648), 'tabulate.tabulate', 'tabulate', (['tabs'], {'headers': 'headers'}), '(tabs, headers=hea... |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import multiprocessing
from multiprocessing.pool import ThreadPool
from tqdm import tqdm
from drqa import retriever
impo... | [
"kilt.kilt_utils.chunk_it",
"tqdm.tqdm",
"multiprocessing.cpu_count",
"multiprocessing.pool.ThreadPool",
"drqa.retriever.get_class"
] | [((703, 721), 'tqdm.tqdm', 'tqdm', (['queries_data'], {}), '(queries_data)\n', (707, 721), False, 'from tqdm import tqdm\n'), ((2084, 2130), 'kilt.kilt_utils.chunk_it', 'utils.chunk_it', (['queries_data', 'self.num_threads'], {}), '(queries_data, self.num_threads)\n', (2098, 2130), True, 'import kilt.kilt_utils as util... |
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Name: to_echse
# Purpose:
#
# Authors: <NAME>
#
# Created: 2015-11-6
# Copyright: (c) <NAME>
# Licence: The MIT License
#------------------------------------------------------------------... | [
"wradlib.georef.get_default_projection",
"datetime.timedelta",
"wradlib.georef.epsg_to_osr",
"trmmlib.wflows.xds_to_echse2"
] | [((8909, 8942), 'trmmlib.wflows.xds_to_echse2', 'tl.wflows.xds_to_echse2', (['conf_xds'], {}), '(conf_xds)\n', (8932, 8942), True, 'import trmmlib as tl\n'), ((1719, 1752), 'wradlib.georef.epsg_to_osr', 'wradlib.georef.epsg_to_osr', (['(32645)'], {}), '(32645)\n', (1745, 1752), False, 'import wradlib\n'), ((1773, 1812)... |
from wayback_machine_archiver.archiver import format_archive_url
def test_archive_org():
BASE = "https://web.archive.org/save/"
URLS = (
"https://alexgude.com",
"http://charles.uno",
)
for url in URLS:
assert BASE + url == format_archive_url(url)
| [
"wayback_machine_archiver.archiver.format_archive_url"
] | [((266, 289), 'wayback_machine_archiver.archiver.format_archive_url', 'format_archive_url', (['url'], {}), '(url)\n', (284, 289), False, 'from wayback_machine_archiver.archiver import format_archive_url\n')] |
# bot.py
# A custom Twitch bot for Hex + MtG card searches
# Based on tutorial here: http://www.instructables.com/id/Twitchtv-Moderator-Bot/
# (The tutorial has several non-functioning bits)
# Uses regex expressions to parse twitch messages and to match card names
# You will need an OAUTH token through Twitch
... | [
"socket.socket",
"re.compile",
"re.match",
"time.sleep",
"sys.exit",
"csv.reader",
"re.search"
] | [((6414, 6429), 'socket.socket', 'socket.socket', ([], {}), '()\n', (6427, 6429), False, 'import socket\n'), ((6779, 6879), 're.compile', 're.compile', (['"""(^:(\\\\w+)!\\\\w+@\\\\w+\\\\.tmi\\\\.twitch\\\\.tv PRIVMSG #\\\\w+ :)(.+)\\\\r\\\\n"""', 're.IGNORECASE'], {}), "('(^:(\\\\w+)!\\\\w+@\\\\w+\\\\.tmi\\\\.twitch\\... |
from kiwoom import config
from kiwoom.config import valid_event
from functools import wraps
from textwrap import dedent
from types import LambdaType
from inspect import (
getattr_static,
ismethod,
isfunction,
isclass,
ismodule
)
class Connector:
"""
Decorator class for mapping empty event... | [
"textwrap.dedent",
"inspect.getattr_static",
"kiwoom.config.valid_event",
"inspect.ismethod",
"inspect.ismodule",
"functools.wraps",
"inspect.isclass",
"inspect.isfunction",
"kiwoom.core.kiwoom.Kiwoom.api_arg_spec"
] | [((11137, 11163), 'kiwoom.core.kiwoom.Kiwoom.api_arg_spec', 'Kiwoom.api_arg_spec', (['event'], {}), '(event)\n', (11156, 11163), False, 'from kiwoom.core.kiwoom import Kiwoom\n'), ((14225, 14240), 'functools.wraps', 'wraps', (['ehandler'], {}), '(ehandler)\n', (14230, 14240), False, 'from functools import wraps\n'), ((... |
#with pytest
import sys
import pytest
import json
sys.path.append('../app/api')
from Question import Question
import flask_restful
from io import BytesIO
class TestQuestionRequest:
def simple_question(self):
return {
'status':'200',
"question":"Who is the presidents of USA ?",
... | [
"Question.Question",
"sys.path.append"
] | [((51, 80), 'sys.path.append', 'sys.path.append', (['"""../app/api"""'], {}), "('../app/api')\n", (66, 80), False, 'import sys\n'), ((1088, 1098), 'Question.Question', 'Question', ([], {}), '()\n', (1096, 1098), False, 'from Question import Question\n'), ((1337, 1347), 'Question.Question', 'Question', ([], {}), '()\n',... |
# -*- coding: utf-8; -*-
#
# @file base.py
# @brief Django base settings for coll-gate messenger project.
# @author <NAME> (INRA UMR1095)
# @date 2017-10-06
# @copyright Copyright (c) 2017 INRA/CIRAD
# @license MIT (see LICENSE file)
# @details
"""
For more information on this file, see
https://docs.djangoproject.com... | [
"os.path.dirname",
"os.path.join"
] | [((1804, 1827), 'os.path.join', 'join', (['BASE_DIR', '"""media"""'], {}), "(BASE_DIR, 'media')\n", (1808, 1827), False, 'from os.path import dirname, join, realpath\n'), ((1772, 1789), 'os.path.dirname', 'dirname', (['__file__'], {}), '(__file__)\n', (1779, 1789), False, 'from os.path import dirname, join, realpath\n'... |
# Functions to run a single trial and write to a file their choices polling every 1/10th of a second
from __future__ import division
import sys,os,random
import pygame as pg
from pygame.locals import *
sharepath = os.path.join(os.path.dirname(__file__),'..','SharedCode')
trpath = os.path.join(os.path.dirname(__... | [
"sys.path.insert",
"os.tmpfile",
"pygame.init",
"sys.exit",
"pygame.Surface",
"pygame.event.get",
"pygame.display.set_mode",
"pygame.display.flip",
"os.path.join",
"pygame.Rect",
"os.path.dirname",
"pygame.key.get_pressed",
"pygame.font.init",
"pygame.time.Clock",
"random.random",
"pyg... | [((344, 373), 'sys.path.insert', 'sys.path.insert', (['(1)', 'sharepath'], {}), '(1, sharepath)\n', (359, 373), False, 'import sys, os, random\n'), ((374, 400), 'sys.path.insert', 'sys.path.insert', (['(1)', 'trpath'], {}), '(1, trpath)\n', (389, 400), False, 'import sys, os, random\n'), ((403, 417), 'pygame.font.init'... |
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, BigInteger, String
import config
Base = declarative_base()
formFields = config.form_fields
class Register(Base):
__tablename__ = config.table_name
col1 = Column(formFields[0]['fname'], formFields[0]['ftype'], primary_key=T... | [
"sqlalchemy.Column",
"sqlalchemy.ext.declarative.declarative_base"
] | [((128, 146), 'sqlalchemy.ext.declarative.declarative_base', 'declarative_base', ([], {}), '()\n', (144, 146), False, 'from sqlalchemy.ext.declarative import declarative_base\n'), ((252, 324), 'sqlalchemy.Column', 'Column', (["formFields[0]['fname']", "formFields[0]['ftype']"], {'primary_key': '(True)'}), "(formFields[... |
from socket import socket, AF_INET, SOCK_DGRAM
SERVER_PORT = 12346
SERVER_BUF_SIZE = 2048
s = socket(family=AF_INET, type=SOCK_DGRAM)
s.bind(('localhost', SERVER_PORT))
while True:
print('Server waiting for new requests...')
data = b''
addr = ('', -1)
try:
data, addr = s.recvfrom(SERVER_BUF_... | [
"socket.socket"
] | [((96, 135), 'socket.socket', 'socket', ([], {'family': 'AF_INET', 'type': 'SOCK_DGRAM'}), '(family=AF_INET, type=SOCK_DGRAM)\n', (102, 135), False, 'from socket import socket, AF_INET, SOCK_DGRAM\n')] |
'''
实验名称:摄像头模块
版本:v1.0
日期:2020.3
作者:01Studio
说明:使用摄像头模块拍照并保存
社区:www.01studio.org
'''
#导入相关库
from picamera import PiCamera
from time import sleep
#构建摄像头
camera = PiCamera()
#打开摄像头
camera.start_preview()
sleep(3) #等待摄像头稳定
#拍摄照片5张并保存到桌面
for i in range(5):
camera.capture('/home/pi/Desktop/'+str(i)+'.jpg')
#关闭摄像头
... | [
"picamera.PiCamera",
"time.sleep"
] | [((163, 173), 'picamera.PiCamera', 'PiCamera', ([], {}), '()\n', (171, 173), False, 'from picamera import PiCamera\n'), ((206, 214), 'time.sleep', 'sleep', (['(3)'], {}), '(3)\n', (211, 214), False, 'from time import sleep\n')] |
# Generated by Django 3.0.4 on 2020-05-31 10:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('customer', '0008_auto_20200531_1002'),
]
operations = [
migrations.AddField(
model_name='customer',
name='email',
... | [
"django.db.models.CharField"
] | [((336, 403), 'django.db.models.CharField', 'models.CharField', ([], {'default': 'None', 'max_length': '(50)', 'verbose_name': '"""Email"""'}), "(default=None, max_length=50, verbose_name='Email')\n", (352, 403), False, 'from django.db import migrations, models\n')] |
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
#!/usr/bin/env python
#
#The MIT CorrelX Correlator
#
#https://github.com/MITHaystack/CorrelX
#Contact: <EMAIL>
#Project leads: <NAME>, <NAME> Project developer: <NAME>
#
#Copyright 2017 MIT Haystack Observatory
#
#Permission is hereby granted, free of c... | [
"os.environ.get",
"ConfigParser.ConfigParser",
"os.path.isdir",
"os.path.abspath",
"os.system"
] | [((1643, 1670), 'os.environ.get', 'os.environ.get', (['"""is_legacy"""'], {}), "('is_legacy')\n", (1657, 1670), False, 'import os\n'), ((2502, 2529), 'ConfigParser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (2527, 2529), True, 'import ConfigParser as configparser\n'), ((3324, 3351), 'ConfigParser.Con... |
import logging
import sys
def get_logger(filename,
logger_name='centroFlye',
level=logging.INFO,
filemode='a',
stdout=True):
logger = logging.getLogger(logger_name)
logger.setLevel(level)
# create the logging file handler
fh = logging.FileHa... | [
"logging.getLogger",
"logging.Formatter",
"logging.StreamHandler",
"logging.FileHandler"
] | [((200, 230), 'logging.getLogger', 'logging.getLogger', (['logger_name'], {}), '(logger_name)\n', (217, 230), False, 'import logging\n'), ((306, 350), 'logging.FileHandler', 'logging.FileHandler', (['filename'], {'mode': 'filemode'}), '(filename, mode=filemode)\n', (325, 350), False, 'import logging\n'), ((368, 441), '... |
import os
import pathlib
import pytest
from eva import eva_base
from unittest.mock import patch
# local imports
from eva.utilities.logger import Logger
from eva.tests import helpers
EVA_TESTS_DIR = pathlib.Path(__file__).parent.resolve()
PYTEST_ENVVARS = {
'EVA_TESTS_DIR': str(EVA_TESTS_DIR)
}
OBS_CORRELATION_S... | [
"unittest.mock.patch.dict",
"pathlib.Path",
"os.path.join",
"eva.utilities.logger.Logger",
"pytest.raises",
"eva.eva_base.eva"
] | [((334, 404), 'os.path.join', 'os.path.join', (['EVA_TESTS_DIR', '"""config/ObsCorrelationScatterDriver.yaml"""'], {}), "(EVA_TESTS_DIR, 'config/ObsCorrelationScatterDriver.yaml')\n", (346, 404), False, 'import os\n'), ((521, 540), 'eva.utilities.logger.Logger', 'Logger', (['"""UnitTests"""'], {}), "('UnitTests')\n", (... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 16 11:35:10 2018
@author: anonymous
"""
import matplotlib.pyplot as plt
import numpy as np
import shutil
import random
import numpy as np
import matplotlib.pyplot as plt
from scipy.misc import imsave
from .maze_generation2 import gen_maze
from omg ... | [
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.close",
"omg.WAD",
"matplotlib.pyplot.scatter",
"shutil.copy",
"random.randint",
"json.dump"
] | [((786, 824), 'omg.WAD', 'WAD', (["('scenarios/basefiles/' + BASE_WAD)"], {}), "('scenarios/basefiles/' + BASE_WAD)\n", (789, 824), False, 'from omg import WAD\n'), ((895, 955), 'shutil.copy', 'shutil.copy', (["('scenarios/basefiles/' + BASE_CFG)", 'cfg_filename'], {}), "('scenarios/basefiles/' + BASE_CFG, cfg_filename... |
import gym
import numpy as np
import pytest
from gym.spaces.discrete import Discrete
from gym.utils import seeding
from tianshou.data import Batch, Collector, ReplayBuffer
from tianshou.env import DummyVectorEnv, SubprocVectorEnv
from tianshou.policy import BasePolicy
class SimpleEnv(gym.Env):
"""A simplest exam... | [
"numpy.ones",
"tianshou.data.ReplayBuffer",
"tianshou.data.Collector",
"gym.spaces.discrete.Discrete",
"pytest.main",
"numpy.random.randint",
"numpy.zeros",
"numpy.random.seed",
"pytest.fixture",
"gym.utils.seeding.np_random"
] | [((1526, 1556), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (1540, 1556), False, 'import pytest\n'), ((1573, 1590), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (1587, 1590), True, 'import numpy as np\n'), ((2076, 2095), 'tianshou.data.ReplayBuffer', 'Rep... |
from zope.component.factory import Factory
from zope import interface
from . import IPath
@interface.implementer(IPath)
class FilesystemPath(str):
pass
filesystemPathFactory = Factory(FilesystemPath) | [
"zope.component.factory.Factory",
"zope.interface.implementer"
] | [((92, 120), 'zope.interface.implementer', 'interface.implementer', (['IPath'], {}), '(IPath)\n', (113, 120), False, 'from zope import interface\n'), ((181, 204), 'zope.component.factory.Factory', 'Factory', (['FilesystemPath'], {}), '(FilesystemPath)\n', (188, 204), False, 'from zope.component.factory import Factory\n... |
from pathlib import Path
import pandas as pd
from colorama import Fore, Style
import traceback
from os import linesep
from typing import IO, Optional, Any, Tuple, Union, List, cast
import sys
from ..exceptions import DataCheckException
from ..result import DataCheckResult, ResultType
from ..io import rel_path
from .ha... | [
"typing.cast",
"pandas.option_context",
"traceback.format_exception"
] | [((1258, 1289), 'traceback.format_exception', 'traceback.format_exception', (['exc'], {}), '(exc)\n', (1284, 1289), False, 'import traceback\n'), ((1323, 1399), 'traceback.format_exception', 'traceback.format_exception', ([], {'value': 'exc', 'tb': 'exc.__traceback__', 'etype': 'Exception'}), '(value=exc, tb=exc.__trac... |
import os, sys
sys.path.insert(0, os.path.join(os.pardir, 'src'))
def sympy_solution():
from sympy import symbols, Rational, solve
C1, C3, C4 = symbols('C1 C3 C4')
s = solve([C1 - 1 - C3,
C1 - Rational(1,2) - C3 - C4,
2 + 2*C3 + C4], [C1,C3,C4])
return s
import numpy as np
import matplo... | [
"matplotlib.pyplot.ylabel",
"numpy.array",
"numpy.sin",
"numpy.where",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.linspace",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.gca",
"sympy.symbols",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show",
"numpy.linalg.solve",
... | [((34, 64), 'os.path.join', 'os.path.join', (['os.pardir', '"""src"""'], {}), "(os.pardir, 'src')\n", (46, 64), False, 'import os, sys\n'), ((153, 172), 'sympy.symbols', 'symbols', (['"""C1 C3 C4"""'], {}), "('C1 C3 C4')\n", (160, 172), False, 'from sympy import symbols, Rational, solve\n'), ((375, 397), 'numpy.linspac... |
from pathlib import Path
from argparse import ArgumentParser
from AutoEncoder import MobileNetV2_UNet
import pandas as pd
import json
from os import makedirs
from sklearn.model_selection import train_test_split
BATCH_SIZE = 64
INPUT_SHAPE = (320,320,3)
LATENT_SPACE_SIZE = 64
def load_paths(csv_path):
x_paths = [... | [
"os.makedirs",
"argparse.ArgumentParser",
"pandas.read_csv",
"pathlib.Path",
"AutoEncoder.MobileNetV2_UNet"
] | [((336, 357), 'pandas.read_csv', 'pd.read_csv', (['csv_path'], {}), '(csv_path)\n', (347, 357), True, 'import pandas as pd\n'), ((462, 478), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (476, 478), False, 'from argparse import ArgumentParser\n'), ((620, 705), 'AutoEncoder.MobileNetV2_UNet', 'MobileNet... |
# -*- coding: utf-8 -*-
import pytest
from autojsdoc.parser import jsdoc
from support import params, parse
def test_classvar():
[mod] = parse("""
odoo.define('a.A', function(require) {
var Class = require('Class');
/**
* This is my class-kai
*/
var A = Class.extend({}... | [
"pytest.mark.skip",
"support.params",
"support.parse"
] | [((5345, 5409), 'pytest.mark.skip', 'pytest.mark.skip', ([], {'reason': '"""Need to implement member/var-parsing?"""'}), "(reason='Need to implement member/var-parsing?')\n", (5361, 5409), False, 'import pytest\n'), ((142, 367), 'support.parse', 'parse', (['"""\n odoo.define(\'a.A\', function(require) {\n var... |
"""A script testing the extraction pipeline of RHEA
Steps
1) Initialise Format, Extractor and RadialVelocity
2) Define file paths for science, flat and dark frames
3) Extract/import spectra
4) Create/import reference spectra
5) Calculate radial velocities
6) Plot radial velocities
"""
import numpy as np
try... | [
"astropy.io.fits.getheader",
"numpy.where",
"pymfe.rhea.Format",
"pymfe.Extractor",
"astropy.io.fits.getdata",
"numpy.concatenate",
"astropy.io.fits.open",
"pymfe.rv.RadialVelocity",
"glob.glob"
] | [((850, 910), 'astropy.io.fits.getdata', 'pyfits.getdata', (['"""/priv/mulga1/jbento/rhea2_data/badpix.fits"""'], {}), "('/priv/mulga1/jbento/rhea2_data/badpix.fits')\n", (864, 910), True, 'import astropy.io.fits as pyfits\n'), ((919, 947), 'numpy.where', 'np.where', (['(badpixel_mask == 1)'], {}), '(badpixel_mask == 1... |
import datetime
import random
import string
import bcrypt
from bson import ObjectId
from mongoengine import QuerySet
def generate_random_str(
length: int,
is_digit: bool = True,
):
if is_digit:
all_char = string.digits
else:
all_char = string.ascii_letters + string.digits
... | [
"bcrypt.gensalt",
"random.sample"
] | [((335, 366), 'random.sample', 'random.sample', (['all_char', 'length'], {}), '(all_char, length)\n', (348, 366), False, 'import random\n'), ((574, 590), 'bcrypt.gensalt', 'bcrypt.gensalt', ([], {}), '()\n', (588, 590), False, 'import bcrypt\n')] |
# Generated by Django 3.1.2 on 2020-10-30 10:30
from django.db import migrations, models
import django.db.models.deletion
import modelcluster.fields
class Migration(migrations.Migration):
dependencies = [
('categories', '0007_auto_20201028_1347'),
('blogs', '0002_blog_source'),
]
operat... | [
"django.db.migrations.RemoveField",
"django.db.models.AutoField",
"django.db.models.ForeignKey"
] | [((337, 397), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""blog"""', 'name': '"""categories"""'}), "(model_name='blog', name='categories')\n", (359, 397), False, 'from django.db import migrations, models\n'), ((555, 648), 'django.db.models.AutoField', 'models.AutoField', ([], {'... |
#!/usr/bin/env python3
import json
# Just FYI!
# b (banned) = [sml] (standard, modern, legacy)
# c (color) = White = A, Blue = B, Black = C, Red = D, Green = E, Gold = F, Artifact = G , Split = S, Unknown = X, Land = Z
# m (CMC) = N (Split = 98, Land = 99)
# n (actual name) = 'true name nemesis' to 'True Name Nemesi... | [
"json.load",
"json.dump"
] | [((863, 880), 'json.load', 'json.load', (['jsonfh'], {}), '(jsonfh)\n', (872, 880), False, 'import json\n'), ((3399, 3425), 'json.dump', 'json.dump', (['ocards', 'ojsonfh'], {}), '(ocards, ojsonfh)\n', (3408, 3425), False, 'import json\n')] |
# coding: utf-8
from mock import Mock
import requests
from boxsdk.network.default_network import DefaultNetworkResponse
from boxsdk.network.network_interface import Network
class MockNetwork(Network):
"""Mock implementation of the network interface for testing purposes."""
def __init__(self):
super(... | [
"mock.Mock"
] | [((357, 379), 'mock.Mock', 'Mock', (['requests.Session'], {}), '(requests.Session)\n', (361, 379), False, 'from mock import Mock\n')] |
"""
utils.py
Utility functions for titanic data analysis
"""
import pandas as pd
import fuckit
from sklearn.svm import SVR, SVC
EVALUATION_FOLD_RANGE = {
0: (0, 89),
1: (90, 179),
2: (180, 269),
3: (270, 359),
4: (360, 449),
5: (450, 539),
6: (540, 629),
7: (630, 719),
8: (720... | [
"sklearn.svm.SVR",
"pandas.read_csv",
"sklearn.svm.SVC"
] | [((1258, 1300), 'pandas.read_csv', 'pd.read_csv', (['"""../data/train.csv"""'], {'header': '(0)'}), "('../data/train.csv', header=0)\n", (1269, 1300), True, 'import pandas as pd\n'), ((1402, 1443), 'pandas.read_csv', 'pd.read_csv', (['"""../data/test.csv"""'], {'header': '(0)'}), "('../data/test.csv', header=0)\n", (14... |
import streamlit as st
from models.utils import model_imports, model_infos, model_urls
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import numpy as np
import time
from models.paramselector import (
lr_params, dt_params,
rf_params, gb... | [
"models.paramselector.nn_params",
"models.paramselector.dt_params",
"pandas.read_csv",
"models.paramselector.lr_params",
"sklearn.model_selection.train_test_split",
"streamlit.expander",
"models.paramselector.rf_params",
"sklearn.preprocessing.StandardScaler",
"streamlit.selectbox",
"time.time",
... | [((410, 444), 'streamlit.expander', 'st.expander', (['"""Train a model"""', '(True)'], {}), "('Train a model', True)\n", (421, 444), True, 'import streamlit as st\n'), ((2532, 2557), 'pandas.read_csv', 'pd.read_csv', (['"""./data.csv"""'], {}), "('./data.csv')\n", (2543, 2557), True, 'import pandas as pd\n'), ((2729, 2... |
import logging
logging_format = ' %(name)s :: %(levelname)-8s :: %(message)s'
logging.basicConfig(level=logging.WARNING, format=logging_format)
logging.getLogger().setLevel(logging.WARNING)
logger = logging.getLogger() | [
"logging.basicConfig",
"logging.getLogger"
] | [((79, 144), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.WARNING', 'format': 'logging_format'}), '(level=logging.WARNING, format=logging_format)\n', (98, 144), False, 'import logging\n'), ((202, 221), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (219, 221), False, 'import loggin... |
# %%
import numpy as np
import pathlib as pth
import matplotlib.pyplot as plt
import re
try:
from pileupplots_utils import *
except:
from .pileupplots_utils import *
# %%
if __name__ == "__main__":
parser = argparser()
args = parser.parse_args()
data_path = pth.Path(args.vial_fld)
fig_path... | [
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.subplot_mosaic",
"numpy.arange",
"pathlib.Path"
] | [((284, 307), 'pathlib.Path', 'pth.Path', (['args.vial_fld'], {}), '(args.vial_fld)\n', (292, 307), True, 'import pathlib as pth\n'), ((323, 345), 'pathlib.Path', 'pth.Path', (['args.fig_fld'], {}), '(args.fig_fld)\n', (331, 345), True, 'import pathlib as pth\n'), ((1065, 1109), 'matplotlib.pyplot.subplot_mosaic', 'plt... |
from typing import Union
import numpy as np
import talib
from jesse.helpers import get_candle_source
def efi(candles: np.ndarray, period: int = 13, source_type: str = "close", sequential: bool = False) -> Union[
float, np.ndarray]:
"""
EFI - Elders Force Index
:param candles: np.ndarray
:param ... | [
"numpy.full",
"talib.EMA",
"jesse.helpers.get_candle_source"
] | [((571, 622), 'jesse.helpers.get_candle_source', 'get_candle_source', (['candles'], {'source_type': 'source_type'}), '(candles, source_type=source_type)\n', (588, 622), False, 'from jesse.helpers import get_candle_source\n'), ((775, 808), 'talib.EMA', 'talib.EMA', (['dif'], {'timeperiod': 'period'}), '(dif, timeperiod=... |
import pytest
from requests.exceptions import HTTPError
from commercetools.platform import models
def test_channel_get_by_id(old_client):
channel = old_client.channels.create(
models.ChannelDraft(
key="test-channel", roles=[models.ChannelRoleEnum.INVENTORY_SUPPLY]
)
)
assert ... | [
"commercetools.platform.models.ChannelDraft",
"pytest.raises",
"commercetools.platform.models.LocalizedString"
] | [((191, 284), 'commercetools.platform.models.ChannelDraft', 'models.ChannelDraft', ([], {'key': '"""test-channel"""', 'roles': '[models.ChannelRoleEnum.INVENTORY_SUPPLY]'}), "(key='test-channel', roles=[models.ChannelRoleEnum.\n INVENTORY_SUPPLY])\n", (210, 284), False, 'from commercetools.platform import models\n')... |
# Copyright (c) 2008 <NAME>
# Licensed under the terms of the MIT License (see LICENSE.txt)
import re
from django.conf import settings
from django.core import urlresolvers
import localeurl.settings
SUPPORTED_LOCALES = dict(settings.LANGUAGES)
LOCALES_RE = '|'.join(SUPPORTED_LOCALES)
PATH_RE = re.compile(r'^/(?P<local... | [
"re.search",
"django.core.urlresolvers.get_script_prefix",
"re.compile"
] | [((296, 352), 're.compile', 're.compile', (["('^/(?P<locale>%s)(?P<path>.*)$' % LOCALES_RE)"], {}), "('^/(?P<locale>%s)(?P<path>.*)$' % LOCALES_RE)\n", (306, 352), False, 'import re\n'), ((366, 426), 're.compile', 're.compile', (["('^(?P<locale>%s)\\\\.(?P<domain>.*)$' % LOCALES_RE)"], {}), "('^(?P<locale>%s)\\\\.(?P<d... |
###############################################################################
##
## Copyright (c) Crossbar.io Technologies GmbH
##
## 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... | [
"autobahn.twisted.websocket.WebSocketClientFactory.__init__",
"autobahn.twisted.websocket.connectWS",
"autobahn.twisted.websocket.listenWS",
"autobahn.twisted.websocket.WebSocketServerFactory.__init__"
] | [((2055, 2073), 'autobahn.twisted.websocket.connectWS', 'connectWS', (['factory'], {}), '(factory)\n', (2064, 2073), False, 'from autobahn.twisted.websocket import connectWS, listenWS, WebSocketClientFactory, WebSocketClientProtocol, WebSocketServerFactory, WebSocketServerProtocol\n'), ((2349, 2378), 'autobahn.twisted.... |
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | [
"onnxbase.randtool",
"onnxbase.APIOnnx",
"paddle.nn.Conv3D"
] | [((1818, 1844), 'onnxbase.APIOnnx', 'APIOnnx', (['op', '"""Conv3D"""', '[9]'], {}), "(op, 'Conv3D', [9])\n", (1825, 1844), False, 'from onnxbase import APIOnnx\n'), ((2177, 2212), 'onnxbase.APIOnnx', 'APIOnnx', (['op', '"""Conv2D_Dropout"""', '[10]'], {}), "(op, 'Conv2D_Dropout', [10])\n", (2184, 2212), False, 'from on... |
import os
import json
import sys
from pathlib import Path
import jinja2
import string
# Schema: performance_models[data_mode][tps] = [model]
performance_models = {}
def add_performance_model(model):
"""
Adds performance model to the list of performance models.
"""
# process model values
model["av... | [
"json.load",
"jinja2.FileSystemLoader",
"os.listdir",
"jinja2.Environment"
] | [((1904, 1960), 'jinja2.FileSystemLoader', 'jinja2.FileSystemLoader', ([], {'searchpath': '"""e2etest/templates/"""'}), "(searchpath='e2etest/templates/')\n", (1927, 1960), False, 'import jinja2\n'), ((1971, 2005), 'jinja2.Environment', 'Environment', ([], {'loader': 'templateLoader'}), '(loader=templateLoader)\n', (19... |
from numpy import column_stack, savetxt
import os
lf = os.linesep#determing the linefeed for the operating system ('\n' for Linux or '\r\n' for Windows)
def _dump_matrix(f, matrix, fmt='%0.10g', delim='\t'):
savetxt(f, matrix, fmt=fmt, delimiter=delim)
return f
def _dump_vectors(f, vectorlist, fmt='%0.1... | [
"numpy.column_stack",
"numpy.savetxt"
] | [((215, 259), 'numpy.savetxt', 'savetxt', (['f', 'matrix'], {'fmt': 'fmt', 'delimiter': 'delim'}), '(f, matrix, fmt=fmt, delimiter=delim)\n', (222, 259), False, 'from numpy import column_stack, savetxt\n'), ((353, 377), 'numpy.column_stack', 'column_stack', (['vectorlist'], {}), '(vectorlist)\n', (365, 377), False, 'fr... |
# (c) 2019 <NAME>
# This file is part of nuskybgd released under MIT License.
# See LICENSE file for full details.
import os
from . import env
_PASSCHECK = False
_AUX_ENV = 'NUSKYBGD_AUXIL'
_AUX_DIR = ''
_AUX_FILES = [
'be.arf',
'diag.rmf',
'fcxbA.arf',
'fcxbB.arf',
'nomapbgdparams.dat',
'detA... | [
"os.path.exists"
] | [((1632, 1675), 'os.path.exists', 'os.path.exists', (["('%s/%s' % (env._AUX_DIR, _))"], {}), "('%s/%s' % (env._AUX_DIR, _))\n", (1646, 1675), False, 'import os\n')] |
import numpy as np
import torch
from scipy.stats import entropy as sc_entropy
class MultipredictionEntropy:
def __int__(self):
"""
Computes the entropy on multiple predictions of the same batch.
"""
super(MultipredictionEntropy, self).__init__()
def __call__(self, y, device='... | [
"torch.tensor",
"numpy.unique",
"torch.argmax"
] | [((575, 816), 'torch.tensor', 'torch.tensor', (['[[[0.7, 0.3, 0.1], [0.7, 0.3, 0.1], [0.7, 0.3, 0.2]], [[0.4, 0.6, 0.3], [\n 0.4, 0.6, 0.4], [0.6, 0.4, 0.3]], [[0.4, 0.6, 0.2], [0.6, 0.4, 0.8], [\n 0.6, 0.4, 0.7]], [[0.1, 0.9, 0.3], [0.1, 0.9, 0.3], [0.1, 0.9, 0.3]]]'], {}), '([[[0.7, 0.3, 0.1], [0.7, 0.3, 0.1], ... |
import struct
import json
class StreamPushAdapter(object):
"""
This represents the interface that must be implemented by push adapters for
IO modes that want to implement streaming output.
"""
def write(self, buf):
"""
Write a chunk of data to the output stream.
"""
... | [
"struct.unpack"
] | [((2730, 2767), 'struct.unpack', 'struct.unpack', (['""">BxxxL"""', 'self._header'], {}), "('>BxxxL', self._header)\n", (2743, 2767), False, 'import struct\n')] |
# Инициализация (генераторы)
list_temp = [] # пустой список
print(type(list_temp))
list_temp = [1.2, 123, 'Volvo', [1,2,3]]
print(list_temp)
# пройдем по элементам списка (функция el)
for el in list_temp:
print(el, type(el))
# list - строка разбивается на элементы, где каждый элемент представляет собой эл... | [
"functools.reduce"
] | [((2570, 2610), 'functools.reduce', 'reduce', (['(lambda x, y: x + y)', 'integer_list'], {}), '(lambda x, y: x + y, integer_list)\n', (2576, 2610), False, 'from functools import reduce\n'), ((2789, 2829), 'functools.reduce', 'reduce', (['(lambda x, y: x * y)', 'integer_list'], {}), '(lambda x, y: x * y, integer_list)\n... |
import time, math, cmath
import numpy as np
from functools import reduce
from qiskit import *
from qiskit.quantum_info import Statevector
from circuit_builder import CircuitBuilder
from agent import Agent
class QRPS_Agent(Agent):
def __init__(self, backend):
self.backend = backend
self.memory =... | [
"circuit_builder.CircuitBuilder",
"numpy.abs",
"numpy.linalg.eig",
"qiskit.quantum_info.Statevector",
"functools.reduce",
"numpy.delete",
"math.sqrt",
"numpy.sum",
"numpy.array",
"numpy.linalg.eigvals",
"numpy.split",
"numpy.concatenate",
"time.time"
] | [((1171, 1186), 'numpy.sum', 'np.sum', (['weights'], {}), '(weights)\n', (1177, 1186), True, 'import numpy as np\n'), ((1202, 1248), 'numpy.array', 'np.array', (['[(h / sum_weights) for h in weights]'], {}), '([(h / sum_weights) for h in weights])\n', (1210, 1248), True, 'import numpy as np\n'), ((2751, 2768), 'numpy.s... |
"""
Supplies the environment variables necessary to set up Local CFC runtime
"""
import uuid
import sys
class EnvironmentVariables(object):
"""
Use this class to get the environment variables necessary to run the CFC function. It returns the BCE specific
variables (credentials, regions, etc) along with a... | [
"uuid.uuid1"
] | [((5949, 5961), 'uuid.uuid1', 'uuid.uuid1', ([], {}), '()\n', (5959, 5961), False, 'import uuid\n')] |
from django.contrib import admin
# Register your models here.
from training.models import Training
admin.site.register(Training) | [
"django.contrib.admin.site.register"
] | [((101, 130), 'django.contrib.admin.site.register', 'admin.site.register', (['Training'], {}), '(Training)\n', (120, 130), False, 'from django.contrib import admin\n')] |
import logging
import os
import numpy as np
import tensorflow as tf
import sys
def create_log(name):
"""Logging."""
if os.path.exists(name):
os.remove(name)
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
# handler for logger file
handler1 = logging.FileHandler(name)
... | [
"logging.getLogger",
"os.path.exists",
"tensorflow.contrib.learn.python.learn.datasets.mnist.read_data_sets",
"logging.StreamHandler",
"numpy.mean",
"logging.Formatter",
"tensorflow.global_variables_initializer",
"numpy.array",
"logging.FileHandler",
"os.mkdir",
"numpy.expand_dims",
"sys.exit"... | [((129, 149), 'os.path.exists', 'os.path.exists', (['name'], {}), '(name)\n', (143, 149), False, 'import os\n'), ((188, 211), 'logging.getLogger', 'logging.getLogger', (['name'], {}), '(name)\n', (205, 211), False, 'import logging\n'), ((292, 317), 'logging.FileHandler', 'logging.FileHandler', (['name'], {}), '(name)\n... |
# http://pastie.org/pastes/10943132/text
# Copyright (c) 2016 1wd
#
# 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, modi... | [
"random.choice",
"random.randint",
"random.seed"
] | [((19376, 19393), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (19387, 19393), False, 'import random\n'), ((2881, 2907), 'random.randint', 'random.randint', (['(1)', 'self.id'], {}), '(1, self.id)\n', (2895, 2907), False, 'import random\n'), ((2920, 2955), 'random.randint', 'random.randint', (['biased_min'... |
import functools
import json
from pathlib import Path
from typing import Dict, Optional
@functools.lru_cache()
def get_raw_types() -> Dict[str, str]:
path = Path(__file__).parent.joinpath("dread_types.json")
with path.open() as f:
return json.load(f)
@functools.lru_cache()
def all_asset_id_to_name()... | [
"json.load",
"functools.lru_cache",
"pathlib.Path"
] | [((91, 112), 'functools.lru_cache', 'functools.lru_cache', ([], {}), '()\n', (110, 112), False, 'import functools\n'), ((272, 293), 'functools.lru_cache', 'functools.lru_cache', ([], {}), '()\n', (291, 293), False, 'import functools\n'), ((690, 711), 'functools.lru_cache', 'functools.lru_cache', ([], {}), '()\n', (709,... |
'''
Ruby Extension for Python-Markdown
==================================
Converts |kanji<kana> to <ruby><rb>kanji</rb><rp>(</rp><rt>kana</rt><rp>)</rp></ruby>.
License: [BSD](http://www.opensource.org/licenses/bsd-license.php)
'''
from __future__ import unicode_literals
from markdown.extensions import Extension
fr... | [
"markdown.util.etree.SubElement",
"markdown.util.etree.Element"
] | [((790, 811), 'markdown.util.etree.Element', 'etree.Element', (['"""ruby"""'], {}), "('ruby')\n", (803, 811), False, 'from markdown.util import etree\n'), ((824, 852), 'markdown.util.etree.SubElement', 'etree.SubElement', (['ruby', '"""rb"""'], {}), "(ruby, 'rb')\n", (840, 852), False, 'from markdown.util import etree\... |
from PIL import Image
from Chess.chess import letter_to_name, numbers_to_dashes
class ChessBoard:
def __init__(self, fen: str, width: int = 75 * 8):
self.width = self.height = width
self.fen = fen
self.image = Image.open("./board/board.png")
self.draw_fen(fen)
def draw_letter... | [
"Chess.chess.letter_to_name",
"PIL.Image.open",
"Chess.chess.numbers_to_dashes"
] | [((241, 272), 'PIL.Image.open', 'Image.open', (['"""./board/board.png"""'], {}), "('./board/board.png')\n", (251, 272), False, 'from PIL import Image\n'), ((543, 559), 'PIL.Image.open', 'Image.open', (['path'], {}), '(path)\n', (553, 559), False, 'from PIL import Image\n'), ((788, 810), 'Chess.chess.numbers_to_dashes',... |
import unittest
from os.path import join, dirname
from io import BytesIO
from urllib.parse import quote
from falcon_heavy.http.multipart_parser import MultiPartParser, MultiPartParserError
from falcon_heavy.http.exceptions import RequestDataTooBig, TooManyFieldsSent
from falcon_heavy.http.utils import parse_options_he... | [
"os.path.join",
"urllib.parse.quote",
"io.BytesIO",
"os.path.dirname",
"falcon_heavy.http.utils.parse_options_header",
"unittest.main"
] | [((18626, 18641), 'unittest.main', 'unittest.main', ([], {}), '()\n', (18639, 18641), False, 'import unittest\n'), ((3820, 3837), 'os.path.dirname', 'dirname', (['__file__'], {}), '(__file__)\n', (3827, 3837), False, 'from os.path import join, dirname\n'), ((5309, 5330), 'os.path.join', 'join', (['resources', 'name'], ... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# File: svhn-resnet.py
# Author: <NAME> <<EMAIL>>
import argparse
import numpy as np
import os
from tensorpack import *
from tensorpack.tfutils.symbolic_functions import *
from tensorpack.tfutils.summary import *
import tensorflow as tf
"""
ResNet-110 for SVHN Digit Clas... | [
"os.path.dirname",
"argparse.ArgumentParser"
] | [((2396, 2421), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2419, 2421), False, 'import argparse\n'), ((586, 611), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (601, 611), False, 'import os\n')] |
# Matriz em Python
import time
import os
matriz = []
while True:
linha = int(input('Quantas linhas você deseja? '))
coluna = int(input('Quantas colunas você deseja? '))
print('')
for i in range(0, linha):
for j in range(0, coluna):
num = int(input(f'Digite um número na posição [{... | [
"os.system",
"time.sleep"
] | [((859, 874), 'time.sleep', 'time.sleep', (['(1.5)'], {}), '(1.5)\n', (869, 874), False, 'import time\n'), ((883, 901), 'os.system', 'os.system', (['"""clear"""'], {}), "('clear')\n", (892, 901), False, 'import os\n')] |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Test that the fuzzer works the way ClusterFuzz invokes it."""
import glob
import os
import shutil
import sys
import tempfile
import unittest
import setu... | [
"setup.RetrieveResources",
"os.path.join",
"fuzz_main_run.main",
"tempfile.mkdtemp",
"shutil.rmtree",
"unittest.main"
] | [((1232, 1247), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1245, 1247), False, 'import unittest\n'), ((422, 440), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (438, 440), False, 'import tempfile\n'), ((472, 497), 'setup.RetrieveResources', 'setup.RetrieveResources', ([], {}), '()\n', (495, 497), ... |
# Generated by Django 3.2.6 on 2021-08-28 23:28
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('shopping', '0003_alter_produto_promocao'),
]
operations = [
migrations.CreateModel(
name='Image... | [
"django.db.models.ImageField",
"django.db.models.BigAutoField",
"django.db.models.ForeignKey"
] | [((368, 464), 'django.db.models.BigAutoField', 'models.BigAutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (387, 464), False, 'from django.db import migrations, m... |
import os
import random
import time
import torch
import torch.nn.functional as F
import torch.nn as nn
import numpy as np
import scipy.io.wavfile as wavfile
import matplotlib
from mir_eval.separation import bss_eval_sources
from arguments import ArgParser
from dataset import MUSICMixDataset
from models import ModelBu... | [
"numpy.clip",
"dataset.MUSICMixDataset",
"viz.plot_loss_loc_sep_acc_metrics",
"torch.cuda.synchronize",
"models.activate",
"torch.squeeze",
"os.path.exists",
"torch.nn.functional.grid_sample",
"utils.istft_reconstruction",
"models.ModelBuilder",
"numpy.asarray",
"time.perf_counter",
"torch.n... | [((3521, 3535), 'utils.AverageMeter', 'AverageMeter', ([], {}), '()\n', (3533, 3535), False, 'from utils import AverageMeter, recover_rgb, magnitude2heatmap, istft_reconstruction, warpgrid, combine_video_audio, save_video, makedirs\n'), ((3552, 3566), 'utils.AverageMeter', 'AverageMeter', ([], {}), '()\n', (3564, 3566)... |
import numpy as np
import cv2
import matplotlib.pyplot as plt
from random import *
def centroid_histogram(clt):
numLabels = np.arange(0, len(np.unique(clt.labels_)) + 1)
(hist, _) = np.histogram(clt.labels_, bins=numLabels)
hist = hist.astype("float")
hist /= hist.sum()
# Olusturulan his... | [
"matplotlib.pyplot.imshow",
"numpy.histogram",
"matplotlib.pyplot.savefig",
"numpy.unique",
"matplotlib.pyplot.figure",
"numpy.zeros",
"matplotlib.pyplot.axis"
] | [((199, 240), 'numpy.histogram', 'np.histogram', (['clt.labels_'], {'bins': 'numLabels'}), '(clt.labels_, bins=numLabels)\n', (211, 240), True, 'import numpy as np\n'), ((604, 642), 'numpy.zeros', 'np.zeros', (['(300, 300, 3)'], {'dtype': '"""uint8"""'}), "((300, 300, 3), dtype='uint8')\n", (612, 642), True, 'import nu... |
#!/usr/bin/env python3
import time
import math
from datetime import datetime
from time import sleep
import numpy as np
import random
import cv2
import os
import argparse
import torch
import sys
sys.path.append('./')
from env_98 import Engine98
from utils_env import get_view,safe_path,cut_frame,point2traj,get_gripper_... | [
"sys.path.append"
] | [((195, 216), 'sys.path.append', 'sys.path.append', (['"""./"""'], {}), "('./')\n", (210, 216), False, 'import sys\n')] |