code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
from setuptools import setup
from Cython.Build import cythonize
from numpy import get_include
setup(
name='vis_precision',
ext_modules=cythonize('vis_precision.pyx'),
include_dirs=[get_include()],
zip_safe=False,
)
setup(
name='dnb_int32',
ext_modules=cythonize('dnb_int32.pyx'),
... | [
"Cython.Build.cythonize",
"numpy.get_include"
] | [((150, 180), 'Cython.Build.cythonize', 'cythonize', (['"""vis_precision.pyx"""'], {}), "('vis_precision.pyx')\n", (159, 180), False, 'from Cython.Build import cythonize\n'), ((291, 317), 'Cython.Build.cythonize', 'cythonize', (['"""dnb_int32.pyx"""'], {}), "('dnb_int32.pyx')\n", (300, 317), False, 'from Cython.Build i... |
import unittest
import copy
from typing import Optional, List, Callable, Tuple
import torch
import torch.nn as nn
import torch.distributed as dist
import torch.multiprocessing as mp
import torch.nn.parallel as parallel
from torch import Tensor
import torchshard as ts
from testing import dist_worker, assertEqual, set... | [
"testing.LinearStackModel",
"torch.nn.CrossEntropyLoss",
"testing.ConvLinearModel",
"torchshard.nn.ParallelLinear.convert_parallel_linear",
"torchshard.distributed.scatter",
"torch.cuda.device_count",
"torch.cuda.is_available",
"unittest.main",
"testing.assertEqual",
"torch.randint",
"testing.se... | [((20645, 20660), 'unittest.main', 'unittest.main', ([], {}), '()\n', (20658, 20660), False, 'import unittest\n'), ((663, 690), 'testing.set_seed', 'set_seed', (['(seed + local_rank)'], {}), '(seed + local_rank)\n', (671, 690), False, 'from testing import dist_worker, assertEqual, set_seed\n'), ((854, 874), 'torch.dist... |
#!/usr/bin/env python
'''
The basic usage of range-separated Gaussian density fitting (RSGDF or simply
RSDF), including choosing an auxiliary basis, initializing 3c integrals, saving
and reading 3c integrals, jk build, ao2mo, etc is the same as that of the
GDF module. Please refer to the following examples for details... | [
"numpy.array",
"pyscf.pbc.scf.KRHF",
"pyscf.pbc.gto.Cell",
"pyscf.pbc.df.RSDF",
"numpy.zeros_like",
"pyscf.pbc.mp.KMP2",
"pyscf.pbc.scf.KRKS"
] | [((807, 817), 'pyscf.pbc.gto.Cell', 'gto.Cell', ([], {}), '()\n', (815, 817), False, 'from pyscf.pbc import gto, scf, cc, df, mp\n'), ((1467, 1486), 'pyscf.pbc.df.RSDF', 'df.RSDF', (['cell', 'kpts'], {}), '(cell, kpts)\n', (1474, 1486), False, 'from pyscf.pbc import gto, scf, cc, df, mp\n'), ((2357, 2387), 'numpy.array... |
from sklearn.utils import shuffle
import numpy as np
from donkeycar.parts.augment import augment_image
from donkeycar.parts.datastore import Tub
from donkeycar.utils import load_scaled_image_arr
import keras
def vae_generator(cfg, data, batch_size, isTrainSet=True, min_records_to_train=1000, aug=False, aux=None, pilot... | [
"donkeycar.templates.train.collate_records",
"numpy.mean",
"argparse.ArgumentParser",
"donkeycar.parts.datastore.Tub.get_angle_throttle",
"sklearn.utils.shuffle",
"donkeycar.parts.augment.augment_image",
"donkeycar.load_config",
"numpy.max",
"keras.utils.to_categorical",
"donkeycar.utils.gather_re... | [((2867, 2987), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Test VAE data loader."""', 'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), "(description='Test VAE data loader.',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n", (2890, 2987), False, 'import ar... |
# -*- coding: utf-8 -*-
from ipaddress import ip_address, IPv4Address
from socket import AF_INET, AF_INET6
def get_ip_address_family(address: str) -> int:
return AF_INET if type(ip_address(address)) is IPv4Address else AF_INET6
def is_ip_address(address: str) -> bool:
try:
ip_address(address)
e... | [
"ipaddress.ip_address"
] | [((295, 314), 'ipaddress.ip_address', 'ip_address', (['address'], {}), '(address)\n', (305, 314), False, 'from ipaddress import ip_address, IPv4Address\n'), ((185, 204), 'ipaddress.ip_address', 'ip_address', (['address'], {}), '(address)\n', (195, 204), False, 'from ipaddress import ip_address, IPv4Address\n')] |
import pytest
import wtforms
from dmutils.forms.fields import DMRadioField
_options = [
{
"label": "Yes",
"value": "yes",
"description": "A positive response."
},
{
"label": "No",
"value": "no",
"description": "A negative response."
}
]
class RadioFor... | [
"pytest.fixture",
"dmutils.forms.fields.DMRadioField"
] | [((436, 472), 'pytest.fixture', 'pytest.fixture', ([], {'params': "['yes', 'no']"}), "(params=['yes', 'no'])\n", (450, 472), False, 'import pytest\n'), ((579, 634), 'pytest.fixture', 'pytest.fixture', ([], {'params': "['true', 'false', 'garbage', '']"}), "(params=['true', 'false', 'garbage', ''])\n", (593, 634), False,... |
from typing import Optional
try:
import neptune
except ImportError:
neptune = None
from minikts.config import config, hparams
from minikts.utils import _flatten_box
from minikts.context import ctx
from minikts.monitoring import report
class NeptuneLogger:
def __init__(self,
api_token: Optional[s... | [
"minikts.utils._flatten_box",
"minikts.context.ctx.switch_workdir",
"neptune.OfflineBackend",
"minikts.monitoring.report",
"minikts.context.ctx.copy_sources",
"neptune.init"
] | [((2323, 2361), 'minikts.context.ctx.copy_sources', 'ctx.copy_sources', ([], {'dest_dir': 'ctx.tmp_dir'}), '(dest_dir=ctx.tmp_dir)\n', (2339, 2361), False, 'from minikts.context import ctx\n'), ((2370, 2401), 'minikts.context.ctx.switch_workdir', 'ctx.switch_workdir', (['ctx.tmp_dir'], {}), '(ctx.tmp_dir)\n', (2388, 24... |
#!/usr/bin/env python
# coding=utf-8
"""
Simple demonstration of TableFormatter with a list of dicts for the table entries.
This approach requires providing the dictionary key to query
for each cell (via attrib='attrib_name').
"""
from tableformatter import generate_table, FancyGrid, SparseGrid, Column
class MyRowObj... | [
"tableformatter.generate_table",
"tableformatter.Column",
"tableformatter.SparseGrid",
"tableformatter.FancyGrid"
] | [((1008, 1035), 'tableformatter.Column', 'Column', (['"""Col1"""'], {'attrib': 'KEY1'}), "('Col1', attrib=KEY1)\n", (1014, 1035), False, 'from tableformatter import generate_table, FancyGrid, SparseGrid, Column\n'), ((1048, 1075), 'tableformatter.Column', 'Column', (['"""Col2"""'], {'attrib': 'KEY2'}), "('Col2', attrib... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 8 08:26:28 2020
@author: arti
"""
import pandas as pd
df = pd.DataFrame({'c1':['a', 'a', 'b', 'a', 'b'],
'c2':[1, 1, 1, 2, 2],
'c3':[1, 1, 2, 2, 2]})
print(df)
print('--')
df2 = df.drop_duplicates()
print(df2... | [
"pandas.DataFrame"
] | [((133, 230), 'pandas.DataFrame', 'pd.DataFrame', (["{'c1': ['a', 'a', 'b', 'a', 'b'], 'c2': [1, 1, 1, 2, 2], 'c3': [1, 1, 2, 2, 2]}"], {}), "({'c1': ['a', 'a', 'b', 'a', 'b'], 'c2': [1, 1, 1, 2, 2], 'c3':\n [1, 1, 2, 2, 2]})\n", (145, 230), True, 'import pandas as pd\n')] |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# zmq_SUB_proc.py
# Author: <NAME>
import zmq
import numpy as np
import time
import matplotlib.pyplot as plt
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.connect("tcp://127.0.0.1:4030") # connect, not bind, the PUB will bind, only 1 can bind
socket.setsoc... | [
"numpy.frombuffer",
"zmq.Context",
"time.sleep"
] | [((165, 178), 'zmq.Context', 'zmq.Context', ([], {}), '()\n', (176, 178), False, 'import zmq\n'), ((742, 786), 'numpy.frombuffer', 'np.frombuffer', (['msg'], {'dtype': 'np.ubyte', 'count': '(-1)'}), '(msg, dtype=np.ubyte, count=-1)\n', (755, 786), True, 'import numpy as np\n'), ((1903, 1918), 'time.sleep', 'time.sleep'... |
"""
Neural Network
by <NAME>
<EMAIL>
"""
import numpy as np
from NeuralNetwork.Activation import fSigmoid as fActivation, dSigmoid as dActivation
from NeuralNetwork.Cost import fQuadratic as fCost, dQuadratic as dCost
class NeuralNetwork:
"""
Class of the neural network which works with backpropagation
"""
de... | [
"numpy.argmax",
"numpy.zeros",
"NeuralNetwork.Activation.dSigmoid",
"numpy.dot",
"numpy.random.seed",
"NeuralNetwork.Cost.fQuadratic",
"NeuralNetwork.Cost.dQuadratic",
"NeuralNetwork.Activation.fSigmoid",
"numpy.random.randn"
] | [((669, 687), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (683, 687), True, 'import numpy as np\n'), ((3084, 3106), 'numpy.zeros', 'np.zeros', (['weight.shape'], {}), '(weight.shape)\n', (3092, 3106), True, 'import numpy as np\n'), ((3149, 3169), 'numpy.zeros', 'np.zeros', (['bias.shape'], {}), '(b... |
# Generated by Django 3.2.5 on 2021-07-24 16:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('gtcrew', '0011_favicon'),
]
operations = [
migrations.AlterField(
model_name='favicon',
name='id',
field... | [
"django.db.models.BigAutoField"
] | [((321, 417), '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", (340, 417), False, 'from django.db import migrations, m... |
#!/usr/bin/env python3
import pkg_resources, platform
print(
'Python',
platform.python_version(),
'LIVR',
pkg_resources.get_distribution("LIVR").version
)
| [
"pkg_resources.get_distribution",
"platform.python_version"
] | [((81, 106), 'platform.python_version', 'platform.python_version', ([], {}), '()\n', (104, 106), False, 'import pkg_resources, platform\n'), ((124, 162), 'pkg_resources.get_distribution', 'pkg_resources.get_distribution', (['"""LIVR"""'], {}), "('LIVR')\n", (154, 162), False, 'import pkg_resources, platform\n')] |
import unittest
import tock
from tock.grammars import *
from tock.syntax import String
class TestGrammar(unittest.TestCase):
def test_init(self):
g = Grammar()
g.set_start_nonterminal('S')
g.add_nonterminal('T')
g.add_rule('S', 'a S b')
g.add_rule('S', 'T')
g.add_rul... | [
"tock.syntax.String"
] | [((459, 470), 'tock.syntax.String', 'String', (['"""S"""'], {}), "('S')\n", (465, 470), False, 'from tock.syntax import String\n'), ((472, 487), 'tock.syntax.String', 'String', (['"""a S b"""'], {}), "('a S b')\n", (478, 487), False, 'from tock.syntax import String\n'), ((531, 542), 'tock.syntax.String', 'String', (['"... |
"""Superficial default settings."""
from matplotlib.cm import get_cmap, register_cmap
from matplotlib.colors import ListedColormap
from numpy import array
#: Default color palette for continuous data.
continuous_palette = "YlGn"
#: Secondary color palette for continuous data.
alternate_palette = "Blues"
#: Default c... | [
"numpy.array",
"matplotlib.cm.get_cmap"
] | [((1100, 1117), 'matplotlib.cm.get_cmap', 'get_cmap', (['"""tab20"""'], {}), "('tab20')\n", (1108, 1117), False, 'from matplotlib.cm import get_cmap, register_cmap\n'), ((2908, 2919), 'numpy.array', 'array', (['axes'], {}), '(axes)\n', (2913, 2919), False, 'from numpy import array\n')] |
# pyuvm uses the Python logging system to do reporting.
# Still, we need this base class to be true to the hierarchy.
# Every instance of a child class has its own logger.
#
# There may be a need to implement uvm_info, uvm_error,
# uvm_warning, and uvm_fatal, but it would be best to
# first see how the native Python lo... | [
"logging.getLogger",
"cocotb.log.SimTimeContextFilter",
"logging.StreamHandler",
"logging.NullHandler"
] | [((1171, 1195), 'logging.getLogger', 'logging.getLogger', (['"""uvm"""'], {}), "('uvm')\n", (1188, 1195), False, 'import logging\n'), ((1584, 1617), 'logging.StreamHandler', 'logging.StreamHandler', (['sys.stdout'], {}), '(sys.stdout)\n', (1605, 1617), False, 'import logging\n'), ((1660, 1682), 'cocotb.log.SimTimeConte... |
#!/usr/bin/python3
'''Routines useful in generation and processing of synthetic data
These are very useful in analyzing the behavior or cameras and lenses.
All functions are exported into the mrcal module. So you can call these via
mrcal.synthetic_data.fff() or mrcal.fff(). The latter is preferred.
'''
import nump... | [
"mrcal.identity_Rt",
"numpy.count_nonzero",
"numpy.array",
"mrcal.ref_calibration_object",
"mrcal.rotate_point_R",
"numpy.arange",
"numpysane.mv",
"mrcal.unproject",
"mrcal.Rt_from_rt",
"numpysane.glue",
"numpysane.cat",
"mrcal.compose_Rt",
"numpy.any",
"mrcal.project",
"numpysane.dummy"... | [((12096, 12205), 'numpy.array', 'np.array', (['((object_width_n - 1) * object_spacing / 2.0, (object_height_n - 1) *\n object_spacing / 2.0, 0)'], {}), '(((object_width_n - 1) * object_spacing / 2.0, (object_height_n - 1\n ) * object_spacing / 2.0, 0))\n', (12104, 12205), True, 'import numpy as np\n'), ((12637, ... |
#! /usr/bin/env python3
import json
import fileinput
import sys
import argparse
import os
import subprocess
import logging
import appdirs
import bsdl_parser.bsdl2json
import pprint
logging.basicConfig()
logging.getLogger().setLevel(logging.INFO)
pp = pprint.PrettyPrinter(indent=4)
parser = argparse.ArgumentPar... | [
"logging.basicConfig",
"logging.getLogger",
"os.linesep.join",
"logging.debug",
"argparse.ArgumentParser",
"appdirs.user_cache_dir",
"subprocess.Popen",
"os.path.splitext",
"os.path.join",
"os.path.isfile",
"os.path.basename",
"pprint.PrettyPrinter",
"os.mkdir",
"json.load",
"logging.inf... | [((186, 207), 'logging.basicConfig', 'logging.basicConfig', ([], {}), '()\n', (205, 207), False, 'import logging\n'), ((258, 288), 'pprint.PrettyPrinter', 'pprint.PrettyPrinter', ([], {'indent': '(4)'}), '(indent=4)\n', (278, 288), False, 'import pprint\n'), ((300, 385), 'argparse.ArgumentParser', 'argparse.ArgumentPar... |
import signal
def install_shutdown_handlers(function, override_sigint=True):
"""Install the given function as a signal handler for all common shutdown
signals (such as SIGINT, SIGTERM, etc). If override_sigint is ``False`` the
SIGINT handler won't be install if there is already a handler in place
(e.g... | [
"signal.getsignal",
"signal.signal"
] | [((340, 379), 'signal.signal', 'signal.signal', (['signal.SIGTERM', 'function'], {}), '(signal.SIGTERM, function)\n', (353, 379), False, 'import signal\n'), ((491, 529), 'signal.signal', 'signal.signal', (['signal.SIGINT', 'function'], {}), '(signal.SIGINT, function)\n', (504, 529), False, 'import signal\n'), ((608, 64... |
"""
Tests for zip archive integrity check
"""
import os
import unittest
from unittest.mock import patch, Mock
from nose.tools import raises
from zipfile import ZipFile
from mtbconverter.mtbconverter import MtbConverter
from mtbconverter.mtbconverter_exceptions import MtbUnknownFileType
from mtbconverter.mtbconverter_e... | [
"os.path.dirname",
"mtbconverter.mtbconverter.MtbConverter",
"unittest.mock.patch",
"nose.tools.raises"
] | [((439, 464), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (454, 464), False, 'import os\n'), ((561, 585), 'unittest.mock.patch', 'patch', (['"""zipfile.ZipFile"""'], {}), "('zipfile.ZipFile')\n", (566, 585), False, 'from unittest.mock import patch, Mock\n'), ((591, 615), 'unittest.mock.pat... |
from catboost import CatBoostClassifier, CatBoostRegressor
from lightgbm import LGBMClassifier, LGBMRegressor
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
from xgboost import XGBClassifier, XGBRegressor
from borutashap... | [
"sklearn.ensemble.RandomForestRegressor",
"sklearn.tree.DecisionTreeRegressor",
"utils.load_data",
"borutashap.BorutaShap",
"sklearn.tree.DecisionTreeClassifier",
"sklearn.ensemble.RandomForestClassifier",
"lightgbm.LGBMClassifier",
"lightgbm.LGBMRegressor",
"catboost.CatBoostRegressor",
"xgboost.... | [((416, 446), 'utils.load_data', 'load_data', ([], {'data_type': 'data_type'}), '(data_type=data_type)\n', (425, 446), False, 'from utils import load_data\n'), ((659, 730), 'borutashap.BorutaShap', 'BorutaShap', ([], {'model': 'value', 'importance_measure': '"""shap"""', 'classification': '(True)'}), "(model=value, imp... |
#!/usr/bin/env python3
import setuptools
with open("README.md", encoding="utf-8") as f:
long_description = f.read()
CLASSIFIERS = """\
Intended Audience :: Developers
Intended Audience :: Science/Research
License :: OSI Approved
License :: OSI Approved :: MIT License
Operating System :: MacOS
Operating System :... | [
"setuptools.find_packages"
] | [((853, 879), 'setuptools.find_packages', 'setuptools.find_packages', ([], {}), '()\n', (877, 879), False, 'import setuptools\n')] |
import os
import stat
from os.path import join, exists, abspath, basename
from os import mkdir
import shutil
import argparse
import time
import json
import logging
import sys
import statistics
from pathlib import Path
import copy
from testing import TestTimeout
from project import Validation, Frontend, Golden, Backend,... | [
"logging.getLogger",
"logging.StreamHandler",
"runtime.Trace.parseLoc",
"runtime.Trace.parseCtxt",
"project.Golden",
"copy.copy",
"transformation.FixInjector",
"project.Frontend",
"transformation.MutateTransformer",
"os.path.exists",
"statistics.save",
"runtime.Load",
"argparse.ArgumentParse... | [((1243, 1270), 'logging.getLogger', 'logging.getLogger', (['"""repair"""'], {}), "('repair')\n", (1260, 1270), False, 'import logging\n'), ((2342, 2370), 'sys.setrecursionlimit', 'sys.setrecursionlimit', (['(10000)'], {}), '(10000)\n', (2363, 2370), False, 'import sys\n'), ((33199, 33233), 'argparse.ArgumentParser', '... |
import matplotlib.pyplot as plt
import charge
import fieldlines
poscharge = charge.Charge(0, [-1,0])
negcharge = charge.Charge(-1, [1,0])
charges = [poscharge, negcharge]
l = fieldlines.Field_lines(charges, max_x=2, max_y=2, num_of_lines=30, step=0.05)
l.plot()
plt.show() | [
"matplotlib.pyplot.show",
"fieldlines.Field_lines",
"charge.Charge"
] | [((78, 103), 'charge.Charge', 'charge.Charge', (['(0)', '[-1, 0]'], {}), '(0, [-1, 0])\n', (91, 103), False, 'import charge\n'), ((115, 140), 'charge.Charge', 'charge.Charge', (['(-1)', '[1, 0]'], {}), '(-1, [1, 0])\n', (128, 140), False, 'import charge\n'), ((187, 264), 'fieldlines.Field_lines', 'fieldlines.Field_line... |
from collections import defaultdict, Counter
from os.path import abspath, dirname, basename
from os import listdir
from xml.sax import make_parser
from xml.sax.handler import ContentHandler
from hashlib import sha1
from datetime import datetime
from subprocess import Popen, PIPE
import traceback
import os
import os.pat... | [
"os.listdir",
"re.compile",
"subprocess.Popen",
"os.path.join",
"re.match",
"os.environ.get",
"xml.sax.make_parser",
"os.path.basename",
"os.path.abspath"
] | [((1121, 1155), 're.compile', 're.compile', (['"""[\\\\]\\\\[\\\\\\\\/@<>^${}]"""'], {}), "('[\\\\]\\\\[\\\\\\\\/@<>^${}]')\n", (1131, 1155), False, 'import re\n'), ((1162, 1187), 're.compile', 're.compile', (['"""[\\\\n\\\\t\\\\r]"""'], {}), "('[\\\\n\\\\t\\\\r]')\n", (1172, 1187), False, 'import re\n'), ((1349, 1389)... |
import re
# Parse the standard output of each target to figure out the elapsed time for an iteration
# For LF targets, the output format is defined by target-specific BenchmarkRunner reactors
# Each of these functions must return a list of floats corresponding to the time in _milliseconds_
def parse_akka_output(lines)... | [
"re.search"
] | [((1523, 1600), 're.search', 're.search', (['"""Iteration (\\\\d+)\\\\t- (\\\\d+) ms\\\\t= (\\\\d+) µs\\\\t= (\\\\d+) ns"""', 'line'], {}), "('Iteration (\\\\d+)\\\\t- (\\\\d+) ms\\\\t= (\\\\d+) µs\\\\t= (\\\\d+) ns', line)\n", (1532, 1600), False, 'import re\n')] |
sc.addPyFile('magichour.zip')
from magichour.api.dist.events.eventEval import event_eval_rdd
from magichour.api.local.util.namedtuples import DistributedLogLine
logLineURI = 'hdfs://namenode/magichour/tbird.500.templateEvalRDD'
rddlogLines = sc.pickleFile(logLineURI)
eventDefURI = 'hdfs://namenode/magichour/tbird.5... | [
"magichour.api.dist.events.eventEval.event_eval_rdd"
] | [((410, 467), 'magichour.api.dist.events.eventEval.event_eval_rdd', 'event_eval_rdd', (['sc', 'rddlogLines', 'eventDefs', 'windowSeconds'], {}), '(sc, rddlogLines, eventDefs, windowSeconds)\n', (424, 467), False, 'from magichour.api.dist.events.eventEval import event_eval_rdd\n')] |
from os.path import join, dirname
from client import app
def fread(fn):
with open(join(dirname(__file__), fn), 'r') as f:
return f.read().decode("utf-8")
app.config["OAUTH_CREDENTIALS"] = {
u"rsa_key": fread("mykey.pem"),
u"signature_method": u"RSA-SHA1",
"signature_type": "body"
}
app.config... | [
"os.path.dirname",
"client.app.run"
] | [((346, 376), 'client.app.run', 'app.run', ([], {'debug': '(True)', 'port': '(5001)'}), '(debug=True, port=5001)\n', (353, 376), False, 'from client import app\n'), ((93, 110), 'os.path.dirname', 'dirname', (['__file__'], {}), '(__file__)\n', (100, 110), False, 'from os.path import join, dirname\n')] |
#Trabalhando com sorted no Pandas
import pandas as pd
import numpy as np
unsorted_df = pd.DataFrame(np.random.randn(10,2),index=[1,4,6,2,3,5,9,8,0,7],columns = ['col2','col1'])
sorted_df=unsorted_df.sort_index()
print (sorted_df) | [
"numpy.random.randn"
] | [((100, 122), 'numpy.random.randn', 'np.random.randn', (['(10)', '(2)'], {}), '(10, 2)\n', (115, 122), True, 'import numpy as np\n')] |
import re
from typing import Any
from bs4 import BeautifulSoup
from bs4.element import ResultSet
from kttool.base import Action
from reprint import output
import time
from kttool.logger import color_cyan, color_green, color_red, log_green, log_red
import emoji, requests
AC_ICON = ':heavy_check_mark:'
RJ_ICON = ':heavy... | [
"kttool.logger.color_cyan",
"kttool.logger.color_red",
"kttool.logger.log_green",
"reprint.output",
"time.strftime",
"kttool.logger.color_green",
"time.sleep",
"bs4.BeautifulSoup",
"kttool.logger.log_red",
"re.search"
] | [((6176, 6210), 'kttool.logger.log_green', 'log_green', (['"""Submission successful"""'], {}), "('Submission successful')\n", (6185, 6210), False, 'from kttool.logger import color_cyan, color_green, color_red, log_green, log_red\n'), ((3584, 3610), 'reprint.output', 'output', ([], {'output_type': '"""dict"""'}), "(outp... |
import os
import sys
import argparse
import tensorflow as tf
import numpy as np
from PIL import Image
from reader import Reader
from source.anchor_filter import AnchorFilter
import logging
import random
import time
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
class VS3D(object):
def __init__(self, k... | [
"tensorflow.shape",
"tensorflow.get_collection_ref",
"tensorflow.boolean_mask",
"tensorflow.reduce_sum",
"tensorflow.split",
"numpy.array",
"tensorflow.control_dependencies",
"numpy.sin",
"tensorflow.cast",
"tensorflow.clip_by_global_norm",
"numpy.save",
"os.path.exists",
"numpy.mean",
"ar... | [((215, 273), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'stream': 'sys.stdout'}), '(level=logging.INFO, stream=sys.stdout)\n', (234, 273), False, 'import logging\n'), ((23911, 23936), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (23934, 23936), False, 'impor... |
'''
(*)~---------------------------------------------------------------------------
Pupil - eye tracking platform
Copyright (C) 2012-2017 Pupil Labs
Distributed under the terms of the GNU
Lesser General Public License (LGPL v3.0).
See COPYING and COPYING.LESSER for license details.
-----------------------------------... | [
"csv.writer",
"csv.reader",
"csv.Sniffer",
"os.remove"
] | [((872, 900), 'csv.reader', 'csv.reader', (['csvfile', 'dialect'], {}), '(csvfile, dialect)\n', (882, 900), False, 'import csv\n'), ((1364, 1398), 'csv.writer', 'csv.writer', (['csvfile'], {'delimiter': '""","""'}), "(csvfile, delimiter=',')\n", (1374, 1398), False, 'import csv\n'), ((2591, 2610), 'os.remove', 'os.remo... |
from . import db
from datetime import datetime
from werkzeug.security import check_password_hash
class User(db.Model):
__tablename__ = 'users'
__table_args__ = {'extend_existing': True}
id = db.Column(db.Integer, primary_key=True, index=True) # 编号
name = db.Column(db.String(20), unique=True, index=Tr... | [
"datetime.datetime.utcnow",
"werkzeug.security.check_password_hash"
] | [((1017, 1051), 'werkzeug.security.check_password_hash', 'check_password_hash', (['self.pwd', 'pwd'], {}), '(self.pwd, pwd)\n', (1036, 1051), False, 'from werkzeug.security import check_password_hash\n'), ((622, 639), 'datetime.datetime.utcnow', 'datetime.utcnow', ([], {}), '()\n', (637, 639), False, 'from datetime imp... |
import torch
import torch.nn as nn
from mmcv.runner import ModuleList
from mmdet.core import (bbox2result, bbox2roi, bbox_mapping, build_assigner,
build_sampler, merge_aug_bboxes, merge_aug_masks,
multiclass_nms)
from ..builder import HEADS, build_head, build_roi_extract... | [
"mmdet.core.build_assigner",
"mmdet.core.merge_aug_bboxes",
"torch.nn.ModuleList",
"mmdet.core.bbox_mapping",
"mmdet.core.bbox2roi",
"mmdet.core.bbox2result",
"torch.nonzero",
"mmdet.core.merge_aug_masks",
"mmdet.core.multiclass_nms",
"torch.zeros",
"mmdet.core.build_sampler",
"torch.no_grad",... | [((2064, 2076), 'mmcv.runner.ModuleList', 'ModuleList', ([], {}), '()\n', (2074, 2076), False, 'from mmcv.runner import ModuleList\n'), ((2102, 2114), 'mmcv.runner.ModuleList', 'ModuleList', ([], {}), '()\n', (2112, 2114), False, 'from mmcv.runner import ModuleList\n'), ((2145, 2157), 'mmcv.runner.ModuleList', 'ModuleL... |
#!/usr/bin/env python
# Lib:
import numpy as np
import pylab
def mandelbrot(h, w, maxit=100):
'''Returns an image of the Mandelbrot fractal of size (h,w).
'''
y, x = np.ogrid[-2:2:h*1j, -3:1:w*1j]
c = x+y*1j
z = c
divtime = maxit + np.zeros(z.shape, dtype=int)
... | [
"numpy.conj",
"numpy.zeros"
] | [((282, 310), 'numpy.zeros', 'np.zeros', (['z.shape'], {'dtype': 'int'}), '(z.shape, dtype=int)\n', (290, 310), True, 'import numpy as np\n'), ((402, 412), 'numpy.conj', 'np.conj', (['z'], {}), '(z)\n', (409, 412), True, 'import numpy as np\n')] |
#!/usr/bin/env python
import numpy as np
import pandas as pd
import copy
from ctypes import *
from ..exrpc.rpclib import *
from ..exrpc.server import *
from ..matrix.dtype import *
from .frovedisColumn import *
from . import df
class FrovedisGroupedDataframe :
'''A python container for holding Frovedis side creat... | [
"numpy.asarray",
"copy.deepcopy"
] | [((590, 609), 'copy.deepcopy', 'copy.deepcopy', (['cols'], {}), '(cols)\n', (603, 609), False, 'import copy\n'), ((628, 648), 'copy.deepcopy', 'copy.deepcopy', (['types'], {}), '(types)\n', (641, 648), False, 'import copy\n'), ((668, 689), 'copy.deepcopy', 'copy.deepcopy', (['p_cols'], {}), '(p_cols)\n', (681, 689), Fa... |
from django.db import models
from rest_framework import mixins
from rest_framework import status
from rest_framework.decorators import action, api_view
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from .models import *
from .serializers import *
__all__ = ('Component... | [
"rest_framework.response.Response",
"rest_framework.decorators.action",
"django.db.models.Sum"
] | [((1560, 1582), 'rest_framework.decorators.action', 'action', (["['get']", '(False)'], {}), "(['get'], False)\n", (1566, 1582), False, 'from rest_framework.decorators import action, api_view\n'), ((2244, 2286), 'rest_framework.decorators.action', 'action', (["['post']", '(False)'], {'url_path': '"""by_raw"""'}), "(['po... |
# ----------------------------------------------------------------------
# managedobjectprofile cpe_profile
# ----------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------... | [
"django.db.models.ForeignKey"
] | [((839, 962), 'django.db.models.ForeignKey', 'models.ForeignKey', (['ManagedObjectProfile'], {'verbose_name': '"""Object Profile"""', 'blank': '(True)', 'null': '(True)', 'on_delete': 'models.CASCADE'}), "(ManagedObjectProfile, verbose_name='Object Profile',\n blank=True, null=True, on_delete=models.CASCADE)\n", (85... |
"""ETL code for the addon_aggregates dataset"""
from pyspark.sql import SparkSession
import pyspark.sql.functions as fun
import click
MS_FIELDS = [
"client_id",
"normalized_channel",
"app_version",
"locale",
"sample_id",
"profile_creation_date",
]
ADDON_FIELDS = [
"addons.addon_id",
"... | [
"click.option",
"pyspark.sql.functions.explode",
"pyspark.sql.functions.substring",
"pyspark.sql.functions.col",
"pyspark.sql.functions.sum",
"pyspark.sql.functions.min",
"pyspark.sql.SparkSession.builder.appName",
"click.command",
"pyspark.sql.functions.when"
] | [((5174, 5189), 'click.command', 'click.command', ([], {}), '()\n', (5187, 5189), False, 'import click\n'), ((5191, 5228), 'click.option', 'click.option', (['"""--date"""'], {'required': '(True)'}), "('--date', required=True)\n", (5203, 5228), False, 'import click\n'), ((5230, 5289), 'click.option', 'click.option', (['... |
import numpy as np
import unittest
import pytest
from mvc.misc.batch import make_batch
class MakeBatchTest(unittest.TestCase):
def test_success(self):
batch_size = np.random.randint(32) + 1
data_size = batch_size * np.random.randint(10) + 1
data = {
'test1': np.random.random((... | [
"numpy.random.random",
"numpy.random.randint",
"pytest.raises",
"mvc.misc.batch.make_batch"
] | [((433, 472), 'mvc.misc.batch.make_batch', 'make_batch', (['data', 'batch_size', 'data_size'], {}), '(data, batch_size, data_size)\n', (443, 472), False, 'from mvc.misc.batch import make_batch\n'), ((179, 200), 'numpy.random.randint', 'np.random.randint', (['(32)'], {}), '(32)\n', (196, 200), True, 'import numpy as np\... |
# -*- coding: utf-8 -*-
from __future__ import print_function, division, unicode_literals
from __future__ import absolute_import
import numpy as np, time, sys, smbus
# default addresses and ChipIDs of Bosch BMP 085/180 and BMP/E 280 sensors
BMP_I2CADDR = 0x77
BMP_I2CADDR2 = 0x76
#BMP_I2CADDR = 0x76 # alternative dev... | [
"smbus.SMBus",
"sys.exit",
"time.sleep",
"ctypes.c_short"
] | [((7375, 7392), 'time.sleep', 'time.sleep', (['(0.005)'], {}), '(0.005)\n', (7385, 7392), False, 'import numpy as np, time, sys, smbus\n'), ((16463, 16508), 'ctypes.c_short', 'c_short', (['((data[index + 1] << 8) + data[index])'], {}), '((data[index + 1] << 8) + data[index])\n', (16470, 16508), False, 'from ctypes impo... |
"""
Test of the Turbidity meter using an ADC
# The Turbidity sensor mapped from 0 to 1023 (0 - 5 volts)
# ADC maps values -32768 to 32767, GND is 0 (-5 - 5 v)
# Voltage conversion is volts = (reading / 32767) * 5
# This may need some calibration adjustment
"""
# Import the ADS1x15 module.
from ADS1115 import ADS1115
... | [
"ADS1115.ADS1115"
] | [((392, 401), 'ADS1115.ADS1115', 'ADS1115', ([], {}), '()\n', (399, 401), False, 'from ADS1115 import ADS1115\n')] |
from datetime import datetime
from django.http.response import JsonResponse
from pydantic import BaseModel
import djhug
from djhug.content_negotiation import json_renderer
routes = djhug.Routes()
@routes.get("^$", re=True)
def index(request, year: float, name: str, rr: int = 2):
loc = locals()
del loc["req... | [
"djhug.response.renderer",
"djhug.Routes"
] | [((184, 198), 'djhug.Routes', 'djhug.Routes', ([], {}), '()\n', (196, 198), False, 'import djhug\n'), ((628, 666), 'djhug.response.renderer', 'djhug.response.renderer', (['json_renderer'], {}), '(json_renderer)\n', (651, 666), False, 'import djhug\n')] |
import json
import pytest
from lxml import etree
import numpy as np
import xarray as xr
import pandas as pd
import finch
import finch.processes
from finch.processes.wps_xclim_indices import XclimIndicatorBase
from finch.processes.wps_base import make_xclim_indicator_process
from . utils import execute_process, wps_inp... | [
"finch.processes.wps_base.make_xclim_indicator_process",
"xclim.testing.open_dataset",
"numpy.ones",
"pathlib.Path",
"numpy.arange",
"numpy.testing.assert_allclose",
"json.dumps",
"pytest.mark.parametrize",
"finch.processes.get_processes",
"numpy.array",
"pytest.raises",
"finch.processes.xclim... | [((824, 888), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""indicator"""', 'finch.processes.indicators'], {}), "('indicator', finch.processes.indicators)\n", (847, 888), False, 'import pytest\n'), ((702, 733), 'finch.processes.get_processes', 'finch.processes.get_processes', ([], {}), '()\n', (731, 733), ... |
"""Websocket example"""
from time import sleep
from eodhistoricaldata import WebSocketClient
def main() -> None:
"""Main"""
websocket = WebSocketClient(
# Demo API key for testing purposes
api_key="<KEY>", endpoint="crypto", symbols=["BTC-USD"]
#api_key="<KEY>", endpoint="forex", symb... | [
"eodhistoricaldata.WebSocketClient",
"time.sleep"
] | [((147, 219), 'eodhistoricaldata.WebSocketClient', 'WebSocketClient', ([], {'api_key': '"""<KEY>"""', 'endpoint': '"""crypto"""', 'symbols': "['BTC-USD']"}), "(api_key='<KEY>', endpoint='crypto', symbols=['BTC-USD'])\n", (162, 219), False, 'from eodhistoricaldata import WebSocketClient\n'), ((684, 695), 'time.sleep', '... |
from multiprocessing import Pool
from bokeh.io import export_png
from bokeh.plotting import figure, show, output_file
from bokeh.palettes import Category10 as palette
import itertools
# import matplotlib.pyplot as plt
import numpy as np
import tqdm
# from progress.bar import Bar
from network_simulator.components import... | [
"itertools.cycle",
"network_simulator.helpers.readSimCache",
"bokeh.plotting.figure",
"bokeh.plotting.show",
"numpy.arange",
"network_simulator.helpers.genDescendUnitArray",
"multiprocessing.Pool",
"network_simulator.helpers.writeSimCache",
"network_simulator.components.simulator",
"bokeh.plotting... | [((442, 485), 'network_simulator.components.simulator', 'simulator', (['g_init_vars', 'g_aplist', 'g_usrlist'], {}), '(g_init_vars, g_aplist, g_usrlist)\n', (451, 485), False, 'from network_simulator.components import simulator\n'), ((701, 728), 'numpy.arange', 'np.arange', (['(0.01)', '(0.99)', '(0.01)'], {}), '(0.01,... |
import math
import pytest
from .anomaly_computation import compute_eccentric_anomaly
@pytest.mark.parametrize(
"mean_anomaly,eccentricity,expected",
[
(0, 0, 0),
(math.pi / 3, 0, math.pi / 3),
(0, 0.5, 0),
(math.pi / 3, 0.5, math.pi / 2.0306),
],
)
def test_eccentric_anom... | [
"pytest.approx",
"pytest.mark.parametrize"
] | [((90, 255), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""mean_anomaly,eccentricity,expected"""', '[(0, 0, 0), (math.pi / 3, 0, math.pi / 3), (0, 0.5, 0), (math.pi / 3, 0.5, \n math.pi / 2.0306)]'], {}), "('mean_anomaly,eccentricity,expected', [(0, 0, 0), (\n math.pi / 3, 0, math.pi / 3), (0, 0.5, ... |
import numpy as np
from produce_lightcurve import Lightcurve
import synphot as sp
import dorado.sensitivity
import astropy.units as u
from astropy import constants as c
import dill as pickle
import os
from dynesty_sampler import getSampler, wrappedSampler, find
from parameters import getParameters
# get parameters
pa... | [
"os.path.exists",
"parameters.getParameters",
"dynesty_sampler.getSampler",
"dynesty_sampler.wrappedSampler",
"numpy.log",
"dynesty_sampler.find",
"numpy.array",
"dill.dump",
"numpy.ndarray",
"os.mkdir",
"synphot.SpectralElement.from_file",
"produce_lightcurve.Lightcurve",
"matplotlib.pyplot... | [((331, 552), 'parameters.getParameters', 'getParameters', ([], {'osargs_list': "['read_data', 'model', 'delay', 'dist', 'include_optical', 'include_uv',\n 'print_progress', 'method', 'resume_previous', 'sample',\n 'save_after_seconds', 'parallel', 'dlogz_threshold']"}), "(osargs_list=['read_data', 'model', 'dela... |
#-*- coding: utf-8 -*-
"""
xml config handling
"""
#202007 kojh create
try:
import xml.etree.cElementTree as ET
except ImportError:
print ("ImportError")
import xml.etree.ElementTree as ET
import os
from pexpect import pxssh
from module_core import lmt_exception
from module_core import lmt_util
from tsp... | [
"module_core.lmt_exception.LmtException",
"xml.etree.ElementTree.parse",
"os.path.dirname",
"tspec_cmd_impl.lmt_remote.get_remote_file",
"module_core.lmt_util.replace_all_symbols",
"os.path.basename",
"tspec_cmd_impl.lmt_remote.backup_remote_file"
] | [((1358, 1490), 'tspec_cmd_impl.lmt_remote.get_remote_file', 'lmt_remote.get_remote_file', (['runner_ctx', 'runner_ctx.ems_ip', 'runner_ctx.ems_id', 'runner_ctx.ems_passwd', 'runner_ctx.ems_xml_cfg_path'], {}), '(runner_ctx, runner_ctx.ems_ip, runner_ctx.ems_id,\n runner_ctx.ems_passwd, runner_ctx.ems_xml_cfg_path)\... |
import numpy as np
import matplotlib.pyplot as plt
from tools import get_array, dags
data = dags[0]
find_or_add_index = get_array(data, "find_or_add index")
find_or_add_add = get_array(data, "find_or_add add")
find_or_add_level = get_array(data, "find_or_add level")
plt.xlabel("index")
plt.ylabel("num")
indices_add... | [
"tools.get_array",
"numpy.logical_and",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"numpy.max",
"numpy.sum",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show"
] | [((122, 158), 'tools.get_array', 'get_array', (['data', '"""find_or_add index"""'], {}), "(data, 'find_or_add index')\n", (131, 158), False, 'from tools import get_array, dags\n'), ((177, 211), 'tools.get_array', 'get_array', (['data', '"""find_or_add add"""'], {}), "(data, 'find_or_add add')\n", (186, 211), False, 'fr... |
from HDPython.ast.ast_classes.ast_base import v_ast_base, add_class,gIndent
from HDPython.ast.ast_classes.ast_type_to_bool import v_type_to_bool
class v_if(v_ast_base):
def __init__(self,ifEsleIfElse, test, body,oreEsle):
self.ifEsleIfElse = ifEsleIfElse
self.test=test
self.body = body
... | [
"HDPython.ast.ast_classes.ast_base.gIndent.deinc",
"HDPython.ast.ast_classes.ast_base.gIndent.inc",
"HDPython.ast.ast_classes.ast_base.add_class"
] | [((1966, 1990), 'HDPython.ast.ast_classes.ast_base.add_class', 'add_class', (['"""If"""', 'body_if'], {}), "('If', body_if)\n", (1975, 1990), False, 'from HDPython.ast.ast_classes.ast_base import v_ast_base, add_class, gIndent\n'), ((1382, 1397), 'HDPython.ast.ast_classes.ast_base.gIndent.deinc', 'gIndent.deinc', ([], ... |
from .matrix import Matrix
from . import constant
import numpy as np
from typing import List
class Key(Matrix):
def __init__(self, array: np.ndarray) -> None:
self._state = super().__init__(array)
def a_key_schedule(round_key: Key, round: int) -> Key:
""" Generate new Roundkey from old one"""
ne... | [
"numpy.empty"
] | [((334, 365), 'numpy.empty', 'np.empty', (['[4, 4]'], {'dtype': '"""uint8"""'}), "([4, 4], dtype='uint8')\n", (342, 365), True, 'import numpy as np\n')] |
import sqlite3
conn = sqlite3.connect('scores_file.txt') | [
"sqlite3.connect"
] | [((22, 56), 'sqlite3.connect', 'sqlite3.connect', (['"""scores_file.txt"""'], {}), "('scores_file.txt')\n", (37, 56), False, 'import sqlite3\n')] |
import pycristoforo.utils.utils as utils_py
import pycristoforo.geo.key_value_pair as keyvaluepair_py
class CountryList:
def __init__(self, full_path):
"""
Constructor method that builds the country dictionary with 'key','value' pair
:param full_path: path where the geojson is stored
... | [
"pycristoforo.utils.utils.read_json"
] | [((402, 431), 'pycristoforo.utils.utils.read_json', 'utils_py.read_json', (['full_path'], {}), '(full_path)\n', (420, 431), True, 'import pycristoforo.utils.utils as utils_py\n')] |
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
MONGO_URI = "mongodb://localhost:27017/game-joy"
MONGO_DBNAME = "game_joy"
SECRET_KEY = 'f1a3k'
MAIL_SERVER = 'smtp.googlemail.com'
MAIL_USERNAME = "<EMAIL>"
MAIL_PASSWORD = "<PASSWORD>"
DB_SERVER_URI = ""
cl... | [
"os.path.dirname"
] | [((37, 62), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (52, 62), False, 'import os\n')] |
from random import randint
from random import seed
from time import sleep
#importanto as funções das bibliotecas.
cadastro = []
seed(100)
print('-' * 20, 'MENU', '-' * 20)
print('1 - Nova inscrição ')
print('2 - Vizualizar inscrição ')
print('0 - Encerrar ')
while True:
pessoa = {}
# Garantindo que a opção di... | [
"time.sleep",
"random.randint",
"random.seed"
] | [((129, 138), 'random.seed', 'seed', (['(100)'], {}), '(100)\n', (133, 138), False, 'from random import seed\n'), ((843, 860), 'random.randint', 'randint', (['(100)', '(400)'], {}), '(100, 400)\n', (850, 860), False, 'from random import randint\n'), ((2323, 2331), 'time.sleep', 'sleep', (['(1)'], {}), '(1)\n', (2328, 2... |
#!/usr/bin/python
"""
Copyright (c) 2015 <NAME>, licensed under the MIT License.
(See accompanying LICENSE file for details.)
The parts of Taurus which interact with the filesystem and are shared between
the sender and listener: logging and conversation records.
"""
import os
import fcntl
import time
import logging
... | [
"logging.basicConfig",
"logging.getLogger",
"os.listdir",
"fcntl.flock",
"time.strftime",
"os.path.join",
"os.path.isdir",
"os.path.expanduser"
] | [((367, 398), 'os.path.expanduser', 'os.path.expanduser', (['"""~/.taurus"""'], {}), "('~/.taurus')\n", (385, 398), False, 'import os\n'), ((406, 431), 'os.path.isdir', 'os.path.isdir', (['TAURUS_DIR'], {}), '(TAURUS_DIR)\n', (419, 431), False, 'import os\n'), ((541, 577), 'os.path.join', 'os.path.join', (['TAURUS_DIR'... |
import math
import random
from functools import partial
from typing import Callable, Optional, Tuple
import flax.linen as nn
import jax
import jax.numpy as jnp
from flax.core.frozen_dict import FrozenDict, unfreeze
from flax.linen import combine_masks, make_causal_mask
from flax.linen.attention import dot_product_atte... | [
"jax.numpy.zeros",
"jax.random.PRNGKey",
"jax.numpy.where",
"flax.core.frozen_dict.unfreeze",
"jax.numpy.atleast_2d",
"jax.ops.index_update",
"jax.numpy.arange",
"jax.numpy.array",
"jax.numpy.ones_like",
"jax.numpy.ones",
"jax.numpy.roll",
"jax.random.split"
] | [((723, 754), 'jax.numpy.roll', 'jnp.roll', (['input_ids', '(1)'], {'axis': '(-1)'}), '(input_ids, 1, axis=-1)\n', (731, 754), True, 'import jax.numpy as jnp\n'), ((779, 852), 'jax.ops.index_update', 'jax.ops.index_update', (['shifted_input_ids', '(..., 0)', 'decoder_start_token_id'], {}), '(shifted_input_ids, (..., 0)... |
import time
import os
from torch.autograd import Variable
import torch
import numpy
import networks
import shutil
import warnings
warnings.filterwarnings("ignore", category=UserWarning)
torch.backends.cudnn.benchmark = True
with open('process_info.txt', 'r') as file:
process_info = file.read()
process_info = ... | [
"torch.unsqueeze",
"torch.load",
"torch.stack",
"os.chdir",
"torch.nn.ReplicationPad2d",
"torch.set_grad_enabled",
"numpy.transpose",
"time.time",
"warnings.filterwarnings",
"numpy.round",
"numpy.load"
] | [((131, 186), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'UserWarning'}), "('ignore', category=UserWarning)\n", (154, 186), False, 'import warnings\n'), ((339, 376), 'os.chdir', 'os.chdir', (["process_info['dain_folder']"], {}), "(process_info['dain_folder'])\n", (347, 376), F... |
""" Problem 2:
Find the sum of all even Fibonacci sequence of whose value does not exceed four million """
import common
# Since the Fibonacci sequence is basically a list comprise of sum of the current value and
# the next. we can just bruteforce to get the finally answer
def run():
res = 0
prev = 1
cu... | [
"common.isOdd"
] | [((368, 386), 'common.isOdd', 'common.isOdd', (['prev'], {}), '(prev)\n', (380, 386), False, 'import common\n')] |
""" Test """
import datetime
import os
def celsius_to_fahrenheit(celsius):
"""A function to convert celsius to fahrenheit"""
print("Converting {0} to fahrenheit...".format(celsius))
try:
return celsius * 9 / 5 + 32
except ZeroDivisionError:
print("An error occurred.")
... | [
"datetime.datetime.now",
"os.listdir",
"os.path.join",
"os.getcwd"
] | [((2352, 2363), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (2361, 2363), False, 'import os\n'), ((2410, 2436), 'os.listdir', 'os.listdir', (['input_file_dir'], {}), '(input_file_dir)\n', (2420, 2436), False, 'import os\n'), ((2787, 2832), 'os.path.join', 'os.path.join', (['input_file_dir', 'input_file_path'], {}), '(i... |
import kdtree
def nonmaximalsuppression(tensor, threshold):
pred_data = tensor.storage()
offset = tensor.storage_offset()
stride = int(tensor.stride()[0])
numel = tensor.numel()
points = []
# Corners
val = pred_data[0 + offset]
if val >= threshold and val >= pred_data[1 + offset] and v... | [
"kdtree.create",
"kdtree.level_order"
] | [((2755, 2782), 'kdtree.create', 'kdtree.create', ([], {'dimensions': '(2)'}), '(dimensions=2)\n', (2768, 2782), False, 'import kdtree\n'), ((3236, 3260), 'kdtree.level_order', 'kdtree.level_order', (['tree'], {}), '(tree)\n', (3254, 3260), False, 'import kdtree\n')] |
from typing import List
from copy import copy
def get_neighbours(current_node: str) -> List[str]:
"""
Get all neighbours for the current node which are not 'start'.
All paths can be traversed in both ways.
"""
global links
return [n2 for n1, n2 in links if n1 == current_node and n2 != 'start']... | [
"copy.copy"
] | [((1613, 1631), 'copy.copy', 'copy', (['current_path'], {}), '(current_path)\n', (1617, 1631), False, 'from copy import copy\n')] |
import json
import os
import requests
import yaml
class Client:
def __init__(self):
base = os.path.dirname(os.path.abspath(__file__))
yml_path = os.path.normpath(os.path.join(base, './kintone.yml'))
with open(yml_path) as f:
env = yaml.load(f)
self.url = env['url'] #... | [
"json.loads",
"json.dumps",
"os.path.join",
"yaml.load",
"os.path.abspath"
] | [((120, 145), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (135, 145), False, 'import os\n'), ((183, 218), 'os.path.join', 'os.path.join', (['base', '"""./kintone.yml"""'], {}), "(base, './kintone.yml')\n", (195, 218), False, 'import os\n'), ((272, 284), 'yaml.load', 'yaml.load', (['f'], {}... |
## pip install librosa
#
import time
import matplotlib.pyplot as plt
import librosa
import librosa.display
# wav 采样率转换
def convert_wav(file, rate=16000):
signal, sr = librosa.load(file, sr=None)
new_signal = librosa.resample(signal, sr, rate) #
out_path = file.split('.wav')[0] + "_new.wav"
librosa.out... | [
"librosa.output.write_wav",
"time.clock",
"matplotlib.pyplot.show",
"librosa.resample",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.title",
"librosa.display.waveplot",
"matplotlib.pyplot.subplot",
"librosa.load"
] | [((693, 705), 'time.clock', 'time.clock', ([], {}), '()\n', (703, 705), False, 'import time\n'), ((173, 200), 'librosa.load', 'librosa.load', (['file'], {'sr': 'None'}), '(file, sr=None)\n', (185, 200), False, 'import librosa\n'), ((218, 252), 'librosa.resample', 'librosa.resample', (['signal', 'sr', 'rate'], {}), '(si... |
import timeit
import argparse
import numpy as np
from core.bamnet.bamnet import BAMnetAgent
from core.matchnn.matchnn import MatchNNAgent
from core.bow.bow import BOWnetAgent
from core.bow.pbow import PBOWnetAgent
from core.build_data.utils import vectorize_data
from core.utils.utils import *
from core.config import *... | [
"timeit.default_timer",
"core.build_data.utils.vectorize_data",
"argparse.ArgumentParser"
] | [((363, 388), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (386, 388), False, 'import argparse\n'), ((1288, 1484), 'core.build_data.utils.vectorize_data', 'vectorize_data', (['train_queries', 'train_query_mentions', 'train_query_marks', 'train_memories'], {'max_query_size': "opt['query_size']... |
import re
import xml.etree.ElementTree as ET
from os import path
from collections import Counter
import argparse
import csv
import json
import os
import random
# package local imports
import sys
import uuid
import matplotlib.pyplot as plt
import math
from dateutil.parser import parse
from tdigest import TDigest
impo... | [
"matplotlib.pyplot.hist",
"matplotlib.pyplot.ylabel",
"numpy.random.lognormal",
"common_datagen.add_deployment_requirements_redis_server_module",
"random.choices",
"common_datagen.generate_inputs_dict_item",
"common_datagen.add_deployment_requirements_utilities",
"os.path.exists",
"tdigest.TDigest",... | [((1553, 1595), 'numpy.random.lognormal', 'np.random.lognormal', (['mu', 'sigma', 'n_elements'], {}), '(mu, sigma, n_elements)\n', (1572, 1595), True, 'import numpy as np\n'), ((3867, 3902), 're.sub', 're.sub', (['"""[^0-9a-zA-Z]+"""', '""" """', 'words'], {}), "('[^0-9a-zA-Z]+', ' ', words)\n", (3873, 3902), False, 'i... |
# -*- coding: utf-8 -*-
import sys
sys.path.append('/notebooks')
import wave
import struct
import glob
import params as par
from scipy import fromstring, int16
import numpy as np
import os.path
from keras.models import Sequential, load_model
from keras.layers import Dense, Flatten, Reshape
from keras.layers.noise impo... | [
"keras.layers.pooling.MaxPooling1D",
"keras.models.load_model",
"keras.layers.normalization.BatchNormalization",
"keras.layers.convolutional.UpSampling1D",
"keras.models.Sequential",
"keras.layers.convolutional.Conv1D",
"keras.backend.function",
"sys.path.append"
] | [((35, 64), 'sys.path.append', 'sys.path.append', (['"""/notebooks"""'], {}), "('/notebooks')\n", (50, 64), False, 'import sys\n'), ((1679, 1740), 'keras.backend.function', 'K.function', (['[model.layers[0].input]', '[model.layers[6].output]'], {}), '([model.layers[0].input], [model.layers[6].output])\n', (1689, 1740),... |
#!/usr/bin/env python3
# Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma de
# Barcelona (UAB).
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
"""A client for benchmarking the CARLA server."""
import argparse
import lo... | [
"logging.basicConfig",
"carla.client.make_carla_client",
"argparse.ArgumentParser",
"time.sleep",
"carla.sensor.Camera",
"os.path.dirname",
"carla.settings.CarlaSettings",
"sys.exit",
"carla.util.StopWatch",
"logging.info",
"logging.error"
] | [((865, 1072), 'carla.settings.CarlaSettings', 'CarlaSettings', ([], {'WeatherId': '(1)', 'SendNonPlayerAgentsInfo': '(False)', 'SynchronousMode': '(False)', 'NumberOfVehicles': '(20)', 'NumberOfPedestrians': '(30)', 'SeedVehicles': '(123456789)', 'SeedPedestrians': '(123456789)', 'QualityLevel': '"""Epic"""'}), "(Weat... |
import os
import platform
if not os.path.exists("temp"):
os.mkdir("temp")
def from_flopy_kl_test():
import shutil
import numpy as np
import pandas as pd
try:
import flopy
except:
return
import pyemu
org_model_ws = os.path.join("..", "examples", "freyberg_sfr_update")
... | [
"flopy.modflow.Modflow.load",
"numpy.sqrt",
"pandas.read_csv",
"pyemu.geostats.GeoStruct",
"pyemu.helpers.PstFromFlopyModel",
"numpy.loadtxt",
"pyemu.geostats.ExpVario",
"os.remove",
"os.path.exists",
"flopy.modflow.ModflowRiv",
"os.listdir",
"numpy.random.random",
"pyemu.Ensemble.reseed",
... | [((34, 56), 'os.path.exists', 'os.path.exists', (['"""temp"""'], {}), "('temp')\n", (48, 56), False, 'import os\n'), ((62, 78), 'os.mkdir', 'os.mkdir', (['"""temp"""'], {}), "('temp')\n", (70, 78), False, 'import os\n'), ((264, 317), 'os.path.join', 'os.path.join', (['""".."""', '"""examples"""', '"""freyberg_sfr_updat... |
from test.application.launchoptions import cancel_options_with_proxy
from test.slurm_assertions import assert_job_canceled
from test.slurmoutput import DEFAULT_JOB_ID
from test.testdoubles.executor import SlurmJobExecutorSpy
from test.testdoubles.filesystem import DummyFilesystemFactory
from typing import Optional
from... | [
"test.application.launchoptions.cancel_options_with_proxy",
"test.slurm_assertions.assert_job_canceled",
"unittest.mock.Mock",
"test.testdoubles.filesystem.DummyFilesystemFactory",
"test.testdoubles.executor.SlurmJobExecutorSpy"
] | [((687, 708), 'test.testdoubles.executor.SlurmJobExecutorSpy', 'SlurmJobExecutorSpy', ([], {}), '()\n', (706, 708), False, 'from test.testdoubles.executor import SlurmJobExecutorSpy\n'), ((785, 830), 'test.slurm_assertions.assert_job_canceled', 'assert_job_canceled', (['executor', 'DEFAULT_JOB_ID'], {}), '(executor, DE... |
#!/usr/bin/env python3.8
import asyncio
from lru import LRU
from logger import log_access, get_access_log_file_descriptor
import json
import os
from req_parser import get_request_object, HTTPError
from req_handler import handle_request, handle_error
from resp_sender import send_response
import multiprocessing as mp
SE... | [
"req_parser.get_request_object",
"logger.log_access",
"logger.get_access_log_file_descriptor",
"os.close",
"req_handler.handle_request",
"multiprocessing.Process",
"asyncio.start_server",
"resp_sender.send_response",
"req_handler.handle_error",
"json.load"
] | [((965, 1001), 'logger.get_access_log_file_descriptor', 'get_access_log_file_descriptor', (['self'], {}), '(self)\n', (995, 1001), False, 'from logger import log_access, get_access_log_file_descriptor\n'), ((2520, 2532), 'json.load', 'json.load', (['f'], {}), '(f)\n', (2529, 2532), False, 'import json\n'), ((2622, 2673... |
from django.db import models
# Create your models here.
class Skill(models.Model):
skillName= models.CharField(verbose_name='Skill', max_length=100)
SKILL_CHOICES = [
('B', 'Beginner'),
('I', 'Intermediate'),
('E', 'Expert'),
]
level= models.CharField(verbose_name='Profici... | [
"django.db.models.EmailField",
"django.db.models.TextField",
"django.db.models.ManyToManyField",
"django.db.models.URLField",
"django.db.models.PositiveSmallIntegerField",
"django.db.models.CharField"
] | [((104, 158), 'django.db.models.CharField', 'models.CharField', ([], {'verbose_name': '"""Skill"""', 'max_length': '(100)'}), "(verbose_name='Skill', max_length=100)\n", (120, 158), False, 'from django.db import models\n'), ((282, 382), 'django.db.models.CharField', 'models.CharField', ([], {'verbose_name': '"""Profici... |
import tensorflow as tf
from tensorflow.python.ops import tensor_array_ops
from tensorflow.python.framework import ops
from tensorflow.python.ops import nn_ops
from tensorflow.python.ops import math_ops
###
# custom loss function, similar to tensorflows but uses 3D tensors
# instead of a list of 2D tensors
def sequen... | [
"tensorflow.shape",
"tensorflow.get_variable",
"tensorflow.transpose",
"tensorflow.reduce_sum",
"tensorflow.tanh",
"tensorflow.truncated_normal_initializer",
"tensorflow.nn.softmax",
"tensorflow.while_loop",
"tensorflow.reduce_min",
"tensorflow.concat",
"tensorflow.matmul",
"tensorflow.greater... | [((1513, 1544), 'tensorflow.reduce_max', 'tf.reduce_max', (['sequence_lengths'], {}), '(sequence_lengths)\n', (1526, 1544), True, 'import tensorflow as tf\n'), ((1571, 1606), 'tensorflow.expand_dims', 'tf.expand_dims', (['sequence_lengths', '(1)'], {}), '(sequence_lengths, 1)\n', (1585, 1606), True, 'import tensorflow ... |
import numpy as np
import pandas as pd
from jeff_rowe_module import NullHelper as nh
from Data_Transformers import DataTransformer as dt
df = pd.read_csv("/Users/connorheraty/Desktop/Datasets/UCI/adult.csv",
names=['age', 'workclass', 'fnlwgt', 'education', 'education-num', 'marital-status',
... | [
"Data_Transformers.DataTransformer.cat_num_split",
"pandas.read_csv"
] | [((145, 439), 'pandas.read_csv', 'pd.read_csv', (['"""/Users/connorheraty/Desktop/Datasets/UCI/adult.csv"""'], {'names': "['age', 'workclass', 'fnlwgt', 'education', 'education-num',\n 'marital-status', 'spouse_absent', 'occupation', 'relationship', 'race',\n 'sex', 'capital-gain', 'capital-loss', 'hours-per-week... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Setup for the Safecast Tracker.
Source:: https://github.com/ampledata/safehook
"""
__title__ = 'safehook'
__version__ = '1.0.0b1'
__author__ = '<NAME> W2GMD <<EMAIL>>'
__license__ = 'Apache License, Version 2.0'
__copyright__ = 'Copyright 2019 <NAME>'
import os
im... | [
"os.system",
"sys.exit"
] | [((458, 499), 'os.system', 'os.system', (['"""python setup.py sdist upload"""'], {}), "('python setup.py sdist upload')\n", (467, 499), False, 'import os\n'), ((508, 518), 'sys.exit', 'sys.exit', ([], {}), '()\n', (516, 518), False, 'import sys\n')] |
from collections import OrderedDict
REGISTERED_GAMES = OrderedDict() | [
"collections.OrderedDict"
] | [((56, 69), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (67, 69), False, 'from collections import OrderedDict\n')] |
# A Faster R-CNN approach to Mu2e Tracking
# The detector (Fast R-CNN) part for alternative (i) method in the original paper
# see https://arxiv.org/abs/1506.01497
# Author: <NAME>
# Email: <EMAIL>
### imports starts
import sys
from pathlib import Path
import pickle
import timeit
import pandas as pd
import numpy as n... | [
"tensorflow.keras.layers.Input",
"Layers.RoIPooling",
"tensorflow.keras.layers.Conv2D",
"pathlib.Path.cwd",
"tensorflow.keras.optimizers.schedules.ExponentialDecay",
"tensorflow.keras.layers.MaxPooling2D",
"tensorflow.keras.optimizers.Adam",
"numpy.expand_dims",
"tensorflow.keras.metrics.Categorical... | [((1111, 1136), 'numpy.load', 'np.load', (['C.img_inputs_npy'], {}), '(C.img_inputs_npy)\n', (1118, 1136), True, 'import numpy as np\n'), ((1148, 1163), 'numpy.load', 'np.load', (['C.rois'], {}), '(C.rois)\n', (1155, 1163), True, 'import numpy as np\n'), ((1179, 1217), 'numpy.load', 'np.load', (['C.detector_train_Y_cla... |
import json
import os
from django.conf import settings
from django.utils.translation import get_language
from django.utils.translation import to_locale
_JSON_MESSAGES_FILE_CACHE = {}
def locale_data_file(locale):
path = getattr(settings, 'LOCALE_PATHS')[0]
return os.path.join(path, locale, "LC_FRONTEND_MESS... | [
"json.load",
"os.path.join",
"django.utils.translation.get_language"
] | [((276, 363), 'os.path.join', 'os.path.join', (['path', 'locale', '"""LC_FRONTEND_MESSAGES"""', '"""contentcuration-messages.json"""'], {}), "(path, locale, 'LC_FRONTEND_MESSAGES',\n 'contentcuration-messages.json')\n", (288, 363), False, 'import os\n'), ((443, 457), 'django.utils.translation.get_language', 'get_lan... |
import numpy as np
import warnings
def drop_outlier(adata,
thresh=15,
axis=0,
drop=True,
verbose=False):
"""Drop all features or cells with a min or max absolute value that is greater than a threshold.
Expects normally distributed data.
... | [
"numpy.logical_and",
"numpy.max",
"numpy.nanmean",
"numpy.min",
"warnings.warn"
] | [((907, 934), 'numpy.nanmean', 'np.nanmean', (['adata.X'], {'axis': '(0)'}), '(adata.X, axis=0)\n', (917, 934), True, 'import numpy as np\n'), ((1551, 1609), 'numpy.logical_and', 'np.logical_and', (['(max_values <= thresh)', '(min_values <= thresh)'], {}), '(max_values <= thresh, min_values <= thresh)\n', (1565, 1609),... |
#!/usr/bin/env python3
# pylint: disable=C0111
import os
from pyndl import count
TEST_ROOT = os.path.dirname(__file__)
EVENT_RESOURCE_FILE = os.path.join(TEST_ROOT, "resources/event_file_trigrams_to_word.tab.gz")
CORPUS_RESOURCE_FILE = os.path.join(TEST_ROOT, "resources/corpus.txt")
def test_cues_outcomes():
... | [
"os.path.join",
"pyndl.count.load_counter",
"os.path.dirname",
"pyndl.count.cues_outcomes",
"pyndl.count.save_counter",
"pyndl.count.words_symbols",
"os.remove"
] | [((97, 122), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (112, 122), False, 'import os\n'), ((145, 216), 'os.path.join', 'os.path.join', (['TEST_ROOT', '"""resources/event_file_trigrams_to_word.tab.gz"""'], {}), "(TEST_ROOT, 'resources/event_file_trigrams_to_word.tab.gz')\n", (157, 216), F... |
import re
import networkx as nx
def read_data(filename="data/input12.data"):
with open(filename) as f:
return f.read().splitlines()
def build_graph(G, lines):
for line in lines:
nodes = [int(n) for n in re.findall(r"-?\d+", line)]
for child in nodes[1:]:
G.add_edge(nodes[0]... | [
"re.findall",
"networkx.number_connected_components",
"networkx.descendants",
"networkx.Graph"
] | [((365, 375), 'networkx.Graph', 'nx.Graph', ([], {}), '()\n', (373, 375), True, 'import networkx as nx\n'), ((478, 511), 'networkx.number_connected_components', 'nx.number_connected_components', (['G'], {}), '(G)\n', (508, 511), True, 'import networkx as nx\n'), ((229, 255), 're.findall', 're.findall', (['"""-?\\\\d+""... |
# Standard lib imports
import logging
# Third party imports
# None
# Project level imports
# None
log = logging.getLogger(__name__)
class Namespace(object):
def __init__(self, connection):
"""
Initialize a new instance
"""
self.conn = connection
def get_namespaces(self):
... | [
"logging.getLogger"
] | [((108, 135), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (125, 135), False, 'import logging\n')] |
import os
import unittest
from bdebld.meta import repocontextloader
from bdebld.meta import repocontext
class TestLoader(unittest.TestCase):
def setUp(self):
self.repo_root = os.path.join(
os.path.dirname(os.path.realpath(__file__)), 'repos', 'one')
def test_loader(self):
loader... | [
"unittest.main",
"bdebld.meta.repocontextloader.RepoContextLoader",
"os.path.realpath"
] | [((1163, 1178), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1176, 1178), False, 'import unittest\n'), ((323, 374), 'bdebld.meta.repocontextloader.RepoContextLoader', 'repocontextloader.RepoContextLoader', (['self.repo_root'], {}), '(self.repo_root)\n', (358, 374), False, 'from bdebld.meta import repocontextloa... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | [
"aliyunsdkhbase.endpoint.endpoint_data.getEndpointMap",
"aliyunsdkhbase.endpoint.endpoint_data.getEndpointRegional",
"aliyunsdkcore.request.RpcRequest.__init__"
] | [((961, 1048), 'aliyunsdkcore.request.RpcRequest.__init__', 'RpcRequest.__init__', (['self', '"""HBase"""', '"""2019-01-01"""', '"""ModifyBackupPlanConfig"""', '"""hbase"""'], {}), "(self, 'HBase', '2019-01-01', 'ModifyBackupPlanConfig',\n 'hbase')\n", (980, 1048), False, 'from aliyunsdkcore.request import RpcReques... |
'''
This script serves to get the speech files prepared for training neural networks, with "matched" noise added to the training data.
Speech was collected from the Saarbücken Voice Database
'''
import pandas as pd
import numpy as np
import librosa
import sqlite3
from sqlite3 import Error
import glob
from pathlib imp... | [
"get_speech_features.get_mfcc",
"sqlite3.connect",
"pathlib.Path",
"get_speech_features.get_fundfreq",
"get_speech_features.get_domfreq",
"numpy.concatenate",
"get_speech_features.get_samps",
"time.time"
] | [((3417, 3428), 'time.time', 'time.time', ([], {}), '()\n', (3426, 3428), False, 'import time\n'), ((1124, 1142), 'get_speech_features.get_samps', 'get_samps', (['wav', 'sr'], {}), '(wav, sr)\n', (1133, 1142), False, 'from get_speech_features import get_samps, get_mfcc, get_fundfreq, get_domfreq\n'), ((1157, 1172), 'ge... |
import httpretty
from nose.tools import raises
from tests import FulcrumTestCase
class PhotoTest(FulcrumTestCase):
@httpretty.activate
def test_records_from_form_via_url_params(self):
httpretty.register_uri(httpretty.GET, self.api_root + '/photos/abc-123',
body='{"photo": {"id": "abc-123"... | [
"nose.tools.raises",
"httpretty.register_uri"
] | [((513, 535), 'nose.tools.raises', 'raises', (['AttributeError'], {}), '(AttributeError)\n', (519, 535), False, 'from nose.tools import raises\n'), ((627, 649), 'nose.tools.raises', 'raises', (['AttributeError'], {}), '(AttributeError)\n', (633, 649), False, 'from nose.tools import raises\n'), ((749, 771), 'nose.tools.... |
#!/usr/bin/env python3
# Copyright (c) 2008-9 Qtrac Ltd. All rights reserved.
# This program or module 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 2 of the License, or
# version 3 of the Lic... | [
"PyQt4.QtCore.QVariant",
"PyQt4.QtCore.QString",
"bisect.bisect_left",
"PyQt4.QtCore.QModelIndex"
] | [((1814, 1860), 'bisect.bisect_left', 'bisect.bisect_left', (['self.children', '(key, None)'], {}), '(self.children, (key, None))\n', (1832, 1860), False, 'import bisect\n'), ((5883, 5893), 'PyQt4.QtCore.QVariant', 'QVariant', ([], {}), '()\n', (5891, 5893), False, 'from PyQt4.QtCore import QAbstractItemModel, QModelIn... |
import app
def main():
print(app.say_hello())
| [
"app.say_hello"
] | [((35, 50), 'app.say_hello', 'app.say_hello', ([], {}), '()\n', (48, 50), False, 'import app\n')] |
# -*- coding: utf-8 -*-
from unittest.mock import Mock
import pytest
from urchintai_client.request_sender import RequestSender
@pytest.mark.asyncio
async def test_should_return_content_if_post_ok():
'''
Test sending HTTP request using POST without error
'''
# Arrange
url = 'http://example.com'
... | [
"unittest.mock.Mock",
"pytest.raises",
"urchintai_client.request_sender.RequestSender"
] | [((456, 462), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (460, 462), False, 'from unittest.mock import Mock\n'), ((521, 543), 'urchintai_client.request_sender.RequestSender', 'RequestSender', (['session'], {}), '(session)\n', (534, 543), False, 'from urchintai_client.request_sender import RequestSender\n'), ((1005... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import io
import os
import pathlib
import random
import shutil
import typing
from datetime import datetime
from os.path import join
import sqlite3
from PyPDF2 import PdfFileReader, PdfFileWriter
from PyPDF2.generic import Destination
#####################... | [
"os.listdir",
"argparse.ArgumentParser",
"pathlib.Path",
"sqlite3.Connection",
"os.path.join",
"io.BytesIO",
"datetime.datetime.now",
"os.path.basename",
"PyPDF2.PdfFileWriter",
"os.system"
] | [((11124, 11148), 'os.listdir', 'os.listdir', (['CHAPTERS_DIR'], {}), '(CHAPTERS_DIR)\n', (11134, 11148), False, 'import os\n'), ((13229, 13278), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""PDF picker"""'}), "(description='PDF picker')\n", (13252, 13278), False, 'import argparse\n'), ... |
import asyncio
import time
from collections import defaultdict
from models.proxy import Proxy
class Saver(object):
RESULT_SAVE_NUM = 100
pattern_lock_map = defaultdict(asyncio.Lock)
success_count = 0
total_count = 0
def __init__(self, redis):
self.redis = redis
async def _save(self,... | [
"models.proxy.Proxy.discard",
"time.time",
"collections.defaultdict",
"asyncio.gather"
] | [((167, 192), 'collections.defaultdict', 'defaultdict', (['asyncio.Lock'], {}), '(asyncio.Lock)\n', (178, 192), False, 'from collections import defaultdict\n'), ((1875, 1897), 'asyncio.gather', 'asyncio.gather', (['*tasks'], {}), '(*tasks)\n', (1889, 1897), False, 'import asyncio\n'), ((2035, 2046), 'time.time', 'time.... |
#----------------------------------------------------------------------------
# Name: wet_antenna
# Purpose: Estimation and removal of wet antenna effects
#
# Authors: <NAME>
#
# Created: 01.12.2014
# Copyright: (c) <NAME> 2014
# Licence: The MIT License
#---------------------------------... | [
"numba.decorators.jit",
"numpy.zeros_like"
] | [((592, 610), 'numba.decorators.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (595, 610), False, 'from numba.decorators import jit\n'), ((1658, 1694), 'numpy.zeros_like', 'np.zeros_like', (['rsl'], {'dtype': 'np.float64'}), '(rsl, dtype=np.float64)\n', (1671, 1694), True, 'import numpy as np\n')] |
"""Tests for the ingredients endpoint.
"""
import json
from app.endpoints.v1.payload.ingredient import IngredientSchema
from app.endpoints.common.dtos.availability import Availability
API_PATH = "/api/v1/ingredients/"
CONTENT_TYPE = "application/json"
# create test data
INGREDIENT_NAME = "pear"
AVAILABILITY_PER_MON... | [
"app.endpoints.v1.payload.ingredient.IngredientSchema"
] | [((5694, 5721), 'app.endpoints.v1.payload.ingredient.IngredientSchema', 'IngredientSchema', ([], {'many': '(True)'}), '(many=True)\n', (5710, 5721), False, 'from app.endpoints.v1.payload.ingredient import IngredientSchema\n'), ((6199, 6217), 'app.endpoints.v1.payload.ingredient.IngredientSchema', 'IngredientSchema', ([... |
#!/usr/bin/env python
"""
./plotAE.py data/WWW_aeasy00007552.dat -t 2013-05-01T07:00 2013-05-01T11:00
"""
from matplotlib.pyplot import show
from aeindex import readae, plotae
from argparse import ArgumentParser
import seaborn as sns
sns.set_style('whitegrid')
def main():
p = ArgumentParser()
p.add_argument(... | [
"argparse.ArgumentParser",
"aeindex.plotae",
"seaborn.set_style",
"aeindex.readae",
"matplotlib.pyplot.show"
] | [((234, 260), 'seaborn.set_style', 'sns.set_style', (['"""whitegrid"""'], {}), "('whitegrid')\n", (247, 260), True, 'import seaborn as sns\n'), ((284, 300), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (298, 300), False, 'from argparse import ArgumentParser\n'), ((447, 467), 'aeindex.readae', 'readae'... |
########################################################################
# File_List.py.
# Purpose:
########################################################################
import shutil
import os
import sys
import csv
import zipfile
from assets.models import AssetType
# indir = '/home/geomemes/projects/cedar/filelis... | [
"os.path.exists",
"zipfile.ZipFile",
"shutil.copy2",
"os.makedirs",
"os.path.split"
] | [((952, 978), 'os.path.split', 'os.path.split', (['source_file'], {}), '(source_file)\n', (965, 978), False, 'import os\n'), ((1227, 1258), 'os.path.split', 'os.path.split', (['destination_file'], {}), '(destination_file)\n', (1240, 1258), False, 'import os\n'), ((1274, 1300), 'os.path.exists', 'os.path.exists', (['des... |
import pathlib
ROOT = pathlib.Path().absolute()
FOLDER_NAME = "formatting_helper"
TEXT_FILE_PATH = ROOT / FOLDER_NAME / "format_me.txt"
OUTPUT_FILE_PATH = ROOT / FOLDER_NAME / "formatted.txt"
#editable constants:
#constants are used in the order they appear
#indicates the number of symbols to remove from the start o... | [
"pathlib.Path"
] | [((24, 38), 'pathlib.Path', 'pathlib.Path', ([], {}), '()\n', (36, 38), False, 'import pathlib\n')] |
import pyhecdss
import pandas as pd
import numpy as np
import os
def test_read_write_cycle_rts():
'''
Test reading and writing of period time stamped data so
that reads and writes don't result in shifting the data
'''
fname = "test2.dss"
if os.path.exists(fname):
os.remove... | [
"os.path.exists",
"pyhecdss.DSSFile",
"numpy.linspace",
"pandas.testing.assert_frame_equal",
"os.remove"
] | [((279, 300), 'os.path.exists', 'os.path.exists', (['fname'], {}), '(fname)\n', (293, 300), False, 'import os\n'), ((625, 665), 'pyhecdss.DSSFile', 'pyhecdss.DSSFile', (['fname'], {'create_new': '(True)'}), '(fname, create_new=True)\n', (641, 665), False, 'import pyhecdss\n'), ((782, 805), 'pyhecdss.DSSFile', 'pyhecdss... |
import os
import trafaret as t
class ExistingDirectory(t.String):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def check_value(self, value):
if not os.path.isdir(value):
raise t.DataError(error='{} is not directory'.format(value))
| [
"os.path.isdir"
] | [((202, 222), 'os.path.isdir', 'os.path.isdir', (['value'], {}), '(value)\n', (215, 222), False, 'import os\n')] |
from dataclasses import dataclass, field
import turing.generated.models
from turing.generated.model_utils import OpenApiModel
@dataclass
class EnvVar:
name: str
value: str
_name: str = field(init=False, repr=False)
_value: str = field(init=False, repr=False)
@property
def name(self) -> str:... | [
"dataclasses.field"
] | [((201, 230), 'dataclasses.field', 'field', ([], {'init': '(False)', 'repr': '(False)'}), '(init=False, repr=False)\n', (206, 230), False, 'from dataclasses import dataclass, field\n'), ((249, 278), 'dataclasses.field', 'field', ([], {'init': '(False)', 'repr': '(False)'}), '(init=False, repr=False)\n', (254, 278), Fal... |