code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 17 11:02:21 2019
@author: elizabethhutton
"""
import pandas as pd
import numpy as np
from sklearn.manifold import TSNE
from matplotlib import pyplot as plt
from sklearn.cluster import KMeans
from wordcloud import WordCloud
from yellowbrick.cluster ... | [
"sklearn.cluster.KMeans",
"sklearn.manifold.TSNE",
"matplotlib.pyplot.annotate",
"matplotlib.pyplot.figure",
"sklearn.neighbors.NearestNeighbors",
"matplotlib.pyplot.scatter",
"pandas.DataFrame",
"numpy.set_printoptions"
] | [((829, 878), 'sklearn.cluster.KMeans', 'KMeans', ([], {'n_clusters': 'num_clusters', 'init': '"""k-means++"""'}), "(n_clusters=num_clusters, init='k-means++')\n", (835, 878), False, 'from sklearn.cluster import KMeans\n'), ((1131, 1197), 'pandas.DataFrame', 'pd.DataFrame', (['idx'], {'columns': "['clusterid']", 'index... |
from netmiko import ConnectHandler
from getpass import getpass
device1 = {
'host' : 'cisco4.lasthop.io',
'username' : 'pyclass',
'password' : getpass(),
'device_type' : 'cisco_ios',
'global_delay_factor' : 2,
}
net_connect = ConnectHandler(**device1)
print(net_connect.find_prompt())
output = net_... | [
"netmiko.ConnectHandler",
"getpass.getpass"
] | [((247, 272), 'netmiko.ConnectHandler', 'ConnectHandler', ([], {}), '(**device1)\n', (261, 272), False, 'from netmiko import ConnectHandler\n'), ((155, 164), 'getpass.getpass', 'getpass', ([], {}), '()\n', (162, 164), False, 'from getpass import getpass\n')] |
# -*- coding: utf-8 -*-
import os
import telebot
import time
import random
import threading
from emoji import emojize
from telebot import types
from pymongo import MongoClient
import traceback
token = os.environ['TELEGRAM_TOKEN']
bot = telebot.TeleBot(token)
fighters=[]
btimer=10
names=['Волк', 'Осёл', 'Кроль', '<NA... | [
"threading.Timer",
"random.choice",
"random.randint",
"telebot.TeleBot"
] | [((237, 259), 'telebot.TeleBot', 'telebot.TeleBot', (['token'], {}), '(token)\n', (252, 259), False, 'import telebot\n'), ((3715, 3745), 'threading.Timer', 'threading.Timer', (['btimer', 'fight'], {}), '(btimer, fight)\n', (3730, 3745), False, 'import threading\n'), ((3621, 3641), 'random.choice', 'random.choice', (['n... |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
... | [
"django.db.models.EmailField",
"django.db.models.TextField",
"django.db.models.ForeignKey",
"django.db.models.BooleanField",
"django.db.models.SlugField",
"django.db.models.PositiveSmallIntegerField",
"django.db.models.PositiveIntegerField",
"django.db.models.BigAutoField",
"django.db.models.DateTim... | [((198, 255), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (229, 255), False, 'from django.db import migrations, models\n'), ((4582, 4687), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'djang... |
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.utils.functional import cached_property
from django.utils.translation import ugettext as _
from django.utils.translation import ugettext_noop, ugettext_lazy
from couchdbkit import ResourceNotFound
from memoized import memoized... | [
"corehq.apps.fixtures.models._id_from_doc",
"django.utils.translation.ugettext_lazy",
"django.utils.translation.ugettext_noop",
"corehq.apps.fixtures.views.data_table",
"corehq.apps.fixtures.views.fixtures_home",
"corehq.apps.fixtures.models.FixtureDataType.get",
"django.utils.translation.ugettext",
"... | [((1048, 1079), 'django.utils.translation.ugettext_lazy', 'ugettext_lazy', (['"""Select a Table"""'], {}), "('Select a Table')\n", (1061, 1079), False, 'from django.utils.translation import ugettext_noop, ugettext_lazy\n'), ((1572, 1600), 'django.utils.translation.ugettext_noop', 'ugettext_noop', (['"""View Tables"""']... |
"""
Code for the optimization and gaming component of the Baselining work.
@author: <NAME>, <NAME>
@date Mar 2, 2016
"""
import numpy as np
import pandas as pd
import logging
from gurobipy import GRB, Model, quicksum, LinExpr
from pandas.tseries.holiday import USFederalHolidayCalendar
from datetime import datetime
f... | [
"pandas.Series",
"datetime.datetime",
"numpy.unique",
"pandas.tseries.holiday.USFederalHolidayCalendar",
"pandas.DatetimeIndex",
"numpy.size",
"numpy.linalg.norm",
"numpy.asarray",
"numpy.max",
"gurobipy.quicksum",
"gurobipy.LinExpr",
"numpy.isnan",
"gurobipy.Model",
"pandas.DataFrame",
... | [((907, 914), 'gurobipy.Model', 'Model', ([], {}), '()\n', (912, 914), False, 'from gurobipy import GRB, Model, quicksum, LinExpr\n'), ((19530, 19541), 'numpy.isnan', 'np.isnan', (['M'], {}), '(M)\n', (19538, 19541), True, 'import numpy as np\n'), ((19974, 20009), 'pandas.Series', 'pd.Series', (['isBusiness'], {'index'... |
#
# prp-htcondor-portal/provisioner
#
# BSD license, copyright <NAME> 2021
#
# Main entry point of the provisioner process
#
import sys
import time
from . import provisioner_logging
from . import provisioner_htcondor
from . import provisioner_k8s
from . import event_loop
def main(namespace, max_pods_per_cluster=10, ... | [
"time.sleep"
] | [((998, 1020), 'time.sleep', 'time.sleep', (['sleep_time'], {}), '(sleep_time)\n', (1008, 1020), False, 'import time\n')] |
# Front matter
##############
import os
from os import fdopen, remove
from tempfile import mkstemp
from shutil import move
import glob
import re
import time
import pandas as pd
import numpy as np
from scipy import constants
from scipy.optimize import curve_fit, fsolve
from scipy.interpolate import interp1d
import matpl... | [
"numpy.sqrt",
"pandas.read_csv",
"seaborn.set_style",
"matplotlib.pyplot.close",
"matplotlib.rc",
"time.time",
"matplotlib.pyplot.subplots"
] | [((509, 545), 'matplotlib.rc', 'matplotlib.rc', (['"""xtick"""'], {'labelsize': '(16)'}), "('xtick', labelsize=16)\n", (522, 545), False, 'import matplotlib\n'), ((547, 583), 'matplotlib.rc', 'matplotlib.rc', (['"""ytick"""'], {'labelsize': '(16)'}), "('ytick', labelsize=16)\n", (560, 583), False, 'import matplotlib\n'... |
"""Test cases."""
import unittest
import logging
from speedtest2dynamodb import parse_output
class SpeedTest2DynamoDBTestCase(unittest.TestCase):
"""Collection of tests."""
def setUp(self):
self.logger = logging.getLogger()
def test_parse_output_bit(self):
"""Test output that contains on... | [
"unittest.main",
"speedtest2dynamodb.parse_output",
"logging.getLogger"
] | [((2628, 2643), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2641, 2643), False, 'import unittest\n'), ((223, 242), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (240, 242), False, 'import logging\n'), ((371, 446), 'speedtest2dynamodb.parse_output', 'parse_output', (['"""Ping: 10.331 ms\nDownload:... |
import cv2
import numpy as np
import picamera
import time
def identifySq(pt, w, h):
tlx = 80
tly = 210
ppx = 94
ppy = 82
sqx = (pt[0]-(tlx-ppx/2))/ppx
sqy = (pt[1]-(tly-ppy/2))/ppy
# print ("ID",pt, w, h, sqx, sqy)
if sqx < 0 or sqx >= 4 or sqy < 0 or sqy >= 4:
return 0, False
... | [
"cv2.imwrite",
"cv2.findHomography",
"numpy.where",
"picamera.PiCamera",
"cv2.imshow",
"numpy.array",
"cv2.warpPerspective",
"cv2.waitKey",
"cv2.cvtColor",
"cv2.resize",
"cv2.matchTemplate",
"cv2.imread"
] | [((417, 436), 'picamera.PiCamera', 'picamera.PiCamera', ([], {}), '()\n', (434, 436), False, 'import picamera\n'), ((506, 530), 'cv2.imread', 'cv2.imread', (['"""newimg.jpg"""'], {}), "('newimg.jpg')\n", (516, 530), False, 'import cv2\n'), ((682, 736), 'cv2.resize', 'cv2.resize', (['im_src', 'dim1'], {'interpolation': ... |
import re
import discord
from data.model import Tag
class TagModal(discord.ui.Modal):
def __init__(self, bot, tag_name, author: discord.Member) -> None:
self.bot = bot
self.tag_name = tag_name
self.author = author
self.tag = None
super().__init__(title=f"Add tag {self.tag... | [
"re.search",
"data.model.Tag",
"re.match",
"discord.ui.TextInput",
"discord.Color.red"
] | [((2955, 2960), 'data.model.Tag', 'Tag', ([], {}), '()\n', (2958, 2960), False, 'from data.model import Tag\n'), ((365, 486), 'discord.ui.TextInput', 'discord.ui.TextInput', ([], {'label': '"""Body of the tag"""', 'placeholder': '"""Enter the body of the tag"""', 'style': 'discord.TextStyle.long'}), "(label='Body of th... |
import NLQ_Preprocessor as preProcessor
import NLP_Engine as nlpEngine
import NLQ_Interpreter as interpreter
import nltk
import time
class NLQ_Chunker:
def __init__(self):
self.preprocessor = preProcessor.PreProcessor()
self.nlp_engine = nlpEngine.NLP_Engine()
self.interpreter = interpre... | [
"nltk.pos_tag",
"nltk.word_tokenize",
"NLP_Engine.NLP_Engine",
"NLQ_Preprocessor.PreProcessor",
"NLQ_Interpreter.Interpreter"
] | [((208, 235), 'NLQ_Preprocessor.PreProcessor', 'preProcessor.PreProcessor', ([], {}), '()\n', (233, 235), True, 'import NLQ_Preprocessor as preProcessor\n'), ((262, 284), 'NLP_Engine.NLP_Engine', 'nlpEngine.NLP_Engine', ([], {}), '()\n', (282, 284), True, 'import NLP_Engine as nlpEngine\n'), ((312, 337), 'NLQ_Interpret... |
from src.neural_networks.art_fuzzy import ARTFUZZY
import numpy as np
def test_If_I_isintance_numpy():
A = ARTFUZZY([1.0, 2.0])
assert isinstance(A.I, np.ndarray)
def test_If_W_isintance_numpy():
A = ARTFUZZY([1.0, 2.0])
assert isinstance(A.I, np.ndarray) | [
"src.neural_networks.art_fuzzy.ARTFUZZY"
] | [((113, 133), 'src.neural_networks.art_fuzzy.ARTFUZZY', 'ARTFUZZY', (['[1.0, 2.0]'], {}), '([1.0, 2.0])\n', (121, 133), False, 'from src.neural_networks.art_fuzzy import ARTFUZZY\n'), ((219, 239), 'src.neural_networks.art_fuzzy.ARTFUZZY', 'ARTFUZZY', (['[1.0, 2.0]'], {}), '([1.0, 2.0])\n', (227, 239), False, 'from src.... |
'''Tests for methods in helpers/no_import_common_class/utilities.py'''
# pylint: disable=missing-function-docstring
# pylint: disable=redefined-outer-name
import pytest
import helpers.no_import_common_class.paragraph_helpers as helpers
import utilities.random_methods as utils
import testing.data.dict_constants as cons... | [
"utilities.random_methods.dict_from_split_string",
"utilities.random_methods.find_dictionary_from_list_by_key_and_value",
"pytest.mark.parametrize",
"utilities.random_methods.key_not_in_dictionary",
"utilities.random_methods.dictionary_key_begins_with_substring",
"utilities.random_methods.key_in_dictionar... | [((951, 1027), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""key, expected"""', "[('alive', True), ('name', False)]"], {}), "('key, expected', [('alive', True), ('name', False)])\n", (974, 1027), False, 'import pytest\n'), ((1172, 1248), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""key, exp... |
# coding: utf-8
#
# Project: X-ray image reader
# https://github.com/silx-kit/fabio
#
#
# Copyright (C) European Synchrotron Radiation Facility, Grenoble, France
#
# Principal author: <NAME> (<EMAIL>)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this s... | [
"logging.getLogger",
"re.compile"
] | [((1470, 1497), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1487, 1497), False, 'import logging\n'), ((2107, 2137), 're.compile', 're.compile', (['"""\\\\s*[,:=\\\\s]\\\\s*"""'], {}), "('\\\\s*[,:=\\\\s]\\\\s*')\n", (2117, 2137), False, 'import re\n')] |
# coding: utf-8
"""
CLOUD API
IONOS Enterprise-grade Infrastructure as a Service (IaaS) solutions can be managed through the Cloud API, in addition or as an alternative to the \"Data Center Designer\" (DCD) browser-based tool. Both methods employ consistent concepts and features, deliver similar power and ... | [
"ionoscloud.configuration.Configuration",
"six.iteritems"
] | [((3223, 3256), 'six.iteritems', 'six.iteritems', (['self.openapi_types'], {}), '(self.openapi_types)\n', (3236, 3256), False, 'import six\n'), ((1567, 1582), 'ionoscloud.configuration.Configuration', 'Configuration', ([], {}), '()\n', (1580, 1582), False, 'from ionoscloud.configuration import Configuration\n')] |
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileRequired, FileAllowed
class CSVUploadForm(FlaskForm):
csvfile = FileField(
"CSV Mark Sheet",
validators=[FileRequired(), FileAllowed(["csv"], "CSV Files only!")],
)
| [
"flask_wtf.file.FileRequired",
"flask_wtf.file.FileAllowed"
] | [((201, 215), 'flask_wtf.file.FileRequired', 'FileRequired', ([], {}), '()\n', (213, 215), False, 'from flask_wtf.file import FileField, FileRequired, FileAllowed\n'), ((217, 256), 'flask_wtf.file.FileAllowed', 'FileAllowed', (["['csv']", '"""CSV Files only!"""'], {}), "(['csv'], 'CSV Files only!')\n", (228, 256), Fals... |
import pandas as pd
from tensorflow import keras, reduce_sum, ragged, function, math, nn, reduce_mean
from os import environ
class MaskedEmbeddingsAggregatorLayer(keras.layers.Layer):
def __init__(self, agg_mode='sum', **kwargs):
super(MaskedEmbeddingsAggregatorLayer, self).__init__(**kwargs)
if ... | [
"tensorflow.keras.layers.Input",
"tensorflow.keras.layers.Concatenate",
"tensorflow.keras.preprocessing.sequence.pad_sequences",
"tensorflow.keras.layers.ReLU",
"tensorflow.reduce_sum",
"tensorflow.ragged.boolean_mask",
"os.environ.get",
"tensorflow.keras.layers.BatchNormalization",
"tensorflow.kera... | [((2042, 2096), 'tensorflow.keras.layers.Input', 'keras.layers.Input', ([], {'shape': '(None,)', 'name': '"""search_query"""'}), "(shape=(None,), name='search_query')\n", (2060, 2096), False, 'from tensorflow import keras, reduce_sum, ragged, function, math, nn, reduce_mean\n'), ((2117, 2172), 'tensorflow.keras.layers.... |
import django_tables2 as tables
from nautobot.utilities.tables import (
BaseTable,
ButtonsColumn,
ToggleColumn,
)
from example_plugin.models import AnotherExampleModel, ExampleModel
class ExampleModelTable(BaseTable):
"""Table for list view of `ExampleModel` objects."""
pk = ToggleColumn()
... | [
"nautobot.utilities.tables.ToggleColumn",
"django_tables2.LinkColumn",
"nautobot.utilities.tables.ButtonsColumn"
] | [((301, 315), 'nautobot.utilities.tables.ToggleColumn', 'ToggleColumn', ([], {}), '()\n', (313, 315), False, 'from nautobot.utilities.tables import BaseTable, ButtonsColumn, ToggleColumn\n'), ((327, 346), 'django_tables2.LinkColumn', 'tables.LinkColumn', ([], {}), '()\n', (344, 346), True, 'import django_tables2 as tab... |
from unittest import TestCase
from datetime import datetime
from ctparse.ctparse import ctparse, _match_rule
from ctparse.types import Time
class TestCTParse(TestCase):
def test_ctparse(self):
txt = '12.12.2020'
res = ctparse(txt)
self.assertEqual(res.resolution, Time(year=2020, month=12,... | [
"datetime.datetime",
"ctparse.ctparse.ctparse",
"ctparse.types.Time",
"ctparse.ctparse._match_rule"
] | [((241, 253), 'ctparse.ctparse.ctparse', 'ctparse', (['txt'], {}), '(txt)\n', (248, 253), False, 'from ctparse.ctparse import ctparse, _match_rule\n'), ((1029, 1057), 'ctparse.ctparse.ctparse', 'ctparse', (['txt'], {'timeout': '(0.0001)'}), '(txt, timeout=0.0001)\n', (1036, 1057), False, 'from ctparse.ctparse import ct... |
from __future__ import absolute_import
from __future__ import print_function
import veriloggen
import thread_mutex_try_lock
expected_verilog = """
module test;
reg CLK;
reg RST;
blinkled
uut
(
.CLK(CLK),
.RST(RST)
);
initial begin
$dumpfile("uut.vcd");
$dumpvars(0, uut);
end
ini... | [
"pyverilog.vparser.parser.VerilogParser",
"veriloggen.reset",
"pyverilog.ast_code_generator.codegen.ASTCodeGenerator",
"thread_mutex_try_lock.mkTest"
] | [((42758, 42776), 'veriloggen.reset', 'veriloggen.reset', ([], {}), '()\n', (42774, 42776), False, 'import veriloggen\n'), ((42795, 42825), 'thread_mutex_try_lock.mkTest', 'thread_mutex_try_lock.mkTest', ([], {}), '()\n', (42823, 42825), False, 'import thread_mutex_try_lock\n'), ((43001, 43016), 'pyverilog.vparser.pars... |
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class Idea(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delet... | [
"django.db.models.DateTimeField",
"django.db.models.TextField",
"django.db.models.CharField",
"django.db.models.ForeignKey"
] | [((148, 180), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)'}), '(max_length=100)\n', (164, 180), False, 'from django.db import models\n'), ((195, 213), 'django.db.models.TextField', 'models.TextField', ([], {}), '()\n', (211, 213), False, 'from django.db import models\n'), ((232, 274), '... |
# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\business\advertising_manager.py
# Compiled at: 2017-04-27 01:01:18
# Size of source mod 2**32: 6129 ... | [
"sims4.log.Logger",
"services.time_service",
"protocolbuffers.Business_pb2.BusinessAdvertisementUpdate",
"distributor.ops.GenericProtocolBufferOp",
"distributor.system.Distributor.instance"
] | [((574, 629), 'sims4.log.Logger', 'sims4.log.Logger', (['"""Business"""'], {'default_owner': '"""jdimailig"""'}), "('Business', default_owner='jdimailig')\n", (590, 629), False, 'import services, sims4\n'), ((3493, 3535), 'protocolbuffers.Business_pb2.BusinessAdvertisementUpdate', 'Business_pb2.BusinessAdvertisementUpd... |
import numpy as np
from mpi4py import MPI
from tacs import TACS, elements, constitutive, functions
from static_analysis_base_test import StaticTestCase
'''
Create a two separate cantilevered plates connected by an RBE3 element.
Apply a load at the RBE2 center node and test KSFailure, StructuralMass,
and Compliance fu... | [
"tacs.functions.Compliance",
"tacs.TACS.Creator",
"tacs.constitutive.IsoShellConstitutive",
"tacs.functions.KSFailure",
"numpy.arange",
"numpy.logical_and",
"tacs.constitutive.MaterialProperties",
"tacs.elements.RBE2",
"numpy.append",
"numpy.array",
"numpy.linspace",
"tacs.elements.ShellNatura... | [((612, 690), 'numpy.array', 'np.array', (['[1.2600980396870352, 51400.0, 3767896.1409673616, 2.912191091671254]'], {}), '([1.2600980396870352, 51400.0, 3767896.1409673616, 2.912191091671254])\n', (620, 690), True, 'import numpy as np\n'), ((863, 925), 'numpy.array', 'np.array', (['[100000000.0, 0.0, 1000000.0, 0.0, 0.... |
# -*- coding: UTF-8 -*-
#
# Copyright 2008-2011, <NAME>, <EMAIL>
#
# This file is part of Pyrit.
#
# Pyrit is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# ... | [
"os.path.exists",
"os.path.join",
"os.makedirs"
] | [((1930, 1964), 'os.path.join', 'os.path.join', (['configpath', '"""config"""'], {}), "(configpath, 'config')\n", (1942, 1964), False, 'import os\n'), ((1969, 2003), 'os.path.exists', 'os.path.exists', (['default_configfile'], {}), '(default_configfile)\n', (1983, 2003), False, 'import os\n'), ((1880, 1907), 'os.path.j... |
import sys
import pylab as plb
import numpy as np
import mountaincar
class DummyAgent():
"""A not so good agent for the mountain-car task.
"""
def __init__(self, mountain_car = None, parameter1 = 3.0):
if mountain_car is None:
self.mountain_car = mountaincar.MountainCar()
... | [
"pylab.ion",
"numpy.random.randint",
"pylab.pause",
"mountaincar.MountainCar",
"sys.stdout.flush",
"mountaincar.MountainCarViewer",
"pylab.show"
] | [((1688, 1698), 'pylab.show', 'plb.show', ([], {}), '()\n', (1696, 1698), True, 'import pylab as plb\n'), ((674, 683), 'pylab.ion', 'plb.ion', ([], {}), '()\n', (681, 683), True, 'import pylab as plb\n'), ((692, 709), 'pylab.pause', 'plb.pause', (['(0.0001)'], {}), '(0.0001)\n', (701, 709), True, 'import pylab as plb\n... |
import numpy as np
from pyquil import Program
from pyquil.api import QuantumComputer, get_qc
from grove.alpha.jordan_gradient.gradient_utils import (binary_float_to_decimal_float,
measurements_to_bf)
from grove.alpha.phaseestimation.phase_estimation import phase_... | [
"grove.alpha.phaseestimation.phase_estimation.phase_estimation",
"grove.alpha.jordan_gradient.gradient_utils.measurements_to_bf",
"numpy.array",
"grove.alpha.jordan_gradient.gradient_utils.binary_float_to_decimal_float",
"numpy.sign"
] | [((744, 792), 'numpy.array', 'np.array', (['[[phase_factor, 0], [0, phase_factor]]'], {}), '([[phase_factor, 0], [0, phase_factor]])\n', (752, 792), True, 'import numpy as np\n'), ((828, 858), 'grove.alpha.phaseestimation.phase_estimation.phase_estimation', 'phase_estimation', (['U', 'precision'], {}), '(U, precision)\... |
from torch import randn
from torch.nn import Conv2d
from backpack import extend
def data_conv2d(device="cpu"):
N, Cin, Hin, Win = 100, 10, 32, 32
Cout, KernelH, KernelW = 25, 5, 5
X = randn(N, Cin, Hin, Win, requires_grad=True, device=device)
module = extend(Conv2d(Cin, Cout, (KernelH, KernelW))).to... | [
"torch.randn",
"torch.nn.Conv2d"
] | [((200, 258), 'torch.randn', 'randn', (['N', 'Cin', 'Hin', 'Win'], {'requires_grad': '(True)', 'device': 'device'}), '(N, Cin, Hin, Win, requires_grad=True, device=device)\n', (205, 258), False, 'from torch import randn\n'), ((429, 470), 'torch.randn', 'randn', (['N', 'Cout', 'Hout', 'Wout'], {'device': 'device'}), '(N... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
Code written by <NAME> with modifications by <NAME> and <NAME>
This file produces plots comparing our first order sensitivity with BS vega.
"""
# %%
# To run the stuff, you need the package plotly in your anaconda "conda install plotly"
import plotly.graph_objs as go
from... | [
"numpy.sqrt",
"plotly.offline.iplot",
"scipy.optimize.minimize",
"plotly.offline.init_notebook_mode",
"numpy.log",
"numpy.exp",
"numpy.array",
"numpy.linspace",
"time.time",
"plotly.graph_objs.Figure",
"numpy.vectorize"
] | [((418, 438), 'plotly.offline.init_notebook_mode', 'init_notebook_mode', ([], {}), '()\n', (436, 438), False, 'from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot\n'), ((2182, 2217), 'numpy.vectorize', 'np.vectorize', (['Robust_Call_Exact_fun'], {}), '(Robust_Call_Exact_fun)\n', (2194, 2217), ... |
import pytest
import pglet
from pglet import Textbox, Stack
@pytest.fixture
def page():
return pglet.page('test_add', no_window=True)
def test_add_single_control(page):
result = page.add(Textbox(id="txt1", label="<NAME>:"))
assert result.id == "txt1", "Test failed"
def test_add_controls_argv(page):
t... | [
"pglet.page",
"pglet.Textbox",
"pglet.Stack"
] | [((100, 138), 'pglet.page', 'pglet.page', (['"""test_add"""'], {'no_window': '(True)'}), "('test_add', no_window=True)\n", (110, 138), False, 'import pglet\n'), ((324, 364), 'pglet.Textbox', 'Textbox', ([], {'id': '"""firstName"""', 'label': '"""<NAME>:"""'}), "(id='firstName', label='<NAME>:')\n", (331, 364), False, '... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import gc
import sys
import random
import unittest
from cllist import sllist
from cllist import sllistnode
from cllist import dllist
from cllist import dllistnode
gc.set_debug(gc.DEBUG_UNCOLLECTABLE | gc.DEBUG_STATS)
if sys.hexversion >= 0x03000000:
# python 3 compat... | [
"unittest.TestSuite",
"cllist.dllistnode",
"cllist.sllistnode",
"random.shuffle",
"gc.set_debug",
"unittest.makeSuite",
"sys.stderr.write",
"cllist.sllist",
"pdb.set_trace",
"cllist.dllist",
"unittest.TextTestRunner"
] | [((210, 263), 'gc.set_debug', 'gc.set_debug', (['(gc.DEBUG_UNCOLLECTABLE | gc.DEBUG_STATS)'], {}), '(gc.DEBUG_UNCOLLECTABLE | gc.DEBUG_STATS)\n', (222, 263), False, 'import gc\n'), ((61660, 61680), 'unittest.TestSuite', 'unittest.TestSuite', ([], {}), '()\n', (61678, 61680), False, 'import unittest\n'), ((837, 845), 'c... |
import trio
from trio._highlevel_open_tcp_stream import close_on_error
from trio.socket import socket, SOCK_STREAM
try:
from trio.socket import AF_UNIX
has_unix = True
except ImportError:
has_unix = False
__all__ = ["open_unix_socket"]
async def open_unix_socket(filename,):
"""Opens a connection to ... | [
"trio.SocketStream",
"trio._highlevel_open_tcp_stream.close_on_error",
"trio.socket.socket"
] | [((1107, 1135), 'trio.socket.socket', 'socket', (['AF_UNIX', 'SOCK_STREAM'], {}), '(AF_UNIX, SOCK_STREAM)\n', (1113, 1135), False, 'from trio.socket import socket, SOCK_STREAM\n'), ((1216, 1239), 'trio.SocketStream', 'trio.SocketStream', (['sock'], {}), '(sock)\n', (1233, 1239), False, 'import trio\n'), ((1145, 1165), ... |
#!/usr/local/bin/python3
# -*- coding: utf-8 -*-
# Встроенные модули
import time, sys, subprocess
from threading import Thread
# Внешние модули
try:
import psycopg2
except ModuleNotFoundError as err:
print(err)
sys.exit(1)
# Внутренние модули
try:
from mod_common import *
except ModuleNotFoundError as err:
... | [
"subprocess.check_output",
"subprocess.call",
"time.sleep",
"sys.exit"
] | [((219, 230), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (227, 230), False, 'import time, sys, subprocess\n'), ((334, 345), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (342, 345), False, 'import time, sys, subprocess\n'), ((6674, 6722), 'subprocess.call', 'subprocess.call', (['"""nft flush ruleset"""'], {'shel... |
from django import forms
from . models import Holdings
class HoldingsForm(forms.ModelForm):
class Meta:
model = Holdings
fields = ['title', 'holding', 'authors', 'category']
widgets={
'title': forms.TextInput(attrs={'class': 'form-control'}),
'holding': forms.FileInp... | [
"django.forms.FileInput",
"django.forms.Select",
"django.forms.CharField",
"django.forms.TextInput"
] | [((580, 611), 'django.forms.CharField', 'forms.CharField', ([], {'max_length': '(250)'}), '(max_length=250)\n', (595, 611), False, 'from django import forms\n'), ((234, 282), 'django.forms.TextInput', 'forms.TextInput', ([], {'attrs': "{'class': 'form-control'}"}), "(attrs={'class': 'form-control'})\n", (249, 282), Fal... |
import cv2
class VideoReader(object):
'''
Class docstring for VideoReader():
Provides a generator for video frames. Returns a numpy array in BGR format.
'''
def __init__(self, file_name):
self.file_name = file_name
try: # OpenCV parses an integer to read a webcam. Supplying '0' wi... | [
"cv2.VideoCapture"
] | [((445, 477), 'cv2.VideoCapture', 'cv2.VideoCapture', (['self.file_name'], {}), '(self.file_name)\n', (461, 477), False, 'import cv2\n'), ((522, 554), 'cv2.VideoCapture', 'cv2.VideoCapture', (['self.file_name'], {}), '(self.file_name)\n', (538, 554), False, 'import cv2\n')] |
import os
import json
from contextlib import suppress
from OrderBook import *
from Signal import Signal
class OrderBookContainer:
def __init__(self, path_to_file):
self.order_books = []
self.trades = []
self.cur_directory = os.path.dirname(path_to_file)
self.f_name = ... | [
"json.loads",
"os.path.join",
"os.path.split",
"os.path.dirname",
"contextlib.suppress",
"os.mkdir",
"json.dump"
] | [((267, 296), 'os.path.dirname', 'os.path.dirname', (['path_to_file'], {}), '(path_to_file)\n', (282, 296), False, 'import os\n'), ((662, 706), 'os.path.join', 'os.path.join', (['self.cur_directory', '"""Datasets"""'], {}), "(self.cur_directory, 'Datasets')\n", (674, 706), False, 'import os\n'), ((320, 347), 'os.path.s... |
'''Functions and classes to wrap existing classes. Provides a wrapper metaclass
and also a function that returns a wrapped class. The function is more flexible
as a metaclass has multiple inheritence limitations.
A wrapper metaclass for building wrapper objects. It is instantiated by
specifying a class to be to be wra... | [
"inspect.isclass",
"functools.wraps"
] | [((1412, 1431), 'functools.wraps', 'functools.wraps', (['fn'], {}), '(fn)\n', (1427, 1431), False, 'import functools\n'), ((6636, 6657), 'inspect.isclass', 'inspect.isclass', (['attr'], {}), '(attr)\n', (6651, 6657), False, 'import inspect\n')] |
import os
from biicode.common.model.brl.block_cell_name import BlockCellName
from biicode.common.model.bii_type import BiiType
def _binary_name(name):
return os.path.splitext(name.replace("/", "_"))[0]
class CPPTarget(object):
def __init__(self):
self.files = set() # The source files in this targe... | [
"biicode.common.model.bii_type.BiiType.isCppHeader"
] | [((2378, 2413), 'biicode.common.model.bii_type.BiiType.isCppHeader', 'BiiType.isCppHeader', (['main.extension'], {}), '(main.extension)\n', (2397, 2413), False, 'from biicode.common.model.bii_type import BiiType\n')] |
'''
This program implements a Fast Neural Style Transfer model.
References:
https://www.tensorflow.org/tutorials/generative/style_transfer
'''
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
import tensorflow_hub as hub
import os, sys
import time
import... | [
"tensorflow.constant",
"time.time",
"tensorflow_hub.load"
] | [((794, 819), 'tensorflow_hub.load', 'hub.load', (['hub_module_path'], {}), '(hub_module_path)\n', (802, 819), True, 'import tensorflow_hub as hub\n'), ((963, 974), 'time.time', 'time.time', ([], {}), '()\n', (972, 974), False, 'import time\n'), ((1130, 1141), 'time.time', 'time.time', ([], {}), '()\n', (1139, 1141), F... |
# -*- coding: utf-8 -*-
# @Author: Anderson
# @Date: 2019-04-25 00:30:09
# @Last Modified by: ander
# @Last Modified time: 2019-12-07 01:14:16
from django.urls import path
from . import views
urlpatterns = [
path("", views.editor, name="editor"),
path("upload_code", views.upload_code, name="upload_code")
... | [
"django.urls.path"
] | [((218, 255), 'django.urls.path', 'path', (['""""""', 'views.editor'], {'name': '"""editor"""'}), "('', views.editor, name='editor')\n", (222, 255), False, 'from django.urls import path\n'), ((261, 319), 'django.urls.path', 'path', (['"""upload_code"""', 'views.upload_code'], {'name': '"""upload_code"""'}), "('upload_c... |
import numpy as np
import torchvision.datasets as datasets
from pathlib import Path
import libs.dirs as dirs
import libs.utils as utils
import libs.dataset_utils as dutils
import models.utils as mutils
import libs.commons as commons
from libs.vis_fun... | [
"numpy.mean",
"libs.dataset_utils.get_input_network_type",
"pathlib.Path",
"numpy.std",
"numpy.argmin",
"models.utils.train_network",
"models.utils.compute_class_acc",
"models.utils.resnet_transforms",
"libs.vis_functions.plot_confusion_matrix"
] | [((556, 625), 'models.utils.resnet_transforms', 'mutils.resnet_transforms', (['commons.IMAGENET_MEAN', 'commons.IMAGENET_STD'], {}), '(commons.IMAGENET_MEAN, commons.IMAGENET_STD)\n', (580, 625), True, 'import models.utils as mutils\n'), ((1045, 1252), 'models.utils.train_network', 'mutils.train_network', (['dataset_pa... |
import cv2 as cv
import sys
import numpy as np
import tifffile as ti
import argparse
import itertools
max_lowThreshold = 100
window_name = 'Edge Map'
title_trackbar = 'Min Threshold:'
ratio = 3
kernel_size = 3
def CannyThreshold(val):
low_threshold = val
#img_blur = cv.blur(src_gray, (3,3))
... | [
"numpy.ones",
"cv2.samples.findFile",
"cv2.medianBlur",
"cv2.imshow",
"numpy.array",
"cv2.cvtColor",
"cv2.Canny",
"cv2.waitKey"
] | [((339, 408), 'cv2.Canny', 'cv.Canny', (['src_gray', 'low_threshold', '(low_threshold * ratio)', 'kernel_size'], {}), '(src_gray, low_threshold, low_threshold * ratio, kernel_size)\n', (347, 408), True, 'import cv2 as cv\n'), ((496, 523), 'cv2.imshow', 'cv.imshow', (['window_name', 'dst'], {}), '(window_name, dst)\n', ... |
# -*- encoding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import re
from addonpayments.utils import GenerationUtils
class TestGenerationUtils:
def test_generate_hash(self):
"""
Test Hash generation success case.
"""
test_string = '20120926112654.thestore... | [
"addonpayments.utils.GenerationUtils",
"re.match",
"addonpayments.utils.GenerationUtils.generate_hash"
] | [((480, 530), 'addonpayments.utils.GenerationUtils.generate_hash', 'GenerationUtils.generate_hash', (['test_string', 'secret'], {}), '(test_string, secret)\n', (509, 530), False, 'from addonpayments.utils import GenerationUtils\n'), ((820, 851), 're.match', 're.match', (['"""([0-9]{14})"""', 'result'], {}), "('([0-9]{1... |
import picamera
from time import sleep
from time import time
import os
import numpy as np
import cv2
import imutils
import argparse
import face_recognition
from camera.check_rectangle_overlap import check_rectangle_overlap
# https://picamera.readthedocs.io/en/release-1.0/api.html
def get_number_faces():
time_now... | [
"cv2.rectangle",
"face_recognition.face_locations",
"picamera.PiCamera",
"time.sleep",
"cv2.HOGDescriptor",
"camera.check_rectangle_overlap.check_rectangle_overlap",
"cv2.destroyAllWindows",
"time.time",
"cv2.HOGDescriptor_getDefaultPeopleDetector",
"cv2.waitKey"
] | [((368, 387), 'picamera.PiCamera', 'picamera.PiCamera', ([], {}), '()\n', (385, 387), False, 'import picamera\n'), ((455, 463), 'time.sleep', 'sleep', (['(3)'], {}), '(3)\n', (460, 463), False, 'from time import sleep\n'), ((625, 644), 'cv2.HOGDescriptor', 'cv2.HOGDescriptor', ([], {}), '()\n', (642, 644), False, 'impo... |
from ._base import BaseWeight
from ..exceptions import NotFittedError
from ..utils.functions import mean_log_beta
import numpy as np
from scipy.special import loggamma
class PitmanYorProcess(BaseWeight):
def __init__(self, pyd=0, alpha=1, truncation_length=-1, rng=None):
super().__init__(rng=rng)
... | [
"scipy.special.loggamma",
"numpy.array",
"numpy.sum",
"numpy.empty",
"numpy.concatenate",
"numpy.cumsum",
"numpy.bincount",
"numpy.arange"
] | [((449, 479), 'numpy.array', 'np.array', (['[]'], {'dtype': 'np.float64'}), '([], dtype=np.float64)\n', (457, 479), True, 'import numpy as np\n'), ((2706, 2757), 'numpy.empty', 'np.empty', (['(self.variational_k, 2)'], {'dtype': 'np.float64'}), '((self.variational_k, 2), dtype=np.float64)\n', (2714, 2757), True, 'impor... |
from __future__ import annotations
from typing import Dict, List, Optional, Union
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from nlp.nlp import Trainer
app = FastAPI()
trainer = Trainer()
#BaseModel is used as data validator when using fast api it cares all about exception handilng and ... | [
"fastapi.FastAPI",
"nlp.nlp.Trainer"
] | [((191, 200), 'fastapi.FastAPI', 'FastAPI', ([], {}), '()\n', (198, 200), False, 'from fastapi import FastAPI, HTTPException\n'), ((211, 220), 'nlp.nlp.Trainer', 'Trainer', ([], {}), '()\n', (218, 220), False, 'from nlp.nlp import Trainer\n')] |
import pandas as pd
import numpy as np
import glob
import os
import global_config
import yaml
import time
import sys
import collections
def flatten(d, parent_key='', sep='_'):
items = []
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
if isinstance(v, collections.Mut... | [
"pandas.DataFrame",
"yaml.safe_load",
"os.chdir",
"glob.glob"
] | [((516, 530), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (528, 530), True, 'import pandas as pd\n'), ((1367, 1419), 'os.chdir', 'os.chdir', (['global_config.EXPERIMENT_SERIALIZATION_DIR'], {}), '(global_config.EXPERIMENT_SERIALIZATION_DIR)\n', (1375, 1419), False, 'import os\n'), ((1443, 1461), 'glob.glob', ... |
###################################################
## ##
## This file is part of the KinBot code v2.0 ##
## ##
## The contents are covered by the terms of the ##
## BSD 3-clause license included in the LICENSE ##
## file,... | [
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"logging.warning",
"numpy.asarray",
"matplotlib.pyplot.clf",
"time.sleep",
"numpy.array",
"numpy.cos",
"numpy.sin"
] | [((1651, 1667), 'numpy.asarray', 'np.asarray', (['cart'], {}), '(cart)\n', (1661, 1667), True, 'import numpy as np\n'), ((6232, 6311), 'logging.warning', 'logging.warning', (["('Hindered rotor potential has more than 2 failures for ' + job)"], {}), "('Hindered rotor potential has more than 2 failures for ' + job)\n", (... |
import re, requests, bs4, unicodedata
from datetime import timedelta, date, datetime
from time import time
# Constants
root = 'https://www.fanfiction.net'
# REGEX MATCHES
# STORY REGEX
_STORYID_REGEX = r"var\s+storyid\s*=\s*(\d+);"
_CHAPTER_REGEX = r"var\s+chapter\s*=\s*(\d+);"
_CHAPTERS_REGEX = r"Chapters:\s*(\d+)\... | [
"re.compile",
"requests.get",
"bs4.BeautifulSoup",
"datetime.datetime.now",
"re.findall",
"datetime.date",
"unicodedata.normalize",
"datetime.datetime.today",
"re.sub",
"datetime.timedelta",
"re.search"
] | [((2058, 2074), 'datetime.date', 'date', (['(1970)', '(1)', '(1)'], {}), '(1970, 1, 1)\n', (2062, 2074), False, 'from datetime import timedelta, date, datetime\n'), ((2553, 2578), 'datetime.timedelta', 'timedelta', ([], {'seconds': 'xutime'}), '(seconds=xutime)\n', (2562, 2578), False, 'from datetime import timedelta, ... |
import torch.utils.data
from torch.utils.tensorboard import SummaryWriter
from torch import nn
from tqdm import tqdm
import numpy as np
from datasets.preprocess import DatasetWrapper
from utils import AverageMeter
class IOC_MLP(torch.nn.Module):
def __init__(self, input_features, out_classes):
super()._... | [
"torch.nn.ELU",
"torch.utils.tensorboard.SummaryWriter",
"torch.nn.CrossEntropyLoss",
"torch.nn.Flatten",
"numpy.exp",
"torch.nn.BatchNorm1d",
"torch.nn.Linear",
"utils.AverageMeter"
] | [((960, 974), 'utils.AverageMeter', 'AverageMeter', ([], {}), '()\n', (972, 974), False, 'from utils import AverageMeter\n'), ((988, 1002), 'utils.AverageMeter', 'AverageMeter', ([], {}), '()\n', (1000, 1002), False, 'from utils import AverageMeter\n'), ((2598, 2612), 'utils.AverageMeter', 'AverageMeter', ([], {}), '()... |
import base64
import re
def base64ToString(base64):
reg = "\\x[a-z0-9][a-z0-9]"
base64.b64decode()
message_bytes = message.encode("ascii")
base64_bytes = base64.b64encode(message_bytes)
base64_message = base64_bytes.decode("ascii")
def shiftASCII(string, n):
r = ""
for i in string:
... | [
"base64.b64encode",
"base64.b64decode"
] | [((90, 108), 'base64.b64decode', 'base64.b64decode', ([], {}), '()\n', (106, 108), False, 'import base64\n'), ((172, 203), 'base64.b64encode', 'base64.b64encode', (['message_bytes'], {}), '(message_bytes)\n', (188, 203), False, 'import base64\n')] |
import time
from math import fabs
import putil.timer
from putil.testing import UtilTest
class TestTimer(UtilTest):
def setUp(self):
self.op1_times = iter([ .01, .02 ])
self.a1 = putil.timer.Accumulator()
self.op2_step1_times = iter([ .005, .015, .005, .005])
self.op2_step2_times ... | [
"time.sleep"
] | [((664, 680), 'time.sleep', 'time.sleep', (['(0.01)'], {}), '(0.01)\n', (674, 680), False, 'import time\n'), ((723, 739), 'time.sleep', 'time.sleep', (['(0.02)'], {}), '(0.02)\n', (733, 739), False, 'import time\n')] |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | [
"google.protobuf.reflection.GeneratedProtocolMessageType",
"google.protobuf.symbol_database.Default",
"google.protobuf.descriptor.FieldDescriptor",
"google.protobuf.descriptor.FileDescriptor"
] | [((1001, 1027), 'google.protobuf.symbol_database.Default', '_symbol_database.Default', ([], {}), '()\n', (1025, 1027), True, 'from google.protobuf import symbol_database as _symbol_database\n'), ((1043, 1744), 'google.protobuf.descriptor.FileDescriptor', '_descriptor.FileDescriptor', ([], {'name': '"""google/api/endpoi... |
from __future__ import unicode_literals, division, absolute_import
import logging
from flexget import plugin
from flexget.event import event
log = logging.getLogger('imdb_required')
class FilterImdbRequired(object):
"""
Rejects entries without imdb_url or imdb_id.
Makes imdb lookup / search if necessary... | [
"logging.getLogger",
"flexget.plugin.register",
"flexget.event.event",
"flexget.plugin.priority",
"flexget.plugin.get_plugin_by_name"
] | [((149, 183), 'logging.getLogger', 'logging.getLogger', (['"""imdb_required"""'], {}), "('imdb_required')\n", (166, 183), False, 'import logging\n'), ((850, 874), 'flexget.event.event', 'event', (['"""plugin.register"""'], {}), "('plugin.register')\n", (855, 874), False, 'from flexget.event import event\n'), ((411, 430... |
"""
This code contains tasks for executing EMIT Level 3 PGEs and helper utilities.
Author: <NAME>, <EMAIL>
"""
import datetime
import logging
import os
import luigi
import spectral.io.envi as envi
from emit_main.workflow.output_targets import AcquisitionTarget
from emit_main.workflow.workflow_manager import Workflo... | [
"logging.getLogger",
"spectral.io.envi.write_envi_header",
"emit_main.workflow.output_targets.AcquisitionTarget",
"emit_main.workflow.l2a_tasks.L2AReflectance",
"os.path.join",
"emit_main.workflow.l2a_tasks.L2AMask",
"os.environ.copy",
"os.path.getmtime",
"datetime.datetime.now",
"spectral.io.envi... | [((508, 538), 'logging.getLogger', 'logging.getLogger', (['"""emit-main"""'], {}), "('emit-main')\n", (525, 538), False, 'import logging\n'), ((701, 718), 'luigi.Parameter', 'luigi.Parameter', ([], {}), '()\n', (716, 718), False, 'import luigi\n'), ((740, 757), 'luigi.Parameter', 'luigi.Parameter', ([], {}), '()\n', (7... |
'''
Code to copy Curry expressions.
'''
from __future__ import absolute_import
from .....common import T_SETGRD, T_FWD
from copy import copy, deepcopy
from ..... import inspect
from . import node
__all__ = ['copygraph', 'copynode', 'GraphCopier', 'Skipper']
class GraphCopier(object):
'''
Deep-copies an expressio... | [
"copy.copy",
"copy.deepcopy"
] | [((599, 619), 'copy.deepcopy', 'deepcopy', (['self', 'memo'], {}), '(self, memo)\n', (607, 619), False, 'from copy import copy, deepcopy\n'), ((2831, 2841), 'copy.copy', 'copy', (['expr'], {}), '(expr)\n', (2835, 2841), False, 'from copy import copy, deepcopy\n'), ((711, 736), 'copy.deepcopy', 'deepcopy', (['self.expr'... |
#
# Visualize the audio of an Elixoids game:
#
# pip3 install websocket-client
# python3 clients/listen.py --host example.com
#
import argparse
import sys
import websocket
try:
import thread
except ImportError:
import _thread as thread
import sound_pb2
def on_message(ws, message):
sound = sound_... | [
"argparse.ArgumentParser",
"sound_pb2.Sound",
"websocket.WebSocketApp",
"sys.stdout.flush",
"sys.stdout.write"
] | [((314, 331), 'sound_pb2.Sound', 'sound_pb2.Sound', ([], {}), '()\n', (329, 331), False, 'import sound_pb2\n'), ((771, 796), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (794, 796), False, 'import argparse\n'), ((1140, 1264), 'websocket.WebSocketApp', 'websocket.WebSocketApp', (['ws_url'], {'... |
import pennylane as qml
import numpy as np
def algo(x, y, z):
qml.RZ(z, wires=[0])
qml.RY(y, wires=[0])
qml.RX(x, wires=[0])
qml.CNOT(wires=[0, 1])
return qml.expval(qml.PauliZ(wires=1))
def run_algo(device, args):
print(args)
circuit = qml.QNode(algo, device)
result = circuit(float(args['X']), float(args['Y'... | [
"pennylane.QNode",
"pennylane.RY",
"pennylane.RZ",
"pennylane.PauliZ",
"pennylane.RX",
"pennylane.CNOT"
] | [((64, 84), 'pennylane.RZ', 'qml.RZ', (['z'], {'wires': '[0]'}), '(z, wires=[0])\n', (70, 84), True, 'import pennylane as qml\n'), ((86, 106), 'pennylane.RY', 'qml.RY', (['y'], {'wires': '[0]'}), '(y, wires=[0])\n', (92, 106), True, 'import pennylane as qml\n'), ((108, 128), 'pennylane.RX', 'qml.RX', (['x'], {'wires': ... |
"""Miscellaneous tools.
"""
import os
import csv
from typing import Union
from subprocess import Popen
from pathlib import Path
from scipy.io import loadmat
import pandas as pd
def open_in_explorer(path : os.PathLike) -> None:
if Path(path).is_dir():
_ = Popen(f'explorer.exe /root,"{path}"')
elif Pat... | [
"pathlib.Path",
"subprocess.Popen",
"csv.writer",
"scipy.io.loadmat",
"pandas.DataFrame",
"pandas.concat"
] | [((3707, 3724), 'scipy.io.loadmat', 'loadmat', (['filename'], {}), '(filename)\n', (3714, 3724), False, 'from scipy.io import loadmat\n'), ((4463, 4492), 'pandas.concat', 'pd.concat', (['dataframes'], {'axis': '(1)'}), '(dataframes, axis=1)\n', (4472, 4492), True, 'import pandas as pd\n'), ((270, 307), 'subprocess.Pope... |
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | [
"paddle.fluid.embedding",
"paddle.fluid.layers.data",
"paddle.fluid.layers.shape",
"paddle.fluid.layers.sequence_mask",
"paddle.fluid.contrib.layers.rnn_impl.BasicLSTMUnit",
"unittest.main",
"paddle.fluid.optimizer.Adam",
"paddle.fluid.layers.transpose",
"paddle.fluid.executor.Executor",
"paddle.f... | [((20147, 20204), 'paddle.fluid.data', 'fluid.data', ([], {'name': '"""src"""', 'shape': '[None, None]', 'dtype': '"""int64"""'}), "(name='src', shape=[None, None], dtype='int64')\n", (20157, 20204), True, 'import paddle.fluid as fluid\n'), ((20225, 20292), 'paddle.fluid.data', 'fluid.data', ([], {'name': '"""src_seque... |
#!/usr/bin/python3
import sys
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter, FileType
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pyfsdb
def parse_args():
parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter,
desc... | [
"argparse.FileType",
"pyfsdb.Fsdb",
"matplotlib.pyplot.savefig",
"argparse.ArgumentParser",
"numpy.array",
"matplotlib.pyplot.subplots"
] | [((226, 339), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'formatter_class': 'ArgumentDefaultsHelpFormatter', 'description': '__doc__', 'epilog': '"""Exmaple Usage: """'}), "(formatter_class=ArgumentDefaultsHelpFormatter, description=\n __doc__, epilog='Exmaple Usage: ')\n", (240, 339), False, 'from argparse ... |
import json
import argparse
def to_output(filepath, outpath):
with open(filepath, encoding='utf-8') as f:
data = json.load(f)
output = []
for d in data:
temp = {}
temp['id'] = d['id']
temp['labels'] = d['pred_labels']
output.append(temp)
with open(outpath, 'w+') ... | [
"json.load",
"json.dump",
"argparse.ArgumentParser"
] | [((396, 488), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Convert model prediction into acceptable format."""'}), "(description=\n 'Convert model prediction into acceptable format.')\n", (419, 488), False, 'import argparse\n'), ((126, 138), 'json.load', 'json.load', (['f'], {}), '(... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 27 13:59:43 2018
@author: ofn77899
"""
import numpy
from ccpi.segmentation.SimpleflexSegmentor import SimpleflexSegmentor
from ccpi.viewer.CILViewer import CILViewer
from ccpi.viewer.CILViewer2D import CILViewer2D, Converter
import vtk
#Text-based input s... | [
"numpy.sqrt",
"vtk.vtkMetaImageReader",
"vtk.vtkTriangle",
"vtk.vtkCamera",
"vtk.vtkCellArray",
"vtk.vtkPolyData",
"numpy.asarray",
"vtk.vtkPoints",
"numpy.dot",
"numpy.cos",
"ccpi.segmentation.SimpleflexSegmentor.SimpleflexSegmentor",
"numpy.sin",
"ccpi.viewer.CILViewer.CILViewer"
] | [((4710, 4734), 'vtk.vtkMetaImageReader', 'vtk.vtkMetaImageReader', ([], {}), '()\n', (4732, 4734), False, 'import vtk\n'), ((4814, 4835), 'ccpi.segmentation.SimpleflexSegmentor.SimpleflexSegmentor', 'SimpleflexSegmentor', ([], {}), '()\n', (4833, 4835), False, 'from ccpi.segmentation.SimpleflexSegmentor import Simplef... |
import json
def read_input():
file = open("Data/day12.json", "r")
return json.load(file)
def calculate_sum(accounts):
if type(accounts) == str:
return 0
elif type(accounts) == int:
return accounts
elif type(accounts) == list:
return sum(calculate_sum(i... | [
"json.load"
] | [((86, 101), 'json.load', 'json.load', (['file'], {}), '(file)\n', (95, 101), False, 'import json\n')] |
from easyvec import Mat2, Vec2
import numpy as np
from pytest import approx
def test_constructor1():
m = Mat2(1,2,3,4)
assert m is not None
assert m.m11 == approx(1)
assert m.m12 == approx(2)
assert m.m21 == approx(3)
assert m.m22 == approx(4)
def test_constructor2():
m = Mat2([1,2,3,4])
... | [
"pytest.approx",
"easyvec.Vec2",
"easyvec.Mat2",
"easyvec.Mat2.eye",
"math.cos",
"numpy.random.uniform",
"easyvec.Mat2.from_angle",
"easyvec.Mat2.from_xaxis",
"math.sin"
] | [((110, 126), 'easyvec.Mat2', 'Mat2', (['(1)', '(2)', '(3)', '(4)'], {}), '(1, 2, 3, 4)\n', (114, 126), False, 'from easyvec import Mat2, Vec2\n'), ((304, 322), 'easyvec.Mat2', 'Mat2', (['[1, 2, 3, 4]'], {}), '([1, 2, 3, 4])\n', (308, 322), False, 'from easyvec import Mat2, Vec2\n'), ((500, 522), 'easyvec.Mat2', 'Mat2'... |
import numpy as np
from two_d_nav.envs.static_maze import StaticMazeNavigation
def test_goal():
env = StaticMazeNavigation()
for i in range(60):
obs, reward, done, _ = env.step(np.array([1.0, -0.1]))
env.render()
for i in range(30):
obs, reward, done, _ = env.step(np.array([-1.0... | [
"two_d_nav.envs.static_maze.StaticMazeNavigation",
"numpy.array"
] | [((109, 131), 'two_d_nav.envs.static_maze.StaticMazeNavigation', 'StaticMazeNavigation', ([], {}), '()\n', (129, 131), False, 'from two_d_nav.envs.static_maze import StaticMazeNavigation\n'), ((917, 939), 'two_d_nav.envs.static_maze.StaticMazeNavigation', 'StaticMazeNavigation', ([], {}), '()\n', (937, 939), False, 'fr... |
import argparse
import git
import github
import os.path
from mesonwrap import gitutils
from mesonwrap import tempfile
from mesonwrap import webapi
from mesonwrap import wrap
from mesonwrap.tools import environment
from retrying import retry
class Importer:
def __init__(self):
self._tmp = None
s... | [
"mesonwrap.tempfile.TemporaryDirectory",
"argparse.ArgumentParser",
"git.Repo.clone_from",
"mesonwrap.gitutils.get_revision",
"mesonwrap.tools.environment.Github",
"mesonwrap.webapi.WebAPI",
"retrying.retry"
] | [((1937, 2006), 'retrying.retry', 'retry', ([], {'stop_max_attempt_number': '(3)', 'retry_on_exception': '_is_github_error'}), '(stop_max_attempt_number=3, retry_on_exception=_is_github_error)\n', (1942, 2006), False, 'from retrying import retry\n'), ((4126, 4155), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ... |
# Generated by Django 3.2.6 on 2021-08-24 09:26
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.TextField",
"django.db.models.ForeignKey",
"django.db.models.BooleanField",
"django.db.models.ImageField",
"django.db.models.BigAutoField",
"django.db.models.DateTimeField",
"django.db.models.CharField"
] | [((337, 433), 'django.db.models.BigAutoField', 'models.BigAutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (356, 433), False, 'from django.db import migrations, m... |
# -*- encoding: utf-8 -*-
"""
License: MIT
Copyright (c) 2019 - present AppSeed.us
"""
from app.home import blueprint
from flask import render_template, redirect, url_for, request, flash, send_file
from flask_login import login_required, current_user
from app import login_manager
from jinja2 import TemplateNotFound
i... | [
"flask.render_template",
"app.base.forms.AddNewIPphasetwo",
"flask.flash",
"backend.dbhelper.DBHelper",
"app.base.forms.AddNewInterface",
"flask.url_for",
"app.base.forms.AddNewIPphaseone",
"app.home.blueprint.route",
"flask.send_file",
"backend.snmphelper.SNMPhelper",
"backend.selfmonitoringhel... | [((557, 567), 'backend.dbhelper.DBHelper', 'DBHelper', ([], {}), '()\n', (565, 567), False, 'from backend.dbhelper import DBHelper\n'), ((579, 591), 'backend.snmphelper.SNMPhelper', 'SNMPhelper', ([], {}), '()\n', (589, 591), False, 'from backend.snmphelper import SNMPhelper\n'), ((601, 617), 'backend.selfmonitoringhel... |
import logging
from botocore.exceptions import ClientError
from aws_cloudformation_power_switch.power_switch import PowerSwitch
from aws_cloudformation_power_switch.tag import logical_id
class RDSClusterPowerSwitch(PowerSwitch):
def __init__(self):
super(RDSClusterPowerSwitch, self).__init__()
s... | [
"aws_cloudformation_power_switch.tag.logical_id",
"logging.info",
"logging.error"
] | [((417, 437), 'aws_cloudformation_power_switch.tag.logical_id', 'logical_id', (['instance'], {}), '(instance)\n', (427, 437), False, 'from aws_cloudformation_power_switch.tag import logical_id\n'), ((494, 544), 'logging.info', 'logging.info', (['"""startup rds cluster %s"""', 'cluster_id'], {}), "('startup rds cluster ... |
# Generated by Django 2.2.1 on 2019-05-09 21:08
from django.conf import settings
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('matchapp', '0003_available_doctors'),
]
operations = [
... | [
"django.db.migrations.RenameModel",
"django.db.migrations.swappable_dependency"
] | [((186, 243), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (217, 243), False, 'from django.db import migrations\n'), ((327, 392), 'django.db.migrations.RenameModel', 'migrations.RenameModel', ([], {'old_name': '"""Use... |
#!/usr/bin/env python
import os, sys, argparse, errno, yaml, time, datetime
import rospy, rospkg
import torch, torchvision, cv2
import numpy as np
from rosky_msgs.msg import WheelsCmdStamped, Twist2DStamped
from img_recognition.msg import Inference
from cv_bridge import CvBridge, CvBridgeError
from jetcam_ros.utils imp... | [
"rospy.Publisher",
"rospy.init_node",
"rospy.wait_for_message",
"rospy.set_param",
"rospy.loginfo",
"rospy.spin",
"rospy.get_name",
"rospy.sleep",
"rospy.Subscriber",
"rospy.on_shutdown"
] | [((3433, 3490), 'rospy.init_node', 'rospy.init_node', (['"""inference_to_reaction"""'], {'anonymous': '(False)'}), "('inference_to_reaction', anonymous=False)\n", (3448, 3490), False, 'import rospy, rospkg\n'), ((3552, 3609), 'rospy.on_shutdown', 'rospy.on_shutdown', (['inference_to_reaction_node.on_shutdown'], {}), '(... |
"""Loads CartPole-v1 demonstrations and trains BC, GAIL, and AIRL models on that data.
"""
import os
import pathlib
import pickle
import tempfile
import seals # noqa: F401
import stable_baselines3 as sb3
from imitation.algorithms import adversarial, bc
from imitation.data import rollout
from imitation.util import ... | [
"tempfile.TemporaryDirectory",
"imitation.util.logger.configure",
"pathlib.Path",
"imitation.algorithms.bc.BC",
"pickle.load",
"os.path.join",
"imitation.data.rollout.flatten_trajectories",
"os.path.dirname",
"imitation.util.util.make_vec_env",
"stable_baselines3.PPO"
] | [((344, 369), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (359, 369), False, 'import os\n'), ((926, 968), 'imitation.data.rollout.flatten_trajectories', 'rollout.flatten_trajectories', (['trajectories'], {}), '(trajectories)\n', (954, 968), False, 'from imitation.data import rollout\n'), (... |
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2017 <NAME> <<EMAIL>>
# Copyright (C) 2014-2017 <NAME> <<EMAIL>>
# Copyright (C) 2014-2017 <NAME> <<EMAIL>>
# Copyright (C) 2014-2017 <NAME> <<EMAIL>>
# Copyright (C) 2014-2017 <NAME> <<EMAIL>>
# This program is free software: you can redistribute it and/or modify
# it under... | [
"tests.factories.UserStoryFactory",
"tests.factories.MembershipFactory",
"django.core.urlresolvers.reverse",
"tests.factories.RelatedUserStory",
"tests.utils.helper_test_http_method",
"taiga.projects.models.Project.objects.all",
"tests.factories.UserFactory.create",
"tests.factories.ProjectFactory",
... | [((1803, 1822), 'tests.utils.reconnect_signals', 'reconnect_signals', ([], {}), '()\n', (1820, 1822), False, 'from tests.utils import helper_test_http_method, reconnect_signals\n'), ((1916, 1938), 'tests.factories.UserFactory.create', 'f.UserFactory.create', ([], {}), '()\n', (1936, 1938), True, 'from tests import fact... |
import os
DB_SERVER = os.getenv('WMT_DB_SERVER', 'localhost')
DB_NAME = os.getenv('WMT_DB_NAME', 'wmt_db')
DB_USERNAME = os.getenv('WMT_DB_USERNAME', 'wmt')
DB_PASSWORD = os.getenv('WMT_DB_PASSWORD', '<PASSWORD>')
| [
"os.getenv"
] | [((23, 62), 'os.getenv', 'os.getenv', (['"""WMT_DB_SERVER"""', '"""localhost"""'], {}), "('WMT_DB_SERVER', 'localhost')\n", (32, 62), False, 'import os\n'), ((73, 107), 'os.getenv', 'os.getenv', (['"""WMT_DB_NAME"""', '"""wmt_db"""'], {}), "('WMT_DB_NAME', 'wmt_db')\n", (82, 107), False, 'import os\n'), ((122, 157), 'o... |
import graphene
import graphql_jwt
import works.schema
import users.schema
import works.schema_relay
import people.schema
class Query(
users.schema.Query,
works.schema.Query,
works.schema_relay.RelayQuery,
people.schema.Query,
graphene.ObjectType,
):
pass
class Mutation(
users.schema.Mut... | [
"graphql_jwt.ObtainJSONWebToken.Field",
"graphene.Schema",
"graphql_jwt.Verify.Field",
"graphql_jwt.Refresh.Field"
] | [((609, 656), 'graphene.Schema', 'graphene.Schema', ([], {'query': 'Query', 'mutation': 'Mutation'}), '(query=Query, mutation=Mutation)\n', (624, 656), False, 'import graphene\n'), ((465, 503), 'graphql_jwt.ObtainJSONWebToken.Field', 'graphql_jwt.ObtainJSONWebToken.Field', ([], {}), '()\n', (501, 503), False, 'import g... |
import pathlib
import configparser
class ConfigManager:
DEFAULT_CONFIG_PATH = "~/.config/notify-sync.ini"
SETTING_NOTIFICATION_ICON = "icon"
SETTING_NOTIFICATION_TIMEOUT = "timeout" # in ms
# SETTING_NOTIFICATION_URGENCY = "urgency" # 0,1,2 low, avg, urgent
SETTING_NOTIFICATION_EXEC = "exec_on... | [
"pathlib.PosixPath",
"configparser.ConfigParser"
] | [((447, 474), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (472, 474), False, 'import configparser\n'), ((491, 526), 'pathlib.PosixPath', 'pathlib.PosixPath', (['self.config_path'], {}), '(self.config_path)\n', (508, 526), False, 'import pathlib\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# -*- mode: Python -*-
#
# (C) <NAME>, 2021
#
import os
import sys
import re
import unicodedata
import unittest
from hypothesis import given, assume, settings, HealthCheck
import hypothesis.strategies as st
# using a try block so that this makes sense if exported to l... | [
"hypothesis.strategies.text",
"sys.exit",
"os.getenv",
"pathlib.Path.home",
"unittest.main",
"hypothesis.settings.register_profile",
"hypothesis.strategies.one_of",
"sys.stderr.write",
"hypothesis.strategies.characters",
"hypothesis.settings",
"unicodedata.normalize",
"hypothesis.given"
] | [((970, 1058), 'hypothesis.settings.register_profile', 'settings.register_profile', (['"""default"""'], {'suppress_health_check': '(HealthCheck.too_slow,)'}), "('default', suppress_health_check=(HealthCheck.\n too_slow,))\n", (995, 1058), False, 'from hypothesis import given, assume, settings, HealthCheck\n'), ((120... |
import os
import numpy as np
import tensorflow as tf
import cPickle
from utils import shared, get_name
from nn import HiddenLayer, EmbeddingLayer, LSTM, forward
class Model(object):
"""
Network architecture.
"""
def __init__(self, parameters=None, models_path=None, model_path=None):
"""
... | [
"tensorflow.shape",
"tensorflow.transpose",
"nn.forward",
"tensorflow.gradients",
"tensorflow.nn.sparse_softmax_cross_entropy_with_logits",
"numpy.array",
"nn.LSTM",
"tensorflow.nn.dropout",
"tensorflow.reverse_sequence",
"tensorflow.nn.softmax",
"tensorflow.reduce_mean",
"tensorflow.scan",
... | [((3248, 3309), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'shape': '[None, None]', 'name': '"""word_ids"""'}), "(tf.int32, shape=[None, None], name='word_ids')\n", (3262, 3309), True, 'import tensorflow as tf\n'), ((3373, 3432), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'shape': '[No... |
import numpy as np
import torch
from torch.utils.data import DataLoader
from torch.utils.data.sampler import RandomSampler
from gnnff.data.keys import Keys
from gnnff.data.split import train_test_split
__all__ = ["get_loader"]
def get_loader(dataset, args, split_path, logging=None):
"""
Parameters
----... | [
"torch.zeros_like",
"torch.utils.data.sampler.RandomSampler",
"gnnff.data.split.train_test_split",
"torch.utils.data.DataLoader"
] | [((1454, 1595), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'data_val', 'batch_size': 'args.batch_size', 'shuffle': '(True)', 'num_workers': '(2)', 'pin_memory': 'args.cuda', 'collate_fn': '_collate_aseatoms'}), '(dataset=data_val, batch_size=args.batch_size, shuffle=True,\n num_workers=2, pin_memo... |
from cms.plugin_base import CMSPluginBase
from cms.models.pluginmodel import CMSPlugin
from cms.plugin_pool import plugin_pool
from fduser import models
from django.utils.translation import ugettext as _
from django.contrib.sites.models import Site
class Users(CMSPluginBase):
model = CMSPlugin # Model where data ... | [
"django.utils.translation.ugettext",
"cms.plugin_pool.plugin_pool.register_plugin",
"django.contrib.sites.models.Site.objects.get_current"
] | [((688, 722), 'cms.plugin_pool.plugin_pool.register_plugin', 'plugin_pool.register_plugin', (['Users'], {}), '(Users)\n', (715, 722), False, 'from cms.plugin_pool import plugin_pool\n'), ((360, 373), 'django.utils.translation.ugettext', '_', (['"""UserList"""'], {}), "('UserList')\n", (361, 373), True, 'from django.uti... |
# pyright: reportUnknownMemberType=false
import logging
import zipfile
from pathlib import Path
from typing import Dict
import requests
from us_pls._config import Config
from us_pls._download.interface import IDownloadService
from us_pls._download.models import DatafileType, DownloadType
from us_pls._logger.interfac... | [
"zipfile.ZipFile",
"requests.get",
"pathlib.Path"
] | [((2394, 2411), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (2406, 2411), False, 'import requests\n'), ((4635, 4649), 'pathlib.Path', 'Path', (['new_name'], {}), '(new_name)\n', (4639, 4649), False, 'from pathlib import Path\n'), ((3535, 3560), 'pathlib.Path', 'Path', (['download_type.value'], {}), '(down... |
#!/usr/bin/env python
from dlbot import default_settings
from flask import Flask
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(default_settings)
app.config.from_pyfile('dlbot.cfg', silent=True)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
... | [
"flask.Flask"
] | [((88, 134), 'flask.Flask', 'Flask', (['__name__'], {'instance_relative_config': '(True)'}), '(__name__, instance_relative_config=True)\n', (93, 134), False, 'from flask import Flask\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
r"""
FIXME:
sometimes you have to chown -R user:user ~/.theano or run with sudo the
first time after roboot, otherwise you get errors
CommandLineHelp:
python -m wbia_cnn --tf netrun <networkmodel>
--dataset, --ds = <dstag>:<subtag>
dstag is the main da... | [
"logging.getLogger",
"wbia_cnn.models.MNISTModel",
"utool.embed",
"wbia_cnn.models.SiameseCenterSurroundModel",
"utool.truepath",
"utool.doctest_funcs",
"utool.invert_dict",
"utool.show_was_requested",
"multiprocessing.freeze_support",
"sys.exit",
"utool.argparse_dict",
"utool.colorprint",
"... | [((1060, 1080), 'utool.inject2', 'ut.inject2', (['__name__'], {}), '(__name__)\n', (1070, 1080), True, 'import utool as ut\n'), ((1090, 1109), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (1107, 1109), False, 'import logging\n'), ((6013, 6053), 'utool.colorprint', 'ut.colorprint', (['"""[netrun] NET RUN"... |
# coding: utf-8
from __future__ import absolute_import
import unittest
import ks_api_client
from ks_api_client.api.super_multiple_order_api import SuperMultipleOrderApi # noqa: E501
from ks_api_client.rest import ApiException
class TestSuperMultipleOrderApi(unittest.TestCase):
"""SuperMultipleOrderApi unit... | [
"unittest.main",
"ks_api_client.api.super_multiple_order_api.SuperMultipleOrderApi"
] | [((1016, 1031), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1029, 1031), False, 'import unittest\n'), ((376, 442), 'ks_api_client.api.super_multiple_order_api.SuperMultipleOrderApi', 'ks_api_client.api.super_multiple_order_api.SuperMultipleOrderApi', ([], {}), '()\n', (440, 442), False, 'import ks_api_client\n... |
import numpy as np
import os
import os.path as path
from keras.applications import vgg16, inception_v3, resnet50, mobilenet
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
import kmri
base_path = path.dirname(path.realpath(__file__))
img_path = path.join(base_path, 'i... | [
"keras.preprocessing.image.img_to_array",
"os.listdir",
"kmri.visualize_model",
"os.path.join",
"os.path.realpath",
"keras.applications.resnet50.ResNet50"
] | [((297, 324), 'os.path.join', 'path.join', (['base_path', '"""img"""'], {}), "(base_path, 'img')\n", (306, 324), True, 'import os.path as path\n'), ((557, 594), 'keras.applications.resnet50.ResNet50', 'resnet50.ResNet50', ([], {'weights': '"""imagenet"""'}), "(weights='imagenet')\n", (574, 594), False, 'from keras.appl... |
import pytest
from secrethitlergame.phase import Phase
from unittest import mock
from secrethitlergame.voting_phase import VotingPhase
def test_initialization():
vp = VotingPhase()
assert isinstance(vp, Phase)
assert vp.chancelor is None
assert vp.president is None
def test_get_previous_government()... | [
"secrethitlergame.voting_phase.VotingPhase",
"unittest.mock.Mock",
"pytest.raises"
] | [((173, 186), 'secrethitlergame.voting_phase.VotingPhase', 'VotingPhase', ([], {}), '()\n', (184, 186), False, 'from secrethitlergame.voting_phase import VotingPhase\n'), ((335, 346), 'unittest.mock.Mock', 'mock.Mock', ([], {}), '()\n', (344, 346), False, 'from unittest import mock\n'), ((402, 415), 'secrethitlergame.v... |
import brownie
def test_set_minter_admin_only(accounts, token):
with brownie.reverts("dev: admin only"):
token.set_minter(accounts[2], {"from": accounts[1]})
def test_set_admin_admin_only(accounts, token):
with brownie.reverts("dev: admin only"):
token.set_admin(accounts[2], {"from": account... | [
"brownie.reverts"
] | [((75, 109), 'brownie.reverts', 'brownie.reverts', (['"""dev: admin only"""'], {}), "('dev: admin only')\n", (90, 109), False, 'import brownie\n'), ((231, 265), 'brownie.reverts', 'brownie.reverts', (['"""dev: admin only"""'], {}), "('dev: admin only')\n", (246, 265), False, 'import brownie\n'), ((385, 440), 'brownie.r... |
import numpy as np
import json
from collections import Counter
import matplotlib.pyplot as plt
DATASET_DIR = './dataset/tacred/train_mod.json'
with open(DATASET_DIR) as f:
examples = json.load(f)
def plot_counts(data):
counts = Counter(data)
del counts["no_relation"]
labels, values = zip(*counts.it... | [
"matplotlib.pyplot.hist",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"collections.Counter",
"numpy.array",
"numpy.argsort",
"matplotlib.pyplot.tight_layout",
"json.load",
"matplotlib.pyplot.show"
] | [((190, 202), 'json.load', 'json.load', (['f'], {}), '(f)\n', (199, 202), False, 'import json\n'), ((240, 253), 'collections.Counter', 'Counter', (['data'], {}), '(data)\n', (247, 253), False, 'from collections import Counter\n'), ((634, 710), 'matplotlib.pyplot.xticks', 'plt.xticks', (['(indexes_sorted + width * 0.5)'... |
import sys
from fractions import Fraction as frac
from math import gcd, floor
from isqrt import isqrt
sys.setrecursionlimit(10**4)
# text=int(open("4.3_ciphertext.hex").read())
e=int(open("4.4_public_key.hex").read(),0)
n=int((open("4.5_modulo.hex").read()),0)
p = 0
q = 0
# print(text,"\n",e,"\n",n)
def ... | [
"sys.setrecursionlimit",
"fractions.Fraction",
"isqrt.isqrt",
"math.floor"
] | [((106, 136), 'sys.setrecursionlimit', 'sys.setrecursionlimit', (['(10 ** 4)'], {}), '(10 ** 4)\n', (127, 136), False, 'import sys\n'), ((392, 410), 'fractions.Fraction', 'frac', (['(e * d - 1)', 'k'], {}), '(e * d - 1, k)\n', (396, 410), True, 'from fractions import Fraction as frac\n'), ((503, 552), 'isqrt.isqrt', 'i... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 19 06:10:55 2018
@author: <NAME>
Demo of gradient boosting tree
A very nice reference for gradient boosting
http://homes.cs.washington.edu/~tqchen/pdf/BoostedTree.pdf
LightGBM
https://github.com/Microsoft/LightGBM/tree/master/examples/python-guide
Catboost
https://gith... | [
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"sklearn.metrics.mean_squared_error",
"lightgbm.Dataset",
"numpy.min",
"sklearn.ensemble.GradientBoostingClassifier",
"lightgbm.plot_importance",
"matplotlib.pyplot.show"
] | [((768, 819), 'pandas.read_csv', 'pd.read_csv', (['"""../Data/winequality-red.csv"""'], {'sep': '""";"""'}), "('../Data/winequality-red.csv', sep=';')\n", (779, 819), True, 'import pandas as pd\n'), ((1008, 1061), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.2)', 'rando... |
import numpy
from scipy.ndimage import gaussian_filter
from skimage.data import binary_blobs
from skimage.util import random_noise
from aydin.it.transforms.fixedpattern import FixedPatternTransform
def add_patterned_noise(image, n):
image = image.copy()
image *= 1 + 0.1 * (numpy.random.rand(n, n) - 0.5)
... | [
"numpy.abs",
"aydin.it.transforms.fixedpattern.FixedPatternTransform",
"numpy.random.rand",
"skimage.data.binary_blobs",
"skimage.util.random_noise",
"scipy.ndimage.gaussian_filter"
] | [((413, 468), 'skimage.util.random_noise', 'random_noise', (['image'], {'mode': '"""gaussian"""', 'var': '(1e-05)', 'seed': '(0)'}), "(image, mode='gaussian', var=1e-05, seed=0)\n", (425, 468), False, 'from skimage.util import random_noise\n'), ((483, 536), 'skimage.util.random_noise', 'random_noise', (['image'], {'mod... |
from os import environ
from pathlib import Path
from appdirs import user_cache_dir
from ._version import version as __version__ # noqa: F401
from .bridge import Transform # noqa: F401
from .core import combine # noqa: F401
from .geodesic import BBox, line, panel, wedge # noqa: F401
from .geometry import get_coast... | [
"appdirs.user_cache_dir",
"geovista_config.update_config"
] | [((828, 850), 'geovista_config.update_config', '_update_config', (['config'], {}), '(config)\n', (842, 850), True, 'from geovista_config import update_config as _update_config\n'), ((978, 1000), 'geovista_config.update_config', '_update_config', (['config'], {}), '(config)\n', (992, 1000), True, 'from geovista_config i... |
from morpion import Morpion
import argparse
if __name__=='__main__':
parser = argparse.ArgumentParser(description="Play Tic-Tac-Toe\n")
parser.add_argument('-mode', '--mode', help='play against Human', default=False)
args = parser.parse_args()
mode = False
if args.mode in ["h", "human", "humain",... | [
"morpion.Morpion",
"argparse.ArgumentParser"
] | [((84, 141), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Play Tic-Tac-Toe\n"""'}), "(description='Play Tic-Tac-Toe\\n')\n", (107, 141), False, 'import argparse\n'), ((372, 391), 'morpion.Morpion', 'Morpion', ([], {'human': 'mode'}), '(human=mode)\n', (379, 391), False, 'from morpion i... |
"""
Mount /sys/fs/cgroup Option
"""
from typing import Callable
import click
def cgroup_mount_option(command: Callable[..., None]) -> Callable[..., None]:
"""
Option for choosing to mount `/sys/fs/cgroup` into the container.
"""
function = click.option(
'--mount-sys-fs-cgroup/--no-mount-sys-... | [
"click.option"
] | [((260, 562), 'click.option', 'click.option', (['"""--mount-sys-fs-cgroup/--no-mount-sys-fs-cgroup"""'], {'default': '(True)', 'show_default': '(True)', 'help': '"""Mounting ``/sys/fs/cgroup`` from the host is required to run applications which require ``cgroup`` isolation. Choose to not mount ``/sys/fs/cgroup`` if it ... |
"""functions that generate reports and figures using the .xml output from the performance tests"""
__all__ = ['TestSuite', 'parse_testsuite_xml']
class TestSuite:
def __init__(self, name, platform, tests):
self.name = name
self.platform = platform
self.tests = tests
def __repr__(self)... | [
"xml.etree.ElementTree.parse",
"pprint.pformat"
] | [((2252, 2270), 'xml.etree.ElementTree.parse', 'ET.parse', (['filename'], {}), '(filename)\n', (2260, 2270), True, 'import xml.etree.ElementTree as ET\n'), ((373, 427), 'pprint.pformat', 'pprint.pformat', (['(self.name, self.platform, self.tests)'], {}), '((self.name, self.platform, self.tests))\n', (387, 427), False, ... |
# coding=utf-8
# Copyright 2018 The TF-Agents Authors.
#
# 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... | [
"tensorflow.keras.initializers.serialize",
"tensorflow.TensorShape",
"tensorflow.keras.initializers.get",
"tensorflow.expand_dims",
"tensorflow.nn.bias_add",
"tensorflow.compat.dimension_value"
] | [((1768, 1811), 'tensorflow.keras.initializers.get', 'tf.keras.initializers.get', (['bias_initializer'], {}), '(bias_initializer)\n', (1793, 1811), True, 'import tensorflow as tf\n'), ((1897, 1924), 'tensorflow.TensorShape', 'tf.TensorShape', (['input_shape'], {}), '(input_shape)\n', (1911, 1924), True, 'import tensorf... |
# __Date__ : 1/5/2020.
# __Author__ : CodePerfectPlus
# __Package__ : Python 3
# __GitHub__ : https://www.github.com/codeperfectplus
#
from Algorithms import LinearRegression
X = [12, 24, 36]
y = [25, 49, 73]
lr = LinearRegression()
lr.fit(X, y)
y_predict = lr.predict(12)
print(y_predict)
| [
"Algorithms.LinearRegression"
] | [((231, 249), 'Algorithms.LinearRegression', 'LinearRegression', ([], {}), '()\n', (247, 249), False, 'from Algorithms import LinearRegression\n')] |
from django.contrib import admin
from di_scoring import models
# copypastad with love from :
# `http://stackoverflow.com/questions/10543032/how-to-show-all-fields-of-model-in-admin-page`
# subclassed modeladmins' list_displays will contain all model fields except
# for id
class CustomModelAdminMixin(object):
def _... | [
"django.contrib.admin.register"
] | [((552, 823), 'django.contrib.admin.register', 'admin.register', (['models.Manager', 'models.School', 'models.TeamChallenge', 'models.Location', 'models.Team', 'models.TC_Field', 'models.TC_Appraiser', 'models.TC_Event', 'models.TC_Score', 'models.IC_Appraiser', 'models.IC_Event', 'models.IC_Score', 'models.TC_Appraise... |
# Originally auto-generated on 2021-02-15-12:14:36 -0500 EST
# By '--verbose --verbose x7.lib.shell_tools'
from unittest import TestCase
from x7.lib.annotations import tests
from x7.testing.support import Capture
from x7.lib import shell_tools
from x7.lib.shell_tools_load import ShellTool
@tests(shell_tools)
class T... | [
"x7.lib.shell_tools.tools",
"x7.lib.shell_tools.help",
"x7.lib.shell_tools.Dir",
"x7.testing.support.Capture",
"x7.lib.annotations.tests",
"x7.lib.shell_tools_load.ShellTool"
] | [((294, 312), 'x7.lib.annotations.tests', 'tests', (['shell_tools'], {}), '(shell_tools)\n', (299, 312), False, 'from x7.lib.annotations import tests\n'), ((425, 447), 'x7.lib.annotations.tests', 'tests', (['shell_tools.Dir'], {}), '(shell_tools.Dir)\n', (430, 447), False, 'from x7.lib.annotations import tests\n'), ((6... |