code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
# -*- coding: utf-8 -*-
"""
utilities.
"""
from __future__ import print_function, unicode_literals
import os
def make_dir(abspath):
"""
Make an empty directory.
"""
try:
os.mkdir(abspath)
print("Made: %s" % abspath)
except: # pragma: no cover
pass
def make_file(abspath... | [
"os.mkdir"
] | [((198, 215), 'os.mkdir', 'os.mkdir', (['abspath'], {}), '(abspath)\n', (206, 215), False, 'import os\n')] |
import PySimpleGUI as sg
from PySimpleGUI.PySimpleGUI import clipboard_get, clipboard_set
from backend import summarize_text
def run_gui():
large_font = ("Helvetica", 15)
# define the layout
layout = [ [sg.Text('Enter text to be summarized here:',font=large_font), sg.Text('', key='_OUTPUT_')],
... | [
"PySimpleGUI.PySimpleGUI.clipboard_set",
"PySimpleGUI.Slider",
"PySimpleGUI.PySimpleGUI.clipboard_get",
"PySimpleGUI.Text",
"PySimpleGUI.Multiline",
"PySimpleGUI.Button",
"PySimpleGUI.Window"
] | [((216, 277), 'PySimpleGUI.Text', 'sg.Text', (['"""Enter text to be summarized here:"""'], {'font': 'large_font'}), "('Enter text to be summarized here:', font=large_font)\n", (223, 277), True, 'import PySimpleGUI as sg\n'), ((278, 305), 'PySimpleGUI.Text', 'sg.Text', (['""""""'], {'key': '"""_OUTPUT_"""'}), "('', key=... |
import sys
seq = []
for line in sys.stdin.read().strip().split('\n'):
on, pos = line.split(' ')
iv = tuple(tuple(int(v) for v in l.split('=')[1].split('..')) for l in line.split(','))
seq.append((on == 'on', iv))
def splitIntersection(i0, i1):
xs, ys, zs = [sorted(i0[i] + i1[i]) for i in range(3)]
... | [
"sys.stdin.read"
] | [((34, 50), 'sys.stdin.read', 'sys.stdin.read', ([], {}), '()\n', (48, 50), False, 'import sys\n')] |
from core.function_context import *
from config.utils import *
from collections import defaultdict
import config.libc_config as libc
class ExternalFunction(CodeContext):
"""A context that describes a source-code point of view of an external function, using references from/to it.
Attrib... | [
"collections.defaultdict"
] | [((30534, 30550), 'collections.defaultdict', 'defaultdict', (['set'], {}), '(set)\n', (30545, 30550), False, 'from collections import defaultdict\n'), ((31760, 31776), 'collections.defaultdict', 'defaultdict', (['set'], {}), '(set)\n', (31771, 31776), False, 'from collections import defaultdict\n')] |
#
# Copyright (c) 2019 Intel Corporation
#
# 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... | [
"tabulate.tabulate",
"click.Choice",
"util.logger.initialize_logger",
"util.cli_state.common_options",
"util.system.handle_error",
"click.option",
"cli_text_consts.PredictBatchCmdTexts.MISSING_MODEL_LOCATION_ERROR_MSG.format",
"commands.predict.common.start_inference_instance",
"click.Path",
"os.p... | [((1343, 1370), 'util.logger.initialize_logger', 'initialize_logger', (['__name__'], {}), '(__name__)\n', (1360, 1370), False, 'from util.logger import initialize_logger\n'), ((1404, 1498), 'click.command', 'click.command', ([], {'short_help': 'Texts.HELP', 'cls': 'AliasCmd', 'alias': '"""b"""', 'options_metavar': '"""... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-08-23 16:20
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):
initial = True
dependencies = [
migratio... | [
"django.db.models.OneToOneField",
"django.db.models.ForeignKey",
"django.db.models.IntegerField",
"django.db.models.ManyToManyField",
"django.db.models.BooleanField",
"django.db.models.AutoField",
"django.db.models.DecimalField",
"django.db.migrations.swappable_dependency",
"django.db.models.CharFie... | [((312, 369), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (343, 369), False, 'from django.db import migrations, models\n'), ((2457, 2546), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'djang... |
from typing import Union, Iterable, Coroutine, Callable
from inspect import isfunction, ismethod, isroutine, iscoroutine, signature, _empty
import discord
from .. import errors
from .. import utils
# Class Command
class Command:
def __init__(self, _function: Union[Callable, Coroutine], name: str = None, aliases: ... | [
"inspect.isfunction",
"inspect.signature",
"inspect.isroutine"
] | [((1127, 1148), 'inspect.isfunction', 'isfunction', (['_function'], {}), '(_function)\n', (1137, 1148), False, 'from inspect import isfunction, ismethod, isroutine, iscoroutine, signature, _empty\n'), ((1477, 1494), 'inspect.isfunction', 'isfunction', (['check'], {}), '(check)\n', (1487, 1494), False, 'from inspect imp... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# 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
#
# ... | [
"ironic.common.exception.ProcessExecutionError",
"os.path.isfile",
"ironic.common.exception.FileNotFound",
"ironic.common.exception.PowerStateFailure",
"ironic.openstack.common.log.getLogger"
] | [((1265, 1292), 'ironic.openstack.common.log.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1282, 1292), True, 'from ironic.openstack.common import log as logging\n'), ((3134, 3235), 'ironic.common.exception.ProcessExecutionError', 'exception.ProcessExecutionError', ([], {'exit_code': 'exit_statu... |
import pytest
from test.utils.test_fixtures.classes_under_test import generator
@pytest.mark.parametrize(
"sort_code,account_number", [
("118765", "64371389")
])
def test_known_values_for_exception_1(generator, sort_code, account_number):
assert generator.validate(sort_code=sort_code, account_numb... | [
"pytest.mark.parametrize",
"test.utils.test_fixtures.classes_under_test.generator.validate"
] | [((83, 160), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""sort_code,account_number"""', "[('118765', '64371389')]"], {}), "('sort_code,account_number', [('118765', '64371389')])\n", (106, 160), False, 'import pytest\n'), ((342, 495), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""sort_code,a... |
#
# Copyright (c) 2014 Piston Cloud Computing, Inc. 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
#
# ... | [
"httmock.response",
"httmock.urlmatch",
"mock.patch",
"httmock.HTTMock",
"json.dumps",
"os.path.join",
"os.environ.get",
"refstack_client.refstack_client.RefstackClient",
"refstack_client.refstack_client.parse_cli_args",
"os.path.realpath",
"os.chmod",
"os.path.dirname",
"os.path.basename",
... | [((17862, 17891), 'mock.patch', 'mock.patch', (['"""six.moves.input"""'], {}), "('six.moves.input')\n", (17872, 17891), False, 'import mock\n'), ((25056, 25132), 'mock.patch', 'mock.patch', (['"""refstack_client.list_parser.TestListParser.create_include_list"""'], {}), "('refstack_client.list_parser.TestListParser.crea... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-03 16:56
from __future__ import unicode_literals
from django.contrib.auth.management import create_permissions
from django.contrib.auth.models import Permission, Group
from django.db import migrations
def add_in_progress_perm(apps, schema_editor):
... | [
"django.contrib.auth.models.Permission.objects.get",
"django.contrib.auth.models.Group.objects.all",
"django.contrib.auth.management.create_permissions",
"django.db.migrations.AlterModelOptions",
"django.db.migrations.RunPython"
] | [((523, 578), 'django.contrib.auth.models.Permission.objects.get', 'Permission.objects.get', ([], {'codename': '"""can_save_in_progress"""'}), "(codename='can_save_in_progress')\n", (545, 578), False, 'from django.contrib.auth.models import Permission, Group\n'), ((596, 615), 'django.contrib.auth.models.Group.objects.a... |
# Generated by Django 4.0 on 2021-12-21 20:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('observe', '0009_alter_observinglocation_options'),
]
operations = [
migrations.AlterField(
model_name='observinglocation',
... | [
"django.db.models.CharField"
] | [((358, 594), 'django.db.models.CharField', 'models.CharField', ([], {'choices': "[('TBD', 'TBD'), ('Possible', 'Possible'), ('Issues', 'Issues'), (\n 'Provisional', 'Provisional'), ('Active', 'Active'), ('Rejected',\n 'Rejected')]", 'default': '"""TBD"""', 'max_length': '(50)', 'verbose_name': '"""Status"""'}), ... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import numpy as np
import scipy.ndimage
from config import config
class FlawDetector(nn.Module):
""" The FC Discriminator proposed in paper:
'Guided Collaborative Training for Pixel-wise Semi-Supervised Learning'
"""
n... | [
"numpy.clip",
"torch.nn.functional.mse_loss",
"torch.nn.LeakyReLU",
"math.floor",
"torch.mean",
"torch.nn.ReflectionPad2d",
"torch.from_numpy",
"torch.nn.InstanceNorm2d",
"torch.nn.Conv2d",
"numpy.exp",
"numpy.zeros",
"torch.nn.MaxPool2d",
"torch.sum",
"torch.nn.functional.interpolate",
... | [((478, 546), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_channels', 'self.ndf'], {'kernel_size': '(4)', 'stride': '(2)', 'padding': '(1)'}), '(in_channels, self.ndf, kernel_size=4, stride=2, padding=1)\n', (487, 546), True, 'import torch.nn as nn\n'), ((628, 697), 'torch.nn.Conv2d', 'nn.Conv2d', (['self.ndf', '(self.ndf * 2... |
# coding=utf-8
from time_series_detector.algorithm.prophet import predict
# 示例数据
# l = [2,1,4,7,4,8,3,6,4,8]
l = [660, 719, 649, 674, 672, 683, 679, 642, 758, 777, 731, 791, 776, 692, 724, 665, 698, 644, 691, 651, 710, 650, 576,
591, 589, 639, 655, 620, 678, 619, 620, 608, 604, 618, 598, 617, 584, 542, 584, 625, ... | [
"time_series_detector.algorithm.prophet.predict"
] | [((2002, 2012), 'time_series_detector.algorithm.prophet.predict', 'predict', (['l'], {}), '(l)\n', (2009, 2012), False, 'from time_series_detector.algorithm.prophet import predict\n')] |
#引入需要的模块
import os
import time
import sys
import codecs
sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
# 更新代码
os.system("php /root/start.php")
#定义grep关键词,和需要执行的命令
keyList = {
# 'rad.php':'cd /root/qingscan/edge && php rad.php >> ./tmp/edge_rad.txt & ',
# 'xray.php':'cd /root/qingscan/edge && ... | [
"codecs.getwriter",
"time.sleep",
"sys.stdout.detach",
"os.popen",
"os.system"
] | [((124, 156), 'os.system', 'os.system', (['"""php /root/start.php"""'], {}), "('php /root/start.php')\n", (133, 156), False, 'import os\n'), ((69, 94), 'codecs.getwriter', 'codecs.getwriter', (['"""utf-8"""'], {}), "('utf-8')\n", (85, 94), False, 'import codecs\n'), ((95, 114), 'sys.stdout.detach', 'sys.stdout.detach',... |
from django.contrib import admin
from .models import chat
# Register your models here.
admin.site.register(chat)
# admin.site.register(fk_model)
| [
"django.contrib.admin.site.register"
] | [((88, 113), 'django.contrib.admin.site.register', 'admin.site.register', (['chat'], {}), '(chat)\n', (107, 113), False, 'from django.contrib import admin\n')] |
"""
Decoding module for a neural speaker (with attention capabilities).
The MIT License (MIT)
Originally created at 06/15/19, for Python 3.x
Copyright (c) 2021 <NAME> (ai.stanford.edu/~optas) & Stanford Geometric Computing Lab
"""
import torch
import random
import time
import warnings
import tqdm
import math
import n... | [
"torch.nn.Dropout",
"torch.LongTensor",
"torch.exp",
"numpy.argsort",
"torch.log2",
"numpy.array",
"torch.softmax",
"torch.sum",
"torch.repeat_interleave",
"torch.arange",
"torch.nn.Sigmoid",
"torch.unsqueeze",
"torch.nn.Identity",
"torch.zeros_like",
"torch.argmax",
"torch.nn.utils.rn... | [((14065, 14080), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (14078, 14080), False, 'import torch\n'), ((15238, 15253), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (15251, 15253), False, 'import torch\n'), ((16902, 16917), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (16915, 16917), False, 'impo... |
""" Load data for the zip code location table. The file has the following format.
zip,city,state,lat,long
"""
import csv
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
import os
from ...models import ZipCodeLocation
class Command(BaseCommand):
args = "<csv... | [
"django.core.management.base.CommandError",
"csv.DictReader",
"os.path.exists",
"django.db.transaction.commit_on_success"
] | [((1498, 1521), 'csv.DictReader', 'csv.DictReader', (['csvfile'], {}), '(csvfile)\n', (1512, 1521), False, 'import csv\n'), ((456, 487), 'django.db.transaction.commit_on_success', 'transaction.commit_on_success', ([], {}), '()\n', (485, 487), False, 'from django.db import transaction\n'), ((947, 986), 'django.core.mana... |
#!/usr/local/bin/python3
from datetime import datetime
import sys
from notion.collection import NotionDate
import pygsheets
import pandas
import json
from notion_api import notion_api
from notion_api import config
from utils import tags_json, office_category_json, office_quarter_json, log
# from utils import office_q... | [
"notion_api.notion_api.office_project_database",
"datetime.datetime.strptime",
"notion_api.config.sheet_id",
"json.dumps",
"pygsheets.authorize",
"sys.stderr.write",
"utils.tags_json",
"pandas.DataFrame",
"utils.office_quarter_json",
"notion_api.notion_api.get_row"
] | [((400, 421), 'utils.office_quarter_json', 'office_quarter_json', ([], {}), '()\n', (419, 421), False, 'from utils import tags_json, office_category_json, office_quarter_json, log\n'), ((437, 448), 'utils.tags_json', 'tags_json', ([], {}), '()\n', (446, 448), False, 'from utils import tags_json, office_category_json, o... |
"""
Django settings for RNAPuzzles project.
Generated by 'django-admin startproject' using Django 2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
... | [
"os.path.abspath",
"os.path.join",
"os.getenv"
] | [((681, 713), 'os.getenv', 'os.getenv', (['"""SECRET_KEY"""', '"""<KEY>"""'], {}), "('SECRET_KEY', '<KEY>')\n", (690, 713), False, 'import os\n'), ((5047, 5078), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""media"""'], {}), "(BASE_DIR, 'media')\n", (5059, 5078), False, 'import os\n'), ((789, 816), 'os.getenv', 'os... |
#!/usr/bin/env python3
import sys
# import osgeo_utils.gdal_merge as a convenience to use as a script
from osgeo_utils.gdal_merge import * # noqa
from osgeo_utils.gdal_merge import main
from osgeo.gdal import deprecation_warn
deprecation_warn('gdal_merge')
sys.exit(main(sys.argv))
| [
"osgeo_utils.gdal_merge.main",
"osgeo.gdal.deprecation_warn"
] | [((230, 260), 'osgeo.gdal.deprecation_warn', 'deprecation_warn', (['"""gdal_merge"""'], {}), "('gdal_merge')\n", (246, 260), False, 'from osgeo.gdal import deprecation_warn\n'), ((270, 284), 'osgeo_utils.gdal_merge.main', 'main', (['sys.argv'], {}), '(sys.argv)\n', (274, 284), False, 'from osgeo_utils.gdal_merge import... |
import hypothesis
import numpy as np
import pytest
import torch
from hypothesis.extra.numpy import arrays, array_shapes
from hypothesis.strategies import floats
from torch.testing import assert_allclose
from dsntnn import average_loss, euclidean_losses, l1_losses, mse_losses
_LOSSES_FNS = {
'euclidean': euclidean... | [
"torch.testing.assert_allclose",
"torch.as_tensor",
"dsntnn.average_loss",
"dsntnn.euclidean_losses",
"hypothesis.strategies.floats",
"torch.tensor",
"pytest.fixture",
"torch.zeros_like",
"torch.randn",
"hypothesis.extra.numpy.array_shapes"
] | [((448, 497), 'pytest.fixture', 'pytest.fixture', ([], {'params': "['euclidean', 'l1', 'mse']"}), "(params=['euclidean', 'l1', 'mse'])\n", (462, 497), False, 'import pytest\n'), ((1988, 2036), 'torch.tensor', 'torch.tensor', (['[[0.0, 1.0, 0.0], [1.0, 0.0, 0.0]]'], {}), '([[0.0, 1.0, 0.0], [1.0, 0.0, 0.0]])\n', (2000, ... |
import numpy as np
from PIL import Image
from typing import Tuple
SQUARE_COLOR = (255, 0, 0, 255) # Let's make a red square
ICON_SIZE = (512, 512) # The recommended minimum size from WordPress
def generate_pixels(resolution: Tuple[int, int]) -> np.ndarray:
"""Generate pixels of an image with the provi... | [
"numpy.array",
"PIL.Image.fromarray"
] | [((657, 689), 'numpy.array', 'np.array', (['pixels'], {'dtype': 'np.uint8'}), '(pixels, dtype=np.uint8)\n', (665, 689), True, 'import numpy as np\n'), ((969, 996), 'PIL.Image.fromarray', 'Image.fromarray', (['img_pixels'], {}), '(img_pixels)\n', (984, 996), False, 'from PIL import Image\n')] |
import pygame
pygame.init()
clock = pygame.time.Clock()
fps = 60
#game window
bottom_panel = 150
screen_width = 800
screen_height = 400 + bottom_panel
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Battle')
#load images
#background image
background_img = pygame.image.l... | [
"pygame.init",
"pygame.quit",
"pygame.event.get",
"pygame.display.set_mode",
"pygame.time.Clock",
"pygame.display.set_caption",
"pygame.image.load",
"pygame.display.update"
] | [((15, 28), 'pygame.init', 'pygame.init', ([], {}), '()\n', (26, 28), False, 'import pygame\n'), ((38, 57), 'pygame.time.Clock', 'pygame.time.Clock', ([], {}), '()\n', (55, 57), False, 'import pygame\n'), ((164, 218), 'pygame.display.set_mode', 'pygame.display.set_mode', (['(screen_width, screen_height)'], {}), '((scre... |
import signal, os, sys, mouse, ctypes, time, win32api, pynput
from serial import Serial
from pynput.keyboard import Key, Controller
from ctypes import wintypes
from MyKeyboard import PressKey
from pynput.mouse import Button, Controller
#=========================== FUNCTIONS ===========================#
d... | [
"signal.signal",
"serial.Serial",
"MyKeyboard.PressKey",
"sys.exit",
"pynput.mouse.Controller",
"ctypes.windll.user32.mouse_event"
] | [((1131, 1171), 'signal.signal', 'signal.signal', (['signal.SIGINT', 'endProgram'], {}), '(signal.SIGINT, endProgram)\n', (1144, 1171), False, 'import signal, os, sys, mouse, ctypes, time, win32api, pynput\n'), ((2301, 2313), 'pynput.mouse.Controller', 'Controller', ([], {}), '()\n', (2311, 2313), False, 'from pynput.m... |
import os
from reinforcement_learning.crypto_market.comitee_trader_agent import ComiteeTraderAgent
from reinforcement_learning.crypto_market.crypto_trader_agent import CryptoTraderAgent
import sys
sys.path.insert(0, '../../../etf_data')
from etf_data_loader import load_all_data_from_file2
import numpy as np
import ... | [
"sys.path.insert",
"matplotlib.pyplot.plot",
"numpy.warnings.filterwarnings",
"reinforcement_learning.crypto_market.comitee_trader_agent.ComiteeTraderAgent",
"etf_data_loader.load_all_data_from_file2",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show"
] | [((200, 239), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""../../../etf_data"""'], {}), "(0, '../../../etf_data')\n", (215, 239), False, 'import sys\n'), ((503, 588), 'etf_data_loader.load_all_data_from_file2', 'load_all_data_from_file2', (["(prefix + 'etf_data_adj_close.csv')", 'start_date', 'end_date'], {}), "(... |
from __future__ import annotations
from textwrap import dedent
from typing import TYPE_CHECKING
import numpy as np
import pandas as pd
from pandas.util._decorators import doc
from sklearn.pipeline import FeatureUnion as SKFeatureUnion
from sklearn.preprocessing import MinMaxScaler as SKMinMaxScaler
from sklearn.prepr... | [
"textwrap.dedent",
"dtoolkit.transformer._util.transform_array_to_frame",
"pandas.util._decorators.doc",
"sklearn.pipeline._name_estimators",
"itertools.chain.from_iterable",
"dtoolkit.transformer._util.transform_series_to_frame",
"pandas.DataFrame",
"pandas.concat"
] | [((7663, 7692), 'pandas.util._decorators.doc', 'doc', (['SKOneHotEncoder.__init__'], {}), '(SKOneHotEncoder.__init__)\n', (7666, 7692), False, 'from pandas.util._decorators import doc\n'), ((2739, 2769), 'sklearn.pipeline._name_estimators', '_name_estimators', (['transformers'], {}), '(transformers)\n', (2755, 2769), F... |
from setuptools import setup
setup(
name = 'wikidata',
packages = ['wikidata'], # this must be the same as the name above
version = '0.1',
description = 'An API for exploiting Wikidata dump',
author = '<NAME>, <NAME>',
author_email = '<EMAIL>, <EMAIL>',
keywords = ['api', 'wikidata', 'LOD'], # arbitrary k... | [
"setuptools.setup"
] | [((29, 585), 'setuptools.setup', 'setup', ([], {'name': '"""wikidata"""', 'packages': "['wikidata']", 'version': '"""0.1"""', 'description': '"""An API for exploiting Wikidata dump"""', 'author': '"""<NAME>, <NAME>"""', 'author_email': '"""<EMAIL>, <EMAIL>"""', 'keywords': "['api', 'wikidata', 'LOD']", 'classifiers': "... |
from flask_wtf import FlaskForm
from wtforms.validators import Length
from wtforms import TextAreaField
class NoticeForm(FlaskForm):
body = TextAreaField('notice', validators=[Length(0, 25)])
| [
"wtforms.validators.Length"
] | [((182, 195), 'wtforms.validators.Length', 'Length', (['(0)', '(25)'], {}), '(0, 25)\n', (188, 195), False, 'from wtforms.validators import Length\n')] |
# Copyright 2018 <NAME> and individual contributors
#
# 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 agr... | [
"nacl._sodium.lib.crypto_kx_publickeybytes",
"nacl._sodium.lib.crypto_kx_seedbytes",
"nacl._sodium.lib.crypto_kx_sessionkeybytes",
"nacl._sodium.ffi.new",
"nacl._sodium.lib.crypto_kx_seed_keypair",
"nacl.exceptions.ensure",
"nacl._sodium.lib.crypto_kx_client_session_keys",
"nacl._sodium.ffi.buffer",
... | [((1130, 1160), 'nacl._sodium.lib.crypto_kx_publickeybytes', 'lib.crypto_kx_publickeybytes', ([], {}), '()\n', (1158, 1160), False, 'from nacl._sodium import ffi, lib\n'), ((1190, 1220), 'nacl._sodium.lib.crypto_kx_secretkeybytes', 'lib.crypto_kx_secretkeybytes', ([], {}), '()\n', (1218, 1220), False, 'from nacl._sodiu... |
import threading
import numpy as np
import SimpleITK as sitk
class NiftiGenerator2D_ExtraInput(object):
def __init__(self, batch_size, image_locations,
labels, image_size, extra_inputs, random_shuffle=True):
self.n = len(image_locations)
self.batch_size = batch_size
self.... | [
"threading.Lock",
"SimpleITK.GetArrayFromImage",
"numpy.zeros",
"numpy.concatenate",
"SimpleITK.ReadImage",
"numpy.arange",
"numpy.random.permutation"
] | [((392, 408), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (406, 408), False, 'import threading\n'), ((2264, 2334), 'numpy.zeros', 'np.zeros', (['(self.batch_size, self.image_size[0], self.image_size[1], 1)'], {}), '((self.batch_size, self.image_size[0], self.image_size[1], 1))\n', (2272, 2334), True, 'import ... |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class cpBatchNorm2d(torch.nn.BatchNorm2d):
def __init__(self, *args, **kwargs):
super(cpBatchNorm2d, self).__init__(*args, **kwargs)
def forward(self, input):
self._check_input_dim(input)
if input.requires... | [
"math.sqrt",
"torch.exp",
"torch.sum",
"torch.nn.functional.pad",
"torch.nn.functional.batch_norm",
"torch.arange"
] | [((3656, 3696), 'torch.nn.functional.pad', 'F.pad', (['input', 'pad_values'], {'mode': '"""reflect"""'}), "(input, pad_values, mode='reflect')\n", (3661, 3696), True, 'import torch.nn.functional as F\n'), ((777, 951), 'torch.nn.functional.batch_norm', 'F.batch_norm', (['input', 'self.running_mean', 'self.running_var', ... |
# 10^n is n+1 digits so base can only be [1,9]
from time import time
t1 = time()
ans = 0
for a in range(1, 10):
for b in range(1, 100):
if b == len(str(a**b)):
ans += 1
print(ans)
print(f"Process completed in {time()-t1}s")
| [
"time.time"
] | [((75, 81), 'time.time', 'time', ([], {}), '()\n', (79, 81), False, 'from time import time\n'), ((235, 241), 'time.time', 'time', ([], {}), '()\n', (239, 241), False, 'from time import time\n')] |
import functools
from django.core.exceptions import ObjectDoesNotExist
from django.core.cache import cache
from django.utils.translation import ugettext as _
from app.models.test_language import TestLanguage
from app.models.german_language import GermanLanguage
from app.models.english_language import EnglishLanguage
... | [
"django.utils.translation.ugettext",
"functools.partial"
] | [((2071, 2124), 'functools.partial', 'functools.partial', (['self.__exact_lookup', 'possible_word'], {}), '(self.__exact_lookup, possible_word)\n', (2088, 2124), False, 'import functools\n'), ((722, 771), 'django.utils.translation.ugettext', '_', (['"""Language "%(language_string)s" not existing."""'], {}), '(\'Languag... |
from behave import *
import test_data
# I open the <name> scene
@given('I open the {name} scene')
def step_impl(context, name):
# Loads the scene mentioned by its name.
test_data.altUnityDriver.load_scene(name)
| [
"test_data.altUnityDriver.load_scene"
] | [((179, 220), 'test_data.altUnityDriver.load_scene', 'test_data.altUnityDriver.load_scene', (['name'], {}), '(name)\n', (214, 220), False, 'import test_data\n')] |
#%%
import pandas as pd
import psycopg2
import os
import matplotlib
from sqlalchemy import create_engine
# from tqdm import notebook_tqdm
from config import DB_PASSWORD, DB_NAME
#%%
# Create a database connection
db_password = DB_PASSWORD # Set to your own password
db_name = DB_NAME # Set to your own db name
engine... | [
"pandas.read_sql_query",
"os.listdir",
"pandas.read_csv",
"sqlalchemy.create_engine",
"pandas.read_sql",
"pandas.to_datetime"
] | [((323, 396), 'sqlalchemy.create_engine', 'create_engine', (['f"""postgresql://postgres:{db_password}@localhost/{db_name}"""'], {}), "(f'postgresql://postgres:{db_password}@localhost/{db_name}')\n", (336, 396), False, 'from sqlalchemy import create_engine\n'), ((5017, 5082), 'pandas.read_sql', 'pd.read_sql', (['"""dail... |
from Models.NN.MultiNNRec import MultiDistilBertRec
from Utils.Data.Data import get_dataset, get_feature, get_feature_reader
from Utils.Submission.Submission import create_submission_file
import numpy as np
import time
from Utils.TelegramBot import telegram_bot_send_update
def main():
'''
feature_list = [
... | [
"Utils.Data.Data.get_dataset",
"Utils.Data.Data.get_feature_reader",
"Utils.Submission.Submission.create_submission_file",
"Utils.Data.Data.get_feature",
"Models.NN.MultiNNRec.MultiDistilBertRec",
"time.time"
] | [((6300, 6332), 'Models.NN.MultiNNRec.MultiDistilBertRec', 'MultiDistilBertRec', ([], {}), '(**rec_params)\n', (6318, 6332), False, 'from Models.NN.MultiNNRec import MultiDistilBertRec\n'), ((6349, 6409), 'Utils.Data.Data.get_dataset', 'get_dataset', ([], {'features': 'feature_list', 'dataset_id': 'train_dataset'}), '(... |
__all__ = ["assign_attributes", "get_attributes"]
def assign_attributes(data, site, sampling_period=None, network=None):
""" Assign attributes to the data we've processed. This ensures that the xarray Datasets produced
as CF 1.7 compliant. Some of the attributes written to the Dataset are saved as metadat... | [
"json.load",
"pandas.Timestamp.now",
"pandas.Timestamp",
"HUGS.Util.get_datapath"
] | [((4017, 4065), 'HUGS.Util.get_datapath', 'get_datapath', ([], {'filename': '"""species_attributes.json"""'}), "(filename='species_attributes.json')\n", (4029, 4065), False, 'from HUGS.Util import get_datapath\n'), ((4170, 4210), 'HUGS.Util.get_datapath', 'get_datapath', ([], {'filename': '"""attributes.json"""'}), "(f... |
from beluga.utils import load
import matplotlib.pyplot as plt
data = load('data.beluga')
sol_set = data['solutions']
traj = sol_set[-1][-1]
continuation = sol_set[-1]
L = len(continuation)
plt.figure()
for ind, sol in enumerate(continuation):
plt.plot(sol.y[:, 0], sol.y[:, 1], linestyle='-', color=(1*(ind/L), 0,... | [
"matplotlib.pyplot.grid",
"beluga.utils.load",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.title",
"matplotlib.pyplot.show"
] | [((70, 89), 'beluga.utils.load', 'load', (['"""data.beluga"""'], {}), "('data.beluga')\n", (74, 89), False, 'from beluga.utils import load\n'), ((192, 204), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (202, 204), True, 'import matplotlib.pyplot as plt\n'), ((336, 359), 'matplotlib.pyplot.title', 'plt.ti... |
import PyPDF2, os
#create a list to store the list of PDF files in the directory.
pdfFiles = []
#Search the directory and make a list of all the PDF files in it.
for filename in os.listdir('.'):
if filename.endswith('.pdf'):
pdfFiles.append(filename)
#sort the list alphabetically
pdfFiles.sort(key=str.lower)
#... | [
"PyPDF2.PdfFileWriter",
"os.listdir",
"PyPDF2.PdfFileReader"
] | [((182, 197), 'os.listdir', 'os.listdir', (['"""."""'], {}), "('.')\n", (192, 197), False, 'import PyPDF2, os\n'), ((355, 377), 'PyPDF2.PdfFileWriter', 'PyPDF2.PdfFileWriter', ([], {}), '()\n', (375, 377), False, 'import PyPDF2, os\n'), ((513, 545), 'PyPDF2.PdfFileReader', 'PyPDF2.PdfFileReader', (['pdfFileObj'], {}), ... |
import base64
import json
import pytest
import requests
import responses
import xendit
from xendit._api_requestor import _APIRequestor
def generate_auth(api_key):
auth_pair = api_key + ":"
auth_base64 = base64.b64encode(auth_pair.encode())
return f'Basic {auth_base64.decode("utf-8")}'
def substitute_ca... | [
"xendit._api_requestor._APIRequestor._request",
"responses.add_callback",
"xendit._api_requestor._APIRequestor.get",
"json.dumps",
"xendit._api_requestor._APIRequestor.patch",
"xendit._api_requestor._APIRequestor.post"
] | [((955, 1030), 'responses.add_callback', 'responses.add_callback', ([], {'method': '"""GET"""', 'url': 'url', 'callback': 'substitute_callback'}), "(method='GET', url=url, callback=substitute_callback)\n", (977, 1030), False, 'import responses\n'), ((1036, 1128), 'xendit._api_requestor._APIRequestor.get', '_APIRequesto... |
import control as c
from control.xferfcn import clean_tf
from control.statesp import clean_ss
from control.timeresp import fival
import numpy as np
ci = 2 / np.sqrt(13)
w = np.sqrt(13)
Kq = -24
T02 = 1.4
V = 160
s = c.tf([1, 0], [1])
Hq = Kq * (1 + T02 * s) / (s ** 2 + 2 * ci * w * s + w ** 2)
Htheta = Hq / s
Hgamma =... | [
"control.timeresp.fival",
"numpy.sqrt",
"control.ss",
"numpy.array",
"control.tf"
] | [((174, 185), 'numpy.sqrt', 'np.sqrt', (['(13)'], {}), '(13)\n', (181, 185), True, 'import numpy as np\n'), ((217, 234), 'control.tf', 'c.tf', (['[1, 0]', '[1]'], {}), '([1, 0], [1])\n', (221, 234), True, 'import control as c\n'), ((389, 537), 'control.tf', 'c.tf', (['[[Hq.num[0][0], Htheta.num[0][0]], [Hgamma.num[0][0... |
from django.contrib import admin
from models import *
admin.site.register(Resource)
admin.site.register(UserConnection)
| [
"django.contrib.admin.site.register"
] | [((56, 85), 'django.contrib.admin.site.register', 'admin.site.register', (['Resource'], {}), '(Resource)\n', (75, 85), False, 'from django.contrib import admin\n'), ((87, 122), 'django.contrib.admin.site.register', 'admin.site.register', (['UserConnection'], {}), '(UserConnection)\n', (106, 122), False, 'from django.co... |
"""Replacement r2_score function for when sklearn is not available."""
import numpy as np
#===============================================================================
# BSD 3-Clause License
# Copyright (c) 2007-2021 The scikit-learn developers.
# All rights reserved.
# Redistribution and use in source and binary... | [
"numpy.ones",
"numpy.average"
] | [((3741, 3767), 'numpy.ones', 'np.ones', (['[y_true.shape[1]]'], {}), '([y_true.shape[1]])\n', (3748, 3767), True, 'import numpy as np\n'), ((4103, 4128), 'numpy.average', 'np.average', (['output_scores'], {}), '(output_scores)\n', (4113, 4128), True, 'import numpy as np\n'), ((3516, 3542), 'numpy.average', 'np.average... |
import numpy as np
import random
from sklearn.model_selection import train_test_split
one_hot_conv = {"A": [1, 0, 0, 0], "T": [0, 0, 0, 1],
"C": [0, 1, 0, 0], "G": [0, 0, 1, 0],
"a": [1, 0, 0, 0], "t": [0, 0, 0, 1],
"c": [0, 1, 0, 0], "g": [0, 0, 1, 0],
"n... | [
"gzip.open",
"numpy.array",
"numpy.zeros",
"numpy.random.randint",
"random.randint"
] | [((552, 572), 'numpy.zeros', 'np.zeros', (['inpt.shape'], {}), '(inpt.shape)\n', (560, 572), True, 'import numpy as np\n'), ((587, 633), 'random.randint', 'random.randint', (['(len_seq - random_seed)', 'len_seq'], {}), '(len_seq - random_seed, len_seq)\n', (601, 633), False, 'import random\n'), ((896, 941), 'numpy.rand... |
"""Constants for the CPU Speed integration."""
import logging
from typing import Final
from homeassistant.const import Platform
DOMAIN: Final = "cpuspeed"
PLATFORMS = [Platform.SENSOR]
LOGGER = logging.getLogger(__package__)
| [
"logging.getLogger"
] | [((197, 227), 'logging.getLogger', 'logging.getLogger', (['__package__'], {}), '(__package__)\n', (214, 227), False, 'import logging\n')] |
""" dbscheme format representation """
import logging
from dataclasses import dataclass
from typing import ClassVar, List
log = logging.getLogger(__name__)
dbscheme_keywords = {"case", "boolean", "int", "string", "type"}
@dataclass
class DbColumn:
schema_name: str
type: str
binding: bool = False
fi... | [
"logging.getLogger"
] | [((130, 157), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (147, 157), False, 'import logging\n')] |
import argparse
import json
import pandas as pd
import pypff
from bs4 import BeautifulSoup
def find_tasks_folder(root):
for i, folder in enumerate(root.sub_folders):
if folder.name == "Top of Personal Folders":
for j, sub_folder in enumerate(folder.sub_folders):
if sub_folder.... | [
"argparse.FileType",
"json.loads",
"argparse.ArgumentParser",
"bs4.BeautifulSoup",
"pypff.file",
"pandas.DataFrame"
] | [((1942, 2038), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Export tasks from a Microsoft To Do pst file to csv."""'}), "(description=\n 'Export tasks from a Microsoft To Do pst file to csv.')\n", (1965, 2038), False, 'import argparse\n'), ((2335, 2347), 'pypff.file', 'pypff.file',... |
import smtplib, time,os,datetime
from email.mime.text import MIMEText
from email.header import Header
from toolkit import Toolkit
from email.mime.multipart import MIMEMultipart
from email import Encoders, Utils
from toolkit import Toolkit
import tushare as ts
from pandas import Series
import matplotlib.pyplot as plt
im... | [
"itchat.send",
"os.path.exists",
"email.mime.text.MIMEText",
"smtplib.SMTP_SSL",
"itchat.auto_login",
"itchat.get_friends",
"email.Utils.formatdate",
"time.sleep",
"os.getcwd",
"os.chdir",
"toolkit.Toolkit.getUserData",
"datetime.datetime.now",
"os.mkdir",
"tushare.get_realtime_quotes",
... | [((1697, 1730), 'itchat.auto_login', 'itchat.auto_login', ([], {'hotReload': '(True)'}), '(hotReload=True)\n', (1714, 1730), False, 'import itchat\n'), ((1743, 1767), 'itchat.get_friends', 'itchat.get_friends', (['name'], {}), '(name)\n', (1761, 1767), False, 'import itchat\n'), ((1940, 1979), 'itchat.send', 'itchat.se... |
import os
import sys
from multiprocessing import Process
from trigger_pipelines import AzureDevOps
PULL_REQUEST_PIPELINES = {
"identity-service": {
"build": 27,
"pr": 54,
"branch": "refs/heads/master"
},
"canary-api": {
"build": 222,
"pr": 223,
"branch": "re... | [
"multiprocessing.Process",
"trigger_pipelines.AzureDevOps",
"sys.exit"
] | [((548, 561), 'trigger_pipelines.AzureDevOps', 'AzureDevOps', ([], {}), '()\n', (559, 561), False, 'from trigger_pipelines import AzureDevOps\n'), ((1305, 1316), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (1313, 1316), False, 'import sys\n'), ((1101, 1164), 'multiprocessing.Process', 'Process', ([], {'target': 'tr... |
from rodio.internals.parther import getTransformer
from rodio import get_running_loop, EventLoop, is_within_loop, printfromprocess
tx = getTransformer(__file__)
printfromprocess("mainmod.py init")
process1 = EventLoop(f"process1", self_pause=False, shared_queue=False)
process2 = EventLoop(f"process2", self_pause=Fals... | [
"rodio.internals.parther.getTransformer",
"rodio.printfromprocess",
"rodio.EventLoop"
] | [((137, 161), 'rodio.internals.parther.getTransformer', 'getTransformer', (['__file__'], {}), '(__file__)\n', (151, 161), False, 'from rodio.internals.parther import getTransformer\n'), ((163, 198), 'rodio.printfromprocess', 'printfromprocess', (['"""mainmod.py init"""'], {}), "('mainmod.py init')\n", (179, 198), False... |
import numpy as np
import matplotlib.pyplot as plt
# 常量
pi = 3.1415926
# 声波属性
A = 0.01
u = 343
v = 40000
_lambda = u / v
w = 2 * pi * v
k = 2 * pi / _lambda
T = 2 * pi / w
rho = 1.293
# 悬浮物件的尺度
R = 0.005
# 两点换算为距离
def r(x0, y0, x1=0, y1=0):
return np.sqrt((x0 - x1) ** 2 + (y0 - y1) ** 2)
# 波运算函数
def wave(x1... | [
"matplotlib.pyplot.contourf",
"matplotlib.pyplot.quiver",
"numpy.abs",
"numpy.sqrt",
"matplotlib.pyplot.colorbar",
"numpy.square",
"numpy.zeros",
"numpy.cos",
"numpy.sin",
"matplotlib.pyplot.title",
"numpy.gradient",
"matplotlib.pyplot.show"
] | [((762, 780), 'numpy.zeros', 'np.zeros', (['(_W, _L)'], {}), '((_W, _L))\n', (770, 780), True, 'import numpy as np\n'), ((2273, 2291), 'numpy.sqrt', 'np.sqrt', (['array_p_2'], {}), '(array_p_2)\n', (2280, 2291), True, 'import numpy as np\n'), ((2415, 2435), 'numpy.gradient', 'np.gradient', (['array_U'], {}), '(array_U)... |
import unittest
from tonalmodel.tonality import Tonality
from harmoniccontext.harmonic_context import HarmonicContext
from melody.constraints.policy_context import PolicyContext
from melody.constraints.contextual_note import ContextualNote
from tonalmodel.modality import ModalityType
from tonalmodel.diatonic_tone impor... | [
"logging.basicConfig",
"operator.attrgetter",
"logging.debug",
"timemodel.duration.Duration",
"tonalmodel.diatonic_pitch.DiatonicPitch.parse",
"tonalmodel.diatonic_tone.DiatonicTone",
"melody.constraints.policy_context.PolicyContext",
"harmonicmodel.tertian_chord_template.TertianChordTemplate.parse",
... | [((875, 934), 'logging.basicConfig', 'logging.basicConfig', ([], {'stream': 'sys.stdout', 'level': 'logging.DEBUG'}), '(stream=sys.stdout, level=logging.DEBUG)\n', (894, 934), False, 'import logging\n'), ((977, 1017), 'logging.debug', 'logging.debug', (['"""Start test_basic_policy"""'], {}), "('Start test_basic_policy'... |
import sublime
import sublime_plugin
import datetime
import re
import os
import fnmatch
import OrgExtended.orgparse.node as node
import OrgExtended.orgutil.util as util
import OrgExtended.orgutil.navigation as nav
import OrgExtended.orgutil.template as templateEngine
import logging
import sys
import traceback
import O... | [
"logging.getLogger",
"OrgExtended.asettings.Get",
"OrgExtended.orgdb.Get",
"re.compile"
] | [((470, 497), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (487, 497), False, 'import logging\n'), ((632, 656), 're.compile', 're.compile', (['"""^(\\\\s*).*$"""'], {}), "('^(\\\\s*).*$')\n", (642, 656), False, 'import re\n'), ((676, 710), 're.compile', 're.compile', (['"""(\\\\[\\\\d*[... |
import tkinter as tk
import tkinter.ttk as ttk
import re, webbrowser
class MainApp(tk.Frame):
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
self.initUI()
def prepString(self, string):
xclusive_list = ['AND', 'OR', 'NOT', 'NOR', 'XNO... | [
"tkinter.Frame.__init__",
"tkinter.ttk.Button",
"tkinter.ttk.Entry",
"tkinter.ttk.Label",
"tkinter.Tk",
"webbrowser.open_new_tab",
"re.sub"
] | [((3414, 3421), 'tkinter.Tk', 'tk.Tk', ([], {}), '()\n', (3419, 3421), True, 'import tkinter as tk\n'), ((150, 190), 'tkinter.Frame.__init__', 'tk.Frame.__init__', (['self', '*args'], {}), '(self, *args, **kwargs)\n', (167, 190), True, 'import tkinter as tk\n'), ((370, 406), 're.sub', 're.sub', (['"""[^A-Za-z0-9]+"""',... |
from django.urls import path
from account import views
urlpatterns = [
path('', views.index, name='index'),
path(r'login/', views.login)
]
| [
"django.urls.path"
] | [((77, 112), 'django.urls.path', 'path', (['""""""', 'views.index'], {'name': '"""index"""'}), "('', views.index, name='index')\n", (81, 112), False, 'from django.urls import path\n'), ((118, 145), 'django.urls.path', 'path', (['"""login/"""', 'views.login'], {}), "('login/', views.login)\n", (122, 145), False, 'from d... |
from local_server import LocalServer
server = LocalServer()
if __name__ == "__main__":
try:
server.run()
except KeyboardInterrupt:
server.stop()
| [
"local_server.LocalServer"
] | [((47, 60), 'local_server.LocalServer', 'LocalServer', ([], {}), '()\n', (58, 60), False, 'from local_server import LocalServer\n')] |
#!/usr/bin/env python
"""A keyword index of client machines.
An index of client machines, associating likely identifiers to client IDs.
"""
from grr.lib import keyword_index
from grr.lib import rdfvalue
from grr.lib import utils
# The system's primary client index.
MAIN_INDEX = rdfvalue.RDFURN("aff4:/client_index"... | [
"grr.lib.utils.SmartStr",
"grr.lib.rdfvalue.ClientURN",
"grr.lib.rdfvalue.RDFURN"
] | [((284, 321), 'grr.lib.rdfvalue.RDFURN', 'rdfvalue.RDFURN', (['"""aff4:/client_index"""'], {}), "('aff4:/client_index')\n", (299, 321), False, 'from grr.lib import rdfvalue\n'), ((622, 651), 'grr.lib.rdfvalue.ClientURN', 'rdfvalue.ClientURN', (['client_id'], {}), '(client_id)\n', (640, 651), False, 'from grr.lib import... |
import os
import pandas as pd
import thoipapy
def add_random_interface_to_combined_features_mult_prot(s, df_set, logging):
"""Creates combined data with a randomly chosen interface residues.
Sorts TMDs according to length.
Adds the shortest one to the bottom of the list again.
Iterates through each... | [
"pandas.DataFrame",
"thoipapy.utils.make_sure_path_exists",
"pandas.read_csv",
"pandas.read_excel"
] | [((1576, 1590), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (1588, 1590), True, 'import pandas as pd\n'), ((2235, 2321), 'thoipapy.utils.make_sure_path_exists', 'thoipapy.utils.make_sure_path_exists', (['feature_combined_file_rand_int'], {'isfile': '(True)'}), '(feature_combined_file_rand_int, isfile\n =Tr... |
"""
gevent_tasks
~~~~~~~~~~~~
Tasks executing in ``gevent`` Pool
.. note:: You need to apply gevent monkey-patch yourself, see
`docs <http://www.gevent.org/gevent.monkey.html>`_
"""
from concurrent import futures
from gevent.pool import Pool
import gevent
from .tasks import Task,... | [
"gevent.pool.Pool",
"concurrent.futures.TimeoutError"
] | [((563, 580), 'gevent.pool.Pool', 'Pool', (['max_workers'], {}), '(max_workers)\n', (567, 580), False, 'from gevent.pool import Pool\n'), ((1279, 1302), 'concurrent.futures.TimeoutError', 'futures.TimeoutError', (['e'], {}), '(e)\n', (1299, 1302), False, 'from concurrent import futures\n')] |
# USAGE: sudo scrapy runspider GeoFabrikSpider.py
import scrapy
import os
import subprocess
from time import sleep
from urllib import parse
from scrapy.selector import Selector
class GeoFabrikSpider(scrapy.Spider):
name = "geofabrik_spider"
start_urls = ['https://download.geofabrik.de/']
wait_time = 30
... | [
"scrapy.selector.Selector",
"time.sleep",
"os.path.split",
"subprocess.call",
"urllib.parse.urljoin"
] | [((583, 601), 'scrapy.selector.Selector', 'Selector', (['response'], {}), '(response)\n', (591, 601), False, 'from scrapy.selector import Selector\n'), ((1654, 1672), 'scrapy.selector.Selector', 'Selector', (['response'], {}), '(response)\n', (1662, 1672), False, 'from scrapy.selector import Selector\n'), ((1958, 1983)... |
# -*- coding: utf-8 -*-
"""DecisionTreeClassifier(Telco Dataset).ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1lSnAsYluPfeTR_sbPvf5qGcz1wBwhRNW
"""
import pandas as pd
import numpy as np
from google.colab import files
uploaded = files.upload()... | [
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"sklearn.tree.DecisionTreeClassifier",
"google.colab.files.upload",
"pandas.set_option",
"sklearn.tree.export_graphviz",
"numpy.printoptions",
"sklearn.externals.six.StringIO",
"sklearn.metrics.accuracy_score",
"sklearn.metrics.confusi... | [((306, 320), 'google.colab.files.upload', 'files.upload', ([], {}), '()\n', (318, 320), False, 'from google.colab import files\n'), ((332, 400), 'pandas.read_csv', 'pd.read_csv', (['"""WA_Fn-UseC_-Telco-Customer-Churn.csv"""'], {'index_col': '(False)'}), "('WA_Fn-UseC_-Telco-Customer-Churn.csv', index_col=False)\n", (... |
import custom_params
custom_params.filename = 'g37e1i002'
from common import rank
import bindict
import params
bindict.mknetwork([37])
bindict.save('g37.dic')
| [
"bindict.mknetwork",
"bindict.save"
] | [((113, 136), 'bindict.mknetwork', 'bindict.mknetwork', (['[37]'], {}), '([37])\n', (130, 136), False, 'import bindict\n'), ((137, 160), 'bindict.save', 'bindict.save', (['"""g37.dic"""'], {}), "('g37.dic')\n", (149, 160), False, 'import bindict\n')] |
#!python
##############
# HOW TO RUN #
##############
# 1. Install Pytest
"pip install pytest"
# 2. Run Tests
"pytest -v test_airlines.py"
# NOTE: if "pytest" is not found, run "python -m pytest ..."
##############
import pytest
from typing import Dict, List, Any
from airlines import Airline, get_delay
try:
from... | [
"airlines.get_delay",
"airlines.get_delay_2",
"pytest.main",
"processRecords.get_ratings_airlines",
"pytest.raises",
"processRecords.get_first_last_elem",
"processRecords.list_sorted_ratings",
"processRecords.read_flight_records",
"airlines.Airline"
] | [((7787, 7811), 'pytest.main', 'pytest.main', ([], {'args': "['-v']"}), "(args=['-v'])\n", (7798, 7811), False, 'import pytest\n'), ((457, 484), 'airlines.get_delay', 'get_delay', (['"""12:10"""', '"""12:45"""'], {}), "('12:10', '12:45')\n", (466, 484), False, 'from airlines import Airline, get_delay\n'), ((502, 529), ... |
import json
import unittest
from automerge import doc
from automerge.datatypes import Counter
class TestCounters(unittest.TestCase):
def test_make_counters_behave_like_primitive_numbers(self):
d0 = doc.Doc(initial_data={"birds": Counter(3)})
self.assertEqual(d0["birds"], 3)
self.assertTrue... | [
"automerge.datatypes.Counter"
] | [((243, 253), 'automerge.datatypes.Counter', 'Counter', (['(3)'], {}), '(3)\n', (250, 253), False, 'from automerge.datatypes import Counter\n'), ((647, 657), 'automerge.datatypes.Counter', 'Counter', (['(0)'], {}), '(0)\n', (654, 657), False, 'from automerge.datatypes import Counter\n')] |
import unittest
from mock import patch
from click import BadParameter
from flotilla.cli.service import configure_service, get_updates, \
validate_health_check
ENVIRONMENT = 'develop'
REGIONS = ('us-east-1', 'us-west-2')
SERVICE = 'test'
ELB_SCHEME = 'internal'
DNS = 'test.test.com'
HEALTH_CHECK = 'HTTP:9200/'
IN... | [
"flotilla.cli.service.validate_health_check",
"mock.patch",
"flotilla.cli.service.get_updates",
"flotilla.cli.service.configure_service"
] | [((2311, 2355), 'mock.patch', 'patch', (['"""flotilla.cli.service.DynamoDbTables"""'], {}), "('flotilla.cli.service.DynamoDbTables')\n", (2316, 2355), False, 'from mock import patch\n'), ((2361, 2402), 'mock.patch', 'patch', (['"""boto.dynamodb2.connect_to_region"""'], {}), "('boto.dynamodb2.connect_to_region')\n", (23... |
from unittest import mock
import pytest
import quibble.util
from quibble.util import (
isCoreOrVendor,
isExtOrSkin,
move_item_to_head,
php_version,
)
def test_parallel_run_accepts_an_empty_list_of_tasks():
quibble.util.parallel_run([])
assert True
# quibble.util.isCoreOrVendor
def test_is... | [
"quibble.util.move_item_to_head",
"quibble.util.php_version",
"pytest.raises",
"unittest.mock.patch",
"quibble.util.isCoreOrVendor",
"quibble.util.isExtOrSkin"
] | [((1583, 1620), 'unittest.mock.patch', 'mock.patch', (['"""subprocess.check_output"""'], {}), "('subprocess.check_output')\n", (1593, 1620), False, 'from unittest import mock\n'), ((1303, 1344), 'quibble.util.move_item_to_head', 'move_item_to_head', (['orig', '"""extensions/foo"""'], {}), "(orig, 'extensions/foo')\n", ... |
# Copyright 2017 Intel Corporation
#
# 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 wri... | [
"logging.getLogger",
"os.path.exists",
"logging.debug",
"sawtooth_supplychain.cli.init.do_init",
"unittest.mock.MagicMock",
"sawtooth_supplychain.cli.main.load_config",
"sawtooth_supplychain.protobuf.application_pb2.Application",
"sawtooth_supplychain.protobuf.record_pb2.Record.AgentRecord",
"sawtoo... | [((1103, 1130), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1120, 1130), False, 'import logging\n'), ((2425, 2455), 'logging.debug', 'logging.debug', (['"""left %s"""', 'left'], {}), "('left %s', left)\n", (2438, 2455), False, 'import logging\n'), ((2460, 2492), 'logging.debug', 'logg... |
from google.cloud import storage
def upload_blob(bucket_name, source_file_name, destination_blob_name):
"""Uploads a file to the bucket.
:param : bucket_name : "your-bucket-name"
:param : source_file_name : "local/path/to/file"
:param : destination_blob_name : "storage-object-name"
... | [
"google.cloud.storage.Client"
] | [((346, 362), 'google.cloud.storage.Client', 'storage.Client', ([], {}), '()\n', (360, 362), False, 'from google.cloud import storage\n')] |
from backend.common.sitevars.google_analytics_id import ContentType, GoogleAnalyticsID
def test_key():
assert GoogleAnalyticsID.key() == "google_analytics.id"
def test_description():
assert (
GoogleAnalyticsID.description()
== "Google Analytics ID for logging API requests"
)
def test_d... | [
"backend.common.sitevars.google_analytics_id.ContentType",
"backend.common.sitevars.google_analytics_id.GoogleAnalyticsID.key",
"backend.common.sitevars.google_analytics_id.GoogleAnalyticsID._fetch_sitevar",
"backend.common.sitevars.google_analytics_id.GoogleAnalyticsID.google_analytics_id",
"backend.common... | [((360, 394), 'backend.common.sitevars.google_analytics_id.GoogleAnalyticsID._fetch_sitevar', 'GoogleAnalyticsID._fetch_sitevar', ([], {}), '()\n', (392, 394), False, 'from backend.common.sitevars.google_analytics_id import ContentType, GoogleAnalyticsID\n'), ((116, 139), 'backend.common.sitevars.google_analytics_id.Go... |
# ©2018 The Arizona Board of Regents for and on behalf of Arizona State University and the Laboratory for Energy And Power Solutions, All Rights Reserved.
# Universal Power System Controller
# USAID Middle East Water Security Initiative
#
# Developed by: <NAME>
# Primary Investigator: <NAME>
#
# Version History (mm_dd_... | [
"os.path.exists",
"sqlite3.connect",
"os.makedirs",
"zipfile.ZipFile",
"datetime.datetime.datetime.now",
"os.getcwd",
"os.chmod",
"sched.scheduler",
"os.walk",
"os.remove"
] | [((993, 1031), 'sched.scheduler', 'sched.scheduler', (['time.time', 'time.sleep'], {}), '(time.time, time.sleep)\n', (1008, 1031), False, 'import sched\n'), ((1261, 1272), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1270, 1272), False, 'import os\n'), ((1358, 1381), 'datetime.datetime.datetime.now', 'datetime.datetime... |
import os
import glob
import gzip
import readfq
for filename in glob.glob("/nvme/fastq/*"):
print("---------")
print(filename)
#os.system("zcat %s |head -n 4" % filename)
count = 0
len_seqs = []
seq_in_headers = 0
for name, seq, qual in readfq.readfq(gzip.open(filename)):
if any([na... | [
"glob.glob",
"gzip.open"
] | [((64, 90), 'glob.glob', 'glob.glob', (['"""/nvme/fastq/*"""'], {}), "('/nvme/fastq/*')\n", (73, 90), False, 'import glob\n'), ((279, 298), 'gzip.open', 'gzip.open', (['filename'], {}), '(filename)\n', (288, 298), False, 'import gzip\n')] |
def xmaslight():
# This is the code from my
#NOTE THE LEDS ARE GRB COLOUR (NOT RGB)
# Here are the libraries I am currently using:
import time
import board
import neopixel
import re
import math
# You are welcome to add any of these:
import random
# import nump... | [
"random.randrange",
"time.sleep",
"neopixel.NeoPixel",
"re.sub",
"random.random"
] | [((1074, 1133), 'neopixel.NeoPixel', 'neopixel.NeoPixel', (['board.D18', 'PIXEL_COUNT'], {'auto_write': '(False)'}), '(board.D18, PIXEL_COUNT, auto_write=False)\n', (1091, 1133), False, 'import neopixel\n'), ((4571, 4616), 'random.randrange', 'random.randrange', (['(0)', 'infectedColourBrightness'], {}), '(0, infectedC... |
from pytest import fixture
from pygiftgrab import ColourSpace
def pytest_addoption(parser):
parser.addoption('--address', action='store',
help='Network source address')
parser.addoption('--init-delay', action='store', type=float,
help='Network source initialisation de... | [
"pytest.fixture"
] | [((729, 753), 'pytest.fixture', 'fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (736, 753), False, 'from pytest import fixture\n'), ((828, 852), 'pytest.fixture', 'fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (835, 852), False, 'from pytest import fixture\n'), ((933, 957), 'pyt... |
# Roller for FATE dice
import random
from ..menus import base_menus as m
def fateroller():
pool = int(input("How many dice are you rolling? "))
rollagain = "Y"
while str.upper(rollagain) == "Y":
try:
sides = 6
if pool < 1:
print("Silly human")
... | [
"random.randint"
] | [((415, 439), 'random.randint', 'random.randint', (['(1)', 'sides'], {}), '(1, sides)\n', (429, 439), False, 'import random\n')] |
# -*- coding: utf-8 -*-
import sys, re, clean
reload(sys)
sys.setdefaultencoding('utf-8')
from collections import OrderedDict
##############################################################################
# Categorized letters and digraphs #
###################################... | [
"collections.OrderedDict",
"sys.setdefaultencoding",
"sys.stdin.read",
"sys.stderr.write",
"re.findall",
"sys.stdout.write"
] | [((58, 89), 'sys.setdefaultencoding', 'sys.setdefaultencoding', (['"""utf-8"""'], {}), "('utf-8')\n", (80, 89), False, 'import sys, re, clean\n'), ((1643, 1704), 're.findall', 're.findall', (['"""[\\\\w\']+|[.,!?();:]"""', 'wholeline'], {'flags': 're.UNICODE'}), '("[\\\\w\']+|[.,!?();:]", wholeline, flags=re.UNICODE)\n... |
from simulator import Simulator
partner_id = 'C0F515F0A2D0A5D9F854008BA76EB537' # partner_id for plotting
# partner_id = '04A66CE7327C6E21493DA6F3B9AACC75' # partner_id for logs
strategy = 'random'
if __name__ == "__main__":
simulator = Simulator(partner_id, strategy)
simulator.run_simulation()
| [
"simulator.Simulator"
] | [((247, 278), 'simulator.Simulator', 'Simulator', (['partner_id', 'strategy'], {}), '(partner_id, strategy)\n', (256, 278), False, 'from simulator import Simulator\n')] |
# -*- coding: utf-8 -*-
from __future__ import division, print_function
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
__all__ = ["limiter"]
limiter = Limiter(
key_func=get_remote_address,
global_limits=["10/minute"],
)
| [
"flask_limiter.Limiter"
] | [((191, 256), 'flask_limiter.Limiter', 'Limiter', ([], {'key_func': 'get_remote_address', 'global_limits': "['10/minute']"}), "(key_func=get_remote_address, global_limits=['10/minute'])\n", (198, 256), False, 'from flask_limiter import Limiter\n')] |
import collect_array as ca
import collect_device as cd
import collect_gen as cg
import collect_id as ci
from processing import collect_loop as cl
def print_dict_sorted(mydict):
keys = sorted(mydict)
entries = ""
for key in keys:
value = mydict[key]
entries += "'" + key + "': " + value.__... | [
"collect_gen.GenKernelArgs",
"collect_gen.GenRemovedIds",
"processing.collect_loop.FindPerfectForLoop",
"collect_array.NumArrayDim",
"collect_array.get_array_ids",
"processing.collect_loop.FindInnerLoops",
"collect_array.get_subscript",
"collect_array.FindReadWrite",
"processing.collect_loop.LoopInd... | [((464, 487), 'processing.collect_loop.FindPerfectForLoop', 'cl.FindPerfectForLoop', ([], {}), '()\n', (485, 487), True, 'from processing import collect_loop as cl\n'), ((1654, 1681), 'collect_device.FindKernel', 'cd.FindKernel', (['self.par_dim'], {}), '(self.par_dim)\n', (1667, 1681), True, 'import collect_device as ... |
"""Provides a class to interact with a subset of the Twitch API.
Specifically, the "new Twitch API", which they haven't put a version
number on yet (so far as I can tell).
"""
import requests
from twitchgamenotify.constants import (
HTTP_200_OK,
HTTP_400_BAD_REQUEST,
HTTP_401_UNAUTHORIZED,
TWITCH_STRE... | [
"requests.post",
"requests.Session"
] | [((1201, 1219), 'requests.Session', 'requests.Session', ([], {}), '()\n', (1217, 1219), False, 'import requests\n'), ((1433, 1581), 'requests.post', 'requests.post', (["(TWITCH_TOKEN_API_URL + '?client_id=' + self.client_id + '&client_secret=' +\n self.client_secret + '&grant_type=client_credentials')"], {}), "(TWIT... |
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
#
# License: BSD (3-clause)
import math
import numpy as np
from scipy import linalg
from scipy.fftpack import fft, ifft
import six
def _framing(a, L):
shape = a.shape[:-1] + (a.shape[-1] - L + 1, L)
strides = a.strides + (a.strides[-1],)
return np.l... | [
"numpy.reshape",
"scipy.fftpack.ifft",
"numpy.asarray",
"math.sqrt",
"numpy.lib.stride_tricks.as_strided",
"numpy.exp",
"numpy.real",
"numpy.zeros",
"numpy.count_nonzero",
"scipy.fftpack.fft",
"numpy.cos",
"scipy.linalg.norm",
"numpy.sin",
"numpy.arange"
] | [((529, 547), 'math.sqrt', 'math.sqrt', (['(2.0 / K)'], {}), '(2.0 / K)\n', (538, 547), False, 'import math\n'), ((664, 696), 'numpy.arange', 'np.arange', (['scale'], {'dtype': 'np.float'}), '(scale, dtype=np.float)\n', (673, 696), True, 'import numpy as np\n'), ((1305, 1334), 'numpy.asarray', 'np.asarray', (['x'], {'d... |
from flask import Flask, make_response, request
import json
app = Flask(__name__)
costs = {}
@app.route('/retrieve-costs', methods=['POST'])
def get_costs():
request_data = json.loads(request.data)
batch = request_data['batch']
tasks = request_data['tasks']
response = {'batch': batch, 'costs': []}
... | [
"flask.make_response",
"json.loads",
"json.dumps",
"flask.Flask"
] | [((67, 82), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (72, 82), False, 'from flask import Flask, make_response, request\n'), ((180, 204), 'json.loads', 'json.loads', (['request.data'], {}), '(request.data)\n', (190, 204), False, 'import json\n'), ((619, 643), 'json.loads', 'json.loads', (['request.dat... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
def fgs(model, input_image, label, targeted=False, alpha=0.02, iterations=1,
reg=1e-2, clamp=((-2.118, -2.036, -1.804), (2.249, 2.429, 2.64)),
use_cuda=True):
"""
Fast gradient sign method for generating adve... | [
"torch.nn.functional.mse_loss",
"torch.nn.CrossEntropyLoss",
"torch.LongTensor",
"torch.sign",
"torch.device"
] | [((1491, 1534), 'torch.device', 'torch.device', (["('cuda' if use_cuda else 'cpu')"], {}), "('cuda' if use_cuda else 'cpu')\n", (1503, 1534), False, 'import torch\n'), ((1584, 1605), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (1603, 1605), True, 'import torch.nn as nn\n'), ((1740, 1765), 'tor... |
from portfolio import cards
def test_get_projects_markdown():
projects = cards.get_projects_markdown()
assert isinstance(projects, list)
assert len(projects) > 0
for project in projects:
assert isinstance(project, str)
| [
"portfolio.cards.get_projects_markdown"
] | [((79, 108), 'portfolio.cards.get_projects_markdown', 'cards.get_projects_markdown', ([], {}), '()\n', (106, 108), False, 'from portfolio import cards\n')] |
# Generated by Django 2.0.5 on 2018-05-24 15:42
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('workshops', '0135_auto_20180519_1403'),
]
operations = [
migrations.AlterModelOptions(
name='person',
options={'ordering': [... | [
"django.db.migrations.AlterModelOptions"
] | [((229, 428), 'django.db.migrations.AlterModelOptions', 'migrations.AlterModelOptions', ([], {'name': '"""person"""', 'options': "{'ordering': ['family', 'personal'], 'permissions': [(\n 'can_access_restricted_API',\n 'Can this user access the restricted API endpoints?')]}"}), "(name='person', options={'ordering'... |
import sys
import re
ignoreList = [
".*_h_$",
"^SDL_test.*",
"^SDLTest_.*",
"SDLCALL",
"^SDL_$",
".*_$",
"SDL_INLINE",
"^SDL$",
"^SDL_Read.*$",
"^SDL_Write.*$",
]
class ImplInfo:
def __init__(self):
self.implemented = "NO"
self.implName = ""
self.com... | [
"re.match"
] | [((1101, 1128), 're.match', 're.match', (['f"""{ignore}"""', 'name'], {}), "(f'{ignore}', name)\n", (1109, 1128), False, 'import re\n')] |
import numpy as np
from torchinfo import summary
import pickle
import torch
import datetime
def weights_init(m):
if isinstance(m, torch.nn.Linear):
torch.nn.init.normal_(m.weight,mean=0.0, std=0.00001)
#m.bias.data.fill_(0)
if isinstance(m, torch.nn.Conv2d):
torch.nn.init.normal_(m.wei... | [
"torch.nn.ReLU",
"torch.exp",
"torchinfo.summary",
"torch.nn.Conv2d",
"torch.randn_like",
"torch.cuda.is_available",
"torch.nn.Linear",
"torch.nn.AvgPool2d",
"torch.nn.ConvTranspose2d",
"torch.nn.init.normal_"
] | [((162, 214), 'torch.nn.init.normal_', 'torch.nn.init.normal_', (['m.weight'], {'mean': '(0.0)', 'std': '(1e-05)'}), '(m.weight, mean=0.0, std=1e-05)\n', (183, 214), False, 'import torch\n'), ((293, 345), 'torch.nn.init.normal_', 'torch.nn.init.normal_', (['m.weight'], {'mean': '(0.0)', 'std': '(1e-05)'}), '(m.weight, ... |
from django.db import models
from django.utils import timezone
from accounting.models import LedgerAccount, LedgerEntry
class MembershipLevel(models.Model):
"""Descriptor for membership costs and privileges.
:param name: Name of membership level.
:param cost: Cost of this membership level.
:param pe... | [
"django.db.models.EmailField",
"django.db.models.OneToOneField",
"django.db.models.DateField",
"django.db.models.ForeignKey",
"django.db.models.BooleanField",
"django.utils.timezone.now",
"django.db.models.DateTimeField",
"django.db.models.DecimalField",
"django.db.models.PositiveSmallIntegerField",... | [((1001, 1033), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(200)'}), '(max_length=200)\n', (1017, 1033), False, 'from django.db import models\n'), ((1045, 1096), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(8)', 'decimal_places': '(2)'}), '(max_digits=8, deci... |
import concurrent.futures
from typing import Iterable, Mapping
from azure.core.exceptions import HttpResponseError
from chaoslib import Configuration, Secrets
from chaoslib.exceptions import FailedActivity
from logzero import logger
from pdchaosazure.common import cleanse, config
from pdchaosazure.common.compute impo... | [
"pdchaosazure.common.config.load_timeout",
"pdchaosazure.vmss.fetcher.fetch_vmss",
"pdchaosazure.vmss.fetcher.fetch_instances",
"pdchaosazure.common.cleanse.vmss",
"pdchaosazure.common.compute.command.prepare",
"pdchaosazure.common.cleanse.vmss_instance",
"chaoslib.exceptions.FailedActivity",
"pdchaos... | [((1419, 1432), 'pdchaosazure.common.compute.client.init', 'client.init', ([], {}), '()\n', (1430, 1432), False, 'from pdchaosazure.common.compute import command, client\n'), ((1449, 1496), 'pdchaosazure.vmss.fetcher.fetch_vmss', 'fetch_vmss', (['vmss_filter', 'configuration', 'secrets'], {}), '(vmss_filter, configurat... |
"""The flake8 command execution script. This is used by the deploying
job mainly.
Command example:
$ python ./scripts/run_flake8.py
"""
import sys
from logging import Logger
sys.path.append('./')
import scripts.command_util as command_util
from apysc._console import loggers
from scripts.apply_lints_an... | [
"scripts.command_util.run_command",
"sys.path.append",
"apysc._console.loggers.get_info_logger"
] | [((187, 208), 'sys.path.append', 'sys.path.append', (['"""./"""'], {}), "('./')\n", (202, 208), False, 'import sys\n'), ((375, 400), 'apysc._console.loggers.get_info_logger', 'loggers.get_info_logger', ([], {}), '()\n', (398, 400), False, 'from apysc._console import loggers\n'), ((625, 673), 'scripts.command_util.run_c... |
# -*- coding: utf-8 -*-
from GridEyeKit import GridEYEKit
import time
import numpy as np
import os
import matplotlib.pyplot as plt
print("Connecting to Grideye\n")
try:
g = GridEYEKit()
g_status_connect = g.connect()
if not g_status_connect:
g.close()
print("could not connect to grideye...... | [
"matplotlib.pyplot.imshow",
"GridEyeKit.GridEYEKit",
"os._exit",
"matplotlib.pyplot.pause",
"matplotlib.pyplot.draw",
"matplotlib.pyplot.show"
] | [((179, 191), 'GridEyeKit.GridEYEKit', 'GridEYEKit', ([], {}), '()\n', (189, 191), False, 'from GridEyeKit import GridEYEKit\n'), ((568, 602), 'matplotlib.pyplot.imshow', 'plt.imshow', (['data'], {'vmin': '(20)', 'vmax': '(30)'}), '(data, vmin=20, vmax=30)\n', (578, 602), True, 'import matplotlib.pyplot as plt\n'), ((6... |
from __future__ import absolute_import, division, print_function
from __future__ import unicode_literals
"""Auxilary functions for group representations"""
import numpy as np
def sgn(s):
"""return (-1)**(s)"""
return 1 - ((s & 1) << 1)
def zero_vector(length, *data):
"""Return zero numpy vector of g... | [
"numpy.zeros"
] | [((364, 396), 'numpy.zeros', 'np.zeros', (['length'], {'dtype': 'np.int32'}), '(length, dtype=np.int32)\n', (372, 396), True, 'import numpy as np\n'), ((717, 749), 'numpy.zeros', 'np.zeros', (['(l, l)'], {'dtype': 'np.int32'}), '((l, l), dtype=np.int32)\n', (725, 749), True, 'import numpy as np\n'), ((1142, 1174), 'num... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... | [
"os.path.abspath",
"sphinx_rtd_theme.get_html_theme_path"
] | [((593, 617), 'os.path.abspath', 'os.path.abspath', (['"""../.."""'], {}), "('../..')\n", (608, 617), False, 'import os\n'), ((4256, 4294), 'sphinx_rtd_theme.get_html_theme_path', 'sphinx_rtd_theme.get_html_theme_path', ([], {}), '()\n', (4292, 4294), False, 'import sphinx_rtd_theme\n')] |
# DB Config
from dotenv import load_dotenv
load_dotenv()
USER = "root"
PASSWORD = "<PASSWORD>"
HOST = "localhost"
PORT = "3306"
SCHEMA = "ase"
# Config for AWS Server
# USER = "ase_db"
# PASSWORD = "<PASSWORD>"
# HOST = "ase.c7htgranr5o5.ap-southeast-1.rds.amazonaws.com"
# PORT = "3306"
# SCHEMA = "ase" | [
"dotenv.load_dotenv"
] | [((43, 56), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (54, 56), False, 'from dotenv import load_dotenv\n')] |
from apiclient import errors
from apiclient.http import BatchHttpRequest
class Gmail(object):
def __init__(self, http, service):
self.connected = False
self.labels = {}
self.events = {
'on_message': []
}
self._http = http
self._service = service
... | [
"apiclient.http.BatchHttpRequest"
] | [((2207, 2248), 'apiclient.http.BatchHttpRequest', 'BatchHttpRequest', ([], {'callback': 'on_get_message'}), '(callback=on_get_message)\n', (2223, 2248), False, 'from apiclient.http import BatchHttpRequest\n')] |
from app import db
def latest_reading(sensor):
query = """
WITH result AS (
SELECT *
FROM thpl_data
WHERE sensor = %s
ORDER BY logged_at DESC
LIMIT 1
)
SELECT ROW_TO_JSON(result.*)
FROM result;
"""
with db.curso... | [
"app.db.cursor"
] | [((312, 323), 'app.db.cursor', 'db.cursor', ([], {}), '()\n', (321, 323), False, 'from app import db\n'), ((809, 820), 'app.db.cursor', 'db.cursor', ([], {}), '()\n', (818, 820), False, 'from app import db\n'), ((1321, 1332), 'app.db.cursor', 'db.cursor', ([], {}), '()\n', (1330, 1332), False, 'from app import db\n')] |
from kalyna_cipher.classBasic import classBasic
from kalyna_cipher.classTable import classTable
class classKey(classBasic):
def __init__(self, var_c, var_l, var_k, var_t):
classBasic.__init__(self, var_c, var_l)
self.var_k = var_k
self.var_t = var_t
self.Ka = self.func_gen_matrix()... | [
"kalyna_cipher.classBasic.classBasic.__init__",
"kalyna_cipher.classTable.classTable.even_indexes_0.count",
"kalyna_cipher.classTable.classTable.even_indexes_3.count",
"kalyna_cipher.classTable.classTable.even_indexes_2.count",
"kalyna_cipher.classTable.classTable.even_indexes.count"
] | [((186, 225), 'kalyna_cipher.classBasic.classBasic.__init__', 'classBasic.__init__', (['self', 'var_c', 'var_l'], {}), '(self, var_c, var_l)\n', (205, 225), False, 'from kalyna_cipher.classBasic import classBasic\n'), ((2419, 2453), 'kalyna_cipher.classTable.classTable.even_indexes_0.count', 'classTable.even_indexes_0.... |
from keras.models import Sequential, load_model
from keras.layers import MaxPool2D, Flatten, Dense, Dropout, BatchNormalization
from keras.losses import SparseCategoricalCrossentropy
from keras.optimizers import RMSprop, Adam
from keras.metrics import SparseCategoricalAccuracy
import matplotlib.pyplot as plt
import num... | [
"keras.optimizers.Adam",
"keras.layers.Flatten",
"keras.losses.SparseCategoricalCrossentropy",
"numpy.argmax",
"keras.models.Sequential",
"keras.layers.Dense",
"keras.layers.BatchNormalization",
"keras.layers.Dropout",
"matplotlib.pyplot.subplots",
"keras.metrics.SparseCategoricalAccuracy",
"mat... | [((470, 482), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (480, 482), False, 'from keras.models import Sequential, load_model\n'), ((3333, 3359), 'numpy.argmax', 'np.argmax', (['y_pred1'], {'axis': '(1)'}), '(y_pred1, axis=1)\n', (3342, 3359), True, 'import numpy as np\n'), ((3652, 3682), 'matplotlib.pyp... |
from __future__ import print_function,division
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
class Evaluator(object):
def __init__(self,loss=nn.MSELoss(),batch_size=64,delay=36,valid_feature_indices=list(range(0,3)),begin_compute_loss_index=0):
self.loss=loss
self.batch... | [
"torch.nn.MSELoss",
"torch.utils.data.DataLoader",
"torch.no_grad",
"torch.device"
] | [((175, 187), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (185, 187), True, 'import torch.nn as nn\n'), ((523, 542), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (535, 542), False, 'import torch\n'), ((609, 694), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'data', 'batch_s... |
from django import template
from django.contrib import admin
register = template.Library()
class CustomRequest:
def __init__(self, user):
self.user = user
@register.simple_tag(takes_context=True)
def get_app_list(context, **kwargs):
custom_request = CustomRequest(context['request'].user)
app_li... | [
"django.contrib.admin.site.get_app_list",
"django.template.Library"
] | [((73, 91), 'django.template.Library', 'template.Library', ([], {}), '()\n', (89, 91), False, 'from django import template\n'), ((325, 364), 'django.contrib.admin.site.get_app_list', 'admin.site.get_app_list', (['custom_request'], {}), '(custom_request)\n', (348, 364), False, 'from django.contrib import admin\n')] |