code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
# Software License Agreement (BSD License)
#
# Copyright (c) 2009, <NAME>, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyri... | [
"rospy.resolve_name",
"dynamic_reconfigure.DynamicReconfigureParameterException",
"rospy.is_shutdown",
"rospy.ServiceProxy",
"roslib.load_manifest",
"threading.Condition",
"rospy.Subscriber",
"time.time",
"rospy.wait_for_service"
] | [((1808, 1851), 'roslib.load_manifest', 'roslib.load_manifest', (['"""dynamic_reconfigure"""'], {}), "('dynamic_reconfigure')\n", (1828, 1851), False, 'import roslib\n'), ((3226, 3247), 'threading.Condition', 'threading.Condition', ([], {}), '()\n', (3245, 3247), False, 'import threading\n'), ((11493, 11537), 'rospy.re... |
from random import Random
from rstr import Rstr
from . import Generator
class Regex(Generator):
def __init__(self, regex, seed=None):
self.gen = Rstr(Random(seed))
self.regex = regex
def get_single(self):
return self.gen.xeger(self.regex)
| [
"random.Random"
] | [((163, 175), 'random.Random', 'Random', (['seed'], {}), '(seed)\n', (169, 175), False, 'from random import Random\n')] |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
import unittest
import torch
from reagent.core.parameters import EvaluationParameters, RLParameters
from reagent.core.types import FeatureData, DiscreteDqnInput, ExtraData
from reagent.evaluation.evaluator import get_metric... | [
"reagent.training.parameters.QRDQNTrainerParameters",
"reagent.core.types.ExtraData",
"reagent.core.parameters.RLParameters",
"torch.isclose",
"reagent.evaluation.evaluator.get_metrics_to_score",
"torch.tensor",
"torch.arange",
"reagent.core.parameters.EvaluationParameters",
"reagent.models.dqn.Full... | [((702, 758), 'reagent.training.parameters.QRDQNTrainerParameters', 'QRDQNTrainerParameters', ([], {'actions': "['1', '2']", 'num_atoms': '(11)'}), "(actions=['1', '2'], num_atoms=11)\n", (724, 758), False, 'from reagent.training.parameters import QRDQNTrainerParameters\n'), ((789, 804), 'reagent.workflow.types.RewardO... |
from gym.envs.registration import register
register(
id='highway-v0',
entry_point='highway_env.envs:HighwayEnv',
)
register(
id='highway-continuous-v0',
entry_point='highway_env.envs:HighwayEnvCon',
)
register(
id='highway-continuous-intrinsic-rew-v0',
entry_point='highway_env.envs:HighwayEnv... | [
"gym.envs.registration.register"
] | [((44, 112), 'gym.envs.registration.register', 'register', ([], {'id': '"""highway-v0"""', 'entry_point': '"""highway_env.envs:HighwayEnv"""'}), "(id='highway-v0', entry_point='highway_env.envs:HighwayEnv')\n", (52, 112), False, 'from gym.envs.registration import register\n'), ((125, 212), 'gym.envs.registration.regist... |
# -*- encoding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from django.conf.urls import patterns, include, url
from django_powerdns_api.routers import router
urlpatterns = patterns(
'',
url(r... | [
"django.conf.urls.include"
] | [((325, 345), 'django.conf.urls.include', 'include', (['router.urls'], {}), '(router.urls)\n', (332, 345), False, 'from django.conf.urls import patterns, include, url\n')] |
#!/usr/bin/env python
import argparse
from PIL import Image
from inky import InkyPHAT
print("""Inky pHAT/wHAT: Logo
Displays the Inky pHAT/wHAT logo.
""")
type = "phat"
colour = "black"
inky_display = InkyPHAT(colour)
inky_display.set_border(inky_display.BLACK)
img = Image.open("assets/InkypHAT-212x104-bw.png")
i... | [
"inky.InkyPHAT",
"PIL.Image.open"
] | [((205, 221), 'inky.InkyPHAT', 'InkyPHAT', (['colour'], {}), '(colour)\n', (213, 221), False, 'from inky import InkyPHAT\n'), ((273, 317), 'PIL.Image.open', 'Image.open', (['"""assets/InkypHAT-212x104-bw.png"""'], {}), "('assets/InkypHAT-212x104-bw.png')\n", (283, 317), False, 'from PIL import Image\n')] |
from django.test import TestCase
from .models import *
from django.contrib.auth.models import User
# Create your tests here.
user = User.objects.get(id=1)
profile = Profile.objects.get(id=1)
neighbourhood = Neighbourhood.objects.get(id=1)
class TestBusiness(TestCase):
def setUp(self):
self.business=Busin... | [
"django.contrib.auth.models.User.objects.get"
] | [((133, 155), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', ([], {'id': '(1)'}), '(id=1)\n', (149, 155), False, 'from django.contrib.auth.models import User\n')] |
# -*- coding: utf-8 -*-
import json
import os
import numpy as np
import tensorflow.compat.v1 as tf
from src import model, sample, encoder
from flask import Flask
from flask import request, jsonify
import time
######model
def interact_model(
model_name='run1',
seed=None,
nsamples=1,
batch_size=1,
... | [
"tensorflow.compat.v1.placeholder",
"flask.request.args.get",
"src.model.default_hparams",
"src.encoder.get_encoder",
"tensorflow.compat.v1.Graph",
"flask.Flask",
"os.path.expandvars",
"os.path.join",
"numpy.random.seed",
"tensorflow.compat.v1.set_random_seed",
"src.sample.sample_sequence",
"j... | [((2062, 2077), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (2067, 2077), False, 'from flask import Flask\n'), ((583, 626), 'src.encoder.get_encoder', 'encoder.get_encoder', (['model_name', 'models_dir'], {}), '(model_name, models_dir)\n', (602, 626), False, 'from src import model, sample, encoder\n'), ... |
"""
Helper functions related to json
Author: <NAME>
"""
import datetime
import decimal
import json
import uuid
import pathlib
class JSONEncoder(json.JSONEncoder):
"""
A custom JSONEncoder that can handle a bit more data types than the one from stdlib.
"""
def default(self, o):
# early passt... | [
"json.JSONEncoder.default"
] | [((1019, 1052), 'json.JSONEncoder.default', 'json.JSONEncoder.default', (['self', 'o'], {}), '(self, o)\n', (1043, 1052), False, 'import json\n'), ((382, 415), 'json.JSONEncoder.default', 'json.JSONEncoder.default', (['self', 'o'], {}), '(self, o)\n', (406, 415), False, 'import json\n')] |
# -*- coding: utf-8 -*-
'''
:synopsis: Unit Tests for Windows IIS Module 'module.win_iis'
:platform: Windows
:maturity: develop
versionadded:: Carbon
'''
# Import Python Libs
from __future__ import absolute_import
import json
# Import Salt Libs
from salt.exceptions import SaltInvocationError
from salt... | [
"salttesting.mock.patch.dict",
"salt.modules.win_iis.remove_apppool",
"salt.modules.win_iis.create_site",
"salt.modules.win_iis.list_apps",
"integration.run_tests",
"salt.modules.win_iis.__virtual__",
"salt.modules.win_iis.create_apppool",
"salttesting.mock.MagicMock",
"salttesting.helpers.ensure_in... | [((556, 583), 'salttesting.helpers.ensure_in_syspath', 'ensure_in_syspath', (['"""../../"""'], {}), "('../../')\n", (573, 583), False, 'from salttesting.helpers import ensure_in_syspath\n'), ((675, 696), 'salt.modules.win_iis.__virtual__', 'win_iis.__virtual__', ([], {}), '()\n', (694, 696), False, 'from salt.modules i... |
from conans import ConanFile, CMake, tools
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
class LuaConan(ConanFile):
name = "Lua"
version = "5.3.5"
description = "Lua is a powerful, fast, lightweight, embeddable scripting language."
# topics can get used for searches, GitHub topics, ... | [
"os.rename",
"conans.CMake",
"os.getuid",
"os.path.realpath",
"os.getgid",
"conans.tools.collect_libs"
] | [((81, 107), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (97, 107), False, 'import os\n'), ((1743, 1791), 'os.rename', 'os.rename', (['extracted_dir', 'self._source_subfolder'], {}), '(extracted_dir, self._source_subfolder)\n', (1752, 1791), False, 'import os\n'), ((2343, 2354), 'conans.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import torch
import logging
import torch.distributed as dist
import torch.multiprocessing as mp
from torch.utils.data import Dataset, DataLoader, BatchSampler
from torch.utils.data.distributed import DistributedSampler
from fairseq.tasks.translation ... | [
"logging.basicConfig",
"logging.getLogger",
"torch.distributed.barrier",
"torch.distributed.destroy_process_group",
"torch.multiprocessing.spawn",
"modules.trainer.Trainer",
"modules.utils.init_arg_parser",
"fairseq.data.language_pair_dataset.collate",
"torch.cuda.device_count",
"modules.data_util... | [((525, 685), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s | %(levelname)s | %(name)s | %(message)s"""', 'datefmt': '"""%Y-%m-%d %H:%M:%S"""', 'level': 'logging.INFO', 'stream': 'sys.stdout'}), "(format=\n '%(asctime)s | %(levelname)s | %(name)s | %(message)s', datefmt=\n '%Y-%m-%... |
#!/usr/bin/env python3
"""
intermediate yaml to markdown conversion
"""
import sys
import yaml
def yaml_to_markdown(yaml, outfile):
"""Given a list of dicts representing PowerPoint slides
-- presumably loaded from a YAML file -- convert to
markdown and print the result on the file-like
object 'outfile'.
""... | [
"yaml.load",
"sys.exit"
] | [((4159, 4199), 'yaml.load', 'yaml.load', (['input'], {'Loader': 'yaml.SafeLoader'}), '(input, Loader=yaml.SafeLoader)\n', (4168, 4199), False, 'import yaml\n'), ((4436, 4447), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (4444, 4447), False, 'import sys\n')] |
"""
Copyright <NAME> College
MIT License
Spring 2020
Contains the Display module of the racecar_core library
"""
import cv2 as cv
import os
from nptyping import NDArray
from display import Display
class DisplayReal(Display):
__WINDOW_NAME: str = "RACECAR display window"
__DISPLAY: str = ":1"
def __init... | [
"os.popen",
"cv2.waitKey",
"cv2.namedWindow",
"cv2.imshow"
] | [((765, 799), 'cv2.namedWindow', 'cv.namedWindow', (['self.__WINDOW_NAME'], {}), '(self.__WINDOW_NAME)\n', (779, 799), True, 'import cv2 as cv\n'), ((933, 969), 'cv2.imshow', 'cv.imshow', (['self.__WINDOW_NAME', 'image'], {}), '(self.__WINDOW_NAME, image)\n', (942, 969), True, 'import cv2 as cv\n'), ((982, 995), 'cv2.w... |
import pandas as pd
melbourne_file_path = './melbourne_housing_data.csv'
melbourne_data = pd.read_csv(melbourne_file_path)
melbourne_data.dropna(axis=0)
y = melbourne_data.Price
melbourne_features = ['Rooms','Bathroom','Landsize','Lattitude','Longtitude']
X = melbourne_data[melbourne_features]
X.describe()
X.he... | [
"sklearn.model_selection.train_test_split",
"sklearn.metrics.mean_absolute_error",
"sklearn.tree.DecisionTreeRegressor",
"pandas.read_csv"
] | [((92, 124), 'pandas.read_csv', 'pd.read_csv', (['melbourne_file_path'], {}), '(melbourne_file_path)\n', (103, 124), True, 'import pandas as pd\n'), ((396, 433), 'sklearn.tree.DecisionTreeRegressor', 'DecisionTreeRegressor', ([], {'random_state': '(1)'}), '(random_state=1)\n', (417, 433), False, 'from sklearn.tree impo... |
import unittest
from textwrap import dedent
from normalize_sentences import normalize_sentences
class NormalizeSentencesTests(unittest.TestCase):
"""Tests for normalize_sentences."""
maxDiff = 1000
def test_no_sentences(self):
sentence = "This isn't a sentence"
self.assertEqual(normali... | [
"unittest.main",
"textwrap.dedent",
"normalize_sentences.normalize_sentences"
] | [((3354, 3380), 'unittest.main', 'unittest.main', ([], {'verbosity': '(2)'}), '(verbosity=2)\n', (3367, 3380), False, 'import unittest\n'), ((313, 342), 'normalize_sentences.normalize_sentences', 'normalize_sentences', (['sentence'], {}), '(sentence)\n', (332, 342), False, 'from normalize_sentences import normalize_sen... |
import atrlib
import pandas as pd
# module for calculation of data for renko graph
def renko(df):
d , l , h ,lbo ,lbc,vol=[],[],[],[],[],[]
brick_size = atrlib.brick_size(df)
volume = 0.0
for i in range(0,len(df)):
if i==0:
if(df['close'][i]>df['open'][i]):
d.append(... | [
"pandas.DataFrame",
"atrlib.brick_size"
] | [((162, 183), 'atrlib.brick_size', 'atrlib.brick_size', (['df'], {}), '(df)\n', (179, 183), False, 'import atrlib\n'), ((2506, 2539), 'pandas.DataFrame', 'pd.DataFrame', (['d'], {'columns': "['date']"}), "(d, columns=['date'])\n", (2518, 2539), True, 'import pandas as pd\n')] |
import os
import pathlib
import requests
import shutil
import subprocess
import time
ENV_PATHS = set()
def add_path_to_env(path):
ENV_PATHS.add(path)
def run_command(command, timeout=-1):
if type(command) == str:
command = str.split(command, ' ')
my_env = os.environ.copy()
my_env["PATH"] +... | [
"shutil.copyfileobj",
"pathlib.Path",
"subprocess.run",
"requests.get",
"time.sleep",
"os.environ.copy",
"time.time"
] | [((282, 299), 'os.environ.copy', 'os.environ.copy', ([], {}), '()\n', (297, 299), False, 'import os\n'), ((1880, 1905), 'pathlib.Path', 'pathlib.Path', (['parent_path'], {}), '(parent_path)\n', (1892, 1905), False, 'import pathlib\n'), ((1551, 1581), 'requests.get', 'requests.get', (['url'], {'stream': '(True)'}), '(ur... |
from typing import List
from fastapi import APIRouter
from fastapi.params import Depends
from fastapi import HTTPException, status
from sqlalchemy.orm.session import Session
from project import schema, models, database, hashing
router = APIRouter(
prefix="/user",
tags=['Users']
)
@router.post('/new')
def crea... | [
"project.models.User",
"fastapi.HTTPException",
"fastapi.params.Depends",
"fastapi.APIRouter",
"project.hashing.get_password_hash"
] | [((238, 279), 'fastapi.APIRouter', 'APIRouter', ([], {'prefix': '"""/user"""', 'tags': "['Users']"}), "(prefix='/user', tags=['Users'])\n", (247, 279), False, 'from fastapi import APIRouter\n'), ((362, 386), 'fastapi.params.Depends', 'Depends', (['database.get_db'], {}), '(database.get_db)\n', (369, 386), False, 'from ... |
import os
import cv2
import torch
from torch.nn import functional as F
from torchvision import transforms
import torchvision.utils
def save_image(img, path):
os.makedirs(os.path.dirname(path), exist_ok=True)
torchvision.utils.save_image(torch.clip(img, -1, 1), path, normalize=True)
def cv2pt(img):
img =... | [
"torch.clip",
"os.path.dirname",
"torch.nn.functional.fold",
"torch.nn.functional.unfold",
"cv2.cvtColor",
"torchvision.transforms.Resize",
"cv2.resize",
"cv2.blur",
"torch.ones"
] | [((321, 357), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2RGB'], {}), '(img, cv2.COLOR_BGR2RGB)\n', (333, 357), False, 'import cv2\n'), ((753, 806), 'cv2.resize', 'cv2.resize', (['img', '(w, h)'], {'interpolation': 'cv2.INTER_AREA'}), '(img, (w, h), interpolation=cv2.INTER_AREA)\n', (763, 806), False, 'impo... |
import random
import shapely.geometry as sg
from locintel.quality.generators.random import RandomRoutePlanGenerator, polygons
random.seed(10)
class TestRandomRoutePlanGenerator(object):
def test_random_route_plan_generator(self):
polygon = polygons["berlin"]
generator = RandomRoutePlanGenerator(... | [
"locintel.quality.generators.random.RandomRoutePlanGenerator",
"random.seed",
"shapely.geometry.Point"
] | [((128, 143), 'random.seed', 'random.seed', (['(10)'], {}), '(10)\n', (139, 143), False, 'import random\n'), ((295, 321), 'locintel.quality.generators.random.RandomRoutePlanGenerator', 'RandomRoutePlanGenerator', ([], {}), '()\n', (319, 321), False, 'from locintel.quality.generators.random import RandomRoutePlanGenerat... |
#!/usr/bin/python
# coding: utf-8
######################
# Uwsgi RCE Exploit
######################
# Author: <EMAIL>
# Created: 2017-7-18
# Last modified: 2018-1-30
# Note: Just for research purpose
import sys
import socket
import argparse
import requests
def sz(x):
s = hex(x if isinstance(x, int) else len(x))[2... | [
"urlparse.urlsplit",
"socket.socket",
"requests.Session",
"argparse.ArgumentParser"
] | [((1311, 1329), 'requests.Session', 'requests.Session', ([], {}), '()\n', (1327, 1329), False, 'import requests\n'), ((3204, 3258), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': 'desc', 'epilog': 'elog'}), '(description=desc, epilog=elog)\n', (3227, 3258), False, 'import argparse\n'), ((173... |
"""
Views file for the Darklang Django App
"""
from django.contrib.auth.decorators import login_required
from django.http import Http404
from django.shortcuts import redirect
from django.template.loader import render_to_string
from django.utils.decorators import method_decorator
from django.utils.translation import L... | [
"web_fragments.fragment.Fragment",
"openedx.core.djangoapps.dark_lang.models.DarkLangConfig.current",
"openedx.core.djangoapps.user_api.preferences.api.set_user_preference",
"django.utils.decorators.method_decorator",
"openedx.core.djangoapps.user_api.preferences.api.delete_user_preference",
"django.short... | [((1962, 1994), 'django.utils.decorators.method_decorator', 'method_decorator', (['login_required'], {}), '(login_required)\n', (1978, 1994), False, 'from django.utils.decorators import method_decorator\n'), ((2274, 2306), 'django.utils.decorators.method_decorator', 'method_decorator', (['login_required'], {}), '(login... |
# !/usr/bin/python
# -*- coding: utf-8 -*-
# @time : 2020/5/27 21:18
# @author : Mo
# @function: 统计
from text_analysis.utils.text_common import txt_read, txt_write, load_json, save_json, get_all_dirs_files
from text_analysis.conf.path_log import logger
from collections import Counter
from typing import List, Dict... | [
"matplotlib.pyplot.boxplot",
"text_analysis.utils.text_common.get_all_dirs_files",
"os.path.exists",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.close",
"os.mkdir",
"matplotlib.pyplot.yscale",
"json.loads",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.xticks",
"os.path.dirname",
"matplotli... | [((608, 637), 'text_analysis.utils.text_common.get_all_dirs_files', 'get_all_dirs_files', (['path_file'], {}), '(path_file)\n', (626, 637), False, 'from text_analysis.utils.text_common import txt_read, txt_write, load_json, save_json, get_all_dirs_files\n'), ((3009, 3040), 'matplotlib.pyplot.subplots_adjust', 'plt.subp... |
#coding:utf-8
"""
@author : linkin
@email : <EMAIL>
@date : 2018-10-04
"""
import logging
from APIserver.apiserver import app
from components.collector import Collector
from components.validator import Validator
from components.detector import Detector
from components.scanner import Sc... | [
"logging.getLogger",
"components.validator.Validator",
"components.tentacle.Tentacle",
"components.scanner.Scaner",
"APIserver.apiserver.app.run",
"multiprocessing.Pool",
"multiprocessing.Manager",
"components.collector.Collector",
"components.detector.Detector"
] | [((546, 565), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (563, 565), False, 'import logging\n'), ((675, 686), 'components.collector.Collector', 'Collector', ([], {}), '()\n', (684, 686), False, 'from components.collector import Collector\n'), ((712, 723), 'components.validator.Validator', 'Validator', ... |
import abc
import logging
from enum import Enum
from tqdm import tqdm
from ml import np
from ml.functions import sigmoid, dot_batch, bernoulli_from_probas
_log = logging.getLogger("ml")
class UnitType(Enum):
GAUSSIAN = 1
BERNOULLI = 2
class RBMSampler(object):
"""Sampler used in training of RBMs for e... | [
"logging.getLogger",
"ml.np.all",
"ml.np.random.shuffle",
"ml.np.matmul",
"ml.np.ones",
"ml.np.tile",
"ml.np.zeros",
"ml.np.linspace",
"ml.np.arange",
"ml.np.log",
"ml.np.mean",
"ml.functions.bernoulli_from_probas",
"ml.np.sqrt",
"ml.np.random.normal",
"ml.np.exp",
"pickle.load",
"ml... | [((165, 188), 'logging.getLogger', 'logging.getLogger', (['"""ml"""'], {}), "('ml')\n", (182, 188), False, 'import logging\n'), ((3675, 3696), 'ml.np.zeros', 'np.zeros', (['num_visible'], {}), '(num_visible)\n', (3683, 3696), False, 'from ml import np\n'), ((3714, 3734), 'ml.np.zeros', 'np.zeros', (['num_hidden'], {}),... |
import ctypes
import threading
from functools import partial
from contextlib import nullcontext
from copy import deepcopy
import multiprocessing as mp
from itertools import zip_longest
from typing import Iterable
import torch
import torch.nn as nn
import torch.utils.data
import torch_xla.core.xla_model as xm
import to... | [
"torch_xla.core.xla_model.do_on_ordinals",
"torch_xla.core.xla_model.xla_device",
"copy.deepcopy",
"torch_xla.core.xla_model.all_reduce",
"torch_xla.core.xla_model.is_master_ordinal",
"hivemind.utils.logging.get_logger",
"multiprocessing.Value",
"torch.zeros_like",
"multiprocessing.Event",
"iterto... | [((476, 496), 'hivemind.utils.logging.get_logger', 'get_logger', (['__name__'], {}), '(__name__)\n', (486, 496), False, 'from hivemind.utils.logging import get_logger\n'), ((1037, 1046), 'multiprocessing.Lock', 'mp.Lock', ([], {}), '()\n', (1044, 1046), True, 'import multiprocessing as mp\n'), ((1583, 1613), 'multiproc... |
import numpy as np
from copy import copy
from .utils.thresholdcurator import ThresholdCurator
from .quality_metric import QualityMetric
import spiketoolkit as st
import spikemetrics.metrics as metrics
from spikemetrics.utils import printProgressBar
from collections import OrderedDict
from sklearn.neighbors import Neare... | [
"numpy.mean",
"collections.OrderedDict",
"spiketoolkit.postprocessing.get_unit_waveforms",
"numpy.median",
"numpy.abs",
"numpy.random.choice",
"numpy.asarray",
"numpy.max",
"numpy.sum",
"numpy.zeros",
"numpy.dot",
"numpy.random.seed",
"numpy.concatenate",
"numpy.min",
"numpy.linalg.svd",... | [((552, 657), 'collections.OrderedDict', 'OrderedDict', (["[('max_spikes_per_unit_for_noise_overlap', 1000), ('num_features', 10), (\n 'num_knn', 6)]"], {}), "([('max_spikes_per_unit_for_noise_overlap', 1000), (\n 'num_features', 10), ('num_knn', 6)])\n", (563, 657), False, 'from collections import OrderedDict\n'... |
# Open3D: www.open3d.org
# The MIT License (MIT)
# See license file or visit www.open3d.org for details
# examples/Python/Advanced/global_registration.py
import open3d as o3d
import numpy as np
import copy
def draw_registration_result(source, target, transformation):
source_temp = copy.deepcopy(source)
targ... | [
"numpy.identity",
"open3d.registration.TransformationEstimationPointToPlane",
"open3d.registration.CorrespondenceCheckerBasedOnEdgeLength",
"numpy.asarray",
"open3d.geometry.KDTreeSearchParamHybrid",
"open3d.registration.RANSACConvergenceCriteria",
"open3d.visualization.draw_geometries",
"open3d.io.re... | [((290, 311), 'copy.deepcopy', 'copy.deepcopy', (['source'], {}), '(source)\n', (303, 311), False, 'import copy\n'), ((330, 351), 'copy.deepcopy', 'copy.deepcopy', (['target'], {}), '(target)\n', (343, 351), False, 'import copy\n'), ((504, 565), 'open3d.visualization.draw_geometries', 'o3d.visualization.draw_geometries... |
import os
import argparse
import pandas as pd
import numpy as np
from sklearn.metrics import f1_score, r2_score
from tqdm import tqdm
parser = argparse.ArgumentParser()
parser.add_argument("--exp_dir", type=str, help="path to directory containing test results",
default="/scratch/wdjo224/deep_protei... | [
"os.listdir",
"sklearn.metrics.f1_score",
"argparse.ArgumentParser",
"pandas.read_csv",
"pandas.DataFrame",
"sklearn.metrics.r2_score",
"os.walk"
] | [((144, 169), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (167, 169), False, 'import argparse\n'), ((845, 866), 'os.walk', 'os.walk', (['args.exp_dir'], {}), '(args.exp_dir)\n', (852, 866), False, 'import os\n'), ((1078, 1139), 'pandas.DataFrame', 'pd.DataFrame', (["{'idx': [], 'pred': [], '... |
import os
from contextlib import ExitStack
from pathlib import Path
import pytest
from synctogit.git_factory import GitError, git_factory
def remotes_dump(remote_name, remote):
# fmt: off
return (
"%(remote_name)s\t%(remote)s (fetch)\n"
"%(remote_name)s\t%(remote)s (push)"
) % locals()
... | [
"pathlib.Path",
"synctogit.git_factory.git_factory",
"pytest.mark.parametrize",
"pytest.raises",
"os.mkdir",
"contextlib.ExitStack"
] | [((480, 600), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""remote_name, remote"""', "[('origin', None), ('angel', '<EMAIL>:KostyaEsmukov/SyncToGit.git')]"], {}), "('remote_name, remote', [('origin', None), ('angel',\n '<EMAIL>:KostyaEsmukov/SyncToGit.git')])\n", (503, 600), False, 'import pytest\n'), ... |
# ===============================================================================
# Copyright 2019 ross
#
# 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/LICE... | [
"traits.api.Instance",
"traits.api.on_trait_change",
"pychron.graph.graph.Graph",
"traitsui.api.Item",
"numpy.linspace",
"traits.api.Int",
"traitsui.api.UItem",
"pychron.processing.argon_calculations.calculate_fractional_loss",
"traits.api.Float"
] | [((1058, 1073), 'traits.api.Instance', 'Instance', (['Graph'], {}), '(Graph)\n', (1066, 1073), False, 'from traits.api import HasTraits, Int, Float, Instance, on_trait_change\n'), ((1085, 1095), 'traits.api.Float', 'Float', (['(475)'], {}), '(475)\n', (1090, 1095), False, 'from traits.api import HasTraits, Int, Float, ... |
import math
from inputs.sine import Sine
from inputs.timeElapsed import TimeElapsed
from utils.number import Number
class SineClock(Number):
def __init__(self, sine: Sine):
self.__sine = sine
self.__elapsed = TimeElapsed()
def get(self):
return self.__sine.at_time(self.__elapsed.get(... | [
"inputs.timeElapsed.TimeElapsed"
] | [((232, 245), 'inputs.timeElapsed.TimeElapsed', 'TimeElapsed', ([], {}), '()\n', (243, 245), False, 'from inputs.timeElapsed import TimeElapsed\n')] |
# main imports
import numpy as np
import sys
# image transform imports
from PIL import Image
from skimage import color
from sklearn.decomposition import FastICA
from sklearn.decomposition import IncrementalPCA
from sklearn.decomposition import TruncatedSVD
from numpy.linalg import svd as lin_svd
from scipy.signal impo... | [
"numpy.uint8",
"sys.path.insert",
"ipfml.utils.get_entropy_contribution_of_i",
"ipfml.utils.normalize_2D_arr",
"ipfml.utils.get_indices_of_lowest_values",
"cv2.filter2D",
"numpy.array",
"sklearn.decomposition.FastICA",
"pywt.waverec2",
"ipfml.processing.transform.rgb_to_mscn",
"numpy.divide",
... | [((538, 560), 'sys.path.insert', 'sys.path.insert', (['(0)', '""""""'], {}), "(0, '')\n", (553, 560), False, 'import sys\n'), ((23763, 23786), 'numpy.divide', 'np.divide', (['imArray', '(255)'], {}), '(imArray, 255)\n', (23772, 23786), True, 'import numpy as np\n'), ((23827, 23868), 'pywt.wavedec2', 'pywt.wavedec2', ([... |
# Generated by Django 2.2.4 on 2019-08-04 21:03
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('jobHistory', '0002_auto_20190106_0202'),
]
operations = [
migrations.AlterField(
model_name='em... | [
"django.db.models.EmailField",
"django.db.models.TextField",
"django.db.models.ForeignKey",
"django.db.models.BooleanField",
"django.db.models.PositiveIntegerField",
"django.db.models.PositiveSmallIntegerField",
"django.db.models.CharField"
] | [((372, 437), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(200)', 'verbose_name': '"""City"""'}), "(blank=True, max_length=200, verbose_name='City')\n", (388, 437), False, 'from django.db import migrations, models\n'), ((562, 630), 'django.db.models.CharField', 'models.Char... |
from Logic.Data.DataManager import Writer
from Logic.Client.ClientsManager import ClientsManager
class LobbyInfoMessage(Writer):
def __init__(self, client, player):
super().__init__(client)
self.id = 23457
self.client = client
self.player = player
def encode(self):
self... | [
"Logic.Client.ClientsManager.ClientsManager.GetCount"
] | [((331, 356), 'Logic.Client.ClientsManager.ClientsManager.GetCount', 'ClientsManager.GetCount', ([], {}), '()\n', (354, 356), False, 'from Logic.Client.ClientsManager import ClientsManager\n')] |
from bs4 import BeautifulSoup
import requests
text = input("text : ")
text.replace(" ", "+")
params = {"q": text}
content = requests.get("https://duckduckgo.com/?q=", params=params)
soup = BeautifulSoup(content.text, 'html.parser')
res = soup.find_all('div', class_="result__snippet js-result-snippet")
for r in res:
... | [
"bs4.BeautifulSoup",
"requests.get"
] | [((126, 183), 'requests.get', 'requests.get', (['"""https://duckduckgo.com/?q="""'], {'params': 'params'}), "('https://duckduckgo.com/?q=', params=params)\n", (138, 183), False, 'import requests\n'), ((191, 233), 'bs4.BeautifulSoup', 'BeautifulSoup', (['content.text', '"""html.parser"""'], {}), "(content.text, 'html.pa... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import Http404
from infinite_scroll_pagination.paginator import SeekPaginator, EmptyPage
def paginate(request, query_set, lookup_field, per_page=15, page_var='value'):
# TODO: remove
page_pk = request.GET.get(page_var, None)
... | [
"infinite_scroll_pagination.paginator.SeekPaginator",
"django.http.Http404"
] | [((335, 405), 'infinite_scroll_pagination.paginator.SeekPaginator', 'SeekPaginator', (['query_set'], {'per_page': 'per_page', 'lookup_field': 'lookup_field'}), '(query_set, per_page=per_page, lookup_field=lookup_field)\n', (348, 405), False, 'from infinite_scroll_pagination.paginator import SeekPaginator, EmptyPage\n')... |
import traceback
from pycompss.api.task import task
from pycompss.api.constraint import constraint
from pycompss.api.parameter import FILE_IN, FILE_OUT
from biobb_common.tools import file_utils as fu
from biobb_md.gromacs_extra import append_ligand
import os
import sys
@constraint(computingUnits="1")
@task(input_top_z... | [
"biobb_common.tools.file_utils.write_failed_output",
"pycompss.api.constraint.constraint",
"sys.stderr.flush",
"os.environ.pop",
"biobb_md.gromacs_extra.append_ligand.AppendLigand",
"pycompss.api.task.task",
"sys.stdout.flush",
"traceback.print_exc"
] | [((272, 302), 'pycompss.api.constraint.constraint', 'constraint', ([], {'computingUnits': '"""1"""'}), "(computingUnits='1')\n", (282, 302), False, 'from pycompss.api.constraint import constraint\n'), ((304, 451), 'pycompss.api.task.task', 'task', ([], {'input_top_zip_path': 'FILE_IN', 'input_itp_path': 'FILE_IN', 'out... |
import requests
import json
from pprint import pprint
import re
import time
import sys
#getdata = requests.get(geturl)
#pprint (vars(getdata))
from bs4 import BeautifulSoup
from geopy.geocoders import Nominatim
if len(sys.argv) != 4:
print(sys.argv[0]+" <item> <location> <num items>")
exit()
#get list of prod... | [
"requests.post",
"geopy.geocoders.Nominatim",
"time.sleep",
"requests.get",
"bs4.BeautifulSoup",
"re.search"
] | [((677, 697), 'requests.get', 'requests.get', (['geturl'], {}), '(geturl)\n', (689, 697), False, 'import requests\n'), ((1625, 1636), 'geopy.geocoders.Nominatim', 'Nominatim', ([], {}), '()\n', (1634, 1636), False, 'from geopy.geocoders import Nominatim\n'), ((731, 777), 'bs4.BeautifulSoup', 'BeautifulSoup', (['respons... |
from __future__ import print_function
import numpy as np
from copy import copy
import torch
import torch.nn.functional as F
from torch.autograd import Variable
import torch.nn as nn
def apply_var(v, k):
if isinstance(v, Variable) and v.requires_grad:
v.register_hook(inves(k))
def apply_dict(dic):
fo... | [
"torch.mean",
"torch.stack",
"torch.cumprod",
"torch.norm",
"torch.sum",
"torch.div",
"torch.bmm",
"copy.copy",
"torch.nn.functional.softmax"
] | [((1019, 1041), 'torch.sum', 'torch.sum', (['inputs', 'dim'], {}), '(inputs, dim)\n', (1028, 1041), False, 'import torch\n'), ((4617, 4662), 'torch.norm', 'torch.norm', (['memory_matrix', '(2)', '(2)'], {'keepdim': '(True)'}), '(memory_matrix, 2, 2, keepdim=True)\n', (4627, 4662), False, 'import torch\n'), ((4679, 4719... |
# Code apapted from https://github.com/mseitzer/pytorch-fid
"""Calculates the Frechet Inception Distance (FID) to evalulate GANs
The FID metric calculates the distance between two distributions of images.
Typically, we have summary statistics (mean & covariance matrix) of one
of these distributions, while the 2nd dist... | [
"numpy.atleast_2d",
"numpy.trace",
"numpy.mean",
"torch.nn.functional.adaptive_avg_pool2d",
"numpy.eye",
"numpy.abs",
"numpy.diagonal",
"util.tools.device_name",
"numpy.iscomplexobj",
"numpy.empty",
"numpy.isfinite",
"torch.utils.data.DataLoader",
"torch.no_grad",
"numpy.cov",
"time.time... | [((2677, 2772), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dataset'], {'batch_size': 'batch_size', 'shuffle': '(False)', 'drop_last': '(False)'}), '(dataset, batch_size=batch_size, shuffle=False,\n drop_last=False)\n', (2704, 2772), False, 'import torch\n'), ((2785, 2807), 'numpy.empty', 'np.em... |
from flask import Flask, current_app, request, Request
app = Flask(__name__)
ctx = app.app_context()
ctx.push()
current_app.static_floder = 'static'
ctx.pop()
app.run
| [
"flask.Flask"
] | [((62, 77), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (67, 77), False, 'from flask import Flask, current_app, request, Request\n')] |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016 Juniper Networks, Inc. All rights reserved.
#
from __future__ import unicode_literals
from builtins import str
from builtins import range
import logging
from netaddr import IPNetwork
from random import randint, choice
import uuid
from .resource import Resource
from ..util... | [
"logging.getLogger",
"random.choice",
"builtins.str",
"uuid.uuid4",
"builtins.range",
"random.randint",
"netaddr.IPNetwork"
] | [((347, 374), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (364, 374), False, 'import logging\n'), ((1451, 1478), 'builtins.range', 'range', (['self._project_amount'], {}), '(self._project_amount)\n', (1456, 1478), False, 'from builtins import range\n'), ((8244, 8264), 'netaddr.IPNetwor... |
import flask ; from flask import *
def Serve(email_form, password_form, rd, dic, host="0.0.0.0", port="8080"):
app = Flask(__name__, template_folder="../clone")
# login storage
class Login:
email = ""
pwd = ""
ip = ""
# forms
@app.get("/")
def index():
retu... | [
"flask.redirect"
] | [((658, 676), 'flask.redirect', 'flask.redirect', (['rd'], {}), '(rd)\n', (672, 676), False, 'import flask\n')] |
import torch
import torch.nn as nn
import numpy as np
import cv2
import os
import shutil
from matplotlib import pyplot as plt
from Model_Definition import VC3D
from mypath import NICKNAME, DATA_DIR, PATH
# TODO: Now can display images with plt.show(), need to solve display on cloud instance
OUT_DIR = PATH + os.path.... | [
"Model_Definition.VC3D",
"torch.max",
"torch.from_numpy",
"numpy.array",
"torch.cuda.is_available",
"cv2.destroyAllWindows",
"os.path.exists",
"torch.autograd.Variable",
"cv2.waitKey",
"cv2.putText",
"cv2.resize",
"numpy.transpose",
"os.makedirs",
"torch.nn.Softmax",
"torch.load",
"os.... | [((424, 451), 'os.path.exists', 'os.path.exists', (['folder_name'], {}), '(folder_name)\n', (438, 451), False, 'import os\n'), ((967, 973), 'Model_Definition.VC3D', 'VC3D', ([], {}), '()\n', (971, 973), False, 'from Model_Definition import VC3D\n'), ((991, 1046), 'torch.load', 'torch.load', (['f"""model_{NICKNAME}.pt""... |
"""Transform signaling data to smoothed trajectories."""
import sys
import numpy
import pandas as pd
import geopandas as gpd
import shapely.geometry
import matplotlib.patches
import matplotlib.pyplot as plt
import mobilib.voronoi
SAMPLING = pd.Timedelta('00:01:00')
STD = pd.Timedelta('00:05:00')
def smoothen(arr... | [
"pandas.Series",
"numpy.ceil",
"pandas.read_csv",
"matplotlib.pyplot.gca",
"pandas.Timedelta",
"pandas.merge",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.scatter",
"pandas.DataFrame",
"numpy.full",
"pandas.to_datetime",
"matplotlib.pyplot.show"
] | [((246, 270), 'pandas.Timedelta', 'pd.Timedelta', (['"""00:01:00"""'], {}), "('00:01:00')\n", (258, 270), True, 'import pandas as pd\n'), ((277, 301), 'pandas.Timedelta', 'pd.Timedelta', (['"""00:05:00"""'], {}), "('00:05:00')\n", (289, 301), True, 'import pandas as pd\n'), ((683, 713), 'numpy.full', 'numpy.full', (['t... |
#!/usr/bin/env python
# -*- coding:utf8 -*-
import sys
import argparse
from lantis.webradio.commands import bind_subparsers
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
bind_subparsers(subparsers)
def main(argv=None):
if argv is None:
argv = sys.argv[1:]
args = parser.pars... | [
"lantis.webradio.commands.bind_subparsers",
"argparse.ArgumentParser",
"sys.exit"
] | [((135, 160), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (158, 160), False, 'import argparse\n'), ((198, 225), 'lantis.webradio.commands.bind_subparsers', 'bind_subparsers', (['subparsers'], {}), '(subparsers)\n', (213, 225), False, 'from lantis.webradio.commands import bind_subparsers\n'),... |
# Pathfinding algorithm.
import pygame
import random
class HotTile( object ):
def __init__( self ):
self.heat = 9999
self.cost = 0
self.block = False
class HotMap( object ):
DELTA8 = [ (-1,-1), (0,-1), (1,-1), (-1,0), (1,0), (-1,1), (0,1), (1,1) ]
EXPENSIVE = 9999
def __init__... | [
"random.randint",
"random.shuffle",
"pygame.Rect"
] | [((3411, 3438), 'random.shuffle', 'random.shuffle', (['self.DELTA8'], {}), '(self.DELTA8)\n', (3425, 3438), False, 'import random\n'), ((3886, 3913), 'random.shuffle', 'random.shuffle', (['self.DELTA8'], {}), '(self.DELTA8)\n', (3900, 3913), False, 'import random\n'), ((6809, 6834), 'pygame.Rect', 'pygame.Rect', (['(20... |
import json
import jsonpickle
from pprint import pprint
class Object(object):
pass
prods = Object()
prods.accountId="<KEY>"
prods.locationId="5db938536d49b300017efcc3"
prods.products=[]
prods.categories=[]
with open ('pl.json', 'r') as f:
products_dict = json.load(f)
for item in products_dict["models"]:
... | [
"json.load",
"jsonpickle.dumps"
] | [((268, 280), 'json.load', 'json.load', (['f'], {}), '(f)\n', (277, 280), False, 'import json\n'), ((725, 737), 'json.load', 'json.load', (['f'], {}), '(f)\n', (734, 737), False, 'import json\n'), ((915, 938), 'jsonpickle.dumps', 'jsonpickle.dumps', (['prods'], {}), '(prods)\n', (931, 938), False, 'import jsonpickle\n'... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-09-18 04:11
from __future__ import unicode_literals
import CareerTinder.listfield
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('CareerTinder', '0001_initial'),
]
operations = [
... | [
"django.db.models.IntegerField",
"django.db.models.FileField",
"django.db.models.ImageField",
"django.db.migrations.RemoveField",
"django.db.models.CharField"
] | [((324, 388), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""hiree"""', 'name': '"""date_of_birth"""'}), "(model_name='hiree', name='date_of_birth')\n", (346, 388), False, 'from django.db import migrations, models\n'), ((433, 488), 'django.db.migrations.RemoveField', 'migrations.R... |
import datetime
import logging
import json
from cadence.activity import ActivityContext
from cadence.cadence_types import PollForActivityTaskRequest, TaskListMetadata, TaskList, PollForActivityTaskResponse, \
RespondActivityTaskCompletedRequest, RespondActivityTaskFailedRequest
from cadence.conversions import json... | [
"logging.getLogger",
"cadence.cadence_types.RespondActivityTaskFailedRequest",
"cadence.workflowservice.WorkflowService.create",
"cadence.activity.ActivityContext.set",
"cadence.cadence_types.RespondActivityTaskCompletedRequest",
"cadence.activity.ActivityContext",
"cadence.workflowservice.WorkflowServi... | [((425, 452), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (442, 452), False, 'import logging\n'), ((509, 557), 'cadence.workflowservice.WorkflowService.create', 'WorkflowService.create', (['worker.host', 'worker.port'], {}), '(worker.host, worker.port)\n', (531, 557), False, 'from cade... |
# Copyright 2020 Toyota Research Institute. All rights reserved.
# Adapted from Pytorch-Lightning
# https://github.com/PyTorchLightning/pytorch-lightning/blob/master/pytorch_lightning/loggers/wandb.py
from argparse import Namespace
from collections import OrderedDict
import numpy as np
import torch.nn as nn
import w... | [
"packnet_sfm.utils.logging.prepare_dataset_prefix",
"collections.OrderedDict",
"wandb.Image",
"wandb.init",
"packnet_sfm.utils.types.is_dict",
"wandb.run.save",
"packnet_sfm.utils.depth.viz_inv_depth",
"packnet_sfm.utils.types.is_tensor"
] | [((8142, 8158), 'packnet_sfm.utils.types.is_tensor', 'is_tensor', (['image'], {}), '(image)\n', (8151, 8158), False, 'from packnet_sfm.utils.types import is_dict, is_tensor\n'), ((1803, 1816), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (1814, 1816), False, 'from collections import OrderedDict\n'), ((21... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 3 17:20:06 2018
@author: chrispedder
A routine to crop sections from the images of different manuscripts in the two
datasets to the same size, and with the same magnification, so that the average
script size doesn't create a feature that the neura... | [
"os.path.exists",
"numpy.dstack",
"PIL.Image.open",
"PIL.Image.fromarray",
"argparse.ArgumentParser",
"random.seed",
"os.mkdir",
"glob.glob"
] | [((7029, 7155), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Command line options for processing the data files needed to train the model."""'}), "(description=\n 'Command line options for processing the data files needed to train the model.'\n )\n", (7052, 7155), False, 'import ... |
from typing import Optional, Union, List, Dict
# local
import ivy
from ivy.container.base import ContainerBase
# noinspection PyMissingConstructor
class ContainerWithGradients(ContainerBase):
@staticmethod
def static_optimizer_update(
w,
effective_grad,
lr,
inplace=None,
... | [
"ivy.container.base.ContainerBase.multi_map_in_static_method"
] | [((562, 810), 'ivy.container.base.ContainerBase.multi_map_in_static_method', 'ContainerBase.multi_map_in_static_method', (['"""optimizer_update"""', 'w', 'effective_grad', 'lr'], {'inplace': 'inplace', 'stop_gradients': 'stop_gradients', 'key_chains': 'key_chains', 'to_apply': 'to_apply', 'prune_unapplied': 'prune_unap... |
from __future__ import with_statement
from contextlib import contextmanager
from test import TemplateTest, eq_, raises, template_base, mock
import os
from mako.cmd import cmdline
class CmdTest(TemplateTest):
@contextmanager
def _capture_output_fixture(self, stream="stdout"):
with mock.patch("sys.%s" % ... | [
"mako.cmd.cmdline",
"test.raises",
"os.path.join",
"test.mock.patch",
"test.eq_",
"test.mock.Mock"
] | [((641, 695), 'test.eq_', 'eq_', (['stdout.write.mock_calls[0][1][0]', '"""hello world 5"""'], {}), "(stdout.write.mock_calls[0][1][0], 'hello world 5')\n", (644, 695), False, 'from test import TemplateTest, eq_, raises, template_base, mock\n'), ((1849, 1903), 'test.eq_', 'eq_', (['stdout.write.mock_calls[0][1][0]', '"... |
from LightPipes import *
import matplotlib.pyplot as plt
def TheExample(N):
fig=plt.figure(figsize=(11,9.5))
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)
labda=1000*nm;
size=10*mm;
f1=10*m
f2=1.11111111*m
z=1.0*... | [
"matplotlib.pyplot.figure",
"matplotlib.pyplot.show"
] | [((85, 114), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(11, 9.5)'}), '(figsize=(11, 9.5))\n', (95, 114), True, 'import matplotlib.pyplot as plt\n'), ((1906, 1916), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1914, 1916), True, 'import matplotlib.pyplot as plt\n')] |
from argparse import ArgumentParser
from ucca import constructions
from ucca.ioutil import read_files_and_dirs
if __name__ == "__main__":
argparser = ArgumentParser(description="Extract linguistic constructions from UCCA corpus.")
argparser.add_argument("passages", nargs="+", help="the corpus, given as... | [
"ucca.ioutil.read_files_and_dirs",
"ucca.constructions.extract_edges",
"ucca.constructions.add_argument",
"argparse.ArgumentParser"
] | [((162, 247), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'description': '"""Extract linguistic constructions from UCCA corpus."""'}), "(description='Extract linguistic constructions from UCCA corpus.'\n )\n", (176, 247), False, 'from argparse import ArgumentParser\n'), ((350, 394), 'ucca.constructions.add_ar... |
import hashlib
import os
import pickle
import tempfile
import zlib
from threading import Lock
from time import time
from multicache.base import BaseCache
try:
from multicache.redis import RedisCache
except ImportError:
pass
lock = Lock()
class DummyCache(BaseCache):
""" Fake cache class to allow a "no c... | [
"hashlib.new",
"pickle.dumps",
"threading.Lock",
"os.path.isdir",
"tempfile.gettempdir",
"os.mkdir",
"time.time"
] | [((241, 247), 'threading.Lock', 'Lock', ([], {}), '()\n', (245, 247), False, 'from threading import Lock\n'), ((2364, 2382), 'hashlib.new', 'hashlib.new', (['"""md5"""'], {}), "('md5')\n", (2375, 2382), False, 'import hashlib\n'), ((2257, 2281), 'os.path.isdir', 'os.path.isdir', (['self.path'], {}), '(self.path)\n', (2... |
# -*- coding: utf-8 -*-
from collections import OrderedDict
from gluon import current
from gluon.storage import Storage
def config(settings):
"""
Template for WA-COP + CAD Cloud Integration
"""
T = current.T
# =========================================================================
# S... | [
"s3.s3_fieldmethod",
"gluon.current.db",
"collections.OrderedDict",
"s3.IS_ONE_OF",
"s3.S3ResourceHeader",
"gluon.current.s3db.set_method",
"gluon.current.request.post_vars.get",
"s3.S3DateFilter",
"gluon.URL",
"s3.S3OptionsFilter",
"os.path.join",
"s3.s3_rheader_resource",
"s3.FS",
"gluon... | [((1991, 2042), 'collections.OrderedDict', 'OrderedDict', (["[('en', 'English'), ('es', 'Español')]"], {}), "([('en', 'English'), ('es', 'Español')])\n", (2002, 2042), False, 'from collections import OrderedDict\n'), ((49140, 49162), 's3.s3_rheader_resource', 's3_rheader_resource', (['r'], {}), '(r)\n', (49159, 49162),... |
import kivy
from kivy.app import App
from kivy.uix.button import Button
import android
import os
import time
from android.permissions import Permission, request_permission, check_permission
from kivy.clock import Clock
class MyApp(App):
def second_thread(self, data):
print("starting second thread")
... | [
"kivy.uix.button.Button",
"os.makedirs",
"os.path.join",
"kivy.clock.Clock.schedule_once",
"android.permissions.request_permission",
"android.permissions.check_permission"
] | [((344, 395), 'android.permissions.check_permission', 'check_permission', (['Permission.WRITE_EXTERNAL_STORAGE'], {}), '(Permission.WRITE_EXTERNAL_STORAGE)\n', (360, 395), False, 'from android.permissions import Permission, request_permission, check_permission\n'), ((956, 998), 'kivy.clock.Clock.schedule_once', 'Clock.... |
from datetime import timedelta
import random
from django.utils import timezone
import factory
class BulletinFactory(factory.DjangoModelFactory):
class Meta:
model = 'bulletin.Bulletin'
url = factory.Sequence(lambda n: f'https://www.sitepage.com/{n}')
latitude = factory.Faker(
... | [
"django.utils.timezone.now",
"factory.Faker",
"datetime.timedelta",
"factory.Sequence"
] | [((224, 283), 'factory.Sequence', 'factory.Sequence', (["(lambda n: f'https://www.sitepage.com/{n}')"], {}), "(lambda n: f'https://www.sitepage.com/{n}')\n", (240, 283), False, 'import factory\n'), ((300, 371), 'factory.Faker', 'factory.Faker', (['"""pydecimal"""'], {'right_digits': '(2)', 'min_value': '(-90)', 'max_va... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# python3 -m pip install --force -U --user PlexAPI
"""
Metadata to be handled:
* Audiobooks
* Playlists -- https://github.com/pkkid/python-plexapi/issues/551
"""
import copy
import json
import time
import logging
import collections
from urllib.parse import urlparse
... | [
"logging.getLogger",
"plexapi.server.PlexServer",
"urllib.parse.urlparse",
"logging.Formatter",
"plexapi.CONFIG.get",
"logging.FileHandler",
"copy.deepcopy",
"json.dump"
] | [((958, 1005), 'logging.getLogger', 'logging.getLogger', (['"""PlexWatchedHistoryExporter"""'], {}), "('PlexWatchedHistoryExporter')\n", (975, 1005), False, 'import logging\n'), ((2539, 2597), 'logging.Formatter', 'logging.Formatter', ([], {'fmt': 'LOG_FORMAT', 'datefmt': 'LOG_DATE_FORMAT'}), '(fmt=LOG_FORMAT, datefmt=... |
from datetime import datetime
from decimal import Decimal
from src.models import db, Required, Optional
class Product(db.Entity):
name = Required(str, unique=True)
price = Required(Decimal)
description = Optional(str)
create_time = Required(datetime, default=datetime.now, precision=6)
update_time... | [
"datetime.datetime.now",
"src.models.Optional",
"src.models.Required"
] | [((144, 170), 'src.models.Required', 'Required', (['str'], {'unique': '(True)'}), '(str, unique=True)\n', (152, 170), False, 'from src.models import db, Required, Optional\n'), ((183, 200), 'src.models.Required', 'Required', (['Decimal'], {}), '(Decimal)\n', (191, 200), False, 'from src.models import db, Required, Opti... |
""" Testing group-level finite difference. """
import unittest
import numpy as np
from openmdao.components.param_comp import ParamComp
from openmdao.core.component import Component
from openmdao.core.group import Group
from openmdao.core.problem import Problem
from openmdao.test.converge_diverge import ConvergeDiverg... | [
"openmdao.components.param_comp.ParamComp",
"openmdao.core.problem.Problem",
"openmdao.test.converge_diverge.ConvergeDivergeGroups",
"openmdao.core.group.Group",
"openmdao.test.util.assert_rel_error",
"unittest.main"
] | [((4041, 4056), 'unittest.main', 'unittest.main', ([], {}), '()\n', (4054, 4056), False, 'import unittest\n'), ((945, 952), 'openmdao.core.group.Group', 'Group', ([], {}), '()\n', (950, 952), False, 'from openmdao.core.group import Group\n'), ((1015, 1024), 'openmdao.core.problem.Problem', 'Problem', ([], {}), '()\n', ... |
from __future__ import absolute_import
import ujson
from rsbroker.core.upstream import RTCWebSocketClient
class BaseUserManager(object):
room_to_uid = {}
uid_to_handler = {}
def register(self, obj):
"""
Dispatch all resource which user need!
:param obj:
:return:
"... | [
"ujson.loads"
] | [((1291, 1312), 'ujson.loads', 'ujson.loads', (['response'], {}), '(response)\n', (1302, 1312), False, 'import ujson\n'), ((1880, 1901), 'ujson.loads', 'ujson.loads', (['response'], {}), '(response)\n', (1891, 1901), False, 'import ujson\n')] |
from pgm.pgmplayer import PGMPlayer
import cps_constraints as con
from operator import itemgetter
import uuid
import os
class ConstraintSolver:
def __init__(self, my_con_collector, my_con_scoper, SHOULD_USE_CONSTRAINT_SCOPING=False):
self.con_collector = my_con_collector
self.con_scoper = my_con_s... | [
"cps_constraints.known_symbol_constraints.items",
"cps_constraints.computed_unit_constraints.items",
"cps_constraints.variables.get",
"operator.itemgetter",
"uuid.uuid4",
"cps_constraints.naming_constraints.items",
"cps_constraints.should_exclude_constraint",
"pgm.pgmplayer.PGMPlayer",
"os.remove"
] | [((2521, 2543), 'pgm.pgmplayer.PGMPlayer', 'PGMPlayer', (['fg_filename'], {}), '(fg_filename)\n', (2530, 2543), False, 'from pgm.pgmplayer import PGMPlayer\n'), ((2911, 2941), 'cps_constraints.naming_constraints.items', 'con.naming_constraints.items', ([], {}), '()\n', (2939, 2941), True, 'import cps_constraints as con... |
import time
import random
import pygame
import pygame.midi
import numpy as np
from typing import Tuple
__author__ = "<NAME>"
AV_SIZE = 20
WIN_X = 30 * AV_SIZE
WIN_Y = 30 * AV_SIZE
DIFF_MAX = np.sqrt(WIN_X**2 + WIN_Y**2)
def adapt_avatar_position(event, user_x_pos:int, user_y_pos:int) -> Tuple[int, int]:
i... | [
"random.choice",
"numpy.sqrt",
"pygame.init",
"pygame.midi.quit",
"pygame.event.get",
"pygame.display.set_mode",
"pygame.display.flip",
"pygame.midi.init",
"pygame.draw.rect",
"pygame.midi.Output",
"time.time",
"random.randint"
] | [((200, 232), 'numpy.sqrt', 'np.sqrt', (['(WIN_X ** 2 + WIN_Y ** 2)'], {}), '(WIN_X ** 2 + WIN_Y ** 2)\n', (207, 232), True, 'import numpy as np\n'), ((1126, 1139), 'pygame.init', 'pygame.init', ([], {}), '()\n', (1137, 1139), False, 'import pygame\n'), ((1145, 1163), 'pygame.midi.init', 'pygame.midi.init', ([], {}), '... |
# coding=utf-8
from __future__ import unicode_literals, absolute_import
from datetime import datetime
from pytz import UTC
from dateutil.parser import parse
fmt = '%Y-%m-%d %H:%M:%S'
utc_fmt = "%Y-%m-%dT%H:%M:%SZ"
def get_utcnow():
at = datetime.utcnow()
at = at.replace(tzinfo=UTC)
return at
def isotime... | [
"dateutil.parser.parse",
"datetime.datetime.utcnow"
] | [((243, 260), 'datetime.datetime.utcnow', 'datetime.utcnow', ([], {}), '()\n', (258, 260), False, 'from datetime import datetime\n'), ((639, 653), 'dateutil.parser.parse', 'parse', (['timestr'], {}), '(timestr)\n', (644, 653), False, 'from dateutil.parser import parse\n'), ((403, 420), 'datetime.datetime.utcnow', 'date... |
# Generated by Django 2.2.4 on 2020-02-08 02:22
from django.db import migrations
def move_batch_fks(apps, schema_editor):
Batch = apps.get_model("petition", "Batch")
CIPRSRecord = apps.get_model("petition", "CIPRSRecord")
for batch in Batch.objects.all():
print(f"Adding batch {batch.pk} to {batch... | [
"django.db.migrations.RunPython"
] | [((721, 757), 'django.db.migrations.RunPython', 'migrations.RunPython', (['move_batch_fks'], {}), '(move_batch_fks)\n', (741, 757), False, 'from django.db import migrations\n')] |
import maya.cmds as mc
import os
import logging
logging.basicConfig()
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
def isNewScene():
"""
Method used to check if this is an untitled scene file.
:rtype: bool
"""
return len(mc.file(query=True, sceneName=True)) == 0
def isSaveRequ... | [
"logging.basicConfig",
"logging.getLogger",
"maya.cmds.delete",
"maya.cmds.ls",
"maya.cmds.window",
"maya.cmds.flushUndo",
"maya.cmds.deleteUI",
"maya.cmds.viewSet",
"maya.cmds.shelfLayout",
"maya.cmds.lsUI",
"maya.cmds.deleteAttr",
"maya.cmds.file",
"maya.cmds.unloadPlugin",
"maya.cmds.lo... | [((49, 70), 'logging.basicConfig', 'logging.basicConfig', ([], {}), '()\n', (68, 70), False, 'import logging\n'), ((77, 104), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (94, 104), False, 'import logging\n'), ((457, 491), 'maya.cmds.file', 'mc.file', ([], {'query': '(True)', 'modified'... |
import sys
import numpy as np
import torch
from monai import transforms, data
from ..data import DataModule, ReadImaged, Renamed, Inferer
###################################
# Transform
###################################
def wmh_train_transform(
spacing=(1.0, 1.0, 1.0), spatial_size=(128, 128, 128), num_patc... | [
"monai.transforms.CropForegroundd",
"monai.transforms.RandScaleIntensityd",
"monai.transforms.NormalizeIntensityd",
"monai.transforms.RandShiftIntensityd",
"monai.transforms.RandAdjustContrastd",
"monai.transforms.Spacingd",
"monai.transforms.AddChanneld",
"monai.transforms.RandGaussianNoised",
"mon... | [((2309, 2344), 'monai.transforms.Compose', 'transforms.Compose', (['train_transform'], {}), '(train_transform)\n', (2327, 2344), False, 'from monai import transforms, data\n'), ((2924, 2957), 'monai.transforms.Compose', 'transforms.Compose', (['val_transform'], {}), '(val_transform)\n', (2942, 2957), False, 'from mona... |
"""Base class for rotor tests."""
import unittest
from enigma.rotor.reflector import Reflector
from enigma.rotor.rotor import Rotor
class RotorTest(unittest.TestCase):
"""Provides tools testing rotors."""
def get_rotor(
self,
wiring="EKMFLGDQVZNTOWYHXUSPAIBRCJ",
ring_setting=1,
... | [
"enigma.rotor.reflector.Reflector",
"enigma.rotor.rotor.Rotor"
] | [((429, 538), 'enigma.rotor.rotor.Rotor', 'Rotor', ([], {'wiring': 'wiring', 'ring_setting': 'ring_setting', 'position': 'position', 'turnover_positions': 'turnover_positions'}), '(wiring=wiring, ring_setting=ring_setting, position=position,\n turnover_positions=turnover_positions)\n', (434, 538), False, 'from enigm... |
# Created by <NAME>.
# GitHub: https://github.com/ikostan
# LinkedIn: https://www.linkedin.com/in/egor-kostan/
# FUNDAMENTALS ARRAYS NUMBERS BASIC LANGUAGE FEATURES
import unittest
import allure
from utils.log_func import print_log
from kyu_8.check_the_exam.check_exam import check_exam
@allure.epic('8 kyu')
@all... | [
"allure.parent_suite",
"allure.tag",
"allure.step",
"kyu_8.check_the_exam.check_exam.check_exam",
"allure.sub_suite",
"allure.dynamic.severity",
"allure.story",
"allure.link",
"allure.dynamic.description_html",
"allure.epic",
"allure.suite",
"allure.dynamic.title",
"allure.feature",
"utils... | [((295, 315), 'allure.epic', 'allure.epic', (['"""8 kyu"""'], {}), "('8 kyu')\n", (306, 315), False, 'import allure\n'), ((317, 348), 'allure.parent_suite', 'allure.parent_suite', (['"""Beginner"""'], {}), "('Beginner')\n", (336, 348), False, 'import allure\n'), ((350, 381), 'allure.suite', 'allure.suite', (['"""Data S... |
import os.path
from twisted.internet import defer
import pysoup.utils
class Virtualenv(object):
def __init__(self, display_pip, path):
self._display_pipe = display_pip
self._path = path
@property
def path(self):
return self._path
@property
def venv_path(self):
... | [
"twisted.internet.defer.returnValue"
] | [((1169, 1192), 'twisted.internet.defer.returnValue', 'defer.returnValue', (['code'], {}), '(code)\n', (1186, 1192), False, 'from twisted.internet import defer\n')] |
from yggdrasil.metaschema.datatypes import MetaschemaTypeError
from yggdrasil.metaschema.datatypes.MetaschemaType import MetaschemaType
from yggdrasil.metaschema.datatypes.JSONObjectMetaschemaType import (
JSONObjectMetaschemaType)
from yggdrasil.metaschema.properties.ArgsMetaschemaProperty import (
ArgsMetasch... | [
"yggdrasil.metaschema.datatypes.JSONObjectMetaschemaType.JSONObjectMetaschemaType.encode_data",
"yggdrasil.metaschema.properties.ArgsMetaschemaProperty.ArgsMetaschemaProperty.instance2args"
] | [((1912, 1953), 'yggdrasil.metaschema.properties.ArgsMetaschemaProperty.ArgsMetaschemaProperty.instance2args', 'ArgsMetaschemaProperty.instance2args', (['obj'], {}), '(obj)\n', (1948, 1953), False, 'from yggdrasil.metaschema.properties.ArgsMetaschemaProperty import ArgsMetaschemaProperty\n'), ((2136, 2192), 'yggdrasil.... |
# Generated by Django 2.1.3 on 2018-12-02 17:52
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('battleships', '0003_auto_20181202_1832'),
]
operations = [
migrations.RenameField(
model_name='coordinate',
old_name='ship',... | [
"django.db.migrations.RenameField"
] | [((231, 318), 'django.db.migrations.RenameField', 'migrations.RenameField', ([], {'model_name': '"""coordinate"""', 'old_name': '"""ship"""', 'new_name': '"""ship1"""'}), "(model_name='coordinate', old_name='ship', new_name=\n 'ship1')\n", (253, 318), False, 'from django.db import migrations\n')] |
import abc
import os
import pandas as pd
import numpy as np
from EoraReader import EoraReader
class PrimaryInputs(EoraReader):
def __init__(self, file_path):
super().__init__(file_path)
self.df = None
def get_dataset(self, extended = False):
"""
Returns a pandas dataframe conta... | [
"pandas.DataFrame",
"numpy.array"
] | [((948, 980), 'numpy.array', 'np.array', (['value_add_coefficients'], {}), '(value_add_coefficients)\n', (956, 980), True, 'import numpy as np\n'), ((994, 1045), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'numpy_data', 'index': 'primary_inputs'}), '(data=numpy_data, index=primary_inputs)\n', (1006, 1045), True, ... |
'''OpenGL extension ATI.text_fragment_shader
This module customises the behaviour of the
OpenGL.raw.GL.ATI.text_fragment_shader to provide a more
Python-friendly API
Overview (from the spec)
The ATI_fragment_shader extension exposes a powerful fragment
processing model that provides a very general means of expr... | [
"OpenGL.extensions.hasGLExtension"
] | [((3804, 3846), 'OpenGL.extensions.hasGLExtension', 'extensions.hasGLExtension', (['_EXTENSION_NAME'], {}), '(_EXTENSION_NAME)\n', (3829, 3846), False, 'from OpenGL import extensions\n')] |
import attr
import types
from typing import Union
from enum import Enum
import numpy as np
from scipy.optimize import differential_evolution
import pygmo as pg
class OptimizationMethod(Enum):
"""
Available optimization solvers.
"""
SCIPY_DE = 1
PYGMO_DE1220 = 2
@attr.s(auto_attribs=True)
class S... | [
"attr.s",
"pygmo.archipelago",
"scipy.optimize.differential_evolution",
"pygmo.problem",
"pygmo.population",
"numpy.array",
"numpy.random.randint",
"pygmo.algorithm",
"pygmo.de1220",
"numpy.argmin",
"numpy.random.RandomState",
"pygmo.nlopt"
] | [((287, 312), 'attr.s', 'attr.s', ([], {'auto_attribs': '(True)'}), '(auto_attribs=True)\n', (293, 312), False, 'import attr\n'), ((4837, 4862), 'attr.s', 'attr.s', ([], {'auto_attribs': '(True)'}), '(auto_attribs=True)\n', (4843, 4862), False, 'import attr\n'), ((5322, 5347), 'attr.s', 'attr.s', ([], {'auto_attribs': ... |
# MIT License
#
# Copyright (c) 2021 TrigonDev
#
# 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, pu... | [
"apgorm.types.Int",
"apgorm.types.Array"
] | [((1292, 1306), 'apgorm.types.Array', 'Array', (['subtype'], {}), '(subtype)\n', (1297, 1306), False, 'from apgorm.types import Array, Int\n'), ((1211, 1216), 'apgorm.types.Int', 'Int', ([], {}), '()\n', (1214, 1216), False, 'from apgorm.types import Array, Int\n'), ((1224, 1229), 'apgorm.types.Int', 'Int', ([], {}), '... |
from fastapi import FastAPI
from vogue.api.api_v1.endpoints import (
insert_documents,
home,
common_trends,
sequencing,
genootype,
reagent_labels,
prepps,
bioinfo_covid,
bioinfo_micro,
bioinfo_mip,
update,
)
from vogue.settings import static_files
app = FastAPI()
app.mount... | [
"fastapi.FastAPI"
] | [((301, 310), 'fastapi.FastAPI', 'FastAPI', ([], {}), '()\n', (308, 310), False, 'from fastapi import FastAPI\n')] |
import torch.nn as nn
import torch.nn.functional as F
from dgcnn.pytorch.model import DGCNN as DGCNN_original
from all_utils import DATASET_NUM_CLASS
class DGCNN(nn.Module):
def __init__(self, task, dataset):
super().__init__()
self.task = task
self.dataset = dataset
if task == "... | [
"dgcnn.pytorch.model.DGCNN"
] | [((674, 723), 'dgcnn.pytorch.model.DGCNN', 'DGCNN_original', (['args'], {'output_channels': 'num_classes'}), '(args, output_channels=num_classes)\n', (688, 723), True, 'from dgcnn.pytorch.model import DGCNN as DGCNN_original\n')] |
from collections import deque
N, K = map(int, input().split())
T = [int(input()) for _ in range(N)]
ans_dq = deque([0, 0, 0])
for i, t in enumerate(T):
ans_dq.append(t)
ans_dq.popleft()
if sum(ans_dq) < K and i > 1:
print(i + 1)
break
else:
print(-1)
| [
"collections.deque"
] | [((109, 125), 'collections.deque', 'deque', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (114, 125), False, 'from collections import deque\n')] |
import cv2
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
import numpy as np
model = "./AI_Mask_Detector/res10_300x300_ssd_iter_140000_fp16.caffemodel"
config = "./AI_Mask_Detector/deploy.prototxt"
# model = './AI_Mask_Detector/opencv_face_detector_uint8.pb'
# config = './AI_Mask_... | [
"cv2.dnn.blobFromImage",
"cv2.rectangle",
"tensorflow.keras.Sequential",
"cv2.imshow",
"cv2.putText",
"cv2.destroyAllWindows",
"tensorflow.keras.models.load_model",
"cv2.VideoCapture",
"cv2.cvtColor",
"tensorflow.convert_to_tensor",
"tensorflow.expand_dims",
"cv2.resize",
"cv2.waitKey",
"c... | [((371, 428), 'tensorflow.keras.models.load_model', 'tf.keras.models.load_model', (['"""./AI_Mask_Detector/model.h5"""'], {}), "('./AI_Mask_Detector/model.h5')\n", (397, 428), True, 'import tensorflow as tf\n'), ((449, 482), 'tensorflow.keras.Sequential', 'tf.keras.Sequential', (['[mask_model]'], {}), '([mask_model])\n... |
# services/ovpn_server/project/tests/test_ovpn_server.py
import os
import json
import io
from flask import current_app
from project.tests.base import BaseTestCase
class TestOvpnServer(BaseTestCase):
def test_certificates(self):
with self.client:
pki_path = current_app.config['PKI_PATH']
... | [
"os.path.isfile",
"io.BytesIO",
"os.remove"
] | [((977, 1020), 'os.remove', 'os.remove', (['f"""{pki_path}/reqs/test_cert.req"""'], {}), "(f'{pki_path}/reqs/test_cert.req')\n", (986, 1020), False, 'import os\n'), ((915, 963), 'os.path.isfile', 'os.path.isfile', (['f"""{pki_path}/reqs/test_cert.req"""'], {}), "(f'{pki_path}/reqs/test_cert.req')\n", (929, 963), False,... |
# encoding: utf-8
from web.ext.acl import when
from ..templates.admin.admintemplate import page as _page
from ..templates.admin.requests import requeststemplate, requestrow
from ..templates.requests import requestrow as rr
from ..send_update import send_update
import cinje
@when(when.matches(True, 'session.authentica... | [
"web.ext.acl.when.matches"
] | [((282, 331), 'web.ext.acl.when.matches', 'when.matches', (['(True)', '"""session.authenticated"""', '(True)'], {}), "(True, 'session.authenticated', True)\n", (294, 331), False, 'from web.ext.acl import when\n')] |
from unittest import TestCase
from day10 import KnotHasher
class TestKnotHasher(TestCase):
def test_calc(self):
sut = KnotHasher(5, [3, 4, 1, 5])
self.assertEqual(12, sut.calc())
def test_hash1(self):
sut = KnotHasher(256, '')
self.assertEqual('a2582a3a0e66e6e86e3812dcb672a272... | [
"day10.KnotHasher"
] | [((132, 159), 'day10.KnotHasher', 'KnotHasher', (['(5)', '[3, 4, 1, 5]'], {}), '(5, [3, 4, 1, 5])\n', (142, 159), False, 'from day10 import KnotHasher\n'), ((242, 261), 'day10.KnotHasher', 'KnotHasher', (['(256)', '""""""'], {}), "(256, '')\n", (252, 261), False, 'from day10 import KnotHasher\n'), ((376, 403), 'day10.K... |
#!/usr/bin/env python3
import fire
import json
import os
import numpy as np
import tensorflow as tf
import model, sample, encoder
def interact_model(
model_name='117M',
seed=None,
nsamples=1000,
batch_size=1,
length=None,
temperature=1,
top_k=0,
top_p=0.0
):
"""
Interactively ... | [
"tensorflow.Graph",
"encoder.get_encoder",
"fire.Fire",
"tensorflow.placeholder",
"tensorflow.train.Saver",
"os.path.join",
"sample.sample_sequence",
"model.default_hparams",
"numpy.random.seed",
"json.load",
"tensorflow.ConfigProto",
"tensorflow.set_random_seed",
"time.time"
] | [((1595, 1626), 'encoder.get_encoder', 'encoder.get_encoder', (['model_name'], {}), '(model_name)\n', (1614, 1626), False, 'import model, sample, encoder\n'), ((1641, 1664), 'model.default_hparams', 'model.default_hparams', ([], {}), '()\n', (1662, 1664), False, 'import model, sample, encoder\n'), ((2059, 2075), 'tenso... |
import saludos
saludos.saludar() | [
"saludos.saludar"
] | [((16, 33), 'saludos.saludar', 'saludos.saludar', ([], {}), '()\n', (31, 33), False, 'import saludos\n')] |
import re
import os
values = {
'uc': 'Vurple',
'lc': 'vurple',
'cl': '#116BB7',
}
def main():
infile = "yeti/variables.less"
f = open(infile, 'r')
lines = f.readlines()
f.close()
outfile = values['lc'] + "/variables.less"
f = open(outfile, 'w')
for line in lines:
l... | [
"re.sub",
"os.system",
"re.search"
] | [((2055, 2069), 'os.system', 'os.system', (['cmd'], {}), '(cmd)\n', (2064, 2069), False, 'import os\n'), ((2210, 2224), 'os.system', 'os.system', (['cmd'], {}), '(cmd)\n', (2219, 2224), False, 'import os\n'), ((2342, 2356), 'os.system', 'os.system', (['cmd'], {}), '(cmd)\n', (2351, 2356), False, 'import os\n'), ((2469,... |
#!/usr/bin/python3
from validData import *
from command import *
from readback import *
import sys
import time
# Expected Input
# 1: Row -> 0 to 9
# 2: Column -> 0 to 19
if (
isInt(sys.argv[1]) and strLengthIs(sys.argv[1],1) and
isInt(sys.argv[2]) and (strLengthIs(sys.argv[2],1) or strLengthIs(sys.ar... | [
"time.sleep"
] | [((462, 477), 'time.sleep', 'time.sleep', (['(0.3)'], {}), '(0.3)\n', (472, 477), False, 'import time\n')] |
from getpass import getpass
from colorama import init, Fore, Back, Style
yes = ['Y', 'y', 'YES', 'yes', 'Yes']
class interface(object):
"""
Terminal CLI
"""
def log(self, arg, get=False):
if not get:
print("[*]: {} ".format(arg))
else:
return "[*]: {} ".format(a... | [
"getpass.getpass"
] | [((1690, 1699), 'getpass.getpass', 'getpass', ([], {}), '()\n', (1697, 1699), False, 'from getpass import getpass\n'), ((1361, 1386), 'getpass.getpass', 'getpass', (['"""[*]: Password:"""'], {}), "('[*]: Password:')\n", (1368, 1386), False, 'from getpass import getpass\n'), ((1419, 1451), 'getpass.getpass', 'getpass', ... |
from app.models import Circuit, CircuitSchema, Provider
from flask import make_response, jsonify
from app import db
def read_all():
"""
This function responds to a request for /circuits
with the complete lists of circuits
:return: sorted list of circuits
"""
circuits = Circuit.query.al... | [
"app.db.session.commit",
"app.db.session.merge",
"app.models.Circuit.query.filter",
"app.models.Circuit.query.all",
"app.models.Provider.query.filter",
"app.db.session.add",
"app.models.Circuit.query.filter_by",
"app.models.CircuitSchema",
"flask.jsonify"
] | [((304, 323), 'app.models.Circuit.query.all', 'Circuit.query.all', ([], {}), '()\n', (321, 323), False, 'from app.models import Circuit, CircuitSchema, Provider\n'), ((337, 361), 'app.models.CircuitSchema', 'CircuitSchema', ([], {'many': '(True)'}), '(many=True)\n', (350, 361), False, 'from app.models import Circuit, C... |
import asyncio
import json
import re
from collections import deque
from typing import Deque, Dict, List, Match, Pattern
import aiohttp
from .error import RateLimited
headers: dict = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"
}
DATA_JSON: Pattern = re.compile(
r'(... | [
"aiohttp.ClientSession",
"aiohttp.TCPConnector",
"collections.deque",
"re.compile"
] | [((301, 377), 're.compile', 're.compile', (['"""(?:window\\\\["ytInitialData"\\\\]|ytInitialData)\\\\W?=\\\\W?({.*?});"""'], {}), '(\'(?:window\\\\["ytInitialData"\\\\]|ytInitialData)\\\\W?=\\\\W?({.*?});\')\n', (311, 377), False, 'import re\n'), ((619, 667), 'aiohttp.TCPConnector', 'aiohttp.TCPConnector', ([], {'local... |
# Generated by Django 2.2.5 on 2019-09-24 09:11
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
... | [
"django.db.models.FloatField",
"django.db.models.DateField",
"django.db.models.TextField",
"django.db.models.ForeignKey",
"django.db.models.DateTimeField",
"django.db.models.AutoField",
"django.db.models.PositiveIntegerField",
"django.db.models.ImageField",
"django.db.models.CharField"
] | [((337, 430), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (353, 430), False, 'from django.db import migrations, models\... |
#!/usr/bin/python3
from typing import Dict
import optparse
import numpy as np
import rasterio
from rasterio import features
def main(county_pop_file, spatial_dist_file, fname_out, no_data_val=-9999):
'''
county_pop_file: County level population estimates
spatial_dist_file: Spatial projection of populati... | [
"numpy.intersect1d",
"numpy.ones",
"rasterio.open",
"optparse.OptionParser",
"numpy.squeeze",
"numpy.unravel_index",
"numpy.round"
] | [((1730, 1753), 'optparse.OptionParser', 'optparse.OptionParser', ([], {}), '()\n', (1751, 1753), False, 'import optparse\n'), ((996, 1018), 'numpy.squeeze', 'np.squeeze', (['county_pop'], {}), '(county_pop)\n', (1006, 1018), True, 'import numpy as np\n'), ((1034, 1054), 'numpy.squeeze', 'np.squeeze', (['pop_dist'], {}... |
import testtools
from oslo_log import log
from tempest.api.compute import base
import tempest.api.compute.flavors.test_flavors as FlavorsV2Test
import tempest.api.compute.flavors.test_flavors_negative as FlavorsListWithDetailsNegativeTest
import tempest.api.compute.flavors.test_flavors_negative as FlavorDetailsNegativ... | [
"testtools.skip",
"oslo_log.log.getLogger"
] | [((530, 553), 'oslo_log.log.getLogger', 'log.getLogger', (['__name__'], {}), '(__name__)\n', (543, 553), False, 'from oslo_log import log\n'), ((644, 691), 'testtools.skip', 'testtools.skip', (['"""testscenarios are not active."""'], {}), "('testscenarios are not active.')\n", (658, 691), False, 'import testtools\n'), ... |
#!/usr/bin/env python3
"""
dycall.exports
~~~~~~~~~~~~~~
Contains `ExportsFrame` and `ExportsTreeView`.
"""
from __future__ import annotations
import logging
import pathlib
from typing import TYPE_CHECKING
import ttkbootstrap as tk
from ttkbootstrap import ttk
from ttkbootstrap.dialogs import Messagebox
from ttkbo... | [
"logging.getLogger",
"dycall.util.StaticThemedTooltip",
"ttkbootstrap.dialogs.Messagebox.show_error",
"ttkbootstrap.localization.MessageCatalog.translate",
"ttkbootstrap.ttk.Label",
"dycall.util.get_img",
"ttkbootstrap.tableview.Tableview",
"ttkbootstrap.dialogs.Messagebox.show_warning"
] | [((563, 590), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (580, 590), False, 'import logging\n'), ((2172, 2191), 'dycall.util.get_img', 'get_img', (['"""list.png"""'], {}), "('list.png')\n", (2179, 2191), False, 'from dycall.util import StaticThemedTooltip, get_img\n'), ((2210, 2248), ... |
#!/usr/bin/env python3
#import face_recognition
import cv2
import numpy as np
from datetime import datetime, timedelta
from buffer import Buffer
from collections import deque
import os
from copy import copy
import archive
WEIGHT_EPS = 5
TIMEOUT = 5 # in seconds
def poll_weight():
return 500
# with an fps we the... | [
"archive.try_upload_buffer",
"buffer.Buffer",
"copy.copy",
"datetime.timedelta",
"datetime.datetime.now",
"cv2.VideoCapture",
"archive.create_from_clip",
"cv2.resize"
] | [((376, 387), 'buffer.Buffer', 'Buffer', (['(300)'], {}), '(300)\n', (382, 387), False, 'from buffer import Buffer\n'), ((482, 501), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (498, 501), False, 'import cv2\n'), ((519, 546), 'archive.try_upload_buffer', 'archive.try_upload_buffer', ([], {}), '()\n'... |