code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
from django.shortcuts import render
from Dovapp.models import *
from rest_framework import viewsets
from Dovapp.serializers import *
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
import json
class ProjectViewSet(v... | [
"django.contrib.auth.authenticate",
"django.contrib.auth.login",
"django.contrib.auth.logout",
"django.http.JsonResponse"
] | [((1166, 1181), 'django.contrib.auth.logout', 'logout', (['request'], {}), '(request)\n', (1172, 1181), False, 'from django.contrib.auth import authenticate, login, logout\n'), ((1247, 1277), 'django.http.JsonResponse', 'JsonResponse', (['data'], {'safe': '(False)'}), '(data, safe=False)\n', (1259, 1277), False, 'from ... |
from sicpythontask.PythonTaskInfo import PythonTaskInfo
from sicpythontask.PythonTask import PythonTask
from sicpythontask.SicParameter import SicParameter
from sicpythontask.InputPort import InputPort
from sicpythontask.OutputPort import OutputPort
from sicpythontask.data.Int32 import Int32
@PythonTaskInfo
@SicParame... | [
"sicpythontask.SicParameter.SicParameter",
"sicpythontask.InputPort.InputPort",
"sicpythontask.OutputPort.OutputPort"
] | [((311, 333), 'sicpythontask.SicParameter.SicParameter', 'SicParameter', ([], {'name': '"""M"""'}), "(name='M')\n", (323, 333), False, 'from sicpythontask.SicParameter import SicParameter\n'), ((335, 376), 'sicpythontask.SicParameter.SicParameter', 'SicParameter', ([], {'name': '"""N"""', 'default_value': '"""5"""'}), ... |
import unittest
import hypothesis.strategies as st
from hypothesis import given
from coin_change import Solution
class Test(unittest.TestCase):
def test_1(self):
solution = Solution()
self.assertEqual(solution.coinChange([1, 2, 5], 11), 3)
def test_2(self):
solution = Solution()
... | [
"unittest.main",
"coin_change.Solution"
] | [((1201, 1216), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1214, 1216), False, 'import unittest\n'), ((187, 197), 'coin_change.Solution', 'Solution', ([], {}), '()\n', (195, 197), False, 'from coin_change import Solution\n'), ((304, 314), 'coin_change.Solution', 'Solution', ([], {}), '()\n', (312, 314), False... |
from functools import wraps
from dj_core.utils import as_absolute
from django.conf import settings
from django.urls import reverse
from rest_framework.settings import perform_import
from wagtail.core.blocks import RichTextBlock
from wagtail.core.models import Site, UserPagePermissionsProxy
from wagtail.images.formats ... | [
"wagtailnest.serializers.EmbedSerializer.for_url",
"dj_core.utils.as_absolute",
"wagtail.core.blocks.RichTextBlock",
"wagtail.core.models.Site.objects.filter",
"functools.wraps",
"wagtail.images.views.serve.generate_signature",
"wagtail.images.formats.get_image_formats",
"wagtail.core.models.UserPageP... | [((1559, 1600), 'wagtail.images.views.serve.generate_signature', 'generate_signature', (['image.id', 'filter_spec'], {}), '(image.id, filter_spec)\n', (1577, 1600), False, 'from wagtail.images.views.serve import generate_signature\n'), ((1644, 1698), 'django.urls.reverse', 'reverse', (['name'], {'args': '(signature, im... |
#!/usr/bin/env python3
# -*- encoding:utf-8 -*-
import os
import logging
from flask import Flask, redirect, url_for
from flask_mdict import __version__, init_app, mdict_query2
logger = logging.getLogger(__name__)
def create_app(mdict_dir='content'):
logging.basicConfig(
level=20,
format='%(mes... | [
"logging.getLogger",
"logging.basicConfig",
"os.path.exists",
"flask.Flask",
"os.path.join",
"flask.url_for",
"os.path.realpath",
"flask_mdict.init_app"
] | [((189, 216), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (206, 216), False, 'import logging\n'), ((260, 311), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': '(20)', 'format': '"""%(message)s"""'}), "(level=20, format='%(message)s')\n", (279, 311), False, 'import logging\... |
'''Define the user model'''
from sqlalchemy import Column, Integer, String
from .base import Base
class User(Base):
'''User Table'''
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
display_name = Column(String(100), nullable=True)
username = Column(String(300), nullable=False, index=... | [
"sqlalchemy.String",
"sqlalchemy.Column"
] | [((175, 208), 'sqlalchemy.Column', 'Column', (['Integer'], {'primary_key': '(True)'}), '(Integer, primary_key=True)\n', (181, 208), False, 'from sqlalchemy import Column, Integer, String\n'), ((235, 246), 'sqlalchemy.String', 'String', (['(100)'], {}), '(100)\n', (241, 246), False, 'from sqlalchemy import Column, Integ... |
import numpy as np
import pytest
from sklego.common import flatten
from sklego.dummy import RandomRegressor
from tests.conftest import nonmeta_checks, regressor_checks, general_checks, select_tests
@pytest.mark.parametrize(
"test_fn",
select_tests(
flatten([general_checks, nonmeta_checks, regressor_c... | [
"numpy.random.normal",
"numpy.mean",
"sklego.dummy.RandomRegressor",
"sklego.common.flatten",
"pytest.raises",
"numpy.random.seed",
"numpy.std"
] | [((859, 893), 'sklego.dummy.RandomRegressor', 'RandomRegressor', ([], {'strategy': '"""normal"""'}), "(strategy='normal')\n", (874, 893), False, 'from sklego.dummy import RandomRegressor\n'), ((977, 1012), 'sklego.dummy.RandomRegressor', 'RandomRegressor', ([], {'strategy': '"""uniform"""'}), "(strategy='uniform')\n", ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu
from django.views.debug import get_safe_settings
class SafeSettings(object):
"""
Map attributes to values in the safe settings dict
"""
def __init__(self):
self._settings = get_safe_settings()
def __getatt... | [
"django.views.debug.get_safe_settings"
] | [((283, 302), 'django.views.debug.get_safe_settings', 'get_safe_settings', ([], {}), '()\n', (300, 302), False, 'from django.views.debug import get_safe_settings\n')] |
# Copyright (c) 1999-2008 <NAME> and <NAME>
# Copyright (c) 2009 The Hewlett-Packard Development Company
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retai... | [
"slicc.symbols.Var"
] | [((2333, 2418), 'slicc.symbols.Var', 'Var', (['self.symtab', '"""in_msg"""', 'self.location', 'msg_type', '"""(*in_msg_ptr)"""', 'self.pairs'], {}), "(self.symtab, 'in_msg', self.location, msg_type, '(*in_msg_ptr)', self.pairs\n )\n", (2336, 2418), False, 'from slicc.symbols import Var\n')] |
import paho.mqtt.client as mqtt
import datetime
import logging as log
import cfg
from time import sleep,time
import json
import socket
conf = {}
# -------------------- mqtt events --------------------
def on_connect(lclient, userdata, flags, rc):
global conf
log.info("mqtt> connected with result code "+str(r... | [
"paho.mqtt.client.Client",
"logging.info",
"time.sleep",
"socket.gethostname",
"logging.error"
] | [((519, 562), 'logging.info', 'log.info', (['"""mqtt> Subscriptions not enabled"""'], {}), "('mqtt> Subscriptions not enabled')\n", (527, 562), True, 'import logging as log\n'), ((604, 640), 'logging.info', 'log.info', (['"""mqtt> Publishing enabled"""'], {}), "('mqtt> Publishing enabled')\n", (612, 640), True, 'import... |
import numpy as np
NSAMPLE=64
NSPEC=4
for spec in range(NSPEC):
list = []
for i in range(NSAMPLE):
infile = "RUN%d/res.mass_spec%d_final_vert" % (i+1,spec+1)
a = np.loadtxt(infile)
list.append(a)
list = np.transpose(np.array(list))
mean = np.mean(list,axis=1)
st... | [
"numpy.mean",
"numpy.array",
"numpy.savetxt",
"numpy.std",
"numpy.loadtxt",
"numpy.transpose"
] | [((293, 314), 'numpy.mean', 'np.mean', (['list'], {'axis': '(1)'}), '(list, axis=1)\n', (300, 314), True, 'import numpy as np\n'), ((324, 352), 'numpy.std', 'np.std', (['list'], {'axis': '(1)', 'ddof': '(1)'}), '(list, axis=1, ddof=1)\n', (330, 352), True, 'import numpy as np\n'), ((371, 396), 'numpy.transpose', 'np.tr... |
import textwrap
from ..formatter import AssetFormatter
wrapper = textwrap.TextWrapper(
initial_indent=' ', subsequent_indent=' ', width=80
)
def c_initializer(data):
if type(data) is str:
data = data.encode('utf-8')
values = ', '.join(f'0x{c:02x}' for c in data)
return f' = {{\n{wrappe... | [
"textwrap.TextWrapper",
"textwrap.dedent"
] | [((67, 146), 'textwrap.TextWrapper', 'textwrap.TextWrapper', ([], {'initial_indent': '""" """', 'subsequent_indent': '""" """', 'width': '(80)'}), "(initial_indent=' ', subsequent_indent=' ', width=80)\n", (87, 146), False, 'import textwrap\n'), ((399, 537), 'textwrap.dedent', 'textwrap.dedent', (['""" ... |
"""Command for reshaping existing 'manuscripts' database, and porting it to the new structure"""
import sys
import argparse
from mpcereform.core import LocalDB
def main():
"""Main entry point for the script"""
# Define argument parser
parser = argparse.ArgumentParser(description='Build the MPCE database f... | [
"mpcereform.core.LocalDB",
"argparse.ArgumentParser"
] | [((258, 335), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Build the MPCE database from raw data."""'}), "(description='Build the MPCE database from raw data.')\n", (281, 335), False, 'import argparse\n'), ((996, 1015), 'mpcereform.core.LocalDB', 'LocalDB', ([], {}), '(**arg_dict)\n', ... |
import shutil
shutil.get_archive_formats()
shutil.make_archive('/tmp/f1', 'zip', root_dir='/tmp/f1/')
shutil.move('/tmp/f1', '/tmp/f2')
shutil.copytree('/tmp/f1/', '/tmp/f2/')
shutil.copytree('/tmp/f1/', '/tmp/f2/', ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))
shutil.rmtree('/tmp/f1/')
shutil.copy('/tmp/f1', '/tmp... | [
"shutil.get_archive_formats",
"shutil.make_archive",
"shutil.move",
"shutil.copy2",
"shutil.copymode",
"shutil.ignore_patterns",
"shutil.copytree",
"shutil.copyfile",
"shutil.copy",
"shutil.rmtree",
"shutil.copystat"
] | [((15, 43), 'shutil.get_archive_formats', 'shutil.get_archive_formats', ([], {}), '()\n', (41, 43), False, 'import shutil\n'), ((44, 102), 'shutil.make_archive', 'shutil.make_archive', (['"""/tmp/f1"""', '"""zip"""'], {'root_dir': '"""/tmp/f1/"""'}), "('/tmp/f1', 'zip', root_dir='/tmp/f1/')\n", (63, 102), False, 'impor... |
from airflow.utils.decorators import apply_defaults
from airflow.plugins_manager import AirflowPlugin
from base_data_quality_operator import BaseDataQualityOperator, get_sql_value
class DataQualityThresholdSQLCheckOperator(BaseDataQualityOperator):
"""
DataQualityThresholdSQLCheckOperator inherits from DataQu... | [
"base_data_quality_operator.get_sql_value"
] | [((1611, 1672), 'base_data_quality_operator.get_sql_value', 'get_sql_value', (['self.threshold_conn_id', 'self.min_threshold_sql'], {}), '(self.threshold_conn_id, self.min_threshold_sql)\n', (1624, 1672), False, 'from base_data_quality_operator import BaseDataQualityOperator, get_sql_value\n'), ((1702, 1763), 'base_dat... |
import numpy as np
import data
import matplotlib.pyplot as plt
def sanityCheck(objType, phiType):
""" draw and save the figure of the mean, range for different methods and N
:param objType: objective type - worst/sum
:param phiType: phi-divergence type - cre/chi/m-chi
"""
loaded = np.load('data/'... | [
"matplotlib.pyplot.savefig",
"data.alphaSet",
"matplotlib.pyplot.ylabel",
"numpy.arange",
"matplotlib.pyplot.xlabel",
"numpy.array",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.xlim",
"numpy.load",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.legend",
"matplo... | [((305, 362), 'numpy.load', 'np.load', (["('data/' + objType + '_' + phiType + '_final.npz')"], {}), "('data/' + objType + '_' + phiType + '_final.npz')\n", (312, 362), True, 'import numpy as np\n'), ((540, 566), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(7, 5)'}), '(figsize=(7, 5))\n', (550, 566), Tr... |
import pickle
import pandas as pd
import numpy as np
import streamlit as st
st.set_page_config(page_title = 'Promotion Prediction',page_icon='🌀')
st.markdown(
""" <style> .main { background-color : #d6b265; }, .sidebar .sidebar-content { color: #4077d6; } </style> """,
unsafe_allow_html = True
... | [
"streamlit.form",
"streamlit.checkbox",
"streamlit.markdown",
"streamlit.image",
"pandas.read_csv",
"streamlit.selectbox",
"streamlit.warning",
"streamlit.write",
"streamlit.slider",
"streamlit.sidebar.header",
"streamlit.success",
"streamlit.sidebar.selectbox",
"streamlit.set_page_config",
... | [((78, 146), 'streamlit.set_page_config', 'st.set_page_config', ([], {'page_title': '"""Promotion Prediction"""', 'page_icon': '"""🌀"""'}), "(page_title='Promotion Prediction', page_icon='🌀')\n", (96, 146), True, 'import streamlit as st\n'), ((148, 300), 'streamlit.markdown', 'st.markdown', (['""" <style> .main { bac... |
#!/usr/bin/python
# -*- coding:utf-8 -*-
"""
Date : 2017-06-20
Authors: linming(<EMAIL>)
"""
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
from elasticsearch import Elasticsearch
class EsConnect(object):
"""
Class of EsConnect
"""
def __init__(self, hostsinfo, index, doc_type, timeout=5000... | [
"elasticsearch.Elasticsearch",
"sys.setdefaultencoding"
] | [((119, 150), 'sys.setdefaultencoding', 'sys.setdefaultencoding', (['"""utf-8"""'], {}), "('utf-8')\n", (141, 150), False, 'import sys\n'), ((635, 692), 'elasticsearch.Elasticsearch', 'Elasticsearch', ([], {'hosts': 'self.hostsinfo', 'timeout': 'self.timeout'}), '(hosts=self.hostsinfo, timeout=self.timeout)\n', (648, 6... |
# -*- coding: utf-8 -*-
import os.path as op
import psutil
def _abspath(path):
return op.abspath(op.expanduser(path))
def gather_notebooks():
""" Gather processes of IPython Notebook
Return
------
notes : list of dict
each dict has following keys: "pid", "cwd", and "port"
Raises
... | [
"os.path.exists",
"psutil.process_iter",
"os.path.expanduser"
] | [((432, 453), 'psutil.process_iter', 'psutil.process_iter', ([], {}), '()\n', (451, 453), False, 'import psutil\n'), ((104, 123), 'os.path.expanduser', 'op.expanduser', (['path'], {}), '(path)\n', (117, 123), True, 'import os.path as op\n'), ((1396, 1417), 'os.path.exists', 'op.exists', (['ipynb_path'], {}), '(ipynb_pa... |
from django.shortcuts import render
# Create your views here.
from .forms import CreateContactForm
from .models import ContactUs
def contact_us(request):
contact_form = CreateContactForm(request.POST or None)
if contact_form.is_valid():
full_name = contact_form.cleaned_data.get('full_name')
... | [
"django.shortcuts.render"
] | [((748, 807), 'django.shortcuts.render', 'render', (['request', '"""contact_us/contact_us_page.html"""', 'context'], {}), "(request, 'contact_us/contact_us_page.html', context)\n", (754, 807), False, 'from django.shortcuts import render\n')] |
#!/usr/bin/env python
###############################################################################
# $Id$
#
# Project: GDAL/OGR Test Suite
# Purpose: Test Raster Matrix Format used in GISes "Panorama"/"Integratsia".
# Author: <NAME> <<EMAIL>>
#
###################################################################... | [
"gdaltest.GDALTest",
"gdaltest.run_tests",
"gdaltest.summarize",
"gdaltest.setup_run",
"sys.path.append"
] | [((1546, 1573), 'sys.path.append', 'sys.path.append', (['"""../pymod"""'], {}), "('../pymod')\n", (1561, 1573), False, 'import sys\n'), ((1728, 1773), 'gdaltest.GDALTest', 'gdaltest.GDALTest', (['"""rmf"""', '"""byte.rsw"""', '(1)', '(4672)'], {}), "('rmf', 'byte.rsw', 1, 4672)\n", (1745, 1773), False, 'import gdaltest... |
import attr
from pathlib import Path
import re
from pylexibank import Lexeme, Language
from pylexibank.providers.clld import CLLD
from pylexibank.util import progressbar
from pylexibank import FormSpec
from clldutils.misc import slug
@attr.s
class CustomLexeme(Lexeme):
Word_ID = attr.ib(default=None)
word_s... | [
"clldutils.misc.slug",
"pylexibank.FormSpec",
"pathlib.Path",
"re.sub",
"pylexibank.util.progressbar",
"attr.ib"
] | [((288, 309), 'attr.ib', 'attr.ib', ([], {'default': 'None'}), '(default=None)\n', (295, 309), False, 'import attr\n'), ((328, 349), 'attr.ib', 'attr.ib', ([], {'default': 'None'}), '(default=None)\n', (335, 349), False, 'import attr\n'), ((365, 386), 'attr.ib', 'attr.ib', ([], {'default': 'None'}), '(default=None)\n',... |
# (c) 2012-2013 Continuum Analytics, Inc. / http://continuum.io
# All Rights Reserved
#
# conda is distributed under the terms of the BSD 3-clause license.
# Consult LICENSE.txt or http://opensource.org/licenses/BSD-3-Clause.
from __future__ import print_function, division, absolute_import
import sys
from os.path imp... | [
"os.path.join",
"conda.__version__.split",
"os.mkdir",
"sys.exit",
"json.dump"
] | [((1079, 1105), 'os.path.join', 'join', (['prefix', '"""conda-meta"""'], {}), "(prefix, 'conda-meta')\n", (1083, 1105), False, 'from os.path import isdir, join\n'), ((743, 778), 'os.path.join', 'join', (['config.root_dir', '"""conda-meta"""'], {}), "(config.root_dir, 'conda-meta')\n", (747, 778), False, 'from os.path i... |
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
import pprint
import fiolib.shared_chart as shared
from matplotlib import cm
# The module required for the 3D graph.
from mpl_toolkits.mplot3d import axes3d
from datetime import datetime
import matplotlib as mpl
import fiolib.supporting as suppor... | [
"numpy.ones_like",
"matplotlib.pyplot.cm.ScalarMappable",
"fiolib.shared_chart.get_dataset_types",
"fiolib.supporting.get_largest_scale_factor",
"fiolib.supporting.get_scale_factor",
"matplotlib.pyplot.close",
"numpy.array",
"matplotlib.pyplot.figure",
"numpy.zeros",
"datetime.datetime.now",
"ma... | [((575, 608), 'fiolib.shared_chart.get_dataset_types', 'shared.get_dataset_types', (['dataset'], {}), '(dataset)\n', (599, 608), True, 'import fiolib.shared_chart as shared\n'), ((755, 825), 'fiolib.shared_chart.get_record_set_3d', 'shared.get_record_set_3d', (['settings', 'dataset', 'dataset_types', 'rw', 'metric'], {... |
#!/usr/bin/env python
# coding=utf-8
# Copyright 2020 The HuggingFace Inc. team. 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/LI... | [
"logging.getLogger",
"data.utils_hart.ft_doc_data_utils.load_dataset",
"logging.StreamHandler",
"os.listdir",
"transformers.AutoConfig.from_pretrained",
"data.data_collator.DataCollatorWithPaddingForHaRT",
"transformers.HfArgumentParser",
"transformers.trainer_utils.is_main_process",
"os.path.abspat... | [((1643, 1670), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1660, 1670), False, 'import logging\n'), ((1903, 1979), 'transformers.HfArgumentParser', 'HfArgumentParser', (['(ModelArguments, DataTrainingArguments, TrainingArguments)'], {}), '((ModelArguments, DataTrainingArguments, Trai... |
"""Gamma distribution."""
import numpy
from scipy import special
from ..baseclass import SimpleDistribution, ShiftScaleDistribution
class gamma(SimpleDistribution):
def __init__(self, a=1):
super(gamma, self).__init__(dict(a=a))
def _pdf(self, x, a):
return x**(a-1)*numpy.e**(-x)/special.ga... | [
"scipy.special.gamma",
"scipy.special.gammainc",
"scipy.special.gammaincinv"
] | [((369, 391), 'scipy.special.gammainc', 'special.gammainc', (['a', 'x'], {}), '(a, x)\n', (385, 391), False, 'from scipy import special\n'), ((434, 459), 'scipy.special.gammaincinv', 'special.gammaincinv', (['a', 'q'], {}), '(a, q)\n', (453, 459), False, 'from scipy import special\n'), ((685, 718), 'scipy.special.gamma... |
# Copyright (c) 2018-2019, NVIDIA CORPORATION
# Copyright (c) 2017- Facebook, Inc
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above ... | [
"signal.signal",
"torch.device",
"signal.getsignal",
"os.path.join",
"torch.distributed.is_initialized",
"torch.distributed.all_reduce",
"torch.tensor",
"torch.distributed.broadcast",
"torch.save",
"torch.distributed.get_rank",
"torch.distributed.get_world_size"
] | [((3340, 3381), 'torch.distributed.all_reduce', 'dist.all_reduce', (['rt'], {'op': 'dist.ReduceOp.SUM'}), '(rt, op=dist.ReduceOp.SUM)\n', (3355, 3381), True, 'import torch.distributed as dist\n'), ((2100, 2138), 'os.path.join', 'os.path.join', (['checkpoint_dir', 'filename'], {}), '(checkpoint_dir, filename)\n', (2112,... |
import sys, signal
def signal_handler(signal, frame):
print("\nprogram exiting gracefully")
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
####################### Listen #################################
import speech_recognition as sr
import wave
def listen_to_me(threshold=3000):
# use... | [
"signal.signal",
"json.loads",
"base64.b64encode",
"json.dumps",
"speech_recognition.Recognizer",
"speech_recognition.Microphone",
"sys.exit",
"time.time"
] | [((113, 157), 'signal.signal', 'signal.signal', (['signal.SIGINT', 'signal_handler'], {}), '(signal.SIGINT, signal_handler)\n', (126, 157), False, 'import sys, signal\n'), ((100, 111), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (108, 111), False, 'import sys, signal\n'), ((658, 673), 'speech_recognition.Recognizer... |
from django.contrib import admin
from django.contrib.auth.admin import User
from server.models.collective import Collective, Session
from server.models.qualification import Qualification, QualificationGroup
from server.models.instruction import Instruction, Topic
from server.models.category import Category, CategoryGro... | [
"django.contrib.admin.site.unregister",
"django.contrib.admin.site.register"
] | [((614, 641), 'django.contrib.admin.site.unregister', 'admin.site.unregister', (['User'], {}), '(User)\n', (635, 641), False, 'from django.contrib import admin\n'), ((642, 678), 'django.contrib.admin.site.register', 'admin.site.register', (['User', 'UserAdmin'], {}), '(User, UserAdmin)\n', (661, 678), False, 'from djan... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This loads the user's _config.py file and provides a standardized interface
into it."""
import os
import sys
import urllib.parse
import re
from . import cache
from . import controller
from . import filter
from .cache import zf
zf.config = sys.modules['zeekofile.con... | [
"os.path.isfile",
"os.path.dirname",
"os.path.join",
"re.compile"
] | [((1007, 1032), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (1022, 1032), False, 'import os\n'), ((1048, 1102), 'os.path.join', 'os.path.join', (['zeekofile_codebase', '"""_default_config.py"""'], {}), "(zeekofile_codebase, '_default_config.py')\n", (1060, 1102), False, 'import os\n'), ((1... |
from collections import Mapping, Hashable
from operator import add
import pytest
from pyrsistent import pmap, m, PVector
import pickle
def test_instance_of_hashable():
assert isinstance(m(), Hashable)
def test_instance_of_map():
assert isinstance(m(), Mapping)
def test_literalish_works():
assert m() is... | [
"pyrsistent.pmap",
"pyrsistent.m",
"pytest.raises"
] | [((422, 428), 'pyrsistent.pmap', 'pmap', ([], {}), '()\n', (426, 428), False, 'from pyrsistent import pmap, m, PVector\n'), ((514, 528), 'pyrsistent.pmap', 'pmap', (["{'a': 2}"], {}), "({'a': 2})\n", (518, 528), False, 'from pyrsistent import pmap, m, PVector\n'), ((848, 851), 'pyrsistent.m', 'm', ([], {}), '()\n', (84... |
import copy
import numpy as np
import pytest
import tensorflow as tf
from tfsnippet.layers import as_gated
def safe_sigmoid(x):
return np.where(x < 0, np.exp(x) / (1. + np.exp(x)), 1. / (1. + np.exp(-x)))
class AsGatedHelper(object):
def __init__(self, main_ret, gate_ret):
self.main_args = None
... | [
"numpy.random.normal",
"tfsnippet.layers.as_gated",
"numpy.exp",
"pytest.raises",
"copy.copy"
] | [((159, 168), 'numpy.exp', 'np.exp', (['x'], {}), '(x)\n', (165, 168), True, 'import numpy as np\n'), ((1149, 1217), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""`default_name` cannot be inferred"""'}), "(ValueError, match='`default_name` cannot be inferred')\n", (1162, 1217), False, 'import pytest\... |
from django.contrib import admin
from .models import Topic, Comment, TagOfTopic, TopicSection
admin.site.register(Topic)
admin.site.register(Comment)
admin.site.register(TagOfTopic)
admin.site.register(TopicSection)
| [
"django.contrib.admin.site.register"
] | [((96, 122), 'django.contrib.admin.site.register', 'admin.site.register', (['Topic'], {}), '(Topic)\n', (115, 122), False, 'from django.contrib import admin\n'), ((123, 151), 'django.contrib.admin.site.register', 'admin.site.register', (['Comment'], {}), '(Comment)\n', (142, 151), False, 'from django.contrib import adm... |
# Copyright 2020- Robot Framework Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | [
"json.loads",
"robotlibcore.keyword"
] | [((892, 968), 'robotlibcore.keyword', 'keyword', ([], {'name': '"""Execute JavaScript"""', 'tags': "['Setter', 'Getter', 'PageContent']"}), "(name='Execute JavaScript', tags=['Setter', 'Getter', 'PageContent'])\n", (899, 968), False, 'from robotlibcore import keyword\n'), ((2048, 2087), 'robotlibcore.keyword', 'keyword... |
from django.test import override_settings
from rest_framework import status
from thenewboston_node.business_logic.tests.base import as_primary_validator, force_blockchain
API_V1_LIST_BLOCKCHAIN_STATE_URL = '/api/v1/blockchain-states-meta/'
def test_memory_blockchain_supported(api_client, memory_blockchain, primary... | [
"django.test.override_settings",
"thenewboston_node.business_logic.tests.base.as_primary_validator",
"thenewboston_node.business_logic.tests.base.force_blockchain"
] | [((351, 386), 'thenewboston_node.business_logic.tests.base.force_blockchain', 'force_blockchain', (['memory_blockchain'], {}), '(memory_blockchain)\n', (367, 386), False, 'from thenewboston_node.business_logic.tests.base import as_primary_validator, force_blockchain\n'), ((729, 789), 'thenewboston_node.business_logic.t... |
"""
GenBank format (:mod:`skbio.io.format.genbank`)
===============================================
.. currentmodule:: skbio.io.format.genbank
GenBank format (GenBank Flat File Format) stores sequence and its annotation
together. The start of the annotation section is marked by a line beginning
with the word "LOCUS".... | [
"pandas.Series",
"re.split",
"skbio.io.create_format",
"skbio.io.GenBankFormatError",
"datetime.datetime.strptime",
"skbio.io.format._base._too_many_blanks",
"re.match",
"skbio.util._misc.chunk_str",
"skbio.io.format._base._line_generator",
"numpy.zeros",
"functools.partial",
"pandas.concat",
... | [((10740, 10764), 'skbio.io.create_format', 'create_format', (['"""genbank"""'], {}), "('genbank')\n", (10753, 10764), False, 'from skbio.io import create_format, GenBankFormatError\n'), ((11287, 11310), 'skbio.io.format._base._too_many_blanks', '_too_many_blanks', (['fh', '(5)'], {}), '(fh, 5)\n', (11303, 11310), Fals... |
import theano
import theano.tensor as T
import lasagne as nn
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
class SpatialDropoutLayer(Layer):
"""Spatial dropout layer
Sets whole filter activations to zero with probability p. See notes for
disabling dropout during testing.
Paramet... | [
"theano.tensor.constant"
] | [((2230, 2243), 'theano.tensor.constant', 'T.constant', (['(1)'], {}), '(1)\n', (2240, 2243), True, 'import theano.tensor as T\n')] |
__author__ = 'dave'
from django.shortcuts import render
def ajax(request, ajax_code):
return render(request=request, template_name="hes/ajax/%s.html" % ajax_code, context={})
def coming_soon(request):
return render(request=request, template_name="hes/coming-soon.html", context={})
| [
"django.shortcuts.render"
] | [((98, 183), 'django.shortcuts.render', 'render', ([], {'request': 'request', 'template_name': "('hes/ajax/%s.html' % ajax_code)", 'context': '{}'}), "(request=request, template_name='hes/ajax/%s.html' % ajax_code,\n context={})\n", (104, 183), False, 'from django.shortcuts import render\n'), ((218, 291), 'django.sh... |
"""
__author__ = "<NAME>"
__copyright__ = "Copyright (C) 2018 <NAME>"
__licence__ = "MIT"
__version = "0.1"
"""
# -*- coding:utf-8 -*-
from __future__ import print_function, unicode_literals, division
from chainer import serializers
from vgg import VggCNN6
def save(model_file_name, net=None):
if not net:
... | [
"chainer.serializers.load_npz",
"vgg.VggCNN6",
"chainer.serializers.save_npz"
] | [((343, 404), 'chainer.serializers.save_npz', 'serializers.save_npz', (["('./saved_model/' + model_file_name)", 'net'], {}), "('./saved_model/' + model_file_name, net)\n", (363, 404), False, 'from chainer import serializers\n'), ((446, 455), 'vgg.VggCNN6', 'VggCNN6', ([], {}), '()\n', (453, 455), False, 'from vgg impor... |
import discord
import os
from discord.ext import commands
from AVARON_func import *
bot = commands.Bot(command_prefix='/')
token = os.environ['DISCORD_BOT_TOKEN']
CHANNEL_ID = 706355172301078577
STATUS_CHANNEL_ID = 707196746824024074
@bot.event
async def on_ready():
"""起動時に通知してくれる処理"""
print('ログ... | [
"discord.ext.commands.Bot",
"discord.ext.commands.dm_only",
"discord.Game"
] | [((96, 128), 'discord.ext.commands.Bot', 'commands.Bot', ([], {'command_prefix': '"""/"""'}), "(command_prefix='/')\n", (108, 128), False, 'from discord.ext import commands\n'), ((5558, 5576), 'discord.ext.commands.dm_only', 'commands.dm_only', ([], {}), '()\n', (5574, 5576), False, 'from discord.ext import commands\n'... |
#!/usr/bin/env python
import sys
import serial
import time
import os.path
import cv2 as cv
import numpy as np
# load image
def load(file):
img = cv.imread(file, 1)
return cv.GaussianBlur(img, (11, 11), 5)
# black image at the size of im
def black(im):
return np.zeros(im.shape[0:2], np.uint8)
# taken f... | [
"time.sleep",
"numpy.array",
"sys.exit",
"numpy.histogram",
"cv2.contourArea",
"cv2.minAreaRect",
"numpy.hypot",
"cv2.drawContours",
"cv2.boxPoints",
"cv2.minEnclosingCircle",
"numpy.int0",
"cv2.morphologyEx",
"cv2.cvtColor",
"cv2.GaussianBlur",
"cv2.imread",
"cv2.imwrite",
"cv2.inRa... | [((151, 169), 'cv2.imread', 'cv.imread', (['file', '(1)'], {}), '(file, 1)\n', (160, 169), True, 'import cv2 as cv\n'), ((181, 214), 'cv2.GaussianBlur', 'cv.GaussianBlur', (['img', '(11, 11)', '(5)'], {}), '(img, (11, 11), 5)\n', (196, 214), True, 'import cv2 as cv\n'), ((275, 308), 'numpy.zeros', 'np.zeros', (['im.sha... |
import os
from robustness import datasets, model_utils
from torchvision import models
from torchvision.datasets import CIFAR100
import torch as ch
from . import constants as cs
from . import fine_tunify
from .custom_models.vision_transformer import *
pytorch_models = {
'alexnet': models.alexnet,
'vgg16': mod... | [
"os.path.join",
"os.path.isfile",
"robustness.datasets.ImageNet",
"robustness.model_utils.make_and_restore_model",
"robustness.datasets.CIFAR"
] | [((4175, 4239), 'os.path.join', 'os.path.join', (['args.out_dir', 'args.exp_name', 'args.resume_ckpt_name'], {}), '(args.out_dir, args.exp_name, args.resume_ckpt_name)\n', (4187, 4239), False, 'import os\n'), ((1297, 1325), 'robustness.datasets.ImageNet', 'datasets.ImageNet', (['args.data'], {}), '(args.data)\n', (1314... |
#!/usr/bin/env python3
"""Provides the ability to find IPv4 ASCOM Alpaca servers on the local networks.
Uses the netifaces library to find the broadcast IPs that can be used for
sending the UDP discovery message.
Note that I've chosen to omit support for IPv6 because I don't need it for
testing Tiny Alpaca Server.
T... | [
"json.loads",
"argparse.ArgumentParser",
"socket.socket",
"pprint.pprint",
"time.sleep",
"netifaces.ifaddresses",
"install_advice.install_advice",
"queue.Queue",
"netifaces.interfaces",
"time.time",
"threading.Thread"
] | [((3901, 3923), 'netifaces.interfaces', 'netifaces.interfaces', ([], {}), '()\n', (3921, 3923), False, 'import netifaces\n'), ((8492, 8517), 'queue.Queue', 'queue.Queue', ([], {'maxsize': '(1000)'}), '(maxsize=1000)\n', (8503, 8517), False, 'import queue\n'), ((8732, 8743), 'time.time', 'time.time', ([], {}), '()\n', (... |
from gi.repository import Gtk, GLib
from typing import Callable, Sequence, Dict, Optional, Any, Iterator
from concurrent.futures import Future, ThreadPoolExecutor, as_completed
RowInitCallback = Callable[[Gtk.TreeModelRow], None]
RowLoadCallback = Callable[[Gtk.TreeModelRow], Gtk.TreeModelRow]
RowHashCallback = Calla... | [
"concurrent.futures.as_completed",
"concurrent.futures.ThreadPoolExecutor"
] | [((1256, 1276), 'concurrent.futures.ThreadPoolExecutor', 'ThreadPoolExecutor', ([], {}), '()\n', (1274, 1276), False, 'from concurrent.futures import Future, ThreadPoolExecutor, as_completed\n'), ((2592, 2618), 'concurrent.futures.as_completed', 'as_completed', (['self.futures'], {}), '(self.futures)\n', (2604, 2618), ... |
from base import app,c
import unittest
class baseTestCase(unittest.TestCase):
email = 'email@<EMAIL>'
password = 'password'
admin = '/admin'
login = '/login'
logout = '/logout'
def setUp(self):
'''Setup test variables and remove form CSRF for easy submission'''
app.testing = T... | [
"unittest.main",
"base.app.test_client"
] | [((1992, 2007), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2005, 2007), False, 'import unittest\n'), ((471, 488), 'base.app.test_client', 'app.test_client', ([], {}), '()\n', (486, 488), False, 'from base import app, c\n')] |
# encoding: UTF-8
import unittest
import sys
from time import sleep
from datetime import datetime
from qtpy.QtCore import QCoreApplication
from hsstock.vnpy.event.event_engine import EventEngine2
from hsstock.vnpy.event.event_type import *
class EventEngineTestCase(unittest.TestCase):
@classmethod
def setU... | [
"hsstock.vnpy.event.event_engine.EventEngine2",
"time.sleep",
"datetime.datetime.now",
"unittest.skip",
"qtpy.QtCore.QCoreApplication"
] | [((540, 579), 'unittest.skip', 'unittest.skip', (['"""demonstrating skipping"""'], {}), "('demonstrating skipping')\n", (553, 579), False, 'import unittest\n'), ((955, 994), 'unittest.skip', 'unittest.skip', (['"""demonstrating skipping"""'], {}), "('demonstrating skipping')\n", (968, 994), False, 'import unittest\n'),... |
import functools
import click
from ..arguments import commands_argument, run_file_option
def run_command(f):
@commands_argument
@run_file_option
@functools.wraps(f)
def wrapper(*args, commands, run_file, **kwargs):
if run_file:
run_options = run_file.data
else:
run_options = {}
if n... | [
"click.UsageError",
"functools.wraps"
] | [((157, 175), 'functools.wraps', 'functools.wraps', (['f'], {}), '(f)\n', (172, 175), False, 'import functools\n'), ((425, 558), 'click.UsageError', 'click.UsageError', (['"""Missing command: Please specify your run command via arguments or in the \'run\' section of the run file."""'], {}), '(\n "Missing command: Pl... |
import sys
import os
def wget( address, target ):
print('wget ' + address + ' -O ' + target)
version = sys.version_info
if not os.path.exists("./data"):
os.mkdir("./data")
if version[0] == 2:
import urllib
urllib.urlretrieve(address, target)
elif version[0] == 3:
imp... | [
"urllib.urlretrieve",
"os.path.exists",
"os.mkdir",
"urllib.request.urlretrieve"
] | [((140, 164), 'os.path.exists', 'os.path.exists', (['"""./data"""'], {}), "('./data')\n", (154, 164), False, 'import os\n'), ((174, 192), 'os.mkdir', 'os.mkdir', (['"""./data"""'], {}), "('./data')\n", (182, 192), False, 'import os\n'), ((247, 282), 'urllib.urlretrieve', 'urllib.urlretrieve', (['address', 'target'], {}... |
import math
def degrees_clockwise(dy, dx):
''' returns rotation degrees assuming 0 is 12 o'clock '''
radians = math.atan2(dy, dx) # between -pi and pi
degrees = radians * 180/math.pi
if degrees > 90:
degrees = 450 - degrees
else:
degrees = 90 - degrees
return degrees
def angle(... | [
"math.sqrt",
"math.atan2"
] | [((120, 138), 'math.atan2', 'math.atan2', (['dy', 'dx'], {}), '(dy, dx)\n', (130, 138), False, 'import math\n'), ((396, 414), 'math.atan2', 'math.atan2', (['dy', 'dx'], {}), '(dy, dx)\n', (406, 414), False, 'import math\n'), ((472, 512), 'math.sqrt', 'math.sqrt', (['(side1 * side1 + side2 * side2)'], {}), '(side1 * sid... |
"""
<NAME>
camera.py
Construct a camera matrix and apply it to project points onto an image plane.
___
/ _ \
| / \ |
| \_/ |
\___/ ___
_|_|_/[_]\__==_
... | [
"numpy.asmatrix",
"numpy.sin",
"numpy.asarray",
"numpy.argmax",
"numpy.min",
"numpy.max",
"numpy.matmul",
"numpy.vstack",
"numpy.cos",
"sys.exit",
"numpy.argmin",
"numpy.loadtxt"
] | [((2010, 2058), 'numpy.asmatrix', 'np.asmatrix', (['[[s, 0, ic], [0, s, jc], [0, 0, 1]]'], {}), '([[s, 0, ic], [0, s, jc], [0, 0, 1]])\n', (2021, 2058), True, 'import numpy as np\n'), ((3232, 3249), 'numpy.matmul', 'np.matmul', (['Rx', 'Ry'], {}), '(Rx, Ry)\n', (3241, 3249), True, 'import numpy as np\n'), ((3258, 3274)... |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Interfaces under evaluation before upstreaming to nipype.interfaces.utility."""
import numpy as np
import re
import json
from collections import OrderedDict
from nipype.utils.filemanip import fname_pres... | [
"nipype.interfaces.base.InputMultiObject",
"nipype.interfaces.base.isdefined",
"nipype.utils.filemanip.fname_presuffix",
"nipype.interfaces.base.traits.Instance",
"nipype.interfaces.base.traits.Str",
"pandas.read_csv",
"nipype.interfaces.io.add_traits",
"nipype.interfaces.base.traits.List",
"nipype.... | [((645, 686), 'nipype.interfaces.base.Str', 'Str', ([], {'mandatory': '(True)', 'desc': '"""selective key"""'}), "(mandatory=True, desc='selective key')\n", (648, 686), False, 'from nipype.interfaces.base import BaseInterface, BaseInterfaceInputSpec, DynamicTraitedSpec, File, InputMultiObject, isdefined, SimpleInterfac... |
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
import os
import sys
sys.path.insert(0, os.path.abspath('../..'))
import j... | [
"os.path.abspath"
] | [((285, 309), 'os.path.abspath', 'os.path.abspath', (['"""../.."""'], {}), "('../..')\n", (300, 309), False, 'import os\n')] |
# Add parent folder to path
import sys, os
sys.path.insert(1, os.path.join(sys.path[0], '..'))
import unittest
import numpy as np
from src.Equations.KineticEnergy import KineticEnergy
from src.Common import particle_dtype
class test_kinetic_energy(unittest.TestCase):
def test(self):
num = 100
pA =... | [
"numpy.zeros",
"os.path.join"
] | [((62, 93), 'os.path.join', 'os.path.join', (['sys.path[0]', '""".."""'], {}), "(sys.path[0], '..')\n", (74, 93), False, 'import sys, os\n'), ((321, 356), 'numpy.zeros', 'np.zeros', (['num'], {'dtype': 'particle_dtype'}), '(num, dtype=particle_dtype)\n', (329, 356), True, 'import numpy as np\n')] |
#-------------------------------------------------------------------------------
#
# Define classes for (uni/multi)-variate kernel density estimation.
#
# Currently, only Gaussian kernels are implemented.
#
# Copyright 2004-2005 by Enthought, Inc.
#
# The code has been adapted by <NAME> to work with GPUs
# using C... | [
"numpy.sqrt",
"math.floor",
"numpy.hstack",
"dataclasses.dataclass",
"cocos.numerics.numerical_package_selector.select_num_pack",
"numpy.array",
"numpy.cov",
"scipy.special.logsumexp",
"numpy.atleast_2d",
"scipy.linalg.cho_solve",
"numpy.reshape",
"numpy.isscalar",
"scipy.linalg.cho_factor",... | [((13173, 13195), 'dataclasses.dataclass', 'dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (13182, 13195), False, 'from dataclasses import dataclass\n'), ((6335, 6355), 'cocos.numerics.numerical_package_selector.select_num_pack', 'select_num_pack', (['gpu'], {}), '(gpu)\n', (6350, 6355), False, 'from cocos.... |
import sys
import os
sys.path.append(os.getcwd())
from training_structures.unimodal import train, test
from datasets.mimic.get_data import get_dataloader
from unimodals.common_models import MLP, GRUWithLinear
from torch import nn
import torch
#get dataloader for icd9 classification task 7
traindata, validdata, testdat... | [
"training_structures.unimodal.test",
"torch.load",
"os.getcwd",
"datasets.mimic.get_data.get_dataloader",
"unimodals.common_models.GRUWithLinear",
"training_structures.unimodal.train",
"unimodals.common_models.MLP"
] | [((324, 378), 'datasets.mimic.get_data.get_dataloader', 'get_dataloader', (['(1)'], {'imputed_path': '"""datasets/mimic/im.pk"""'}), "(1, imputed_path='datasets/mimic/im.pk')\n", (338, 378), False, 'from datasets.mimic.get_data import get_dataloader\n'), ((623, 701), 'training_structures.unimodal.train', 'train', (['en... |
from os import rename, listdir
import os
path = os.getcwd()
from os.path import isfile, join
import re
def change_names_dir(dir_name, path):
os.chdir(dir_name)
filenames = [f for f in listdir(dir_name) if isfile(join(dir_name, f))]
change_names(filenames)
os.chdir(path)
def create_label_names(dir_name... | [
"os.listdir",
"os.path.join",
"os.getcwd",
"os.chdir",
"re.sub"
] | [((48, 59), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (57, 59), False, 'import os\n'), ((146, 164), 'os.chdir', 'os.chdir', (['dir_name'], {}), '(dir_name)\n', (154, 164), False, 'import os\n'), ((273, 287), 'os.chdir', 'os.chdir', (['path'], {}), '(path)\n', (281, 287), False, 'import os\n'), ((340, 358), 'os.chdir'... |
from rest_framework import serializers
from .models import City, ForecastDate
import datetime
class UserInputCitySerializer(serializers.Serializer):
city_name = serializers.CharField(max_length=200, default='')
iso_country_code = serializers.CharField(max_length=2, default='')
required_date_search = seria... | [
"rest_framework.serializers.DateField",
"rest_framework.serializers.ValidationError",
"datetime.date.today",
"rest_framework.serializers.CharField",
"datetime.timedelta"
] | [((167, 216), 'rest_framework.serializers.CharField', 'serializers.CharField', ([], {'max_length': '(200)', 'default': '""""""'}), "(max_length=200, default='')\n", (188, 216), False, 'from rest_framework import serializers\n'), ((240, 287), 'rest_framework.serializers.CharField', 'serializers.CharField', ([], {'max_le... |
import speech_recognition as sr
for index, name in enumerate(sr.Microphone.list_microphone_names()):
print("Microphone with name \"{1}\" found for `Microphone(device_index={0})`".format(index, name)) | [
"speech_recognition.Microphone.list_microphone_names"
] | [((61, 98), 'speech_recognition.Microphone.list_microphone_names', 'sr.Microphone.list_microphone_names', ([], {}), '()\n', (96, 98), True, 'import speech_recognition as sr\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
功能实现:从列表中返回一个随机元素。
解读:
使用random.choice()从lst中获取一个随机元素
"""
from random import choice
def sample(lst):
return choice(lst)
# Examples
print(sample([3, 7, 9, 11]))
# output:
# 9
| [
"random.choice"
] | [((165, 176), 'random.choice', 'choice', (['lst'], {}), '(lst)\n', (171, 176), False, 'from random import choice\n')] |
"""
@Author: <NAME>
@Description: The C/Python API allows for the exporting of functions, but exporting
objects can be very difficult. To bypass this, this file provides a Python object
oriented interface for the functions contained in cryptolight.cpp
"""
import CryptoLightFunctions
import random, string, time, sys
f... | [
"random.choice",
"Cryptodome.Random.get_random_bytes",
"CryptoLightFunctions.generateKey",
"time.sleep",
"Cryptodome.Cipher.AES.new",
"Cryptodome.Util.Padding.pad",
"time.time"
] | [((3129, 3140), 'time.time', 'time.time', ([], {}), '()\n', (3138, 3140), False, 'import random, string, time, sys\n'), ((3313, 3324), 'time.time', 'time.time', ([], {}), '()\n', (3322, 3324), False, 'import random, string, time, sys\n'), ((664, 698), 'CryptoLightFunctions.generateKey', 'CryptoLightFunctions.generateKe... |
from django.contrib.auth.models import User
from Picturedom.photo.models import Category, Photo
from django.test import TestCase
from django.core.files.uploadedfile import SimpleUploadedFile
from django.urls import reverse
class TestAddCommentView(TestCase):
def setUp(self):
self.user = User.objects.creat... | [
"django.urls.reverse",
"django.core.files.uploadedfile.SimpleUploadedFile",
"django.contrib.auth.models.User.objects.create_user",
"Picturedom.photo.models.Category.objects.create"
] | [((302, 357), 'django.contrib.auth.models.User.objects.create_user', 'User.objects.create_user', (['"""user"""', '"""email"""', '"""<PASSWORD>"""'], {}), "('user', 'email', '<PASSWORD>')\n", (326, 357), False, 'from django.contrib.auth.models import User\n'), ((382, 423), 'Picturedom.photo.models.Category.objects.creat... |
import numpy as np
def schlawin(x):
a1 = 0.44325141463
a2 = 0.06260601220
a3 = 0.04757383546
a4 = 0.01736506451
b1 = 0.24998368310
b2 = 0.09200180037
b3 = 0.04069697526
b4 = 0.00526449639
return 1 + x*(a1 + x*(a2 + x*(a3 + x*a4))) + x*(b1 + x*(b2 + x*(b3 + x*b4)))*np.log(1/x)
| [
"numpy.log"
] | [((302, 315), 'numpy.log', 'np.log', (['(1 / x)'], {}), '(1 / x)\n', (308, 315), True, 'import numpy as np\n')] |
import logging
import math
import gym
from gym import spaces
from gym.utils import seeding
import numpy as np
import sys
import cv2
import math
from sklearn.metrics import accuracy_score, f1_score
class ClassifyEnv(gym.Env):
"""Classification as an unsupervised OpenAI Gym RL problem.
Includes scikit-learn digits d... | [
"cv2.resize",
"pandas.read_csv",
"domain.text_vectorizers.BiLSTMVectorizer",
"sklearn.model_selection.train_test_split",
"scipy.signal.spectrogram",
"numpy.argmax",
"numpy.array",
"numpy.sum",
"scipy.io.wavfile.read",
"numpy.empty",
"domain.text_vectorizers.ASCIIVectorizer",
"domain.text_vecto... | [((2937, 2980), 'pandas.read_csv', 'pd.read_csv', (['"""data/spam_classify/train.csv"""'], {}), "('data/spam_classify/train.csv')\n", (2948, 2980), True, 'import pandas as pd\n'), ((4135, 4173), 'pandas.read_csv', 'pd.read_csv', (['"""data/sen_imdb/train.csv"""'], {}), "('data/sen_imdb/train.csv')\n", (4146, 4173), Tru... |
from rest_framework.views import APIView
from rest_framework.response import Response
from .serializers import OrderSerializer
from .schemas import (
InventoryByStatusSchema,
OrderSchema,
OrderIDSchema,
InvalidInputSchema,
NotFoundSchema,
)
class InventoryAPI(APIView):
summary = "Returns toy ... | [
"rest_framework.response.Response"
] | [((445, 457), 'rest_framework.response.Response', 'Response', (['{}'], {}), '({})\n', (453, 457), False, 'from rest_framework.response import Response\n'), ((716, 728), 'rest_framework.response.Response', 'Response', (['{}'], {}), '({})\n', (724, 728), False, 'from rest_framework.response import Response\n'), ((1193, 1... |
#
# Copyright (c) 2021, NVIDIA CORPORATION. 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 appl... | [
"tensorrt.IInt8EntropyCalibrator2.__init__",
"pycuda.driver.mem_alloc",
"os.path.exists",
"pycuda.driver.memcpy_htod"
] | [((2021, 2063), 'tensorrt.IInt8EntropyCalibrator2.__init__', 'trt.IInt8EntropyCalibrator2.__init__', (['self'], {}), '(self)\n', (2057, 2063), True, 'import tensorrt as trt\n'), ((2422, 2475), 'pycuda.driver.mem_alloc', 'cuda.mem_alloc', (['(self.data[0].nbytes * self.batch_size)'], {}), '(self.data[0].nbytes * self.ba... |
#!/usr/bin/env python2
from __future__ import print_function
import sys
import os
import time
global_server_list = ['172.16.17.32', '192.168.127.12', '172.16.58.3', '172.16.58.3', '172.16.58.3', '192.168.127.12', '192.168.3.11', '192.168.127.12', '172.16.58.3', '172.16.31.10', '172.16.58.3', '192.168.3.11', '192.168.3... | [
"os.system",
"sys.stdout.flush",
"time.sleep"
] | [((714, 732), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (730, 732), False, 'import sys\n'), ((797, 815), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (813, 815), False, 'import sys\n'), ((879, 897), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (895, 897), False, 'import sys\n')... |
import json
import requests
from six import integer_types, iteritems
from six.moves import xrange
import strongarm
class StrongarmException(Exception):
"""
An error occured in stronglib.
"""
class StrongarmHttpError(StrongarmException):
"""
The strongarm.io API responded with an HTTP error co... | [
"json.dumps",
"six.iteritems",
"requests.request"
] | [((1733, 1777), 'requests.request', 'requests.request', (['method', 'endpoint'], {}), '(method, endpoint, **kwargs)\n', (1749, 1777), False, 'import requests\n'), ((5500, 5524), 'six.iteritems', 'iteritems', (['self.__dict__'], {}), '(self.__dict__)\n', (5509, 5524), False, 'from six import integer_types, iteritems\n')... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2019 The FATE 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/licens... | [
"federatedml.protobuf.generated.onehot_param_pb2.ColsMap",
"federatedml.param.onehot_encoder_param.OneHotEncoderParam",
"federatedml.protobuf.generated.onehot_param_pb2.OneHotParam",
"numpy.array",
"arch.api.utils.log_utils.getLogger",
"federatedml.statistic.data_overview.get_header",
"functools.partial... | [((1031, 1052), 'arch.api.utils.log_utils.getLogger', 'log_utils.getLogger', ([], {}), '()\n', (1050, 1052), False, 'from arch.api.utils import log_utils\n'), ((3866, 3886), 'federatedml.param.onehot_encoder_param.OneHotEncoderParam', 'OneHotEncoderParam', ([], {}), '()\n', (3884, 3886), False, 'from federatedml.param.... |
# -*- coding: utf-8 -*-
"""
Author: <NAME>
Lab: Large Scale Hydrology research group - UFRGS\Brazil
"""
import folium
import ee
import webbrowser
class Map(object):
def __init__(self,center=[0, 0],zoom=3):
self._map = folium.Map(location=center,zoom_start=zoom)
return
def add... | [
"folium.GeoJson",
"folium.WmsTileLayer",
"webbrowser.open",
"folium.Map",
"folium.Marker",
"folium.map.LayerControl"
] | [((246, 290), 'folium.Map', 'folium.Map', ([], {'location': 'center', 'zoom_start': 'zoom'}), '(location=center, zoom_start=zoom)\n', (256, 290), False, 'import folium\n'), ((1521, 1548), 'webbrowser.open', 'webbrowser.open', (['"""Map.html"""'], {}), "('Map.html')\n", (1536, 1548), False, 'import webbrowser\n'), ((139... |
#
# spyne - Copyright (C) Spyne contributors.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This libra... | [
"logging.getLogger",
"json.loads",
"shutil.move",
"lxml.html.tostring",
"lxml.html.fromstring",
"os.path.join",
"os.access",
"json.dumps",
"uuid.uuid1",
"spyne.util.xml.get_object_as_xml",
"os.path.isfile",
"os.path.basename",
"lxml.etree.fromstring",
"shutil.copy",
"os.path.abspath",
... | [((799, 826), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (816, 826), False, 'import logging\n'), ((2359, 2464), 'lxml.etree.tostring', 'etree.tostring', (['value'], {'pretty_print': 'self.pretty_print', 'encoding': 'self.encoding', 'xml_declaration': '(False)'}), '(value, pretty_print... |
import pandas as pd
import pytz
def load_data(path):
"""
ARGS: path to the local .csv file
Load data and search for the Date_Time column to index the dataframe by a datetime value.
"""
data = pd.read_csv(path,delimiter=";") # , engine='python')
data["Date_Time"] = pd.to_datetime(data["Date_... | [
"pytz.timezone",
"pandas.to_datetime",
"pandas.read_csv"
] | [((216, 248), 'pandas.read_csv', 'pd.read_csv', (['path'], {'delimiter': '""";"""'}), "(path, delimiter=';')\n", (227, 248), True, 'import pandas as pd\n'), ((294, 327), 'pandas.to_datetime', 'pd.to_datetime', (["data['Date_Time']"], {}), "(data['Date_Time'])\n", (308, 327), True, 'import pandas as pd\n'), ((386, 420),... |
# 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 or agreed to in writing, ... | [
"pandas.DataFrame.from_records",
"lib.data_source.DataSource",
"unittest.main"
] | [((782, 3021), 'pandas.DataFrame.from_records', 'DataFrame.from_records', (["[{'key': 'AA', 'country_code': 'AA', 'subregion1_code': None,\n 'subregion2_code': None, 'match_string': None}, {'key': 'AB',\n 'country_code': 'AB', 'subregion1_code': None, 'subregion2_code': None,\n 'match_string': None}, {'key': '... |
#Copyright 2020 ModEngineer
#
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, softwa... | [
"warnings.warn",
"copy.deepcopy"
] | [((8271, 8293), 'copy.deepcopy', 'deepcopy', (['outGraphs[0]'], {}), '(outGraphs[0])\n', (8279, 8293), False, 'from copy import deepcopy\n'), ((8418, 8440), 'copy.deepcopy', 'deepcopy', (['outGraphs[1]'], {}), '(outGraphs[1])\n', (8426, 8440), False, 'from copy import deepcopy\n'), ((8791, 8810), 'copy.deepcopy', 'deep... |
import os
import argparse
import random
import numpy as np
import torch
from torch.utils.data import DataLoader, Dataset
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, AutoConfig
from transformers.optimization import get_linear_schedule_with_warmup, Adafactor
import nlp
from rouge_score import rouge_sc... | [
"torch.nn.CrossEntropyLoss",
"torch.nn.utils.rnn.pad_sequence",
"torch.cuda.device_count",
"torch.utils.data.distributed.DistributedSampler",
"torch.cuda.is_available",
"transformers.AutoTokenizer.from_pretrained",
"nlp.load_dataset",
"transformers.optimization.get_linear_schedule_with_warmup",
"arg... | [((15429, 15451), 'random.seed', 'random.seed', (['args.seed'], {}), '(args.seed)\n', (15440, 15451), False, 'import random\n'), ((15456, 15481), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (15470, 15481), True, 'import numpy as np\n'), ((15486, 15514), 'torch.manual_seed', 'torch.manua... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import pandas as pd
import math
def moving_average(a, n=7) :
ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n
#leitura de dados e montagem dos arrays para plotagem:
df = pd.read_exc... | [
"matplotlib.pyplot.grid",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.figure",
"matplotlib.patches.Patch",
"pandas.read_excel",
"pandas.DataFrame",
"numpy.cumsum",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show"
] | [((309, 336), 'pandas.read_excel', 'pd.read_excel', (['"""dados.xlsx"""'], {}), "('dados.xlsx')\n", (322, 336), True, 'import pandas as pd\n'), ((1952, 1965), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (1962, 1965), True, 'import matplotlib.pyplot as plt\n'), ((1979, 2034), 'matplotlib.patches.Pa... |
import copy
from .graph import Graph
'''
单源最短路
一次性得到单个点到全部点的最短路径
广度优先搜索
'''
class Dijkstra(Graph):
def __init__(self, size=10, graph=None):
super().__init__(size=size, graph=graph)
self.result = copy.deepcopy(self.graph)
def shortest_path(self, start=None, end=None):
S = {start: 0... | [
"copy.deepcopy"
] | [((221, 246), 'copy.deepcopy', 'copy.deepcopy', (['self.graph'], {}), '(self.graph)\n', (234, 246), False, 'import copy\n')] |
import sys
sys.path.append('./scripts')
from scripts.ExpStats import runExpWithName
from scripts.Nader import genSourceExp, runOnlyNader
from scripts.Nader import runNader
from scripts.ResultPresenter import genFig5, genFig9, genFig8
import subprocess
import os
import filecmp
import shutil
import argparse
from tqdm.aut... | [
"scripts.Nader.genSourceExp",
"scripts.Nader.runOnlyNader",
"sys.path.append",
"os.path.exists",
"argparse.ArgumentParser",
"scripts.ExpStats.runExpWithName",
"shutil.move",
"subprocess.Popen",
"subprocess.run",
"scripts.ResultPresenter.genFig5",
"os.mkdir",
"scripts.Nader.runNader",
"script... | [((11, 39), 'sys.path.append', 'sys.path.append', (['"""./scripts"""'], {}), "('./scripts')\n", (26, 39), False, 'import sys\n'), ((363, 389), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (379, 389), False, 'import os\n'), ((474, 606), 'subprocess.run', 'subprocess.run', (["['find', direc... |
"""
The flask application package.
"""
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
app = Flask(__name__)
app.config['SECRET_KEY'] = '<KEY>'
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:testing@localhost:5432/flaskproject'
app.config['SQLALCHEMY... | [
"flask_sqlalchemy.SQLAlchemy",
"flask_migrate.Migrate",
"flask.Flask"
] | [((145, 160), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (150, 160), False, 'from flask import Flask\n'), ((358, 373), 'flask_sqlalchemy.SQLAlchemy', 'SQLAlchemy', (['app'], {}), '(app)\n', (368, 373), False, 'from flask_sqlalchemy import SQLAlchemy\n'), ((385, 401), 'flask_migrate.Migrate', 'Migrate',... |
# Generated by Django 3.2.5 on 2021-08-11 09:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('socialaccount', '0003_extra_data_default_dict'),
]
operations = [
migrations.AddField(
model_name='socialaccount',
n... | [
"django.db.migrations.AlterUniqueTogether",
"django.db.models.CharField"
] | [((455, 569), 'django.db.migrations.AlterUniqueTogether', 'migrations.AlterUniqueTogether', ([], {'name': '"""socialaccount"""', 'unique_together': "{('provider', 'uid', 'simulationtype')}"}), "(name='socialaccount', unique_together={(\n 'provider', 'uid', 'simulationtype')})\n", (485, 569), False, 'from django.db i... |
import sqlite3
from ObjetoArtista import Artista
def showArt():
try:
conexion = sqlite3.connect('musicBrainzDB.db')
cursor = conexion.cursor()
uMostrar = cursor.execute("SELECT * from Artistas").fetchall()
Art = []
for u in uMostrar:
u = Artista(id=u[0],area=u[1... | [
"ObjetoArtista.Artista",
"sqlite3.connect"
] | [((93, 128), 'sqlite3.connect', 'sqlite3.connect', (['"""musicBrainzDB.db"""'], {}), "('musicBrainzDB.db')\n", (108, 128), False, 'import sqlite3\n'), ((685, 720), 'sqlite3.connect', 'sqlite3.connect', (['"""musicBrainzDB.db"""'], {}), "('musicBrainzDB.db')\n", (700, 720), False, 'import sqlite3\n'), ((296, 386), 'Obje... |
from django.db.models.signals import post_save
from .models import Comment
from notifications.signals import notify
from django.conf import settings
from django.apps import apps
from .tasks import email_handler
def get_recipient():
admins = [i[0] for i in settings.ADMINS]
app_model = settings.AUTH_USER_MODEL.... | [
"django.db.models.signals.post_save.connect",
"notifications.signals.notify.send",
"django.apps.apps.get_model",
"django.conf.settings.AUTH_USER_MODEL.split"
] | [((2141, 2191), 'django.db.models.signals.post_save.connect', 'post_save.connect', (['comment_handler'], {'sender': 'Comment'}), '(comment_handler, sender=Comment)\n', (2158, 2191), False, 'from django.db.models.signals import post_save\n'), ((295, 330), 'django.conf.settings.AUTH_USER_MODEL.split', 'settings.AUTH_USER... |
import asyncio
import unittest
from types import ModuleType
from common import *
class TestArtist(unittest.TestCase):
@async_with_client(SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET)
async def test_artist(self, *, client):
for artist_uri in TEST_ARTISTS:
artist = await client.get_artist(artis... | [
"unittest.main"
] | [((602, 617), 'unittest.main', 'unittest.main', ([], {}), '()\n', (615, 617), False, 'import unittest\n')] |
import unittest
import os
import numpy as np
import sys
import torch
import matplotlib.pyplot as plt
# Add .. to the PYTHONPATH
sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir))
import lilfilter.filters as F
import lilfilter.torch_filter as T
class TestTorchFilter(unittest.TestCase):
def te... | [
"matplotlib.pyplot.show",
"lilfilter.torch_filter.SymmetricFirFilter",
"os.path.dirname",
"unittest.main",
"torch.randn",
"torch.arange",
"lilfilter.filters.gaussian_filter"
] | [((633, 648), 'unittest.main', 'unittest.main', ([], {}), '()\n', (646, 648), False, 'import unittest\n'), ((161, 186), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (176, 186), False, 'import os\n'), ((346, 368), 'lilfilter.filters.gaussian_filter', 'F.gaussian_filter', (['(5.0)'], {}), '(5... |
from import_export import resources
from import_export.admin import ImportExportActionModelAdmin
from django import forms
from django.conf.urls import url
from django.contrib import admin
from django.contrib import messages
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import... | [
"django.contrib.contenttypes.models.ContentType.objects.get_for_model",
"pyconcz_2017.proposals.models.Ranking",
"pyconcz_2017.proposals.models.Ranking.objects.filter",
"django.template.response.TemplateResponse",
"django.contrib.admin.site.register",
"django.db.models.Avg",
"django.core.urlresolvers.re... | [((7988, 8024), 'django.contrib.admin.site.register', 'admin.site.register', (['Talk', 'TalkAdmin'], {}), '(Talk, TalkAdmin)\n', (8007, 8024), False, 'from django.contrib import admin\n'), ((8025, 8069), 'django.contrib.admin.site.register', 'admin.site.register', (['Workshop', 'WorkshopAdmin'], {}), '(Workshop, Worksh... |
import pytest
from custom_components.racelandshop.helpers.classes.exceptions import RacelandshopException
@pytest.mark.asyncio
async def test_async_post_installation(repository_integration, racelandshop):
await repository_integration.async_post_installation()
repository_integration.data.config_flow = True
... | [
"pytest.raises"
] | [((937, 973), 'pytest.raises', 'pytest.raises', (['RacelandshopException'], {}), '(RacelandshopException)\n', (950, 973), False, 'import pytest\n')] |
#!/usr/bin/env python
from __future__ import print_function
from __future__ import absolute_import
from numpy.random import RandomState
from numpy.random import mtrand
def randomu(seed, di=None, binomial=None, double=False, gamma=False,
normal=False, poisson=False):
"""
Replicates the randomu fun... | [
"numpy.random.RandomState"
] | [((5125, 5138), 'numpy.random.RandomState', 'RandomState', ([], {}), '()\n', (5136, 5138), False, 'from numpy.random import RandomState\n')] |
from unittest import TestCase
from unittest.mock import patch, call
from maintain_frontend.add_land_charge.validation.location_confirmation_validator import LocationConfirmationValidator
class TestLocationConfirmationValidator(TestCase):
@patch('maintain_frontend.add_land_charge.validation.location_confirmation_... | [
"maintain_frontend.add_land_charge.validation.location_confirmation_validator.LocationConfirmationValidator.validate",
"unittest.mock.call",
"unittest.mock.patch"
] | [((246, 364), 'unittest.mock.patch', 'patch', (['"""maintain_frontend.add_land_charge.validation.location_confirmation_validator.ValidationErrorBuilder"""'], {}), "(\n 'maintain_frontend.add_land_charge.validation.location_confirmation_validator.ValidationErrorBuilder'\n )\n", (251, 364), False, 'from unittest.mo... |
import pytest
from numpy.testing import assert_array_equal
from cloudnetpy.instruments import rpg
@pytest.fixture
def example_files(tmpdir):
file_names = ['f.LV1', 'f.txt', 'f.LV0', 'f.lv1', 'g.LV1']
folder = tmpdir.mkdir('data/')
for name in file_names:
with open(folder.join(name), 'wb') as f:
... | [
"pytest.raises",
"cloudnetpy.instruments.rpg.get_rpg_files",
"cloudnetpy.instruments.rpg._reduce_header",
"cloudnetpy.instruments.rpg._get_rpg_time"
] | [((530, 557), 'cloudnetpy.instruments.rpg.get_rpg_files', 'rpg.get_rpg_files', (['dir_name'], {}), '(dir_name)\n', (547, 557), False, 'from cloudnetpy.instruments import rpg\n'), ((1117, 1137), 'cloudnetpy.instruments.rpg._get_rpg_time', 'rpg._get_rpg_time', (['(0)'], {}), '(0)\n', (1134, 1137), False, 'from cloudnetpy... |
###########################################
# EXERCICIO 058 #
###########################################
'''MELHORE O EX028, ONDE O COMPUTADOR VAI PENSAR
EM UM NUMERO ENTRE 0 E 5. SÓ QUE AGORA O JOGADOR
VAI TENTAR ADIVINHAR ATÉ ACERTAR. MOSTRANDO NO
FINAL QUANTOS PALPITES FORAM NECESSARIOS'''... | [
"random.randint",
"time.sleep"
] | [((378, 392), 'random.randint', 'randint', (['(0)', '(10)'], {}), '(0, 10)\n', (385, 392), False, 'from random import randint\n'), ((953, 964), 'time.sleep', 'sleep', (['(0.25)'], {}), '(0.25)\n', (958, 964), False, 'from time import sleep\n')] |
from django.core.urlresolvers import reverse
from guardian.shortcuts import assign_perm, get_objects_for_user
from core.models import ServerRole
from core.tests.base import BaseModalTestCase, BaseModalTests, BaseForbiddenModalTests
from core.tests.fixtures import ServerRoleFactory, ApplicationFactory, EnvironmentFactor... | [
"core.models.ServerRole.objects.filter",
"core.tests.fixtures.ApplicationFactory",
"django.core.urlresolvers.reverse"
] | [((2665, 2710), 'core.tests.fixtures.ApplicationFactory', 'ApplicationFactory', ([], {'department': 'cls.department'}), '(department=cls.department)\n', (2683, 2710), False, 'from core.tests.fixtures import ServerRoleFactory, ApplicationFactory, EnvironmentFactory, ServerFactory\n'), ((3121, 3166), 'core.tests.fixtures... |
import os
import numpy as np
def get_all_file(filepath):
files = os.listdir(filepath)
file_list = []
for fi in files:
fi_d = os.path.join(filepath, fi)
if os.path.isdir(fi_d):
get_all_file(fi_d)
elif 'acc_' in fi_d:
# file_list.append(os.path.join(filepath, fi... | [
"os.listdir",
"numpy.reshape",
"os.path.join",
"os.path.isdir",
"numpy.concatenate"
] | [((69, 89), 'os.listdir', 'os.listdir', (['filepath'], {}), '(filepath)\n', (79, 89), False, 'import os\n'), ((1494, 1518), 'numpy.reshape', 'np.reshape', (['x_all', '(-1,)'], {}), '(x_all, (-1,))\n', (1504, 1518), True, 'import numpy as np\n'), ((1562, 1583), 'numpy.reshape', 'np.reshape', (['y_all', '(-1)'], {}), '(y... |
import colorsys
import json
import socket
import logging
from enum import Enum
from .decorator import decorator
from .flow import Flow
MUSIC_PORT = 37657
_LOGGER = logging.getLogger(__name__)
@decorator
def _command(f, *args, **kw):
"""
A decorator that wraps a function and enables effects.
"""
self... | [
"logging.getLogger",
"json.dumps",
"colorsys.hsv_to_rgb",
"socket.socket"
] | [((167, 194), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (184, 194), False, 'import logging\n'), ((12660, 12709), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (12673, 12709), False, 'import socket\n'), ((32... |
from resizeimage import resizeimage
from PIL import Image,ImageDraw
from skimage import measure
import matplotlib.pyplot as plt
import numpy as np
import cv2
import csv
import os
import sys
specs_path = "../level1specs/"
im_array = []
unique_symbols = ["=","E","=","C","C","F","P","?","C","#","-","P","P","P","#","?","=... | [
"PIL.Image.open",
"os.specs_path.splitext",
"cv2.cvtColor",
"skimage.measure.compare_ssim",
"resizeimage.resizeimage.resize_cover",
"cv2.imread"
] | [((1482, 1520), 'PIL.Image.open', 'Image.open', (['(folder_levels + level_name)'], {}), '(folder_levels + level_name)\n', (1492, 1520), False, 'from PIL import Image, ImageDraw\n'), ((864, 887), 'PIL.Image.open', 'Image.open', (['im_array[i]'], {}), '(im_array[i])\n', (874, 887), False, 'from PIL import Image, ImageDra... |
import numpy as np
import pandas as pd
from datetime import datetime as dt, timedelta
import sys
N_DATASETS = 3
args = sys.argv[1:]
if __name__ == "__main__":
if len(args) == 1:
N_DATASETS = int(args[0])
for i in range(1,N_DATASETS+1):
start_date = dt.now()
days = int(np.random.randi... | [
"datetime.datetime.now",
"numpy.random.randint",
"pandas.date_range",
"datetime.timedelta"
] | [((277, 285), 'datetime.datetime.now', 'dt.now', ([], {}), '()\n', (283, 285), True, 'from datetime import datetime as dt, timedelta\n'), ((420, 455), 'pandas.date_range', 'pd.date_range', (['start_date', 'end_date'], {}), '(start_date, end_date)\n', (433, 455), True, 'import pandas as pd\n'), ((472, 518), 'numpy.rando... |
# coding: utf-8
import re
import six
from huaweicloudsdkcore.sdk_response import SdkResponse
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class ListStacksByTagResponse(SdkResponse):
"""
Attributes:
openapi_types (dict): The key is attribute name
... | [
"huaweicloudsdkcore.utils.http_utils.sanitize_for_serialization",
"six.iteritems",
"sys.setdefaultencoding"
] | [((2148, 2181), 'six.iteritems', 'six.iteritems', (['self.openapi_types'], {}), '(self.openapi_types)\n', (2161, 2181), False, 'import six\n'), ((3166, 3197), 'sys.setdefaultencoding', 'sys.setdefaultencoding', (['"""utf-8"""'], {}), "('utf-8')\n", (3188, 3197), False, 'import sys\n'), ((3224, 3256), 'huaweicloudsdkcor... |
#!/usr/bin/env python
"""
This is used to select sites with the highest measurement ratios of Qle, Qh
and NEE. Sites are selected where all ratios are above 0.9 or 0.8. Also, sites are
selected where Qle and Qh are above 0.8 or 0.9.The maps from this script are
with zoom. Data generatred by method2.py script.
"""
... | [
"pandas.read_csv",
"matplotlib.pyplot.legend",
"os.path.join",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.figure",
"mpl_toolkits.basemap.Basemap",
"matplotlib.patches.Patch",
"mpl_toolkits.axes_grid.inset_locator.zoomed_inset_axes",
"matplotlib.pyplot.title",
"mpl_toolkits.axes_grid.inset_loc... | [((4050, 4475), 'pandas.concat', 'pd.concat', (['[df_results_LH1.site, df_results_LH1.length, df_results_LH1.overallLH,\n df_results_LH1.smallerthan2stdevLH, df_results_LH1.largerthan2stdevLH,\n df_results_SH1.overallSH, df_results_SH1.smallerthan2stdevSH,\n df_results_SH1.largerthan2stdevSH, df_results_NEE1.o... |
"""
Compute the principal eigenvector of a matrix using power iteration.
See also numpy.linalg.eig which calculates all the eigenvalues and
eigenvectors.
"""
from typing import Tuple
import numpy as np
def _normalise(nvec: np.ndarray) -> np.ndarray:
"""Normalises the given numpy array."""
with np.errstate(... | [
"numpy.sqrt",
"numpy.ones",
"numpy.errstate",
"numpy.array",
"numpy.dot"
] | [((604, 614), 'numpy.sqrt', 'np.sqrt', (['s'], {}), '(s)\n', (611, 614), True, 'import numpy as np\n'), ((1792, 1805), 'numpy.array', 'np.array', (['mat'], {}), '(mat)\n', (1800, 1805), True, 'import numpy as np\n'), ((1845, 1858), 'numpy.ones', 'np.ones', (['size'], {}), '(size)\n', (1852, 1858), True, 'import numpy a... |
import unittest
from games.connect_four import ConnectFourGame, MiniMaxPlayer, EMPTY, AI_PIECE, PLAYER_PIECE
class TestConnectFourClass(unittest.TestCase):
def setUp(self):
self.game = ConnectFourGame(AI_PIECE, PLAYER_PIECE)
self.aiPlayer = MiniMaxPlayer(AI_PIECE)
def test_is_moves_left... | [
"unittest.main",
"games.connect_four.ConnectFourGame",
"games.connect_four.MiniMaxPlayer"
] | [((5478, 5493), 'unittest.main', 'unittest.main', ([], {}), '()\n', (5491, 5493), False, 'import unittest\n'), ((201, 240), 'games.connect_four.ConnectFourGame', 'ConnectFourGame', (['AI_PIECE', 'PLAYER_PIECE'], {}), '(AI_PIECE, PLAYER_PIECE)\n', (216, 240), False, 'from games.connect_four import ConnectFourGame, MiniM... |
# -*- coding: utf-8 -*-
from PySide2.QtGui import QFont
from PySide2.QtCore import (Qt, QModelIndex, QAbstractTableModel)
from PySide2.QtWidgets import (QApplication, QMainWindow, QVBoxLayout,
QWidget, QTableView, QHeaderView, QAction, QMenu)
import re
from src.ValueSyntaxChecker import... | [
"PySide2.QtWidgets.QMenu",
"re.compile",
"PySide2.QtGui.QFont",
"src.ValueSyntaxChecker.SyntaxChecker",
"PySide2.QtWidgets.QHeaderView",
"PySide2.QtCore.QModelIndex",
"PySide2.QtWidgets.QVBoxLayout",
"PySide2.QtWidgets.QTableView"
] | [((561, 576), 'src.ValueSyntaxChecker.SyntaxChecker', 'SyntaxChecker', ([], {}), '()\n', (574, 576), False, 'from src.ValueSyntaxChecker import SyntaxChecker\n'), ((605, 647), 're.compile', 're.compile', (['"""[a-zA-Z_][a-zA-Z0-9_]*"""', 're.I'], {}), "('[a-zA-Z_][a-zA-Z0-9_]*', re.I)\n", (615, 647), False, 'import re\... |
"""CIFAR10
****************************************
This is a dataset of 50,000 32x32 color training images and 10,000 test
images, labeled over 10 categories. See more info at the
`CIFAR homepage <https://www.cs.toronto.edu/~kriz/cifar.html>`_
The classes are:
- airplane
- automobile
- bird
- cat
- deer
- dog
-... | [
"os.listdir",
"numpy.unique",
"os.makedirs",
"mltk.utils.logger.get_logger",
"keras_preprocessing.image.utils.array_to_img",
"os.path.join",
"pickle.load",
"numpy.empty",
"mltk.utils.archive_downloader.download_verify_extract",
"numpy.concatenate",
"mltk.utils.path.create_user_dir",
"tensorflo... | [((2006, 2263), 'mltk.utils.archive_downloader.download_verify_extract', 'download_verify_extract', ([], {'url': '"""https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz"""', 'dest_subdir': '"""datasets/cifar10"""', 'file_hash': '"""6d958be074577803d12ecdefd02955f39262c83c16fe9348329d7fe0b5c001ce"""', 'show_progress... |