code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2017 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... | [
"hyver.command.create.Create"
] | [((1418, 1448), 'hyver.command.create.Create', 'create.Create', (['config_instance'], {}), '(config_instance)\n', (1431, 1448), False, 'from hyver.command import create\n')] |
import napari
def show_image(im, title, viewer=None, label=False):
""" convenience helper function to show image in Napari
Args:
im (numpy array): image to show
title (string): title of image
viewer (napari instance, optional): pre-existing Napari
label (bool, optional): True ... | [
"napari.Viewer"
] | [((436, 451), 'napari.Viewer', 'napari.Viewer', ([], {}), '()\n', (449, 451), False, 'import napari\n')] |
import bpy
import numpy as np
from smorgasbord.common.decorate import register
from smorgasbord.common.io import get_vecs, get_scalars
def get_red(arr):
return arr[:, 0:1].ravel()
def get_green(arr):
return arr[:, 1:2].ravel()
def get_blue(arr):
return arr[:, 2:3].ravel()
def avg_rgb(arr):
# St... | [
"numpy.unique",
"smorgasbord.common.io.get_scalars",
"numpy.average",
"numpy.where",
"bpy.props.EnumProperty",
"smorgasbord.common.io.get_vecs"
] | [((363, 394), 'numpy.average', 'np.average', (['arr[:, :-1]'], {'axis': '(1)'}), '(arr[:, :-1], axis=1)\n', (373, 394), True, 'import numpy as np\n'), ((825, 1132), 'bpy.props.EnumProperty', 'bpy.props.EnumProperty', ([], {'name': '"""Method"""', 'description': '"""Method used to calculate scalar weights from rgb color... |
#!/usr/bin/env python3
import sys
import os
from scipy.stats import wasserstein_distance
from scipy.stats import ks_2samp
def compare_fct_mse(input1, input2):
fct_dict = dict()
with open(input1, "r") as f1:
for line in f1:
toks = line.split()
dst = int(toks[0])
src... | [
"scipy.stats.wasserstein_distance",
"os.path.isdir",
"os.listdir",
"scipy.stats.ks_2samp"
] | [((4871, 4896), 'os.path.isdir', 'os.path.isdir', (['approx_fct'], {}), '(approx_fct)\n', (4884, 4896), False, 'import os\n'), ((1269, 1289), 'scipy.stats.ks_2samp', 'ks_2samp', (['cdf1', 'cdf2'], {}), '(cdf1, cdf2)\n', (1277, 1289), False, 'from scipy.stats import ks_2samp\n'), ((1563, 1595), 'scipy.stats.wasserstein_... |
# created by gelearthur
# imports
import uuid
import os
import argparse
# arguments
parser = argparse.ArgumentParser("Script that makes music files for unturned")
parser.add_argument('-f','--file',help="A path to the myMusic.content.manifest",required=True)
args = parser.parse_args()
# a loop thing
asse... | [
"argparse.ArgumentParser",
"os.path.splitext",
"os.path.join",
"uuid.uuid4",
"os.path.dirname",
"os.path.basename"
] | [((103, 172), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""Script that makes music files for unturned"""'], {}), "('Script that makes music files for unturned')\n", (126, 172), False, 'import argparse\n'), ((420, 447), 'os.path.basename', 'os.path.basename', (['args.file'], {}), '(args.file)\n', (436, 44... |
#! coding:utf-8
"""
track_controller.py
Created by 0160929 on 2016/09/29 16:38
"""
import os
from TrackMaster.signalfigureview import WaveViewer
__version__ = '0.0'
import sys
from PySide.QtGui import *
from PySide.QtCore import *
import iconsloader
__all__ = ["TrackController"]
class T... | [
"os.path.basename",
"TrackMaster.signalfigureview.WaveViewer"
] | [((582, 616), 'os.path.basename', 'os.path.basename', (['self.wavfilepath'], {}), '(self.wavfilepath)\n', (598, 616), False, 'import os\n'), ((3732, 3774), 'TrackMaster.signalfigureview.WaveViewer', 'WaveViewer', (['self'], {'wavpath': 'self.wavfilepath'}), '(self, wavpath=self.wavfilepath)\n', (3742, 3774), False, 'fr... |
# This is a synthesizer filter for adding sawtooth wave patterns
# of a given duration and sample rate
from scipy import signal
import fileIO
import math
import numpy as np
def sawWav(fileName, fs, freq):
t = np.linspace(0, 1, int(fs))
dat = signal.sawtooth(2 * math.pi * freq * t)
fileIO.file_output(fil... | [
"scipy.signal.sawtooth"
] | [((253, 292), 'scipy.signal.sawtooth', 'signal.sawtooth', (['(2 * math.pi * freq * t)'], {}), '(2 * math.pi * freq * t)\n', (268, 292), False, 'from scipy import signal\n')] |
#!/usr/bin/env python
import argparse
import sys, subprocess, os
import re
import datetime
import math
# Generate customized SLURM submit scripts to run RAxML-ng.
# Takes a directory of alignmets, runs the raxml-ng --parse
# function to get estimates of RAM and CPU needs for the job.
# Then uses a templates sba... | [
"os.listdir",
"math.ceil",
"argparse.ArgumentParser",
"re.compile",
"os.makedirs",
"subprocess.Popen",
"subprocess.run",
"os.path.join",
"datetime.datetime.now",
"os.path.basename",
"sys.exit",
"os.path.relpath"
] | [((881, 950), 're.compile', 're.compile', (['"""Estimated memory requirements\\\\s*:\\\\s*(\\\\d+)\\\\s*([MG]B)"""'], {}), "('Estimated memory requirements\\\\s*:\\\\s*(\\\\d+)\\\\s*([MG]B)')\n", (891, 950), False, 'import re\n'), ((963, 1033), 're.compile', 're.compile', (['"""Recommended number of threads / MPI proce... |
from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules=cythonize("sieve_module.py")) | [
"Cython.Build.cythonize"
] | [((87, 115), 'Cython.Build.cythonize', 'cythonize', (['"""sieve_module.py"""'], {}), "('sieve_module.py')\n", (96, 115), False, 'from Cython.Build import cythonize\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
from alipay.aop.api.domain.RateCurrency import RateCurrency
class AlipayOverseasTravelRateCurrencyBatchqueryResponse(AlipayResponse):
def __init__(self):
super(AlipayOverseasTravel... | [
"alipay.aop.api.domain.RateCurrency.RateCurrency.from_alipay_dict"
] | [((818, 850), 'alipay.aop.api.domain.RateCurrency.RateCurrency.from_alipay_dict', 'RateCurrency.from_alipay_dict', (['i'], {}), '(i)\n', (847, 850), False, 'from alipay.aop.api.domain.RateCurrency import RateCurrency\n')] |
import torch
import numpy
from deep_signature.nn.datasets import DeepSignatureEuclideanArclengthTupletsOnlineDataset
from deep_signature.nn.datasets import DeepSignatureEquiaffineArclengthTupletsOnlineDataset
from deep_signature.nn.datasets import DeepSignatureAffineArclengthTupletsOnlineDataset
from deep_signature.nn.... | [
"common.utils.get_latest_subdirectory",
"deep_signature.nn.losses.ArcLengthLoss",
"deep_signature.nn.trainers.ModelTrainer",
"argparse.ArgumentParser",
"deep_signature.nn.networks.DeepSignatureArcLengthNet",
"torch.set_default_dtype",
"numpy.load",
"torch.device"
] | [((656, 694), 'torch.set_default_dtype', 'torch.set_default_dtype', (['torch.float64'], {}), '(torch.float64)\n', (679, 694), False, 'import torch\n'), ((709, 725), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (723, 725), False, 'from argparse import ArgumentParser\n'), ((5678, 5737), 'deep_signature.... |
import os
import pathlib
from click.testing import CliRunner
from syncify.core import rsync_to, rsync, store, load, extract_archive
import mock
settings = {"tarfile_output_path": "$HOME/transfer/syncify.tar.gz"}
applications = {
"transgui": {
"description": "Transmission Remote GUI",
"paths": [
{
... | [
"pathlib.Path",
"click.testing.CliRunner",
"os.path.dirname",
"syncify.core.extract_archive",
"os.path.expanduser"
] | [((5211, 5222), 'click.testing.CliRunner', 'CliRunner', ([], {}), '()\n', (5220, 5222), False, 'from click.testing import CliRunner\n'), ((5778, 5789), 'click.testing.CliRunner', 'CliRunner', ([], {}), '()\n', (5787, 5789), False, 'from click.testing import CliRunner\n'), ((6447, 6458), 'click.testing.CliRunner', 'CliR... |
import collections
import logging
import time
import itertools
import io
import subprocess
import selectors
from typing import Any
from typing import Deque, Type, List, Tuple
import pytest
from .config import SSHConfiguration
from .continuous import Action
from .continuous import ContinuousSSH
@pytest.fixture
def c... | [
"pytest.approx",
"logging.getLogger",
"collections.deque",
"selectors.SelectorKey",
"itertools.product",
"io.BytesIO",
"pytest.mark.parametrize",
"pytest.raises"
] | [((730, 959), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""logline,expected_action"""', "[('Entering interactive session', Action.CONNECTED), (\n 'debug1: Reading configuration', Action.CONTINUE), (\n 'Host example.com not responding', Action.DISCONNECTED)]"], {}), "('logline,expected_action', [(\n... |
# PROGRAMMER: <NAME>
# DATE CREATED: 26/04/2020
# REVISED DATE:
# PURPOSE: Classifies flower images using a pretrained deep neural network such as VGG11 and RESNET50
# This Python script is used to build and train a new classifier of the pretrained model (VGG11 as defaut)
#
# E... | [
"fc_model.train",
"fc_model.classifier",
"torch.cuda.is_available",
"torch.nn.NLLLoss",
"torch.save",
"torchvision.models.resnet50",
"torchvision.models.vgg11",
"utility_model.load_data",
"utility_model.get_input_arg"
] | [((947, 962), 'utility_model.get_input_arg', 'get_input_arg', ([], {}), '()\n', (960, 962), False, 'from utility_model import load_data, get_input_arg\n'), ((1460, 1479), 'utility_model.load_data', 'load_data', (['data_dir'], {}), '(data_dir)\n', (1469, 1479), False, 'from utility_model import load_data, get_input_arg\... |
# -*- coding: utf-8 -*-
"""
Copyright © 2017, <NAME>
Contributed by <NAME> (<EMAIL>)
This file is part of BSD license
<https://opensource.org/licenses/BSD-3-Clause>
"""
import logging
from quest.models import CIQuest
class QuestUtility:
"""
strState route graph:
↓---- all cancel ----↑ ... | [
"quest.models.CIQuest.objects.filter"
] | [((1095, 1132), 'quest.models.CIQuest.objects.filter', 'CIQuest.objects.filter', ([], {'strQID': 'strQID'}), '(strQID=strQID)\n', (1117, 1132), False, 'from quest.models import CIQuest\n')] |
"""Work out the optimum mass for maximum cannonball range"""
import sympy as sym
import numpy as np
import matplotlib.pyplot as plt
import atmosphere
import pycollo
from pycollo.functions import cubic_spline
# state variables
r = sym.Symbol("r") # downrange distance
h = sym.Symbol("h") # height (above sea level?)
v =... | [
"sympy.sin",
"sympy.Symbol",
"sympy.cos",
"pycollo.functions.cubic_spline",
"matplotlib.pyplot.ylabel",
"pycollo.OptimalControlProblem",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.max",
"numpy.rad2deg",
"matplotlib.pyplot.show"
] | [((232, 247), 'sympy.Symbol', 'sym.Symbol', (['"""r"""'], {}), "('r')\n", (242, 247), True, 'import sympy as sym\n'), ((273, 288), 'sympy.Symbol', 'sym.Symbol', (['"""h"""'], {}), "('h')\n", (283, 288), True, 'import sympy as sym\n'), ((321, 336), 'sympy.Symbol', 'sym.Symbol', (['"""v"""'], {}), "('v')\n", (331, 336), ... |
import json
import os
import boto3
import time
import uuid
from helper import AwsHelper
from og import OutputGenerator
from trp import Document
from decimal import Decimal
import datastore
import re
def getJobResults(api, jobId):
pages = []
time.sleep(5)
client = AwsHelper().getClient('textract')
if... | [
"trp.Document",
"datastore.DocumentStore",
"json.loads",
"helper.AwsHelper",
"time.sleep",
"boto3.resource"
] | [((252, 265), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (262, 265), False, 'import time\n'), ((1864, 1879), 'trp.Document', 'Document', (['pages'], {}), '(pages)\n', (1872, 1879), False, 'from trp import Document\n'), ((4421, 4460), 'datastore.DocumentStore', 'datastore.DocumentStore', (['documentsTable'], {}... |
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^smartling_callback/$', 'mezzanine_smartling.views.smartling_callback', name='smartling_callback'),
]
| [
"django.conf.urls.url"
] | [((96, 203), 'django.conf.urls.url', 'url', (['"""^smartling_callback/$"""', '"""mezzanine_smartling.views.smartling_callback"""'], {'name': '"""smartling_callback"""'}), "('^smartling_callback/$', 'mezzanine_smartling.views.smartling_callback',\n name='smartling_callback')\n", (99, 203), False, 'from django.conf.ur... |
import pytest
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import random
@pytest.fixture
def driver(request):
wd = webdriver.Chrome(desired_capabilities={"pageLoadStrategy": "eager"})
# wd = webdriver.... | [
"selenium.webdriver.Chrome",
"selenium.webdriver.support.wait.WebDriverWait",
"selenium.webdriver.support.expected_conditions.number_of_windows_to_be",
"selenium.webdriver.support.expected_conditions.title_is",
"random.randint"
] | [((230, 298), 'selenium.webdriver.Chrome', 'webdriver.Chrome', ([], {'desired_capabilities': "{'pageLoadStrategy': 'eager'}"}), "(desired_capabilities={'pageLoadStrategy': 'eager'})\n", (246, 298), False, 'from selenium import webdriver\n'), ((1055, 1077), 'random.randint', 'random.randint', (['(1)', '(239)'], {}), '(1... |
# Copyright 2019 Open End AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | [
"blm.testblm.Sub._query",
"blm.testblm.Defaults._query",
"bson.objectid.ObjectId",
"os.path.dirname",
"blm.TO._query",
"blm.clear",
"blm.testblm.Base._query"
] | [((983, 994), 'blm.clear', 'blm.clear', ([], {}), '()\n', (992, 994), False, 'import blm\n'), ((818, 843), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (833, 843), False, 'import os\n'), ((944, 969), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (959, 969), False... |
from rpyc.utils.server import ThreadedServer
import rpyc
import subprocess
import os
import re
from dataclasses import dataclass
DOCKER_SWARM_ADDR = os.getenv('DOCKER_SWARM_ADDR')
@dataclass
class WorkerCXT:
host_addr: str
username: str
password: str
key_file: str
def __init__(self):
pas... | [
"subprocess.run",
"re.match",
"os.getenv"
] | [((150, 180), 'os.getenv', 'os.getenv', (['"""DOCKER_SWARM_ADDR"""'], {}), "('DOCKER_SWARM_ADDR')\n", (159, 180), False, 'import os\n'), ((750, 825), 'subprocess.run', 'subprocess.run', (["['docker', 'context', 'use', ctx_name]"], {'capture_output': '(True)'}), "(['docker', 'context', 'use', ctx_name], capture_output=T... |
import io
import os
import re
import shutil
import sys
import typing
import webbrowser
from time import sleep
import click
import pandas as pd
from whylogs.app import SessionConfig, WriterConfig
from whylogs.app.session import session_from_config
from whylogs.cli import (
OBSERVATORY_EXPLANATION,
PIPELINE_DES... | [
"pandas.read_csv",
"re.compile",
"whylogs.cli.generate_notebooks",
"click.File",
"webbrowser.open",
"time.sleep",
"sys.exit",
"click.BadParameter",
"whylogs.app.WriterConfig",
"os.listdir",
"click.secho",
"click.option",
"io.StringIO",
"click.command",
"click.confirm",
"click.prompt",
... | [((647, 673), 're.compile', 're.compile', (['"""^(\\\\w|-|_)+$"""'], {}), "('^(\\\\w|-|_)+$')\n", (657, 673), False, 'import re\n'), ((962, 977), 'click.command', 'click.command', ([], {}), '()\n', (975, 977), False, 'import click\n'), ((979, 1088), 'click.option', 'click.option', (['"""--project-dir"""', '"""-d"""'], ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#__author__ = '0xAE'
#_name_ = ' drupal full path disclousure'
import re
def assign(service, arg):
if service == "drupal":
return True, arg
def audit(arg):
payload='?q[]=x'
verify_url = arg + payload
pathinfo = re.compile(r' in <b>... | [
"re.compile"
] | [((300, 337), 're.compile', 're.compile', (['""" in <b>(.*)</b> on line"""'], {}), "(' in <b>(.*)</b> on line')\n", (310, 337), False, 'import re\n')] |
# -*- coding: UTF-8 -*-
"""
Based on ``behave tutorial``
Feature: A Step uses a User-Defined Type as Step Parameter (tutorial10)
Scenario Outline: Calculator
Given I have a calculator
When I add "<x>" and "<y>"
Then the calculator returns "<sum>"
Examples: Add Numbers
| x | y | sum |
... | [
"behave.given",
"behave.register_type",
"behave.when",
"calculator.Calculator",
"behave.then",
"hamcrest.equal_to"
] | [((967, 1001), 'behave.register_type', 'register_type', ([], {'Number': 'parse_number'}), '(Number=parse_number)\n', (980, 1001), False, 'from behave import register_type\n'), ((1302, 1330), 'behave.given', 'given', (['"""I have a calculator"""'], {}), "('I have a calculator')\n", (1307, 1330), False, 'from behave impo... |
'''
Tests the data merge functions and package.
.. moduleauthor:: <NAME> <<EMAIL>>
'''
from __future__ import absolute_import
import unittest
import os
from segeval.data.tsv import (input_linear_mass_tsv, input_linear_positions_tsv)
from segeval.data.samples import HEARST_1997_STARGAZER
class TestTsv(unittest.TestCa... | [
"segeval.data.tsv.input_linear_positions_tsv",
"os.path.join",
"segeval.data.tsv.input_linear_mass_tsv",
"os.path.split"
] | [((394, 417), 'os.path.split', 'os.path.split', (['__file__'], {}), '(__file__)\n', (407, 417), False, 'import os\n'), ((541, 591), 'os.path.join', 'os.path.join', (['self.test_data_dir', '"""hearst1997.tsv"""'], {}), "(self.test_data_dir, 'hearst1997.tsv')\n", (553, 591), False, 'import os\n'), ((610, 641), 'segeval.d... |
"""
:Author: <NAME>
:Date: Dec 06, 2019
:Version: 0.0.3
"""
import logging
import ltn.fol.fol_status as FOL
from ltn.fol.constant import constant
from ltn.fol.logic import Forall, Not
from ltn.fol.predicate import predicate
from ltn.fol.variable import variable
logging.basicConfig(format='[%(asctime)s] {%(pathname)s:... | [
"logging.basicConfig",
"ltn.fol.fol_status.train",
"ltn.fol.constant.constant",
"matplotlib.pyplot.pcolor",
"ltn.fol.predicate.predicate",
"matplotlib.pyplot.colorbar",
"pandas.set_option",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show"
] | [((264, 391), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s"""', 'level': 'logging.DEBUG'}), "(format=\n '[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s',\n level=logging.DEBUG)\n", (283, 391), False, 'imp... |
from ..config.config import LennyBotActionConfig
from .iaction import IAction
import requests
class DownloadResourcesAction(IAction):
def __init__(self, name, source_version, target_version, config: LennyBotActionConfig) -> None:
self._name = name
self._source_version = source_version
self... | [
"requests.get"
] | [((795, 821), 'requests.get', 'requests.get', (['download_url'], {}), '(download_url)\n', (807, 821), False, 'import requests\n')] |
from safenotes.paths import SAFENOTES_DIR_PATH, PASSWORD_FILE_PATH
from safenotes.colors import red, green, yellow, blue
from safenotes.helpers import display_colored_text
from hmac import compare_digest as compare_hash
from os.path import isfile, join
from os import listdir, system
from getpass import getpass
from cry... | [
"safenotes.paths.SAFENOTES_DIR_PATH.mkdir",
"os.listdir",
"os.getenv",
"os.path.join",
"getpass.getpass",
"os.system",
"crypt.crypt",
"safenotes.helpers.display_colored_text"
] | [((481, 534), 'safenotes.paths.SAFENOTES_DIR_PATH.mkdir', 'SAFENOTES_DIR_PATH.mkdir', ([], {'parents': '(True)', 'exist_ok': '(True)'}), '(parents=True, exist_ok=True)\n', (505, 534), False, 'from safenotes.paths import SAFENOTES_DIR_PATH, PASSWORD_FILE_PATH\n'), ((1091, 1192), 'safenotes.helpers.display_colored_text',... |
import sys
import rospy
import signal
from geometry_msgs.msg import Twist
# AUTONOMOUS MOVEMENT
from A_movement.baseline.A_Baseline import A_Baseline
from A_movement.ee1.A_EE1 import A_EE1
from A_movement.ee2.A_EE2 import A_EE2
from A_movement.ee3.A_EE3 import A_EE3
from A_movement.ee4.A_EE4 import A_EE4
from A_movem... | [
"signal.signal",
"A_movement.baseline.A_Baseline.A_Baseline",
"common.recording.MetricsRecorder.MetricsRecorder"
] | [((1105, 1122), 'common.recording.MetricsRecorder.MetricsRecorder', 'MetricsRecorder', ([], {}), '()\n', (1120, 1122), False, 'from common.recording.MetricsRecorder import MetricsRecorder\n'), ((1250, 1288), 'signal.signal', 'signal.signal', (['signal.SIGTSTP', 'handler'], {}), '(signal.SIGTSTP, handler)\n', (1263, 128... |
import numpy as np
import torch
from torchvision import models
from utils import process_image
import json
from torch import nn, optim
from collections import OrderedDict
#loads a checkpoint and rebuilds the model
def load_checkpoint(filepath):
checkpoint = torch.load(filepath)
if checkpoint['arch'] ==... | [
"torch.nn.ReLU",
"torch.nn.Dropout",
"torch.load",
"torch.topk",
"numpy.argmax",
"torch.exp",
"torchvision.models.vgg11",
"utils.process_image",
"torch.cuda.is_available",
"torch.nn.NLLLoss",
"torch.nn.Linear",
"torch.nn.LogSoftmax",
"json.load",
"torch.no_grad",
"torchvision.models.vgg1... | [((266, 286), 'torch.load', 'torch.load', (['filepath'], {}), '(filepath)\n', (276, 286), False, 'import torch\n'), ((1217, 1229), 'torch.nn.NLLLoss', 'nn.NLLLoss', ([], {}), '()\n', (1227, 1229), False, 'from torch import nn, optim\n'), ((1813, 1843), 'utils.process_image', 'process_image', (['image_path', 'gpu'], {})... |
#!/usr/bin/env python
# Copyright 2016-2019 Biomedical Imaging Group Rotterdam, Departments of
# Medical Informatics and Radiology, Erasmus MC, Rotterdam, The Netherlands
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obt... | [
"numpy.mean",
"argparse.ArgumentParser",
"matplotlib.use",
"collections.Counter",
"numpy.random.seed",
"tikzplotlib.save",
"matplotlib.pyplot.rcdefaults",
"matplotlib.pyplot.subplots",
"pandas.read_hdf"
] | [((737, 758), 'matplotlib.use', 'matplotlib.use', (['"""agg"""'], {}), "('agg')\n", (751, 758), False, 'import matplotlib\n'), ((2107, 2130), 'pandas.read_hdf', 'pd.read_hdf', (['prediction'], {}), '(prediction)\n', (2118, 2130), True, 'import pandas as pd\n'), ((3724, 3748), 'numpy.random.seed', 'np.random.seed', (['(... |
# Generated by Django 2.2.24 on 2021-11-04 08:51
from django.db import migrations, models
def update_stood_down(self, schema_editor):
"Set is_stood_down value depending on molnix_status for existing records"
SurgeAlert = self.get_model('notifications', 'surgealert')
for record in SurgeAlert.objects.all():... | [
"django.db.migrations.RunPython",
"django.db.models.BooleanField"
] | [((805, 884), 'django.db.migrations.RunPython', 'migrations.RunPython', (['update_stood_down'], {'reverse_code': 'migrations.RunPython.noop'}), '(update_stood_down, reverse_code=migrations.RunPython.noop)\n', (825, 884), False, 'from django.db import migrations, models\n'), ((719, 784), 'django.db.models.BooleanField',... |
# Generated by Django 2.2.2 on 2019-07-03 13:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('radio', '0004_new_song_path_structure'),
]
operations = [
migrations.AddField(
model_name='store',
name='track_gain'... | [
"django.db.models.DecimalField"
] | [((340, 468), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'blank': '(True)', 'decimal_places': '(2)', 'max_digits': '(6)', 'null': '(True)', 'verbose_name': '"""recommended replaygain adjustment"""'}), "(blank=True, decimal_places=2, max_digits=6, null=True,\n verbose_name='recommended replaygain a... |
import eel
import numpy as np
import datetime
def rotate(arr, x, y, z):
cos_z, sin_z, cos_y = np.cos(z), np.sin(z), np.cos(y)
sin_y, cos_x, sin_x = np.sin(y), np.cos(x), np.sin(x)
rot_mat = [[cos_z*cos_y, cos_z*sin_y*sin_x - sin_z*cos_x, cos_z*sin_y*cos_x + sin_z*sin_x],
[sin_z*cos_y, sin_z*sin_y*sin_x + cos_z... | [
"numpy.random.normal",
"eel.sleep",
"eel.start",
"eel.init",
"numpy.array",
"numpy.zeros",
"datetime.datetime.now",
"numpy.dot",
"numpy.cos",
"numpy.sin",
"eel.drawLines"
] | [((957, 1043), 'numpy.array', 'np.array', (['[0, 1, 0, 2, 0, 4, 1, 3, 1, 5, 2, 3, 2, 6, 3, 7, 4, 5, 4, 6, 5, 7, 6, 7]'], {}), '([0, 1, 0, 2, 0, 4, 1, 3, 1, 5, 2, 3, 2, 6, 3, 7, 4, 5, 4, 6, 5, 7,\n 6, 7])\n', (965, 1043), True, 'import numpy as np\n'), ((1022, 1039), 'numpy.zeros', 'np.zeros', (['(3, 24)'], {}), '((3... |
from utils import escape_text, make_fake_message
def test_template_basis():
from nonebot.adapters import MessageTemplate
template = MessageTemplate("{key:.3%}")
formatted = template.format(key=0.123456789)
assert formatted == "12.346%"
def test_template_message():
Message = make_fake_message()
... | [
"nonebot.adapters.MessageTemplate",
"utils.escape_text",
"utils.make_fake_message"
] | [((143, 171), 'nonebot.adapters.MessageTemplate', 'MessageTemplate', (['"""{key:.3%}"""'], {}), "('{key:.3%}')\n", (158, 171), False, 'from nonebot.adapters import MessageTemplate\n'), ((300, 319), 'utils.make_fake_message', 'make_fake_message', ([], {}), '()\n', (317, 319), False, 'from utils import escape_text, make_... |
import socket
from contextlib import closing
from typing import cast
from .logging import LoggingDescriptor
_logger = LoggingDescriptor(name=__name__)
def find_free_port() -> int:
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
s.bind(("127.0.0.1", 0))
s.setsockopt(socket.S... | [
"socket.socket"
] | [((201, 250), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (214, 250), False, 'import socket\n'), ((458, 507), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (471, ... |
# -*- coding: utf-8 -*-
import os
import distutils.util
try:
from config import *
except ImportError:
from config_example import *
def env_bool(env, default):
if os.environ.get(env):
return distutils.util.strtobool(os.environ.get(env))
else:
return default
def env_str(env, default)... | [
"os.environ.get",
"os.getenv"
] | [((178, 197), 'os.environ.get', 'os.environ.get', (['env'], {}), '(env)\n', (192, 197), False, 'import os\n'), ((333, 356), 'os.getenv', 'os.getenv', (['env', 'default'], {}), '(env, default)\n', (342, 356), False, 'import os\n'), ((393, 412), 'os.environ.get', 'os.environ.get', (['env'], {}), '(env)\n', (407, 412), Fa... |
#!/usr/local/bin/python3
import sys
import serial
#SERIAL_DEVICE = "/dev/tty.SLAB_USBtoUART"
SERIAL_DEVICE = "/dev/tty.usbserial-1410"
MY_AXIS = 'X'
DISABLE_MOSFETS_COMMAND = 0
ENABLE_MOSFETS_COMMAND = 1
SET_POSITION_AND_MOVE_COMMAND = 2
SET_VELOCITY_COMMAND = 3
SET_POSITION_AND_FINISH_TIME_COMMAND = 4
SET_ACCELERA... | [
"serial.Serial"
] | [((939, 988), 'serial.Serial', 'serial.Serial', (['SERIAL_DEVICE', '(230400)'], {'timeout': '(0.5)'}), '(SERIAL_DEVICE, 230400, timeout=0.5)\n', (952, 988), False, 'import serial\n')] |
#!/usr/bin/env python
#####################################
# Sense temperature from SenseHat
# Send data to third party api.
#####################################
from subprocess import call
import os, sys, json, time, urllib2, getopt
sys.path.append('../lib')
import osutils as utils
try:
from sense_hat import ... | [
"getopt.getopt",
"urllib2.urlopen",
"sense_hat.SenseHat",
"osutils.install_pkg",
"time.sleep",
"os.path.basename",
"sys.exit",
"sys.path.append"
] | [((238, 263), 'sys.path.append', 'sys.path.append', (['"""../lib"""'], {}), "('../lib')\n", (253, 263), False, 'import os, sys, json, time, urllib2, getopt\n'), ((477, 519), 'urllib2.urlopen', 'urllib2.urlopen', (["(url + '&field1=%s' % temp)"], {}), "(url + '&field1=%s' % temp)\n", (492, 519), False, 'import os, sys, ... |
#!/usr/bin/env python2
import urllib.request
import cv2
import os
import random
import json
cap=cv2.VideoCapture(0)
while cap.isOpened():
status,img=cap.read()
cv2.imshow("Press C for 2 sec to capture the photo",img)
if cv2.waitKey(1) & 0xff==ord('c'):
cv2.imshow("Capture Image",img)
num=s... | [
"cv2.imwrite",
"cv2.imshow",
"cv2.destroyAllWindows",
"cv2.VideoCapture",
"os.system",
"random.random",
"cv2.waitKey"
] | [((97, 116), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (113, 116), False, 'import cv2\n'), ((1206, 1229), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (1227, 1229), False, 'import cv2\n'), ((169, 226), 'cv2.imshow', 'cv2.imshow', (['"""Press C for 2 sec to capture the photo"... |
# coding: utf-8
"""
Author @NirajDevPandey
Purpose = Passage search for a given query using Doc2Vec algorithm. this will train your own
text passages and return the most similar paragraph from the corpus. The more passages you
have the better it works. I would recommend to use pre trained model if you have less data... | [
"gensim.models.doc2vec.Doc2Vec",
"smart_open.smart_open",
"warnings.filterwarnings",
"gensim.utils.simple_preprocess"
] | [((632, 665), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (655, 665), False, 'import warnings\n'), ((1245, 1314), 'gensim.models.doc2vec.Doc2Vec', 'gensim.models.doc2vec.Doc2Vec', ([], {'vector_size': '(50)', 'min_count': '(2)', 'epochs': '(50)'}), '(vector_size=50, min... |
"""End-to-end test for templar/cli/templar.py"""
from templar.api.config import ConfigBuilderError
from templar.cli import templar
import io
import mock
import os.path
import shutil
import unittest
STAGING_DIR = os.path.join('tests', 'cli', 'staging')
TEST_DATA = os.path.join('tests', 'cli', 'test_data')
class Temp... | [
"mock.patch",
"shutil.rmtree"
] | [((432, 458), 'shutil.rmtree', 'shutil.rmtree', (['STAGING_DIR'], {}), '(STAGING_DIR)\n', (445, 458), False, 'import shutil\n'), ((2726, 2776), 'mock.patch', 'mock.patch', (['"""sys.stdout"""'], {'new_callable': 'io.StringIO'}), "('sys.stdout', new_callable=io.StringIO)\n", (2736, 2776), False, 'import mock\n'), ((3604... |
"""Test embedding different file formats and different encodings within the <Data> tag."""
import unittest
import os
from pywps import get_ElementMakerForVersion
from pywps.app.basic import get_xpath_ns
from pywps import Service, Process, ComplexInput, ComplexOutput, FORMATS
from pywps.tests import client_for, assert_... | [
"pywps.get_ElementMakerForVersion",
"owslib.wps.WPSExecution",
"pywps.app.basic.get_xpath_ns",
"pywps.ComplexInput",
"base64.b64encode",
"pywps.tests.assert_response_success",
"owslib.wps.ComplexDataInput",
"os.path.dirname",
"pywps.ComplexOutput"
] | [((457, 492), 'pywps.get_ElementMakerForVersion', 'get_ElementMakerForVersion', (['VERSION'], {}), '(VERSION)\n', (483, 492), False, 'from pywps import get_ElementMakerForVersion\n'), ((504, 525), 'pywps.app.basic.get_xpath_ns', 'get_xpath_ns', (['VERSION'], {}), '(VERSION)\n', (516, 525), False, 'from pywps.app.basic ... |
import os
import glob
import random
class PairGenerator(object):
person1 = 'person1'
person2 = 'person2'
label = 'same_person'
def __init__(self, lfw_path='./tf_dataset/resources' + os.path.sep + 'lfw'):
self.all_people = self.generate_all_people_dict(lfw_path)
def generate_all_people_di... | [
"random.choice",
"random.random",
"os.listdir",
"glob.glob"
] | [((477, 497), 'os.listdir', 'os.listdir', (['lfw_path'], {}), '(lfw_path)\n', (487, 497), False, 'import os\n'), ((527, 600), 'glob.glob', 'glob.glob', (["(lfw_path + os.path.sep + person_folder + os.path.sep + '*.jpg')"], {}), "(lfw_path + os.path.sep + person_folder + os.path.sep + '*.jpg')\n", (536, 600), False, 'im... |
"""Added a type for processes
Revision ID: eadce7fbbf49
Revises: <PASSWORD>
Create Date: 2018-08-31 13:24:22.009338
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '<PASSWORD>'
branch_labels = None
depends_on = None
def upgrade():
... | [
"sqlalchemy.String",
"alembic.op.drop_column"
] | [((425, 462), 'alembic.op.drop_column', 'op.drop_column', (['"""processes"""', '"""p_type"""'], {}), "('processes', 'p_type')\n", (439, 462), False, 'from alembic import op\n'), ((367, 378), 'sqlalchemy.String', 'sa.String', ([], {}), '()\n', (376, 378), True, 'import sqlalchemy as sa\n')] |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import pytz
import datetime
BASEDIR = os.path.realpath(os.path.dirname(__file__))
### Core Settings
DB_URL = 'postgresql+psycopg2://compiler2017:mypassword@localhost/compiler2017'
# DB_URL = 'sqlite:///data/compiler.db'
TIMEZONE = pytz.timezone(... | [
"os.path.dirname",
"pytz.timezone",
"os.path.join"
] | [((306, 336), 'pytz.timezone', 'pytz.timezone', (['"""Asia/Shanghai"""'], {}), "('Asia/Shanghai')\n", (319, 336), False, 'import pytz\n'), ((594, 632), 'os.path.join', 'os.path.join', (['BASEDIR', '"""data"""', '"""build"""'], {}), "(BASEDIR, 'data', 'build')\n", (606, 632), False, 'import os\n'), ((660, 700), 'os.path... |
import matplotlib.pyplot as plt
import cv2
import numpy as np
def plot_imgs(imgs, titles=None, cmap='brg', ylabel='', normalize=True, ax=None,
r=(0, 1), dpi=100):
n = len(imgs)
if not isinstance(cmap, list):
cmap = [cmap]*n
if ax is None:
_, ax = plt.subplots(1, n, figsize=(6... | [
"cv2.line",
"numpy.array",
"cv2.circle",
"numpy.random.randint",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.subplots",
"numpy.round",
"matplotlib.pyplot.get_cmap"
] | [((1245, 1263), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (1261, 1263), True, 'import matplotlib.pyplot as plt\n'), ((291, 338), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', 'n'], {'figsize': '(6 * n, 6)', 'dpi': 'dpi'}), '(1, n, figsize=(6 * n, 6), dpi=dpi)\n', (303, 338), True,... |
import typing as tp
import pydantic
import yaml
from loguru import logger
from .config_models import GlobalConfig, CameraConfigSection
@logger.catch(reraise=True)
@tp.no_type_check
def _load_config(config_path: str, model) -> tp.Any:
logger.debug(f"Looking for config in {config_path}")
with open(config_pat... | [
"loguru.logger.catch",
"loguru.logger.debug",
"pydantic.parse_obj_as"
] | [((140, 166), 'loguru.logger.catch', 'logger.catch', ([], {'reraise': '(True)'}), '(reraise=True)\n', (152, 166), False, 'from loguru import logger\n'), ((242, 294), 'loguru.logger.debug', 'logger.debug', (['f"""Looking for config in {config_path}"""'], {}), "(f'Looking for config in {config_path}')\n", (254, 294), Fal... |
import json
import networkx as nx
def createGraphs(data):
graphs=[]
for timeIdx,window in enumerate(data['windows']):
interval_graphs=[]
for com_index,community in enumerate(window['communities']):
com_id = 'TF'+str(timeIdx)+'_c'+str(com_index)
G = nx.MultiDiGraph(cid=com_id)
G.add_edges_from(community... | [
"json.load",
"networkx.MultiDiGraph"
] | [((263, 290), 'networkx.MultiDiGraph', 'nx.MultiDiGraph', ([], {'cid': 'com_id'}), '(cid=com_id)\n', (278, 290), True, 'import networkx as nx\n'), ((485, 497), 'json.load', 'json.load', (['f'], {}), '(f)\n', (494, 497), False, 'import json\n')] |
#!/usr/bin/python
# -*- encoding: utf-8 -*-
import math
from bisect import bisect_right
import torch
class WarmupLrScheduler(torch.optim.lr_scheduler._LRScheduler):
def __init__(
self,
optimizer,
warmup_iter,
warmup_ratio=5e-4,
warmup='exp',
... | [
"matplotlib.pyplot.grid",
"torch.nn.Conv2d",
"math.cos",
"numpy.array",
"bisect.bisect_right",
"numpy.arange",
"matplotlib.pyplot.show"
] | [((4201, 4232), 'torch.nn.Conv2d', 'torch.nn.Conv2d', (['(3)', '(16)', '(3)', '(1)', '(1)'], {}), '(3, 16, 3, 1, 1)\n', (4216, 4232), False, 'import torch\n'), ((4640, 4653), 'numpy.array', 'np.array', (['lrs'], {}), '(lrs)\n', (4648, 4653), True, 'import numpy as np\n'), ((4715, 4725), 'matplotlib.pyplot.grid', 'plt.g... |
import pandas as pd
import numpy as np
project_directory = '/Users/etiennelenaour/Desktop/Stage/'
sentiment_score = pd.read_excel(project_directory + "csv_files/" +'inquirerbasic.xls')
df_true = pd.read_csv(project_directory + 'csv_files/final_df_v3.csv')
def creation_list(df, cate):
final_list = list()
fo... | [
"pandas.read_csv",
"pandas.read_excel"
] | [((122, 191), 'pandas.read_excel', 'pd.read_excel', (["(project_directory + 'csv_files/' + 'inquirerbasic.xls')"], {}), "(project_directory + 'csv_files/' + 'inquirerbasic.xls')\n", (135, 191), True, 'import pandas as pd\n'), ((201, 261), 'pandas.read_csv', 'pd.read_csv', (["(project_directory + 'csv_files/final_df_v3.... |
from abc import ABC
from pathlib import Path
from typing import List, Union
import pytest
from pydantic import BaseModel
from yaml import load
from auto_optional.file_handling import convert_file
try:
from yaml import CLoader as YamlLoader
except ImportError:
from yaml import YamlLoader # type: ignore
cla... | [
"pytest.mark.parametrize",
"auto_optional.file_handling.convert_file",
"yaml.load",
"pathlib.Path"
] | [((894, 1002), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""test_config"""', 'SINGLE_FILE_TESTS'], {'ids': '[test.name for test in SINGLE_FILE_TESTS]'}), "('test_config', SINGLE_FILE_TESTS, ids=[test.name for\n test in SINGLE_FILE_TESTS])\n", (917, 1002), False, 'import pytest\n'), ((1183, 1215), 'aut... |
# The MIT License (MIT)
#
# 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, distribute, subl... | [
"data_utils.get_batch",
"data_utils.add_padding",
"random.shuffle"
] | [((2515, 2534), 'random.shuffle', 'random.shuffle', (['qna'], {}), '(qna)\n', (2529, 2534), False, 'import random\n'), ((2056, 2111), 'data_utils.get_batch', 'data_gen.get_batch', (['length', 'batch_size', '(False)', 'cnf.task'], {}), '(length, batch_size, False, cnf.task)\n', (2074, 2111), True, 'import data_utils as ... |
from .helper import parse_rule_list, inherit_json
from .exceptions import VersionNotFound
from .utils import get_library_version
from typing import Dict, List, Any
from .natives import get_natives
import platform
import json
import copy
import os
__all__ = ["get_minecraft_command"]
def get_libraries(data: Dict[str,A... | [
"os.path.join",
"json.load",
"copy.copy",
"platform.system"
] | [((5133, 5151), 'copy.copy', 'copy.copy', (['options'], {}), '(options)\n', (5142, 5151), False, 'import copy\n'), ((425, 442), 'platform.system', 'platform.system', ([], {}), '()\n', (440, 442), False, 'import platform\n'), ((672, 703), 'os.path.join', 'os.path.join', (['path', '"""libraries"""'], {}), "(path, 'librar... |
# crossvalidation evaluation script
import datetime
import itertools
import os
import sys
from ginipls.__main__ import train_on_vectors, apply_on_vectors, evaluate, f1_score_on_prediction_file, \
accuracy_score_on_prediction_file
from ginipls.models.ginipls import PLS_VARIANT
from ginipls.config import GLOBAL_LOGGE... | [
"ginipls.__main__.accuracy_score_on_prediction_file",
"ginipls.config.GLOBAL_LOGGER.info",
"os.makedirs",
"ginipls.__main__.f1_score_on_prediction_file",
"itertools.product",
"os.path.join",
"ginipls.config.GLOBAL_LOGGER.debug",
"os.path.isfile",
"os.path.isdir",
"ginipls.__main__.apply_on_vectors... | [((396, 425), 'os.path.join', 'os.path.join', (['wd', '"""processed"""'], {}), "(wd, 'processed')\n", (408, 425), False, 'import os\n'), ((477, 504), 'os.path.isdir', 'os.path.isdir', (['matrices_dir'], {}), '(matrices_dir)\n', (490, 504), False, 'import os\n'), ((522, 548), 'os.path.join', 'os.path.join', (['wd', '"""... |
import requests
base = "https://danbot.host/nodeStatus"
sysinfo = 'https://danbot.host/sysinfo'
leaderboard = "https://api.danbot.host/leaderboard"
######################################
##### GETTING ALL STATUS #####
######################################
def getallstats():
r = requests.get(base)
if r... | [
"requests.get"
] | [((293, 311), 'requests.get', 'requests.get', (['base'], {}), '(base)\n', (305, 311), False, 'import requests\n'), ((679, 697), 'requests.get', 'requests.get', (['base'], {}), '(base)\n', (691, 697), False, 'import requests\n'), ((2082, 2100), 'requests.get', 'requests.get', (['base'], {}), '(base)\n', (2094, 2100), Fa... |
#!/usr/bin/env python3
import pandas as pd
import numpy as np
def last_week():
# Create the dataframe
df = pd.read_csv("src/UK-top40-1964-1-2.tsv", sep="\t")
# Replace songs that weren't on the last week's list with nulls.
cond = (df["LW"] != "New") & (df["LW"] != "Re")
df = df.where(cond, ot... | [
"pandas.isna",
"pandas.notna",
"pandas.read_csv"
] | [((117, 167), 'pandas.read_csv', 'pd.read_csv', (['"""src/UK-top40-1964-1-2.tsv"""'], {'sep': '"""\t"""'}), "('src/UK-top40-1964-1-2.tsv', sep='\\t')\n", (128, 167), True, 'import pandas as pd\n'), ((974, 989), 'pandas.isna', 'pd.isna', (['df.Pos'], {}), '(df.Pos)\n', (981, 989), True, 'import pandas as pd\n'), ((833, ... |
from __future__ import unicode_literals, print_function
import io
import json
from snips_nlu import SnipsNLUEngine
from snips_nlu.default_configs import CONFIG_EN
import glob
class IntentRecognition:
def __init__(self, name=''):
self.name = name
def loadntrain(self, rootpath = './datasets/*.json'):
... | [
"json.load",
"snips_nlu.SnipsNLUEngine",
"glob.glob",
"io.open"
] | [((340, 359), 'glob.glob', 'glob.glob', (['rootpath'], {}), '(rootpath)\n', (349, 359), False, 'import glob\n'), ((522, 554), 'snips_nlu.SnipsNLUEngine', 'SnipsNLUEngine', ([], {'config': 'CONFIG_EN'}), '(config=CONFIG_EN)\n', (536, 554), False, 'from snips_nlu import SnipsNLUEngine\n'), ((443, 456), 'io.open', 'io.ope... |
import numpy as np
import utils
from dataset_specifications.dataset import Dataset
class ConstNoiseSet(Dataset):
def __init__(self):
super().__init__()
self.name = "const_noise"
self.std_dev = np.sqrt(0.25)
def get_support(self, x):
return (x-2*self.std_dev, x+2*self.std_dev)... | [
"numpy.random.normal",
"utils.get_gaussian_pdf",
"numpy.sqrt",
"numpy.stack",
"numpy.random.uniform"
] | [((224, 237), 'numpy.sqrt', 'np.sqrt', (['(0.25)'], {}), '(0.25)\n', (231, 237), True, 'import numpy as np\n'), ((360, 405), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(-1.0)', 'high': '(1.0)', 'size': 'n'}), '(low=-1.0, high=1.0, size=n)\n', (377, 405), True, 'import numpy as np\n'), ((420, 473), 'nump... |
import sys
import json
import time
import pexpect
import pexpect.replwrap
import subprocess
with open(sys.argv[1], 'r') as f:
log = json.load(f)
tidal_startup = subprocess.check_output('bash -c "ghc-pkg field -f ~/.cabal/store/ghc-$(ghc --numeric-version)/package.db tidal data-dir --simple-output"', shell=True).... | [
"subprocess.check_output",
"pexpect.replwrap.REPLWrapper",
"subprocess.Popen",
"time.sleep",
"json.load"
] | [((369, 426), 'subprocess.Popen', 'subprocess.Popen', (["['ghci', '-ghci-script', tidal_startup]"], {}), "(['ghci', '-ghci-script', tidal_startup])\n", (385, 426), False, 'import subprocess\n'), ((435, 551), 'pexpect.replwrap.REPLWrapper', 'pexpect.replwrap.REPLWrapper', (['f"""ghci -ghci-script {tidal_startup}"""', '"... |
# -*- coding: utf-8 -*-
"""
Copyright (c) Microsoft Corporation. All Rights Reserved.
Licensed under the MIT license. See LICENSE file on the project webpage for details.
XBlock to allow for video playback from Azure Media Services
Built using documentation from: http://amp.azure.net/libs/amp/latest/docs/index.html
"... | [
"logging.getLogger",
"azure_video_pipeline.utils.get_video_info",
"edxval.models.Video.objects.filter",
"xblock.core.XBlock.needs",
"django.http.HttpResponseBadRequest",
"xmodule.modulestore.django.modulestore",
"xblock.fragment.Fragment",
"edxval.models.Video.objects.get",
"requests.get",
"lms.dj... | [((1300, 1327), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1317, 1327), False, 'import logging\n'), ((1337, 1361), 'xblockutils.resources.ResourceLoader', 'ResourceLoader', (['__name__'], {}), '(__name__)\n', (1351, 1361), False, 'from xblockutils.resources import ResourceLoader\n'),... |
#!/usr/bin/python
from getpass import getpass
from os import system
system('clear')
# colors
red = "\033[91;1m"
green = "\033[92;1m"
yellow = "\033[93;1m"
blue = "\033[94;1m"
# banner
print(green +
'''
┌───────────────────────────────┐
│╻ ╻┏━┓┏━┓╻ ╻ ┏┓ ╻ ╻┏━┓╺┳╸┏━╸┏━┓│
│┣━┫┣━┫┗━┓┣━┫ ┣┻┓┃ ┃┗━┓ ┃ ┣╸ ┣┳┛│
│╹ ╹╹ ╹┗━┛╹... | [
"os.system"
] | [((69, 84), 'os.system', 'system', (['"""clear"""'], {}), "('clear')\n", (75, 84), False, 'from os import system\n'), ((746, 780), 'os.system', 'system', (['"""python modules/hasher.py"""'], {}), "('python modules/hasher.py')\n", (752, 780), False, 'from os import system\n'), ((821, 858), 'os.system', 'system', (['"""p... |
# Copyright (c) 2021, 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 i... | [
"cugraph.utilities.check_nx_graph",
"cudf.Series",
"collections.defaultdict",
"cudf.DataFrame",
"cugraph.sampling.random_walks_wrapper.random_walks"
] | [((1944, 1979), 'cugraph.utilities.check_nx_graph', 'cugraph.utilities.check_nx_graph', (['G'], {}), '(G)\n', (1976, 1979), False, 'import cugraph\n'), ((2485, 2548), 'cugraph.sampling.random_walks_wrapper.random_walks', 'random_walks_wrapper.random_walks', (['G', 'start_vertices', 'max_depth'], {}), '(G, start_vertice... |
#!/usr/bin/env python
from __future__ import print_function
# Core
import collections
from functools import wraps
import logging
import pprint
import random
import re
import time
import ConfigParser
from decimal import *
# Third-Party
import argh
from clint.textui import progress
import html2text
from PIL import Ima... | [
"re.compile",
"time.sleep",
"ConfigParser.ConfigParser",
"logging.info",
"argh.dispatch_command",
"logging.warn",
"html2text.HTML2Text",
"functools.wraps",
"pprint.PrettyPrinter",
"selenium.webdriver.support.ui.WebDriverWait",
"random.randrange",
"splinter.Browser",
"selenium.webdriver.suppo... | [((737, 811), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(lineno)s - %(message)s"""', 'level': 'logging.INFO'}), "(format='%(lineno)s - %(message)s', level=logging.INFO)\n", (756, 811), False, 'import logging\n'), ((823, 836), 'random.seed', 'random.seed', ([], {}), '()\n', (834, 836), False, 'i... |
from collections import OrderedDict, defaultdict
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import time
import torch
from FClip.line_parsing import OneStageLineParsing
from FClip.config import M
from FClip.losses import ce_loss, sigmoid_l1_loss, focal_loss, l12loss
from FClip.nms import ... | [
"FClip.losses.l12loss",
"collections.OrderedDict",
"FClip.nms.structure_nms_torch",
"FClip.losses.ce_loss",
"FClip.line_parsing.OneStageLineParsing.fclip_torch",
"FClip.losses.sigmoid_l1_loss",
"time.time",
"FClip.config.M.to_dict",
"FClip.losses.focal_loss",
"torch.cat",
"torch.nn.functional.bi... | [((492, 503), 'FClip.config.M.to_dict', 'M.to_dict', ([], {}), '()\n', (501, 503), False, 'from FClip.config import M\n'), ((6492, 6503), 'time.time', 'time.time', ([], {}), '()\n', (6501, 6503), False, 'import time\n'), ((1266, 1297), 'FClip.losses.focal_loss', 'focal_loss', (['pred', 'target', 'alpha'], {}), '(pred, ... |
import os
import sys
import json
import logging
import numpy as np
logging.basicConfig(level=logging.INFO)
from robo.solver.hyperband_datasets_size import HyperBand_DataSubsets
from hpolib.benchmarks.ml.surrogate_svm import SurrogateSVM
run_id = int(sys.argv[1])
seed = int(sys.argv[2])
rng = np.random.RandomState(... | [
"logging.basicConfig",
"os.makedirs",
"json.dump",
"numpy.log",
"os.path.join",
"hpolib.benchmarks.ml.surrogate_svm.SurrogateSVM",
"robo.solver.hyperband_datasets_size.HyperBand_DataSubsets",
"numpy.random.RandomState"
] | [((68, 107), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (87, 107), False, 'import logging\n'), ((298, 325), 'numpy.random.RandomState', 'np.random.RandomState', (['seed'], {}), '(seed)\n', (319, 325), True, 'import numpy as np\n'), ((353, 448), 'hpolib.bench... |
import numpy as np
from slugnet.activation import ReLU, Softmax
from slugnet.layers import Convolution, Dense, MeanPooling, Flatten
from slugnet.loss import SoftmaxCategoricalCrossEntropy as SCCE
from slugnet.model import Model
from slugnet.optimizers import SGD
from slugnet.data.mnist import get_mnist
X, y = get_mn... | [
"slugnet.activation.Softmax",
"slugnet.layers.Convolution",
"slugnet.optimizers.SGD",
"slugnet.layers.Flatten",
"slugnet.data.mnist.get_mnist",
"numpy.random.seed",
"slugnet.loss.SoftmaxCategoricalCrossEntropy",
"slugnet.layers.MeanPooling",
"numpy.random.permutation"
] | [((314, 325), 'slugnet.data.mnist.get_mnist', 'get_mnist', ([], {}), '()\n', (323, 325), False, 'from slugnet.data.mnist import get_mnist\n'), ((365, 384), 'numpy.random.seed', 'np.random.seed', (['(100)'], {}), '(100)\n', (379, 384), True, 'import numpy as np\n'), ((421, 440), 'numpy.random.seed', 'np.random.seed', ([... |
#!/usr/bin/env python
from __future__ import print_function
import MV2
import cdms2
import vcs
import genutil
import glob
import numpy
# import time
import datetime
from genutil import StringConstructor
import os
import pkg_resources
pmp_egg_path = pkg_resources.resource_filename(
pkg_resources.Requirement.parse("... | [
"vcs.createtext",
"vcs.createtextorientation",
"numpy.logical_not",
"vcs.createtemplate",
"MV2.array",
"numpy.array",
"pkg_resources.Requirement.parse",
"genutil.arrayindexing.set",
"numpy.ma.logical_not",
"MV2.count",
"MV2.transpose",
"MV2.ones",
"MV2.sqrt",
"MV2.concatenate",
"MV2.mask... | [((287, 335), 'pkg_resources.Requirement.parse', 'pkg_resources.Requirement.parse', (['"""pcmdi_metrics"""'], {}), "('pcmdi_metrics')\n", (318, 335), False, 'import pkg_resources\n'), ((912, 928), 'vcs.createtext', 'vcs.createtext', ([], {}), '()\n', (926, 928), False, 'import vcs\n'), ((2475, 2502), 'vcs.createtextori... |
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from . import models, serializers
class Notifys(APIView):
def get(self, request, format=None):
user = request.user
notifys = models.Notify.objects.filter(to=user)
seri... | [
"rest_framework.response.Response"
] | [((395, 452), 'rest_framework.response.Response', 'Response', ([], {'data': 'serializer.data', 'status': 'status.HTTP_200_OK'}), '(data=serializer.data, status=status.HTTP_200_OK)\n', (403, 452), False, 'from rest_framework.response import Response\n')] |
import random
import numpy as np
def divided_training_test(examples_matrix, lbls, train_prec):
concatenated_examples_lbs = np.concatenate((examples_matrix, lbls), axis=1)
np.random.shuffle(concatenated_examples_lbs)
size_of_vector = np.shape(concatenated_examples_lbs)[1]
size_of_matrix = len(concaten... | [
"numpy.shape",
"numpy.concatenate",
"numpy.random.shuffle"
] | [((129, 176), 'numpy.concatenate', 'np.concatenate', (['(examples_matrix, lbls)'], {'axis': '(1)'}), '((examples_matrix, lbls), axis=1)\n', (143, 176), True, 'import numpy as np\n'), ((181, 225), 'numpy.random.shuffle', 'np.random.shuffle', (['concatenated_examples_lbs'], {}), '(concatenated_examples_lbs)\n', (198, 225... |
""" Prepare Tests
Script generating and a set of parameters for simulations.
Parameters are saved as set in `parameters/test_set`
To use just run
python test_set
script does not take any command line arguments or flags.
The script is intended to provide a simple way to describe
what experiments to perform.
""... | [
"numpy.linspace",
"sortedcontainers.SortedSet",
"numpy.random.randn"
] | [((433, 446), 'sortedcontainers.SortedSet', 'SortedSet', (['[]'], {}), '([])\n', (442, 446), False, 'from sortedcontainers import SortedSet\n'), ((461, 474), 'sortedcontainers.SortedSet', 'SortedSet', (['[]'], {}), '([])\n', (470, 474), False, 'from sortedcontainers import SortedSet\n'), ((518, 541), 'numpy.linspace', ... |
from django.shortcuts import render
from .models import Osoba
def poosobama(request):
svao = Osoba.objects.all()
return render(request, "pitanja/index.html", {'svao' : svao})
# Create your views here.
| [
"django.shortcuts.render"
] | [((129, 182), 'django.shortcuts.render', 'render', (['request', '"""pitanja/index.html"""', "{'svao': svao}"], {}), "(request, 'pitanja/index.html', {'svao': svao})\n", (135, 182), False, 'from django.shortcuts import render\n')] |
"""
Copyright (c) 2021 Graphcore Ltd. All rights reserved.
"""
"""
# Efficient data loading with PopTorch
"""
"""
This tutorial will present how PopTorch could help to efficiently load data to
your model and how to avoid common sources of performance loss from the host.
This will also cover the more general notion of... | [
"torch.nn.GroupNorm",
"torch.nn.ReLU",
"time.time",
"torch.utils.data.TensorDataset",
"torch.nn.Conv2d",
"poptorch.DataLoader",
"torch.nn.MaxPool2d",
"torch.nn.NLLLoss",
"torch.nn.Linear",
"sys.exit",
"torch.nn.LogSoftmax",
"poptorch.Options",
"torch.empty",
"torch.randn",
"torch.flatten... | [((4709, 4727), 'poptorch.Options', 'poptorch.Options', ([], {}), '()\n', (4725, 4727), False, 'import poptorch\n'), ((5080, 5113), 'torch.randn', 'torch.randn', (['[10000, 1, 128, 128]'], {}), '([10000, 1, 128, 128])\n', (5091, 5113), False, 'import torch\n'), ((5184, 5232), 'torch.utils.data.TensorDataset', 'torch.ut... |
##################################################################################################
# Copyright (c) 2012 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restri... | [
"frog.models.Video.objects.all",
"frog.models.Image.objects.all"
] | [((2307, 2326), 'frog.models.Image.objects.all', 'Image.objects.all', ([], {}), '()\n', (2324, 2326), False, 'from frog.models import Gallery, Image, Video, Piece\n'), ((2716, 2735), 'frog.models.Video.objects.all', 'Video.objects.all', ([], {}), '()\n', (2733, 2735), False, 'from frog.models import Gallery, Image, Vid... |
import binascii
import os
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils.translation import ugettext_lazy as _
from project.apps.user.managers import UserManager, ActionTokenManager
from rest_framework.authtoken.models import Token
from django.utils import timezone... | [
"project.apps.user.managers.UserManager",
"django.utils.translation.ugettext_lazy",
"django.db.models.ForeignKey",
"os.urandom",
"project.apps.user.managers.ActionTokenManager",
"django.utils.timezone.now",
"django.utils.timezone.timedelta",
"django.db.models.DateTimeField",
"django.db.models.CharFi... | [((613, 626), 'project.apps.user.managers.UserManager', 'UserManager', ([], {}), '()\n', (624, 626), False, 'from project.apps.user.managers import UserManager, ActionTokenManager\n'), ((4212, 4281), 'django.db.models.CharField', 'models.CharField', ([], {'verbose_name': '"""Key"""', 'max_length': '(40)', 'primary_key'... |
"""Dummy DIMSE-C SCPs for use in unit tests"""
from copy import deepcopy
import logging
import os
import socket
import time
import threading
from pydicom import read_file
from pydicom.dataset import Dataset
from pydicom.uid import UID, ImplicitVRLittleEndian, JPEG2000Lossless
from pynetdicom import (
AE,
Ass... | [
"logging.getLogger",
"pynetdicom.Association",
"threading.Thread.__init__",
"os.path.join",
"pynetdicom.AE",
"time.sleep",
"pynetdicom.transport.AssociationSocket",
"os.path.dirname",
"copy.deepcopy",
"pydicom.dataset.Dataset"
] | [((2340, 2371), 'logging.getLogger', 'logging.getLogger', (['"""pynetdicom"""'], {}), "('pynetdicom')\n", (2357, 2371), False, 'import logging\n'), ((2466, 2491), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (2481, 2491), False, 'import os\n'), ((2532, 2579), 'os.path.join', 'os.path.join',... |
from __future__ import absolute_import
from ..coordinate import Coordinate
from ..roi import Roi
from .shared_graph_provider import\
SharedGraphProvider, SharedSubGraph
from ..graph import Graph, DiGraph
from pymongo import MongoClient, ASCENDING, ReplaceOne, UpdateOne
from pymongo.errors import BulkWriteError, Wri... | [
"logging.getLogger",
"numpy.int64",
"networkx.DiGraph",
"networkx.Graph",
"networkx.connected_components",
"pymongo.UpdateOne",
"numpy.uint64",
"networkx.weakly_connected_components",
"pymongo.ReplaceOne",
"pymongo.MongoClient",
"pymongo.errors.WriteError"
] | [((394, 421), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (411, 421), False, 'import logging\n'), ((19336, 19367), 'pymongo.MongoClient', 'MongoClient', (['self.provider.host'], {}), '(self.provider.host)\n', (19347, 19367), False, 'from pymongo import MongoClient, ASCENDING, ReplaceOn... |
#!BPY
"""
Name: 'Clean Weight...'
Blender: 245
Group: 'WeightPaint'
Tooltip: 'Removed verts from groups below a weight limit.'
"""
__author__ = "<NAME> aka ideasman42"
__url__ = ["www.blender.org", "blenderartists.org", "www.python.org"]
__version__ = "0.1"
__bpydoc__ = """\
Clean Weight
This Script is to be used on... | [
"BPyMesh.dict2MeshWeight",
"Blender.Draw.PupBlock",
"Blender.Draw.Create",
"Blender.Draw.PupMenu",
"Blender.Scene.GetCurrent",
"BPyMesh.meshWeight2Dict"
] | [((1475, 1502), 'BPyMesh.meshWeight2Dict', 'BPyMesh.meshWeight2Dict', (['me'], {}), '(me)\n', (1498, 1502), False, 'import BPyMesh\n'), ((2190, 2242), 'BPyMesh.dict2MeshWeight', 'BPyMesh.dict2MeshWeight', (['me', 'groupNames', 'vWeightDict'], {}), '(me, groupNames, vWeightDict)\n', (2213, 2242), False, 'import BPyMesh\... |
#!/usr/bin/python
import sys
import astor
from CodeRunner import runCode
from CustomExceptions import *
class DistanceCalculator():
def normalise_branch_distance(self, branch_distance):
try:
return 1 - pow(1.001, -branch_distance)
except OverflowError as e:
print(branch_distance)
raise e
def calc_bran... | [
"CodeRunner.runCode"
] | [((1096, 1114), 'CodeRunner.runCode', 'runCode', (['code_tree'], {}), '(code_tree)\n', (1103, 1114), False, 'from CodeRunner import runCode\n')] |
import csv
import json
#jsonfile = open('nuts.json', 'w')
#
#
#
#
#
# reader = csv.DictReader(csvfile, delimiter='|', quotechar='"')
# for row in reader:
# json.dump(row, jsonfile)
# jsonfile.write('\n')
#jsonfile.write('[')
#with open('nuts3-qgis.csv', mode="r", encoding="utf-8") as csv_file:
globallist = [... | [
"json.dumps",
"csv.DictReader"
] | [((407, 551), 'csv.DictReader', 'csv.DictReader', (['csv_file'], {'delimiter': '"""|"""', 'quotechar': '"""\\""""', 'fieldnames': "['level', 'code', 'country', 'label', 'nuts0', 'nuts1', 'nuts2', 'nuts3']"}), '(csv_file, delimiter=\'|\', quotechar=\'"\', fieldnames=[\'level\',\n \'code\', \'country\', \'label\', \'n... |
import json
import jydoop
import telemetryutils
setupjob = telemetryutils.setupjob
"""
Example job to read the SECURITY_UI histogram and output one row for each
entry in the "values" map.
Rows are of the form:
YYYYMMDD<uuid>, bucket, count, channel, os, os_version
"""
def map(key, value, cx):
try:
j = js... | [
"json.loads"
] | [((318, 335), 'json.loads', 'json.loads', (['value'], {}), '(value)\n', (328, 335), False, 'import json\n')] |
import time
def robo_sleep(duration, get_now=time.perf_counter):
now = get_now()
end = now + duration
while now < end:
now = get_now()
def check_time_sleep(amount):
start = time.perf_counter()
time.sleep(amount)
end = time.perf_counter()
return end-start
def check_robo_sleep(am... | [
"time.perf_counter",
"time.sleep"
] | [((201, 220), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (218, 220), False, 'import time\n'), ((225, 243), 'time.sleep', 'time.sleep', (['amount'], {}), '(amount)\n', (235, 243), False, 'import time\n'), ((254, 273), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (271, 273), False, 'import... |
import json
from lints.vim import VimVint, VimLParserLint
def test_vint_undefined_variable():
msg = ['t.vim:3:6: Undefined variable: s:test (see :help E738)']
res = VimVint().parse_loclist(msg, 1)
assert json.loads(res)[0] == {
"lnum": "3",
"col": "6",
"text": "[vint]Undefined var... | [
"lints.vim.VimLParserLint",
"json.loads",
"lints.vim.VimVint"
] | [((176, 185), 'lints.vim.VimVint', 'VimVint', ([], {}), '()\n', (183, 185), False, 'from lints.vim import VimVint, VimLParserLint\n'), ((219, 234), 'json.loads', 'json.loads', (['res'], {}), '(res)\n', (229, 234), False, 'import json\n'), ((549, 565), 'lints.vim.VimLParserLint', 'VimLParserLint', ([], {}), '()\n', (563... |
# 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
# distributed under th... | [
"logging.getLogger",
"logging.basicConfig",
"httpexceptor.HTTP302",
"datetime.datetime.utcnow",
"httpexceptor.HTTP404",
"purpler.store.Store",
"os.environ.get",
"selector.Selector",
"iso8601.parse_date",
"datetime.timedelta",
"jinja2.FileSystemLoader",
"httpexceptor.HTTP400",
"bleach.linkify... | [((781, 808), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (798, 808), False, 'import logging\n'), ((809, 830), 'logging.basicConfig', 'logging.basicConfig', ([], {}), '()\n', (828, 830), False, 'import logging\n'), ((1422, 1461), 'os.environ.get', 'os.environ.get', (['"""PURPLER_TEMPLA... |
import unittest
import numpy as np
import pytest
from audiomentations import TanhDistortion
from audiomentations.core.utils import calculate_rms
class TestTanhDistortion(unittest.TestCase):
def test_single_channel(self):
samples = np.random.normal(0, 0.1, size=(2048,)).astype(np.float32)
sample_... | [
"numpy.random.normal",
"numpy.allclose",
"audiomentations.core.utils.calculate_rms",
"audiomentations.TanhDistortion",
"numpy.amax"
] | [((353, 414), 'audiomentations.TanhDistortion', 'TanhDistortion', ([], {'min_distortion': '(0.2)', 'max_distortion': '(0.6)', 'p': '(1.0)'}), '(min_distortion=0.2, max_distortion=0.6, p=1.0)\n', (367, 414), False, 'from audiomentations import TanhDistortion\n'), ((1005, 1067), 'audiomentations.TanhDistortion', 'TanhDis... |
import json
import time
import traceback
from components.registrators.aws_iot.generic import AwsIoTGenericRegistrator
from handlers.utils import Logger, base_response
# Import Project Logger
project_logger = Logger()
logger = project_logger.get_logger()
# Set the Registration Class handler from the import to keep La... | [
"traceback.format_exc",
"json.loads",
"handlers.utils.Logger",
"handlers.utils.base_response",
"time.time"
] | [((210, 218), 'handlers.utils.Logger', 'Logger', ([], {}), '()\n', (216, 218), False, 'from handlers.utils import Logger, base_response\n'), ((1272, 1302), 'handlers.utils.base_response', 'base_response', ([], {'status_code': '(405)'}), '(status_code=405)\n', (1285, 1302), False, 'from handlers.utils import Logger, bas... |
### basic modules
import numpy as np
import time, pickle, os, sys, json, PIL, tempfile, warnings, importlib, math, copy, shutil, setproctitle
### torch modules
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from torchvision import datasets, transforms
from torch.opti... | [
"os.path.exists",
"os.makedirs",
"torch.utils.data.DataLoader",
"torchvision.transforms.RandomHorizontalFlip",
"torchvision.transforms.RandomCrop",
"torchvision.datasets.ImageFolder",
"torch.utils.data.distributed.DistributedSampler",
"torchvision.transforms.Normalize",
"torchvision.datasets.CIFAR10... | [((5470, 5529), 'torch.utils.data.distributed.DistributedSampler', 'torch.utils.data.distributed.DistributedSampler', (['train_data'], {}), '(train_data)\n', (5517, 5529), False, 'import torch\n'), ((5551, 5609), 'torch.utils.data.distributed.DistributedSampler', 'torch.utils.data.distributed.DistributedSampler', (['te... |
import os
from ray.tune.logger import DEFAULT_LOGGERS, CSVLogger
from ray.tune.result import EXPR_PROGRESS_FILE
class PathmindCSVLogger(CSVLogger):
def _init(self):
"""CSV outputted with Headers as first set of results."""
progress_file = os.path.join(self.logdir, EXPR_PROGRESS_FILE)
self... | [
"os.path.exists",
"os.path.getsize",
"os.path.join"
] | [((262, 307), 'os.path.join', 'os.path.join', (['self.logdir', 'EXPR_PROGRESS_FILE'], {}), '(self.logdir, EXPR_PROGRESS_FILE)\n', (274, 307), False, 'import os\n'), ((349, 378), 'os.path.exists', 'os.path.exists', (['progress_file'], {}), '(progress_file)\n', (363, 378), False, 'import os\n'), ((383, 413), 'os.path.get... |
import os
import urllib.request
import csv
import yaml
from flask import Flask, request, jsonify
import numpy as np
from package.preprocessing import read_data, preprocess
from package.model_utils import train_model
from package.app_util import json_to_row
app = Flask(__name__)
# read in configuration
with open('.... | [
"os.path.exists",
"flask.Flask",
"flask.request.get_data",
"package.preprocessing.read_data",
"yaml.safe_load",
"package.app_util.json_to_row",
"os.mkdir",
"numpy.random.RandomState",
"flask.jsonify"
] | [((267, 282), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (272, 282), False, 'from flask import Flask, request, jsonify\n'), ((466, 507), 'numpy.random.RandomState', 'np.random.RandomState', (["cfg['random_seed']"], {}), "(cfg['random_seed'])\n", (487, 507), True, 'import numpy as np\n'), ((375, 399), '... |
"""
support.py
Convenience and utility methods.
"""
import time
class Timer:
"""
Context manager which measures elapsed time
"""
def __enter__(self):
self.start = time.time()
return self
def __exit__(self, *args):
self.end = time.time()
self.elapsed_time = self.en... | [
"time.time"
] | [((190, 201), 'time.time', 'time.time', ([], {}), '()\n', (199, 201), False, 'import time\n'), ((273, 284), 'time.time', 'time.time', ([], {}), '()\n', (282, 284), False, 'import time\n')] |
import re, os, glob
def CollectData(N, mem):
for fn in glob.glob("search_tmp.*"):
os.remove(fn)
with open("search.cpp", "rt") as f:
src = f.read()
ints = mem / 8
src = re.sub(r"const int SIZE = (\d*);", r"const int SIZE = %d;" % N, src)
src = re.sub(r"const int ARR_SAMPLE... | [
"re.sub",
"os.system",
"glob.glob",
"os.remove"
] | [((833, 851), 'glob.glob', 'glob.glob', (['"""res/*"""'], {}), "('res/*')\n", (842, 851), False, 'import re, os, glob\n'), ((63, 88), 'glob.glob', 'glob.glob', (['"""search_tmp.*"""'], {}), "('search_tmp.*')\n", (72, 88), False, 'import re, os, glob\n'), ((211, 278), 're.sub', 're.sub', (['"""const int SIZE = (\\\\d*);... |
import collections
import multiprocessing
import threading
from tkinter import *
import evolution_render
from ea.store import Store
from game.simulation import dnn_to_handler
from render import App
load_cromosomes = []
ins_cromosomes = []
max_generation = 10
global curr_case
curr_case = 1
def CurSelect(evt):
val... | [
"render.App",
"ea.store.Store.load_gen"
] | [((586, 598), 'render.App', 'App', (['handler'], {}), '(handler)\n', (589, 598), False, 'from render import App\n'), ((1460, 1477), 'ea.store.Store.load_gen', 'Store.load_gen', (['i'], {}), '(i)\n', (1474, 1477), False, 'from ea.store import Store\n')] |
# -*- coding: utf-8 -*-
import datetime
import urllib
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.contenttypes.models import ContentType
from django.shortcuts import get_object_or_404
from django.utils import timezone
from .models import *
from .help... | [
"django.contrib.contenttypes.models.ContentType.objects.get_for_model",
"urllib.unquote",
"django.shortcuts.get_object_or_404",
"django.template.RequestContext",
"django.utils.timezone.now"
] | [((2986, 3008), 'urllib.unquote', 'urllib.unquote', (['in_tag'], {}), '(in_tag)\n', (3000, 3008), False, 'import urllib\n'), ((1116, 1164), 'django.contrib.contenttypes.models.ContentType.objects.get_for_model', 'ContentType.objects.get_for_model', (['authorProfile'], {}), '(authorProfile)\n', (1149, 1164), False, 'fro... |
# © BugHunterCodeLabs ™
# © bughunter0
# 2021
# Copyright - https://en.m.wikipedia.org/wiki/Fair_use
import os
from os import error
import pyrogram
from pyrogram import Client, filters
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from pyrogram.types import User, Message
from bs4 import Beauti... | [
"pyrogram.filters.command",
"requests.get",
"bs4.BeautifulSoup",
"pyrogram.filters.regex",
"os.remove"
] | [((554, 580), 'pyrogram.filters.command', 'filters.command', (["['start']"], {}), "(['start'])\n", (569, 580), False, 'from pyrogram import Client, filters\n'), ((1041, 1058), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (1053, 1058), False, 'import requests\n'), ((1873, 1915), 'bs4.BeautifulSoup', 'Beauti... |
"Example substitution; adapted from t_sub.py/t_NomialSubs /test_Basic"
from gpkit import Variable
x = Variable("x")
p = x**2
assert p.sub({x: 3}) == 9
assert p.sub({x.key: 3}) == 9
assert p.sub({"x": 3}) == 9
| [
"gpkit.Variable"
] | [((102, 115), 'gpkit.Variable', 'Variable', (['"""x"""'], {}), "('x')\n", (110, 115), False, 'from gpkit import Variable\n')] |
import urllib.request
import re
import argparse
import sys
import os
from time import sleep
__version__ = "1.0"
banner = """
\033[1m\033[91m .d888888b.
d88888888b
8888 8888
8888 8888
... | [
"os.getcwd",
"argparse.ArgumentParser",
"re.search"
] | [((1381, 1411), 're.search', 're.search', (['"""http(.*)mp4"""', 'html'], {}), "('http(.*)mp4', html)\n", (1390, 1411), False, 'import re\n'), ((1754, 1814), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Musical.ly Downloader"""'}), "(description='Musical.ly Downloader')\n", (1777, 1814... |
from collections import deque
n, Q = map(int, input().split())
graph = [[] for _ in range(n)]
for i in range(n - 1):
a, b = map(int, input().split())
a -= 1
b -= 1
graph[a].append(b)
graph[b].append(a)
# print(graph)
dist = [-1] * n
q = deque()
q.append(0)
dist[0] = 0
while q:
v = q.popleft()
... | [
"collections.deque"
] | [((259, 266), 'collections.deque', 'deque', ([], {}), '()\n', (264, 266), False, 'from collections import deque\n')] |
import pytest
from tests.communication.test_FileComm import TestFileComm as base_class
class TestAsciiFileComm(base_class):
r"""Test for AsciiFileComm communication class."""
@pytest.fixture(scope="class", autouse=True)
def filetype(self):
r"""Communicator type being tested."""
return "as... | [
"pytest.fixture"
] | [((187, 230), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""class"""', 'autouse': '(True)'}), "(scope='class', autouse=True)\n", (201, 230), False, 'import pytest\n')] |
import unittest
import numpy
from chainer import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
from chainer.testing import condition
@testing.parameterize(*testing.product({
'in_shape': [(2, 3, 8, 6), (2, 1, 4, 6)],
}))
class T... | [
"chainer.functions.ResizeImages",
"chainer.testing.condition.retry",
"chainer.testing.run_module",
"chainer.testing.product",
"numpy.zeros",
"numpy.array",
"chainer.functions.resize_images",
"numpy.random.uniform",
"chainer.testing.assert_allclose",
"chainer.cuda.to_gpu"
] | [((3757, 3795), 'chainer.testing.run_module', 'testing.run_module', (['__name__', '__file__'], {}), '(__name__, __file__)\n', (3775, 3795), False, 'from chainer import testing\n'), ((3443, 3461), 'chainer.testing.condition.retry', 'condition.retry', (['(3)'], {}), '(3)\n', (3458, 3461), False, 'from chainer.testing imp... |
#third party imports
import traceback
from tqdm import tqdm #progress bar from github
#std imports
import os
import threading
import json
import re
import time
#local imports
from . import helpers
class Ufc_Data_Scraper:
#Constants
DEFAULT_DIRECTORY ="UFC_Data_Scraper"
SAVE_FIGHT_DIR = "fight_history"
... | [
"traceback.format_exc",
"os.listdir",
"tqdm.tqdm",
"time.sleep",
"os.getcwd",
"os.chdir",
"os.remove",
"os.path.isdir",
"os.mkdir",
"threading.Thread",
"json.dump",
"re.search"
] | [((2080, 2091), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (2089, 2091), False, 'import os\n'), ((3944, 3966), 'os.chdir', 'os.chdir', (['starting_dir'], {}), '(starting_dir)\n', (3952, 3966), False, 'import os\n'), ((4830, 4841), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (4839, 4841), False, 'import os\n'), ((7807,... |