code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
#!/usr/bin/env python
import nltk
from nltk.corpus import brown
import numpy as np
from math import log
from config import *
"""
convert word list file to a map from word to id
"""
def word2map(filename):
word2idx = {};
with open(filename) as f:
for line in f:
word2idx[line.strip('\n')] =... | [
"nltk.corpus.brown.words",
"nltk.data.path.append",
"numpy.zeros",
"numpy.ones",
"math.log"
] | [((416, 448), 'nltk.data.path.append', 'nltk.data.path.append', (['DATA_HOME'], {}), '(DATA_HOME)\n', (437, 448), False, 'import nltk\n'), ((985, 1010), 'numpy.ones', 'np.ones', (['(V_SIZE, C_SIZE)'], {}), '((V_SIZE, C_SIZE))\n', (992, 1010), True, 'import numpy as np\n'), ((1029, 1049), 'numpy.ones', 'np.ones', (['(1,... |
# This file is part of the Python aiocoap library project.
#
# Copyright (c) 2012-2014 <NAME> <http://sixpinetrees.blogspot.com/>,
# 2013-2014 <NAME> <<EMAIL>>
#
# aiocoap is free software, this file is published under the MIT license as
# described in the accompanying LICENSE file.
"""Confront a CoAP ov... | [
"unittest.skipIf",
"aiocoap.transports.tcp._decode_message",
"asyncio.sleep",
"aiocoap.transports.tcp._extract_message_size",
"asyncio.open_connection"
] | [((611, 671), 'unittest.skipIf', 'unittest.skipIf', (['tcp_disabled', '"""TCP disabled in environment"""'], {}), "(tcp_disabled, 'TCP disabled in environment')\n", (626, 671), False, 'import unittest\n'), ((843, 905), 'asyncio.open_connection', 'asyncio.open_connection', (['self.serveraddress', 'aiocoap.COAP_PORT'], {}... |
#!/usr/bin/python3
# <NAME>
# audio to speech using google speech api
# 11/7/19
# Mac speech_recognition library installation
# pip3 install SpeechRecognition
# brew install portaudio
# pip3 install pyaudio
# pip3 install pydub
# Testing speech_recognization
# python3 -m speech_recognition
#Program usage
#usage: py... | [
"os.mkdir",
"os.system",
"pydub.AudioSegment.from_wav",
"textblob.TextBlob",
"pydub.silence.split_on_silence",
"speech_recognition.AudioFile",
"os.chdir",
"speech_recognition.Recognizer"
] | [((744, 771), 'pydub.AudioSegment.from_wav', 'AudioSegment.from_wav', (['path'], {}), '(path)\n', (765, 771), False, 'from pydub import AudioSegment\n'), ((998, 1061), 'pydub.silence.split_on_silence', 'split_on_silence', (['song'], {'min_silence_len': '(400)', 'silence_thresh': '(-16)'}), '(song, min_silence_len=400, ... |
#!/usr/bin/env python3
#
# Copyright (c) 2020 JinTian.
#
# This file is part of alfred
# (see http://jinfagang.github.io).
#
# 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 cop... | [
"alfred.utils.log.logger.info",
"traceback.print_exc",
"argparse.ArgumentParser"
] | [((2037, 2075), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'prog': '"""alfred"""'}), "(prog='alfred')\n", (2060, 2075), False, 'import argparse\n'), ((16740, 16761), 'traceback.print_exc', 'traceback.print_exc', ([], {}), '()\n', (16759, 16761), False, 'import traceback\n'), ((16120, 16181), 'alfred.ut... |
# Generated by Django 2.2.20 on 2021-05-21 15:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('waldur_azure', '0018_drop_spl'),
]
operations = [
migrations.AlterModelOptions(
name='image', options={'ordering': ['publisher'... | [
"django.db.models.CharField",
"django.db.migrations.AlterModelOptions"
] | [((231, 339), 'django.db.migrations.AlterModelOptions', 'migrations.AlterModelOptions', ([], {'name': '"""image"""', 'options': "{'ordering': ['publisher', 'offer', 'name', 'sku']}"}), "(name='image', options={'ordering': [\n 'publisher', 'offer', 'name', 'sku']})\n", (259, 339), False, 'from django.db import migrat... |
import os
import csv
import collections
import numpy as np
class StatsTracker(collections.defaultdict):
"""Keep track of mean values"""
def __init__(self):
super().__init__(float)
self.step = 1
def update(self, data):
for key, val in data.items():
if key.endswith('_mi... | [
"os.makedirs",
"os.path.dirname",
"numpy.max",
"numpy.min",
"numpy.mean",
"csv.DictWriter"
] | [((1032, 1057), 'os.path.dirname', 'os.path.dirname', (['filepath'], {}), '(filepath)\n', (1047, 1057), False, 'import os\n'), ((1062, 1097), 'os.makedirs', 'os.makedirs', (['dirpath'], {'exist_ok': '(True)'}), '(dirpath, exist_ok=True)\n', (1073, 1097), False, 'import os\n'), ((815, 857), 'csv.DictWriter', 'csv.DictWr... |
#!/usr/bin/env python3
"""
Daemon to watch over Zabbix
"""
from pyzabbix import ZabbixAPI
from aiohttp import web
from os import getenv
import logging
zabbix_srv = 'https://zabbix.company.ru'
zabbix_user = getenv('secret_zabbix_user')
zabbix_pass = getenv('secret_zabbix_pass')
zabbix_groups = ['Production']
def ge... | [
"logging.error",
"logging.basicConfig",
"pyzabbix.ZabbixAPI",
"aiohttp.web.Application",
"aiohttp.web.json_response",
"logging.info",
"aiohttp.web.get",
"aiohttp.web.run_app",
"os.getenv"
] | [((209, 237), 'os.getenv', 'getenv', (['"""secret_zabbix_user"""'], {}), "('secret_zabbix_user')\n", (215, 237), False, 'from os import getenv\n'), ((252, 280), 'os.getenv', 'getenv', (['"""secret_zabbix_pass"""'], {}), "('secret_zabbix_pass')\n", (258, 280), False, 'from os import getenv\n'), ((349, 370), 'pyzabbix.Za... |
#
# ovirt-engine-setup -- ovirt engine setup
# Copyright (C) 2015 Red Hat, Inc.
#
# 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 r... | [
"gettext.dgettext",
"os.path.exists",
"otopi.plugin.event"
] | [((797, 853), 'gettext.dgettext', 'gettext.dgettext', ([], {'message': 'm', 'domain': '"""ovirt-engine-setup"""'}), "(message=m, domain='ovirt-engine-setup')\n", (813, 853), False, 'import gettext\n'), ((1021, 1065), 'otopi.plugin.event', 'plugin.event', ([], {'stage': 'plugin.Stages.STAGE_INIT'}), '(stage=plugin.Stage... |
"""
Test management commands
"""
from io import StringIO
from sga.management.commands.createmockdata import CreateMockDataCommand
from sga.tests.common import SGATestCase
class ManagementTest(SGATestCase):
"""
Class for management tests
"""
def test_create_mock_data(self):
"""
Test cr... | [
"io.StringIO",
"sga.management.commands.createmockdata.CreateMockDataCommand"
] | [((369, 379), 'io.StringIO', 'StringIO', ([], {}), '()\n', (377, 379), False, 'from io import StringIO\n'), ((398, 421), 'sga.management.commands.createmockdata.CreateMockDataCommand', 'CreateMockDataCommand', ([], {}), '()\n', (419, 421), False, 'from sga.management.commands.createmockdata import CreateMockDataCommand... |
#Name: Blackjack
#Version: v.010
#Authour: dp
#Date: Aug2019
import sys
import random
import time
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
class Card(object):
def __init__(self, ... | [
"tkinter.Button",
"random.shuffle",
"tkinter.Listbox",
"time.sleep",
"tkinter.Toplevel",
"sys.stdout.flush",
"tkinter.Label",
"tkinter.Tk"
] | [((3249, 3264), 'time.sleep', 'time.sleep', (['(0.3)'], {}), '(0.3)\n', (3259, 3264), False, 'import time\n'), ((3609, 3627), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (3625, 3627), False, 'import sys\n'), ((3825, 3843), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (3841, 3843), False, 'imp... |
from django import forms
from jobboard.models import Job
class FormControl(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for form_field in self.visible_fields():
form_field.field.widget.attrs['class'] = 'form-control'
class CreateNewJobForm(... | [
"django.forms.Textarea"
] | [((517, 552), 'django.forms.Textarea', 'forms.Textarea', ([], {'attrs': "{'rows': '5'}"}), "(attrs={'rows': '5'})\n", (531, 552), False, 'from django import forms\n')] |
import pytest
from jwkest.jwt import JWT, b2s_conv
__author__ = 'roland'
def _eq(l1, l2):
return set(l1) == set(l2)
def test_pack_jwt():
_jwt = JWT(**{"alg": "none", "cty": "jwt"})
jwt = _jwt.pack(parts=[{"iss": "joe", "exp": 1300819380,
"http://example.com/is_root": True},... | [
"pytest.raises",
"jwkest.jwt.JWT"
] | [((158, 194), 'jwkest.jwt.JWT', 'JWT', ([], {}), "(**{'alg': 'none', 'cty': 'jwt'})\n", (161, 194), False, 'from jwkest.jwt import JWT, b2s_conv\n'), ((410, 432), 'jwkest.jwt.JWT', 'JWT', ([], {}), "(**{'alg': 'none'})\n", (413, 432), False, 'from jwkest.jwt import JWT, b2s_conv\n'), ((678, 700), 'jwkest.jwt.JWT', 'JWT... |
"""
Copyright (C) 2022 <NAME>
This work is released under the MIT License.
See the file LICENSE for details
Utility functions
"""
from math import sqrt
from typing import List
import numpy as np
import carla
import io
def loc_dist(a, b):
return sqrt((a.x - b.x)**2 + (a.y - b.y)**2 + (a.z - b.... | [
"math.sqrt",
"numpy.array2string",
"numpy.hstack",
"numpy.around",
"numpy.linalg.norm",
"numpy.array",
"numpy.vstack",
"carla.Vector3D"
] | [((272, 332), 'math.sqrt', 'sqrt', (['((a.x - b.x) ** 2 + (a.y - b.y) ** 2 + (a.z - b.z) ** 2)'], {}), '((a.x - b.x) ** 2 + (a.y - b.y) ** 2 + (a.z - b.z) ** 2)\n', (276, 332), False, 'from math import sqrt\n'), ((414, 470), 'carla.Vector3D', 'carla.Vector3D', ([], {'x': '(v.x / norm)', 'y': '(v.y / norm)', 'z': '(v.z ... |
# Copyright 2020 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | [
"tensorflow_probability.python.internal.prefer_static.maximum",
"tensorflow.compat.v2.math.log_softmax",
"tensorflow_probability.python.internal.prefer_static.shape",
"tensorflow_probability.python.internal.samplers.sanitize_seed",
"tensorflow_probability.python.internal.prefer_static.range",
"tensorflow_... | [((1280, 1353), 'collections.namedtuple', 'collections.namedtuple', (['"""WeightedParticles"""', "['particles', 'log_weights']"], {}), "('WeightedParticles', ['particles', 'log_weights'])\n", (1302, 1353), False, 'import collections\n'), ((2315, 2491), 'collections.namedtuple', 'collections.namedtuple', (['"""Sequentia... |
# -*- coding: utf-8 -*-
## @package ivf.batch.initial_normal
#
# ivf.batch.initial_normal utility package.
# @author tody
# @date 2016/02/19
import numpy as np
import cv2
import matplotlib.pyplot as plt
from ivf.batch.batch import DatasetBatch
from ivf.io_util.image import loadNormal, saveNormal
from i... | [
"ivf.np.norm.normalizeVectors",
"ivf.io_util.image.loadNormal",
"ivf.core.sfs.amg_constraints.silhouetteConstraints",
"ivf.core.sfs.lumo.computeNz",
"ivf.io_util.image.saveNormal",
"ivf.core.sfs.amg_constraints.laplacianMatrix",
"ivf.core.solver.amg_solver.solve"
] | [((743, 770), 'ivf.io_util.image.loadNormal', 'loadNormal', (['self._data_file'], {}), '(self._data_file)\n', (753, 770), False, 'from ivf.io_util.image import loadNormal, saveNormal\n'), ((909, 966), 'ivf.core.sfs.amg_constraints.silhouetteConstraints', 'amg_constraints.silhouetteConstraints', (['A_8U'], {'is_flat': '... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from torch import optim
import copy
class Extragradient(optim.Optimizer):
def __init__(self, optimizer, params):
super(Extragrad... | [
"copy.deepcopy"
] | [((719, 749), 'copy.deepcopy', 'copy.deepcopy', (["group['params']"], {}), "(group['params'])\n", (732, 749), False, 'import copy\n')] |
# Copyright 2021 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
"""
This class provides GWS Group related methods
"""
import logging
from uw_trumba.models import TrumbaCalendar
from accountsynchr.models import (
UwcalGroup, EDITOR, SHOWON, new_editor_group, new_showon_group)
from accountsync... | [
"accountsynchr.models.new_editor_group",
"accountsynchr.models.new_showon_group",
"accountsynchr.dao.gws.Gws",
"logging.getLogger"
] | [((352, 379), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (369, 379), False, 'import logging\n'), ((446, 451), 'accountsynchr.dao.gws.Gws', 'Gws', ([], {}), '()\n', (449, 451), False, 'from accountsynchr.dao.gws import Gws\n'), ((3026, 3054), 'accountsynchr.models.new_editor_group', 'n... |
import os
import imp
from setuptools import setup, find_packages
dirname = os.path.dirname(__file__)
path_version = os.path.join(dirname, 'vaex_gql_schema/_version.py')
version = imp.load_source('version', path_version)
name = 'vaex-gql-schema'
author = '<NAME>'
author_email= '<EMAIL>'
license = 'MIT'... | [
"imp.load_source",
"os.path.dirname",
"os.path.join",
"setuptools.find_packages"
] | [((76, 101), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (91, 101), False, 'import os\n'), ((117, 169), 'os.path.join', 'os.path.join', (['dirname', '"""vaex_gql_schema/_version.py"""'], {}), "(dirname, 'vaex_gql_schema/_version.py')\n", (129, 169), False, 'import os\n'), ((180, 220), 'imp... |
# -*- coding: utf-8 -*-
"""
Copyright © 2017, <NAME>
Contributed by <NAME> (<EMAIL>)
This file is part of BSD license
<https://opensource.org/licenses/BSD-3-Clause>
"""
import os
from channels.asgi import get_channel_layer
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ci.settings")
channel_layer = get_channel_la... | [
"channels.asgi.get_channel_layer",
"os.environ.setdefault"
] | [((226, 288), 'os.environ.setdefault', 'os.environ.setdefault', (['"""DJANGO_SETTINGS_MODULE"""', '"""ci.settings"""'], {}), "('DJANGO_SETTINGS_MODULE', 'ci.settings')\n", (247, 288), False, 'import os\n'), ((306, 325), 'channels.asgi.get_channel_layer', 'get_channel_layer', ([], {}), '()\n', (323, 325), False, 'from c... |
from fastapi.testclient import TestClient
from main import *
client = TestClient(app)
def test_index():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"msg": "Hello World"}
def test_health():
response = client.get("/health")
assert response.status_code =... | [
"fastapi.testclient.TestClient"
] | [((72, 87), 'fastapi.testclient.TestClient', 'TestClient', (['app'], {}), '(app)\n', (82, 87), False, 'from fastapi.testclient import TestClient\n')] |
# coding: utf-8
'''
Pages.
'''
import re
import canvas as cv
from canvas.plugins import users
@cv.alter_root_page_view
def alter_root_page_view(PageView):
class CustomPageView(PageView):
def setup(self):
self.assets = ('site.js', 'site.css', *self.assets, 'decor.js')
if self.title is None:
self.title = ... | [
"re.match",
"canvas.page"
] | [((521, 577), 'canvas.page', 'cv.page', (['"""/"""'], {'title': 'None', 'assets': "('home.js', 'home.css')"}), "('/', title=None, assets=('home.js', 'home.css'))\n", (528, 577), True, 'import canvas as cv\n'), ((601, 656), 'canvas.page', 'cv.page', (['"""/login"""'], {'title': '"""log in"""', 'assets': "('login.js',)"}... |
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
# Licensed under the Apache License, Version 2.0 https://aws.amazon.com/apache-2-0/
import boto3
import time
import os
from botocore.exceptions import ClientError
from boto3.dynamodb.conditions import Key, ... | [
"api.queue_manager.queue_manager",
"api.state_table_manager.state_table_manager",
"time.time",
"utils.performance_tracker.performance_tracker_initializer",
"utils.performance_tracker.EventsCounter"
] | [((587, 765), 'utils.performance_tracker.performance_tracker_initializer', 'performance_tracker_initializer', (["os.environ['METRICS_ARE_ENABLED']", "os.environ['METRICS_TTL_CHECKER_LAMBDA_CONNECTION_STRING']", "os.environ['METRICS_GRAFANA_PRIVATE_IP']"], {}), "(os.environ['METRICS_ARE_ENABLED'], os.\n environ['METR... |
import time
from django.utils.deprecation import MiddlewareMixin
class StatsMiddleware(MiddlewareMixin):
def process_request(selfs, request):
request.start_time = time.time()
def process_response(self, request, response):
total = time.time() - request.start_time
print(f"cycle took {to... | [
"time.time"
] | [((177, 188), 'time.time', 'time.time', ([], {}), '()\n', (186, 188), False, 'import time\n'), ((257, 268), 'time.time', 'time.time', ([], {}), '()\n', (266, 268), False, 'import time\n')] |
# modify from clovaai
import random
import re
import lmdb
import six
from PIL import Image
from .base import BaseDataset
from .registry import DATASETS
@DATASETS.register_module
class LmdbDataset(BaseDataset):
def __init__(self, *args, **kwargs):
super(LmdbDataset, self).__init__(*args, **kwargs)
... | [
"six.BytesIO",
"re.sub",
"lmdb.open",
"PIL.Image.open"
] | [((365, 465), 'lmdb.open', 'lmdb.open', (['self.root'], {'max_readers': '(32)', 'readonly': '(True)', 'lock': '(False)', 'readahead': '(False)', 'meminit': '(False)'}), '(self.root, max_readers=32, readonly=True, lock=False, readahead=\n False, meminit=False)\n', (374, 465), False, 'import lmdb\n'), ((1654, 1667), '... |
from functools import partial
from PyQt5 import QtCore
from PyQt5.QtCore import QParallelAnimationGroup, QPoint, QPropertyAnimation, QRect, QTimer
from PyQt5.QtGui import QCursor
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QGraphicsOpacityEffect, QHBoxLayout, QLabel, QMainWindow, QPushButton, QScrollArea, Q... | [
"PyQt5.QtCore.QTimer",
"PyQt5.QtWidgets.QLabel",
"functools.partial",
"PyQt5.QtWidgets.QWidget",
"PyQt5.QtCore.QRect",
"PyQt5.QtCore.QParallelAnimationGroup",
"PyQt5.QtWidgets.QPushButton",
"PyQt5.QtWidgets.QHBoxLayout",
"PyQt5.QtWidgets.QScrollArea",
"PyQt5.QtGui.QCursor",
"PyQt5.QtWidgets.QVBo... | [((636, 660), 'PyQt5.QtWidgets.QGraphicsOpacityEffect', 'QGraphicsOpacityEffect', ([], {}), '()\n', (658, 660), False, 'from PyQt5.QtWidgets import QGraphicsOpacityEffect, QHBoxLayout, QLabel, QMainWindow, QPushButton, QScrollArea, QVBoxLayout, QWidget\n'), ((734, 784), 'PyQt5.QtCore.QPropertyAnimation', 'QtCore.QPrope... |
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'first_name']
... | [
"django.forms.FileInput",
"django.forms.EmailField"
] | [((208, 226), 'django.forms.EmailField', 'forms.EmailField', ([], {}), '()\n', (224, 226), False, 'from django import forms\n'), ((371, 389), 'django.forms.EmailField', 'forms.EmailField', ([], {}), '()\n', (387, 389), False, 'from django import forms\n'), ((657, 674), 'django.forms.FileInput', 'forms.FileInput', ([], ... |
from django.db import models
from django.core import validators
# Create your models here.
class Players(models.Model):
POSITION_CHOICES = (
('', '選択'),
(1, '投'),
(2, '捕'),
(3, '一'),
(4, '二'),
(5, '三'),
(6, '遊'),
(7, '外'),
)
... | [
"django.db.models.CharField",
"django.db.models.ForeignKey",
"django.core.validators.MinValueValidator",
"django.db.models.PositiveSmallIntegerField",
"django.db.models.IntegerField",
"django.db.models.DateTimeField",
"django.core.validators.MaxValueValidator"
] | [((790, 841), 'django.db.models.CharField', 'models.CharField', ([], {'verbose_name': '"""選手名"""', 'max_length': '(10)'}), "(verbose_name='選手名', max_length=10)\n", (806, 841), False, 'from django.db import models\n'), ((1057, 1142), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'verbose_name': '"""メインポジ... |
from unittest.mock import Mock
from uuid import uuid4
import pytest
from returns.result import Failure, Result, Success
from kamui.core.entity.source import SourceType
from kamui.core.entity.stream import Stream
from kamui.core.use_case.failure import FailureDetails, BusinessFailureDetails
from kamui.core.use_case.st... | [
"uuid.uuid4",
"returns.result.Success",
"kamui.core.use_case.stream.get_streams.GetStreamsUseCase",
"unittest.mock.Mock",
"pytest.fixture",
"returns.result.Failure",
"kamui.core.use_case.failure.FailureDetails"
] | [((378, 410), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (392, 410), False, 'import pytest\n'), ((476, 508), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (490, 508), False, 'import pytest\n'), ((450, 472), 'unittest.mo... |
from apex import amp
from argparse import ArgumentParser
from collections import OrderedDict
from datetime import datetime
import scipy.sparse as sp_sparse
import tables
from itertools import chain
from model import loss_function
from model import VAE
import numpy as np
import os
import pandas as pd
from sklearn.metric... | [
"apex.amp.state_dict",
"numpy.load",
"numpy.random.seed",
"argparse.ArgumentParser",
"pandas.read_csv",
"sklearn.metrics.accuracy_score",
"numpy.argsort",
"numpy.savez_compressed",
"numpy.arange",
"seaborn.relplot",
"train_multitask_ccle.make_labels",
"os.path.join",
"torch.isnan",
"numpy.... | [((578, 622), 'os.path.join', 'os.path.join', (['outdir', '"""cellByGeneMatrix.npz"""'], {}), "(outdir, 'cellByGeneMatrix.npz')\n", (590, 622), False, 'import os\n'), ((1460, 1512), 'numpy.intersect1d', 'np.intersect1d', (['genes', 'ar_genes'], {'return_indices': '(True)'}), '(genes, ar_genes, return_indices=True)\n', ... |
# Numpy is imported, seed is set
import numpy as np
np.random.seed(123)
# Initialization
random_walk = [0]
for x in range(100) :
step = random_walk[-1]
dice = np.random.randint(1,7)
if dice <= 2:
step = max(0, step - 1)
elif dice <= 5:
step = step + 1
else:
step = step + np... | [
"numpy.random.randint",
"numpy.random.seed",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.show"
] | [((52, 71), 'numpy.random.seed', 'np.random.seed', (['(123)'], {}), '(123)\n', (66, 71), True, 'import numpy as np\n'), ((458, 479), 'matplotlib.pyplot.plot', 'plt.plot', (['random_walk'], {}), '(random_walk)\n', (466, 479), True, 'import matplotlib.pyplot as plt\n'), ((497, 507), 'matplotlib.pyplot.show', 'plt.show', ... |
#!/usr/bin/env python
from netCDF4 import Dataset # pylint: disable=no-name-in-module
import numpy as np
#########################################################
# Class for ROMS grd and clm files
# (For use in various post-processing scripts)
#########################################################
class getGrid(... | [
"netCDF4.Dataset",
"numpy.zeros_like",
"numpy.abs",
"argparse.ArgumentParser",
"numpy.tanh",
"numpy.sum",
"numpy.multiply",
"numpy.zeros",
"numpy.arange",
"numpy.array",
"numpy.exp",
"numpy.cosh",
"numpy.sinh",
"sys.exit"
] | [((4031, 4084), 'numpy.zeros', 'np.zeros', (['(nr_zlev, h.shape[0], h.shape[1])', 'np.float'], {}), '((nr_zlev, h.shape[0], h.shape[1]), np.float)\n', (4039, 4084), True, 'import numpy as np\n'), ((6626, 6649), 'numpy.zeros_like', 'np.zeros_like', (['z_values'], {}), '(z_values)\n', (6639, 6649), True, 'import numpy as... |
import subprocess
import shutil
import tempfile
import logging
from time import sleep
logger = logging.getLogger(__name__)
class Npm:
def __init__(self):
self.process = None
pass
def install(self, path):
logger.info("Installing npm packages...")
process = subprocess.Popen(
... | [
"subprocess.Popen",
"logging.getLogger"
] | [((96, 123), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (113, 123), False, 'import logging\n'), ((300, 398), 'subprocess.Popen', 'subprocess.Popen', (["['npm', 'install']"], {'cwd': 'path', 'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.PIPE'}), "(['npm', 'install'], cwd=path, std... |
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree. An additional grant of patent rights
# can be found in the PATENTS file in the same directory.
import math
import os
import json
... | [
"torch.nn.Dropout",
"argparse.Namespace",
"fairseq.utils.parse_embedding",
"torch.bmm",
"torch.sqrt",
"torch.nn.Embedding",
"fairseq.utils.softmax",
"torch.nn.functional.dropout",
"torch.cuda.device_count",
"torch.nn.init.constant_",
"torch.arange",
"fairseq.modules.LearnedPositionalEmbedding"... | [((35116, 35184), 'torch.nn.Embedding', 'nn.Embedding', (['num_embeddings', 'embedding_dim'], {'padding_idx': 'padding_idx'}), '(num_embeddings, embedding_dim, padding_idx=padding_idx)\n', (35128, 35184), True, 'import torch.nn as nn\n'), ((35189, 35249), 'torch.nn.init.normal_', 'nn.init.normal_', (['m.weight'], {'mea... |
"""
Create MDX View on }ClientGroups cube and query data through it.
IMPORTANT: MDX Views can not be seen through Architect/Perspectives.
"""
import configparser
import uuid
from TM1py.Objects import MDXView
from TM1py.Services import TM1Service
config = configparser.ConfigParser()
# storing the credentials in a fil... | [
"uuid.uuid4",
"configparser.ConfigParser",
"TM1py.Objects.MDXView",
"TM1py.Services.TM1Service"
] | [((258, 285), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (283, 285), False, 'import configparser\n'), ((564, 596), 'TM1py.Services.TM1Service', 'TM1Service', ([], {}), "(**config['tm1srv01'])\n", (574, 596), False, 'from TM1py.Services import TM1Service\n'), ((881, 960), 'TM1py.Objects.... |
import numpy as np
import torch
import torch.nn as nn
from torch import optim
from torch.utils.data import DataLoader, ConcatDataset
from argparse import ArgumentParser
from models.psp.pspnet import PSPNet
from models.sobel_op import SobelComputer
from dataset import OnlineTransformDataset
from util.logger import Boar... | [
"util.logger.BoardLogger",
"numpy.random.seed",
"models.psp.pspnet.PSPNet",
"argparse.ArgumentParser",
"torch.utils.data.DataLoader",
"numpy.random.get_state",
"util.image_saver.vis_prediction",
"torch.load",
"dataset.OnlineTransformDataset",
"torch.cuda.device_count",
"util.model_saver.ModelSav... | [((696, 713), 'util.hyper_para.HyperParameters', 'HyperParameters', ([], {}), '()\n', (711, 713), False, 'from util.hyper_para import HyperParameters\n'), ((737, 753), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (751, 753), False, 'from argparse import ArgumentParser\n'), ((1002, 1022), 'util.logger.... |
from __future__ import absolute_import
import httpretty
import pygerduty
import pygerduty.v2
###################
# Version 1 Tests #
###################
@httpretty.activate
def test_get_user_v1():
body = open('tests/fixtures/user_v1.json').read()
httpretty.register_uri(
httpretty.GET, "https://contos... | [
"pygerduty.PagerDuty",
"pygerduty.v2.PagerDuty",
"httpretty.register_uri",
"pygerduty.common.clean_response"
] | [((258, 381), 'httpretty.register_uri', 'httpretty.register_uri', (['httpretty.GET', '"""https://contosso.pagerduty.com/api/v1/users/PIJ90N7"""'], {'body': 'body', 'status': '(200)'}), "(httpretty.GET,\n 'https://contosso.pagerduty.com/api/v1/users/PIJ90N7', body=body,\n status=200)\n", (280, 381), False, 'import... |
""" Test multithreading to ensure consistent behavior with
serial implementation."""
import unittest
import warnings
from os import remove
from os.path import exists, join
import numpy as np
from molSim.chemical_datastructures import MoleculeSet
from time import time
from tabulate import tabulate
class TestMultithrea... | [
"unittest.main",
"molSim.chemical_datastructures.MoleculeSet",
"os.remove",
"os.path.exists",
"time.time",
"tabulate.tabulate",
"warnings.warn",
"os.path.join"
] | [((64099, 64114), 'unittest.main', 'unittest.main', ([], {}), '()\n', (64112, 64114), False, 'import unittest\n'), ((1419, 1613), 'molSim.chemical_datastructures.MoleculeSet', 'MoleculeSet', ([], {'molecule_database_src': 'self.text_fpath', 'molecule_database_src_type': '"""text"""', 'is_verbose': '(True)', 'similarity... |
from django.shortcuts import render, redirect
from bs4 import BeautifulSoup
from django.views.generic import DetailView, FormView, CreateView
from news.models import Article, Comment
from django.db import IntegrityError
from django.db.models import Q
from .forms import AddComment
import requests
from urllib.request imp... | [
"requests.packages.urllib3.disable_warnings",
"urllib.request.Request",
"news.models.Article",
"django.shortcuts.render",
"django.shortcuts.redirect",
"urllib.request.urlopen",
"django.db.models.Q",
"django.urls.reverse",
"operator.attrgetter",
"django.core.paginator.Paginator",
"requests.get",
... | [((537, 581), 'requests.packages.urllib3.disable_warnings', 'requests.packages.urllib3.disable_warnings', ([], {}), '()\n', (579, 581), False, 'import requests\n'), ((626, 684), 'requests.get', 'requests.get', (['"""https://foreignpolicy.com/category/latest/"""'], {}), "('https://foreignpolicy.com/category/latest/')\n"... |
import abc
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type, Union
import gym
import numpy as np
import pymunk as pm
from gym import spaces
import xmagical.entities as en
import xmagical.render as r
from xmagical.phys_vars import PhysicsVariablesBase, PhysVar
from xmagical.style import ARENA_ZOOM_O... | [
"pymunk.Space",
"xmagical.entities.ArenaBoundaries",
"numpy.allclose",
"xmagical.phys_vars.PhysVar",
"xmagical.style.lighten_rgb",
"numpy.random.RandomState",
"numpy.random.randint",
"numpy.array",
"gym.spaces.Box",
"xmagical.render.Viewer",
"gym.envs.classic_control.rendering.SimpleImageViewer"... | [((525, 547), 'xmagical.phys_vars.PhysVar', 'PhysVar', (['(5)', '(3.2, 5.5)'], {}), '(5, (3.2, 5.5))\n', (532, 547), False, 'from xmagical.phys_vars import PhysicsVariablesBase, PhysVar\n'), ((580, 602), 'xmagical.phys_vars.PhysVar', 'PhysVar', (['(1)', '(0.7, 1.5)'], {}), '(1, (0.7, 1.5))\n', (587, 602), False, 'from ... |
# -*- coding: utf-8 -*-
# Copyright 2019 Tampere University
# This software was developed as a part of the CityIoT project: https://www.cityiot.fi/english
# This source code is licensed under the 3-clause BSD license. See license.txt in the repository root directory.
# Author(s): <NAME> <<EMAIL>>
'''
Helper module for ... | [
"json.load",
"utils.getAppDir"
] | [((668, 683), 'json.load', 'json.load', (['file'], {}), '(file)\n', (677, 683), False, 'import json\n'), ((575, 592), 'utils.getAppDir', 'utils.getAppDir', ([], {}), '()\n', (590, 592), False, 'import utils\n')] |
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipeline
def fit_poly_reg(X, y, degree=1, memory_path=None) -> Pipeline:
polyreg = make_pipeline(PolynomialFeatures(degree), LinearRegressi... | [
"sklearn.linear_model.LinearRegression",
"sklearn.preprocessing.PolynomialFeatures"
] | [((278, 304), 'sklearn.preprocessing.PolynomialFeatures', 'PolynomialFeatures', (['degree'], {}), '(degree)\n', (296, 304), False, 'from sklearn.preprocessing import PolynomialFeatures\n'), ((306, 324), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (322, 324), False, 'from sklearn.linea... |
#!/usr/bin/env python3
import bdsim
sim = bdsim.BDSim(animation=True) # create simulator
print(sim)
bd = sim.blockdiagram() # create an empty block diagram
# define the blocks
demand = bd.STEP(T=1, pos=(0,0), name='demand')
sum = bd.SUM('+-', pos=(1,0))
gain = bd.GAIN(10, pos=(1.5,0))
plant = bd.LTI_SISO(0.5, [2, ... | [
"bdsim.BDSim"
] | [((44, 71), 'bdsim.BDSim', 'bdsim.BDSim', ([], {'animation': '(True)'}), '(animation=True)\n', (55, 71), False, 'import bdsim\n')] |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Created on 2016年8月9日13:16:54
import datetime
import json
import os
import youkube.compoents.model as model
import youkube.compoents.youtube_compoent as youtube
import youkube.util as util
import time
import youkube.constants as constants
import youkube.compoents.youku_... | [
"os.remove",
"youkube.compoents.model.Video.select",
"youkube.compoents.model.deferred_db.init",
"os.path.exists",
"youkube.compoents.model.Video.create_table",
"youkube.compoents.youku_compoent.Youku",
"time.sleep",
"youkube.compoents.model.Video.get",
"youkube.util.get_logger",
"datetime.datetim... | [((351, 377), 'youkube.util.get_logger', 'util.get_logger', (['"""Youkube"""'], {}), "('Youkube')\n", (366, 377), True, 'import youkube.util as util\n'), ((1477, 1506), 'youkube.compoents.youtube_compoent.YoutubeCompoentImpl', 'youtube.YoutubeCompoentImpl', ([], {}), '()\n', (1504, 1506), True, 'import youkube.compoent... |
import json
class ROIUpdateRegions:
roi_region_list = list()
def __init__(self):
self.roi_region_list.clear()
def add_roi_region(self, id, ltx, lty, rbx, rby):
testNestedDict = {
"id": id,
"region": {
"lt": {
"x": ltx,
... | [
"json.dumps"
] | [((585, 617), 'json.dumps', 'json.dumps', (['self.roi_region_list'], {}), '(self.roi_region_list)\n', (595, 617), False, 'import json\n')] |
#!/usr/bin/env python
from __future__ import unicode_literals
from __future__ import print_function
import falcon
import spacy
import json
import sys
from spacy.pipeline import EntityRecognizer
import spacy.util
from spacy.tagger import Tagger
from .parse import Entities, TrainEntities
from falcon_cors import CORS
... | [
"spacy.tagger.Tagger",
"spacy.pipeline.EntityRecognizer",
"json.dumps",
"falcon_cors.CORS",
"spacy.load",
"falcon.API",
"sys.exc_info"
] | [((3117, 3145), 'falcon_cors.CORS', 'CORS', ([], {'allow_all_origins': '(True)'}), '(allow_all_origins=True)\n', (3121, 3145), False, 'from falcon_cors import CORS\n'), ((3152, 3192), 'falcon.API', 'falcon.API', ([], {'middleware': '[cors.middleware]'}), '(middleware=[cors.middleware])\n', (3162, 3192), False, 'import ... |
from mmcv.utils import Registry
OPTIMIZERS = Registry('optimizers')
| [
"mmcv.utils.Registry"
] | [((46, 68), 'mmcv.utils.Registry', 'Registry', (['"""optimizers"""'], {}), "('optimizers')\n", (54, 68), False, 'from mmcv.utils import Registry\n')] |
from lumada.client.api.gateway_client_base import GatewayClientBase
from lumada.utils.validator import Validator
from lumada.client.lumada_client import LumadaClient
from lumada.client.asset_registration_client import AssetRegistrationClient
from lumada.client.asset_client import AssetClient
class GatewayClient(Gatew... | [
"lumada.client.asset_client.AssetClient.from_gateway",
"lumada.utils.validator.Validator.validate_config_provided",
"lumada.utils.validator.Validator.validate_param"
] | [((1362, 1411), 'lumada.utils.validator.Validator.validate_param', 'Validator.validate_param', (['asset_name', '"""AssetName"""'], {}), "(asset_name, 'AssetName')\n", (1386, 1411), False, 'from lumada.utils.validator import Validator\n'), ((1420, 1469), 'lumada.utils.validator.Validator.validate_param', 'Validator.vali... |
import unittest
import numpy as np
import cddm.core as core
from cddm.conf import FDTYPE, CDTYPE
from cddm.video import fromarrays
#test arrays
a = [1.,2,3,4]
b = [5,6,7,8]
t1 = [1,3,7,8]
t2 = [2,4,6,8]
#results fo calculations
cross_a_b = np.array([ 70., 100., 62., 28.],FDTYPE)
cross_a_b_t1_t2 = np.array([32., 72.,... | [
"numpy.random.seed",
"numpy.abs",
"numpy.allclose",
"numpy.ones",
"cddm.core.cross_count",
"cddm.core.ccorr",
"numpy.arange",
"cddm.core.acorr",
"cddm.video.fromarrays",
"cddm.core.cross_correlate_fft",
"unittest.main",
"cddm.core.normalize",
"cddm.core.iacorr",
"cddm.core.abs2",
"numpy.... | [((241, 284), 'numpy.array', 'np.array', (['[70.0, 100.0, 62.0, 28.0]', 'FDTYPE'], {}), '([70.0, 100.0, 62.0, 28.0], FDTYPE)\n', (249, 284), True, 'import numpy as np\n'), ((301, 366), 'numpy.array', 'np.array', (['[32.0, 72.0, 28.0, 38.0, 24.0, 38.0, 20.0, 8.0]', 'FDTYPE'], {}), '([32.0, 72.0, 28.0, 38.0, 24.0, 38.0, ... |
import argparse
import numpy as np
import pytorch_lightning as pl
from torch.utils.data.dataloader import DataLoader
import utils.data.functions
class SpatioTemporalCSVDataModule(pl.LightningDataModule):
def __init__(
self,
feat_path: str,
adj_path: str,
batch_size: int = 32,
... | [
"torch.utils.data.dataloader.DataLoader",
"numpy.max",
"argparse.ArgumentParser"
] | [((863, 881), 'numpy.max', 'np.max', (['self._feat'], {}), '(self._feat)\n', (869, 881), True, 'import numpy as np\n'), ((1223, 1287), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'parents': '[parent_parser]', 'add_help': '(False)'}), '(parents=[parent_parser], add_help=False)\n', (1246, 1287), False, 'i... |
# Copyright 2016 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | [
"manilaclient.api_versions.wraps",
"manilaclient.common.apiclient.base.getid"
] | [((1250, 1276), 'manilaclient.api_versions.wraps', 'api_versions.wraps', (['"""2.31"""'], {}), "('2.31')\n", (1268, 1276), False, 'from manilaclient import api_versions\n'), ((1599, 1625), 'manilaclient.api_versions.wraps', 'api_versions.wraps', (['"""2.31"""'], {}), "('2.31')\n", (1617, 1625), False, 'from manilaclien... |
from csv import reader, writer
import sys
def get_id(s):
#adapted from Biopython SeqIO fasta parser
return s[1:].split(None, 1)[0]
r = reader(sys.stdin, delimiter="\t")
w = writer(sys.stdout, delimiter="\t")
for row in r:
row[0] = get_id(row[0]) #only keep the Accession number (trim everything after first... | [
"csv.reader",
"csv.writer"
] | [((145, 178), 'csv.reader', 'reader', (['sys.stdin'], {'delimiter': '"""\t"""'}), "(sys.stdin, delimiter='\\t')\n", (151, 178), False, 'from csv import reader, writer\n'), ((183, 217), 'csv.writer', 'writer', (['sys.stdout'], {'delimiter': '"""\t"""'}), "(sys.stdout, delimiter='\\t')\n", (189, 217), False, 'from csv im... |
import os
import cv2
import numpy as np
import sys
caffe_root = os.path.expanduser('~') + "/CNN/ssd"
sys.path.insert(0, caffe_root+'/python')
import caffe
from tqdm import tqdm
CLASSES = ('background', 'aeroplane', 'bicycle', 'bird', 'boat','bottle', 'bus', 'car', 'cat',
'chair','cow', 'diningtable', 'dog', 'horse','... | [
"cv2.putText",
"os.makedirs",
"cv2.waitKey",
"cv2.imshow",
"sys.path.insert",
"os.path.exists",
"numpy.array",
"cv2.rectangle",
"caffe.Net",
"os.path.expanduser"
] | [((101, 143), 'sys.path.insert', 'sys.path.insert', (['(0)', "(caffe_root + '/python')"], {}), "(0, caffe_root + '/python')\n", (116, 143), False, 'import sys\n'), ((64, 87), 'os.path.expanduser', 'os.path.expanduser', (['"""~"""'], {}), "('~')\n", (82, 87), False, 'import os\n'), ((827, 855), 'numpy.array', 'np.array'... |
# 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... | [
"aliyunsdkcore.request.RpcRequest.__init__"
] | [((910, 989), 'aliyunsdkcore.request.RpcRequest.__init__', 'RpcRequest.__init__', (['self', '"""CSB"""', '"""2017-11-18"""', '"""FindApproveServiceList"""', '"""CSB"""'], {}), "(self, 'CSB', '2017-11-18', 'FindApproveServiceList', 'CSB')\n", (929, 989), False, 'from aliyunsdkcore.request import RpcRequest\n')] |
import urllib3
import os
import sys
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir)
from request import get_employment_data
from datetime import date
from utils import get_label_data, getLogger
DEBUG = getLogger()
def main(label, commencement_date, end_date):
result = ... | [
"sys.path.append",
"os.path.abspath",
"utils.get_label_data",
"request.get_employment_data",
"utils.getLogger"
] | [((107, 132), 'sys.path.append', 'sys.path.append', (['base_dir'], {}), '(base_dir)\n', (122, 132), False, 'import sys\n'), ((251, 262), 'utils.getLogger', 'getLogger', ([], {}), '()\n', (260, 262), False, 'from utils import get_label_data, getLogger\n'), ((320, 341), 'request.get_employment_data', 'get_employment_data... |
import pytest
from _pytest.monkeypatch import MonkeyPatch
from update_status_groups import update_status_groups
class Struct:
def __init__(self, **entries):
self.__dict__.update(entries)
class Test():
monkeypatch = MonkeyPatch()
existing_groups = []
# Mock API request for token.
def moc... | [
"_pytest.monkeypatch.MonkeyPatch",
"update_status_groups.update_status_groups"
] | [((235, 248), '_pytest.monkeypatch.MonkeyPatch', 'MonkeyPatch', ([], {}), '()\n', (246, 248), False, 'from _pytest.monkeypatch import MonkeyPatch\n'), ((1984, 2010), 'update_status_groups.update_status_groups', 'update_status_groups', (['args'], {}), '(args)\n', (2004, 2010), False, 'from update_status_groups import up... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, <NAME>PORATION. 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... | [
"torch.nn.Dropout",
"torch.sqrt",
"torch.nn.Embedding",
"torch.nn.Softmax",
"torch.arange",
"os.path.join",
"torch.ones",
"json.loads",
"io.open",
"torch.zeros",
"torch.nn.Linear",
"torch.matmul",
"copy.deepcopy",
"math.sqrt",
"torch.nn.Tanh",
"apex.normalization.fused_layer_norm.Fused... | [((1055, 1082), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1072, 1082), False, 'import logging\n'), ((2532, 2548), 'torch.sigmoid', 'torch.sigmoid', (['x'], {}), '(x)\n', (2545, 2548), False, 'import torch\n'), ((5329, 5357), 'copy.deepcopy', 'copy.deepcopy', (['self.__dict__'], {}),... |
# Generated by Django 3.2.3 on 2021-05-21 12:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cmsmenus', '0006_auto_20210507_1618'),
]
operations = [
migrations.AlterField(
model_name='navigationbar',
name='nam... | [
"django.db.models.CharField"
] | [((342, 374), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(255)'}), '(max_length=255)\n', (358, 374), False, 'from django.db import migrations, models\n')] |
from .market import Market
from . import position
from ..db.models import TradingOrder
import logging
logger = logging.getLogger(__name__)
class MarketSimulator(Market):
"""Wrapper for market that allows simulating simple buys and sells"""
def __init__(self, exchange, base_currency, quote_currency, quote_cur... | [
"logging.getLogger"
] | [((112, 139), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (129, 139), False, 'import logging\n')] |
import lyricsgenius
# wrapper for lyrics which remembers last search
# if there are several providers implemented this class should be inherited
class geniuslyrics:
"""
Class for searching for lyrics
"""
def __init__(self,_token = "<KEY>",_timeout=15,_retries=3,_verbose=False):
self.__session =... | [
"lyricsgenius.Genius"
] | [((321, 407), 'lyricsgenius.Genius', 'lyricsgenius.Genius', (['_token'], {'timeout': '_timeout', 'retries': '_retries', 'verbose': '_verbose'}), '(_token, timeout=_timeout, retries=_retries, verbose=\n _verbose)\n', (340, 407), False, 'import lyricsgenius\n')] |
import os.path
import pickle
import random
from data.base_dataset import BaseDataset, get_params, get_transform
from data.image_folder import make_numbering_dataset
import numpy as np
from PIL import Image
class AlignedDataset(BaseDataset):
"""A dataset class for paired image dataset.
It assumes that the dir... | [
"random.randint",
"data.base_dataset.get_params",
"data.base_dataset.BaseDataset.__init__",
"numpy.asarray",
"numpy.zeros",
"data.image_folder.make_numbering_dataset",
"PIL.Image.open",
"numpy.sort",
"pickle.load",
"numpy.arange",
"data.base_dataset.get_transform",
"numpy.random.shuffle"
] | [((694, 725), 'data.base_dataset.BaseDataset.__init__', 'BaseDataset.__init__', (['self', 'opt'], {}), '(self, opt)\n', (714, 725), False, 'from data.base_dataset import BaseDataset, get_params, get_transform\n'), ((2143, 2187), 'numpy.zeros', 'np.zeros', (['self.text_words_num'], {'dtype': '"""int64"""'}), "(self.text... |
import networkx
import fda
# Da Vinci robotic system
regulatory_graph = networkx.DiGraph()
regulatory_graph.add_node(fda.empty)
seeds = [fda.FDAApproval("K173585"),
fda.FDAApproval("K081113")]
for seed in seeds:
fda.populate_predicates(regulatory_graph, seed)
for seed in seeds:
subgraph = fda.netwo... | [
"fda.get_subgraph",
"networkx.DiGraph",
"fda.populate_predicates",
"fda.FDAApproval"
] | [((74, 92), 'networkx.DiGraph', 'networkx.DiGraph', ([], {}), '()\n', (90, 92), False, 'import networkx\n'), ((140, 166), 'fda.FDAApproval', 'fda.FDAApproval', (['"""K173585"""'], {}), "('K173585')\n", (155, 166), False, 'import fda\n'), ((177, 203), 'fda.FDAApproval', 'fda.FDAApproval', (['"""K081113"""'], {}), "('K08... |
from math import pi
from compas_fea.cad import rhino
from compas_fea.structure import CircularSection
from compas_fea.structure import ElasticIsotropic
from compas_fea.structure import ElementProperties as Properties
from compas_fea.structure import GeneralDisplacement
from compas_fea.structure import GeneralStep
from... | [
"compas_fea.structure.Structure",
"compas_fea.cad.rhino.add_sets_from_layers",
"compas_fea.structure.PinnedDisplacement",
"compas_fea.structure.ElasticIsotropic",
"compas_fea.cad.rhino.ordered_network",
"compas_fea.structure.GeneralStep",
"compas_fea.cad.rhino.network_from_lines",
"compas_fea.structur... | [((521, 567), 'compas_fea.structure.Structure', 'Structure', ([], {'name': '"""beam_simple"""', 'path': '"""C:/Temp/"""'}), "(name='beam_simple', path='C:/Temp/')\n", (530, 567), False, 'from compas_fea.structure import Structure\n'), ((591, 636), 'compas_fea.cad.rhino.network_from_lines', 'rhino.network_from_lines', (... |
import copy
from collections import OrderedDict
import zinc.route53
from zinc.utils import memoized_property
from .record import Record, RECORD_PREFIX
class Policy:
def __init__(self, zone, policy):
assert isinstance(zone, zinc.route53.Zone)
self.zone = zone
self.db_policy = policy
@... | [
"copy.copy"
] | [((3220, 3237), 'copy.copy', 'copy.copy', (['record'], {}), '(record)\n', (3229, 3237), False, 'import copy\n')] |
from ecolor import slow_color, slow_print, ecolor
ecolor("This is red text", "red")
ecolor("This is bold blue text", "bold_blue")
slow_print("This is slow_print", 0.025)
slow_color("This is slow_print but colorful", "blue", 0.025)
slow_color("This is slow_print but colorful and bold", "bold_blue", 0.025)
| [
"ecolor.ecolor",
"ecolor.slow_print",
"ecolor.slow_color"
] | [((50, 83), 'ecolor.ecolor', 'ecolor', (['"""This is red text"""', '"""red"""'], {}), "('This is red text', 'red')\n", (56, 83), False, 'from ecolor import slow_color, slow_print, ecolor\n'), ((84, 129), 'ecolor.ecolor', 'ecolor', (['"""This is bold blue text"""', '"""bold_blue"""'], {}), "('This is bold blue text', 'b... |
# -*- coding: utf-8 -*-
import os
import sys
import six
import json
import tccli.options_define as OptionsDefine
import tccli.format_output as FormatOutput
from tccli import __version__
from tccli.utils import Utils
from tccli.exceptions import ConfigurationError, ClientError, ParamError
from tencentcloud.common import... | [
"tencentcloud.common.credential.CVMRoleCredential",
"json.loads",
"tencentcloud.common.profile.client_profile.ClientProfile",
"tccli.exceptions.ConfigurationError",
"tccli.utils.Utils.load_json_msg",
"tccli.format_output.output",
"tccli.options_define.UseCVMRole.replace",
"time.time",
"json.dumps",
... | [((1693, 1757), 'tencentcloud.common.profile.client_profile.ClientProfile', 'ClientProfile', ([], {'httpProfile': 'http_profile', 'signMethod': '"""HmacSHA256"""'}), "(httpProfile=http_profile, signMethod='HmacSHA256')\n", (1706, 1757), False, 'from tencentcloud.common.profile.client_profile import ClientProfile\n'), (... |
"""
phase.py
Estimate the phase of an oscillation using a waveform-based approach
"""
import numpy as np
def extrema_interpolated_phase(x, Ps, Ts, zeroxR=None, zeroxD=None):
"""
Use peaks (phase 0) and troughs (phase pi/-pi) to estimate
instantaneous phase. Also use rise and decay zerocrossings
(phas... | [
"numpy.zeros",
"numpy.isnan",
"numpy.append",
"numpy.diff",
"numpy.arange"
] | [((1263, 1275), 'numpy.arange', 'np.arange', (['L'], {}), '(L)\n', (1272, 1275), True, 'import numpy as np\n'), ((2105, 2122), 'numpy.diff', 'np.diff', (['pha_tnpi'], {}), '(pha_tnpi)\n', (2112, 2122), True, 'import numpy as np\n'), ((2135, 2155), 'numpy.append', 'np.append', (['diffs', '(99)'], {}), '(diffs, 99)\n', (... |
# -*- coding: utf-8 -*-
import os
from collections import defaultdict
from copy import deepcopy
from warnings import warn
import numpy as np
import pandas as pd
from pathlib import Path
from simulator.core.DtnBundle import Bundle
from simulator.utils.DtnIO import load_traffic_file
from simulator.utils.DtnUtils import... | [
"pandas.DataFrame",
"numpy.random.uniform",
"numpy.zeros_like",
"numpy.ceil",
"numpy.argmax",
"numpy.floor",
"numpy.random.exponential",
"numpy.zeros",
"collections.defaultdict",
"numpy.cumsum",
"numpy.diff",
"numpy.array",
"numpy.arange",
"simulator.core.DtnBundle.Bundle.from_flow",
"si... | [((710, 960), 'numpy.array', 'np.array', (['[[60, np.nan, np.nan], [60, np.nan, np.nan], [60, np.nan, 3600], [60, 60,\n np.nan], [60, 900, 21600], [60, 300, 3600], [60, 300, np.nan], [60, 60,\n np.nan], [60, 900, 21600], [60, 900, 21600], [60, 900, 21600], [60, 300,\n np.nan]]'], {}), '([[60, np.nan, np.nan], ... |
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
from twisted.trial.unittest import TestCase, SkipTest
from twisted.internet.defer import Deferred
from twisted.web.server import Site
from twisted.internet import reactor
from twisted.web.client import Agent
from twisted.internet.error import TimeoutError
... | [
"dummyserver.AuthDummyServer",
"twisted.cred.credentials.UsernamePassword",
"twisted.web.guard.BasicCredentialFactory",
"dummyserver.DummyServer",
"os.path.abspath",
"twisted.cred.credentials.Anonymous",
"os.path.exists",
"fastjsonrpc.client.ProxyFactory",
"twisted.web.client.HTTPConnectionPool",
... | [((40, 61), 'os.path.abspath', 'os.path.abspath', (['""".."""'], {}), "('..')\n", (55, 61), False, 'import os\n'), ((2324, 2344), 'fastjsonrpc.client.StringProducer', 'StringProducer', (['data'], {}), '(data)\n', (2338, 2344), False, 'from fastjsonrpc.client import StringProducer\n'), ((2520, 2540), 'fastjsonrpc.client... |
"""Multi-agent traffic light example (single shared policy)."""
from ray.rllib.agents.ppo.ppo_policy import PPOTFPolicy
from flow.envs.multiagent import MyMultiTrafficLightGridPOEnv
from flow.networks import TrafficLightGridNetwork
from flow.core.params import SumoParams, EnvParams, InitialConfig, NetParams
from flow.... | [
"flow.networks.TrafficLightGridNetwork",
"flow.core.params.EnvParams",
"flow.core.params.VehicleParams",
"flow.envs.multiagent.MyMultiTrafficLightGridPOEnv",
"flow.core.params.SumoParams",
"numpy.zeros",
"flow.core.params.SumoCarFollowingParams",
"numpy.mean",
"numpy.array",
"flow.core.params.InFl... | [((1495, 1510), 'flow.core.params.VehicleParams', 'VehicleParams', ([], {}), '()\n', (1508, 1510), False, 'from flow.core.params import InFlows, SumoCarFollowingParams, VehicleParams\n'), ((2385, 2394), 'flow.core.params.InFlows', 'InFlows', ([], {}), '()\n', (2392, 2394), False, 'from flow.core.params import InFlows, ... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available.
Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... | [
"common.forms.ListField",
"django.forms.CharField",
"django.forms.IntegerField"
] | [((2683, 2736), 'django.forms.CharField', 'forms.CharField', ([], {'label': '"""business name"""', 'required': '(True)'}), "(label='business name', required=True)\n", (2698, 2736), False, 'from django import forms\n'), ((2759, 2796), 'common.forms.ListField', 'ListField', ([], {'label': '"""OPS"""', 'required': '(True)... |
""" Module for the KMCRateCalculatorPlugin class """
# Copyright (c) 2013 <NAME>
#
# This file is part of the KMCLib project distributed under the terms of the
# GNU General Public License version 3, see <http://www.gnu.org/licenses/>.
#
import numpy
from KMCLib.Backend import Backend
from KMCLib.Exceptions.Erro... | [
"KMCLib.Backend.Backend.RateCalculator.__init__",
"numpy.array",
"KMCLib.Exceptions.Error.Error"
] | [((691, 728), 'KMCLib.Backend.Backend.RateCalculator.__init__', 'Backend.RateCalculator.__init__', (['self'], {}), '(self)\n', (722, 728), False, 'from KMCLib.Backend import Backend\n'), ((3162, 3306), 'KMCLib.Exceptions.Error.Error', 'Error', (['"""The rate(self,...) API function in the \'KMCRateCalculator\' base clas... |
import torch
from torch import nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
def test_img(model, dataset, args):
model.eval()
test_loss = 0
correct = 0
data_loader = DataLoader(dataset, batch_size=args.batch_size)
with torch.no_grad():
for index, data in enumer... | [
"torch.no_grad",
"torch.nn.functional.cross_entropy",
"torch.utils.data.DataLoader"
] | [((213, 260), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset'], {'batch_size': 'args.batch_size'}), '(dataset, batch_size=args.batch_size)\n', (223, 260), False, 'from torch.utils.data import DataLoader\n'), ((270, 285), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (283, 285), False, 'import torch\n'), ... |
import csv
import matplotlib as matplot
import matplotlib.pyplot as plt
import numpy as np
# List the colors that will be used for tracing the track.
colors = ['black','blue','red','green', 'cyan', \
'gray', 'gold', 'lightcoral', 'turquoise','red','blue','green','pink']
patterns = ['-', '--','--','--','--'... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.show",
"numpy.concatenate",
"matplotlib.pyplot.plot",
"numpy.std",
"csv.DictReader",
"matplotlib.pyplot.legend",
"numpy.zeros",
"numpy.mean",
"numpy.array",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",... | [((1745, 1847), 'matplotlib.pyplot.legend', 'plt.legend', (["['Real Track', 'C0.0001', 'C0.01', 'C1', 'C100']"], {'loc': '"""upper right"""', 'prop': "{'size': 7}"}), "(['Real Track', 'C0.0001', 'C0.01', 'C1', 'C100'], loc=\n 'upper right', prop={'size': 7})\n", (1755, 1847), True, 'import matplotlib.pyplot as plt\n... |
"""
Unit tests for Schema
"""
import datetime
import json
import pytest
from marshmallow import fields
from pyspark.sql.types import *
from pyspark.sql import Row
from marshmallow_pyspark.constants import *
from marshmallow_pyspark.schema import Schema, _RowValidator
def test_create():
schema = Schema()
... | [
"json.loads",
"marshmallow.fields.Integer",
"marshmallow.fields.DateTime",
"marshmallow.fields.Float",
"marshmallow.fields.Str",
"datetime.date",
"marshmallow.fields.Boolean",
"marshmallow.fields.Number",
"datetime.datetime",
"pytest.raises",
"marshmallow.fields.String",
"marshmallow_pyspark.s... | [((309, 317), 'marshmallow_pyspark.schema.Schema', 'Schema', ([], {}), '()\n', (315, 317), False, 'from marshmallow_pyspark.schema import Schema, _RowValidator\n'), ((4668, 4706), 'json.loads', 'json.loads', (['row[DEFAULT_ERRORS_COLUMN]'], {}), '(row[DEFAULT_ERRORS_COLUMN])\n', (4678, 4706), False, 'import json\n'), (... |
import pygame, random
def ball_animation():
global ball_speed_x, ball_speed_y, left_player_score, right_player_score, score_time
ball.x += ball_speed_x
ball.y += ball_speed_y
if ball.top <= 0 or ball.bottom >= screen_height:
ball_speed_y *= -1
# Left Player Score
if ball.right <= 0:
score_time = pygam... | [
"pygame.quit",
"pygame.draw.line",
"pygame.font.SysFont",
"pygame.event.get",
"pygame.display.set_mode",
"pygame.draw.rect",
"pygame.Rect",
"pygame.mixer.pre_init",
"pygame.time.delay",
"pygame.init",
"random.choice",
"pygame.display.flip",
"pygame.display.update",
"pygame.time.get_ticks",... | [((2741, 2783), 'pygame.mixer.pre_init', 'pygame.mixer.pre_init', (['(44100)', '(-16)', '(1)', '(1024)'], {}), '(44100, -16, 1, 1024)\n', (2762, 2783), False, 'import pygame, random\n'), ((2782, 2795), 'pygame.init', 'pygame.init', ([], {}), '()\n', (2793, 2795), False, 'import pygame, random\n'), ((2804, 2823), 'pygam... |
#!/usr/bin/env python
""" Award points for position. """
import benchmark_analysis_utils as bau
import pandas as pd
import sys
def aggregate(df, ratio=False):
values = ['compress', 'decompress', 'dc_no_cache']
if ratio:
values.append('ratio')
results = {}
for size in ('small', 'mid', 'large... | [
"benchmark_analysis_utils.load_results_file"
] | [((1195, 1229), 'benchmark_analysis_utils.load_results_file', 'bau.load_results_file', (['sys.argv[1]'], {}), '(sys.argv[1])\n', (1216, 1229), True, 'import benchmark_analysis_utils as bau\n'), ((1444, 1478), 'benchmark_analysis_utils.load_results_file', 'bau.load_results_file', (['sys.argv[1]'], {}), '(sys.argv[1])\n'... |
import os
import pandas as pd
for file in os.listdir():
if file.endswith("json"):
reviews_data = pd.read_json("yelp_academic_dataset_review_41.json")
print(reviews_data.head())
break
| [
"os.listdir",
"pandas.read_json"
] | [((43, 55), 'os.listdir', 'os.listdir', ([], {}), '()\n', (53, 55), False, 'import os\n'), ((110, 162), 'pandas.read_json', 'pd.read_json', (['"""yelp_academic_dataset_review_41.json"""'], {}), "('yelp_academic_dataset_review_41.json')\n", (122, 162), True, 'import pandas as pd\n')] |
import sqlite3
import pomozne_fun
conn = sqlite3.connect("kosarka_turnir")
def najboljsi_na_turnirju():
'''vrne igralca z največ doseženimi točkami na turnirju,
v primeru ko je takšnih igralcev več vrne prvega po abecedi.'''
sql = '''
SELECT
ime,
priimek
... | [
"sqlite3.connect",
"pomozne_fun.ekipi_from_tekma",
"pomozne_fun.ekipa"
] | [((41, 74), 'sqlite3.connect', 'sqlite3.connect', (['"""kosarka_turnir"""'], {}), "('kosarka_turnir')\n", (56, 74), False, 'import sqlite3\n'), ((11402, 11424), 'pomozne_fun.ekipa', 'pomozne_fun.ekipa', (['id1'], {}), '(id1)\n', (11419, 11424), False, 'import pomozne_fun\n'), ((11442, 11464), 'pomozne_fun.ekipa', 'pomo... |
import weakref
import gc
from kivy.uix.screenmanager import WipeTransition, FadeTransition
from mpfmc.config_players.slide_player import McSlidePlayer
from mpfmc.tests.MpfMcTestCase import MpfMcTestCase
from mpfmc.transitions.move_in import MoveInTransition
from mpf.tests.MpfTestCase import MpfTestCase
import mpfmc.... | [
"gc.collect",
"weakref.ref",
"mpf.core.bcp.bcp_socket_client.encode_command_string",
"mpfmc.config_players.slide_player.McSlidePlayer"
] | [((1521, 1575), 'weakref.ref', 'weakref.ref', (["self.mc.targets['display1'].current_slide"], {}), "(self.mc.targets['display1'].current_slide)\n", (1532, 1575), False, 'import weakref\n'), ((1897, 1909), 'gc.collect', 'gc.collect', ([], {}), '()\n', (1907, 1909), False, 'import gc\n'), ((4804, 4858), 'weakref.ref', 'w... |
from distutils.core import setup, Extension
import sys
module1 = Extension('bsvcuckoo',
include_dirs=['include'],
sources=["src/cuckoo_filter.c", "src/cuckoo_python.c"],
# https://cibuildwheel.readthedocs.io/en/stable/faq/#windows-importerror-dll-load-failed-... | [
"distutils.core.Extension"
] | [((66, 247), 'distutils.core.Extension', 'Extension', (['"""bsvcuckoo"""'], {'include_dirs': "['include']", 'sources': "['src/cuckoo_filter.c', 'src/cuckoo_python.c']", 'extra_compile_args': "(['/d2FH4-'] if sys.platform == 'win32' else [])"}), "('bsvcuckoo', include_dirs=['include'], sources=[\n 'src/cuckoo_filter.... |
from importer import *
import sys, os
sys.path.append('/usr/data/minhas/zpace/stellarmass_pca')
import read_results as from_pca
pca_basedir = '/usr/data/minhas2/zpace/CSPs/CSPs_CKC14_MaNGA_20181026-1'
import numpy as np
import matplotlib.pyplot as plt
import pymc3
import manga_tools as m
import metallicity
import p... | [
"sys.path.append",
"pi_grid.elines_table.copy",
"metallicity.Elines.DAP_from_plateifu",
"metallicity.find_ism_params",
"pi_grid.load_CloudyFSPS_grid",
"manga_tools.load_drpall",
"os.path.join"
] | [((39, 96), 'sys.path.append', 'sys.path.append', (['"""/usr/data/minhas/zpace/stellarmass_pca"""'], {}), "('/usr/data/minhas/zpace/stellarmass_pca')\n", (54, 96), False, 'import sys, os\n'), ((448, 751), 'pi_grid.load_CloudyFSPS_grid', 'pi_grid.load_CloudyFSPS_grid', ([], {'linenames_fname': '"""./data/cloudyFSPS/line... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-06-22 07:28
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('siteEngine', '0004_auto_201... | [
"django.db.models.OneToOneField"
] | [((817, 916), 'django.db.models.OneToOneField', 'models.OneToOneField', ([], {'on_delete': 'django.db.models.deletion.CASCADE', 'to': 'settings.AUTH_USER_MODEL'}), '(on_delete=django.db.models.deletion.CASCADE, to=\n settings.AUTH_USER_MODEL)\n', (837, 916), False, 'from django.db import migrations, models\n'), ((47... |
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "quora.settings")
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
from whitenoise.django import DjangoWhiteNoise
application = Cling(get_wsgi_application())
application = DjangoWhiteNoise(application)
| [
"django.core.wsgi.get_wsgi_application",
"os.environ.setdefault",
"whitenoise.django.DjangoWhiteNoise"
] | [((10, 75), 'os.environ.setdefault', 'os.environ.setdefault', (['"""DJANGO_SETTINGS_MODULE"""', '"""quora.settings"""'], {}), "('DJANGO_SETTINGS_MODULE', 'quora.settings')\n", (31, 75), False, 'import os\n'), ((261, 290), 'whitenoise.django.DjangoWhiteNoise', 'DjangoWhiteNoise', (['application'], {}), '(application)\n'... |
import urllib.parse
from notifier.grabbers.base import Base, Internet
class BetterAdvice(object):
@staticmethod
def sync(obj: Base, *args, **kwargs):
r = Internet.html_get(obj.sync_type.base_url)
links = r.html.xpath('/html/body/div[*]/div[*]/div/div[*]/div[*]/section/div... | [
"notifier.grabbers.base.Internet.html_get"
] | [((194, 235), 'notifier.grabbers.base.Internet.html_get', 'Internet.html_get', (['obj.sync_type.base_url'], {}), '(obj.sync_type.base_url)\n', (211, 235), False, 'from notifier.grabbers.base import Base, Internet\n')] |
import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Activation, Dense,Flatten, Add, TimeDistributed, Flatten, BatchNormalization
from tensorflow.keras.layers import Conv1D,MaxPooling1D,GlobalAveragePooling1D, GlobalMaxPooling1D
from tensorflow.keras.layers import... | [
"tensorflow.keras.layers.Add",
"tensorflow.keras.layers.Activation",
"tensorflow.keras.layers.Flatten",
"tensorflow.keras.layers.Dense"
] | [((5507, 5512), 'tensorflow.keras.layers.Add', 'Add', ([], {}), '()\n', (5510, 5512), False, 'from tensorflow.keras.layers import Input, Activation, Dense, Flatten, Add, TimeDistributed, Flatten, BatchNormalization\n'), ((8674, 8679), 'tensorflow.keras.layers.Add', 'Add', ([], {}), '()\n', (8677, 8679), False, 'from te... |
#!/usr/bin/env python3
import sys
import os, inspect
try:
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)
from logic import *
except:
print("Could not import")
sys.exit(1)
def question_... | [
"os.path.dirname",
"sys.path.insert",
"sys.exit",
"inspect.currentframe"
] | [((167, 194), 'os.path.dirname', 'os.path.dirname', (['currentdir'], {}), '(currentdir)\n', (182, 194), False, 'import os, inspect\n'), ((199, 228), 'sys.path.insert', 'sys.path.insert', (['(0)', 'parentdir'], {}), '(0, parentdir)\n', (214, 228), False, 'import sys\n'), ((294, 305), 'sys.exit', 'sys.exit', (['(1)'], {}... |
from ov2640_constants import *
#los scripts de constantes lores y hires son para la resolucion
#se los encierra en try except para que si no son incluidos
#no haya problema, sin embargo dara problemas luego si uno de estos
#no es usado y especificado para la iniciacion de la camara
try:
from ov2640_lores_constants... | [
"uos.remove",
"time.sleep",
"gc.collect",
"time.sleep_us",
"ubinascii.hexlify",
"time.sleep_ms",
"gc.enable",
"machine.Pin"
] | [((771, 782), 'gc.enable', 'gc.enable', ([], {}), '()\n', (780, 782), False, 'import gc\n'), ((1522, 1562), 'machine.Pin', 'machine.Pin', (['self.cspin', 'machine.Pin.OUT'], {}), '(self.cspin, machine.Pin.OUT)\n', (1533, 1562), False, 'import machine\n'), ((1974, 1992), 'time.sleep_ms', 'time.sleep_ms', (['(100)'], {})... |
import threading
import os
import logging
import pprint
import traceback
import tempfile
from qtpy import QtCore
LOGGER = logging.getLogger(__name__)
class Executor(QtCore.QObject, threading.Thread):
"""Executor represents a thread of control that runs a python function with
a single input. Once created w... | [
"threading.Thread.__init__",
"qtpy.QtCore.QObject.__init__",
"tempfile.mkdtemp",
"traceback.format_exc",
"qtpy.QtCore.Signal",
"logging.getLogger"
] | [((125, 152), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (142, 152), False, 'import logging\n'), ((1508, 1523), 'qtpy.QtCore.Signal', 'QtCore.Signal', ([], {}), '()\n', (1521, 1523), False, 'from qtpy import QtCore\n'), ((1602, 1631), 'qtpy.QtCore.QObject.__init__', 'QtCore.QObject.__... |
"""Configuration for mkdocs_mdpo_plugin tests."""
import os
import sys
from tempfile import TemporaryDirectory
import polib
import pytest
import yaml
from mkdocs import config
from mkdocs.commands.build import build
from mkdocs_mdpo_plugin.plugin import MdpoPlugin
ROOT_DIR = os.path.abspath(os.path.dirname(os.path... | [
"sys.path.append",
"os.remove",
"tempfile.TemporaryDirectory",
"os.path.dirname",
"yaml.dump",
"os.path.isfile",
"os.path.normpath",
"mkdocs.config.load_config",
"polib.pofile",
"os.path.join"
] | [((375, 400), 'sys.path.append', 'sys.path.append', (['ROOT_DIR'], {}), '(ROOT_DIR)\n', (390, 400), False, 'import sys\n'), ((313, 338), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (328, 338), False, 'import os\n'), ((664, 684), 'tempfile.TemporaryDirectory', 'TemporaryDirectory', ([], {})... |
import binascii
import socket
import struct
import sys
string_address = 'fdf8:f53e:61e4::18'
packed = socket.inet_pton(socket.AF_INET6, string_address)
print('Original:', string_address)
print('Packed :', binascii.hexlify(packed))
print('Unpacked:', socket.inet_ntop(socket.AF_INET6, packed))
| [
"binascii.hexlify",
"socket.inet_pton",
"socket.inet_ntop"
] | [((103, 152), 'socket.inet_pton', 'socket.inet_pton', (['socket.AF_INET6', 'string_address'], {}), '(socket.AF_INET6, string_address)\n', (119, 152), False, 'import socket\n'), ((208, 232), 'binascii.hexlify', 'binascii.hexlify', (['packed'], {}), '(packed)\n', (224, 232), False, 'import binascii\n'), ((253, 294), 'soc... |
"""
Licensed Materials - Property of IBM
Restricted Materials of IBM
20190891
© Copyright IBM Corp. 2020 All Rights Reserved.
"""
import logging
import keras
import time
import json
import numpy as np
import tensorflow as tf
from tensorflow.python.keras.backend import set_session
from keras import backend as k
from k... | [
"keras.models.load_model",
"tensorflow.keras.models.model_from_json",
"ibmfl.exceptions.FLException",
"tensorflow.keras.models.load_model",
"tensorflow.Session",
"ibmfl.model.model_update.ModelUpdate",
"json.dumps",
"time.time",
"ibmfl.exceptions.LocalTrainingException",
"ibmfl.util.config.get_abs... | [((701, 728), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (718, 728), False, 'import logging\n'), ((1498, 1520), 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), '()\n', (1518, 1520), True, 'import tensorflow as tf\n'), ((1541, 1553), 'tensorflow.Session', 'tf.Session'... |
# !/usr/bin/python
from tornado import ioloop
async def cal(num):
print('cal called.')
x = await calculator(num)
print(x)
async def calculator(num):
try:
result = 0
for i in range(0, num):
result += i
# print(f'result is {result}')
raise Exception()
... | [
"tornado.ioloop.IOLoop.current"
] | [((510, 533), 'tornado.ioloop.IOLoop.current', 'ioloop.IOLoop.current', ([], {}), '()\n', (531, 533), False, 'from tornado import ioloop\n')] |
from pathlib import Path
import os
path = Path(os.getcwd())
npath = path.joinpath('zizi')
# print(path)
# print(npath.parts)
# print(npath.name)
# for idx, dirz in enumerate(path.iterdir()):
# print(idx, dirz)
#
for idx, file in enumerate(path.glob('*.zip')):
print(idx,file)
#
# pp = list(path.glob('*.py'))
... | [
"os.getcwd"
] | [((48, 59), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (57, 59), False, 'import os\n')] |
import unittest
import cv2
import numpy as np
from extractor.cropping import clip_to_image_region, \
crop_module, build_merged_index
quadrilaterals = {
('e3e70682-c209-4cac-a29f-6fbed82c07cd',
'frame_000000',
'mask_000000'): {
'quadrilateral': [
[424, 279],
[499, 28... | [
"numpy.copy",
"extractor.cropping.build_merged_index",
"numpy.allclose",
"extractor.cropping.crop_module",
"cv2.imread",
"numpy.array",
"numpy.eye"
] | [((1901, 1967), 'numpy.array', 'np.array', (['[[[424, 279]], [[499, 280]], [[499, 327]], [[421, 323]]]'], {}), '([[[424, 279]], [[499, 280]], [[499, 327]], [[421, 323]]])\n', (1909, 1967), True, 'import numpy as np\n'), ((2458, 2524), 'numpy.array', 'np.array', (['[[[424, 279]], [[499, 280]], [[499, 327]], [[421, 323]]... |
import graphene
from graphene import relay
from graphene_sqlalchemy import SQLAlchemyObjectType
from core.models import Category as CategoryModel
from core.models import CategoryConnector
category_connector = CategoryConnector()
class CategoryNode(SQLAlchemyObjectType):
class Meta:
model = CategoryModel... | [
"core.models.CategoryConnector",
"graphene.Int",
"graphene.String"
] | [((211, 230), 'core.models.CategoryConnector', 'CategoryConnector', ([], {}), '()\n', (228, 230), False, 'from core.models import CategoryConnector\n'), ((473, 503), 'graphene.String', 'graphene.String', ([], {'required': '(True)'}), '(required=True)\n', (488, 503), False, 'import graphene\n'), ((986, 1013), 'graphene.... |
from dcim.models import Site, Rack, DeviceRole, DeviceType, Device, Platform
from ipam.models import IPAddress
from startup_script_utils import load_yaml
import sys
devices = load_yaml('/opt/netbox/initializers/dcim_devices.yml')
if devices is None:
sys.exit()
handled_attrs = [
'primary_ip4_id',
'primary_ip6_i... | [
"dcim.models.Device.objects.filter",
"startup_script_utils.load_yaml",
"sys.exit"
] | [((176, 230), 'startup_script_utils.load_yaml', 'load_yaml', (['"""/opt/netbox/initializers/dcim_devices.yml"""'], {}), "('/opt/netbox/initializers/dcim_devices.yml')\n", (185, 230), False, 'from startup_script_utils import load_yaml\n'), ((254, 264), 'sys.exit', 'sys.exit', ([], {}), '()\n', (262, 264), False, 'import... |
import sqlite3, ast
##############################################
### Login to database
##############################################
def login(dbfile):
conn = sqlite3.connect(dbfile) # create or open db file
curs = conn.cursor()
return conn, curs
###########################################... | [
"sqlite3.connect"
] | [((175, 198), 'sqlite3.connect', 'sqlite3.connect', (['dbfile'], {}), '(dbfile)\n', (190, 198), False, 'import sqlite3, ast\n')] |
import os
import json
import boto3
ssm = boto3.client('ssm')
def query_association():
query_association_response = ssm.list_associations(
AssociationFilterList = [
{
"key": "AssociationName",
"value": "ssm-patch-portal-scan"
}
],
)
... | [
"boto3.client",
"json.dumps"
] | [((43, 62), 'boto3.client', 'boto3.client', (['"""ssm"""'], {}), "('ssm')\n", (55, 62), False, 'import boto3\n'), ((1400, 1420), 'json.dumps', 'json.dumps', (['response'], {}), '(response)\n', (1410, 1420), False, 'import json\n')] |
# Generated by Django 2.0.7 on 2018-07-09 08:15
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Heartbeat',
fields=[
('id', models.AutoFiel... | [
"django.db.models.CharField",
"django.db.models.DateTimeField",
"django.db.models.AutoField"
] | [((305, 398), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (321, 398), False, 'from django.db import migrations, models\... |
from django.db import models
import datetime as dt
# Create your models here.
class Category(models.Model):
category_name = models.CharField(max_length = 50)
# image = models.ForeignKey(Image)
def __str__(self):
return self.category_name
class Location(models.Model):
location_name = models.... | [
"django.db.models.TextField",
"django.db.models.CharField",
"django.db.models.ForeignKey",
"datetime.date.today",
"django.db.models.ImageField",
"django.db.models.DateTimeField"
] | [((131, 162), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)'}), '(max_length=50)\n', (147, 162), False, 'from django.db import models\n'), ((313, 344), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)'}), '(max_length=50)\n', (329, 344), False, 'from django.db im... |