code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
from calendar import monthrange
from datetime import date
from flask import abort, Blueprint, flash, Markup, redirect, render_template, request, session, url_for
from sqlalchemy.orm.exc import NoResultFound
from app import app, db
from app.users.decorators import login_required
from .forms import TicketSearchForm, Ti... | [
"flask.render_template",
"flask.request.args.get",
"app.db.session.commit",
"flask.flash",
"app.db.session.query",
"flask.url_for",
"calendar.monthrange",
"datetime.date",
"flask.Markup",
"flask.abort",
"datetime.date.today",
"flask.Blueprint"
] | [((375, 428), 'flask.Blueprint', 'Blueprint', (['"""tickets"""', '__name__'], {'url_prefix': '"""/tickets"""'}), "('tickets', __name__, url_prefix='/tickets')\n", (384, 428), False, 'from flask import abort, Blueprint, flash, Markup, redirect, render_template, request, session, url_for\n'), ((890, 1010), 'flask.render_... |
# Copyright 2014 Open Source Robotics Foundation, 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... | [
"os.path.exists",
"catkin_tools.execution.stages.FunctionStage",
"os.path.join",
"os.path.isfile",
"catkin_tools.execution.stages.CommandStage",
"catkin_tools.argument_parsing.handle_make_arguments",
"catkin_tools.common.mkdir_p"
] | [((1357, 1407), 'os.path.join', 'os.path.join', (['prefix', '"""etc"""', '"""catkin"""', '"""profile.d"""'], {}), "(prefix, 'etc', 'catkin', 'profile.d')\n", (1369, 1407), False, 'import os\n'), ((1432, 1477), 'os.path.join', 'os.path.join', (['ctr_nuke_path', '"""06-ctr-nuke.sh"""'], {}), "(ctr_nuke_path, '06-ctr-nuke... |
"""
Read-only services for data on the types of Transactions supported by CloudCIX
"""
# libs
from cloudcix_rest.exceptions import Http404
from cloudcix_rest.views import APIView
from django.conf import settings
from rest_framework.permissions import BasePermission
from rest_framework.request import Request
from rest_... | [
"membership.serializers.TransactionTypeSerializer",
"membership.models.TransactionType.objects.filter",
"membership.models.TransactionType.objects.get",
"rest_framework.response.Response",
"membership.controllers.TransactionTypeListController",
"cloudcix_rest.exceptions.Http404"
] | [((3145, 3195), 'rest_framework.response.Response', 'Response', (["{'content': data, '_metadata': metadata}"], {}), "({'content': data, '_metadata': metadata})\n", (3153, 3195), False, 'from rest_framework.response import Response\n'), ((4333, 4360), 'rest_framework.response.Response', 'Response', (["{'content': data}"... |
"""
This file contains basic tests for the core app.
"""
from django.core.urlresolvers import reverse
from django.utils import timezone
from datetime import timedelta
from calendar import month_name
import dateutil.parser
from .models import EventOccurrence, Event, TemporaryRegistration
from .constants import getCon... | [
"django.utils.timezone.now",
"datetime.timedelta",
"django.core.urlresolvers.reverse"
] | [((842, 865), 'django.core.urlresolvers.reverse', 'reverse', (['"""registration"""'], {}), "('registration')\n", (849, 865), False, 'from django.core.urlresolvers import reverse\n'), ((1266, 1298), 'django.core.urlresolvers.reverse', 'reverse', (['"""admin:core_series_add"""'], {}), "('admin:core_series_add')\n", (1273... |
import re
from typing import List
# class MyList():
#
# my_list: List
#
# def __init__(self):
def sortl_list_of_strings_alphanumerically(list_of_strings: List[str]) -> list:
convert = lambda text: float(text) if text.isdigit() else text
alphanum = lambda key: [convert(c) for c in re.split(r'([-+]?[... | [
"re.split"
] | [((302, 342), 're.split', 're.split', (['"""([-+]?[0-9]*\\\\.?[0-9]*)"""', 'key'], {}), "('([-+]?[0-9]*\\\\.?[0-9]*)', key)\n", (310, 342), False, 'import re\n')] |
import os
import shutil
import subprocess
import pytest
from buildstream.testing import Repo
from buildstream.testing._utils.site import GIT, GIT_ENV, HAVE_GIT
class Git(Repo):
def __init__(self, directory, subdir="repo"):
if not HAVE_GIT:
pytest.skip("git is not available")
self.su... | [
"subprocess.run",
"os.path.join",
"os.environ.copy",
"os.path.basename",
"shutil.copy",
"pytest.skip"
] | [((399, 416), 'os.environ.copy', 'os.environ.copy', ([], {}), '()\n', (414, 416), False, 'import os\n'), ((729, 759), 'subprocess.run', 'subprocess.run', (['argv'], {}), '(argv, **kwargs)\n', (743, 759), False, 'import subprocess\n'), ((1393, 1425), 'shutil.copy', 'shutil.copy', (['filename', 'self.repo'], {}), '(filen... |
#!/usr/bin/env python
# Following along with: https://www.learnopencv.com/pytorch-for-beginners-semantic-segmentation-using-torchvision/
# Generated by https://traingenerator.jrieke.com/
# Before running, install required packages:
# pip install numpy torch torchvision pytorch-ignite
from pathlib import Path
import ... | [
"zipfile.ZipFile",
"torchvision.models.segmentation.fcn_resnet101",
"torch.utils.data.DataLoader",
"numpy.array",
"torch.cuda.is_available",
"matplotlib.pyplot.imshow",
"pathlib.Path",
"urllib.request.urlretrieve",
"torchvision.datasets.ImageFolder",
"numpy.stack",
"torchvision.transforms.ToTens... | [((1198, 1223), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1221, 1223), False, 'import torch\n'), ((1440, 1454), 'pathlib.Path', 'Path', (['DATA_DIR'], {}), '(DATA_DIR)\n', (1444, 1454), False, 'from pathlib import Path\n'), ((2147, 2194), 'torchvision.datasets.ImageFolder', 'datasets.Imag... |
#!/usr/bin/env python
from __future__ import print_function
import os
import subprocess
import sys
from peyutil import (read_as_json,
write_as_json)
from peyotl import (read_all_otifacts,
filter_otifacts_by_type,
partition_otifacts_by_root_element, )
from t... | [
"logging.getLogger",
"peyotl.read_all_otifacts",
"taxalotl.tax_partition.get_taxonomies_for_dir",
"taxalotl.cmds.partitions.get_part_dir_from_part_name",
"peyutil.read_as_json",
"taxalotl.cmds.partitions.do_partition",
"peyotl.filter_otifacts_by_type",
"os.walk",
"taxalotl.cmds.analyze_update.analyz... | [((1339, 1366), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1356, 1366), False, 'import logging\n'), ((1706, 1763), 'taxalotl.cmds.align.align_resource', 'align_resource', (['taxalotl_config', 'ott_res', 'res', 'level_list'], {}), '(taxalotl_config, ott_res, res, level_list)\n', (1720... |
from rest_framework.test import APITestCase
from api.v1.mixins.testcase import VulnmanAPITestCaseMixin
from apps.assets import models
class AgentHostViewSetTestCase(APITestCase, VulnmanAPITestCaseMixin):
def setUp(self):
self.init_mixin()
def test_createview(self):
token = self.create_project... | [
"apps.assets.models.Host.objects.count"
] | [((711, 738), 'apps.assets.models.Host.objects.count', 'models.Host.objects.count', ([], {}), '()\n', (736, 738), False, 'from apps.assets import models\n'), ((932, 959), 'apps.assets.models.Host.objects.count', 'models.Host.objects.count', ([], {}), '()\n', (957, 959), False, 'from apps.assets import models\n')] |
import math
import fractions
import functools
def lcm(a,b):
return a // fractions.gcd(a,b) * b
k = int(input())
m = functools.reduce(lcm, range(1,k+1), 1)
n = 2*m
h = [0] * (n+1)
qs = range(1,k+1)
for a in qs:
for x in range(-m,m+1):
y = 10*a*x
if abs(y) <= 10*m:
h[m+x] = y
hmin... | [
"fractions.gcd"
] | [((77, 96), 'fractions.gcd', 'fractions.gcd', (['a', 'b'], {}), '(a, b)\n', (90, 96), False, 'import fractions\n')] |
'''
Description: multi object tracking
Author: <EMAIL>
FilePath: /obj_evaluation/measure_judge/common/mot.py
Date: 2021-09-24 19:37:53
'''
import numpy as np
class Munkres:
def __init__(self, cost: list, inv_eps=1000) -> None:
"""[summary]
https://brc2.com/the-algorithm-workshop/
Args:
... | [
"numpy.array",
"numpy.sum",
"numpy.zeros"
] | [((898, 930), 'numpy.zeros', 'np.zeros', (['(self.rows, self.cols)'], {}), '((self.rows, self.cols))\n', (906, 930), True, 'import numpy as np\n'), ((956, 975), 'numpy.zeros', 'np.zeros', (['self.rows'], {}), '(self.rows)\n', (964, 975), True, 'import numpy as np\n'), ((1001, 1020), 'numpy.zeros', 'np.zeros', (['self.c... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "<NAME>"
__doc__ = r"""
Created on 27-10-2020
"""
import random
import pygame
pygame.init()
display_width = 800
display_height = 600
game_display = pygame.display.set_mode((display_width, display_height))
# icon = pygame.image.load... | [
"pygame.draw.circle",
"random.randint",
"pygame.mouse.get_pressed",
"pygame.init",
"pygame.draw.line",
"random.randrange",
"pygame.quit",
"pygame.display.set_mode",
"pygame.event.get",
"pygame.mouse.get_pos",
"pygame.draw.rect",
"pygame.time.Clock",
"pygame.display.update",
"pygame.font.Sy... | [((165, 178), 'pygame.init', 'pygame.init', ([], {}), '()\n', (176, 178), False, 'import pygame\n'), ((237, 293), 'pygame.display.set_mode', 'pygame.display.set_mode', (['(display_width, display_height)'], {}), '((display_width, display_height))\n', (260, 293), False, 'import pygame\n'), ((600, 619), 'pygame.time.Clock... |
from __future__ import absolute_import, print_function
import pytest
def test_error_handler(flask_app):
# disable testing so we use our error handler
flask_app.testing = False
c = flask_app.test_client()
rv = c.get('/test/error')
print(rv.data)
assert "Caught unhandled exception:" in rv.da... | [
"pytest.vcr.use_cassette"
] | [((326, 351), 'pytest.vcr.use_cassette', 'pytest.vcr.use_cassette', ([], {}), '()\n', (349, 351), False, 'import pytest\n'), ((664, 689), 'pytest.vcr.use_cassette', 'pytest.vcr.use_cassette', ([], {}), '()\n', (687, 689), False, 'import pytest\n'), ((1151, 1176), 'pytest.vcr.use_cassette', 'pytest.vcr.use_cassette', ([... |
"""
Module: utils.c3.c3s1_post_processing
Author: <NAME>
License: The MIT license, https://opensource.org/licenses/MIT
This file is part of the FMP Notebooks (https://www.audiolabs-erlangen.de/FMP)
"""
import numpy as np
from scipy import signal
from numba import jit
@jit(nopython=True)
def log_compre... | [
"numpy.abs",
"scipy.signal.medfilt2d",
"scipy.signal.convolve",
"numpy.sqrt",
"numpy.ones",
"numpy.log",
"numpy.sum",
"numpy.zeros",
"numba.jit",
"scipy.signal.get_window"
] | [((286, 304), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (289, 304), False, 'from numba import jit\n'), ((626, 644), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (629, 644), False, 'from numba import jit\n'), ((598, 619), 'numpy.log', 'np.log', (['(1 + gamma * v)'],... |
import pytest
from devinstaller_core import dependency_graph as m
from devinstaller_core import exception as e
@pytest.fixture
def mock_modules_list():
"""Standard module list without any issues"""
return [
{"name": "foo", "module_type": "app", "supported_platforms": ["macos"]},
{"name": "ba... | [
"devinstaller_core.dependency_graph.ModuleApp",
"pytest.lazy_fixture",
"pytest.raises",
"devinstaller_core.dependency_graph.BlockPlatform",
"devinstaller_core.dependency_graph.DependencyGraph"
] | [((2286, 2303), 'devinstaller_core.dependency_graph.BlockPlatform', 'm.BlockPlatform', ([], {}), '()\n', (2301, 2303), True, 'from devinstaller_core import dependency_graph as m\n'), ((3006, 3082), 'devinstaller_core.dependency_graph.DependencyGraph', 'm.DependencyGraph', ([], {'module_list': 'modules_list', 'platform_... |
# Copyright (c) 2021, Frappe Technologies and contributors
# For license information, please see license.txt
from json.encoder import JSONEncoder
import datetime
import requests
from datetime import timedelta
from dateutil import parser
import frappe
from frappe import _
from frappe.model.document import Document
fro... | [
"dateutil.parser.parse",
"frappe.get_value",
"erpnext_argentina.pagos360.pago360_log_error",
"frappe.throw",
"frappe.utils.validate_email_address",
"frappe._",
"datetime.timedelta",
"frappe.utils.call_hook_method",
"frappe.integrations.utils.get_payment_gateway_controller",
"frappe.get_doc",
"fr... | [((869, 903), 'frappe.integrations.utils.create_payment_gateway', 'create_payment_gateway', (['"""Pagos360"""'], {}), "('Pagos360')\n", (891, 903), False, 'from frappe.integrations.utils import create_payment_gateway, get_payment_gateway_controller\n'), ((912, 975), 'frappe.utils.call_hook_method', 'call_hook_method', ... |
# <NAME>
# starting from from adafruit example
# https://learn.adafruit.com/welcome-to-circuitpython/creating-and-editing-code
#
import board
import digitalio
import time
led = digitalio.DigitalInOut(board.LED)
led.direction = digitalio.Direction.OUTPUT
# Choose a brightness between 0 and 1
brightness = .01
# Time pe... | [
"digitalio.DigitalInOut",
"time.sleep"
] | [((178, 211), 'digitalio.DigitalInOut', 'digitalio.DigitalInOut', (['board.LED'], {}), '(board.LED)\n', (200, 211), False, 'import digitalio\n'), ((442, 458), 'time.sleep', 'time.sleep', (['T_on'], {}), '(T_on)\n', (452, 458), False, 'import time\n'), ((485, 502), 'time.sleep', 'time.sleep', (['T_off'], {}), '(T_off)\n... |
import torch
from torch.autograd import Variable
from ptstat.core import RandomVariable, _to_v
# TODO: Implement Uniform(a, b) constructor.
class Uniform(RandomVariable):
"""
Uniform(0, 1) iid rv.
"""
def __init__(self, size, cuda=False):
super(Uniform, self).__init__()
assert len(size... | [
"torch.FloatTensor",
"ptstat.core._to_v"
] | [((747, 784), 'ptstat.core._to_v', '_to_v', (['(0)', 'self._p_size[0]', 'self._cuda'], {}), '(0, self._p_size[0], self._cuda)\n', (752, 784), False, 'from ptstat.core import RandomVariable, _to_v\n'), ((597, 629), 'torch.FloatTensor', 'torch.FloatTensor', (['*self._p_size'], {}), '(*self._p_size)\n', (614, 629), False,... |
from ir_sim.world import obs_circle
from math import pi, cos, sin
import numpy as np
from collections import namedtuple
from ir_sim.util import collision_cir_cir, collision_cir_matrix, collision_cir_seg, reciprocal_vel_obs
class env_obs_cir:
def __init__(self, obs_cir_class=obs_circle, obs_model='static', obs_cir_... | [
"collections.namedtuple",
"ir_sim.util.collision_cir_matrix",
"numpy.linalg.norm",
"ir_sim.util.reciprocal_vel_obs",
"math.cos",
"numpy.array",
"ir_sim.util.collision_cir_seg",
"numpy.random.uniform",
"math.sin"
] | [((5447, 5476), 'collections.namedtuple', 'namedtuple', (['"""circle"""', '"""x y r"""'], {}), "('circle', 'x y r')\n", (5457, 5476), False, 'from collections import namedtuple\n'), ((5493, 5519), 'collections.namedtuple', 'namedtuple', (['"""point"""', '"""x y"""'], {}), "('point', 'x y')\n", (5503, 5519), False, 'fro... |
'''
Module for running scenario tasks
'''
import sys
import os
from logging import getLogger
from collections import namedtuple
from argparse import ArgumentParser
from shared.startup import StartupWrapper
from shared.util import publishedexe
from shared import const
from performance.logger import setup_loggers
req... | [
"logging.getLogger",
"shared.util.publishedexe",
"argparse.ArgumentParser",
"os.path.join",
"performance.logger.setup_loggers",
"sys.exit",
"shared.startup.StartupWrapper"
] | [((1340, 1359), 'performance.logger.setup_loggers', 'setup_loggers', (['(True)'], {}), '(True)\n', (1353, 1359), False, 'from performance.logger import setup_loggers\n'), ((1467, 1483), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (1481, 1483), False, 'from argparse import ArgumentParser\n'), ((2014, ... |
from django.test import TestCase, Client
import pprint
import requests
# Create your tests here.
class Test(TestCase):
localhost = 'localhost'
port = '8000'
cookie = None
def test_login(self):
# c = Client(HTTP_USER_AGENT='Mozilla/5.0')
# response = c.post('/api/user/login', {'usernam... | [
"requests.post",
"requests.get"
] | [((491, 582), 'requests.post', 'requests.post', (['f"""http://{self.localhost}:{self.port}/api/user/auth/login"""'], {'json': 'payload'}), "(f'http://{self.localhost}:{self.port}/api/user/auth/login',\n json=payload)\n", (504, 582), False, 'import requests\n'), ((788, 887), 'requests.post', 'requests.post', (['f"""h... |
#!/usr/bin/env python
import cv2
from matplotlib.widgets import Cursor
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import subprocess
import random
import matplotlib.patches as patches
coefficient = 1.5 # modify for your resolution, e.g. 1280 to 1920 is x1.5, 1920 to 1920 is x1.0
click_data = []
... | [
"matplotlib.patches.Rectangle",
"random.randint",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.gcf",
"matplotlib.image.imread",
"cv2.Canny",
"matplotlib.pyplot.close",
"cv2.minMaxLoc",
"matplotlib.widgets.Cursor",
"random.random",
"matplotlib.pyplot.pause",
"cv2.resize",
"cv2.matchTemplate",
... | [((2944, 2958), 'matplotlib.pyplot.pause', 'plt.pause', (['(1.2)'], {}), '(1.2)\n', (2953, 2958), True, 'import matplotlib.pyplot as plt\n'), ((2963, 2974), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (2972, 2974), True, 'import matplotlib.pyplot as plt\n'), ((4477, 4488), 'matplotlib.pyplot.close', 'plt.... |
# coding=utf-8
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distr... | [
"jax_md.space.map_neighbor",
"jax_md.space.periodic",
"absl.logging.info",
"optax.apply_updates",
"tensorflow_datasets.as_numpy",
"jax.numpy.mean",
"jax.random.split",
"optax.adam",
"jax.random.PRNGKey",
"jax_md.nn.GraphTuple",
"haiku.initializers.VarianceScaling",
"optax.clip_by_global_norm",... | [((760, 795), 'absl.logging.set_verbosity', 'logging.set_verbosity', (['logging.INFO'], {}), '(logging.INFO)\n', (781, 795), False, 'from absl import logging\n'), ((1362, 1379), 'jax.random.PRNGKey', 'random.PRNGKey', (['(0)'], {}), '(0)\n', (1376, 1379), False, 'from jax import random, vmap, jit, grad\n'), ((1748, 178... |
"""
Window [DiamondQuest]
Handles the game window and caches primary surfaces.
Author(s): <NAME>, <NAME>, <NAME>
"""
# LICENSE (BSD-3-Clause)
# Copyright (c) 2020 MousePaw Media.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that ... | [
"pygame.Surface",
"pygame.display.flip",
"pygame.display.get_surface",
"diamondquest.common.Resolution.get_primary",
"diamondquest.common.mode.ModeType.render_order",
"pygame.display.set_caption",
"diamondquest.common.Resolution.set_primary"
] | [((2384, 2418), 'diamondquest.common.Resolution.set_primary', 'Resolution.set_primary', (['resolution'], {}), '(resolution)\n', (2406, 2418), False, 'from diamondquest.common import Resolution\n'), ((3590, 3633), 'pygame.display.set_caption', 'pygame.display.set_caption', (['constants.TITLE'], {}), '(constants.TITLE)\n... |
import pip_setup
pip_setup.install("moviepy")
pip_setup.install("pygame")
import Menu
import pygame
from moviepy.editor import *
import random
from Settings import *
from Sprites import *
from Menu import *
import time
import numpy as np
class GAME :
def __init__(self):
#GAME ~initiali... | [
"random.randint",
"pygame.init",
"pygame.sprite.spritecollide",
"pygame.event.get",
"pygame.time.get_ticks",
"pygame.display.set_mode",
"pygame.sprite.Group",
"pygame.display.flip",
"pygame.sprite.collide_rect",
"random.randrange",
"pygame.time.Clock",
"pygame.mixer.Sound",
"Menu.set_music",... | [((20, 48), 'pip_setup.install', 'pip_setup.install', (['"""moviepy"""'], {}), "('moviepy')\n", (37, 48), False, 'import pip_setup\n'), ((50, 77), 'pip_setup.install', 'pip_setup.install', (['"""pygame"""'], {}), "('pygame')\n", (67, 77), False, 'import pip_setup\n'), ((24686, 24719), 'pygame.display.set_caption', 'pyg... |
import sys
import os
try:
import configparser
except:
import ConfigParser as configparser
import logging
# import json
import datetime
import argparse
import csv
import boto3
from get_solr_json import get_solr_json
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
def get_solr_docs(solr_ur... | [
"logging.getLogger",
"logging.StreamHandler",
"argparse.ArgumentParser",
"ConfigParser.SafeConfigParser",
"get_solr_json.get_solr_json",
"csv.writer",
"boto3.resource",
"datetime.date.today"
] | [((234, 261), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (251, 261), False, 'import logging\n'), ((710, 757), 'get_solr_json.get_solr_json', 'get_solr_json', (['solr_url', 'query'], {'api_key': 'api_key'}), '(solr_url, query, api_key=api_key)\n', (723, 757), False, 'from get_solr_json... |
from Crawl import Crawl
def deepCrawl(crawled) :
tmp = []
for each in crawled :
crawl = Crawl(each['url'])
crawl.filter()
tmp.extend(crawl.get())
return tmp
def deleteOverlap(crawled) :
for i in range(0, len(crawled)) :
for j in range(0, len(crawled)) :
if i... | [
"Crawl.Crawl"
] | [((105, 123), 'Crawl.Crawl', 'Crawl', (["each['url']"], {}), "(each['url'])\n", (110, 123), False, 'from Crawl import Crawl\n')] |
import unittest
"""
Leetcode(https://leetcode.com/problems/subarray-sum-equals-k)
"""
def subarraySum(nums, k):
n = len(nums)
preSum = [0] * n
for i in range(n):
if i == 0:
preSum[i] = nums[i]
else:
preSum[i] = preSum[i - 1] + nums[i]
print(preSum)
S = {}... | [
"unittest.main"
] | [((1113, 1128), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1126, 1128), False, 'import unittest\n')] |
from unittest.mock import MagicMock
import pytest
from polecat.db.sql.expression.array_agg import ArrayAgg
from polecat.db.sql.sql import Sql
from .conftest import SqlTermTester
def test_to_sql():
term = ArrayAgg('test')
sql = Sql(term.to_sql())
assert str(sql) == 'array_agg("test")'
@pytest.mark.para... | [
"polecat.db.sql.expression.array_agg.ArrayAgg",
"pytest.mark.parametrize",
"unittest.mock.MagicMock"
] | [((304, 365), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""test_func"""', 'SqlTermTester.ALL_TESTS'], {}), "('test_func', SqlTermTester.ALL_TESTS)\n", (327, 365), False, 'import pytest\n'), ((212, 228), 'polecat.db.sql.expression.array_agg.ArrayAgg', 'ArrayAgg', (['"""test"""'], {}), "('test')\n", (220, ... |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('adverts', '0006_auto_20150303_0009'),
]
operations = [
migrations.AlterField(
model_name='adchannel',
name='ad_formats',
field=models.ManyToManyField(
... | [
"django.db.models.ManyToManyField"
] | [((294, 373), 'django.db.models.ManyToManyField', 'models.ManyToManyField', ([], {'to': '"""adverts.AdFormat"""', 'help_text': '"""size and shape of ad"""'}), "(to='adverts.AdFormat', help_text='size and shape of ad')\n", (316, 373), False, 'from django.db import migrations, models\n'), ((530, 627), 'django.db.models.M... |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
from modeling.sync_batchnorm.batchnorm import SynchronizedBatchNorm2d
from modeling.backbone.resnext import ResNeXt101
class DAF(nn.Module):
def __init__(self):
super(DAF, self).__init__(... | [
"torch.nn.Sigmoid",
"modeling.backbone.resnext.ResNeXt101",
"torch.abs",
"torch.nn.BatchNorm2d",
"torch.nn.Conv2d",
"torch.nn.PReLU",
"torch.cat",
"torch.nn.MaxPool2d",
"torch.rand"
] | [((3525, 3551), 'torch.rand', 'torch.rand', (['(1)', '(3)', '(512)', '(512)'], {}), '(1, 3, 512, 512)\n', (3535, 3551), False, 'import torch\n'), ((345, 357), 'modeling.backbone.resnext.ResNeXt101', 'ResNeXt101', ([], {}), '()\n', (355, 357), False, 'from modeling.backbone.resnext import ResNeXt101\n'), ((1209, 1241), ... |
#!/usr/bin/env python
# This script generates pseudo-label QREL files from a previously generated
import argparse
import sys
sys.path.append('.')
from scripts.common_eval import read_run_dict, write_qrels, QrelEntry, get_sorted_scores_from_score_dict
parser = argparse.ArgumentParser('Generate pseudo-QRELs from a r... | [
"scripts.common_eval.get_sorted_scores_from_score_dict",
"scripts.common_eval.write_qrels",
"argparse.ArgumentParser",
"scripts.common_eval.QrelEntry",
"scripts.common_eval.read_run_dict",
"sys.path.append"
] | [((128, 148), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (143, 148), False, 'import sys\n'), ((265, 324), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""Generate pseudo-QRELs from a run"""'], {}), "('Generate pseudo-QRELs from a run')\n", (288, 324), False, 'import argparse\n'), ((... |
import tensorflow as tf
import numpy as np
from utils.environ import env
from utils.helpers import *
from utils.mlogging import mlogging
from utils.model_config import ModelConfig
from utils.layers import Dense, build_mlp
from utils.word_embeddings import WordHashing
from utils.vsm import vsm_search
from dataclasse... | [
"tensorflow.equal",
"tensorflow.shape",
"tensorflow.sparse_placeholder",
"tensorflow.nn.softmax",
"tensorflow.Summary.Value",
"tensorflow.while_loop",
"tensorflow.reduce_mean",
"utils.vsm.vsm_search",
"math.exp",
"tensorflow.tuple",
"tensorflow.set_random_seed",
"tensorflow.GPUOptions",
"ten... | [((10428, 10489), 'tensorflow.GPUOptions', 'tf.GPUOptions', ([], {'per_process_gpu_memory_fraction': 'gpu_limit_frac'}), '(per_process_gpu_memory_fraction=gpu_limit_frac)\n', (10441, 10489), True, 'import tensorflow as tf\n'), ((10507, 10546), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'gpu_options': 'gpu_option... |
# coding: utf8
from __future__ import unicode_literals
import platform
from pathlib import Path
from ..compat import unicode_
from .. import about
from .. import util
#import spacy
import spacy
def nlp(sntnc=""):
# lets parse a static sentence
#sntnc = "At this time tomorrow, we will see if a summer crush c... | [
"spacy.load"
] | [((481, 497), 'spacy.load', 'spacy.load', (['"""en"""'], {}), "('en')\n", (491, 497), False, 'import spacy\n')] |
from django import forms
class MispConfigForm(forms.Form):
error_css_class = 'error'
required_css_class = 'required'
misp_url = forms.CharField(required=True,
label="MISP URL",
initial='',
widget=forms.TextInput(),... | [
"django.forms.TextInput"
] | [((302, 319), 'django.forms.TextInput', 'forms.TextInput', ([], {}), '()\n', (317, 319), False, 'from django import forms\n'), ((577, 594), 'django.forms.TextInput', 'forms.TextInput', ([], {}), '()\n', (592, 594), False, 'from django import forms\n'), ((892, 909), 'django.forms.TextInput', 'forms.TextInput', ([], {}),... |
from math import sqrt, atan
import pytest
from pytest import approx
import ts2vg
import numpy as np
@pytest.fixture
def empty_ts():
return []
@pytest.fixture
def sample_ts():
return [3.0, 4.0, 2.0, 1.0]
def test_basic(sample_ts):
out_got = ts2vg.NaturalVG().build(sample_ts).edges
out_truth = [
... | [
"pytest.approx",
"ts2vg.NaturalVG",
"math.sqrt",
"pytest.raises",
"math.atan",
"numpy.testing.assert_array_equal"
] | [((8103, 8152), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['out_got', 'out_truth'], {}), '(out_got, out_truth)\n', (8132, 8152), True, 'import numpy as np\n'), ((8276, 8325), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['out_got', 'out_truth'], {}), '(out_got, out_t... |
from django.test import TestCase
from rest_framework.test import APIClient
from django.contrib.auth.models import User
class UserTestCase(TestCase):
def setUp(self):
User.objects.create_user(username='api_user', email='<EMAIL>', password='password')
User.objects.create_user(username='other_user',... | [
"django.contrib.auth.models.User.objects.get",
"django.contrib.auth.models.User.objects.create_user",
"rest_framework.test.APIClient"
] | [((181, 269), 'django.contrib.auth.models.User.objects.create_user', 'User.objects.create_user', ([], {'username': '"""api_user"""', 'email': '"""<EMAIL>"""', 'password': '"""password"""'}), "(username='api_user', email='<EMAIL>', password=\n 'password')\n", (205, 269), False, 'from django.contrib.auth.models import... |
"""
copy_opendata_shapefiles
Copies the Toronto Centreline and Intersection File datasets in SHP format into our database.
First, shapefiles are downloaded from the City of Toronto Open Data Portal into `/data/shapefile`.
These are then loaded into the database by using `shp2pgsql` to transform the shapefiles into
Po... | [
"datetime.datetime",
"airflow_utils.create_bash_task_nested",
"airflow_utils.create_dag",
"airflow.operators.bash_operator.BashOperator"
] | [((563, 584), 'datetime.datetime', 'datetime', (['(2020)', '(2)', '(27)'], {}), '(2020, 2, 27)\n', (571, 584), False, 'from datetime import datetime\n'), ((624, 684), 'airflow_utils.create_dag', 'create_dag', (['__file__', '__doc__', 'START_DATE', 'SCHEDULE_INTERVAL'], {}), '(__file__, __doc__, START_DATE, SCHEDULE_INT... |
from django.test import TestCase
from explorer.actions import generate_report_action
from explorer.tests.factories import SimpleQueryFactory
from explorer import app_settings
from explorer.utils import passes_blacklist, schema_info, param, swap_params, extract_params, shared_dict_update, EXPLORER_PARAM_TOKEN, execute_q... | [
"explorer.utils.passes_blacklist",
"explorer.tests.factories.SimpleQueryFactory",
"explorer.utils.param",
"explorer.utils.schema_info",
"explorer.utils.extract_params",
"explorer.utils.swap_params",
"explorer.utils.shared_dict_update",
"explorer.actions.generate_report_action"
] | [((623, 672), 'explorer.tests.factories.SimpleQueryFactory', 'SimpleQueryFactory', ([], {'sql': '"""SELECT 1+1 AS "DELETE";"""'}), '(sql=\'SELECT 1+1 AS "DELETE";\')\n', (641, 672), False, 'from explorer.tests.factories import SimpleQueryFactory\n'), ((688, 712), 'explorer.actions.generate_report_action', 'generate_rep... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
__... | [
"pulumi.get",
"pulumi.getter",
"pulumi.set",
"pulumi.InvokeOptions",
"pulumi.runtime.invoke"
] | [((1105, 1138), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""displayName"""'}), "(name='displayName')\n", (1118, 1138), False, 'import pulumi\n'), ((713, 763), 'pulumi.set', 'pulumi.set', (['__self__', '"""display_name"""', 'display_name'], {}), "(__self__, 'display_name', display_name)\n", (723, 763), False, 'i... |
from polylogyx.models import Query, db, Pack, Tag
from polylogyx.utils import create_tags
from sqlalchemy import desc, asc, or_, cast
import sqlalchemy
def get_total_count():
return Query.query.count()
def get_total_packed_queries_count():
return Query.query \
.options(
db.joinedload(Query.t... | [
"polylogyx.models.db.joinedload",
"polylogyx.models.Query.query.count",
"polylogyx.models.db.session.query",
"polylogyx.models.Query.name.in_",
"polylogyx.models.Tag.value.in_",
"polylogyx.models.Query.create",
"polylogyx.models.Query.name.ilike",
"sqlalchemy.desc",
"polylogyx.dao.v1.packs_dao.get_p... | [((188, 207), 'polylogyx.models.Query.query.count', 'Query.query.count', ([], {}), '()\n', (205, 207), False, 'from polylogyx.models import Query, db, Pack, Tag\n'), ((617, 655), 'polylogyx.models.Query.create', 'Query.create', ([], {'name': 'query_name'}), '(name=query_name, **query)\n', (629, 655), False, 'from polyl... |
import torch
import torch.nn as nn
import model.ops as ops
import torch
import math, re, functools
import torch.nn.functional as F
import numpy as np
import scipy.io as sio
import copy
def make_model(args, parent=False):
return Bucket_Conv(args)
class LocalConv2d_No(nn.Module):
def __init__(self, in_channels=... | [
"torch.nn.Embedding",
"torch.nn.PReLU",
"torch.nn.Conv2d",
"torch.nn.init.normal_",
"torch.nn.functional.pad",
"torch.cat"
] | [((4362, 4415), 'torch.nn.Conv2d', 'nn.Conv2d', (['self.input_channels', 'args.n_feats', '(3)', '(1)', '(1)'], {}), '(self.input_channels, args.n_feats, 3, 1, 1)\n', (4371, 4415), True, 'import torch.nn as nn\n'), ((9997, 10049), 'torch.nn.Conv2d', 'nn.Conv2d', (['args.n_feats', 'self.args.n_colors', '(3)', '(1)', '(1)... |
# Main function that goes thru PER_PATIENT_VISIT clinical data table and turns it into a usable form
# Goes thru columns manually and assess quality
# A unique index is made from PUBLIC_ID + VISIT
# TODO: Apply cols in pres to turn various rows of data into nan (especially those converted from 'Checked'/blank)
# This... | [
"pandas.notnull",
"os.path.join",
"load_patient_data.load_per_visit_data"
] | [((1648, 1669), 'load_patient_data.load_per_visit_data', 'load_per_visit_data', ([], {}), '()\n', (1667, 1669), False, 'from load_patient_data import load_per_visit_data\n'), ((22300, 22333), 'pandas.notnull', 'pd.notnull', (["date['SS_DAYOFVISIT']"], {}), "(date['SS_DAYOFVISIT'])\n", (22310, 22333), True, 'import pand... |
"""
========================================================================
Test sources
========================================================================
Test sources with CL or RTL interfaces.
Author : <NAME>
Date : Mar 11, 2019
"""
from collections import deque
from copy import deepcopy
from pymtl3 impor... | [
"pymtl3.stdlib.ifcs.OutValRdyIfc",
"copy.deepcopy"
] | [((501, 519), 'pymtl3.stdlib.ifcs.OutValRdyIfc', 'OutValRdyIfc', (['Type'], {}), '(Type)\n', (513, 519), False, 'from pymtl3.stdlib.ifcs import OutValRdyIfc\n'), ((548, 562), 'copy.deepcopy', 'deepcopy', (['msgs'], {}), '(msgs)\n', (556, 562), False, 'from copy import deepcopy\n')] |
"""Prime number operations used for just intonation."""
from math import gcd
from functools import reduce
__version__ = '0.0.1'
def is_prime(number):
"""States if a number is prime.
:param number: A number
:type number: int
:rtype: bool
**Examples**
>>> is_prime(31)
True
>>> is... | [
"math.gcd"
] | [((1610, 1619), 'math.gcd', 'gcd', (['x', 'y'], {}), '(x, y)\n', (1613, 1619), False, 'from math import gcd\n')] |
from __future__ import absolute_import, division, print_function
from six.moves import range
def intify(a):
return tuple([int(round(val)) for val in a])
def reference_map(sg, mi):
from cctbx import sgtbx
asu = sgtbx.reciprocal_space_asu(sg.type())
isym_ = []
mi_ = []
for hkl in mi:
found = False
... | [
"six.moves.range",
"cctbx.sgtbx.space_group",
"cctbx.sgtbx.space_group_symbols",
"cctbx.array_family.flex.int",
"random.randint",
"cctbx.array_family.flex.miller_index"
] | [((1236, 1255), 'cctbx.array_family.flex.miller_index', 'flex.miller_index', ([], {}), '()\n', (1253, 1255), False, 'from cctbx.array_family import flex\n'), ((1262, 1272), 'cctbx.array_family.flex.int', 'flex.int', ([], {}), '()\n', (1270, 1272), False, 'from cctbx.array_family import flex\n'), ((1317, 1328), 'six.mov... |
from configparser import ConfigParser
import pytest
def pytest_addoption(parser):
pass
@pytest.fixture(scope='session')
def contract(request):
pass
@pytest.fixture(scope='session')
def block(request, conf):
pass
| [
"pytest.fixture"
] | [((97, 128), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (111, 128), False, 'import pytest\n'), ((168, 199), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (182, 199), False, 'import pytest\n')] |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @Time : 2020/7/23 18:03
# @Software: PyCharm
# @Author : https://github.com/Valuebai/
"""
<moudule>.$ {NAME}
~~~~~~~~~~~~~~~
常用的秒,毫秒时间转换
Usage Example
-------------
::
"""
import time
def timeStamp_ms_convert_time(time_num):
"""
输入... | [
"time.localtime",
"time.strftime"
] | [((495, 521), 'time.localtime', 'time.localtime', (['time_stamp'], {}), '(time_stamp)\n', (509, 521), False, 'import time\n'), ((540, 586), 'time.strftime', 'time.strftime', (['"""%Y-%m-%d %H:%M:%S"""', 'time_array'], {}), "('%Y-%m-%d %H:%M:%S', time_array)\n", (553, 586), False, 'import time\n'), ((871, 917), 'time.st... |
"""Representation of a bullet as a sprite."""
import pygame
from colors import *
from settings import *
from geometry import *
from pygame import Color
class Bullet(pygame.sprite.Sprite):
def __init__(self, shooter, x, y, angle, speed, radius=5):
"""Initialize the bullet object."""
super().__ini... | [
"pygame.Color",
"pygame.Surface"
] | [((410, 450), 'pygame.Surface', 'pygame.Surface', (['[radius * 2, radius * 2]'], {}), '([radius * 2, radius * 2])\n', (424, 450), False, 'import pygame\n'), ((471, 484), 'pygame.Color', 'Color', (['*WHITE'], {}), '(*WHITE)\n', (476, 484), False, 'from pygame import Color\n'), ((518, 531), 'pygame.Color', 'Color', (['*W... |
import json
import logging
import os
import requests
from skygear.registry import get_registry
log = logging.getLogger(__name__)
class FacebookBot():
def __init__(self, page_id, token):
self.page_id = page_id
self.token = token
@property
def thread_settings_url(self):
url = "htt... | [
"logging.getLogger",
"json.loads",
"requests.post",
"os.getenv",
"skygear.registry.get_registry"
] | [((103, 130), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (120, 130), False, 'import logging\n'), ((477, 775), 'requests.post', 'requests.post', (['self.thread_settings_url'], {'params': "{'access_token': self.token}", 'json': "{'call_to_actions': [{'message': {'attachment': {'payload'... |
from random import *
import subprocess
import sys
import warnings
warnings.filterwarnings("ignore")
nb_prob = 50
open_prob = 100
prob_end = 5
num_range = [0, 100]
expr = ""
operators = ["+","-","*","/", "%"]
opened_p = 0
min_expr_len = 5
max_expr_len = 30
no_overflow = False
error = False
def append_number():
glo... | [
"subprocess.Popen",
"warnings.filterwarnings"
] | [((67, 100), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (90, 100), False, 'import warnings\n'), ((644, 697), 'subprocess.Popen', 'subprocess.Popen', (["['echo', s]"], {'stdout': 'subprocess.PIPE'}), "(['echo', s], stdout=subprocess.PIPE)\n", (660, 697), False, 'import ... |
import os
import json
from collections import OrderedDict
def sort_meta_dict(input_dict: dict) -> OrderedDict:
"""
Sorting Meta dictionary in result directory.
@param input_dict:
@return:
"""
sorted_tuple = sorted(input_dict.items(), key=lambda item: int(item[0]))
return OrderedDict(sorted... | [
"os.path.exists",
"collections.OrderedDict",
"os.path.getsize",
"os.path.join",
"os.getcwd",
"os.mkdir",
"json.load",
"os.remove"
] | [((302, 327), 'collections.OrderedDict', 'OrderedDict', (['sorted_tuple'], {}), '(sorted_tuple)\n', (313, 327), False, 'from collections import OrderedDict\n'), ((807, 839), 'os.path.join', 'os.path.join', (['txt_dir', 'file_name'], {}), '(txt_dir, file_name)\n', (819, 839), False, 'import os\n'), ((1557, 1582), 'os.pa... |
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import binom
from crypto_quandl_loader import load_data
import price_changes
import grid_approx
data = load_data('BTER/VTCBTC')
up_down = price_changes.compute(data)
c1 = up_down.count(1)
c0 = up_down.count(0)
p1 = c1 / len(up_down)
p0 = c0 / len(up... | [
"grid_approx.compute",
"matplotlib.pyplot.plot",
"crypto_quandl_loader.load_data",
"price_changes.compute",
"matplotlib.pyplot.show"
] | [((172, 196), 'crypto_quandl_loader.load_data', 'load_data', (['"""BTER/VTCBTC"""'], {}), "('BTER/VTCBTC')\n", (181, 196), False, 'from crypto_quandl_loader import load_data\n'), ((207, 234), 'price_changes.compute', 'price_changes.compute', (['data'], {}), '(data)\n', (228, 234), False, 'import price_changes\n'), ((46... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import RPi.GPIO as GPIO
from time import sleep
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
class Relay():
def __init__(self, name, pin):
self.pin = pin # 5 6 13 19
self.name = name
self.init_gpio()
self.status = "off"
def init_gpio(self):
... | [
"RPi.GPIO.cleanup",
"RPi.GPIO.setup",
"RPi.GPIO.output",
"RPi.GPIO.setwarnings",
"time.sleep",
"RPi.GPIO.setmode"
] | [((96, 118), 'RPi.GPIO.setmode', 'GPIO.setmode', (['GPIO.BCM'], {}), '(GPIO.BCM)\n', (108, 118), True, 'import RPi.GPIO as GPIO\n'), ((119, 142), 'RPi.GPIO.setwarnings', 'GPIO.setwarnings', (['(False)'], {}), '(False)\n', (135, 142), True, 'import RPi.GPIO as GPIO\n'), ((323, 353), 'RPi.GPIO.setup', 'GPIO.setup', (['se... |
import pandas as pd
import random
import time
number = 2000
value = random.randint(1, number)
matrix = []
for i in range(6000000):
row = [j for j in range(5)]
row.append(value)
matrix.append(row)
df = pd.DataFrame(matrix, columns=["l"+str(i) for i in range(6)])
t1 = time.time()
for eid in df["l5"... | [
"time.time",
"random.randint"
] | [((69, 94), 'random.randint', 'random.randint', (['(1)', 'number'], {}), '(1, number)\n', (83, 94), False, 'import random\n'), ((290, 301), 'time.time', 'time.time', ([], {}), '()\n', (299, 301), False, 'import time\n'), ((374, 385), 'time.time', 'time.time', ([], {}), '()\n', (383, 385), False, 'import time\n')] |
#!/usr/bin/python
# Model counting for free ITE graph
# Optionally generate output ITEG file
import getopt
import sys
import iteg
import writer
def usage(name):
print("Usage: %s [-h] [-i IFILE] [-p PREFIX] [-o OFILE] [-q QFILE] [-P PFILE]" % name)
print(" -h Print this message")
print(" -i IFILE ... | [
"writer.OrderWriter",
"getopt.getopt",
"iteg.IteGraph",
"writer.QcnfWriter"
] | [((854, 870), 'iteg.IteGraph', 'iteg.IteGraph', (['(0)'], {}), '(0)\n', (867, 870), False, 'import iteg\n'), ((2537, 2571), 'getopt.getopt', 'getopt.getopt', (['args', '"""hi:p:o:q:P:"""'], {}), "(args, 'hi:p:o:q:P:')\n", (2550, 2571), False, 'import getopt\n'), ((1672, 1703), 'writer.QcnfWriter', 'writer.QcnfWriter', ... |
# coding: utf-8
"""
"""
import pytest
import stream_processor as sp
from stream_processor import Token as tk
TOKEN_EXAMPLES = (
(r'<', [tk.START_GARBAGE]),
(r'>', [tk.END_GARBAGE]),
(r'c', [tk.CHARACTER]),
(r'!c', [tk.ESCAPE, tk.CHARACTER]),
(r'{c', [tk.START_GROUP, tk.CHARACTER]),
(r'}', [tk... | [
"stream_processor.count_groups",
"stream_processor.tokenize",
"pytest.mark.parametrize",
"stream_processor.score_garbage",
"stream_processor.score_groups"
] | [((1181, 1243), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""test_input,expected"""', 'TOKEN_EXAMPLES'], {}), "('test_input,expected', TOKEN_EXAMPLES)\n", (1204, 1243), False, 'import pytest\n'), ((1417, 1467), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""test_input"""', 'ALL_GARBAGE'], {}... |
#!/usr/bin/python3
# <---------------------------------------------------------------------------- general imports --->
import os
import sys
import datetime
import configparser
from random import random
import math
# <---------------------------------------------------------------------------- numeric imports --->
imp... | [
"os.listdir",
"configparser.ConfigParser",
"scipy.integrate.odeint",
"matplotlib.animation.FuncAnimation",
"os.path.join",
"scipy.concatenate",
"scipy.array",
"scipy.transpose",
"os.path.isfile",
"scipy.linspace",
"matplotlib.pyplot.figure",
"os.path.dirname",
"os.path.isdir",
"matplotlib.... | [((1122, 1158), 'scipy.array', 'sci.array', (['position'], {'dtype': '"""float64"""'}), "(position, dtype='float64')\n", (1131, 1158), True, 'import scipy as sci\n'), ((1183, 1219), 'scipy.array', 'sci.array', (['velocity'], {'dtype': '"""float64"""'}), "(velocity, dtype='float64')\n", (1192, 1219), True, 'import scipy... |
# def flatten(current, result=[]):
# if isinstance(current, dict):
# for key in current:
# flatten(current[key], result)
# else:
# result.append(current)
# return result
import ndmg
def test_flatten():
current = {'name':'liming', 'age':'20'}
value = ndmg.utils.bids_ut... | [
"ndmg.utils.bids_utils.flatten"
] | [((302, 344), 'ndmg.utils.bids_utils.flatten', 'ndmg.utils.bids_utils.flatten', (['current', '[]'], {}), '(current, [])\n', (331, 344), False, 'import ndmg\n')] |
from math import asin, degrees, pi, radians, sin, cos, sqrt
from helper import *
default_config = {
"acc_cal": [4968.7, 4981.1], # zero-value for acc
"acc_g": [1240.0, 1240.0], # 1g value for acc
"acc_fc": 10.0, # lp cutoff frequency, Hz
"gyro_cal": [-12.0, 15.0, 0.1], # zero-value for gyro
"gyro_s... | [
"math.cos",
"math.sin",
"math.sqrt",
"math.radians"
] | [((3522, 3532), 'math.radians', 'radians', (['x'], {}), '(x)\n', (3529, 3532), False, 'from math import asin, degrees, pi, radians, sin, cos, sqrt\n'), ((3840, 3855), 'math.cos', 'cos', (['gyro_da[2]'], {}), '(gyro_da[2])\n', (3843, 3855), False, 'from math import asin, degrees, pi, radians, sin, cos, sqrt\n'), ((3905,... |
import pandas as pd
from pathlib import Path
def add_new_track_layer(viewer, track_layers, point_size):
num = len(track_layers)
new_track_layers = viewer.add_points(
n_dimensional=True,
size=point_size,
name=f"track_{num}",
)
new_track_layers.mode = "ADD"
track_layers.appen... | [
"pandas.read_hdf",
"pathlib.Path"
] | [((418, 441), 'pandas.read_hdf', 'pd.read_hdf', (['track_file'], {}), '(track_file)\n', (429, 441), True, 'import pandas as pd\n'), ((566, 582), 'pathlib.Path', 'Path', (['track_file'], {}), '(track_file)\n', (570, 582), False, 'from pathlib import Path\n')] |
from userbot.modules.sql_helper.global_collectionjson import get_collection
def blacklist_chats_list():
try:
blacklistchats = get_collection("blacklist_chats_list").json
except AttributeError:
blacklistchats = {}
blacklist = blacklistchats.keys()
return [int(chat) for chat in blacklist... | [
"userbot.modules.sql_helper.global_collectionjson.get_collection"
] | [((140, 178), 'userbot.modules.sql_helper.global_collectionjson.get_collection', 'get_collection', (['"""blacklist_chats_list"""'], {}), "('blacklist_chats_list')\n", (154, 178), False, 'from userbot.modules.sql_helper.global_collectionjson import get_collection\n')] |
import discord
from discord.ext import commands, tasks
from logger import DatabaseLogger
from cogs.wow.wownewsdb import WoWNewsDB
import cogs.wow.config as cfg
import cogs.wow.messageembedder as me
class WoWNewsCog(commands.Cog, name='World of Warcraft News'):
def __init__(self, bot: commands.Bot):
self.... | [
"cogs.wow.wownewsdb.WoWNewsDB",
"logger.DatabaseLogger",
"discord.ext.commands.command",
"cogs.wow.messageembedder.embed_message"
] | [((707, 725), 'discord.ext.commands.command', 'commands.command', ([], {}), '()\n', (723, 725), False, 'from discord.ext import commands, tasks\n'), ((1292, 1349), 'discord.ext.commands.command', 'commands.command', ([], {'aliases': "['hotfix', 'update', 'updates']"}), "(aliases=['hotfix', 'update', 'updates'])\n", (13... |
# coding: utf-8
import logging
import re
import urllib
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import JsonResponse
from django.views import generic
from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse
from django.db.models import QuerySet
... | [
"logging.getLogger",
"django.shortcuts.render",
"re.compile",
"django.http.JsonResponse",
"django.shortcuts.get_object_or_404",
"django.shortcuts.redirect",
"market.core.models.Vendor.objects.get",
"django.urls.reverse",
"rest_framework.parsers.JSONParser",
"market.core.models.Vendor.objects.filte... | [((486, 518), 'logging.getLogger', 'logging.getLogger', (['"""market.core"""'], {}), "('market.core')\n", (503, 518), False, 'import logging\n'), ((2397, 2436), 'django.urls.reverse', 'reverse', (['name'], {'args': 'args', 'kwargs': 'kwargs'}), '(name, args=args, kwargs=kwargs)\n', (2404, 2436), False, 'from django.url... |
import time
import torch
# [s, px, py, pz, dxy, dyz, dxz, dx2-y2, dz2, S]
def get_hop_int(input_params=torch.zeros(7)):
# input_params[0]=V_sss,
# input_params[1]=V_sps,
# input_params[2]=V_pps,
# input_params[3]=V_ppp,
# input_params[4]=l,
# input_params[5]=m
# input_params[6]=n
... | [
"torch.stack",
"torch.zeros"
] | [((105, 119), 'torch.zeros', 'torch.zeros', (['(7)'], {}), '(7)\n', (116, 119), False, 'import torch\n'), ((1617, 1678), 'torch.stack', 'torch.stack', (['(hop_int_00, hop_int_01, hop_int_02, hop_int_03)'], {}), '((hop_int_00, hop_int_01, hop_int_02, hop_int_03))\n', (1628, 1678), False, 'import torch\n'), ((1704, 1765)... |
import cv2
from turbojpeg import TurboJPEG, TJPF_GRAY, TJSAMP_GRAY, TJFLAG_PROGRESSIVE
import torch
from torch.utils.data import Dataset, DataLoader
import os, sys
sys.path.append("../")
from models.metrics import ROOT_PATH
import os.path as osp
import glob
import csv
import numpy as np
import random
from collection... | [
"csv.DictWriter",
"os.path.exists",
"random.sample",
"tqdm.tqdm",
"os.path.join",
"turbojpeg.TurboJPEG",
"random.seed",
"collections.defaultdict",
"sys.path.append"
] | [((166, 188), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (181, 188), False, 'import sys\n'), ((384, 395), 'turbojpeg.TurboJPEG', 'TurboJPEG', ([], {}), '()\n', (393, 395), False, 'from turbojpeg import TurboJPEG, TJPF_GRAY, TJSAMP_GRAY, TJFLAG_PROGRESSIVE\n'), ((626, 643), 'collections.defa... |
# -*- coding: utf-8 -*-
import os
import asyncio
import pickle
from copy import deepcopy
from typing import Any, Optional, Union
from grpc.aio import ServicerContext
from recc.argparse.config.task_config import TaskConfig
from recc.argparse.default_namespace import get_default_task_config
from recc.argparse.injection_... | [
"recc.storage.task_workspace.TaskWorkspace",
"pickle.dumps",
"recc.proto.rpc.rpc_api_pb2.Pat",
"os.chown",
"recc.vs.task_graph.TaskGraph",
"pickle.loads",
"recc.rpc.rpc_converter.cvt_box_data",
"recc.system.user.get_user_id",
"recc.argparse.default_namespace.get_default_task_config",
"recc.system.... | [((1476, 1509), 'os.chown', 'os.chown', (['path', 'user_id', 'group_id'], {}), '(path, user_id, group_id)\n', (1484, 1509), False, 'import os\n'), ((1369, 1386), 'recc.system.user.get_user_id', 'get_user_id', (['user'], {}), '(user)\n', (1380, 1386), False, 'from recc.system.user import get_user_id\n'), ((1451, 1470), ... |
#!/usr/bin/env python
"""
Custom functions for identifiability analysis to calculate
and plot confidence intervals based on a profile-likelihood analysis. Adapted
from lmfit, with custom functions to select the range for parameter scanning and
for plotting the profile likelihood.
"""
from collections import Ordere... | [
"collections.OrderedDict",
"lmfit.minimizer.MinimizerException",
"math.ceil",
"numpy.log10",
"numpy.linspace",
"scipy.stats.chi2.ppf",
"numpy.isnan",
"multiprocessing.Pool",
"scipy.interpolate.UnivariateSpline",
"matplotlib.pyplot.subplots"
] | [((2517, 2530), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (2528, 2530), False, 'from collections import OrderedDict\n'), ((4410, 4465), 'scipy.interpolate.UnivariateSpline', 'sp.interpolate.UnivariateSpline', (['xx', 'yy'], {'k': 'self._k', 's': '(0)'}), '(xx, yy, k=self._k, s=0)\n', (4441, 4465), Tru... |
# Copyright (c) 2014 Mirantis 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 writing, so... | [
"inspect.ismethod",
"time.sleep"
] | [((2096, 2122), 'time.sleep', 'time.sleep', (['self.wait_time'], {}), '(self.wait_time)\n', (2106, 2122), False, 'import time\n'), ((2641, 2663), 'inspect.ismethod', 'inspect.ismethod', (['attr'], {}), '(attr)\n', (2657, 2663), False, 'import inspect\n')] |
"""
backend URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-base... | [
"django.views.generic.TemplateView.as_view",
"django.urls.path",
"rest_framework.schemas.get_schema_view",
"django.urls.include"
] | [((821, 852), 'django.urls.path', 'path', (['"""admin/"""', 'admin.site.urls'], {}), "('admin/', admin.site.urls)\n", (825, 852), False, 'from django.urls import path, include\n'), ((877, 905), 'django.urls.include', 'include', (['"""risk_factors.urls"""'], {}), "('risk_factors.urls')\n", (884, 905), False, 'from djang... |
#!/usr/bin/env python
# coding: utf-8
# In[7]:
import torch
import torch.nn as nn
from torchvision import datasets, models, transforms
import os
# In[8]:
# Load the test data.
data_transforms = {
'test': transforms.Compose([
transforms.Resize([224, 224]),
transforms.ToTensor()
])
}
data_... | [
"torch.nn.Dropout",
"torch.load",
"torch.max",
"os.path.join",
"torchvision.models.alexnet",
"torch.cuda.is_available",
"torch.utils.data.DataLoader",
"torchvision.transforms.Resize",
"torch.no_grad",
"torchvision.transforms.ToTensor",
"pandas_ml.ConfusionMatrix"
] | [((1063, 1094), 'torchvision.models.alexnet', 'models.alexnet', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (1077, 1094), False, 'from torchvision import datasets, models, transforms\n'), ((2166, 2204), 'pandas_ml.ConfusionMatrix', 'ConfusionMatrix', (['all_labels', 'all_preds'], {}), '(all_labels, all_preds... |
from CommonServerPython import *
from collections import defaultdict
from DBotPredictPhishingWords import get_model_data, predict_phishing_words
import pytest
def get_args():
args = defaultdict(lambda: "yes")
args['encoding'] = 'utf8'
args['encoding'] = 'utf8'
args['removeNonEnglishWords'] = 'no'
... | [
"DBotPredictPhishingWords.get_model_data",
"DBotPredictPhishingWords.predict_phishing_words",
"collections.defaultdict",
"pytest.raises"
] | [((188, 215), 'collections.defaultdict', 'defaultdict', (["(lambda : 'yes')"], {}), "(lambda : 'yes')\n", (199, 215), False, 'from collections import defaultdict\n'), ((2184, 2246), 'DBotPredictPhishingWords.predict_phishing_words', 'predict_phishing_words', (['"""modelName"""', '"""list"""', '"""subject"""', '"""body"... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-09-18 03:58
from __future__ import unicode_literals
from django.db import migrations
def image_to_custom_image(apps, schema_editor):
Image = apps.get_model("wagtailimages","Image")
CustomImage = apps.get_model("cms_pages", "CustomImage")
HomePag... | [
"django.db.migrations.RunPython"
] | [((2339, 2382), 'django.db.migrations.RunPython', 'migrations.RunPython', (['image_to_custom_image'], {}), '(image_to_custom_image)\n', (2359, 2382), False, 'from django.db import migrations\n')] |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from .plot_error import calculate_error_area
from .distance import distance
# Trajectory
def plot_trajectory(df, vmr, blockN, trial_vars, axs, colors):
# Plot aspect
for ax in axs[0]:
ax.axis('equal')
ax.set_box_aspect(1)
... | [
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.subplots",
"pandas.read_csv",
"matplotlib.pyplot.show"
] | [((2571, 2625), 'pandas.read_csv', 'pd.read_csv', (['output_file'], {'names': 'names', 'index_col': '(False)'}), '(output_file, names=names, index_col=False)\n', (2582, 2625), True, 'import pandas as pd\n'), ((2774, 2816), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(5)', 'block_count'], {'sharey': '"""row"""'}), ... |
# Copyright (c) 2020, 2021 The Linux Foundation
#
# SPDX-License-Identifier: Apache-2.0
from datetime import datetime
from west import log
from zspdx.util import getHashes
# Output tag-value SPDX 2.2 content for the given Relationship object.
# Arguments:
# 1) f: file handle for SPDX document
# 2) rln: Relation... | [
"zspdx.util.getHashes",
"west.log.err",
"west.log.inf",
"datetime.datetime.utcnow"
] | [((5028, 5047), 'zspdx.util.getHashes', 'getHashes', (['spdxPath'], {}), '(spdxPath)\n', (5037, 5047), False, 'from zspdx.util import getHashes\n'), ((4710, 4772), 'west.log.inf', 'log.inf', (['f"""Writing SPDX document {doc.cfg.name} to {spdxPath}"""'], {}), "(f'Writing SPDX document {doc.cfg.name} to {spdxPath}')\n",... |
from flask_philo_core import init_app
from flask_philo_core.test import create_test_app
from flask_philo_core.exceptions import ConfigurationError
from unittest.mock import patch
import os
import pytest
import sys
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
sys.path.append(os.path.join(BASE_DIR, '../'))
... | [
"unittest.mock.patch.dict",
"os.path.join",
"flask_philo_core.init_app",
"flask_philo_core.test.create_test_app",
"os.path.dirname",
"pytest.raises"
] | [((244, 269), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (259, 269), False, 'import os\n'), ((287, 316), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""../"""'], {}), "(BASE_DIR, '../')\n", (299, 316), False, 'import os\n'), ((489, 522), 'pytest.raises', 'pytest.raises', (['Configurati... |
#!/usr/bin/env python3.5
import json
import sys
from pprint import pprint
import mysql.connector
from mysql.connector import errorcode
def main(argv):
print(argv)
result = {}
try:
with open(argv[0], 'r') as f:
i = 0
for line in f:
# remove the new line to ke... | [
"json.dumps",
"traceback.print_exc",
"pprint.pprint"
] | [((948, 969), 'traceback.print_exc', 'traceback.print_exc', ([], {}), '()\n', (967, 969), False, 'import traceback\n'), ((1877, 1897), 'json.dumps', 'json.dumps', (['portions'], {}), '(portions)\n', (1887, 1897), False, 'import json\n'), ((555, 570), 'pprint.pprint', 'pprint', (['headers'], {}), '(headers)\n', (561, 57... |
# Generated by Django 3.0.6 on 2020-05-04 17:45
import crdb.models
from django.conf import settings
import django.contrib.auth.validators
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies... | [
"django.db.models.GenericIPAddressField",
"django.db.models.EmailField",
"django.db.models.OneToOneField",
"django.db.models.FloatField",
"django.db.models.TextField",
"django.db.models.ForeignKey",
"django.db.models.ManyToManyField",
"django.db.models.BooleanField",
"django.db.models.AutoField",
... | [((8237, 8290), 'django.db.models.ManyToManyField', 'models.ManyToManyField', ([], {'blank': '(True)', 'to': '"""crdb.Website"""'}), "(blank=True, to='crdb.Website')\n", (8259, 8290), False, 'from django.db import migrations, models\n'), ((9422, 9533), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'blank': ... |
import logging
import re
LOG = logging.getLogger(__name__)
class ValidationError(Exception):
pass
class RegexValidator:
def __init__(self, pattern, ignore_case):
self.pattern = pattern
flags = re.I if ignore_case else 0
self.regex = re.compile(pattern, flags=flags)
def __call__(... | [
"logging.getLogger",
"re.compile"
] | [((32, 59), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (49, 59), False, 'import logging\n'), ((269, 301), 're.compile', 're.compile', (['pattern'], {'flags': 'flags'}), '(pattern, flags=flags)\n', (279, 301), False, 'import re\n')] |
import torch
import torch.nn.functional as F
import numpy as np
from torch import nn
from torch.autograd import Variable
from random import shuffle
from matplotlib.colors import rgb_to_hsv, hsv_to_rgb
from PIL import Image
import cv2
def CE_Loss(inputs, target, num_classes=21):
n, c, h, w = inputs.size()
nt,... | [
"torch.mean",
"torch.sum",
"torch.nn.NLLLoss",
"torch.nn.functional.log_softmax",
"torch.nn.functional.interpolate"
] | [((1224, 1283), 'torch.sum', 'torch.sum', (['(temp_target[..., :-1] * temp_inputs)'], {'axis': '[0, 1]'}), '(temp_target[..., :-1] * temp_inputs, axis=[0, 1])\n', (1233, 1283), False, 'import torch\n'), ((389, 462), 'torch.nn.functional.interpolate', 'F.interpolate', (['inputs'], {'size': '(ht, wt)', 'mode': '"""biline... |
import json
import time
from paprika.connectors.DatasourceBuilder import DatasourceBuilder
from paprika.executors.ManagedWorker import ManagedWorker
from paprika.processing.ProcessService import ProcessService
from paprika.repositories.ChunkRepository import ChunkRepository
from paprika.repositories.JobRepository impor... | [
"paprika.repositories.PayloadRepository.PayloadRepository",
"paprika.repositories.RuleRepository.RuleRepository",
"paprika.repositories.ProcessPropertyRepository.ProcessPropertyRepository",
"json.dumps",
"paprika.executors.ManagedWorker.ManagedWorker.__init__",
"paprika.processing.ProcessService.ProcessSe... | [((930, 992), 'paprika.executors.ManagedWorker.ManagedWorker.__init__', 'ManagedWorker.__init__', (['self', 'id', 'settings', 'claim', 'abort', 'stop'], {}), '(self, id, settings, claim, abort, stop)\n', (952, 992), False, 'from paprika.executors.ManagedWorker import ManagedWorker\n'), ((1137, 1179), 'paprika.connector... |
from graphql.type.definition import GraphQLArgument, GraphQLField, GraphQLNonNull, GraphQLObjectType
from graphql.type.scalars import GraphQLString, GraphQLInt
from graphql.type.schema import GraphQLSchema
def resolve_raises(*_):
raise Exception("Throws!")
QueryRootType = GraphQLObjectType(
name='QueryRoot'... | [
"graphql.type.definition.GraphQLArgument",
"graphql.type.definition.GraphQLField",
"graphql.type.definition.GraphQLNonNull",
"graphql.type.schema.GraphQLSchema"
] | [((1400, 1446), 'graphql.type.schema.GraphQLSchema', 'GraphQLSchema', (['QueryRootType', 'MutationRootType'], {}), '(QueryRootType, MutationRootType)\n', (1413, 1446), False, 'from graphql.type.schema import GraphQLSchema\n'), ((1280, 1347), 'graphql.type.definition.GraphQLField', 'GraphQLField', ([], {'type': 'QueryRo... |
#! python
from bs4 import BeautifulSoup
from argparse import ArgumentParser
import re
def get_imgs_list(fp):
fobj=open(fp,'r')
soup=BeautifulSoup(fobj,features="html.parser")
fobj.close()
imgs=list(set(soup.find_all('img')))
return imgs
def get_links_list(fp):
fobj=open(fp,'r')
soup=Beaut... | [
"bs4.BeautifulSoup"
] | [((142, 185), 'bs4.BeautifulSoup', 'BeautifulSoup', (['fobj'], {'features': '"""html.parser"""'}), "(fobj, features='html.parser')\n", (155, 185), False, 'from bs4 import BeautifulSoup\n'), ((315, 358), 'bs4.BeautifulSoup', 'BeautifulSoup', (['fobj'], {'features': '"""html.parser"""'}), "(fobj, features='html.parser')\... |
# Copyright (c) 2021 elParaguayo
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distrib... | [
"pytest.mark.parametrize",
"test.widgets.test_mpd2widget.MockMPD"
] | [((1326, 1449), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""screenshot_manager"""', "[{}, {'status_format': '{play_status} {artist}/{title}'}]"], {'indirect': '(True)'}), "('screenshot_manager', [{}, {'status_format':\n '{play_status} {artist}/{title}'}], indirect=True)\n", (1349, 1449), False, 'impo... |
from functools import cmp_to_key
from LMS.models import DAY_OF_WEEK
def sort_day(day_class):
cmp_attrs = ['start_time', 'end_time', 'start_week', 'end_week', 'unit.code']
def get_attr(obj, attr):
attrs = attr.split('.')
for at in attrs:
obj = getattr(obj, at)
return obj
... | [
"functools.cmp_to_key"
] | [((591, 606), 'functools.cmp_to_key', 'cmp_to_key', (['cmp'], {}), '(cmp)\n', (601, 606), False, 'from functools import cmp_to_key\n')] |
import pygame
from animal import Animal
import game_config as gc
from time import sleep
from pygame import display, event, image
def find_index(x,y):
row=y//gc.IMAGE_SIZE
col=x//gc.IMAGE_SIZE
index=row*gc.NUM_TILES_SIDE+col
return index
pygame.init()
display.set_caption('Guessing Game')
screen=display.set_mode((5... | [
"pygame.init",
"pygame.event.get",
"pygame.display.set_mode",
"pygame.display.flip",
"pygame.mouse.get_pos",
"time.sleep",
"pygame.display.set_caption",
"pygame.image.load",
"animal.Animal"
] | [((242, 255), 'pygame.init', 'pygame.init', ([], {}), '()\n', (253, 255), False, 'import pygame\n'), ((257, 293), 'pygame.display.set_caption', 'display.set_caption', (['"""Guessing Game"""'], {}), "('Guessing Game')\n", (276, 293), False, 'from pygame import display, event, image\n'), ((301, 329), 'pygame.display.set_... |
from aiogram.utils.callback_data import CallbackData
main_callback = CallbackData('main', 'menu')
| [
"aiogram.utils.callback_data.CallbackData"
] | [((70, 98), 'aiogram.utils.callback_data.CallbackData', 'CallbackData', (['"""main"""', '"""menu"""'], {}), "('main', 'menu')\n", (82, 98), False, 'from aiogram.utils.callback_data import CallbackData\n')] |
from collections import namedtuple
Param = namedtuple('Param', ['name', 'display_name', 'type', 'required', 'default', 'choices'])
Param.__new__.__defaults__ = (None,) * len(Param._fields)
_FORMATTERS = {}
def formatter(name=None, params=[]):
def deco_func(func):
# 做注册工作
func_name = name if name e... | [
"collections.namedtuple"
] | [((44, 135), 'collections.namedtuple', 'namedtuple', (['"""Param"""', "['name', 'display_name', 'type', 'required', 'default', 'choices']"], {}), "('Param', ['name', 'display_name', 'type', 'required', 'default',\n 'choices'])\n", (54, 135), False, 'from collections import namedtuple\n')] |
"""
Author: <NAME>
Created On: 23 August 2017
"""
# To test if two rectangle intersect, we only have to find out
# if their projections intersect on all of the coordinate axes
import inspect
class Coord:
"""Coord
Class to initialize Coordinate of one point
"""
def __init__(self, x, y):
self... | [
"inspect.getsource"
] | [((1237, 1267), 'inspect.getsource', 'inspect.getsource', (['broad_phase'], {}), '(broad_phase)\n', (1254, 1267), False, 'import inspect\n')] |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
import pdb
class Model(nn.Module):
r"""Spatial temporal graph convolutional networks.
Args:
in_channels (int): Number of channels in the input data
num_class (int): Number... | [
"torch.nn.Sigmoid",
"torch.nn.ReLU",
"torch.nn.BatchNorm2d",
"torch.nn.Dropout",
"torch.nn.Conv2d",
"torch.transpose",
"numpy.sum",
"numpy.zeros",
"torch.tensor",
"torch.einsum",
"numpy.dot"
] | [((1411, 1423), 'numpy.sum', 'np.sum', (['A', '(0)'], {}), '(A, 0)\n', (1417, 1423), True, 'import numpy as np\n'), ((1467, 1497), 'numpy.zeros', 'np.zeros', (['(num_node, num_node)'], {}), '((num_node, num_node))\n', (1475, 1497), True, 'import numpy as np\n'), ((1664, 1701), 'numpy.zeros', 'np.zeros', (['(1, A.shape[... |
import os.path as osp
import numpy
import torch
from torch.nn import Sequential, Linear, ReLU, Sigmoid, Tanh, Dropout, Upsample
import torch.nn.functional as F
import torch.nn as nn
from torch_geometric.nn import NNConv, BatchNorm
import argparse
from torch.distributions import normal, kl
from torch_geometric.datasets ... | [
"warnings.filterwarnings",
"torch.autograd.set_detect_anomaly",
"torch.ones_like",
"torch.load",
"torch.nn.L1Loss",
"torch.stack",
"torch.nn.BCELoss",
"torch.normal",
"torch.zeros_like",
"torch.cuda.empty_cache"
] | [((783, 816), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (806, 816), False, 'import warnings\n'), ((929, 947), 'torch.nn.BCELoss', 'torch.nn.BCELoss', ([], {}), '()\n', (945, 947), False, 'import torch\n'), ((958, 975), 'torch.nn.L1Loss', 'torch.nn.L1Loss', ([], {}), '... |
import csv
from workflow_session.pipeline import lab, subject, session
def ingest_general(csvs, tables, skip_duplicates=True, verbose=True):
"""
Inserts data from a series of csvs into their corresponding table:
e.g., ingest_general(['./lab_data.csv', './proj_data.csv'],
... | [
"csv.DictReader",
"workflow_session.pipeline.lab.ProtocolType",
"workflow_session.pipeline.subject.Subject.Lab",
"workflow_session.pipeline.subject.SubjectDeath",
"workflow_session.pipeline.session.SessionExperimenter",
"workflow_session.pipeline.session.SessionNote",
"workflow_session.pipeline.subject.... | [((2859, 2868), 'workflow_session.pipeline.lab.Lab', 'lab.Lab', ([], {}), '()\n', (2866, 2868), False, 'from workflow_session.pipeline import lab, subject, session\n'), ((2878, 2892), 'workflow_session.pipeline.lab.Location', 'lab.Location', ([], {}), '()\n', (2890, 2892), False, 'from workflow_session.pipeline import ... |
import numpy as np
from scipy.signal import stft, istft
from scipy.io import wavfile
from Crypto.Cipher import AES
from Crypto.PublicKey import RSA
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA256
from Crypto.Util.Padding import pad, unpad
from Crypto.Util.strxor import strxor
import random
import s... | [
"numpy.abs",
"scipy.signal.stft",
"Crypto.Util.Padding.pad",
"numpy.angle",
"numpy.complex",
"numpy.array",
"Crypto.Signature.pkcs1_15.new",
"reedsolo.RSCodec",
"scipy.io.wavfile.read",
"scipy.io.wavfile.write",
"os.popen",
"numpy.cos",
"numpy.sin",
"Crypto.Util.strxor.strxor",
"numpy.ar... | [((382, 415), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (405, 415), False, 'import warnings\n'), ((5030, 5053), 'scipy.io.wavfile.read', 'wavfile.read', (['audiofile'], {}), '(audiofile)\n', (5042, 5053), False, 'from scipy.io import wavfile\n'), ((5119, 5187), 'scipy... |
import pkg_resources
import pytest
from pathlib import Path
from offspect.input.tms.cmep.mat import prepare_annotations, cut_traces
from offspect.api import populate, CacheFile
from matprot.convert.traces import is_matlab_installed
from subprocess import Popen, PIPE
import time
@pytest.mark.skipif(is_matlab_installed... | [
"offspect.input.tms.cmep.mat.prepare_annotations",
"pathlib.Path",
"time.sleep",
"offspect.api.CacheFile",
"offspect.api.populate",
"offspect.input.tms.cmep.mat.cut_traces",
"matprot.convert.traces.is_matlab_installed"
] | [((460, 561), 'offspect.input.tms.cmep.mat.prepare_annotations', 'prepare_annotations', (['xmlfile', 'matfile'], {'channel_of_interest': '"""EDC_L"""', 'pre_in_ms': '(100)', 'post_in_ms': '(100)'}), "(xmlfile, matfile, channel_of_interest='EDC_L',\n pre_in_ms=100, post_in_ms=100)\n", (479, 561), False, 'from offspec... |
import time
import numpy as np
import brainflow
from brainflow import BoardIds
from brainflow.board_shim import BoardShim, BrainFlowInputParams
class Board:
def __init__(self):
self.__board_ID = brainflow.board_shim.BoardIds(BoardIds.CYTON_BOARD)
self.__parameters = self.__setBoardParameters()
self.__bo... | [
"brainflow.board_shim.BoardShim.enable_dev_board_logger",
"brainflow.board_shim.BoardShim",
"brainflow.board_shim.BrainFlowInputParams",
"brainflow.board_shim.BoardIds",
"brainflow.board_shim.BoardShim.get_eeg_channels"
] | [((205, 256), 'brainflow.board_shim.BoardIds', 'brainflow.board_shim.BoardIds', (['BoardIds.CYTON_BOARD'], {}), '(BoardIds.CYTON_BOARD)\n', (234, 256), False, 'import brainflow\n'), ((561, 604), 'brainflow.board_shim.BoardShim.get_eeg_channels', 'BoardShim.get_eeg_channels', (['self.__board_ID'], {}), '(self.__board_ID... |
#!/usr/bin/env python3
"""What do you do when Python does not know about some exotic encoder or
decoder that exists out there? Suppose you have some text,
perhaps an e-mail message, that Python won't decode, saying::
LookupError: unknown encoding: ansi_x3.110-1983
What you do is tell Python to call some UNIX com... | [
"codecs.register",
"subprocess.Popen",
"codecs.CodecInfo"
] | [((17502, 17618), 'subprocess.Popen', 'subprocess.Popen', (['cmd'], {'env': "{'LANG': 'C'}", 'stdout': 'subprocess.PIPE', 'stdin': 'subprocess.PIPE', 'stderr': 'subprocess.PIPE'}), "(cmd, env={'LANG': 'C'}, stdout=subprocess.PIPE, stdin=\n subprocess.PIPE, stderr=subprocess.PIPE)\n", (17518, 17618), False, 'import s... |
from ttracker.model.messages.prompt_req import Prompt
class SubmitBlockersResp:
def __init__(self, content):
self.system_seat_ids = content['systemSeatIds']
self.msg_id = content['msgId']
self.game_state_id = content['gameStateId']
self.prompt = Prompt(content['prompt'])
sel... | [
"ttracker.model.messages.prompt_req.Prompt"
] | [((283, 308), 'ttracker.model.messages.prompt_req.Prompt', 'Prompt', (["content['prompt']"], {}), "(content['prompt'])\n", (289, 308), False, 'from ttracker.model.messages.prompt_req import Prompt\n')] |
#coding: utf-8
import re
from django.db.models import Q
from django.db import models
from django.conf import settings
from django.core import validators
from accounts.localflavor.br.br_states import STATE_CHOICES
from django.contrib.auth.models import (AbstractBaseUser, PermissionsMixin, UserManager)
cl... | [
"django.db.models.EmailField",
"django.db.models.OneToOneField",
"django.db.models.DateField",
"django.db.models.TextField",
"django.db.models.ForeignKey",
"django.db.models.IntegerField",
"re.compile",
"django.db.models.BooleanField",
"django.db.models.AutoField",
"django.db.models.DateTimeField"... | [((367, 459), 'django.db.models.AutoField', 'models.AutoField', ([], {'primary_key': '(True)', 'verbose_name': 'u"""Cod Account"""', 'db_column': '"""id_account"""'}), "(primary_key=True, verbose_name=u'Cod Account', db_column=\n 'id_account')\n", (383, 459), False, 'from django.db import models\n'), ((466, 552), 'd... |
from django.urls import path, include
from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns=[
path('register/', views.register, name='my_instagram-register'),
]
if settings.DEBUG:
urlpatterns+= static(settings.MEDIA_U... | [
"django.conf.urls.static.static",
"django.urls.path"
] | [((186, 249), 'django.urls.path', 'path', (['"""register/"""', 'views.register'], {'name': '"""my_instagram-register"""'}), "('register/', views.register, name='my_instagram-register')\n", (190, 249), False, 'from django.urls import path, include\n'), ((297, 358), 'django.conf.urls.static.static', 'static', (['settings... |
import torch
import argparse
import code
import prettytable
from termcolor import colored
from drqa import pipeline
from drqa.retriever import utils
# ------------------------------------------------------------------------------
# Drop in to interactive mode
# --------------------------------------------------------... | [
"prettytable.PrettyTable",
"termcolor.colored",
"drqa.pipeline.DrQA",
"torch.cuda.is_available",
"torch.cuda.set_device"
] | [((519, 598), 'prettytable.PrettyTable', 'prettytable.PrettyTable', (["['Rank', 'Answer', 'Doc', 'Answer Score', 'Doc Score']"], {}), "(['Rank', 'Answer', 'Doc', 'Answer Score', 'Doc Score'])\n", (542, 598), False, 'import prettytable\n'), ((2408, 2651), 'drqa.pipeline.DrQA', 'pipeline.DrQA', ([], {'cuda': 'args_cuda',... |