code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... | [
"mindspore.context.set_context",
"mindspore.train.callback.CheckpointConfig",
"mindspore.nn.Adam",
"src.loss.NetWithLoss",
"argparse.ArgumentParser",
"src.config.update_config",
"src.scheduler.get_lr",
"mindspore.communication.management.init",
"moxing.file.copy_parallel",
"mindspore.Tensor",
"m... | [((1501, 1556), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Train PoseEstNet"""'}), "(description='Train PoseEstNet')\n", (1524, 1556), False, 'import argparse\n'), ((2201, 2225), 'src.config.update_config', 'update_config', (['cfg', 'args'], {}), '(cfg, args)\n', (2214, 2225), False,... |
from hwt.hdl.constants import WRITE, READ
from hwt.interfaces.agents.handshaked import HandshakedReadListener
from hwtLib.sim.abstractMemSpaceMaster import AbstractMemSpaceMaster
class TupleWithCallback(tuple):
def __new__(cls, *args):
return tuple.__new__(cls, args)
class AvalonMmMemSpaceMaster(Abstra... | [
"hwt.interfaces.agents.handshaked.HandshakedReadListener"
] | [((1467, 1506), 'hwt.interfaces.agents.handshaked.HandshakedReadListener', 'HandshakedReadListener', (['self._bus.r._ag'], {}), '(self._bus.r._ag)\n', (1489, 1506), False, 'from hwt.interfaces.agents.handshaked import HandshakedReadListener\n')] |
from dataclasses import dataclass
from typing import Any, Optional
@dataclass(frozen=True)
class Product:
name: str
link: str
price: Optional[float] = None
def __hash__(self) -> int:
return hash(self.name + self.link)
def __eq__(self, other: Any) -> bool:
return isinstance(other,... | [
"dataclasses.dataclass"
] | [((70, 92), 'dataclasses.dataclass', 'dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (79, 92), False, 'from dataclasses import dataclass\n')] |
from pip._internal import main as pipmain
import requests
import json
import os
import fontbakery
import sys
from PyQt5.QtWidgets import (
QMessageBox,
)
url = 'https://api.github.com/repos/googlefonts/fontbakery/tags'
tag_url = 'git+git://github.com/googlefonts/fontbakery.git@v'
current = fontbakery.__version__
i... | [
"PyQt5.QtWidgets.QMessageBox",
"json.loads",
"pip._internal.main",
"requests.get",
"sys.exit"
] | [((1009, 1022), 'PyQt5.QtWidgets.QMessageBox', 'QMessageBox', ([], {}), '()\n', (1020, 1022), False, 'from PyQt5.QtWidgets import QMessageBox\n'), ((1525, 1570), 'pip._internal.main', 'pipmain', (["['install', '--user', tag_url + ver]"], {}), "(['install', '--user', tag_url + ver])\n", (1532, 1570), True, 'from pip._in... |
# -*- coding: utf-8 -*-
from django.core.exceptions import ValidationError
from django.test import TestCase, override_settings, tag
import factories
from workflow.models import (Dashboard, TolaUser, Office,
ROLE_ORGANIZATION_ADMIN)
@tag('pkg')
class DashboardTest(TestCase):
def setUp... | [
"factories.Organization.build",
"factories.WorkflowTeam",
"factories.WorkflowLevel2",
"workflow.models.TolaUser.objects.create",
"factories.Group",
"factories.WorkflowLevel1.build",
"workflow.models.Dashboard",
"factories.TolaUser",
"django.test.tag",
"factories.Organization",
"workflow.models.O... | [((265, 275), 'django.test.tag', 'tag', (['"""pkg"""'], {}), "('pkg')\n", (268, 275), False, 'from django.test import TestCase, override_settings, tag\n'), ((1839, 1849), 'django.test.tag', 'tag', (['"""pkg"""'], {}), "('pkg')\n", (1842, 1849), False, 'from django.test import TestCase, override_settings, tag\n'), ((353... |
#!/usr/bin/env python3
# Copyleft (c) 2017 <NAME>
import datetime
import time
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (assert_equal, assert_raises_rpc_error)
class WHC_RawTx_Test(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 2
... | [
"datetime.datetime.now"
] | [((1343, 1366), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (1364, 1366), False, 'import datetime\n')] |
#
# DeepR<NAME>
#
# Version 3.0 onwards
#
# Copyright (c) 2021 dmh23
#
import math
from base64 import b16encode
from enum import IntEnum, auto
from matplotlib.colors import Colormap
from matplotlib.pyplot import get_cmap
import src.personalize.configuration.appearance as config
_COLORMAP_A = get_cmap(config.COLORMA... | [
"enum.auto",
"math.floor",
"matplotlib.pyplot.get_cmap"
] | [((297, 324), 'matplotlib.pyplot.get_cmap', 'get_cmap', (['config.COLORMAP_A'], {}), '(config.COLORMAP_A)\n', (305, 324), False, 'from matplotlib.pyplot import get_cmap\n'), ((339, 366), 'matplotlib.pyplot.get_cmap', 'get_cmap', (['config.COLORMAP_B'], {}), '(config.COLORMAP_B)\n', (347, 366), False, 'from matplotlib.p... |
#@category VtableDatabase
import json
from ghidra.util.task.TaskMonitor import DUMMY
from ghidra.program.model.data import InvalidDataTypeException
from ghidra.app.cmd.data.rtti.gcc import VtableModel
from ghidra.app.cmd.data.rtti.gcc.TypeInfoUtils import getDataTypePath
from ghidra.app.cmd.data.rtti.gcc.ClassTypeInfoU... | [
"ghidra.program.model.data.DataTypePath",
"ghidra.app.util.demangler.DemanglerUtil.demangle",
"json.load",
"ghidra.app.util.demangler.DemanglerOptions",
"ghidra.program.model.data.UnionDataType",
"ghidra.program.model.data.StructureDataType"
] | [((1032, 1050), 'ghidra.app.util.demangler.DemanglerOptions', 'DemanglerOptions', ([], {}), '()\n', (1048, 1050), False, 'from ghidra.app.util.demangler import DemanglerOptions\n'), ((3853, 3896), 'ghidra.program.model.data.DataTypePath', 'DataTypePath', (["entry['CategoryPath', 'Name']"], {}), "(entry['CategoryPath', ... |
# This firmware publishes the built firmware.hex file to an Azure blob store
# so the Server can find it there and distribute it to the Raspberry Pi Devices.
import os
import sys
import binascii
import hashlib
import hmac
from azure.storage.blob import BlobServiceClient
script_dir = os.path.dirname(os.path.abspath(_... | [
"os.path.abspath",
"azure.storage.blob.BlobServiceClient.from_connection_string",
"hmac.new",
"os.path.isfile",
"binascii.unhexlify",
"os.path.join",
"os.getenv",
"sys.exit"
] | [((340, 400), 'os.path.join', 'os.path.join', (['script_dir', '""".pio/build/teensy40/firmware.hex"""'], {}), "(script_dir, '.pio/build/teensy40/firmware.hex')\n", (352, 400), False, 'import os\n'), ((552, 594), 'os.getenv', 'os.getenv', (['"""ADA_STORAGE_CONNECTION_STRING"""'], {}), "('ADA_STORAGE_CONNECTION_STRING')\... |
import sys
import os.path as op
from aiida.engine import submit
from aiida.orm import load_code
from aiida_siesta.calculations.siesta import SiestaCalculation
from aiida.plugins import DataFactory
from aiida_siesta.workflows.stm import SiestaSTMWorkChain
# This is an example for the submission of the STM WorkChain.
# ... | [
"os.path.dirname",
"aiida.plugins.DataFactory",
"aiida.orm.load_code",
"aiida.engine.submit"
] | [((598, 623), 'aiida.plugins.DataFactory', 'DataFactory', (['"""pseudo.psf"""'], {}), "('pseudo.psf')\n", (609, 623), False, 'from aiida.plugins import DataFactory\n'), ((631, 650), 'aiida.plugins.DataFactory', 'DataFactory', (['"""dict"""'], {}), "('dict')\n", (642, 650), False, 'from aiida.plugins import DataFactory\... |
# coding=UTF-8
import json
import unittest
import requests
from jsonpath import jsonpath
class TaskControllerTest(unittest.TestCase):
def test_registration(self):
headers = {'Content-type': 'application/x-www-form-urlencoded'}
payload = {'username': 'dev', 'password': '<PASSWORD>', 'tenentCode':... | [
"unittest.main",
"json.loads",
"jsonpath.jsonpath",
"requests.get",
"requests.post"
] | [((1260, 1275), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1273, 1275), False, 'import unittest\n'), ((347, 434), 'requests.post', 'requests.post', (['"""http://127.0.0.1:8002/auth/sign-in"""'], {'headers': 'headers', 'data': 'payload'}), "('http://127.0.0.1:8002/auth/sign-in', headers=headers, data=\n pay... |
##############################################################################
#
# Copyright (c) 2003-2018 by The University of Queensland
# http://www.uq.edu.au
#
# Primary Business: Queensland, Australia
# Licensed under the Apache License, version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
#
# Development unt... | [
"esys.modellib.input.InterpolateOverBox",
"esys.escript.modelframe.Link",
"esys.modellib.visualization.WriteVTK",
"esys.modellib.geometry.VectorConstrainerOverBox",
"esys.escript.modelframe.Simulation",
"esys.modellib.input.Sequencer",
"esys.modellib.geometry.UpdateGeometry",
"esys.modellib.mechanics.... | [((1431, 1459), 'esys.modellib.geometry.RectangularDomain', 'RectangularDomain', ([], {'debug': 'dbg'}), '(debug=dbg)\n', (1448, 1459), False, 'from esys.modellib.geometry import RectangularDomain, VectorConstrainerOverBox, UpdateGeometry\n'), ((1544, 1564), 'esys.modellib.input.Sequencer', 'Sequencer', ([], {'debug': ... |
import sys
import numpy as np
import matplotlib.pyplot as plt
import torch
import random
try:
import cv2
except ImportError:
import sys
sys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages')
import cv2
from data import COCODetection
from data import cfg, set_cfg, set_dataset
from data import ... | [
"sys.path.remove",
"cv2.putText",
"random.randint",
"data.cfg.dataset.print",
"cv2.waitKey",
"cv2.getTextSize",
"torch.split",
"data.set_dataset",
"torch.Tensor",
"cv2.rectangle",
"cv2.imshow",
"utils.augmentations.SSDAugmentation",
"torch.from_numpy"
] | [((431, 453), 'random.randint', 'random.randint', (['(0)', '(255)'], {}), '(0, 255)\n', (445, 453), False, 'import random\n'), ((462, 484), 'random.randint', 'random.randint', (['(0)', '(255)'], {}), '(0, 255)\n', (476, 484), False, 'import random\n'), ((493, 515), 'random.randint', 'random.randint', (['(0)', '(255)'],... |
from pathlib import Path
import pytest
from robocop.rules import RuleSeverity, Rule
from robocop.utils import DisablersFinder
@pytest.fixture
def message():
msg = (
"somerule",
"Some description",
RuleSeverity.WARNING
)
return Rule('1010', msg)
class TestDisablers:
def test... | [
"robocop.rules.Rule",
"pathlib.Path"
] | [((267, 284), 'robocop.rules.Rule', 'Rule', (['"""1010"""', 'msg'], {}), "('1010', msg)\n", (271, 284), False, 'from robocop.rules import RuleSeverity, Rule\n'), ((401, 415), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (405, 415), False, 'from pathlib import Path\n'), ((599, 613), 'pathlib.Path', 'Path'... |
from django.contrib import admin
from bookmarks import models
class BookmarkAdmin(admin.ModelAdmin):
list_display = ('content_object', 'key', 'user', 'created_at')
list_filter = ('created_at',)
ordering = ('-created_at',)
search_fields = ('user', 'key')
readonly_fields = ('user',)
admin.site.reg... | [
"django.contrib.admin.site.register"
] | [((306, 357), 'django.contrib.admin.site.register', 'admin.site.register', (['models.Bookmark', 'BookmarkAdmin'], {}), '(models.Bookmark, BookmarkAdmin)\n', (325, 357), False, 'from django.contrib import admin\n')] |
import random
async def run(client, message):
if len(message.content.split()) < 2:
value_list = list(range(2,11)) + ['jack', 'queen', 'king', 'ace']
suit_list = ['hearts', 'diamonds', 'spades', 'clubs']
value = random.choice(value_list)
suit = random.choice(suit_list)
res... | [
"random.choice"
] | [((242, 267), 'random.choice', 'random.choice', (['value_list'], {}), '(value_list)\n', (255, 267), False, 'import random\n'), ((283, 307), 'random.choice', 'random.choice', (['suit_list'], {}), '(suit_list)\n', (296, 307), False, 'import random\n')] |
"""
Running the backend:
$ uvicorn formatter:app
Viewing the frontend:
http://127.0.0.1:8000/
"""
from typing import Optional
import yaml
from fastapi import FastAPI
from fastapi.responses import JSONResponse, HTMLResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
TEST_DATA = {
... | [
"fastapi.staticfiles.StaticFiles",
"fastapi.FastAPI"
] | [((899, 908), 'fastapi.FastAPI', 'FastAPI', ([], {}), '()\n', (906, 908), False, 'from fastapi import FastAPI\n'), ((930, 962), 'fastapi.staticfiles.StaticFiles', 'StaticFiles', ([], {'directory': '"""static/"""'}), "(directory='static/')\n", (941, 962), False, 'from fastapi.staticfiles import StaticFiles\n')] |
import logging
import random
import redis
from flask import abort
from flask import after_this_request
from flask import current_app
from flask import make_response
from flask import request
from flask.views import MethodView
from .schemas import SmsRequestParameters
from .schemas import ValidateSmsCodeParameters
fro... | [
"redis.Redis",
"flask_rest_api.Blueprint",
"random.randint",
"app.services.tencent.send_sms.send_message",
"flask.abort",
"flask.request.cookies.get",
"flask.make_response",
"logging.getLogger"
] | [((442, 469), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (459, 469), False, 'import logging\n'), ((476, 554), 'flask_rest_api.Blueprint', 'Blueprint', (['"""SMS"""', '"""SMS"""'], {'url_prefix': '"""/auth/sms"""', 'description': '"""SMS Related API"""'}), "('SMS', 'SMS', url_prefix='/... |
#! /usr/bin/env python3
import os, sys, re, time
# check if the set ps1 is set and not too long
def check_ps1():
try:
if len(os.environ['PS1']) < 20 and len(os.environ['PS1']) >= 0:
return os.environ['PS1']
except KeyError:
return '$ '
return '$ '
# reads input from fd 0 from user
def my_read_l... | [
"os.read",
"re.split",
"os.getpid",
"os.pipe",
"os.dup",
"os.wait",
"os.execve",
"os.fork",
"os.close",
"os.set_inheritable",
"os.chdir",
"sys.exit"
] | [((373, 389), 'os.read', 'os.read', (['(0)', '(1000)'], {}), '(0, 1000)\n', (380, 389), False, 'import os, sys, re, time\n'), ((585, 618), 're.split', 're.split', (['""":"""', "os.environ['PATH']"], {}), "(':', os.environ['PATH'])\n", (593, 618), False, 'import os, sys, re, time\n'), ((997, 1008), 'sys.exit', 'sys.exit... |
import os
ROOTDIR = "./after_modify/train/"
DESTDIR = "./after_modify/chi/"
total_doc_num = 0
total_vocabulary = {}
each_class_words = [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}]
each_class_words_list = [[], [], [], [], [], [], [], [], [], []]
each_class_doc_num = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
class_index = ["07", "08",... | [
"os.walk"
] | [((445, 461), 'os.walk', 'os.walk', (['ROOTDIR'], {}), '(ROOTDIR)\n', (452, 461), False, 'import os\n')] |
# -*- coding: utf-8 -*-
# Copyright Noronha Development Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | [
"mongoengine.fields.StringField",
"mongoengine.fields.ReferenceField"
] | [((1310, 1354), 'mongoengine.fields.StringField', 'StringField', ([], {'max_length': 'DBConst.MAX_NAME_LEN'}), '(max_length=DBConst.MAX_NAME_LEN)\n', (1321, 1354), False, 'from mongoengine.fields import StringField, ListField, ReferenceField\n'), ((1366, 1422), 'mongoengine.fields.StringField', 'StringField', ([], {'ma... |
from omnisolver.plugin import Plugin
from omnisolver.pt import get_plugin
def test_plugin_can_be_loaded():
assert isinstance(get_plugin(), Plugin)
| [
"omnisolver.pt.get_plugin"
] | [((132, 144), 'omnisolver.pt.get_plugin', 'get_plugin', ([], {}), '()\n', (142, 144), False, 'from omnisolver.pt import get_plugin\n')] |
import sys
import os
from typing import Tuple
from numpy.random.mtrand import random
sys.path.append('C:\\Users\\coton\\Desktop\\github\\fema\\src\\')
import numpy as np
import math
from fem_basis import Basis
class FEMaSemiSupervisedClassifier:
"""
Class responsible to perform the classificatio... | [
"sys.path.append",
"numpy.append",
"numpy.zeros",
"numpy.argmax"
] | [((88, 153), 'sys.path.append', 'sys.path.append', (['"""C:\\\\Users\\\\coton\\\\Desktop\\\\github\\\\fema\\\\src\\\\"""'], {}), "('C:\\\\Users\\\\coton\\\\Desktop\\\\github\\\\fema\\\\src\\\\')\n", (103, 153), False, 'import sys\n'), ((1993, 2045), 'numpy.zeros', 'np.zeros', (['(self.num_classes, self.num_train_sample... |
# Generated by Django 3.2.8 on 2021-11-29 15:59
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('menu', '0003_auto_20211126_0134'),
migrations.swappable_dependency(settings.AUTH_US... | [
"django.db.models.ForeignKey",
"django.db.migrations.swappable_dependency"
] | [((272, 329), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (303, 329), False, 'from django.db import migrations, models\n'), ((529, 640), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'blank': '(True)', 'n... |
"""All command definitions."""
# Standard Library
import re
import sys
import socket
import ipaddress
# Third Party
from click import option, command, confirm, argument
from icmplib import ping
from rich.table import Table
from rich.console import Console
# Project
from jollyip.types import NUMBER
from jollyip.forma... | [
"stackprinter.set_excepthook",
"ipaddress.ip_network",
"click.argument",
"jollyip.formatting.success",
"ipaddress.summarize_address_range",
"click.option",
"ipaddress.ip_address",
"click.command",
"jollyip.formatting.info",
"os.getegid",
"socket.getaddrinfo",
"jollyip.formatting.error",
"icm... | [((4334, 4456), 'jollyip.formatting.info', 'info', (['"""Ping {t}\n\n{t} Can be an IPv4 or IPv6 host, subnet, range, or an FQDN.\n\n"""'], {'t': '"""<target>"""', 'callback': 'None'}), '(\n """Ping {t}\n\n{t} Can be an IPv4 or IPv6 host, subnet, range, or an FQDN.\n\n"""\n , t=\'<target>\', callback=None)\n', (43... |
import numpy as np
import math
# TODO: Use anytree to represent the tree
class TreeNode:
def __init__(self, lb, ub, num_split, rand = False):
self.lb = lb
self.ub = ub
self.x = 0.5 * (lb + ub) if not rand else np.random.uniform(lb, ub)
self.y = np.nan
self.ch... | [
"numpy.random.uniform",
"numpy.all",
"numpy.argmax"
] | [((726, 754), 'numpy.argmax', 'np.argmax', (['(self.ub - self.lb)'], {}), '(self.ub - self.lb)\n', (735, 754), True, 'import numpy as np\n'), ((247, 272), 'numpy.random.uniform', 'np.random.uniform', (['lb', 'ub'], {}), '(lb, ub)\n', (264, 272), True, 'import numpy as np\n'), ((383, 408), 'numpy.all', 'np.all', (['(sel... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 合并多个字典或映射
Desc :
"""
from collections import ChainMap
def combine_map():
a = {'x': 1, 'z': 3 }
b = {'y': 2, 'z': 4 }
c = ChainMap(a,b)
print(c['x']) # Outputs 1 (from a)
print(c['y']) # Outputs 2 (from b)
print(c['z']) # Outputs 3 (f... | [
"collections.ChainMap"
] | [((196, 210), 'collections.ChainMap', 'ChainMap', (['a', 'b'], {}), '(a, b)\n', (204, 210), False, 'from collections import ChainMap\n'), ((492, 502), 'collections.ChainMap', 'ChainMap', ([], {}), '()\n', (500, 502), False, 'from collections import ChainMap\n')] |
#!/usr/bin/env python
""" verlat numerical integration methods """
import numpy as np
def velocity_verlat(x_init, acc, step, time):
""" the velocity verlat method """
# finding count
count = int(time / step)
# initialization
x = np.zeros(count)
x_dot = np.zeros(count)
x[0] = x_init
... | [
"numpy.zeros",
"numpy.delete"
] | [((254, 269), 'numpy.zeros', 'np.zeros', (['count'], {}), '(count)\n', (262, 269), True, 'import numpy as np\n'), ((282, 297), 'numpy.zeros', 'np.zeros', (['count'], {}), '(count)\n', (290, 297), True, 'import numpy as np\n'), ((698, 717), 'numpy.zeros', 'np.zeros', (['(count + 2)'], {}), '(count + 2)\n', (706, 717), T... |
import os
import tempfile
import shutil
import os.path as op
from bento.compat.api.moves \
import \
unittest
from bento.core.package \
import \
PackageDescription
from bento.core.node_package \
import \
NodeRepresentation
from bento.core.node \
import \
create_root_wit... | [
"bento.core.node_package.NodeRepresentation",
"os.getcwd",
"bento.core.package.PackageDescription.from_string",
"tempfile.mkdtemp",
"bento.core.testing.create_fake_package_from_bento_info",
"shutil.rmtree",
"os.path.join",
"os.chdir"
] | [((505, 523), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (521, 523), False, 'import tempfile\n'), ((688, 699), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (697, 699), False, 'import os\n'), ((708, 724), 'os.chdir', 'os.chdir', (['self.d'], {}), '(self.d)\n', (716, 724), False, 'import os\n'), ((758, 780)... |
import numpy as np
from datetime import datetime
from scipy import sparse
class Indexer:
def __init__(self, nodes):
self.indices = {node: 0 for node in nodes}
self.mapping = {node: {} for node in nodes}
def index(self, category, query):
if query not in self.mapping[category]:
... | [
"scipy.sparse.coo_matrix",
"datetime.datetime"
] | [((787, 838), 'scipy.sparse.coo_matrix', 'sparse.coo_matrix', (['(data, (row, col))'], {'shape': '(m, n)'}), '((data, (row, col)), shape=(m, n))\n', (804, 838), False, 'from scipy import sparse\n'), ((1067, 1087), 'datetime.datetime', 'datetime', (['(2006)', '(1)', '(1)'], {}), '(2006, 1, 1)\n', (1075, 1087), False, 'f... |
from bs4 import BeautifulSoup, Comment
from yarl import URL
from typing import Optional, List
from ..util import parsing
from .request import Request
class item_description(Request):
"""
Gets the description of an item and then parses various information from the response.
"""
def __init__(self, ses... | [
"bs4.BeautifulSoup",
"yarl.URL"
] | [((561, 598), 'bs4.BeautifulSoup', 'BeautifulSoup', (['content', '"""html.parser"""'], {}), "(content, 'html.parser')\n", (574, 598), False, 'from bs4 import BeautifulSoup, Comment\n'), ((881, 913), 'yarl.URL', 'URL', (["container.center.img['src']"], {}), "(container.center.img['src'])\n", (884, 913), False, 'from yar... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import cv2
import numpy as np
camera = cv2.VideoCapture(0)
gray = None
while True:
ret, frame = camera.read()
if ret is False:
print("Camera open failed")
break
newgray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
display_img = newgray
if ... | [
"cv2.cvtColor",
"cv2.waitKey",
"cv2.VideoCapture",
"numpy.where",
"cv2.imshow"
] | [((87, 106), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (103, 106), False, 'import cv2\n'), ((247, 286), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2GRAY'], {}), '(frame, cv2.COLOR_BGR2GRAY)\n', (259, 286), False, 'import cv2\n'), ((565, 597), 'cv2.imshow', 'cv2.imshow', (['"""hello""... |
import json
class BadRequest(Exception):
"""Bad Request Exception (400)"""
def __str__(self):
return 'Bad Request'
class AuthenticationException(Exception):
"""Unauthenticated Exception (401)"""
def __str__(self):
return 'Unauthenticated'
class FormErrorBag:
def __init__(self, ... | [
"json.dumps"
] | [((798, 821), 'json.dumps', 'json.dumps', (['self.errors'], {}), '(self.errors)\n', (808, 821), False, 'import json\n')] |
'''
Date: 2021-09-16 16:15:55
LastEditors: xgy
LastEditTime: 2021-09-17 22:09:02
FilePath: \code\crnn_ctc\src\metric.py
'''
"""Metric for accuracy evaluation."""
from mindspore import nn
import Levenshtein
from src.config import label_dict
# label_dict = "abcdefghijklmnopqrstuvwxyz0123456789"
class CRNNAccuracy(nn.Met... | [
"Levenshtein.distance",
"Levenshtein.ratio"
] | [((1284, 1317), 'Levenshtein.distance', 'Levenshtein.distance', (['pred', 'label'], {}), '(pred, label)\n', (1304, 1317), False, 'import Levenshtein\n'), ((1340, 1370), 'Levenshtein.ratio', 'Levenshtein.ratio', (['label', 'pred'], {}), '(label, pred)\n', (1357, 1370), False, 'import Levenshtein\n')] |
from kivy.app import App
from kivy.lang.builder import Builder
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from hello_world import HelloWorld
class Box(BoxLayout):
pass
Builder.load_string("""
<Box>:
Button:
on_press: app.hello_world.send_string("Hello from python")
"... | [
"hello_world.HelloWorld",
"kivy.lang.builder.Builder.load_string"
] | [((209, 333), 'kivy.lang.builder.Builder.load_string', 'Builder.load_string', (['"""\n<Box>:\n Button:\n on_press: app.hello_world.send_string("Hello from python")\n"""'], {}), '(\n """\n<Box>:\n Button:\n on_press: app.hello_world.send_string("Hello from python")\n"""\n )\n', (228, 333), Fals... |
# Copyright 2016 The TensorFlow 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... | [
"tensorflow.python.util.all_util.remove_undocumented"
] | [((1309, 1338), 'tensorflow.python.util.all_util.remove_undocumented', 'remove_undocumented', (['__name__'], {}), '(__name__)\n', (1328, 1338), False, 'from tensorflow.python.util.all_util import remove_undocumented\n')] |
from my_db.db_mongo.model import IotConnector, Token, Endpoint, Shadow, ResourceUse
from my_db.db_mongo import mongo_setup
from my_db.restful_API.auth import core
from http import HTTPStatus
from django import http
import json
import uuid
mongo_setup.global_init() # makes connection with db
def get_physical_device... | [
"my_db.db_mongo.model.Endpoint.objects.with_id",
"my_db.db_mongo.model.Shadow.objects.with_id",
"uuid.uuid4",
"json.loads",
"my_db.db_mongo.model.IotConnector",
"django.http.JsonResponse",
"my_db.restful_API.auth.core.validate",
"my_db.db_mongo.model.Token.objects",
"my_db.db_mongo.model.ResourceUse... | [((241, 266), 'my_db.db_mongo.mongo_setup.global_init', 'mongo_setup.global_init', ([], {}), '()\n', (264, 266), False, 'from my_db.db_mongo import mongo_setup\n'), ((589, 609), 'my_db.restful_API.auth.core.validate', 'core.validate', (['token'], {}), '(token)\n', (602, 609), False, 'from my_db.restful_API.auth import ... |
#!/usr/bin/env python
u"""
count_leap_seconds.py (08/2020)
Count number of leap seconds that have passed for each GPS time
"""
import warnings
import pyTMD.time
def count_leap_seconds(*args,**kwargs):
warnings.filterwarnings("always")
warnings.warn("Deprecated. Please use pyTMD.time instead",DeprecationWarning... | [
"warnings.warn",
"warnings.filterwarnings"
] | [((206, 239), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""always"""'], {}), "('always')\n", (229, 239), False, 'import warnings\n'), ((244, 322), 'warnings.warn', 'warnings.warn', (['"""Deprecated. Please use pyTMD.time instead"""', 'DeprecationWarning'], {}), "('Deprecated. Please use pyTMD.time instea... |
import dataclasses
from typing import Any, Callable, Dict, Iterator, Type
from .enums import Strategy
ConverterFn = Callable[[Any], Any]
MappingFn = Callable[[Any], Any]
FieldMapping = Dict[str, MappingFn]
FieldIterator = Iterator[str]
TestFn = Callable[[Type], bool]
@dataclasses.dataclass
class FieldIter:
test:... | [
"dataclasses.field"
] | [((914, 953), 'dataclasses.field', 'dataclasses.field', ([], {'default_factory': 'dict'}), '(default_factory=dict)\n', (931, 953), False, 'import dataclasses\n')] |
import random
from app import db
from app.models.models import Detail
from app.utils.common.common import login_user_data
from . import detail_blu
from flask import render_template, request, session, redirect, url_for,g
# 创建视图函数
@detail_blu.route("/add_detail/<news_id>", methods=["POST", "GET"])
@login_user_data
def... | [
"flask.redirect",
"flask.request.form.get",
"app.db.session.commit",
"flask.render_template",
"app.db.session.query"
] | [((510, 528), 'flask.redirect', 'redirect', (['"""/login"""'], {}), "('/login')\n", (518, 528), False, 'from flask import render_template, request, session, redirect, url_for, g\n'), ((712, 777), 'flask.render_template', 'render_template', (['"""jie/add.html"""'], {'detail_id': 'detail_id', 'user': 'g.user'}), "('jie/a... |
#!/usr/bin/env python3
import logging
from functools import wraps
__author__ = '<NAME>'
__email__ = '<EMAIL>'
_level = -1
_step = ' '
def log_def(name):
def decorator(func):
@wraps(func)
def wrapper(*args, **kw):
logger = logging.getLogger(name)
global _level
... | [
"logging.getLogger",
"functools.wraps"
] | [((194, 205), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (199, 205), False, 'from functools import wraps\n'), ((261, 284), 'logging.getLogger', 'logging.getLogger', (['name'], {}), '(name)\n', (278, 284), False, 'import logging\n')] |
import unittest
from exercises import (
factorial,
fib,
power,
product_of_list,
reverse,
sum_range
)
class TestRecursionExercises(unittest.TestCase):
def test_power(self):
"""
Tests the power(base, exponent) method
"""
self.assertEqual(4, power(2, 2))
... | [
"unittest.main",
"exercises.power",
"exercises.fib",
"exercises.product_of_list",
"exercises.sum_range",
"exercises.reverse",
"exercises.factorial"
] | [((1837, 1852), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1850, 1852), False, 'import unittest\n'), ((303, 314), 'exercises.power', 'power', (['(2)', '(2)'], {}), '(2, 2)\n', (308, 314), False, 'from exercises import factorial, fib, power, product_of_list, reverse, sum_range\n'), ((344, 355), 'exercises.powe... |
# -*- coding: utf-8 -*-
import os
import test
from django.conf import settings
from django.contrib.auth import get_user_model
from django.shortcuts import reverse
from ontask.action.views.import_export import do_import_action
from ontask.dataops.pandas import check_wf_df, load_table
from ontask.models import Action,... | [
"test.delete_all_tables",
"django.conf.settings.BASE_DIR",
"test.pg_restore_table",
"django.contrib.auth.get_user_model",
"ontask.action.views.import_export.do_import_action",
"ontask.models.Action.objects.get",
"ontask.dataops.pandas.check_wf_df",
"django.shortcuts.reverse",
"ontask.models.Workflow... | [((456, 475), 'django.conf.settings.BASE_DIR', 'settings.BASE_DIR', ([], {}), '()\n', (473, 475), False, 'from django.conf import settings\n'), ((1017, 1052), 'test.pg_restore_table', 'test.pg_restore_table', (['cls.filename'], {}), '(cls.filename)\n', (1038, 1052), False, 'import test\n'), ((1086, 1110), 'test.delete_... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import numpy as np
from numpy import sin, cos, tan, arctan2, radians, degrees, sqrt
from Quaternion import Quat
def radec2eci(ra, dec):
"""
Convert from RA,Dec to ECI. The input ``ra`` and ``dec`` values can be 1-d
arrays of length N in whic... | [
"numpy.radians",
"numpy.sum",
"numpy.arctan2",
"Quaternion.Quat",
"numpy.degrees",
"numpy.cross",
"numpy.arcsin",
"numpy.sin",
"numpy.array",
"numpy.cos",
"numpy.dot",
"numpy.arccos",
"numpy.sqrt"
] | [((535, 546), 'numpy.radians', 'radians', (['ra'], {}), '(ra)\n', (542, 546), False, 'from numpy import sin, cos, tan, arctan2, radians, degrees, sqrt\n'), ((555, 567), 'numpy.radians', 'radians', (['dec'], {}), '(dec)\n', (562, 567), False, 'from numpy import sin, cos, tan, arctan2, radians, degrees, sqrt\n'), ((2382,... |
from PyQt5.QtWidgets import *
from os import listdir, getenv
from datetime import datetime
from ctypes import *
import zipfile
resolution = [windll.user32.GetSystemMetrics(0), windll.user32.GetSystemMetrics(1)]
backups_dir = listdir(path=getenv('appdata') + "\\Backups\\")
zip_name = datetime.strftime(datetime.now(), "... | [
"zipfile.ZipFile",
"datetime.datetime.now",
"os.getenv"
] | [((303, 317), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (315, 317), False, 'from datetime import datetime\n'), ((239, 256), 'os.getenv', 'getenv', (['"""appdata"""'], {}), "('appdata')\n", (245, 256), False, 'from os import listdir, getenv\n'), ((1318, 1351), 'zipfile.ZipFile', 'zipfile.ZipFile', (['de... |
import torch
from torch import nn
from torch.nn import functional as F
from Utils.flags import FLAGS
import numpy as np
from torch.autograd import Variable
crossentropy = nn.CrossEntropyLoss()
softmax = nn.Softmax(1)
logsoftmax = nn.LogSoftmax(1)
# some utils TODO
def update_average(model_tgt, model_src, beta=0.999)... | [
"torch.mean",
"numpy.sum",
"torch.nn.LogSoftmax",
"torch.nn.CrossEntropyLoss",
"torch.cat",
"numpy.clip",
"torch.nn.functional.softmax",
"torch.nn.Softmax",
"numpy.exp",
"torch.nn.functional.log_softmax",
"numpy.cos",
"torch.sum",
"torch.from_numpy"
] | [((173, 194), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (192, 194), False, 'from torch import nn\n'), ((205, 218), 'torch.nn.Softmax', 'nn.Softmax', (['(1)'], {}), '(1)\n', (215, 218), False, 'from torch import nn\n'), ((232, 248), 'torch.nn.LogSoftmax', 'nn.LogSoftmax', (['(1)'], {}), '(1)\... |
from datetime import datetime
from unittest.mock import MagicMock, patch
from pytest import fixture
from app.twitter_learning_journal.models.tweet import Tweet
from app.twitter_learning_journal.retrievers.twitter.tweets import Tweets
@fixture(name='tweets')
@patch('app.twitter_learning_journal.retrievers.twitter.tw... | [
"app.twitter_learning_journal.models.tweet.Tweet",
"unittest.mock.MagicMock",
"app.twitter_learning_journal.retrievers.twitter.tweets.Tweets._remove_ignore_urls",
"pytest.fixture",
"unittest.mock.patch",
"app.twitter_learning_journal.retrievers.twitter.tweets.Tweets.extract_urls",
"datetime.datetime.now... | [((239, 261), 'pytest.fixture', 'fixture', ([], {'name': '"""tweets"""'}), "(name='tweets')\n", (246, 261), False, 'from pytest import fixture\n'), ((263, 338), 'unittest.mock.patch', 'patch', (['"""app.twitter_learning_journal.retrievers.twitter.tweets.TweetCacher"""'], {}), "('app.twitter_learning_journal.retrievers.... |
# -*- coding: utf-8 -*-
"""
Initial AST validation and normalization.
"""
from __future__ import print_function, division, absolute_import
import ast
from numba import error
class ValidateAST(ast.NodeVisitor):
"Validate AST"
#------------------------------------------------------------------------
# Va... | [
"numba.error.NumbaError"
] | [((462, 534), 'numba.error.NumbaError', 'error.NumbaError', (['node', '"""Generator comprehensions are not yet supported"""'], {}), "(node, 'Generator comprehensions are not yet supported')\n", (478, 534), False, 'from numba import error\n'), ((602, 668), 'numba.error.NumbaError', 'error.NumbaError', (['node', '"""Set ... |
#!/usr/bin/env python
# Copyright (C) 2014, PAL Robotics S.L.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the... | [
"rospy.wait_for_service",
"rostest.rosrun"
] | [((5829, 5906), 'rostest.rosrun', 'rostest.rosrun', (['"""controller_manager_msgs"""', '"""cm_msgs_utils_rostest"""', 'TestUtils'], {}), "('controller_manager_msgs', 'cm_msgs_utils_rostest', TestUtils)\n", (5843, 5906), False, 'import rostest\n'), ((1885, 1952), 'rospy.wait_for_service', 'rospy.wait_for_service', (['""... |
from sympy import Add, Matrix, Mul, S, symbols, Eq, pi, factorint, oo, powsimp, Rational
from sympy.core.function import _mexpand
from sympy.core.compatibility import ordered
from sympy.functions.elementary.trigonometric import sin
from sympy.solvers.diophantine import diophantine
from sympy.solvers.diophantine.diophan... | [
"sympy.solvers.diophantine.diophantine.prime_as_sum_of_two_squares",
"sympy.solvers.diophantine.diophantine._remove_gcd",
"sympy.solvers.diophantine.diophantine.ldescent",
"sympy.solvers.diophantine.diophantine.find_DN",
"sympy.solvers.diophantine.diophantine.diop_quadratic",
"sympy.Matrix",
"sympy.solv... | [((1445, 1516), 'sympy.symbols', 'symbols', (['"""a, b, c, d, p, q, x, y, z, w, t, u, v, X, Y, Z"""'], {'integer': '(True)'}), "('a, b, c, d, p, q, x, y, z, w, t, u, v, X, Y, Z', integer=True)\n", (1452, 1516), False, 'from sympy import Add, Matrix, Mul, S, symbols, Eq, pi, factorint, oo, powsimp, Rational\n'), ((1559,... |
from setuptools import find_packages, setup
setup(
name="coffee",
version="0.0.0",
description="PyBullet infrastructure is great, and so is coffee.",
author="<NAME>",
license="MIT",
packages=find_packages(),
package_data={"coffee": ["py.typed"]},
python_requires=">=3.8",
install_req... | [
"setuptools.find_packages"
] | [((216, 231), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (229, 231), False, 'from setuptools import find_packages, setup\n')] |
from flask import Flask, request, jsonify, Response
#import Flask-HTTPAuth
import models as model
import yagmail as yagmail ## temporal mientras se configura el servidor de correo
import os
import random
import secrets
import db_con as db
# SCRAM -> si se cambia por SCRAM (cifrar contraseña cliente -> DB),... | [
"flask_jwt_extended.get_jwt_identity",
"flask.jsonify",
"yagmail.SMTP",
"db_con.nuevo_hospital",
"flask.request.args.get",
"models.Hospital",
"flask_jwt_extended.create_access_token",
"db_con.verif_esta_hospital",
"db_con.revertirRegistroHospital",
"os.urandom",
"db_con.cargar_roles",
"db_con.... | [((611, 626), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (616, 626), False, 'from flask import Flask, request, jsonify, Response\n'), ((643, 657), 'os.urandom', 'os.urandom', (['(24)'], {}), '(24)\n', (653, 657), False, 'import os\n'), ((706, 721), 'flask_jwt_extended.JWTManager', 'JWTManager', (['app'... |
"""libaray for multi-modal dataset loaders.
Acknowledgements:
`image_to_caption_collate_fn` is based on
https://github.com/yalesong/pvse/blob/master/data.py
"""
import os
import numpy as np
import torch
from torch.utils.data import DataLoader
from datasets.coco import CocoCaptionsCap
from datasets.cub import CUBCap... | [
"numpy.load",
"torch.stack",
"torch.utils.data.DataLoader",
"datasets.coco.CocoCaptionsCap",
"datasets._transforms.imagenet_transform",
"datasets.vocab.Vocabulary",
"torch.Tensor",
"datasets._transforms.caption_transform",
"os.path.join"
] | [((1247, 1269), 'torch.stack', 'torch.stack', (['images', '(0)'], {}), '(images, 0)\n', (1258, 1269), False, 'import torch\n'), ((3785, 3822), 'os.path.join', 'os.path.join', (['dataset_root', '"""images/"""'], {}), "(dataset_root, 'images/')\n", (3797, 3822), False, 'import os\n'), ((8301, 8378), 'datasets._transforms... |
import cv2
class MovieWriter(object):
def __init__(self, file_name, frame_size, fps):
"""
frame_size is (w, h)
"""
self._frame_size = frame_size
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
self.vout = cv2.VideoWriter()
success = self.vout.open(file_n... | [
"cv2.cvtColor",
"cv2.VideoWriter_fourcc",
"cv2.VideoWriter"
] | [((200, 242), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (['"""m"""', '"""p"""', '"""4"""', '"""v"""'], {}), "('m', 'p', '4', 'v')\n", (222, 242), False, 'import cv2\n'), ((263, 280), 'cv2.VideoWriter', 'cv2.VideoWriter', ([], {}), '()\n', (278, 280), False, 'import cv2\n'), ((674, 724), 'cv2.cvtColor', 'cv2.c... |
#Python script for batch geocoding of addresses using the Google Geocoding API.
#This script geocodes addresses (including address components) from a specified csv file.
#Credit (template/framework): https://gist.github.com/shanealynn/033c8a3cacdba8ce03cbe116225ced31
#https://developers.google.com/maps/documentation... | [
"pandas.DataFrame",
"pandas.read_csv",
"logging.StreamHandler",
"time.sleep",
"requests.get",
"logging.getLogger"
] | [((546, 571), 'logging.getLogger', 'logging.getLogger', (['"""root"""'], {}), "('root')\n", (563, 571), False, 'import logging\n'), ((634, 657), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (655, 657), False, 'import logging\n'), ((1797, 1841), 'pandas.read_csv', 'pd.read_csv', (['FILENAME_INPUT'... |
import getopt
import os
import sys
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pylab
from matplotlib.font_manager import FontProperties
from matplotlib.ticker import LinearLocator, LogLocator, MaxNLocator
from numpy import double
OPT_FONT_NAME = 'Helvetica'
TICK_FONT_SIZE = 20
LABEL_FO... | [
"os.makedirs",
"matplotlib.font_manager.FontProperties",
"matplotlib.pyplot.legend",
"os.path.exists",
"os.system",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.savefig"
] | [((366, 418), 'matplotlib.font_manager.FontProperties', 'FontProperties', ([], {'style': '"""normal"""', 'size': 'LABEL_FONT_SIZE'}), "(style='normal', size=LABEL_FONT_SIZE)\n", (380, 418), False, 'from matplotlib.font_manager import FontProperties\n'), ((431, 484), 'matplotlib.font_manager.FontProperties', 'FontProper... |
import os
from .datacomm import *
CONST_PI = 3.14
datafile=os.path.join(os.getcwd(), 'data', 'data.csv')
| [
"os.getcwd"
] | [((74, 85), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (83, 85), False, 'import os\n')] |
"""
This module contains functions to average mdtraj-object data
"""
from copy import deepcopy
import numpy as np
from ase.data import chemical_symbols as symbols
def average_energies(mdtraj_list, tstart):
"""
function to compute averages of a selection of mdtraj objects
sorted by their composition... | [
"copy.deepcopy",
"numpy.std",
"numpy.zeros",
"numpy.mean",
"numpy.where"
] | [((876, 891), 'copy.deepcopy', 'deepcopy', (['comps'], {}), '(comps)\n', (884, 891), False, 'from copy import deepcopy\n'), ((1781, 1796), 'copy.deepcopy', 'deepcopy', (['comps'], {}), '(comps)\n', (1789, 1796), False, 'from copy import deepcopy\n'), ((4878, 4914), 'numpy.where', 'np.where', (["(dens['hists'][esub] != ... |
#!/usr/bin/python3
#
# Copyright (c) 2017-2021, <NAME> <<EMAIL>>
# Released under the ASL 2.0 license. See LICENSE.md file for details.
#
import asyncio
import json
import asyncws
ACCESS_TOKEN = '<KEY>'
async def main():
"""Simple WebSocket client for Home Assistant."""
websocket = await asyncws.connect('ws... | [
"asyncio.get_event_loop",
"json.dumps",
"asyncws.connect"
] | [((721, 745), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (743, 745), False, 'import asyncio\n'), ((301, 353), 'asyncws.connect', 'asyncws.connect', (['"""ws://localhost:8123/api/websocket"""'], {}), "('ws://localhost:8123/api/websocket')\n", (316, 353), False, 'import asyncws\n'), ((380, 438)... |
from app.api.business.validators import ApplicationValidator
from app.models import Application
from datetime import date, timedelta
def test_can_get_errors_with_none_recruiter():
application = Application(
data={
'recruiter': None
}
)
errors = ApplicationValidator(application)... | [
"app.models.Application",
"datetime.timedelta",
"datetime.date.today",
"app.api.business.validators.ApplicationValidator"
] | [((200, 237), 'app.models.Application', 'Application', ([], {'data': "{'recruiter': None}"}), "(data={'recruiter': None})\n", (211, 237), False, 'from app.models import Application\n'), ((436, 456), 'app.models.Application', 'Application', ([], {'data': '{}'}), '(data={})\n', (447, 456), False, 'from app.models import ... |
import re
import os
import glob
import shutil
import random
import logging
import torch
import numpy as np
logger = logging.getLogger(__name__)
def _rotate_checkpoints(args, checkpoint_prefix, use_mtime=False):
if not args.save_total_limit:
return
if args.save_total_limit <= 0:
return
#... | [
"numpy.random.seed",
"torch.manual_seed",
"torch.cuda.manual_seed_all",
"torch.cuda.is_available",
"random.seed",
"os.path.getmtime",
"shutil.rmtree",
"logging.getLogger"
] | [((118, 145), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (135, 145), False, 'import logging\n'), ((1551, 1573), 'random.seed', 'random.seed', (['args.seed'], {}), '(args.seed)\n', (1562, 1573), False, 'import random\n'), ((1578, 1603), 'numpy.random.seed', 'np.random.seed', (['args.se... |
import numpy as np
from numba import jit
np.random.seed(1)
class rocket_engine():
def __init__(self, dimensions = 3, temperature = 10000, N = 1E5, mass = 1.67e-27, length = 1e-6):
self.k = 1.38064852e-23
self.T = temperature
self.N = N
self.m = mass
self.L = le... | [
"numpy.less_equal",
"numpy.zeros_like",
"numpy.abs",
"numpy.random.seed",
"numpy.logical_and",
"numpy.sum",
"numpy.ones_like",
"numpy.multiply",
"numpy.where",
"numba.jit",
"numpy.greater_equal",
"numpy.sqrt"
] | [((43, 60), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (57, 60), True, 'import numpy as np\n'), ((734, 752), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (737, 752), False, 'from numba import jit\n'), ((379, 412), 'numpy.sqrt', 'np.sqrt', (['(self.k * self.T / self.m)'], {}... |
"""
Unit tests for instructor_task subtasks.
"""
from unittest.mock import Mock, patch
from uuid import uuid4
from common.djangoapps.student.models import CourseEnrollment
from lms.djangoapps.instructor_task.subtasks import queue_subtasks_for_query
from lms.djangoapps.instructor_task.tests.factories import Instructo... | [
"uuid.uuid4",
"unittest.mock.Mock",
"common.djangoapps.student.models.CourseEnrollment.objects.filter",
"unittest.mock.patch",
"lms.djangoapps.instructor_task.tests.factories.InstructorTaskFactory.create",
"lms.djangoapps.instructor_task.subtasks.queue_subtasks_for_query"
] | [((1158, 1291), 'lms.djangoapps.instructor_task.tests.factories.InstructorTaskFactory.create', 'InstructorTaskFactory.create', ([], {'course_id': 'self.course.id', 'task_id': 'task_id', 'task_key': '"""dummy_task_key"""', 'task_type': '"""bulk_course_email"""'}), "(course_id=self.course.id, task_id=task_id,\n task_k... |
import tensorflow as tf
from tensorflow.keras import layers
import tensorflow_hub as hub
import config
CHANNELS = 3
IMG_SIZE=224
class BeautyModel:
"""
This classes uses tensorflow hub api to download the pretrained model. There are multiple
models based on the type of the problem. Each model has its o... | [
"tensorflow_hub.KerasLayer",
"config.get_config",
"tensorflow.keras.layers.Dense"
] | [((403, 422), 'config.get_config', 'config.get_config', ([], {}), '()\n', (420, 422), False, 'import config\n'), ((499, 562), 'tensorflow_hub.KerasLayer', 'hub.KerasLayer', (['url'], {'input_shape': '(IMG_SIZE, IMG_SIZE, CHANNELS)'}), '(url, input_shape=(IMG_SIZE, IMG_SIZE, CHANNELS))\n', (513, 562), True, 'import tens... |
import os
import pandas as pd
from loguru import logger
logger.info('Import OK')
# define location parameters, assign number of frames for pre- and bleach portions
input_folder = f'results/example_diffuse-FRET/pixel_collection/'
output_folder = f'results/example_diffuse-FRET/summary_calculations/'
fret_channel = 3
... | [
"os.mkdir",
"pandas.pivot_table",
"pandas.read_csv",
"os.path.exists",
"loguru.logger.info",
"os.listdir"
] | [((58, 82), 'loguru.logger.info', 'logger.info', (['"""Import OK"""'], {}), "('Import OK')\n", (69, 82), False, 'from loguru import logger\n'), ((352, 381), 'os.path.exists', 'os.path.exists', (['output_folder'], {}), '(output_folder)\n', (366, 381), False, 'import os\n'), ((387, 410), 'os.mkdir', 'os.mkdir', (['output... |
#!/usr/bin/env python
from utils import utils
def part_one(day: int) -> None:
valid = 0
input_str = utils.get_input(day)
for line in input_str.split('\n'):
words = line.split()
if words and len(set(words)) == len(words):
valid += 1
print(valid)
def part_two(day: int) ->... | [
"utils.utils.get_input"
] | [((112, 132), 'utils.utils.get_input', 'utils.get_input', (['day'], {}), '(day)\n', (127, 132), False, 'from utils import utils\n'), ((358, 378), 'utils.utils.get_input', 'utils.get_input', (['day'], {}), '(day)\n', (373, 378), False, 'from utils import utils\n')] |
import time
import socket
import mouse
def mouseEventHandler(event):
msg = ''
if type(event).__name__ == 'MoveEvent': msg = f'move:{event.x},{event.y}'
elif type(event).__name__ == 'WheelEvent': msg = f'wheel:{event.delta}'
elif type(event).__name__ == 'ButtonEvent': msg = f'button {event.event_type}:{... | [
"mouse.hook",
"socket.socket",
"time.sleep"
] | [((544, 592), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_DGRAM'], {}), '(socket.AF_INET, socket.SOCK_DGRAM)\n', (557, 592), False, 'import socket\n'), ((602, 631), 'mouse.hook', 'mouse.hook', (['mouseEventHandler'], {}), '(mouseEventHandler)\n', (612, 631), False, 'import mouse\n'), ((707, 720),... |
import numpy as np
import pickle
import sys
import seaborn as sns
import pandas as pd
# import pkg_resources
# pkg_resources.require("scanpy==1.3")
import scanpy as sc
print(sc.__version__)
import os
import scipy.stats
import scipy.sparse
import matplotlib.pyplot as plt
import sklearn.preprocessing
from sklearn.metrics... | [
"pandas.DataFrame",
"scanpy.AnnData",
"sklearn.preprocessing.binarize",
"pandas.read_csv",
"numpy.asarray",
"pandas.isnull",
"sklearn.metrics.auc",
"gc.collect",
"pickle.load",
"numpy.array",
"multiprocessing.Pool",
"numpy.squeeze",
"numpy.round",
"os.path.join",
"numpy.concatenate"
] | [((703, 718), 'pandas.DataFrame', 'pd.DataFrame', (['X'], {}), '(X)\n', (715, 718), True, 'import pandas as pd\n'), ((1010, 1078), 'numpy.array', 'np.array', (['[[(1 if i == y else 0) for y in y_cluster] for i in index]'], {}), '([[(1 if i == y else 0) for y in y_cluster] for i in index])\n', (1018, 1078), True, 'impor... |
#!/usr/bin/env python
import rospy
import numpy as np
from std_msgs.msg import Float32
from week2.srv import angularvelocity, angularvelocityResponse
linvel = 0.1
angvel = None
def angular(req):
angvel = linvel/float(req.radius)
return angularvelocityResponse(ang_vel = (angvel))
rospy.init_node('ang_vel')
#... | [
"rospy.spin",
"rospy.Service",
"rospy.init_node",
"week2.srv.angularvelocityResponse"
] | [((292, 318), 'rospy.init_node', 'rospy.init_node', (['"""ang_vel"""'], {}), "('ang_vel')\n", (307, 318), False, 'import rospy\n'), ((380, 438), 'rospy.Service', 'rospy.Service', (['"""compute_ang_vel"""', 'angularvelocity', 'angular'], {}), "('compute_ang_vel', angularvelocity, angular)\n", (393, 438), False, 'import ... |
"""Faça um programa que mostre na tela uma contagem regressiva para o estouro de fogos de artificio,
indo de 10 até 0, com uma pausa de 1 segundo entre eles"""
import time
for tempo in range(10,-1,-1):
time.sleep(1)
print(tempo)
print('BOMMMM') | [
"time.sleep"
] | [((209, 222), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (219, 222), False, 'import time\n')] |
# Estimates of mixing time
# To-do's:
# * Estimate "baseline" mixing times from "brute-force simulations" (GHMC, Random-Walk Metropolis-Hastings, NUTS)
# * Make sure we cover all relevant modes
import pyemma
def estimate_mixing_time_tica(x):
"""Return an estimate of the mixing time of a stochastic process,
... | [
"pyemma.coordinates.tica"
] | [((956, 982), 'pyemma.coordinates.tica', 'pyemma.coordinates.tica', (['x'], {}), '(x)\n', (979, 982), False, 'import pyemma\n')] |
from itertools import accumulate
NOTE_NAMES = ('C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B')
class Scale(object):
def __init__(self, root, steps):
self.root = root
self.steps = steps
self.offsets = [0] + list(accumulate(steps))
def transpose(self, amount):
... | [
"itertools.accumulate"
] | [((260, 277), 'itertools.accumulate', 'accumulate', (['steps'], {}), '(steps)\n', (270, 277), False, 'from itertools import accumulate\n')] |
from django.contrib import admin
from .models import *
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import User
class PInline(admin.StackedInline):
model = Personnel
can_delete = False
verbose_name_plural = 'personnel'
... | [
"django.contrib.admin.site.register",
"django.contrib.admin.site.unregister"
] | [((429, 456), 'django.contrib.admin.site.unregister', 'admin.site.unregister', (['User'], {}), '(User)\n', (450, 456), False, 'from django.contrib import admin\n'), ((457, 493), 'django.contrib.admin.site.register', 'admin.site.register', (['User', 'UserAdmin'], {}), '(User, UserAdmin)\n', (476, 493), False, 'from djan... |
import os
import logging
from functools import lru_cache
from typing import Dict, Any
from storage import Junction, BLK, BLM, Signal, Disconnector, Railway, Track_Section, Control_Area, BLUV, BLEZ
DATASET_TYPES = ['PNL', 'OR', 'OPM', 'OPD', 'L', 'W', 'T', 'H', 'B', 'C', 'A', 'D', 'E', 'V', 'M', 'S', 'K', 'UV', 'Q',
... | [
"logging.info",
"functools.lru_cache",
"os.path.exists",
"os.remove"
] | [((1407, 1430), 'functools.lru_cache', 'lru_cache', ([], {'maxsize': '(1000)'}), '(maxsize=1000)\n', (1416, 1430), False, 'from functools import lru_cache\n'), ((1761, 1784), 'functools.lru_cache', 'lru_cache', ([], {'maxsize': '(1000)'}), '(maxsize=1000)\n', (1770, 1784), False, 'from functools import lru_cache\n'), (... |
from os import path
import sqlite3
BASE_DIR = path.dirname(path.realpath(__file__))
DATABASE = path.join(BASE_DIR, 'tpdb.db')
def close_commit(func):
def magic(*args):
conn = sqlite3.connect(DATABASE)
cur = conn.cursor()
sql = func(*args)
cur.execute(sql[0], sql[1])
conn.co... | [
"os.path.realpath",
"sqlite3.connect",
"os.path.join"
] | [((96, 126), 'os.path.join', 'path.join', (['BASE_DIR', '"""tpdb.db"""'], {}), "(BASE_DIR, 'tpdb.db')\n", (105, 126), False, 'from os import path\n'), ((60, 83), 'os.path.realpath', 'path.realpath', (['__file__'], {}), '(__file__)\n', (73, 83), False, 'from os import path\n'), ((804, 829), 'sqlite3.connect', 'sqlite3.c... |
import timeit
start = timeit.timeit()
#end = timeit.timeit()
#print end - start | [
"timeit.timeit"
] | [((23, 38), 'timeit.timeit', 'timeit.timeit', ([], {}), '()\n', (36, 38), False, 'import timeit\n')] |
from django.contrib.auth import views
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('', include('moodle.urls')),
path('admin/', admin.site.urls),
path('authentication/', include('authentication.urls')),
]
handler403 = 'moodle.views.fordbidden_view'
| [
"django.urls.path",
"django.urls.include"
] | [((169, 200), 'django.urls.path', 'path', (['"""admin/"""', 'admin.site.urls'], {}), "('admin/', admin.site.urls)\n", (173, 200), False, 'from django.urls import include, path\n'), ((140, 162), 'django.urls.include', 'include', (['"""moodle.urls"""'], {}), "('moodle.urls')\n", (147, 162), False, 'from django.urls impor... |
"""Tests for the log_normal_distribution module"""
# Copyright 2019 <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 requi... | [
"numpy.seterr",
"numpy.array",
"numpy.exp"
] | [((891, 913), 'numpy.seterr', 'np.seterr', ([], {'all': '"""raise"""'}), "(all='raise')\n", (900, 913), True, 'import numpy as np\n'), ((1107, 1132), 'numpy.array', 'np.array', (['[0.0, 1.0, 2.0]'], {}), '([0.0, 1.0, 2.0])\n', (1115, 1132), True, 'import numpy as np\n'), ((1145, 1170), 'numpy.array', 'np.array', (['[1.... |
"""
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import math
import torch
from .atom_update_block import AtomUpdateBlock
from .base_layers import Dense, ResidualLayer
from .efficient impor... | [
"math.sqrt"
] | [((4651, 4665), 'math.sqrt', 'math.sqrt', (['(2.0)'], {}), '(2.0)\n', (4660, 4665), False, 'import math\n'), ((9394, 9408), 'math.sqrt', 'math.sqrt', (['(2.0)'], {}), '(2.0)\n', (9403, 9408), False, 'import math\n')] |
# Generated by Django 2.0.2 on 2018-06-22 14:23
from django.db import migrations, models
import wagtail.core.fields
class Migration(migrations.Migration):
dependencies = [
('determinations', '0003_message_template_settings'),
]
operations = [
migrations.AlterField(
model_nam... | [
"django.db.models.IntegerField"
] | [((385, 518), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'choices': "[(0, 'Dismissed'), (1, 'Needs more info'), (2, 'Approved')]", 'default': '(1)', 'verbose_name': '"""Determination"""'}), "(choices=[(0, 'Dismissed'), (1, 'Needs more info'), (2,\n 'Approved')], default=1, verbose_name='Determinat... |
import os, fnmatch, sys
import dill as pickle
import scipy.interpolate as interp
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import bead_util as bu
import configuration as config
dir1 = '/data/20180618/bead1/tf_20180618/freq_comb_elec5_10V'
dir1 = '/data/20180618/bead1/discha... | [
"numpy.fft.rfft",
"matplotlib.pyplot.show",
"numpy.abs",
"matplotlib.pyplot.legend",
"bead_util.find_all_fnames",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.subplots",
"bead_util.DataFile"
] | [((470, 494), 'bead_util.find_all_fnames', 'bu.find_all_fnames', (['dir1'], {}), '(dir1)\n', (488, 494), True, 'import bead_util as bu\n'), ((524, 537), 'bead_util.DataFile', 'bu.DataFile', ([], {}), '()\n', (535, 537), True, 'import bead_util as bu\n'), ((622, 635), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], ... |
"""Software to receive sensor readings from data sources and post
them to a HTTP URL. Readings are cached if an Internet connection
is not available, or the the post fails for any reason.
Copyright (c) 2014, Alaska Housing Finance Corporation. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the... | [
"threading.Thread.__init__",
"logging.exception",
"logging.debug",
"json.dumps",
"time.sleep",
"time.time",
"sqlite_queue.SqliteReliableQueue",
"requests.post",
"urllib3.disable_warnings"
] | [((11743, 11810), 'urllib3.disable_warnings', 'urllib3.disable_warnings', (['urllib3.exceptions.InsecureRequestWarning'], {}), '(urllib3.exceptions.InsecureRequestWarning)\n', (11767, 11810), False, 'import urllib3\n'), ((12912, 12961), 'sqlite_queue.SqliteReliableQueue', 'sqlite_queue.SqliteReliableQueue', (['post_q_f... |
# -*- coding: utf-8 -*-
u"""
:copyright: Copyright (c) 2020 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
import time
import os
import yaml
import numpy as np
def record_time(func, time_list, *args, ... | [
"numpy.fft.rfft",
"numpy.sum",
"yaml.dump",
"time.time",
"os.path.splitext",
"os.path.split",
"os.path.join"
] | [((340, 351), 'time.time', 'time.time', ([], {}), '()\n', (349, 351), False, 'import time\n'), ((387, 398), 'time.time', 'time.time', ([], {}), '()\n', (396, 398), False, 'import time\n'), ((3357, 3380), 'os.path.split', 'os.path.split', (['filename'], {}), '(filename)\n', (3370, 3380), False, 'import os\n'), ((4885, 4... |
from setuptools import setup
setup(
name="PyQt5Singleton",
version="0.1",
author="<NAME>",
author_email="<EMAIL>",
description="A simple singleton implementation to work with PyQt5",
license="MIT",
url="https://github.com/jazzycamel/PyQt5Singleton",
packages=['PyQt5Singleton'],
inst... | [
"setuptools.setup"
] | [((30, 644), 'setuptools.setup', 'setup', ([], {'name': '"""PyQt5Singleton"""', 'version': '"""0.1"""', 'author': '"""<NAME>"""', 'author_email': '"""<EMAIL>"""', 'description': '"""A simple singleton implementation to work with PyQt5"""', 'license': '"""MIT"""', 'url': '"""https://github.com/jazzycamel/PyQt5Singleton"... |
import os
import numpy as np
ROOT_DIR = '/projects/katefgroup/language_grounding/scans/group_free_pred_bboxes' # 81
ROOT_DIR = '/projects/katefgroup/language_grounding/scans/group_free_pred_bboxes_03' # 101
with open('./referit3d/data/scannet/splits/official/v2/scannetv2_val.txt', "rb") as f:
bytelist = f.read()... | [
"os.path.join"
] | [((487, 538), 'os.path.join', 'os.path.join', (['ROOT_DIR', "(scan_id + '_pred_boxes.npy')"], {}), "(ROOT_DIR, scan_id + '_pred_boxes.npy')\n", (499, 538), False, 'import os\n')] |
import numpy as np
from abc import ABCMeta, abstractmethod
from ratcave.utils.observers import IterObservable
import itertools
from operator import setitem
from scipy.spatial.transform import Rotation as R
class Coordinates(IterObservable):
coords = {'x': 0, 'y': 1, 'z': 2}
def __init__(self, *args, **kwargs... | [
"numpy.radians",
"numpy.eye",
"numpy.degrees",
"scipy.spatial.transform.Rotation.from_euler",
"numpy.cross",
"numpy.identity",
"numpy.array",
"numpy.linalg.norm",
"scipy.spatial.transform.Rotation.from_matrix",
"scipy.spatial.transform.Rotation.from_quat",
"numpy.dot",
"operator.setitem",
"n... | [((6717, 6793), 'numpy.array', 'np.array', (['[[0, -vec[2], vec[1]], [vec[2], 0, -vec[0]], [-vec[1], vec[0], 0]]'], {}), '([[0, -vec[2], vec[1]], [vec[2], 0, -vec[0]], [-vec[1], vec[0], 0]])\n', (6725, 6793), True, 'import numpy as np\n'), ((7202, 7216), 'numpy.cross', 'np.cross', (['a', 'b'], {}), '(a, b)\n', (7210, 7... |
import backoff
import requests
class Ticker:
def __init__(self, session, pairs, apiTicker):
self.session = session
self.pairs = pairs
self.apiTicker = apiTicker
def gatePrice(self):
res = dict()
try:
for pair in self.pairs:
lastPrice = floa... | [
"backoff.on_exception"
] | [((592, 698), 'backoff.on_exception', 'backoff.on_exception', (['backoff.expo', '(requests.exceptions.ConnectionError, requests.exceptions.Timeout)'], {}), '(backoff.expo, (requests.exceptions.ConnectionError,\n requests.exceptions.Timeout))\n', (612, 698), False, 'import backoff\n')] |
# Author: <NAME>, https://users.soe.ucsc.edu/~cicekm/
#Dirty importing that allows the main author to switch environments easily
if '.' in __name__:
from Core.NeighborFolderimporter import *
from Reinforce_with_Keras.helpers import printProgressBar
else:
from NeighborFolderimporter import *
from helper... | [
"keras.initializers.RandomNormal",
"keras.backend.gradients",
"tensorflow.assign_sub",
"tensorflow.abs",
"tensorflow.reduce_sum",
"keras.losses.mean_absolute_error",
"tensorflow.convert_to_tensor",
"helpers.printProgressBar",
"tensorflow.reduce_mean",
"tensorflow.Session",
"tensorflow.stack",
... | [((653, 710), 'keras.initializers.RandomNormal', 'RandomNormal', ([], {'mean': 'model.outputs', 'stddev': 'sigma', 'seed': 'seed'}), '(mean=model.outputs, stddev=sigma, seed=seed)\n', (665, 710), False, 'from keras.initializers import RandomNormal\n'), ((1070, 1112), 'tensorflow.tile', 'tf.tile', (['targets', '[samples... |
import pickle
from learnhtml.extractor import HTMLExtractor
import webpage2html
from lxml import etree
with open('models/model-recipe.pkl', 'rb') as f:
model = pickle.load(f)
extractor = HTMLExtractor(model)
url = 'https://trinesmatblogg.no/recipe/kremet-kyllingform-med-paprika'
html = webpage2html.generate(url,... | [
"lxml.etree.tostring",
"webpage2html.generate",
"pickle.load",
"learnhtml.extractor.HTMLExtractor"
] | [((193, 213), 'learnhtml.extractor.HTMLExtractor', 'HTMLExtractor', (['model'], {}), '(model)\n', (206, 213), False, 'from learnhtml.extractor import HTMLExtractor\n'), ((294, 335), 'webpage2html.generate', 'webpage2html.generate', (['url'], {'verbose': '(False)'}), '(url, verbose=False)\n', (315, 335), False, 'import ... |
# -*- coding: utf-8 -*-
#
# profiler2: a Wi-Fi client capability analyzer
# Copyright 2020 <NAME>
#
# 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 not... | [
"scapy.all.conf.L2socket",
"os.getpid",
"os.getppid",
"scapy.all.RadioTap",
"time.time",
"scapy.all.Dot11ProbeResp",
"scapy.all.Dot11Beacon",
"scapy.all.sniff",
"scapy.all.Dot11",
"scapy.all.Dot11Auth",
"inspect.stack",
"sys.exit"
] | [((3435, 3475), 'scapy.all.conf.L2socket', 'scapyconf.L2socket', ([], {'iface': 'self.interface'}), '(iface=self.interface)\n', (3453, 3475), True, 'from scapy.all import conf as scapyconf\n'), ((4366, 4372), 'time.time', 'time', ([], {}), '()\n', (4370, 4372), False, 'from time import sleep, time\n'), ((6857, 6897), '... |
'''
This examples show how to train a basic Bi-Encoder for any BEIR dataset without any mined hard negatives or triplets.
The queries and passages are passed independently to the transformer network to produce fixed sized embeddings.
These embeddings can then be compared using cosine-similarity to find matching passag... | [
"beir.datasets.data_loader.GenericDataLoader",
"os.makedirs",
"sentence_transformers.models.Transformer",
"sentence_transformers.losses.MultipleNegativesRankingLoss",
"beir.LoggingHandler",
"pathlib.Path",
"beir.util.download_and_unzip",
"sentence_transformers.SentenceTransformer",
"beir.retrieval.t... | [((1464, 1501), 'beir.util.download_and_unzip', 'util.download_and_unzip', (['url', 'out_dir'], {}), '(url, out_dir)\n', (1487, 1501), False, 'from beir import util, LoggingHandler\n'), ((1944, 1994), 'sentence_transformers.models.Transformer', 'models.Transformer', (['model_name'], {'max_seq_length': '(350)'}), '(mode... |
from django.views import View
from django.http import JsonResponse
from bastion.utils.status_code import success, SuccessStatusCode, error, ErrorStatusCode
from bastion.utils.iam import Permission
from bastion.utils.esb_api import EsbApi
from bastion.models import HostModel, CredentialModel, StrategyAccessModel, Strat... | [
"bastion.models.HostModel.fetch_all",
"bastion.utils.iam.Permission",
"bastion.utils.status_code.success",
"bastion.models.SessionLogModel.fetch_all",
"bastion.utils.esb_api.EsbApi",
"bastion.models.CredentialModel.fetch_all",
"bastion.models.StrategyCommandModel.fetch_all",
"bastion.models.StrategyAc... | [((2017, 2030), 'bastion.utils.esb_api.EsbApi', 'EsbApi', (['token'], {}), '(token)\n', (2023, 2030), False, 'from bastion.utils.esb_api import EsbApi\n'), ((1413, 1469), 'bastion.utils.status_code.success', 'success', (['SuccessStatusCode.MESSAGE_GET_SUCCESS', 'end_data'], {}), '(SuccessStatusCode.MESSAGE_GET_SUCCESS,... |
import json
import os
import stat
import sys
import appdirs
if sys.version[0] == '2':
# pylint: disable=undefined-variable
ask_user = raw_input
else:
ask_user = input
TOKEN_PATH = os.path.join(appdirs.user_config_dir("slack-cli"), "slack_token")
TEAMS_PATH = os.path.join(appdirs.user_config_dir("slack-cl... | [
"json.dump",
"os.chmod",
"json.load",
"os.makedirs",
"os.path.dirname",
"os.path.exists",
"os.environ.get",
"appdirs.user_config_dir"
] | [((208, 244), 'appdirs.user_config_dir', 'appdirs.user_config_dir', (['"""slack-cli"""'], {}), "('slack-cli')\n", (231, 244), False, 'import appdirs\n'), ((287, 323), 'appdirs.user_config_dir', 'appdirs.user_config_dir', (['"""slack-cli"""'], {}), "('slack-cli')\n", (310, 323), False, 'import appdirs\n'), ((411, 440), ... |
import os
import logging
logging.basicConfig(level = logging.INFO, filename = 'train.log', filemode = 'w', format = "%(asctime)s [%(filename)s:%(lineno)d - %(levelname)s ] %(message)s")
import sys
sys.path.insert(0, "../../../")
import math
import numpy as np
# import torch
# from torch.utils.data import DataLoader
... | [
"tqdm.tqdm",
"oneflow.nn.functional.normalize",
"logging.basicConfig",
"libs.utils.utils.read_config",
"sys.path.insert",
"libs.components.loss.backward",
"libs.utils.config_parser.ArgParser",
"oneflow.max",
"libs.nnet.tdnn.XVector",
"oneflow.no_grad",
"libs.components.loss.item"
] | [((25, 186), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'filename': '"""train.log"""', 'filemode': '"""w"""', 'format': '"""%(asctime)s [%(filename)s:%(lineno)d - %(levelname)s ] %(message)s"""'}), "(level=logging.INFO, filename='train.log', filemode='w',\n format='%(asctime)s [%(fi... |
from google.cloud import secretmanager
def get_secret(project_id, secret_id, version_id='latest'):
client = secretmanager.SecretManagerServiceClient()
name = f"projects/{project_id}/secrets/{secret_id}/versions/{version_id}"
response = client.access_secret_version(request={'name': name})
payload = resp... | [
"google.cloud.secretmanager.SecretManagerServiceClient"
] | [((113, 155), 'google.cloud.secretmanager.SecretManagerServiceClient', 'secretmanager.SecretManagerServiceClient', ([], {}), '()\n', (153, 155), False, 'from google.cloud import secretmanager\n')] |
import unittest
from unittest.mock import patch
from tmc import points
from tmc.utils import load_module, reload_module, get_stdout
from functools import reduce
from random import randint
exercise = 'src.gift_tax_calculator'
@points('2.gift_tax_calculator')
class GiftTaxCalculatorTest(unittest.TestCase):
@classm... | [
"unittest.main",
"tmc.utils.get_stdout",
"random.randint",
"unittest.mock.patch",
"tmc.utils.reload_module",
"tmc.points",
"tmc.utils.load_module"
] | [((229, 260), 'tmc.points', 'points', (['"""2.gift_tax_calculator"""'], {}), "('2.gift_tax_calculator')\n", (235, 260), False, 'from tmc import points\n'), ((2729, 2744), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2742, 2744), False, 'import unittest\n'), ((364, 405), 'unittest.mock.patch', 'patch', (['"""bui... |
"""
The defaultdict tool is a container in the collections class of Python. It's similar to the usual dictionary (dict) container, but the only difference is that a defaultdict will have a default value if that key has not been set yet. If you didn't use a defaultdict you'd have to check to see if that key exists, and ... | [
"collections.defaultdict"
] | [((2076, 2105), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (2099, 2105), False, 'import collections\n')] |
# references:
# https://github.com/weigq/3d_pose_baseline_pytorch/blob/master/src/model.py
# https://github.com/una-dinosauria/3d-pose-baseline/blob/master/src/linear_model.py
import torch.nn as nn
def init_weights(module):
"""Initialize weights of the baseline linear model.
Our initialization scheme is dif... | [
"torch.nn.Dropout",
"torch.nn.ReLU",
"torch.nn.init.kaiming_normal_",
"torch.nn.ModuleList",
"torch.nn.BatchNorm1d",
"torch.nn.Linear"
] | [((738, 817), 'torch.nn.init.kaiming_normal_', 'nn.init.kaiming_normal_', (['module.weight.data'], {'mode': '"""fan_in"""', 'nonlinearity': '"""relu"""'}), "(module.weight.data, mode='fan_in', nonlinearity='relu')\n", (761, 817), True, 'import torch.nn as nn\n'), ((1258, 1279), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplac... |
# Generated by Django 2.2.4 on 2019-10-29 13:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0022_auto_20191029_0000'),
]
operations = [
migrations.AlterField(
model_name='timer',
name='start',
... | [
"django.db.models.DateTimeField"
] | [((331, 401), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'blank': '(True)', 'null': '(True)', 'verbose_name': '"""Start time"""'}), "(blank=True, null=True, verbose_name='Start time')\n", (351, 401), False, 'from django.db import migrations, models\n')] |
# coding: utf-8
__author__ = 'Miso'
from db.dbInit import db
class UserTime(db.Model):
__tablename__ = 'user_time'
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.ForeignKey('user.id', ondelete='CASCADE', onupdate='CASCADE'), index=True)
goalTime = db.Column(db.Float)
nonGoalT... | [
"db.dbInit.db.Column",
"db.dbInit.db.ForeignKey"
] | [((131, 170), 'db.dbInit.db.Column', 'db.Column', (['db.Integer'], {'primary_key': '(True)'}), '(db.Integer, primary_key=True)\n', (140, 170), False, 'from db.dbInit import db\n'), ((288, 307), 'db.dbInit.db.Column', 'db.Column', (['db.Float'], {}), '(db.Float)\n', (297, 307), False, 'from db.dbInit import db\n'), ((32... |