code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
from utilities import utilities
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.applicationinsights import ApplicationInsightsManagementClient
from azure.mgmt.applicationinsights.models import (
ApplicationInsightsComponent
)
def create_or_update(resource_name, resource_group_name, locati... | [
"azure.mgmt.applicationinsights.models.ApplicationInsightsComponent",
"azure.mgmt.applicationinsights.ApplicationInsightsManagementClient",
"utilities.utilities.get_credentials",
"azure.mgmt.resource.ResourceManagementClient"
] | [((373, 400), 'utilities.utilities.get_credentials', 'utilities.get_credentials', ([], {}), '()\n', (398, 400), False, 'from utilities import utilities\n'), ((433, 487), 'azure.mgmt.resource.ResourceManagementClient', 'ResourceManagementClient', (['credentials', 'subscription_id'], {}), '(credentials, subscription_id)\... |
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse, parse_qs
import os
from textwrap import dedent
from cowpy import cow
import json
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
""" sets a status code, sets headers, sets body, and end... | [
"textwrap.dedent",
"cowpy.cow.Bunny",
"urllib.parse.urlparse",
"cowpy.cow.DragonAndCow",
"json.dumps",
"urllib.parse.parse_qs"
] | [((361, 844), 'textwrap.dedent', 'dedent', (['"""\n <html>\n <head>\n <title> cowsay </title>\n </head>\n <body>\n <header>\n <nav>\n <ul>\n <li><a href="/cow">cowsay</a></li>\n </ul>\n </nav... |
# coding=utf-8
"""List filter test cases."""
import pytest
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.test import TestCase, override_settings
from django.urls import reverse
from acme.core.models import Customer
from acme.tests import new_... | [
"model_filters.models.FieldFilter.objects.create",
"django.contrib.auth.models.Permission.objects.get",
"django.contrib.contenttypes.models.ContentType.objects.get_for_model",
"acme.core.models.Customer.objects.create",
"django.test.override_settings",
"django.urls.reverse",
"model_filters.models.ModelF... | [((647, 689), 'acme.tests.new_user', 'new_user', ([], {'is_staff': '(True)', 'is_superuser': '(True)'}), '(is_staff=True, is_superuser=True)\n', (655, 689), False, 'from acme.tests import new_user\n'), ((749, 828), 'acme.core.models.Customer.objects.create', 'Customer.objects.create', ([], {'name': '"""<NAME>"""', 'mem... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import random
import psutil
import logging
import pandas as pd
import numpy as np
from io import open
from collections import Counter
from multiprocessing import cpu_count
from concurrent.futures import ProcessPoolExecutor
from scipy.sparse import csr... | [
"logging.getLogger",
"pdb.pm",
"pandas.read_csv",
"io.open",
"sys.stderr.isatty",
"multiprocessing.cpu_count",
"sys.__excepthook__",
"argparse.ArgumentParser",
"fastGraph.ngram.build_ngram",
"random.Random",
"fastGraph.graph.Graph",
"traceback.print_exception",
"gensim.models.Word2Vec",
"g... | [((882, 919), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': 'LOGFORMAT'}), '(format=LOGFORMAT)\n', (901, 919), False, 'import logging\n'), ((930, 960), 'logging.getLogger', 'logging.getLogger', (['"""fastGraph"""'], {}), "('fastGraph')\n", (947, 960), False, 'import logging\n'), ((706, 717), 'os.getpid'... |
from nose.tools import assert_equals, assert_true
from wikimetrics.metrics import metric_classes
from wikimetrics.models import SumAggregateByUserReport
from wikimetrics.models.storage.wikiuser import WikiUserKey
from wikimetrics.enums import Aggregation
from ..fixtures import DatabaseTest
class SumAggregateByUserRep... | [
"nose.tools.assert_true",
"wikimetrics.models.storage.wikiuser.WikiUserKey",
"wikimetrics.models.SumAggregateByUserReport",
"nose.tools.assert_equals"
] | [((551, 596), 'wikimetrics.models.SumAggregateByUserReport', 'SumAggregateByUserReport', (['self.cohort', 'metric'], {}), '(self.cohort, metric)\n', (575, 596), False, 'from wikimetrics.models import SumAggregateByUserReport\n'), ((1160, 1200), 'nose.tools.assert_true', 'assert_true', (['(Aggregation.SUM in finished)']... |
#!/usr/bin/env python3
#
# Copyright 2015 Google Inc. 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 requir... | [
"tarfile.open",
"yaml.load",
"setup.toolchain_specific_setup",
"re.search",
"utilities.log",
"codecs.decode",
"os.listdir",
"os.path.isdir",
"utilities.get_argparser",
"glob.glob",
"yaml.dump",
"re.sub",
"tempfile.TemporaryDirectory",
"shutil.chown",
"os.path.join",
"utilities.recursiv... | [((1417, 1432), 'utilities.get_argparser', 'get_argparser', ([], {}), '()\n', (1430, 1432), False, 'from utilities import get_argparser, log, timestamp, run_cmd\n'), ((1886, 1975), 'os.path.join', 'os.path.join', (['args.shared_directory', '"""get_base_package_names"""', '"""latest"""', '"""names.json"""'], {}), "(args... |
import argparse
parser = argparse.ArgumentParser(description='Oh Deyu.')
parser.add_argument('-i','--input', help='Input file name',required=True)
parser.add_argument('-o','--output',help='Output file name', required=True)
parser.add_argument('-n','--number',help='numer', required=True)
args = parser.parse_args()
targ... | [
"argparse.ArgumentParser"
] | [((26, 73), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Oh Deyu."""'}), "(description='Oh Deyu.')\n", (49, 73), False, 'import argparse\n')] |
from natas import ocr_builder
from mikatools import *
#from gensim.models import Word2Vec
#from gensim.models.keyedvectors import Word2VecKeyedVectors
import natas
print(natas.normalize_words(["seacreat", "wiþe"], n_best=5))
print(natas.ocr_correct_words(["paft", "friendlhip"]))
#print(natas.is_correctly_spelled("cat... | [
"natas.ocr_correct_words",
"natas.normalize_words"
] | [((171, 224), 'natas.normalize_words', 'natas.normalize_words', (["['seacreat', 'wiþe']"], {'n_best': '(5)'}), "(['seacreat', 'wiþe'], n_best=5)\n", (192, 224), False, 'import natas\n'), ((232, 279), 'natas.ocr_correct_words', 'natas.ocr_correct_words', (["['paft', 'friendlhip']"], {}), "(['paft', 'friendlhip'])\n", (2... |
#!/usr/bin/env python
"""
CREATED AT: 2021/8/17
Des:
https://leetcode.com/problems/count-good-nodes-in-binary-tree/
https://leetcode.com/explore/challenge/card/august-leetcoding-challenge-2021/615/week-3-august-15th-august-21st/3899/
GITHUB: https://github.com/Jiezhi/myleetcode
"""
# Definition for a binary tree node... | [
"collections.deque"
] | [((799, 818), 'collections.deque', 'collections.deque', ([], {}), '()\n', (816, 818), False, 'import collections\n')] |
"""
Views to create WorldMap layers by:
- Joining a tabular file to an existing layer OR
- Using Lat/Lng columns for mapping
"""
from django.http import HttpResponse
from django.views.decorators.http import require_POST
from gc_apps.geo_utils.message_helper_json import MessageHelperJSON, format_errors_as_text... | [
"logging.getLogger",
"gc_apps.gis_tabular.models.WorldMapTabularLayerInfo.build_from_worldmap_json",
"gc_apps.dv_notify.metadata_updater.MetadataUpdater.run_update_via_popen",
"gc_apps.geo_utils.message_helper_json.MessageHelperJSON.get_json_success_msg",
"gc_apps.gis_tabular.forms.ChooseSingleColumnForm",
... | [((1230, 1257), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1247, 1257), False, 'import logging\n'), ((2427, 2462), 'gc_apps.worldmap_connect.utils.get_geocode_types_and_join_layers', 'get_geocode_types_and_join_layers', ([], {}), '()\n', (2460, 2462), False, 'from gc_apps.worldmap_co... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
py_sep_sdk - Symantec Endpoint Protection Manager API Client Library
Copyright (C) 2019 <NAME> @greenpau
See LICENSE for licensing details
'''
from __future__ import (absolute_import, division, print_function)
import logging
import json
import requests
import urllib3... | [
"logging.getLogger",
"json.loads",
"logging.StreamHandler",
"requests.Session",
"logging.Formatter",
"py_sep_sdk.config.ClientConfiguration",
"urllib3.disable_warnings"
] | [((356, 382), 'urllib3.disable_warnings', 'urllib3.disable_warnings', ([], {}), '()\n', (380, 382), False, 'import urllib3\n'), ((591, 623), 'logging.getLogger', 'logging.getLogger', (['"""sepm-client"""'], {}), "('sepm-client')\n", (608, 623), False, 'import logging\n'), ((642, 665), 'logging.StreamHandler', 'logging.... |
"""
Render k8s templates from NIST format
"""
import sys
from os.path import abspath, dirname, join, normpath, isdir, isfile
from jinja2 import (Template,
Environment,
PackageLoader,
select_autoescape)
CURRENT_DIR = dirname(abspath(__file__))
# adding this pa... | [
"os.path.join",
"os.path.dirname",
"jinja2.select_autoescape",
"os.path.abspath",
"jinja2.PackageLoader"
] | [((445, 472), 'os.path.join', 'join', (['CURRENT_DIR', '"""output"""'], {}), "(CURRENT_DIR, 'output')\n", (449, 472), False, 'from os.path import abspath, dirname, join, normpath, isdir, isfile\n'), ((285, 302), 'os.path.abspath', 'abspath', (['__file__'], {}), '(__file__)\n', (292, 302), False, 'from os.path import ab... |
#!/usr/bin/env python3
import os
import sys
import argparse
import csv
import re
from dateutil import parser
import datetime
from abc import ABC, abstractmethod
import xlwt
import openpyxl
class Csv2XlsException(Exception):
pass
class ExcelWriter(ABC):
@abstractmethod
def add_sheet(self, wb, name):
... | [
"datetime.datetime",
"dateutil.parser.parse",
"dateutil.parser.parse_args",
"datetime.time",
"argparse.ArgumentParser",
"xlwt.XFStyle",
"dateutil.parser.add_argument",
"openpyxl.Workbook",
"csv.reader",
"os.path.basename",
"datetime.date",
"xlwt.Workbook",
"re.search"
] | [((4395, 4420), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (4418, 4420), False, 'import argparse\n'), ((4425, 4524), 'dateutil.parser.add_argument', 'parser.add_argument', (['"""-i"""', '"""--input-files"""'], {'nargs': '"""+"""', 'required': '(True)', 'help': '"""input excel files"""'}), "... |
import yaml
document = """
"name": "example_app"
"version": "1.0.0"
"main": "example_app/main.py"
"description": "A example structure for building projects cross-platform using kivy"
"license": "MIT"
"repository":
"type": "git"
"url": "<EMAIL>:VictorManhani/kivy_build.git"
"engines":
"python": "3.7.7"
... | [
"yaml.load"
] | [((388, 407), 'yaml.load', 'yaml.load', (['document'], {}), '(document)\n', (397, 407), False, 'import yaml\n')] |
# -*- coding: utf-8 -*-
import re
from mattermost_bot.bot import respond_to
@respond_to('(.*) added to the channel by (.*)', re.IGNORECASE)
def added_to_channel(message, myname, channel_admin):
message.reply('Hi, %s. I am %s. Glad to join this channel :) ' % (channel_admin, myname))
added_to_channel.__doc__ = ... | [
"mattermost_bot.bot.respond_to"
] | [((81, 143), 'mattermost_bot.bot.respond_to', 'respond_to', (['"""(.*) added to the channel by (.*)"""', 're.IGNORECASE'], {}), "('(.*) added to the channel by (.*)', re.IGNORECASE)\n", (91, 143), False, 'from mattermost_bot.bot import respond_to\n')] |
# coding=utf-8
import sys
import os
import csv
from datetime import datetime, timedelta
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.dates import drange
from matplotlib.patches import Rectangle
import scenario_factory
# http://www.javascripter.net/faq/hextorgb.htm
PRIMA = (148/256, 164/256, 1... | [
"matplotlib.patches.Rectangle",
"numpy.repeat",
"numpy.roll",
"numpy.ma.array",
"os.path.join",
"numpy.array",
"os.path.dirname",
"numpy.zeros",
"os.path.isdir",
"datetime.timedelta",
"numpy.load",
"csv.reader",
"matplotlib.pyplot.subplots",
"scenario_factory.Scenario",
"matplotlib.pyplo... | [((1295, 1318), 'numpy.ma.array', 'np.ma.array', (['P_el_sched'], {}), '(P_el_sched)\n', (1306, 1318), True, 'import numpy as np\n'), ((1331, 1349), 'numpy.array', 'np.array', (['sc.block'], {}), '(sc.block)\n', (1339, 1349), True, 'import numpy as np\n'), ((1723, 1751), 'numpy.repeat', 'np.repeat', (['P_el_ctrl[:-1]',... |
"""Functions for transforming raw data about the films into csv"""
from typing import List, Tuple
import pandas as pd
def extract_info(line: str):
"""
Extract information from raw string with information
about the film: title, year and location. If data is
invalid, return None.
"""
try:
... | [
"pandas.DataFrame"
] | [((1971, 2028), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {'columns': "['Title', 'Year', 'Location']"}), "(data, columns=['Title', 'Year', 'Location'])\n", (1983, 2028), True, 'import pandas as pd\n')] |
from defs import *
def main() -> None:
"""
Main game logic loop shim.
"""
from providers import cpucheck
cpucheck.instantiate()
if cpucheck.is_over_limit():
return
import logic
logic.main()
module.exports.loop = main
| [
"providers.cpucheck.instantiate",
"logic.main",
"providers.cpucheck.is_over_limit"
] | [((128, 150), 'providers.cpucheck.instantiate', 'cpucheck.instantiate', ([], {}), '()\n', (148, 150), False, 'from providers import cpucheck\n'), ((159, 183), 'providers.cpucheck.is_over_limit', 'cpucheck.is_over_limit', ([], {}), '()\n', (181, 183), False, 'from providers import cpucheck\n'), ((222, 234), 'logic.main'... |
import discord
import random
def create_embed(text):
embed=discord.Embed(description=text,color=discord.Color.blurple())
return embed
def error_embed(text):
embed=discord.Embed(description=text,color=discord.Color.red())
return embed
| [
"discord.Color.blurple",
"discord.Color.red"
] | [((105, 128), 'discord.Color.blurple', 'discord.Color.blurple', ([], {}), '()\n', (126, 128), False, 'import discord\n'), ((224, 243), 'discord.Color.red', 'discord.Color.red', ([], {}), '()\n', (241, 243), False, 'import discord\n')] |
import pybullet as p
import time
p.connect(p.PhysX)
p.loadPlugin("eglRendererPlugin")
p.loadURDF("plane.urdf")
for i in range (50):
p.loadURDF("r2d2.urdf",[0,0,1+i*2])
p.setGravity(0,0,-10)
while (1):
p.stepSimulation()
time.sleep(1./240.) | [
"pybullet.connect",
"pybullet.setGravity",
"time.sleep",
"pybullet.stepSimulation",
"pybullet.loadURDF",
"pybullet.loadPlugin"
] | [((34, 52), 'pybullet.connect', 'p.connect', (['p.PhysX'], {}), '(p.PhysX)\n', (43, 52), True, 'import pybullet as p\n'), ((53, 86), 'pybullet.loadPlugin', 'p.loadPlugin', (['"""eglRendererPlugin"""'], {}), "('eglRendererPlugin')\n", (65, 86), True, 'import pybullet as p\n'), ((88, 112), 'pybullet.loadURDF', 'p.loadURD... |
# 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
fro... | [
"pulumi.get",
"pulumi.Alias",
"pulumi.getter",
"pulumi.set",
"pulumi.ResourceOptions",
"pulumi.ResourceOptions.merge"
] | [((3810, 3839), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""hubName"""'}), "(name='hubName')\n", (3823, 3839), False, 'import pulumi\n'), ((4118, 4169), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""participantPropertyReferences"""'}), "(name='participantPropertyReferences')\n", (4131, 4169), False, 'impo... |
"""
Database connection and sessions
"""
from sqlalchemy.engine.url import URL
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.interfaces import PoolListener
from igcweight import settings
__engine_url = {'drivername': settings.DB_ENGINE, 'query': settings.DB_ARGS}
if se... | [
"sqlalchemy.orm.sessionmaker",
"sqlalchemy.engine.url.URL"
] | [((1000, 1041), 'sqlalchemy.orm.sessionmaker', 'sessionmaker', ([], {'bind': 'engine', 'autoflush': '(True)'}), '(bind=engine, autoflush=True)\n', (1012, 1041), False, 'from sqlalchemy.orm import sessionmaker\n'), ((877, 896), 'sqlalchemy.engine.url.URL', 'URL', ([], {}), '(**__engine_url)\n', (880, 896), False, 'from ... |
#!/usr/bin/env python3
import os
import sys
import copy
import re
import importlib
import numpy as np
import rclpy
from rclpy.qos import qos_profile_sensor_data
from rclpy.node import Node
from rclpy.exceptions import ParameterNotDeclaredException
from rcl_interfaces.msg import Parameter
from rcl_interfaces.msg import ... | [
"rcl_interfaces.msg.ParameterDescriptor",
"rclpy.spin",
"cv_bridge.CvBridge",
"rclpy.init",
"rclpy.shutdown"
] | [((2647, 2668), 'rclpy.init', 'rclpy.init', ([], {'args': 'args'}), '(args=args)\n', (2657, 2668), False, 'import rclpy\n'), ((2702, 2718), 'rclpy.spin', 'rclpy.spin', (['node'], {}), '(node)\n', (2712, 2718), False, 'import rclpy\n'), ((2723, 2739), 'rclpy.shutdown', 'rclpy.shutdown', ([], {}), '()\n', (2737, 2739), F... |
import binaryCode as bc
import pyperclip
import time
a = input("encode, decode, or make a key[e/d/m]?\n")
if a == "e":
bc.encode(input("what text?\n"), input("what key?\n"))
print("file saved as photo.jpeg.\nRename for extra security.")
elif a == "d":
print(bc.decode(input("what key?\n"), input("filename?\n... | [
"time.sleep",
"binaryCode.generateKey"
] | [((487, 500), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (497, 500), False, 'import time\n'), ((389, 410), 'binaryCode.generateKey', 'bc.generateKey', (['(False)'], {}), '(False)\n', (403, 410), True, 'import binaryCode as bc\n')] |
# -*- coding: utf-8 -*-
'''
Created on Mar 20, 2011
@author: <NAME>
@copyright: Copyright © 2011
other contributers:
'''
from django import forms
from django.utils.translation import ugettext, ugettext_lazy as _
from calendars.models.cals import Occurrence
class OccurrenceForm(forms.ModelForm):
start = forms.D... | [
"django.utils.translation.ugettext_lazy",
"django.forms.DateTimeField"
] | [((313, 334), 'django.forms.DateTimeField', 'forms.DateTimeField', ([], {}), '()\n', (332, 334), False, 'from django import forms\n'), ((345, 366), 'django.forms.DateTimeField', 'forms.DateTimeField', ([], {}), '()\n', (364, 366), False, 'from django import forms\n'), ((631, 679), 'django.utils.translation.ugettext_laz... |
#!/usr/bin/env python
import argparse
import logging
import pymongo
from logger import setup_logger
def database(connection_string, db_name):
"""Connect to mongodb."""
client = pymongo.MongoClient(connection_string)
return client[db_name]
def move_notes(db, collection, source_id, source, dest, dry_run... | [
"argparse.ArgumentParser",
"logger.setup_logger",
"pymongo.UpdateMany",
"pymongo.MongoClient",
"logging.info"
] | [((189, 227), 'pymongo.MongoClient', 'pymongo.MongoClient', (['connection_string'], {}), '(connection_string)\n', (208, 227), False, 'import pymongo\n'), ((618, 705), 'logging.info', 'logging.info', (['f"""Moving values from {source} to {dest} in collection: {collection}"""'], {}), "(\n f'Moving values from {source}... |
import contextlib
import logging
import socket
import sys
import docker
import yaml
import ip_utils
client = docker.from_env()
logging.basicConfig(level=logging.INFO)
log = logging.getLogger('netz')
def compose_name():
""" HACK (?) getting the compose project this container belongs to. """
me = socket.get... | [
"logging.basicConfig",
"docker.from_env",
"socket.gethostname",
"logging.getLogger"
] | [((112, 129), 'docker.from_env', 'docker.from_env', ([], {}), '()\n', (127, 129), False, 'import docker\n'), ((131, 170), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (150, 170), False, 'import logging\n'), ((177, 202), 'logging.getLogger', 'logging.getLogger'... |
#Program to fetch the http status code give the url/api
from urllib.request import urlopen
from urllib.error import URLError, HTTPError
import emoji
#Taking input url from user
requestURL = input("Enter the URL to be invoked: ")
#Gets the response from URL and prints the status code and message accordingly
try:
r... | [
"urllib.request.urlopen"
] | [((330, 349), 'urllib.request.urlopen', 'urlopen', (['requestURL'], {}), '(requestURL)\n', (337, 349), False, 'from urllib.request import urlopen\n')] |
import re
import torch
from torchvision import transforms
import users.neural_transfer.utils as utils
from users.neural_transfer.transformer_net import TransformerNet
from users.neural_transfer.vgg import Vgg16
def stylize(image):
device = torch.device('cpu')
content_image = utils.load_image(image)
content_tran... | [
"re.search",
"torch.load",
"users.neural_transfer.transformer_net.TransformerNet",
"users.neural_transfer.utils.save_image",
"users.neural_transfer.utils.load_image",
"torch.no_grad",
"torchvision.transforms.ToTensor",
"torch.device"
] | [((245, 264), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (257, 264), False, 'import torch\n'), ((283, 306), 'users.neural_transfer.utils.load_image', 'utils.load_image', (['image'], {}), '(image)\n', (299, 306), True, 'import users.neural_transfer.utils as utils\n'), ((1010, 1050), 'users.neural_... |
from scapy.all import *
from scapy.layers.dns import DNSQR, DNS, DNSRR
from scapy.layers.inet import IP, UDP
def dnsSpoof(packet):
spoofDNS = '192.168.0.7'
dstip = packet[IP].src
srcip = packet[IP].dst
sport = packet[UDP].sport
dport = packet[UDP].dport
if packet.haslayer(DNSQR):
dnsi... | [
"scapy.layers.dns.DNS",
"scapy.layers.dns.DNSRR",
"scapy.layers.inet.UDP",
"scapy.layers.inet.IP"
] | [((383, 429), 'scapy.layers.dns.DNSRR', 'DNSRR', ([], {'rrname': 'qd.qname', 'ttl': '(10)', 'rdata': 'spoofDNS'}), '(rrname=qd.qname, ttl=10, rdata=spoofDNS)\n', (388, 429), False, 'from scapy.layers.dns import DNSQR, DNS, DNSRR\n'), ((534, 576), 'scapy.layers.dns.DNS', 'DNS', ([], {'id': 'dnsid', 'qd': 'qd', 'aa': '(1... |
import sqlite3
import json
import logging
from ryu.app.wsgi import ControllerBase, WSGIApplication, route
from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller.handler import MAIN_DISPATCHER, CONFIG_DISPATCHER, DEAD_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.of... | [
"ryu.lib.packet.packet.Packet",
"json.loads",
"logging.debug",
"ryu.app.wsgi.route",
"sqlite3.connect",
"json.dumps",
"ryu.controller.handler.set_ev_cls",
"webob.Response"
] | [((519, 548), 'sqlite3.connect', 'sqlite3.connect', (['"""nfv.sqlite"""'], {}), "('nfv.sqlite')\n", (534, 548), False, 'import sqlite3\n'), ((6145, 6198), 'ryu.app.wsgi.route', 'route', (['"""hello"""', '"""/{greeting}/{name}"""'], {'methods': "['GET']"}), "('hello', '/{greeting}/{name}', methods=['GET'])\n", (6150, 61... |
"""
This module tests nipy's uses of aliased sympy expressions.
That is, sympy.Function's whose value is an arbitrary callable.
In these tests, the callable's are scipy.interpolate.interp1d instances
representing approximations to Brownian Motions.
"""
import numpy as np
import scipy.interpolate
import pylab
import ... | [
"numpy.random.standard_normal",
"numpy.sqrt",
"numpy.arange",
"nipy.modalities.fmri.aliased._add_aliases_to_namespace",
"sympy.lambdify",
"numpy.exp",
"nipy.modalities.fmri.formula.aliased_function",
"numpy.cumsum",
"sympy.DeferredVector"
] | [((411, 432), 'numpy.arange', 'np.arange', (['(0)', '(5)', '(0.01)'], {}), '(0, 5, 0.01)\n', (420, 432), True, 'import numpy as np\n'), ((439, 472), 'numpy.random.standard_normal', 'np.random.standard_normal', (['(500,)'], {}), '((500,))\n', (464, 472), True, 'import numpy as np\n'), ((633, 665), 'nipy.modalities.fmri.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import sys
import jsbeautifier
from bs4 import BeautifulSoup
from django.apps import apps
from django.conf import settings
from django.template.loader import render_to_string
from editorconfig import PathError
def flatten(lst: []) -> []:
if not is... | [
"os.makedirs",
"jsbeautifier.set_file_editorconfig_opts",
"jsbeautifier.default_options",
"os.path.join",
"os.getcwd",
"bs4.BeautifulSoup",
"django.apps.apps.get_containing_app_config",
"re.sub",
"re.findall",
"jsbeautifier.beautify",
"django.template.loader.render_to_string",
"sys.stdout.writ... | [((979, 1014), 'django.template.loader.render_to_string', 'render_to_string', (['template', 'context'], {}), '(template, context)\n', (995, 1014), False, 'from django.template.loader import render_to_string\n'), ((1029, 1059), 'jsbeautifier.default_options', 'jsbeautifier.default_options', ([], {}), '()\n', (1057, 1059... |
import fnmatch
import logging
import os
import select
import signal
import subprocess
import tempfile
import time
from threading import Lock
from easyprocess import EasyProcess, EasyProcessError
from pyvirtualdisplay import xauth
from pyvirtualdisplay.util import get_helptext, py2
# try:
# import fcntl
# except ... | [
"logging.getLogger",
"time.sleep",
"pyvirtualdisplay.xauth.call",
"os.read",
"pyvirtualdisplay.util.py2",
"os.remove",
"os.kill",
"os.listdir",
"pyvirtualdisplay.xauth.generate_mcookie",
"threading.Lock",
"subprocess.Popen",
"select.select",
"os.close",
"os.path.isfile",
"time.time",
"... | [((363, 369), 'threading.Lock', 'Lock', ([], {}), '()\n', (367, 369), False, 'from threading import Lock\n'), ((377, 404), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (394, 404), False, 'import logging\n'), ((816, 843), 'fnmatch.filter', 'fnmatch.filter', (['ls', 'pattern'], {}), '(ls,... |
"""
test_http_auth_detect.py
Copyright 2012 <NAME>
This file is part of w3af, http://w3af.org/ .
w3af is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.
w3af is distributed in the hope th... | [
"w3af.core.data.kb.knowledge_base.kb.cleanup",
"w3af.core.data.kb.knowledge_base.kb.get",
"w3af.core.data.url.HTTPResponse.HTTPResponse",
"w3af.core.data.parsers.doc.url.URL",
"w3af.core.data.request.fuzzable_request.FuzzableRequest",
"w3af.plugins.grep.http_auth_detect.http_auth_detect"
] | [((1147, 1174), 'w3af.core.data.parsers.doc.url.URL', 'URL', (['"""http://www.w3af.com/"""'], {}), "('http://www.w3af.com/')\n", (1150, 1174), False, 'from w3af.core.data.parsers.doc.url import URL\n'), ((1268, 1307), 'w3af.core.data.request.fuzzable_request.FuzzableRequest', 'FuzzableRequest', (['self.url'], {'method'... |
from __future__ import absolute_import
import os
import logging
try:
from urllib import urlopen # py2
except ImportError:
from urllib.request import urlopen # py3
from traitlets import (
observe,
Bool, Bytes, Dict, Instance, Int, List, TraitError, Unicode, validate
)
from ipywidgets import DOMWidget, ... | [
"logging.getLogger",
"traitlets.Unicode",
"traitlets.Bytes",
"traitlets.default",
"traitlets.Dict",
"traitlets.Instance",
"os.path.splitext",
"traitlets.observe",
"traitlets.TraitError",
"traitlets.validate",
"traitlets.Int",
"ipywidgets.Image",
"urllib.request.urlopen",
"traitlets.Bool"
] | [((492, 527), 'logging.getLogger', 'logging.getLogger', (['"""jupyter-webrtc"""'], {}), "('jupyter-webrtc')\n", (509, 527), False, 'import logging\n'), ((1752, 1771), 'traitlets.validate', 'validate', (['"""max_fps"""'], {}), "('max_fps')\n", (1760, 1771), False, 'from traitlets import observe, Bool, Bytes, Dict, Insta... |
import numpy
from chainer import functions
from chainer import testing
@testing.parameterize(*(testing.product({
'batchsize': [1, 5],
'size': [10, 20],
'dtype': [numpy.float32],
'eps': [1e-5, 1e-1],
})))
@testing.inject_backend_tests(
None,
# CPU tests
[
{},
]
# GPU tests
... | [
"numpy.mean",
"numpy.prod",
"numpy.sqrt",
"chainer.functions.layer_normalization",
"chainer.testing.run_module",
"numpy.square",
"chainer.testing.product",
"numpy.expand_dims",
"numpy.random.uniform"
] | [((2133, 2171), 'chainer.testing.run_module', 'testing.run_module', (['__name__', '__file__'], {}), '(__name__, __file__)\n', (2151, 2171), False, 'from chainer import testing\n'), ((1658, 1694), 'numpy.mean', 'numpy.mean', (['x'], {'axis': '(1)', 'keepdims': '(True)'}), '(x, axis=1, keepdims=True)\n', (1668, 1694), Fa... |
import matse_stundenplan
matse_stundenplan.run() | [
"matse_stundenplan.run"
] | [((26, 49), 'matse_stundenplan.run', 'matse_stundenplan.run', ([], {}), '()\n', (47, 49), False, 'import matse_stundenplan\n')] |
import subprocess
import tempfile
import unittest
COMMON_SUBPROCESS_ARGS = {
'timeout': 5,
'stdout': subprocess.PIPE,
'universal_newlines': True
}
class TestCommandLineInterface(unittest.TestCase):
def test_simple_invocation(self):
"""Test simple execution: read from stdin, write to stdout""... | [
"subprocess.run",
"tempfile.NamedTemporaryFile"
] | [((340, 473), 'subprocess.run', 'subprocess.run', (["['python3', '-m', 'hasami.cli']"], {'input': '"""これは単純な文です。\nこれが最初の文です。これは二番目の文です。これが最後の文です。"""'}), '([\'python3\', \'-m\', \'hasami.cli\'], **COMMON_SUBPROCESS_ARGS,\n input="""これは単純な文です。\nこれが最初の文です。これは二番目の文です。これが最後の文です。""")\n', (354, 473), False, 'import subproc... |
import random
from vindinium.bots import RawBot
__all__ = ['RandomBot']
class RandomBot(RawBot):
'''Random bot.'''
def move(self):
return random.choice(['Stay', 'North', 'West', 'East', 'South']) | [
"random.choice"
] | [((161, 218), 'random.choice', 'random.choice', (["['Stay', 'North', 'West', 'East', 'South']"], {}), "(['Stay', 'North', 'West', 'East', 'South'])\n", (174, 218), False, 'import random\n')] |
import numpy as np
import pandas as pd
array = [1,3,4,7,8,10,15]
np_array = np.array(array)
print("Arranjo NumPy")
print(np_array)
print("Convertendo para serie Pandas")
ds_array = pd.Series(np_array)
print("Serie Pandas")
print(ds_array) | [
"pandas.Series",
"numpy.array"
] | [((78, 93), 'numpy.array', 'np.array', (['array'], {}), '(array)\n', (86, 93), True, 'import numpy as np\n'), ((186, 205), 'pandas.Series', 'pd.Series', (['np_array'], {}), '(np_array)\n', (195, 205), True, 'import pandas as pd\n')] |
from rich.console import Console
from rich.table import Table
def print_table(gss: tuple, fib: tuple) -> None:
console = Console()
table = Table(title='Find Function Extremum')
table.add_column('Method name', justify='right', style='cyan', no_wrap=True)
table.add_column('function in Xm value', style='... | [
"rich.console.Console",
"rich.table.Table"
] | [((127, 136), 'rich.console.Console', 'Console', ([], {}), '()\n', (134, 136), False, 'from rich.console import Console\n'), ((149, 186), 'rich.table.Table', 'Table', ([], {'title': '"""Find Function Extremum"""'}), "(title='Find Function Extremum')\n", (154, 186), False, 'from rich.table import Table\n')] |
# time_count.py
from webpie import WPApp, WPHandler
import time
class Handler(WPHandler):
def time(self, request, relpath):
return "[%d]: %s\n" % (self.App.bump_counter(), time.ctime()), "text/plain"
class App(WPApp):
def __init__(self, h... | [
"time.ctime",
"webpie.WPApp.__init__"
] | [((343, 378), 'webpie.WPApp.__init__', 'WPApp.__init__', (['self', 'handler_class'], {}), '(self, handler_class)\n', (357, 378), False, 'from webpie import WPApp, WPHandler\n'), ((248, 260), 'time.ctime', 'time.ctime', ([], {}), '()\n', (258, 260), False, 'import time\n')] |
from warehouse_item import warehouse_item
import csv
import datetime
log_file_path = "YOUR_FILE_PATH_HERE"
storage_file_path = "YOUR_FILE_PATH_HERE"
def reg_new_item(name, description, qr_code_id):
date_registered = ""
time_registered = ""
if item_already_exists(qr_code_id):
print("Can't regis... | [
"datetime.datetime.now",
"datetime.date.today",
"csv.writer",
"csv.reader"
] | [((893, 934), 'csv.reader', 'csv.reader', (['warehouse_file'], {'delimiter': '""","""'}), "(warehouse_file, delimiter=',')\n", (903, 934), False, 'import csv\n'), ((440, 461), 'datetime.date.today', 'datetime.date.today', ([], {}), '()\n', (459, 461), False, 'import datetime\n'), ((463, 486), 'datetime.datetime.now', '... |
import math
import time
last = 10000
found = 1 # because we skip 2, the only even prime number
start = time.monotonic()
print('Prime numbers to {}'.format(last))
# print('2',end='')
def check(number):
prime = 1
f = 1.5
g = int(math.sqrt(number))+1
for divider in range(2, g):
f = number/divid... | [
"time.monotonic",
"math.sqrt"
] | [((106, 122), 'time.monotonic', 'time.monotonic', ([], {}), '()\n', (120, 122), False, 'import time\n'), ((510, 526), 'time.monotonic', 'time.monotonic', ([], {}), '()\n', (524, 526), False, 'import time\n'), ((243, 260), 'math.sqrt', 'math.sqrt', (['number'], {}), '(number)\n', (252, 260), False, 'import math\n')] |
"""
Some meta networks
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from utils.quantize import Function_STE, Function_BWN
from utils.miscellaneous import progress_bar
from utils.quantize import quantized_CNN, quantized_Linear
import utils.global_var as gVar
meta_count = 0
class... | [
"torch.tanh",
"torch.nn.ReLU",
"torch.nn.Tanh",
"torch.nn.LSTM",
"torch.nn.Sequential",
"torch.load",
"torch.max",
"torch.nn.BatchNorm1d",
"torch.save",
"torch.nn.Linear",
"torch.nn.functional.relu",
"torch.rand",
"torch.ones"
] | [((6281, 6378), 'torch.save', 'torch.save', (["{'model': net, 'hidden_size': 100, 'nonlinear': 'None'}", '"""./Results/meta_net.pkl"""'], {}), "({'model': net, 'hidden_size': 100, 'nonlinear': 'None'},\n './Results/meta_net.pkl')\n", (6291, 6378), False, 'import torch\n'), ((6452, 6488), 'torch.load', 'torch.load', ... |
# Copyright 2022 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | [
"cunumeric.indices",
"numpy.indices",
"pytest.main",
"numpy.array_equal",
"random.randint"
] | [((861, 883), 'numpy.indices', 'np.indices', (['dimensions'], {}), '(dimensions)\n', (871, 883), True, 'import numpy as np\n'), ((897, 919), 'cunumeric.indices', 'cn.indices', (['dimensions'], {}), '(dimensions)\n', (907, 919), True, 'import cunumeric as cn\n'), ((931, 961), 'numpy.array_equal', 'np.array_equal', (['np... |
from django.db import models
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import post_save
from django.urls import reverse
from config.utils import notify_slack
from random import random
... | [
"django.db.models.FloatField",
"django.db.models.Manager",
"django.contrib.contenttypes.models.ContentType.objects.get_for_model",
"django.db.models.DateField",
"django.db.models.ForeignKey",
"django.db.models.IntegerField",
"django.db.models.signals.post_save.connect",
"config.utils.notify_slack",
... | [((2269, 2324), 'django.db.models.signals.post_save.connect', 'post_save.connect', (['notify_assignment'], {'sender': 'Assignment'}), '(notify_assignment, sender=Assignment)\n', (2286, 2324), False, 'from django.db.models.signals import post_save\n'), ((491, 520), 'django.db.models.SlugField', 'models.SlugField', ([], ... |
from typing import Optional
from Core.ConfigHandler import ConfigHandler
from FlexioFlow.Options import Options
from FlexioFlow.StateHandler import StateHandler
from VersionControlProvider.Issuer import Issuer
from VersionControlProvider.IssuerFactory import IssuerFactory
from VersionControlProvider.Issuers import Iss... | [
"VersionControlProvider.IssuerFactory.IssuerFactory.build"
] | [((756, 844), 'VersionControlProvider.IssuerFactory.IssuerFactory.build', 'IssuerFactory.build', (['self.state_handler', 'self.config_handler', 'issuers', 'self.options'], {}), '(self.state_handler, self.config_handler, issuers, self.\n options)\n', (775, 844), False, 'from VersionControlProvider.IssuerFactory impor... |
import tensorflow as tf
import numpy as np
import os
import imageio
from utils import get_shardsize, get_zeros_array
def resize(image, target_shape):
imdtype = image.dtype
with tf.device('/CPU:0'):
image = tf.image.resize(image, target_shape[:2]).numpy()
assert image.shape == target_shape
retur... | [
"tensorflow.device",
"os.listdir",
"imageio.imread",
"tensorflow.image.resize",
"os.path.join",
"os.path.isfile",
"os.path.isdir",
"tensorflow.constant",
"os.mkdir",
"numpy.concatenate",
"numpy.expand_dims",
"utils.get_zeros_array",
"utils.get_shardsize",
"numpy.save"
] | [((2888, 2912), 'os.path.isfile', 'os.path.isfile', (['writedir'], {}), '(writedir)\n', (2902, 2912), False, 'import os\n'), ((3406, 3433), 'utils.get_shardsize', 'get_shardsize', (['target_shape'], {}), '(target_shape)\n', (3419, 3433), False, 'from utils import get_shardsize, get_zeros_array\n'), ((3454, 3483), 'util... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2018-07-05 19:05
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bot', '0025_auto_20180705_1839'),
]
operations = [
migrations.AddField(
... | [
"django.db.models.IntegerField"
] | [((395, 425), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'default': '(1)'}), '(default=1)\n', (414, 425), False, 'from django.db import migrations, models\n')] |
__author__ = "<NAME> (Protein Data Bank in Europe; http://pdbe.org)"
__date__ = "$17-Aug-2013 12:39:18$"
import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
def get_version(rel_path):
for line in read(rel_path).splitlines... | [
"os.path.dirname",
"setuptools.find_packages"
] | [((869, 939), 'setuptools.find_packages', 'find_packages', (['"""src"""'], {'exclude': "['*.test', '*.test.*', 'test.*', 'test']"}), "('src', exclude=['*.test', '*.test.*', 'test.*', 'test'])\n", (882, 939), False, 'from setuptools import setup, find_packages\n'), ((208, 233), 'os.path.dirname', 'os.path.dirname', (['_... |
import os
from channels.routing import ProtocolTypeRouter
from django.core.asgi import get_asgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
application = ProtocolTypeRouter(
{
"http": get_asgi_application(),
# Just HTTP for now. (We can add other protocols late... | [
"os.environ.setdefault",
"django.core.asgi.get_asgi_application"
] | [((110, 177), 'os.environ.setdefault', 'os.environ.setdefault', (['"""DJANGO_SETTINGS_MODULE"""', '"""project.settings"""'], {}), "('DJANGO_SETTINGS_MODULE', 'project.settings')\n", (131, 177), False, 'import os\n'), ((235, 257), 'django.core.asgi.get_asgi_application', 'get_asgi_application', ([], {}), '()\n', (255, 2... |
from bitarray import bitarray
from PIL import Image
image = Image.open('knowit_03.png')
red, *_ = image.split()
bits = [x & 1 for x in red.tobytes()]
#byte_string, *_ = bitarray(bits, endian='little').tobytes().partition(b'\0')
#result = byte_string.decode('ascii')
print(bitarray(bits, endian='little').tobytes()) | [
"PIL.Image.open",
"bitarray.bitarray"
] | [((61, 88), 'PIL.Image.open', 'Image.open', (['"""knowit_03.png"""'], {}), "('knowit_03.png')\n", (71, 88), False, 'from PIL import Image\n'), ((275, 306), 'bitarray.bitarray', 'bitarray', (['bits'], {'endian': '"""little"""'}), "(bits, endian='little')\n", (283, 306), False, 'from bitarray import bitarray\n')] |
from Statistics.ZScore import zscore
from Statistics.Mean import mean
from Statistics.StandardDeviation import standard_deviation
from Calculator.Subtraction import subtraction
from Calculator.Division import division
from Calculator.Multiplication import multiplication
from Calculator.Addition import addition
def po... | [
"Statistics.ZScore.zscore"
] | [((381, 396), 'Statistics.ZScore.zscore', 'zscore', (['numbers'], {}), '(numbers)\n', (387, 396), False, 'from Statistics.ZScore import zscore\n'), ((405, 421), 'Statistics.ZScore.zscore', 'zscore', (['numbers1'], {}), '(numbers1)\n', (411, 421), False, 'from Statistics.ZScore import zscore\n')] |
from flask import render_template, url_for, request, Flask
from app import app
import pandas as pd
from flaskext.mysql import MySQL
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
plt.switch_backend('agg')
import numpy as np
import operator # sorting dictionary
import random
import string
########... | [
"flask.render_template",
"flask.request.args.get",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.switch_backend",
"flaskext.mysql.MySQL",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.close",
"app.app.route",
"matplotlib.pyplot.scatter",
"random.choice",
"matplotlib... | [((201, 226), 'matplotlib.pyplot.switch_backend', 'plt.switch_backend', (['"""agg"""'], {}), "('agg')\n", (219, 226), True, 'import matplotlib.pyplot as plt\n'), ((405, 412), 'flaskext.mysql.MySQL', 'MySQL', ([], {}), '()\n', (410, 412), False, 'from flaskext.mysql import MySQL\n'), ((823, 837), 'app.app.route', 'app.r... |
# vim: set ff=unix expandtab ts=4 sw=4:
from copy import deepcopy
from .TsTpMassFields import TsTpMassFieldsPerPool
class CompatibleTsTpMassFieldsPerPool(TsTpMassFieldsPerPool):
# This class is a list of mass Distributions with an entry for every
# pool
def __init__(self, normal_list):
# make sur... | [
"copy.deepcopy"
] | [((1860, 1874), 'copy.deepcopy', 'deepcopy', (['self'], {}), '(self)\n', (1868, 1874), False, 'from copy import deepcopy\n')] |
"""
An app script to run registration between two cameras from the command line.
Copyright (C) Microsoft Corporation. All rights reserved.
"""
# Standard Libraries.
import argparse
# Calibration tools.
from camera_tools import register
# ------------------------------------------------------------------------------... | [
"camera_tools.register",
"argparse.ArgumentParser"
] | [((499, 565), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Get extrinsics for cameras."""'}), "(description='Get extrinsics for cameras.')\n", (522, 565), False, 'import argparse\n'), ((1400, 1493), 'camera_tools.register', 'register', (['args.img_a', 'args.img_b', 'args.template', 'ar... |
#!/usr/bin/env python3
from shutil import which
import sys
def check_program_exists(program):
if which(program) is None:
print('ERROR: Could not find {}. Is it installed? Is PATH setup properly?'.format(program))
sys.exit() | [
"shutil.which",
"sys.exit"
] | [((104, 118), 'shutil.which', 'which', (['program'], {}), '(program)\n', (109, 118), False, 'from shutil import which\n'), ((236, 246), 'sys.exit', 'sys.exit', ([], {}), '()\n', (244, 246), False, 'import sys\n')] |
import params
import numpy as np
def calc_min_delta_t(delta_x, alpha, v_max) -> int:
return min(1, 1 / 4 * delta_x ** 2 / alpha, delta_x / v_max)
def adjust_boundary(T, v_x, v_y):
T[0, :] = params.T_h
T[-1, :] = T[-2, :]
T[:, 0] = T[:, 1]
T[:, -1] = T[:, -2]
v_y[0, :] = 0
v_y[-1, :] = v_... | [
"numpy.zeros"
] | [((1184, 1205), 'numpy.zeros', 'np.zeros', (['T_cen.shape'], {}), '(T_cen.shape)\n', (1192, 1205), True, 'import numpy as np\n')] |
"""
Routes here:
- Where am I ?
- Return the street, city and country a given geolocation point is at.
- Linear distance (Haversine)
- Return the linear distance on a globe given two geo-coordinates.
"""
from fastapi import APIRouter
from src.service.HaversineService import linear_distance
from src.model.l... | [
"src.service.HaversineService.linear_distance",
"fastapi.APIRouter",
"src.service.whereAmIService.getLocation"
] | [((469, 480), 'fastapi.APIRouter', 'APIRouter', ([], {}), '()\n', (478, 480), False, 'from fastapi import APIRouter\n'), ((593, 618), 'src.service.HaversineService.linear_distance', 'linear_distance', (['distance'], {}), '(distance)\n', (608, 618), False, 'from src.service.HaversineService import linear_distance\n'), (... |
"""A text format for Bril.
This module defines both a parser and a pretty-printer for a
human-editable representation of Bril programs. There are two commands:
`bril2txt`, which takes a Bril program in its (canonical) JSON format and
pretty-prints it in the text format, and `bril2json`, which parses the
format a... | [
"lark.Lark",
"json.dumps",
"sys.stderr.flush",
"sys.exit",
"json.load",
"sys.stdin.read"
] | [((3352, 3370), 'lark.Lark', 'lark.Lark', (['GRAMMAR'], {}), '(GRAMMAR)\n', (3361, 3370), False, 'import lark\n'), ((3739, 3781), 'json.dumps', 'json.dumps', (['data'], {'indent': '(2)', 'sort_keys': '(True)'}), '(data, indent=2, sort_keys=True)\n', (3749, 3781), False, 'import json\n'), ((3860, 3902), 'json.dumps', 'j... |
import warnings
import numpy as np
from tabulate import tabulate
from collections import Counter
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.metrics import precision_score, recall_score, f1_score
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
def get_sentiment(documents, docu... | [
"vaderSentiment.vaderSentiment.SentimentIntensityAnalyzer",
"numpy.mean",
"sklearn.metrics.f1_score",
"tabulate.tabulate",
"sklearn.metrics.precision_score",
"sklearn.metrics.recall_score",
"numpy.array",
"numpy.sum",
"warnings.filterwarnings",
"numpy.round"
] | [((699, 727), 'vaderSentiment.vaderSentiment.SentimentIntensityAnalyzer', 'SentimentIntensityAnalyzer', ([], {}), '()\n', (725, 727), False, 'from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\n'), ((1592, 1625), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')... |
from __future__ import with_statement
# ==============================================================================
# GGisy (python v2.7)
#
# Author: <NAME> (<EMAIL>)
# Bugs and errors: https://github.com/Sanrrone/GGisy/issues
#
# Please type "python GGisy.py -h" for usage help
#
# ==========================... | [
"collections.namedtuple",
"os.access",
"os.path.join",
"optparse.OptionParser",
"os.path.split",
"os.path.isfile",
"subprocess.call",
"sys.exit",
"csv.reader",
"os.remove"
] | [((591, 665), 'optparse.OptionParser', 'OptionParser', ([], {'usage': '"""Usage: python GGisy.py -r genome1.fna -q genome2.fna"""'}), "(usage='Usage: python GGisy.py -r genome1.fna -q genome2.fna')\n", (603, 665), False, 'from optparse import OptionParser\n'), ((3104, 3190), 'collections.namedtuple', 'collections.named... |
"""
This is a simplified version to find statistical prevalence that counts instances and is numerically equivalent
to the confidence metric in association rules (# of occurrences / total occurrences).
"""
import csv
def count_stuff(filename):
"""
Counts instances and sorts them by prevalence
... | [
"csv.reader"
] | [((1024, 1061), 'csv.reader', 'csv.reader', (['input_file'], {'delimiter': '""","""'}), "(input_file, delimiter=',')\n", (1034, 1061), False, 'import csv\n')] |
# Generated by Django 3.0.5 on 2020-09-06 20:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='user',
name='bio',
field=mo... | [
"django.db.models.EmailField",
"django.db.models.TextField",
"django.db.models.CharField"
] | [((318, 390), 'django.db.models.TextField', 'models.TextField', ([], {'blank': '(True)', 'max_length': '(500)', 'verbose_name': '"""description"""'}), "(blank=True, max_length=500, verbose_name='description')\n", (334, 390), False, 'from django.db import migrations, models\n'), ((509, 576), 'django.db.models.EmailField... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import os
import unittest
import ConfigParser
from textwrap import dedent
from StringIO import StringIO
from mock import MagicMock, patch
from shoplift.config import *
from shoplift.exceptions import ConfigDoesNotExistException
BASE_CONFIG_TESTFILE = os.path.join(os.pat... | [
"StringIO.StringIO",
"textwrap.dedent",
"mock.patch",
"os.path.dirname",
"unittest.main",
"mock.MagicMock"
] | [((314, 339), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (329, 339), False, 'import os\n'), ((14746, 14782), 'mock.patch', 'patch', (['"""shoplift.scrapers.opengraph"""'], {}), "('shoplift.scrapers.opengraph')\n", (14751, 14782), False, 'from mock import MagicMock, patch\n'), ((15488, 155... |
# Parse conf.py in the root directory and check for validity
#
# A more detailed explanation of a valid configuration can be found
# in the documentation
#
import yaml
from pathlib import Path
import sys
import os
from logging import getLogger
from . import prefix, __version__
logger = getLogger(__name__)
class C... | [
"logging.getLogger",
"yaml.safe_dump",
"os.environ.get",
"pathlib.Path"
] | [((291, 310), 'logging.getLogger', 'getLogger', (['__name__'], {}), '(__name__)\n', (300, 310), False, 'from logging import getLogger\n'), ((1853, 1875), 'os.environ.get', 'os.environ.get', (['"""USER"""'], {}), "('USER')\n", (1867, 1875), False, 'import os\n'), ((1879, 1905), 'os.environ.get', 'os.environ.get', (['"""... |
import random
import tkinter
import math
class Blackjack():
def __init__(self, master):
#Menu
glavniMenu = tkinter.Menu(master)
master.config(menu = glavniMenu)
menuBJ = tkinter.Menu(glavniMenu)
glavniMenu.add_cascade(label = 'Blackjack', menu=menuBJ)
menuBJ.add_cascade(label = 'New Game', command = ... | [
"tkinter.Menu",
"math.ceil",
"random.shuffle",
"tkinter.Button",
"tkinter.Canvas",
"tkinter.Tk",
"tkinter.Label",
"tkinter.PhotoImage"
] | [((31798, 31810), 'tkinter.Tk', 'tkinter.Tk', ([], {}), '()\n', (31808, 31810), False, 'import tkinter\n'), ((115, 135), 'tkinter.Menu', 'tkinter.Menu', (['master'], {}), '(master)\n', (127, 135), False, 'import tkinter\n'), ((185, 209), 'tkinter.Menu', 'tkinter.Menu', (['glavniMenu'], {}), '(glavniMenu)\n', (197, 209)... |
from django.urls import path
from datahub.investment.summary.views import IProjectSummaryView
urlpatterns = [
path(
'adviser/<uuid:adviser_pk>/investment-summary',
IProjectSummaryView.as_view(),
name='investment-summary-item',
),
]
| [
"datahub.investment.summary.views.IProjectSummaryView.as_view"
] | [((187, 216), 'datahub.investment.summary.views.IProjectSummaryView.as_view', 'IProjectSummaryView.as_view', ([], {}), '()\n', (214, 216), False, 'from datahub.investment.summary.views import IProjectSummaryView\n')] |
# Generated by Django 4.0.1 on 2022-03-10 17:36
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('Assets', '0003_alter_assetlist_timestamp_alter_assettask_timestamp'),
('VulnerableScan', '0003_alter_exploitregister... | [
"django.db.models.ForeignKey",
"django.db.migrations.RemoveField",
"django.db.models.TextField",
"django.db.models.CharField"
] | [((377, 449), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""exploitregister"""', 'name': '"""file_object"""'}), "(model_name='exploitregister', name='file_object')\n", (399, 449), False, 'from django.db import migrations, models\n'), ((600, 666), 'django.db.models.TextField', 'mo... |
import datetime
import logging
import re
import serial
import sys
import termios
import threading
import time
import tty
import configuration
class RCReader(threading.Thread):
sp = None
start_called = False
chassis = None
def __init__(self, group = None, target = None, name = None,
a... | [
"datetime.datetime",
"threading.Thread.__init__",
"logging.getLogger",
"datetime.datetime.utcnow",
"re.match",
"serial.Serial",
"configuration.configuration"
] | [((370, 461), 'threading.Thread.__init__', 'threading.Thread.__init__', (['self'], {'group': 'group', 'target': 'target', 'name': 'name', 'verbose': 'verbose'}), '(self, group=group, target=target, name=name,\n verbose=verbose)\n', (395, 461), False, 'import threading\n'), ((787, 829), 'configuration.configuration',... |
__copyright__ = "Copyright (c) Microsoft Corporation and Mila - Quebec AI Institute"
__license__ = "MIT"
import os
import pickle
import time
from typing import Callable
import warnings
from gym import register
_SIM = None
ASSET_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "resources")
def ... | [
"gym.register",
"pickle.load",
"os.path.realpath",
"warnings.warn",
"time.time"
] | [((266, 292), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (282, 292), False, 'import os\n'), ((555, 672), 'warnings.warn', 'warnings.warn', (['"""Overwriting sim. This can have unexpected consequences if using old sim objects somewhere."""'], {}), "(\n 'Overwriting sim. This can have ... |
#!/usr/bin/python 3.7
#-*-coding:utf-8-*-
from torch import nn
import argparse
from progressbar import *
from torch.optim import Adam
import pandas as pd
import numpy as np
from my_tsp.datasets import data_processing
from my_tsp.trainer import train
def main(args):
# 读取数据
data_path = '../data/2-2.csv'
dS... | [
"my_tsp.trainer.train",
"my_tsp.datasets.data_processing.Data_utility",
"argparse.ArgumentParser",
"pandas.read_csv"
] | [((440, 590), 'my_tsp.datasets.data_processing.Data_utility', 'data_processing.Data_utility', (['dSet', 'args.num_obs_to_train', 'args.predict_seq_len', 'args.horizon', 'args.normalize', 'args.use_split', 'args.use_cuda'], {}), '(dSet, args.num_obs_to_train, args.\n predict_seq_len, args.horizon, args.normalize, arg... |
import numpy as np
import matplotlib.pyplot as plt
with open('input.txt', 'r') as f:
stream = f.readline()
image = np.array(tuple(map(int, stream))).reshape(-1, 6, 25)
nonzero_counts = np.sum(np.count_nonzero(image, axis=2), axis=1)
fewest_zeros_layer = np.argsort(nonzero_counts)[-1]
unique_values, counts = np.u... | [
"matplotlib.pyplot.imshow",
"numpy.unique",
"numpy.where",
"numpy.count_nonzero",
"numpy.argsort",
"numpy.zeros",
"matplotlib.pyplot.show"
] | [((316, 372), 'numpy.unique', 'np.unique', (['image[fewest_zeros_layer]'], {'return_counts': '(True)'}), '(image[fewest_zeros_layer], return_counts=True)\n', (325, 372), True, 'import numpy as np\n'), ((437, 454), 'numpy.zeros', 'np.zeros', (['(6, 25)'], {}), '((6, 25))\n', (445, 454), True, 'import numpy as np\n'), ((... |
# encoding: utf-8
import sys
from workflow import Workflow3, ICON_ERROR, ICON_CLOCK, ICON_NETWORK, ICON_SYNC
from workflow.background import run_in_background, is_running
from decimal import Decimal
from fetch import NetworkError
from parse import ParseError, WaitingForInputError, parse_input
"""Request Model
{
... | [
"workflow.Workflow3",
"fetch.NetworkError",
"parse.parse_input",
"decimal.Decimal",
"workflow.background.is_running"
] | [((3149, 3160), 'workflow.Workflow3', 'Workflow3', ([], {}), '()\n', (3158, 3160), False, 'from workflow import Workflow3, ICON_ERROR, ICON_CLOCK, ICON_NETWORK, ICON_SYNC\n'), ((763, 782), 'parse.parse_input', 'parse_input', (['stream'], {}), '(stream)\n', (774, 782), False, 'from parse import ParseError, WaitingForInp... |
# pylint: disable=wildcard-import, unused-wildcard-import, redefined-outer-name
# pylint: disable=C0415
import pytest
@pytest.fixture(name="logging_app")
def _logging_app():
from app import app
return app.test_client()
@pytest.fixture(name="query_utils")
def _utils():
from bot_logging_server.storage.my... | [
"pytest.fixture",
"app.app.test_client"
] | [((121, 155), 'pytest.fixture', 'pytest.fixture', ([], {'name': '"""logging_app"""'}), "(name='logging_app')\n", (135, 155), False, 'import pytest\n'), ((233, 267), 'pytest.fixture', 'pytest.fixture', ([], {'name': '"""query_utils"""'}), "(name='query_utils')\n", (247, 267), False, 'import pytest\n'), ((358, 385), 'pyt... |
#!/usr/bin/env python
import glob,os
import numpy as np
from bunch import Bunch
import mygis as io
import load_data
def adjust_p(p,h,dz):
'''Convert p [Pa] at elevation h [m] by shifting its elevation by dz [m]'''
# p in pascals
# h,dz in meters
# slp = p/(1 - 2.25577E-5*h)**5.25588
# p=slp*(1... | [
"numpy.arange",
"numpy.diff",
"numpy.zeros",
"load_data.cols",
"numpy.meshgrid",
"glob.glob",
"os.remove"
] | [((436, 460), 'load_data.cols', 'load_data.cols', (['filename'], {}), '(filename)\n', (450, 460), False, 'import load_data\n'), ((1074, 1109), 'numpy.arange', 'np.arange', (['(0)', '(nz * base.dz)', 'base.dz'], {}), '(0, nz * base.dz, base.dz)\n', (1083, 1109), True, 'import numpy as np\n'), ((1113, 1138), 'glob.glob',... |
import asyncio
import logging
import sys
from pathlib import Path
from aioquic.quic.configuration import QuicConfiguration
from rsocket.helpers import single_transport_provider
from rsocket.payload import Payload
from rsocket.rsocket_client import RSocketClient
from rsocket.transports.aioquic_transport import rsocket... | [
"logging.basicConfig",
"aioquic.quic.configuration.QuicConfiguration",
"pathlib.Path",
"rsocket.payload.Payload",
"rsocket.helpers.single_transport_provider",
"asyncio.sleep",
"rsocket.transports.aioquic_transport.rsocket_connect",
"logging.info"
] | [((364, 429), 'logging.info', 'logging.info', (['"""Connecting to server at localhost:%s"""', 'server_port'], {}), "('Connecting to server at localhost:%s', server_port)\n", (376, 429), False, 'import logging\n'), ((458, 491), 'aioquic.quic.configuration.QuicConfiguration', 'QuicConfiguration', ([], {'is_client': '(Tru... |
import inspect
import importlib
import pkgutil
import Plugins
from .PluginBase import PluginBase
class PluginsLoader:
def __init__(self):
pass
@staticmethod
def __iter_namespace(ns_pkg):
return pkgutil.iter_modules(ns_pkg.__path__, ns_pkg.__name__ + ".")
def load(self):
res... | [
"inspect.getmembers",
"importlib.import_module",
"pkgutil.iter_modules"
] | [((227, 287), 'pkgutil.iter_modules', 'pkgutil.iter_modules', (['ns_pkg.__path__', "(ns_pkg.__name__ + '.')"], {}), "(ns_pkg.__path__, ns_pkg.__name__ + '.')\n", (247, 287), False, 'import pkgutil\n'), ((467, 496), 'importlib.import_module', 'importlib.import_module', (['name'], {}), '(name)\n', (490, 496), False, 'imp... |
from aws_cdk import (
Stack,
aws_sns as sns,
aws_sqs as sqs,
aws_lambda as _lambda,
aws_lambda_destinations as destination,
)
from constructs import Construct
from dlq import core_lambda
class LambdaSnsDlqDestinationStack(Stack):
def __init__(self, scope: Construct, construct_id: str, **kwargs... | [
"dlq.core_lambda.add_sns_event_source",
"aws_cdk.aws_sqs.Queue",
"aws_cdk.aws_lambda.Code.from_asset",
"aws_cdk.aws_sns.Topic"
] | [((822, 895), 'aws_cdk.aws_sns.Topic', 'sns.Topic', (['self', '"""topic"""'], {'display_name': '"""topic"""', 'topic_name': '"""lambda_topic"""'}), "(self, 'topic', display_name='topic', topic_name='lambda_topic')\n", (831, 895), True, 'from aws_cdk import Stack, aws_sns as sns, aws_sqs as sqs, aws_lambda as _lambda, a... |
from dateutil import tz
from django.http.response import JsonResponse
from 臺灣言語平臺.項目模型 import 平臺項目表
from 臺灣言語資料庫.資料模型 import 來源表
from 臺灣言語平臺.介面.Json失敗回應 import Json失敗回應
from django.core.exceptions import ObjectDoesNotExist
_臺北時間 = tz.gettz('Asia/Taipei')
_時間輸出樣式 = '%Y-%m-%d %H:%M:%S'
def 轉做臺北時間字串(時間... | [
"dateutil.tz.gettz",
"臺灣言語平臺.項目模型.平臺項目表.這句講了按怎",
"臺灣言語資料庫.資料模型.來源表.objects.get",
"臺灣言語平臺.介面.Json失敗回應.Json失敗回應",
"django.http.response.JsonResponse"
] | [((253, 276), 'dateutil.tz.gettz', 'tz.gettz', (['"""Asia/Taipei"""'], {}), "('Asia/Taipei')\n", (261, 276), False, 'from dateutil import tz\n'), ((1505, 1523), 'django.http.response.JsonResponse', 'JsonResponse', (['來源內容'], {}), '(來源內容)\n', (1517, 1523), False, 'from django.http.response import JsonResponse\n'), ((185... |
# coding: utf-8
# 2021/8/2 @ tongshiwei
import pytest
from EduNLP import get_pretrained_i2v
from EduNLP.Vector.t2v import PRETRAINED_MODELS
from EduNLP.I2V.i2v import MODELS
from EduNLP.I2V import D2V
def test_pretrained_i2v(tmp_path):
PRETRAINED_MODELS["test"] = ["http://base.ustc.edu.cn/data/model_zoo/EduNLP/d2... | [
"EduNLP.get_pretrained_i2v",
"pytest.raises"
] | [((426, 455), 'EduNLP.get_pretrained_i2v', 'get_pretrained_i2v', (['"""test"""', 'd'], {}), "('test', d)\n", (444, 455), False, 'from EduNLP import get_pretrained_i2v\n'), ((532, 561), 'EduNLP.get_pretrained_i2v', 'get_pretrained_i2v', (['"""test"""', 'd'], {}), "('test', d)\n", (550, 561), False, 'from EduNLP import g... |
import glob
import unittest
import os
from collections import namedtuple
from rappel import db
Result = namedtuple('response', 'word value tries found time')
class DBTestCreation(unittest.TestCase):
def setUp(self):
self.db_file_name = "temp/tu.db"
# do some house cleaning
if glob.glob(self.db_file_name):
... | [
"collections.namedtuple",
"unittest.main",
"rappel.db.db",
"glob.glob",
"os.remove"
] | [((106, 159), 'collections.namedtuple', 'namedtuple', (['"""response"""', '"""word value tries found time"""'], {}), "('response', 'word value tries found time')\n", (116, 159), False, 'from collections import namedtuple\n'), ((1463, 1478), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1476, 1478), False, 'impor... |
from flask import Flask
from flask_assets import Bundle, Environment
from .. import app
bundles = {
'js': Bundle(
'js/graph.js',
'js/side_bar.js',
# 'js/regression.js',
# 'js/pca.js',
'js/script.js',
'js/entropy.js',
output='gen/script.js'
),
... | [
"flask_assets.Bundle",
"flask_assets.Environment"
] | [((447, 463), 'flask_assets.Environment', 'Environment', (['app'], {}), '(app)\n', (458, 463), False, 'from flask_assets import Bundle, Environment\n'), ((111, 211), 'flask_assets.Bundle', 'Bundle', (['"""js/graph.js"""', '"""js/side_bar.js"""', '"""js/script.js"""', '"""js/entropy.js"""'], {'output': '"""gen/script.js... |
# Copyright 2017 Battelle Energy Alliance, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | [
"numpy.arange"
] | [((896, 909), 'numpy.arange', 'np.arange', (['nx'], {}), '(nx)\n', (905, 909), True, 'import numpy as np\n'), ((922, 935), 'numpy.arange', 'np.arange', (['ny'], {}), '(ny)\n', (931, 935), True, 'import numpy as np\n'), ((970, 988), 'numpy.arange', 'np.arange', (['(nx * ny)'], {}), '(nx * ny)\n', (979, 988), True, 'impo... |
import os
from setuptools import setup, find_packages
import userpypi
def fread(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
try:
reqs = open(os.path.join(os.path.dirname(__file__), 'requirements.txt')).read()
except (IOError, OSError):
reqs = ''
setup(
name='userpypi',
... | [
"os.path.dirname",
"setuptools.find_packages",
"userpypi.get_version"
] | [((332, 354), 'userpypi.get_version', 'userpypi.get_version', ([], {}), '()\n', (352, 354), False, 'import userpypi\n'), ((1361, 1376), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (1374, 1376), False, 'from setuptools import setup, find_packages\n'), ((118, 143), 'os.path.dirname', 'os.path.dirname',... |
from service_user.models import UserModel
from django.core.exceptions import ValidationError
def get_user_instance_with_session_id(user_id, session_id):
try:
instance = UserModel.objects.get(
user_id__exact=user_id,
session_id__exact=session_id
)
except (UserModel.DoesN... | [
"service_user.models.UserModel.objects.get"
] | [((183, 258), 'service_user.models.UserModel.objects.get', 'UserModel.objects.get', ([], {'user_id__exact': 'user_id', 'session_id__exact': 'session_id'}), '(user_id__exact=user_id, session_id__exact=session_id)\n', (204, 258), False, 'from service_user.models import UserModel\n'), ((610, 681), 'service_user.models.Use... |
# Copyright 2019 The DataFrame Show Reader 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... | [
"pyspark.sql.types.StructField"
] | [((3159, 3202), 'pyspark.sql.types.StructField', 'StructField', (['f.name', 'f.dataType', 'f.nullable'], {}), '(f.name, f.dataType, f.nullable)\n', (3170, 3202), False, 'from pyspark.sql.types import StructField, StructType\n')] |
from tempfile import TemporaryFile
import discord
#import requests
import json
import asyncio
from discord.ext import commands
import re
from random import randint
questions = ["When was NT founded?", "", "q3"]
answers = {
"Which of the following celebs went to NT? \na) <NAME> \nb) <NAME> \nc) <NAME> \nd) <NAME>" ... | [
"discord.ext.commands.Cog.listener",
"discord.ext.commands.command"
] | [((1314, 1337), 'discord.ext.commands.Cog.listener', 'commands.Cog.listener', ([], {}), '()\n', (1335, 1337), False, 'from discord.ext import commands\n'), ((3403, 3421), 'discord.ext.commands.command', 'commands.command', ([], {}), '()\n', (3419, 3421), False, 'from discord.ext import commands\n'), ((4052, 4070), 'dis... |
import json
import os
import unittest
from unittest.mock import MagicMock
from ingest.api.ingestapi import IngestApi
from ingest.downloader.data_collector import DataCollector
class DataCollectorTest(unittest.TestCase):
def setUp(self) -> None:
self.maxDiff = None
self.mock_ingest_api = MagicMoc... | [
"unittest.mock.MagicMock",
"os.path.join",
"ingest.downloader.data_collector.DataCollector",
"os.path.split",
"json.load",
"os.path.dirname",
"unittest.main"
] | [((5330, 5345), 'unittest.main', 'unittest.main', ([], {}), '()\n', (5343, 5345), False, 'import unittest\n'), ((312, 337), 'unittest.mock.MagicMock', 'MagicMock', ([], {'spec': 'IngestApi'}), '(spec=IngestApi)\n', (321, 337), False, 'from unittest.mock import MagicMock\n'), ((368, 403), 'ingest.downloader.data_collect... |
""""
STRIP Scanning Strategy Tools test module.
"""
import unittest
import healpy as hp
import numpy as np
from ScanningTools import ScanningTools as st
from astropy.time import Time
from astropy.coordinates import SkyCoord, AltAz
from ScanningTools.Quaternions import Quaternion as q
angles = np.array([[-10, 45, 59... | [
"ScanningTools.ScanningTools.dec2sex",
"numpy.radians",
"ScanningTools.ScanningTools.spin_generator",
"numpy.array",
"ScanningTools.ScanningTools.get_full_fp_polarization_angles",
"numpy.arctan2",
"unittest.main",
"ScanningTools.ScanningTools.get_nside_eff",
"ScanningTools.ScanningTools.hours2degree... | [((298, 364), 'numpy.array', 'np.array', (['[[-10, 45, 59], [30, 35, 15], [-180, 25, 20], [3, 4, 5]]'], {}), '([[-10, 45, 59], [30, 35, 15], [-180, 25, 20], [3, 4, 5]])\n', (306, 364), True, 'import numpy as np\n'), ((425, 462), 'numpy.array', 'np.array', (['[[23, 59, 16], [7, 56, 59]]'], {}), '([[23, 59, 16], [7, 56, ... |
from flask_restful import Resource, reqparse
from flask_jwt import jwt_required
from models.word import WordModel
class Word(Resource):
parser = reqparse.RequestParser()
parser.add_argument('stem_id',
type=int,
required=True,
help="Every word needs a stem."
)
#@jwt_required()
... | [
"models.word.WordModel",
"models.word.WordModel.find_by_word",
"flask_restful.reqparse.RequestParser",
"models.word.WordModel.query.all"
] | [((150, 174), 'flask_restful.reqparse.RequestParser', 'reqparse.RequestParser', ([], {}), '()\n', (172, 174), False, 'from flask_restful import Resource, reqparse\n'), ((365, 399), 'models.word.WordModel.find_by_word', 'WordModel.find_by_word', (['word_value'], {}), '(word_value)\n', (387, 399), False, 'from models.wor... |
from dataclasses import dataclass
from typing import Dict
from typing import Optional
@dataclass(frozen=True)
class CurrentDestinationStatus:
number_of_pending_messages: Optional[int]
number_of_consumers: int
messages_enqueued: int
messages_dequeued: int
@dataclass(frozen=True)
class ConsumerStatus:... | [
"dataclasses.dataclass"
] | [((89, 111), 'dataclasses.dataclass', 'dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (98, 111), False, 'from dataclasses import dataclass\n'), ((276, 298), 'dataclasses.dataclass', 'dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (285, 298), False, 'from dataclasses import dataclass\n'), ((653, ... |
r"""
Mutual Coherence and Babel Function are the properties of a matrix, used to
estimate the Spark of a matrix, which in turn is used to determine the
optimality of the solution to :math:`\text{P}_0` problem.
Babel Function gives a tighter bound on the Spark of a matrix.
Spark of a matrix :math:`\boldsymbol{A}` is t... | [
"collections.namedtuple",
"numpy.reshape",
"math.ceil",
"numpy.fill_diagonal",
"numpy.nonzero",
"numpy.linalg.norm"
] | [((615, 667), 'collections.namedtuple', 'namedtuple', (['"""CoherenceSpark"""', "('coherence', 'spark')"], {}), "('CoherenceSpark', ('coherence', 'spark'))\n", (625, 667), False, 'from collections import namedtuple\n'), ((1712, 1737), 'numpy.fill_diagonal', 'np.fill_diagonal', (['gram', '(0)'], {}), '(gram, 0)\n', (172... |
from datetime import datetime
from couchdb.mapping import BooleanField
from couchdb.mapping import DateTimeField
from couchdb.mapping import Document
from couchdb.mapping import TextField
from .utils import get_random_uid
from .utils import url_for
class URL(Document):
target = TextField()
public = BooleanF... | [
"couchdb.mapping.BooleanField",
"couchdb.mapping.TextField",
"datetime.datetime.utcnow"
] | [((287, 298), 'couchdb.mapping.TextField', 'TextField', ([], {}), '()\n', (296, 298), False, 'from couchdb.mapping import TextField\n'), ((312, 326), 'couchdb.mapping.BooleanField', 'BooleanField', ([], {}), '()\n', (324, 326), False, 'from couchdb.mapping import BooleanField\n'), ((396, 419), 'couchdb.mapping.TextFiel... |
# -*- coding: utf-8 -*-
from os import linesep
from SciDataTool.Classes._check import set_array, check_init_dict, check_var, raise_
from SciDataTool.Functions.save import save
from SciDataTool.Classes.DataND import DataND
# Import all class method
# Try/catch to remove unnecessary dependencies in unused method
try:
... | [
"SciDataTool.Classes._check.check_init_dict"
] | [((2494, 2618), 'SciDataTool.Classes._check.check_init_dict', 'check_init_dict', (['init_dict', "['axes', 'normalizations', 'FTparameters', 'values', 'symbol', 'name',\n 'unit', 'symmetries']"], {}), "(init_dict, ['axes', 'normalizations', 'FTparameters',\n 'values', 'symbol', 'name', 'unit', 'symmetries'])\n", (... |
"""
Created on Sun Feb 12 11:51:29 2017
@author: <NAME>
Class: Computer Architecture
Language Python 2.7
Input an array of hex-instructions, and return a of decoded MIPS instructions (e.g. 7a078 ADD $2, $9, $8).
Instruction types de-constructed in this assignment are ADD, AND, OR, SLT, SUB, BEQ, BNE, LW, a... | [
"numpy.array",
"numpy.vectorize"
] | [((642, 668), 'numpy.array', 'np.array', (['hex_instructions'], {}), '(hex_instructions)\n', (650, 668), True, 'import numpy as np\n'), ((677, 694), 'numpy.vectorize', 'np.vectorize', (['hex'], {}), '(hex)\n', (689, 694), True, 'import numpy as np\n')] |
import sklearn.datasets
import sklearn.model_selection
import sklearn.linear_model
import numpy
import compare_auc_delong_xu
import unittest
import scipy.stats
class TestIris(unittest.TestCase):
@classmethod
def setUpClass(cls):
data = sklearn.datasets.load_iris()
x_train, x_test, y_train, ... | [
"numpy.ones",
"numpy.testing.assert_allclose",
"compare_auc_delong_xu.delong_roc_variance",
"numpy.zeros",
"numpy.empty",
"numpy.random.seed"
] | [((758, 830), 'compare_auc_delong_xu.delong_roc_variance', 'compare_auc_delong_xu.delong_roc_variance', (['self.y_test', 'self.predictions'], {}), '(self.y_test, self.predictions)\n', (799, 830), False, 'import compare_auc_delong_xu\n'), ((839, 891), 'numpy.testing.assert_allclose', 'numpy.testing.assert_allclose', (['... |
import torch
def confusion_matrix(preds, labels, num_classes):
hist = (
torch.bincount(
num_classes * labels + preds,
minlength=num_classes ** 2,
)
.reshape(num_classes, num_classes)
.float()
)
return hist
def compute_IoU_from_cmatrix(hist, ignore_... | [
"torch.bincount",
"torch.mean",
"torch.sum",
"torch.diag",
"torch.cat"
] | [((570, 586), 'torch.diag', 'torch.diag', (['hist'], {}), '(hist)\n', (580, 586), False, 'import torch\n'), ((768, 823), 'torch.cat', 'torch.cat', (['(IoU[:ignore_index], IoU[ignore_index + 1:])'], {}), '((IoU[:ignore_index], IoU[ignore_index + 1:]))\n', (777, 823), False, 'import torch\n'), ((834, 849), 'torch.mean', ... |