code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
from telegram.ext import Updater,CommandHandler
import subprocess
updater = Updater("TOKEN",use_context = True)
def start_method(update,context):
context.bot.sendMessage(update.message.chat_id,"Connected !")
def run_command(update,context):
command = ""
for i in context.args:
command += i+" "
... | [
"subprocess.Popen",
"telegram.ext.CommandHandler",
"telegram.ext.Updater"
] | [((77, 111), 'telegram.ext.Updater', 'Updater', (['"""TOKEN"""'], {'use_context': '(True)'}), "('TOKEN', use_context=True)\n", (84, 111), False, 'from telegram.ext import Updater, CommandHandler\n'), ((381, 494), 'subprocess.Popen', 'subprocess.Popen', (['command'], {'shell': '(True)', 'stdout': 'subprocess.PIPE', 'std... |
import socket
import select
import time
import datetime
import random
from collections import deque, namedtuple
BOARD_LENGTH = 32
OFFSET = 16
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
DIRECTIONS = namedtuple('DIRECTIONS',
['Up', 'Down', 'Left', 'Right'])(0, 1, 2, 3)
SNAKE... | [
"select.select",
"collections.namedtuple",
"collections.deque",
"socket.socket",
"random.randrange",
"time.sleep",
"datetime.datetime.now"
] | [((236, 293), 'collections.namedtuple', 'namedtuple', (['"""DIRECTIONS"""', "['Up', 'Down', 'Left', 'Right']"], {}), "('DIRECTIONS', ['Up', 'Down', 'Left', 'Right'])\n", (246, 293), False, 'from collections import deque, namedtuple\n'), ((329, 373), 'collections.namedtuple', 'namedtuple', (['"""SNAKE_STATE"""', "['Aliv... |
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
from config import config
bootstrap = Bootstrap()
moment = Moment()
db = SQLAlchemy()
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name]... | [
"flask_sqlalchemy.SQLAlchemy",
"flask_moment.Moment",
"flask.Flask",
"flask_bootstrap.Bootstrap"
] | [((175, 186), 'flask_bootstrap.Bootstrap', 'Bootstrap', ([], {}), '()\n', (184, 186), False, 'from flask_bootstrap import Bootstrap\n'), ((196, 204), 'flask_moment.Moment', 'Moment', ([], {}), '()\n', (202, 204), False, 'from flask_moment import Moment\n'), ((210, 222), 'flask_sqlalchemy.SQLAlchemy', 'SQLAlchemy', ([],... |
import pandas as pd
import glob
# alpha3Codeをindexに設定して読み込む
country_data = pd.read_csv('../../country.csv', keep_default_na=False, index_col=0)
# 空行を除いて3行目からデータがスタートする(適宜要調整)
# 2列目の「Country Code」をindexに設定する。country.csvと同じ値が入るカラムをindexに指定する必要がある(適宜要調整)
raw_csv = glob.glob('API*.csv')[0]
data = pd.read_csv(raw_csv, hea... | [
"glob.glob",
"pandas.read_csv"
] | [((76, 144), 'pandas.read_csv', 'pd.read_csv', (['"""../../country.csv"""'], {'keep_default_na': '(False)', 'index_col': '(0)'}), "('../../country.csv', keep_default_na=False, index_col=0)\n", (87, 144), True, 'import pandas as pd\n'), ((296, 339), 'pandas.read_csv', 'pd.read_csv', (['raw_csv'], {'header': '(2)', 'inde... |
# Generated by Django 2.2 on 2020-09-18 06:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0007_contact'),
]
operations = [
migrations.AddField(
model_name='userprofile',
name='private',
... | [
"django.db.models.BooleanField"
] | [((328, 362), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (347, 362), False, 'from django.db import migrations, models\n')] |
import os
# 获取当前文件目录的根目录
DIR = os.path.dirname(os.path.dirname(__file__))
# 定义测试数据的存放目录
DATA_DIR = os.path.join(DIR, 'data')
# 定义用例存放的根目录
CASE_DIR = os.path.join(os.getcwd(), "testcases")
# 定义报告存放的根目录
REPORT_DIR = os.path.join(os.getcwd(), 'reports')
# 定义配置文件存放的根目录
CONFIG_DIR = os.path.join(DIR, 'config')
# 测试文件目录
TES... | [
"os.path.dirname",
"os.path.join",
"os.getcwd"
] | [((100, 125), 'os.path.join', 'os.path.join', (['DIR', '"""data"""'], {}), "(DIR, 'data')\n", (112, 125), False, 'import os\n'), ((280, 307), 'os.path.join', 'os.path.join', (['DIR', '"""config"""'], {}), "(DIR, 'config')\n", (292, 307), False, 'import os\n'), ((48, 73), 'os.path.dirname', 'os.path.dirname', (['__file_... |
import tqdm
import mediapipe
import requests
import cv2
import numpy as np
import matplotlib
class FullBodyPoseEmbedder(object):
"""Converts 3D pose landmarks into 3D embedding."""
def __init__(self, torso_size_multiplier=2.5):
# Multiplier to apply to the torso to get minimal body size.
se... | [
"numpy.copy",
"numpy.linalg.norm"
] | [((1734, 1752), 'numpy.copy', 'np.copy', (['landmarks'], {}), '(landmarks)\n', (1741, 1752), True, 'import numpy as np\n'), ((2095, 2113), 'numpy.copy', 'np.copy', (['landmarks'], {}), '(landmarks)\n', (2102, 2113), True, 'import numpy as np\n'), ((3729, 3761), 'numpy.linalg.norm', 'np.linalg.norm', (['(shoulders - hip... |
import pytest
from project import create_app, db
from project.models import User
@pytest.fixture(scope='module')
def new_user():
user = User('<EMAIL>', '<PASSWORD>')
return user
@pytest.fixture(scope='module')
def test_client():
flask_app = create_app('flask_test.cfg')
# Create a test client using ... | [
"project.models.User",
"project.db.drop_all",
"project.db.create_all",
"project.create_app",
"project.db.session.add",
"pytest.fixture",
"project.db.session.commit"
] | [((84, 114), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (98, 114), False, 'import pytest\n'), ((191, 221), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (205, 221), False, 'import pytest\n'), ((572, 602), 'pytest.fixture', 'pyt... |
import csv
import itertools
def _boolean(data):
if data == "False":
result = False
else:
result = True
return result
def row_to_location(row):
if row[4] == "0":
sub = False
nosub = True
else:
sub = True
nosub = False
tss = _boolean(row[6])
... | [
"csv.reader"
] | [((2506, 2537), 'csv.reader', 'csv.reader', (['f_h'], {'delimiter': '"""\t"""'}), "(f_h, delimiter='\\t')\n", (2516, 2537), False, 'import csv\n')] |
import numpy as np
import math
def GMM(alpha, x, u, conv,dim):
covdet = np.linalg.det(conv + np.eye(dim) * 0.001)
covinv = np.linalg.inv(conv + np.eye(dim) * 0.001)
T1 = 1 / ( (2 * math.pi)**(dim/2) * np.sqrt(covdet))
T2 = np.exp((-0.5) * ((np.transpose(x - u)).dot(covinv).dot(x - u)))
prob = T1 *... | [
"numpy.eye",
"numpy.reshape",
"numpy.sqrt",
"math.log",
"numpy.array",
"numpy.sum",
"numpy.expand_dims",
"numpy.transpose"
] | [((446, 466), 'numpy.expand_dims', 'np.expand_dims', (['i', '(1)'], {}), '(i, 1)\n', (460, 466), True, 'import numpy as np\n'), ((647, 674), 'math.log', 'math.log', (['(all_value + 1e-05)'], {}), '(all_value + 1e-05)\n', (655, 674), False, 'import math\n'), ((215, 230), 'numpy.sqrt', 'np.sqrt', (['covdet'], {}), '(covd... |
# Copyright 2021 QuantumBlack Visual Analytics Limited
#
# 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
#
# THE SOFTWARE IS PROVIDED "AS IS", WIT... | [
"logging.getLogger",
"seaborn.countplot",
"pandas.get_dummies",
"pandas.concat",
"matplotlib.pyplot.subplots"
] | [((1681, 1695), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1693, 1695), True, 'import matplotlib.pyplot as plt\n'), ((1848, 1911), 'pandas.get_dummies', 'pd.get_dummies', (["hr_data['EnvironmentSatisfaction']"], {'prefix': '"""ES"""'}), "(hr_data['EnvironmentSatisfaction'], prefix='ES')\n", (1862,... |
import logging
import logging.config
import json
import re
import emoji
logger = logging.getLogger(__name__)
API_EXCEPTIONS = {
10: 'sticker set name is already occupied',
11: 'STICKERSET_INVALID', # eg. trying to remove a sticker from a set the bot doesn't own
12: 'STICKERSET_NOT_MODIFIED',
13: 'st... | [
"logging.getLogger",
"logging.config.dictConfig",
"json.load"
] | [((83, 110), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (100, 110), False, 'import logging\n'), ((739, 780), 'logging.config.dictConfig', 'logging.config.dictConfig', (['logging_config'], {}), '(logging_config)\n', (764, 780), False, 'import logging\n'), ((721, 733), 'json.load', 'jso... |
# -*- encoding: utf-8 -*-
"""
@Author : zYx.Tom
@Contact : <EMAIL>
@site : https://zhuyuanxiang.github.io
---------------------------
@Software : PyCharm
@Project : deep-learning-with-python-notebooks
@File : ch0604_conv1D.py
@Version : v0.1
@Time : 2019-11-26 11:08
... | [
"keras.layers.MaxPooling1D",
"keras.optimizers.rmsprop",
"keras.datasets.imdb.load_data",
"tools.plot_classes_results",
"matplotlib.pyplot.show",
"matplotlib.pyplot.get_fignums",
"keras.layers.GlobalMaxPooling1D",
"keras.models.Sequential",
"numpy.random.seed",
"winsound.Beep",
"keras.layers.Den... | [((1192, 1277), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(3)', 'suppress': '(True)', 'threshold': 'np.inf', 'linewidth': '(200)'}), '(precision=3, suppress=True, threshold=np.inf, linewidth=200\n )\n', (1211, 1277), True, 'import numpy as np\n'), ((1343, 1363), 'numpy.random.seed', 'np.ra... |
#! /usr/bin/env python3
"""
Stein PPO: Sample-efficient Policy Optimization with Stein Control Variate
Motivated by the Stein’s identity, Stein PPO extends the previous
control variate methods used in REINFORCE and advantage actor-critic
by introducing more general action-dependent baseline functions.
Details see th... | [
"utils.Scaler",
"numpy.array",
"gym.wrappers.Monitor",
"tensorflow.set_random_seed",
"gym.make",
"numpy.mean",
"numpy.max",
"numpy.random.seed",
"numpy.concatenate",
"numpy.min",
"policy.Policy",
"tb_logger.log",
"value_function.NNValueFunction",
"numpy.squeeze",
"datetime.datetime.utcno... | [((1299, 1316), 'numpy.random.seed', 'np.random.seed', (['i'], {}), '(i)\n', (1313, 1316), True, 'import numpy as np\n'), ((1321, 1335), 'random.seed', 'random.seed', (['i'], {}), '(i)\n', (1332, 1335), False, 'import random\n'), ((1689, 1707), 'gym.make', 'gym.make', (['env_name'], {}), '(env_name)\n', (1697, 1707), F... |
import sys
sys.path.append('..')
from FrozenLake.Game import Config, FrozenLake
from random import randint
import pprint
class qAlgorithm(object):
EPOCH = 1000
def __init__(self):
conf = Config()
conf.setSize(10,10)
conf.setEnd(9,9)
conf.addHole(randint(0,9),randint(0,9))
conf.addHole(randint(0,9),randint... | [
"FrozenLake.Game.Config",
"sys.path.append",
"random.randint",
"FrozenLake.Game.FrozenLake"
] | [((11, 32), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (26, 32), False, 'import sys\n'), ((193, 201), 'FrozenLake.Game.Config', 'Config', ([], {}), '()\n', (199, 201), False, 'from FrozenLake.Game import Config, FrozenLake\n'), ((715, 731), 'FrozenLake.Game.FrozenLake', 'FrozenLake', (['conf'... |
import argparse
import os
class Opts:
def __init__(self):
self.parser = argparse.ArgumentParser()
def init(self):
self.parser.add_argument('-expID', default='default', help='Experiment ID')
self.parser.add_argument('-data', default='default', help='Input data folder')
self.pars... | [
"os.makedirs",
"os.path.exists",
"os.path.join",
"argparse.ArgumentParser"
] | [((85, 110), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (108, 110), False, 'import argparse\n'), ((2780, 2825), 'os.path.join', 'os.path.join', (['self.opt.expDir', 'self.opt.expID'], {}), '(self.opt.expDir, self.opt.expID)\n', (2792, 2825), False, 'import os\n'), ((3130, 3171), 'os.path.jo... |
from flask import Blueprint
from flask import flash
from flask import redirect
from flask import render_template
from flask import request
from flask import url_for
from werkzeug.exceptions import abort
from cooking.routers.auth import login_required
from cooking.db import get_db
bp = Blueprint("participant", __name_... | [
"flask.render_template",
"flask.flash",
"flask.url_for",
"cooking.db.get_db",
"flask.Blueprint"
] | [((288, 349), 'flask.Blueprint', 'Blueprint', (['"""participant"""', '__name__'], {'url_prefix': '"""/participant"""'}), "('participant', __name__, url_prefix='/participant')\n", (297, 349), False, 'from flask import Blueprint\n'), ((440, 448), 'cooking.db.get_db', 'get_db', ([], {}), '()\n', (446, 448), False, 'from c... |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed unde... | [
"senlin.common.messaging.get_rpc_client",
"mock.patch",
"mock.Mock",
"mock.patch.object",
"senlin.common.messaging.get_rpc_server"
] | [((723, 774), 'mock.patch.object', 'mock.patch.object', (['oslo_messaging', '"""get_rpc_server"""'], {}), "(oslo_messaging, 'get_rpc_server')\n", (740, 774), False, 'import mock\n'), ((780, 842), 'mock.patch', 'mock.patch', (['"""senlin.common.messaging.RequestContextSerializer"""'], {}), "('senlin.common.messaging.Req... |
#!/usr/bin/python3
import os
from shutil import rmtree
from os.path import join
from common.bash import execute_bash_script
feature_branch_name = os.environ["FEATURE_BRANCH"]
feature_branch_folder = join("./cluster/development/kon", feature_branch_name)
rmtree(feature_branch_folder)
execute_bash_script(
[
... | [
"common.bash.execute_bash_script",
"os.path.join",
"shutil.rmtree"
] | [((203, 257), 'os.path.join', 'join', (['"""./cluster/development/kon"""', 'feature_branch_name'], {}), "('./cluster/development/kon', feature_branch_name)\n", (207, 257), False, 'from os.path import join\n'), ((258, 287), 'shutil.rmtree', 'rmtree', (['feature_branch_folder'], {}), '(feature_branch_folder)\n', (264, 28... |
"""Create materialized view for unique adverts
Revision ID: <KEY>
Revises: ec6065fc7ea3
Create Date: 2020-10-01 11:47:32.801222
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "<KEY>"
down_revision = "ec6065fc7ea3"
branch_labels = None
depends_on = None
def u... | [
"alembic.op.execute"
] | [((334, 942), 'alembic.op.execute', 'op.execute', (['"""\n CREATE MATERIALIZED VIEW mv_unique_adverts_by_date\n AS SELECT adverts.page_id,\n md5(adverts.ad_creative_body) AS body_hash,\n to_char(adverts.ad_creation_time::date::timestamp with time zone, \'yyyy-mm-dd\'::text) ... |
import theano
import numpy
# CRF implementation based on Lample et al.
# "Neural Architectures for Named Entity Recognition"
floatX=theano.config.floatX
def log_sum(x, axis=None):
x_max_value = x.max(axis=axis)
x_max_tensor = x.max(axis=axis, keepdims=True)
return x_max_value + theano.tensor.log(theano.t... | [
"theano.tensor.exp",
"theano.scan",
"theano.tensor.cast",
"theano.tensor.argmax",
"theano.tensor.arange",
"theano.tensor.zeros",
"theano.tensor.set_subtensor",
"theano.tensor.concatenate"
] | [((1045, 1217), 'theano.scan', 'theano.scan', ([], {'fn': 'recurrence', 'outputs_info': '((initial, None) if return_best_sequence else initial)', 'sequences': '[observation_weights[1:]]', 'non_sequences': 'transition_weights'}), '(fn=recurrence, outputs_info=(initial, None) if\n return_best_sequence else initial, se... |
from flask import Flask
from lib.router import Router
app = Flask(__name__)
Router.run(app) | [
"lib.router.Router.run",
"flask.Flask"
] | [((61, 76), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (66, 76), False, 'from flask import Flask\n'), ((78, 93), 'lib.router.Router.run', 'Router.run', (['app'], {}), '(app)\n', (88, 93), False, 'from lib.router import Router\n')] |
from psycopg2 import sql
'''
@name -> retrieveOldCustomTime
@param (dbConnection) -> db connection object
@param (cursor) -> db cursor object
@return -> a python list of 5 integers that means [year, month, day, hour, minute]
@about -> This model will retrieve the last row from the same table with every call.
... | [
"psycopg2.sql.Literal",
"psycopg2.sql.SQL"
] | [((916, 933), 'psycopg2.sql.Literal', 'sql.Literal', (['time'], {}), '(time)\n', (927, 933), False, 'from psycopg2 import sql\n'), ((837, 908), 'psycopg2.sql.SQL', 'sql.SQL', (['"""INSERT INTO last_custom_time_stamp (time_custom) VALUES ({})"""'], {}), "('INSERT INTO last_custom_time_stamp (time_custom) VALUES ({})')\n... |
from django.conf.urls import *
from djangocms_comments.views import SaveComment
urlpatterns = [
url(r'^ajax/save_comment$', SaveComment.as_view(), name='djangocms_comments_save_comment'),
]
| [
"djangocms_comments.views.SaveComment.as_view"
] | [((130, 151), 'djangocms_comments.views.SaveComment.as_view', 'SaveComment.as_view', ([], {}), '()\n', (149, 151), False, 'from djangocms_comments.views import SaveComment\n')] |
"""
Functions to load and process Ausgrid dataset.
The dataset contains 300 users with their location, PV production and electrical consumption.
The timeline for this dataset is 3 years separated in 3 files.
"""
import os
import pickle
import numpy as np
import pandas as pd
from pandas.tseries.offsets import Day
from... | [
"pickle.dump",
"pandas.MultiIndex",
"pandas.read_csv",
"numpy.arange",
"torch.utils.data.dataloader.DataLoader",
"os.path.join",
"pickle.load",
"numpy.zeros",
"pandas.DataFrame",
"pandas.tseries.offsets.Day",
"os.path.expanduser"
] | [((465, 539), 'os.path.expanduser', 'os.path.expanduser', (['"""~/Documents/Deep_Learning_Resources/datasets/ausgrid"""'], {}), "('~/Documents/Deep_Learning_Resources/datasets/ausgrid')\n", (483, 539), False, 'import os\n'), ((934, 984), 'os.path.join', 'os.path.join', (['DATA_PATH_ROOT', 'FILE_PATH_DICT[year]'], {}), ... |
"""
Manages the network negotiation portion of a client connection.
Node connects here first to get the node and Pool ID, then is redirected to the PUB/SUB ZMQ interface.
"""
import zmq
import sqlalchemy as sa
from sqlalchemy.orm import Session
import server.constants as const
import threading
import pickle
from proto.... | [
"pickle.dump",
"sqlalchemy.create_engine",
"sqlalchemy.orm.Session",
"pickle.load",
"server.db.mappings.Node",
"proto.negotiation_pb2.Negotiation",
"server.constants.BROKER_FILE.exists",
"threading.Thread",
"server.db.mappings.Pool",
"zmq.Context"
] | [((586, 599), 'zmq.Context', 'zmq.Context', ([], {}), '()\n', (597, 599), False, 'import zmq\n'), ((863, 981), 'sqlalchemy.create_engine', 'sa.create_engine', (['f"""mysql://{self.user}:{self.password}@{self.host}:{self.port}/{self.dbname}"""'], {'echo': 'verbose'}), "(\n f'mysql://{self.user}:{self.password}@{self.... |
import multiprocessing as mp
import os
import re
import string
from collections import OrderedDict
from typing import Callable, List, Optional, Union
import spacy
import vaex
from pandas.core.frame import DataFrame
from pandas.core.series import Series
from textacy.preprocessing import make_pipeline, normalize, remove... | [
"collections.OrderedDict",
"re.compile",
"spacy.load",
"vaex.from_pandas",
"textacy.preprocessing.make_pipeline"
] | [((571, 604), 're.compile', 're.compile', (['"""(?:[a-zA-Z]\\\\.){2,}"""'], {}), "('(?:[a-zA-Z]\\\\.){2,}')\n", (581, 604), False, 'import re\n'), ((766, 790), 're.compile', 're.compile', (['"""[^A-Za-z]+"""'], {}), "('[^A-Za-z]+')\n", (776, 790), False, 'import re\n'), ((967, 986), 're.compile', 're.compile', (['""" {... |
'''
Vortex OpenSplice
This software and documentation are Copyright 2006 to TO_YEAR ADLINK
Technology Limited, its affiliated companies and licensors. All rights
reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the Lice... | [
"api.emulation.task_worker.TaskWorker",
"time.sleep",
"redis.StrictRedis",
"threading.Thread",
"api.emulation.task_queue.TaskQueue"
] | [((944, 955), 'api.emulation.task_queue.TaskQueue', 'TaskQueue', ([], {}), '()\n', (953, 955), False, 'from api.emulation.task_queue import TaskQueue\n'), ((983, 995), 'api.emulation.task_worker.TaskWorker', 'TaskWorker', ([], {}), '()\n', (993, 995), False, 'from api.emulation.task_worker import TaskWorker\n'), ((1028... |
#!/usr/bin/env python
"""Configuration values."""
from os import path
import click
EXP_DATA_FP = path.abspath(path.join(path.dirname(__file__), "data"))
@click.command()
@click.argument("key", type=click.STRING)
def cli(key):
"""Print a configuration value."""
if key in globals().keys():
print(globa... | [
"os.path.dirname",
"click.argument",
"click.command"
] | [((158, 173), 'click.command', 'click.command', ([], {}), '()\n', (171, 173), False, 'import click\n'), ((175, 215), 'click.argument', 'click.argument', (['"""key"""'], {'type': 'click.STRING'}), "('key', type=click.STRING)\n", (189, 215), False, 'import click\n'), ((122, 144), 'os.path.dirname', 'path.dirname', (['__f... |
import logging
from arago.hiro.actionhandler.plugin.stonebranch.action.stonebranch_exec_unix_command_action import \
StonebranchExecUnixCommandAction
from arago.hiro.actionhandler.plugin.stonebranch.stonebranch_instance import StonebranchInstance
from arago.hiro.actionhandler.plugin.stonebranch.stonebranch_rest_cl... | [
"arago.hiro.actionhandler.plugin.stonebranch.stonebranch_instance.StonebranchInstance",
"logging.getLogger",
"logging.basicConfig",
"arago.hiro.actionhandler.plugin.stonebranch.action.stonebranch_exec_unix_command_action.StonebranchExecUnixCommandAction.exec_task"
] | [((431, 523), 'arago.hiro.actionhandler.plugin.stonebranch.stonebranch_instance.StonebranchInstance', 'StonebranchInstance', ([], {'host': '"""stonebranch.cloud"""', 'username': '"""username"""', 'password': '"""password"""'}), "(host='stonebranch.cloud', username='username', password\n ='password')\n", (450, 523), ... |
# -*- coding: utf-8 -*-
from six.moves import cStringIO as StringIO
import codecs
import collections
import datetime
import imghdr
import json
import logging
import os
import pkg_resources
import pprint
import re
import six
import socket
import subprocess
import sys
import unittest
import uuid
from jinja2 import Temp... | [
"logging.StreamHandler",
"six.b",
"pygments.highlight",
"jinja2.Template",
"six.text_type",
"six.u",
"os.path.exists",
"json.dumps",
"six.binary_type",
"pygments.lexers.TextLexer",
"subprocess.call",
"pygments.lexers.Python3Lexer",
"socket.gethostname",
"six.moves.cStringIO",
"json.loads... | [((1327, 1355), 'six.add_metaclass', 'six.add_metaclass', (['Singleton'], {}), '(Singleton)\n', (1344, 1355), False, 'import six\n'), ((6947, 7026), 'collections.namedtuple', 'collections.namedtuple', (['"""CodeLine"""', "('lineno', 'code', 'highlight', 'extended')"], {}), "('CodeLine', ('lineno', 'code', 'highlight', ... |
# Generated by Django 3.1.3 on 2020-11-26 07:32
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import uuid
class Migration(migrations.Migration):
replaces = [('annotators', '0001_initial'), ('annotators', '0002_auto_20201110_0257'), ('annotators', '0003_au... | [
"django.db.models.EmailField",
"django.db.models.TextField",
"django.db.models.IntegerField",
"django.db.models.ForeignKey",
"django.db.models.JSONField",
"django.db.models.BooleanField",
"django.db.models.AutoField",
"django.db.models.CharField",
"django.db.models.DateTimeField",
"django.db.model... | [((555, 648), '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", (571, 648), False, 'from django.db import migrations, models\... |
#!/usr/bin/env python
"""
Estimates the static background in a STORM movie.
The estimate is performed by averaging this might
not be the best choice for movies with a high density
of real localizations.
This may be a good choice if you have a largish
fixed background and a relatively low density of
real localizations... | [
"storm_analysis.sa_library.datareader.inferReader",
"storm_analysis.sa_library.datawriter.DaxWriter",
"argparse.ArgumentParser",
"numpy.zeros",
"storm_analysis.sa_library.parameters.ParametersCommon"
] | [((3756, 3833), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Running average background subtraction"""'}), "(description='Running average background subtraction')\n", (3779, 3833), False, 'import argparse\n'), ((4453, 4490), 'storm_analysis.sa_library.datareader.inferReader', 'dataread... |
# Generated by Django 2.1.7 on 2019-02-19 18:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0004_auto_20190218_1809'),
]
operations = [
migrations.AlterField(
model_name='userprofiles',
name='head_po... | [
"django.db.models.ImageField"
] | [((347, 533), 'django.db.models.ImageField', 'models.ImageField', ([], {'default': '"""users/static/users/image/head_portrait/default.png"""', 'max_length': '(200)', 'upload_to': '"""users/static/users/image/head_portrait/%Y/%m"""', 'verbose_name': '"""头像"""'}), "(default=\n 'users/static/users/image/head_portrait/d... |
import argparse
import ast
import os
import numpy as np
import cv2
parser = argparse.ArgumentParser()
parser.add_argument('OutputDirectory', help='The directory where the generated images will be saved')
parser.add_argument('--numberOfImages', help='The number of generated images. Default: 100', type=int, default=100)... | [
"cv2.imwrite",
"numpy.ones",
"argparse.ArgumentParser",
"ast.literal_eval",
"numpy.random.randint"
] | [((77, 102), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (100, 102), False, 'import argparse\n'), ((895, 927), 'ast.literal_eval', 'ast.literal_eval', (['args.imageSize'], {}), '(args.imageSize)\n', (911, 927), False, 'import ast\n'), ((943, 978), 'ast.literal_eval', 'ast.literal_eval', (['a... |
# Python packages
import re, json
class Blog:
"""
Read config file and store site-wide variables.
"""
def __init__(self, config_file="./config.json"):
"""
When initializing a Blog instance, populate it with settings in the
config file.
In case of KeyError (user not prov... | [
"json.load",
"re.match",
"re.compile"
] | [((579, 593), 'json.load', 'json.load', (['fin'], {}), '(fin)\n', (588, 593), False, 'import re, json\n'), ((1571, 1590), 're.compile', 're.compile', (['pattern'], {}), '(pattern)\n', (1581, 1590), False, 'import re, json\n'), ((2487, 2512), 're.match', 're.match', (['REGEX', 'filename'], {}), '(REGEX, filename)\n', (2... |
# MIT License
# Copyright (c) 2017 MassChallenge, Inc.
import swapper
from accelerator_abstract.models import BasePartnerApplicationInterest
class PartnerApplicationInterest(BasePartnerApplicationInterest):
class Meta(BasePartnerApplicationInterest.Meta):
swappable = swapper.swappable_setting(
... | [
"swapper.swappable_setting"
] | [((284, 390), 'swapper.swappable_setting', 'swapper.swappable_setting', (['BasePartnerApplicationInterest.Meta.app_label', '"""PartnerApplicationInterest"""'], {}), "(BasePartnerApplicationInterest.Meta.app_label,\n 'PartnerApplicationInterest')\n", (309, 390), False, 'import swapper\n')] |
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... | [
"mock.patch",
"ebcli.operations.spotops.get_spot_instance_types_from_customer"
] | [((708, 772), 'mock.patch', 'mock.patch', (['"""ebcli.operations.spotops.prompt_for_instance_types"""'], {}), "('ebcli.operations.spotops.prompt_for_instance_types')\n", (718, 772), False, 'import mock\n'), ((1152, 1216), 'mock.patch', 'mock.patch', (['"""ebcli.operations.spotops.prompt_for_instance_types"""'], {}), "(... |
# Author: StevenChaoo
# -*- coding:UTF-8 -*-
import json
import logging
import time
import random
import sys
from sklearn_crfsuite import CRF
from sklearn.metrics import classification_report
from util import tools
from tqdm import tqdm
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(me... | [
"logging.basicConfig",
"logging.getLogger",
"sklearn.metrics.classification_report",
"tqdm.tqdm",
"sklearn_crfsuite.CRF"
] | [((242, 383), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s - %(levelname)s - %(name)s - %(message)s"""', 'datefmt': '"""%m/%d/%Y %H:%M:%S"""', 'level': 'logging.INFO'}), "(format=\n '%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt=\n '%m/%d/%Y %H:%M:%S', level=loggi... |
from setuptools import setup
setup(name='geo',
version='0.1',
description='Useful geoprospection processing methods',
author='<NAME>',
author_email='<EMAIL>',
license='MIT',
packages=['geo'],
zip_safe=False)
| [
"setuptools.setup"
] | [((32, 219), 'setuptools.setup', 'setup', ([], {'name': '"""geo"""', 'version': '"""0.1"""', 'description': '"""Useful geoprospection processing methods"""', 'author': '"""<NAME>"""', 'author_email': '"""<EMAIL>"""', 'license': '"""MIT"""', 'packages': "['geo']", 'zip_safe': '(False)'}), "(name='geo', version='0.1', de... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = 'setup'
__author__ = 'zhouzhuan'
__mtime__ = '2017/6/29'
"""
import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__),'README.rst')) as readme:
README = readme.read()
#allow setup to be run from any path
os.... | [
"os.path.abspath",
"os.path.dirname",
"setuptools.setup"
] | [((398, 1041), 'setuptools.setup', 'setup', ([], {'name': '"""django-polls"""', 'version': '"""0.1"""', 'packages': "['polls']", 'include_package_data': '(True)', 'license': '"""BSD License"""', 'description': '"""A simple Django app to conduct Web-based polls."""', 'long_description': 'README', 'url': '"""https://gith... |
from setuptools import setup
setup(
name="timely-beliefs",
description="Data modelled as beliefs (at a certain time) about events (at a certain time).",
author="<NAME>",
author_email="<EMAIL>",
keywords=[
"time series",
"forecasting",
"analytics",
"visualization",
... | [
"setuptools.setup"
] | [((30, 1422), 'setuptools.setup', 'setup', ([], {'name': '"""timely-beliefs"""', 'description': '"""Data modelled as beliefs (at a certain time) about events (at a certain time)."""', 'author': '"""<NAME>"""', 'author_email': '"""<EMAIL>"""', 'keywords': "['time series', 'forecasting', 'analytics', 'visualization', 'un... |
# Copyright 2021 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# 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.... | [
"numpy.mean",
"numpy.linalg.pinv",
"datasets.utils.file_utils.add_start_docstrings",
"numpy.array",
"numpy.dot",
"numpy.linalg.inv",
"datasets.Value",
"numpy.cov"
] | [((1945, 2030), 'datasets.utils.file_utils.add_start_docstrings', 'datasets.utils.file_utils.add_start_docstrings', (['_DESCRIPTION', '_KWARGS_DESCRIPTION'], {}), '(_DESCRIPTION,\n _KWARGS_DESCRIPTION)\n', (1991, 2030), False, 'import datasets\n'), ((2534, 2545), 'numpy.array', 'np.array', (['X'], {}), '(X)\n', (254... |
from sys import argv
from context import TGB
if __name__ == '__main__':
print('Running communication smoketest.')
if len(argv) == 1:
print('please input local address for testing the communication as an argument\nEx. %s 111.111.11.11' % (
argv[0]))
quit()
if len(argv) == 2:
... | [
"context.TGB.Blockchain",
"context.TGB.Network"
] | [((369, 395), 'context.TGB.Blockchain', 'TGB.Blockchain', (['_testNodes'], {}), '(_testNodes)\n', (383, 395), False, 'from context import TGB\n'), ((419, 439), 'context.TGB.Network', 'TGB.Network', (['_testBC'], {}), '(_testBC)\n', (430, 439), False, 'from context import TGB\n')] |
#
# test template
#
# @ author becxer
# @ email <EMAIL>
#
from test_pytrain import test_Suite
class test_Template(test_Suite):
def __init__(self, logging = True):
test_Suite.__init__(self, logging)
def test_process(self):
global_value = self.get_global_value('some_key')
self.set_glob... | [
"test_pytrain.test_Suite.__init__"
] | [((178, 212), 'test_pytrain.test_Suite.__init__', 'test_Suite.__init__', (['self', 'logging'], {}), '(self, logging)\n', (197, 212), False, 'from test_pytrain import test_Suite\n')] |
from django.shortcuts import render
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from django.views.generic import TemplateView
# @method_decorator(cache_page(60 * 10), name='dispatch')
class HomePageView(TemplateView):
template_name = 'home/home.html'
... | [
"django.shortcuts.render"
] | [((497, 542), 'django.shortcuts.render', 'render', (['request', '"""error_404.html"""'], {'status': '(404)'}), "(request, 'error_404.html', status=404)\n", (503, 542), False, 'from django.shortcuts import render\n'), ((581, 626), 'django.shortcuts.render', 'render', (['request', '"""error_500.html"""'], {'status': '(50... |
import plotly.graph_objects as go
large_rockwell_template = dict(
layout=go.Layout(title_font=dict(family="Rockwell", size=24))
)
fig = go.Figure()
fig.update_layout(title='Figure Title', template=large_rockwell_template)
fig.show()
| [
"plotly.graph_objects.Figure"
] | [((142, 153), 'plotly.graph_objects.Figure', 'go.Figure', ([], {}), '()\n', (151, 153), True, 'import plotly.graph_objects as go\n')] |
from django.conf.urls import url
from ratelimitbackend import admin
from ratelimitbackend.views import login
from .forms import CustomAuthForm, TokenOnlyAuthForm
urlpatterns = [
url(r'^login/$', login,
{'template_name': 'admin/login.html'}, name='login'),
url(r'^custom_login/$', login,
{'tem... | [
"django.conf.urls.url"
] | [((186, 261), 'django.conf.urls.url', 'url', (['"""^login/$"""', 'login', "{'template_name': 'admin/login.html'}"], {'name': '"""login"""'}), "('^login/$', login, {'template_name': 'admin/login.html'}, name='login')\n", (189, 261), False, 'from django.conf.urls import url\n'), ((276, 409), 'django.conf.urls.url', 'url'... |
#!/usr/bin/python
# This is the second program shown in Kunal chawla's prank project in udacity's Programming foundation with Python.
import os
def rename_files():
#(1) get fle names in an array from a directory
# give your directory path based on OS
file_list = os.listdir(r"/home/sanjeev/prank")
saved_path =... | [
"os.chdir",
"os.listdir",
"os.getcwd"
] | [((271, 304), 'os.listdir', 'os.listdir', (['"""/home/sanjeev/prank"""'], {}), "('/home/sanjeev/prank')\n", (281, 304), False, 'import os\n'), ((321, 332), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (330, 332), False, 'import os\n'), ((388, 419), 'os.chdir', 'os.chdir', (['"""/home/sanjeev/prank"""'], {}), "('/home/sa... |
""" integrity checks for the wxyz repo
"""
import re
# pylint: disable=redefined-outer-name
import sys
import tempfile
from pathlib import Path
import pytest
from . import _paths as P
PYTEST_INI = """
[pytest]
junit_family = xunit2
"""
@pytest.fixture(scope="module")
def contributing_text():
"""the text of CO... | [
"tempfile.TemporaryDirectory",
"pathlib.Path",
"pytest.main",
"pytest.mark.parametrize",
"pytest.fixture",
"re.findall"
] | [((243, 273), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (257, 273), False, 'import pytest\n'), ((394, 424), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (408, 424), False, 'import pytest\n'), ((527, 557), 'pytest.fixture', 'p... |
import datetime
import hashlib
import logging
import os
import tarfile
from azure.storage.blob import BlockBlobService
from boto.s3.connection import S3Connection
from boto.s3.bucket import Bucket
from boto.s3.key import Key
import dj_database_url
import django # Provides django.setup()
from django.apps import apps a... | [
"logging.getLogger",
"tarfile.open",
"os.path.remove",
"boto.s3.connection.S3Connection",
"hashlib.sha1",
"boto.s3.bucket.Bucket",
"os.path.exists",
"dj_database_url.config",
"os.path.lexists",
"os.unlink",
"os.path.getsize",
"django.apps.apps.get_app_configs",
"os.path.isfile",
"boto.s3.k... | [((505, 644), 'logging.basicConfig', 'logging.basicConfig', ([], {'filename': '"""backup.log"""', 'level': 'logging.INFO', 'format': '"""%(asctime)s [%(levelname)s]: %(message)s"""', 'datefmt': 'DATE_FORMAT'}), "(filename='backup.log', level=logging.INFO, format=\n '%(asctime)s [%(levelname)s]: %(message)s', datefmt... |
"""
Script to control mouse cursor with gamepad stick.
Specifically: right stick x axis controls mouse x position.
Requires FreePIE: https://github.com/AndersMalmgren/FreePIE
2020-06-11 JAO
"""
if starting:
"""This block only runs once."""
import time
joy_id = 0 # gamepad device number
x_axis_mult = 0.... | [
"time.time"
] | [((523, 534), 'time.time', 'time.time', ([], {}), '()\n', (532, 534), False, 'import time\n'), ((647, 658), 'time.time', 'time.time', ([], {}), '()\n', (656, 658), False, 'import time\n')] |
import json as _json
import os as _os
import retry as _retry
from flytekit.common.tasks import sdk_runnable as _sdk_runnable
from flytekit.engines import common as _common_engine
SM_RESOURCE_CONFIG_FILE = "/opt/ml/input/config/resourceconfig.json"
SM_ENV_VAR_CURRENT_HOST = "SM_CURRENT_HOST"
SM_ENV_VAR_HOSTS = "SM_HO... | [
"json.load",
"retry.retry",
"os.environ.get"
] | [((716, 779), 'retry.retry', '_retry.retry', ([], {'exceptions': 'KeyError', 'delay': '(1)', 'tries': '(10)', 'backoff': '(1)'}), '(exceptions=KeyError, delay=1, tries=10, backoff=1)\n', (728, 779), True, 'import retry as _retry\n'), ((1530, 1602), 'retry.retry', '_retry.retry', ([], {'exceptions': 'FileNotFoundError',... |
#
# betatest setup script
#
# Copyright (c) 2018 Beta Five Ltd
#
# SPDX-License-Identifier: Apache-2.0
#
import re
import runpy
import setuptools
import sys
# Check minimum python version
if sys.version_info < (3,6):
print('ERROR: betatest requires Python 3.6+')
sys.exit(1)
# Pick up the version number from ... | [
"runpy.run_path",
"setuptools.find_packages",
"re.match",
"sys.exit"
] | [((621, 663), 're.match', 're.match', (['"""(.*) <(.*)>$"""', 'first_maintainer'], {}), "('(.*) <(.*)>$', first_maintainer)\n", (629, 663), False, 'import re\n'), ((273, 284), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (281, 284), False, 'import sys\n'), ((350, 387), 'runpy.run_path', 'runpy.run_path', (['"""betat... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
These are the set of attributes that can be computed for each run. The
configuration specifies which subset of these should be stored, how
and where.
The attributes provide a fairly expressive language to collect
information recursively. Each attribute can combine ... | [
"datetime.datetime.now",
"os.path.join"
] | [((1770, 1788), 'os.path.join', 'os.path.join', (['args'], {}), '(args)\n', (1782, 1788), False, 'import os, sys\n'), ((1255, 1269), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1267, 1269), False, 'from datetime import datetime\n')] |
from django.contrib import admin
from cliente.models import Cliente
admin.site.register(Cliente)
| [
"django.contrib.admin.site.register"
] | [((69, 97), 'django.contrib.admin.site.register', 'admin.site.register', (['Cliente'], {}), '(Cliente)\n', (88, 97), False, 'from django.contrib import admin\n')] |
"""
Author: <NAME>
Date last modified: 01-03-2019
"""
from unittest import TestCase
from graphy.utils import dict as my_dict
class TestDict(TestCase):
def test_calc_percentage(self):
""" Tests calc_percentage function. """
test_dict = {'0': 1, '1': 1, '2': 2}
right_result_dict =... | [
"graphy.utils.dict.update",
"graphy.utils.dict.sort",
"graphy.utils.dict.calc_percentage",
"graphy.utils.dict.filter"
] | [((1805, 1848), 'graphy.utils.dict.update', 'my_dict.update', (['test_dict', '"""2"""', 'update_func'], {}), "(test_dict, '2', update_func)\n", (1819, 1848), True, 'from graphy.utils import dict as my_dict\n'), ((444, 478), 'graphy.utils.dict.calc_percentage', 'my_dict.calc_percentage', (['test_dict'], {}), '(test_dict... |
from django.urls import path
from xcx_interface.controller.menu.menu_msg import getMenuList
urlpatterns = [
# 获取菜单列表
path('getMenuList', getMenuList, name='getMenuList')
]
| [
"django.urls.path"
] | [((126, 178), 'django.urls.path', 'path', (['"""getMenuList"""', 'getMenuList'], {'name': '"""getMenuList"""'}), "('getMenuList', getMenuList, name='getMenuList')\n", (130, 178), False, 'from django.urls import path\n')] |
#!/usr/bin/env python
# Copyright (C) 2016 Apple Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:n
#
# 1. Redistributions of source code must retain the above copyright
# notice, this li... | [
"optparse.OptionParser",
"re.compile"
] | [((1504, 1571), 'optparse.OptionParser', 'optparse.OptionParser', ([], {'usage': '"""usage: %prog <wasm.json> <WasmOps.h>"""'}), "(usage='usage: %prog <wasm.json> <WasmOps.h>')\n", (1525, 1571), False, 'import optparse\n'), ((1785, 1813), 're.compile', 're.compile', (['"""([a-zA-Z0-9]+)"""'], {}), "('([a-zA-Z0-9]+)')\n... |
#!/usr/bin/env python
import rospy
from sensor_msgs.msg import Image, CameraInfo
import os.path
import cv2
from cv_bridge import CvBridge, CvBridgeError
import time
IMAGE_MESSAGE_TOPIC = 'image_color'
CAMERA_MESSAGE_TOPIC = 'cam_info'
rospy.init_node('video_2_camera_stream')
device_path = rospy.get_param('~dev', ... | [
"rospy.logerr",
"rospy.is_shutdown",
"rospy.init_node",
"rospy.get_param",
"cv_bridge.CvBridge",
"sensor_msgs.msg.CameraInfo",
"rospy.Rate",
"cv2.VideoCapture",
"rospy.Publisher",
"time.time",
"rospy.loginfo"
] | [((240, 280), 'rospy.init_node', 'rospy.init_node', (['"""video_2_camera_stream"""'], {}), "('video_2_camera_stream')\n", (255, 280), False, 'import rospy\n'), ((296, 334), 'rospy.get_param', 'rospy.get_param', (['"""~dev"""', '"""/dev/video0"""'], {}), "('~dev', '/dev/video0')\n", (311, 334), False, 'import rospy\n'),... |
from typing import List
from collections import Counter
def top_k_frequent(words: List[str], k: int) -> List[str]:
words = sorted(words)
freq = Counter(words)
freq = sorted(freq.items(), key=lambda x: x[1], reverse=True)
return [i[0] for i in freq[:k]]
if __name__ == '__main__':
pr... | [
"collections.Counter"
] | [((162, 176), 'collections.Counter', 'Counter', (['words'], {}), '(words)\n', (169, 176), False, 'from collections import Counter\n')] |
# Copyright (c) OpenMMLab. All rights reserved.
import warnings
import torch
from ..builder import DETECTORS
from .single_stage import SingleStageDetector
@DETECTORS.register_module()
class DETR(SingleStageDetector):
r"""Implementation of `DETR: End-to-End Object Detection with
Transformers <https://arxiv.o... | [
"warnings.warn",
"torch.no_grad",
"torch._shape_as_tensor"
] | [((1035, 1172), 'warnings.warn', 'warnings.warn', (['"""Warning! MultiheadAttention in DETR does not support flops computation! Do not use the results in your papers!"""'], {}), "(\n 'Warning! MultiheadAttention in DETR does not support flops computation! Do not use the results in your papers!'\n )\n", (1048, 117... |
import numpy as np
import matplotlib.pyplot as plt
from .integrate import Integrate
class Riemann(Integrate):
"""
Compute the Riemann sum of f(x) over the interval [a,b].
Parameters
----------
f : function
A single variable function f(x), ex: lambda x:np.exp(x**2)
"""
def _... | [
"matplotlib.pyplot.plot",
"numpy.linspace",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show"
] | [((1479, 1518), 'numpy.linspace', 'np.linspace', (['self.a', 'self.b', '(self.N + 1)'], {}), '(self.a, self.b, self.N + 1)\n', (1490, 1518), True, 'import numpy as np\n'), ((2043, 2082), 'numpy.linspace', 'np.linspace', (['self.a', 'self.b', '(self.N + 1)'], {}), '(self.a, self.b, self.N + 1)\n', (2054, 2082), True, 'i... |
import pandas as pd
import numpy as np
import torch
import torch.nn as nn
import utils
from torch.utils.data import Dataset, DataLoader
from net import model
import math
from tqdm import tqdm
import matplotlib.pyplot as plt
import os
from sklearn.preprocessing import StandardScaler
from torch.optim import lr_scheduler
... | [
"pandas.read_csv",
"matplotlib.pyplot.ylabel",
"net.model.RNN_modelv1",
"numpy.array",
"torch.nn.MSELoss",
"utils.Setloader",
"torch.cuda.is_available",
"torch.squeeze",
"net.model.train",
"net.model.eval",
"torch.unsqueeze",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"net.model... | [((635, 660), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (658, 660), False, 'import torch\n'), ((876, 967), 'pandas.read_csv', 'pd.read_csv', (['"""D:\\\\dataset\\\\lilium_price\\\\train_data.csv"""'], {'encoding': '"""utf-8"""', 'index_col': '(0)'}), "('D:\\\\dataset\\\\lilium_price\\\\tra... |
from django.db import models
class User(models.Model):
id = models.AutoField(primary_key=True, blank=True)
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
login = models.CharField(max_length=200, unique=True)
password = models.CharField(max_length=200)
... | [
"django.db.models.EmailField",
"django.db.models.AutoField",
"django.db.models.CharField",
"django.db.models.BooleanField"
] | [((66, 112), 'django.db.models.AutoField', 'models.AutoField', ([], {'primary_key': '(True)', 'blank': '(True)'}), '(primary_key=True, blank=True)\n', (82, 112), False, 'from django.db import models\n'), ((130, 162), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(200)'}), '(max_length=200)\n', ... |
import numpy as np
from scipy import stats
__all__ = ['register_stat']
statistic_factory = {
'min': np.min,
'max': np.max,
'mean': np.mean,
'median': np.median,
'std': np.std,
'sum': np.sum,
'cumsum': np.cumsum,
}
def register_stat(func=None, name=None):
"""Function to register sta... | [
"scipy.stats.mode"
] | [((1322, 1346), 'scipy.stats.mode', 'stats.mode', (['a'], {'axis': 'None'}), '(a, axis=None)\n', (1332, 1346), False, 'from scipy import stats\n'), ((1391, 1415), 'scipy.stats.mode', 'stats.mode', (['a'], {'axis': 'None'}), '(a, axis=None)\n', (1401, 1415), False, 'from scipy import stats\n')] |
import argparse
import numpy as np
import utils.loader as l
def get_arguments():
"""Gets arguments from the command line.
Returns:
A parser with the input arguments.
"""
# Creates the ArgumentParser
parser = argparse.ArgumentParser(
usage='Digitizes a numpy array into interval... | [
"numpy.flip",
"utils.loader.load_npy",
"numpy.unique",
"argparse.ArgumentParser",
"numpy.digitize",
"numpy.linspace",
"utils.loader.save_npy",
"numpy.zeros",
"numpy.bincount"
] | [((243, 347), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'usage': '"""Digitizes a numpy array into intervals in order to create targets."""'}), "(usage=\n 'Digitizes a numpy array into intervals in order to create targets.')\n", (266, 347), False, 'import argparse\n'), ((796, 819), 'utils.loader.loa... |
import json
import queue
from concurrent.futures import ThreadPoolExecutor
import flask
from flask import Response, jsonify, request
from jsonschema import validate
from node.gpg_utils import *
from node.schema import property_schema
from node.utils import BlockList, get_hash
# currently its using inmemory, can be c... | [
"flask.Flask",
"concurrent.futures.ThreadPoolExecutor",
"queue.empty",
"queue.full",
"queue.get",
"queue.Queue",
"flask.request.get_json",
"jsonschema.validate",
"queue.put",
"queue.all_tasks_done",
"node.utils.BlockList",
"node.utils.get_hash",
"flask.jsonify"
] | [((438, 452), 'queue.Queue', 'queue.Queue', (['(5)'], {}), '(5)\n', (449, 452), False, 'import queue\n'), ((466, 487), 'concurrent.futures.ThreadPoolExecutor', 'ThreadPoolExecutor', (['(8)'], {}), '(8)\n', (484, 487), False, 'from concurrent.futures import ThreadPoolExecutor\n'), ((510, 521), 'node.utils.BlockList', 'B... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2020 <NAME> <<EMAIL>>
import time
from preggy import expect
from tornado.ioloop import IOLoop
from tornado.... | [
"thumbor.context.Context",
"thumbor.app.ThumborServiceApp",
"preggy.expect",
"thumbor.config.Config",
"time.sleep",
"tornado.ioloop.IOLoop.instance",
"thumbor.context.ServerParameters",
"preggy.expect.error_to_happen",
"thumbor.importer.Importer"
] | [((788, 819), 'thumbor.app.ThumborServiceApp', 'ThumborServiceApp', (['self.context'], {}), '(self.context)\n', (805, 819), False, 'from thumbor.app import ThumborServiceApp\n'), ((895, 966), 'thumbor.context.ServerParameters', 'ServerParameters', (['(8888)', '"""localhost"""', '"""thumbor.conf"""', 'None', '"""info"""... |
from base import BaseHandler
from functions import *
from models import User
class SignupHandler(BaseHandler):
"""Sign up handler that is used to signup users."""
def get(self):
self.render("signup.html")
def post(self):
error = False
self.username = self.request.get("username")
... | [
"models.User.by_username",
"models.User.register"
] | [((748, 779), 'models.User.by_username', 'User.by_username', (['self.username'], {}), '(self.username)\n', (764, 779), False, 'from models import User\n'), ((1425, 1480), 'models.User.register', 'User.register', (['self.username', 'self.password', 'self.email'], {}), '(self.username, self.password, self.email)\n', (143... |
from BasicRL.BasicRL import BasicRL
from BasicRL.MyPlotter import MyPlotter
import gym, glob
if __name__ == "__main__":
print("Hello Basic RL example!")
# Load Gym Env
env = gym.make("CartPole-v1")
# Run PPO Algorithm
learner = BasicRL("PPO", gym_env=env, verbose=2, gamma=0.99, sigma=1.0, exploration_decay=0.9... | [
"BasicRL.MyPlotter.MyPlotter",
"BasicRL.BasicRL.BasicRL",
"gym.make",
"glob.glob"
] | [((180, 203), 'gym.make', 'gym.make', (['"""CartPole-v1"""'], {}), "('CartPole-v1')\n", (188, 203), False, 'import gym, glob\n'), ((237, 326), 'BasicRL.BasicRL.BasicRL', 'BasicRL', (['"""PPO"""'], {'gym_env': 'env', 'verbose': '(2)', 'gamma': '(0.99)', 'sigma': '(1.0)', 'exploration_decay': '(0.99)'}), "('PPO', gym_env... |
import unittest
from pathlib import Path
from coldtype.grid import Grid
from coldtype.geometry import *
from coldtype.color import hsl
from coldtype.text.composer import StSt, Glyphwise, Style, Font
from coldtype.pens.draftingpens import DraftingPens
from coldtype.pens.svgpen import SVGPen
tf = Path(__file__).parent
... | [
"coldtype.text.composer.Font.Find",
"pathlib.Path",
"coldtype.text.composer.Style",
"coldtype.text.composer.Font.Cacheable",
"coldtype.color.hsl",
"coldtype.text.composer.StSt",
"coldtype.text.composer.Glyphwise",
"unittest.main"
] | [((297, 311), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (301, 311), False, 'from pathlib import Path\n'), ((3143, 3158), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3156, 3158), False, 'import unittest\n'), ((482, 526), 'coldtype.text.composer.StSt', 'StSt', (['txt', 'font_path', '(100)'], {'... |
#!/usr/local/bin/python3
import os
import sys
from PIL import Image
import re
# Converts multiple video files to images in corresponding individual folder:
# - dir
# - images
# - frame_000001.PNG
# - frame_000002.PNG
#
#
def video_to_images(dir):
dir = os.path.join(dir, 'images')
for filena... | [
"os.listdir",
"PIL.Image.open",
"os.path.join",
"os.path.isfile",
"os.remove",
"re.search"
] | [((278, 305), 'os.path.join', 'os.path.join', (['dir', '"""images"""'], {}), "(dir, 'images')\n", (290, 305), False, 'import os\n'), ((333, 348), 'os.listdir', 'os.listdir', (['dir'], {}), '(dir)\n', (343, 348), False, 'import os\n'), ((366, 393), 'os.path.join', 'os.path.join', (['dir', 'filename'], {}), '(dir, filena... |
import numpy as np
import pandas as pd
import tensorflow as tf
tfd = tf.contrib.distributions
def create_german_datasets(batch=64):
def gather_labels(df):
labels = []
for j in range(df.shape[1]):
if type(df[0, j]) is str:
labels.append(np.unique(df[:, j]).tolist())
... | [
"numpy.mean",
"numpy.median",
"numpy.unique",
"pandas.read_csv",
"tensorflow.data.Dataset.from_tensor_slices",
"numpy.zeros",
"numpy.random.seed",
"numpy.arange",
"numpy.random.shuffle"
] | [((1895, 1916), 'numpy.arange', 'np.arange', (['d.shape[0]'], {}), '(d.shape[0])\n', (1904, 1916), True, 'import numpy as np\n'), ((1921, 1938), 'numpy.random.seed', 'np.random.seed', (['(4)'], {}), '(4)\n', (1935, 1938), True, 'import numpy as np\n'), ((1943, 1965), 'numpy.random.shuffle', 'np.random.shuffle', (['idx'... |
# coding=utf-8
from tqdm import tqdm
from base.base_train import BaseTrain
from utils.signal_process import plot_alignment
class TacotronTrainer(BaseTrain):
def __init__(self, sess, model, data_loader, config, logger):
super(TacotronTrainer, self).__init__(sess, model, data_loader, config, logger)
d... | [
"utils.signal_process.plot_alignment"
] | [((1881, 1933), 'utils.signal_process.plot_alignment', 'plot_alignment', (['al[0]', 'cur_it', 'self.config.align_dir'], {}), '(al[0], cur_it, self.config.align_dir)\n', (1895, 1933), False, 'from utils.signal_process import plot_alignment\n')] |
from steem import Steem
from datetime import datetime, date, timedelta
from math import ceil, log, isnan
import requests
API = 'https://api.steemjs.com/'
def tag_filter(tag, limit = 10):
tag_search = Steem()
tag_query = {
"tag":tag,
"limit": limit
}
tag_filters = tag_search.get_dis... | [
"math.ceil",
"requests.get",
"math.log",
"steem.Steem",
"math.isnan"
] | [((206, 213), 'steem.Steem', 'Steem', ([], {}), '()\n', (211, 213), False, 'from steem import Steem\n'), ((1214, 1224), 'math.isnan', 'isnan', (['out'], {}), '(out)\n', (1219, 1224), False, 'from math import ceil, log, isnan\n'), ((1358, 1372), 'math.ceil', 'ceil', (['(vp / 100)'], {}), '(vp / 100)\n', (1362, 1372), Fa... |
from typing import Union
import flask_restx
import flask
from keepachangelog._changelog import to_dict
def add_changelog_endpoint(
namespace: Union[flask_restx.Namespace, flask_restx.Api], changelog_path: str
):
"""
Create /changelog: Changelog endpoint parsing https://keepachangelog.com/en/1.0.0/
... | [
"flask_restx.fields.Date",
"keepachangelog._changelog.to_dict",
"flask_restx.fields.String",
"flask.jsonify"
] | [((3242, 3265), 'keepachangelog._changelog.to_dict', 'to_dict', (['changelog_path'], {}), '(changelog_path)\n', (3249, 3265), False, 'from keepachangelog._changelog import to_dict\n'), ((3328, 3345), 'flask.jsonify', 'flask.jsonify', (['{}'], {}), '({})\n', (3341, 3345), False, 'import flask\n'), ((1631, 1685), 'flask_... |
import bisect
import math
import operator
from datetime import timedelta
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cm
import matplotlib.font_manager as font_manager
import matplotlib.patheff... | [
"scipy.ndimage.filters.gaussian_filter",
"numpy.array",
"datetime.timedelta",
"matplotlib.patheffects.withStroke",
"historical_hrrr.historical_hrrr_snow",
"numpy.arange",
"numpy.where",
"nohrsc_plotting.nohrsc_snow",
"plot_cities.get_cities",
"matplotlib.colors.ListedColormap",
"matplotlib.offse... | [((593, 628), 'matplotlib.font_manager.findSystemFonts', 'font_manager.findSystemFonts', (["['.']"], {}), "(['.'])\n", (621, 628), True, 'import matplotlib.font_manager as font_manager\n'), ((1358, 1385), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 6)'}), '(figsize=(12, 6))\n', (1368, 1385), True, ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Scheduler Resource"""
from hiispider.resources.base import BaseResource
class SchedulerResource(BaseResource):
isLeaf = True
def __init__(self, schedulerserver):
self.schedulerserver = schedulerserver
BaseResource.__init__(self)
def rend... | [
"hiispider.resources.base.BaseResource.__init__"
] | [((279, 306), 'hiispider.resources.base.BaseResource.__init__', 'BaseResource.__init__', (['self'], {}), '(self)\n', (300, 306), False, 'from hiispider.resources.base import BaseResource\n')] |
# -*- coding: utf-8 -*-
from sdgen._configurable_mixin import ConfigurableMixin
from sdgen.utils import helpers
class Field(ConfigurableMixin):
"""Abstract base *field* class.
Each field represents simple or complex graphical element, for example:
:class:`sdgen.fields.character.Character` or
:cla... | [
"sdgen.utils.helpers.pt_to_px",
"sdgen.utils.helpers.px_to_pt"
] | [((2216, 2240), 'sdgen.utils.helpers.pt_to_px', 'helpers.pt_to_px', (['points'], {}), '(points)\n', (2232, 2240), False, 'from sdgen.utils import helpers\n'), ((2479, 2503), 'sdgen.utils.helpers.px_to_pt', 'helpers.px_to_pt', (['points'], {}), '(points)\n', (2495, 2503), False, 'from sdgen.utils import helpers\n')] |
import tensorflow as tf
import numpy as np
import os
import pickle
from utils.symbolic_network import SymbolicNet, MaskedSymbolicNet, SymbolicCell
from utils import functions, regularization, helpers, pretty_print
import argparse
def main(results_dir='results/sho/test', trials=1, learning_rate=1e-2, reg_weight=2e-4, ... | [
"utils.symbolic_network.SymbolicCell",
"tensorflow.shape",
"utils.functions.Square",
"tensorflow.sin",
"utils.functions.Exp",
"os.path.exists",
"argparse.ArgumentParser",
"tensorflow.placeholder",
"tensorflow.Session",
"numpy.asarray",
"json.dumps",
"numpy.stack",
"utils.helpers.batch_genera... | [((795, 821), 'numpy.load', 'np.load', (['"""dataset/sho.npz"""'], {}), "('dataset/sho.npz')\n", (802, 821), True, 'import numpy as np\n'), ((832, 855), 'numpy.asarray', 'np.asarray', (["data['x_d']"], {}), "(data['x_d'])\n", (842, 855), True, 'import numpy as np\n'), ((866, 889), 'numpy.asarray', 'np.asarray', (["data... |
from unittest import TestCase
from urllib.parse import urljoin
import pytest
from osbot_browser.javascript.Javascript_Parser import Javascript_Parser
from osbot_utils.testing.Duration import Duration
from osbot_utils.decorators.methods.cache_on_tmp import cache_on_tmp
from osbot_utils.utils.Http import GET
from os... | [
"osbot_utils.utils.Http.GET",
"osbot_browser.py_query.Py_Query.py_query_from_GET",
"pytest.mark.skip",
"osbot_utils.testing.Duration.Duration",
"urllib.parse.urljoin",
"osbot_utils.decorators.methods.cache_on_tmp.cache_on_tmp",
"osbot_browser.javascript.Javascript_Parser.Javascript_Parser"
] | [((756, 770), 'osbot_utils.decorators.methods.cache_on_tmp.cache_on_tmp', 'cache_on_tmp', ([], {}), '()\n', (768, 770), False, 'from osbot_utils.decorators.methods.cache_on_tmp import cache_on_tmp\n'), ((2791, 2877), 'pytest.mark.skip', 'pytest.mark.skip', (['"""todo: write test for this function (that uses larger js f... |
from setuptools import setup, find_packages
from os import path
import re
def read_file(file_name: str) -> str:
here = path.abspath(path.dirname(__file__))
with open(path.join(here, file_name), encoding="utf-8") as f:
return f.read()
long_description = read_file("README.md")
version = re.sub("\s+", ... | [
"os.path.dirname",
"setuptools.find_packages",
"os.path.join"
] | [((138, 160), 'os.path.dirname', 'path.dirname', (['__file__'], {}), '(__file__)\n', (150, 160), False, 'from os import path\n'), ((707, 750), 'setuptools.find_packages', 'find_packages', ([], {'exclude': "['tests', 'tests.*']"}), "(exclude=['tests', 'tests.*'])\n", (720, 750), False, 'from setuptools import setup, fin... |
from dotenv import load_dotenv
import os
import tweepy
load_dotenv()
APIkey = os.getenv('APIkey')
APIsecretkey = os.getenv('APIsecretkey')
AccessToken = os.getenv("AccessToken")
AccessTokenSecret = os.getenv("AccessTokenSecret")
auth = tweepy.OAuthHandler(APIkey, APIsecretkey)
auth.set_access_token(AccessToken, Acces... | [
"tweepy.API",
"tweepy.OAuthHandler",
"os.getenv",
"dotenv.load_dotenv"
] | [((56, 69), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (67, 69), False, 'from dotenv import load_dotenv\n'), ((79, 98), 'os.getenv', 'os.getenv', (['"""APIkey"""'], {}), "('APIkey')\n", (88, 98), False, 'import os\n'), ((114, 139), 'os.getenv', 'os.getenv', (['"""APIsecretkey"""'], {}), "('APIsecretkey')\n"... |
""" make_prefixsums.py
For generating prefix sums dataset for the
DeepThinking project.
<NAME> and <NAME>
July 2021
"""
import collections as col
import torch
def binary(x, bits):
mask = 2**torch.arange(bits)
return x.unsqueeze(-1).bitwise_and(mask).ne(0).long()
def get_target(inputs):
... | [
"torch.cumsum",
"torch.randperm",
"torch.rand",
"collections.defaultdict",
"torch.save",
"torch.zeros",
"torch.arange"
] | [((330, 353), 'torch.cumsum', 'torch.cumsum', (['inputs', '(0)'], {}), '(inputs, 0)\n', (342, 353), False, 'import torch\n'), ((214, 232), 'torch.arange', 'torch.arange', (['bits'], {}), '(bits)\n', (226, 232), False, 'import torch\n'), ((599, 625), 'torch.zeros', 'torch.zeros', (['(10000)', 'digits'], {}), '(10000, di... |
import unittest
import mongomock
from dasbot.db.stats_repo import StatsRepo
class TestStatsRepo(unittest.TestCase):
def setUp(self):
scores_col = mongomock.MongoClient().db.collection
stats_col = mongomock.MongoClient().db.collection
self.stats_repo = StatsRepo(scores_col, stats_col)
... | [
"unittest.main",
"mongomock.MongoClient",
"dasbot.db.stats_repo.StatsRepo"
] | [((546, 561), 'unittest.main', 'unittest.main', ([], {}), '()\n', (559, 561), False, 'import unittest\n'), ((284, 316), 'dasbot.db.stats_repo.StatsRepo', 'StatsRepo', (['scores_col', 'stats_col'], {}), '(scores_col, stats_col)\n', (293, 316), False, 'from dasbot.db.stats_repo import StatsRepo\n'), ((162, 185), 'mongomo... |
# FinSim
# Copyright 2018 <NAME>. All Rights Reserved.
# NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, ... | [
"requests.post",
"flask_restful.marshal_with",
"flask_jwt_extended.get_jwt_identity",
"finsim_trans.models.TransactionModel.find_by_id",
"finsim_trans.models.UserModel.find_by_username",
"flask_restful.reqparse.RequestParser",
"flask_jwt_extended.create_access_token",
"finsim_trans.models.AccountModel... | [((2149, 2173), 'flask_restful.reqparse.RequestParser', 'reqparse.RequestParser', ([], {}), '()\n', (2171, 2173), False, 'from flask_restful import Resource, reqparse, marshal_with, fields\n'), ((2492, 2516), 'flask_restful.reqparse.RequestParser', 'reqparse.RequestParser', ([], {}), '()\n', (2514, 2516), False, 'from ... |
"""Test `with` tag parsing and rendering."""
# pylint: disable=missing-class-docstring
from dataclasses import dataclass
from dataclasses import field
from typing import Dict
from unittest import TestCase
from liquid import Environment
from liquid_extra.tags import WithTag
@dataclass
class Case:
"""Table dri... | [
"liquid.Environment",
"dataclasses.field"
] | [((429, 456), 'dataclasses.field', 'field', ([], {'default_factory': 'dict'}), '(default_factory=dict)\n', (434, 456), False, 'from dataclasses import field\n'), ((1640, 1653), 'liquid.Environment', 'Environment', ([], {}), '()\n', (1651, 1653), False, 'from liquid import Environment\n')] |
from mpkg.common import Soft
from mpkg.load import Load
from mpkg.utils import Search
class Package(Soft):
ID = 'qbittorrent'
def _prepare(self):
data = self.data
data.args='/S'
parser = Load('http/common-zpcc.py', sync=False)[0][0].sourceforge
url = 'https://sourceforge.net/p... | [
"mpkg.load.Load"
] | [((222, 261), 'mpkg.load.Load', 'Load', (['"""http/common-zpcc.py"""'], {'sync': '(False)'}), "('http/common-zpcc.py', sync=False)\n", (226, 261), False, 'from mpkg.load import Load\n')] |
import sys
def index_equals_value(arr):
l, h = 0, len(arr) - 1
while l <= h:
m = (l + h) // 2
if arr[m] < m:
l = m + 1
elif m < arr[m]:
h = m - 1
elif l != h:
h = m
else:
return m
# Case if not found
return -1
i... | [
"sys.exit"
] | [((527, 538), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (535, 538), False, 'import sys\n')] |
import torch
import torch.utils.data
from torch import nn
from torch.nn import functional as F
from rlkit.pythonplusplus import identity
from rlkit.torch import pytorch_util as ptu
import numpy as np
from rlkit.torch.conv_networks import CNN, DCNN
from rlkit.torch.vae.vae_base import GaussianLatentVAE
imsize48_default... | [
"torch.ones_like",
"torch.nn.functional.mse_loss",
"numpy.ones",
"torch.nn.LSTM",
"numpy.log",
"torch.nn.functional.binary_cross_entropy",
"numpy.zeros",
"torch.nn.Linear",
"rlkit.torch.pytorch_util.ones_like",
"torch.clamp",
"rlkit.torch.pytorch_util.zeros"
] | [((1868, 1902), 'numpy.zeros', 'np.zeros', (['self.representation_size'], {}), '(self.representation_size)\n', (1876, 1902), True, 'import numpy as np\n'), ((1928, 1961), 'numpy.ones', 'np.ones', (['self.representation_size'], {}), '(self.representation_size)\n', (1935, 1961), True, 'import numpy as np\n'), ((2993, 303... |
from tkinter import Tk
from src.homework.widget.main_frame import MainFrame
class ClockApp(Tk):
def __init__(self, *args, **kwargs):
Tk.__init__(self, *args, **kwargs)
frame = MainFrame(self)
frame.pack()
if __name__ == '__main__':
app = ClockApp()
app.mainloop()
| [
"tkinter.Tk.__init__",
"src.homework.widget.main_frame.MainFrame"
] | [((146, 180), 'tkinter.Tk.__init__', 'Tk.__init__', (['self', '*args'], {}), '(self, *args, **kwargs)\n', (157, 180), False, 'from tkinter import Tk\n'), ((198, 213), 'src.homework.widget.main_frame.MainFrame', 'MainFrame', (['self'], {}), '(self)\n', (207, 213), False, 'from src.homework.widget.main_frame import MainF... |
import pandas as pd
from data_science_pipeline_code.feature_engineering_functions import *
from data_science_layer.pipeline.basic_regressor_pipeline import BasicRegressorPipeline
from data_science_layer.preprocessing.default_scaler import DefaultScaler
import pickle, os
model_params = [dict(), dict(), dict(), dict()]
i... | [
"plotly.express.scatter",
"pickle.dump",
"pandas.read_csv",
"data_science_layer.preprocessing.default_scaler.DefaultScaler",
"os.path.dirname",
"data_science_layer.pipeline.basic_regressor_pipeline.BasicRegressorPipeline",
"pandas.concat",
"pandas.to_datetime"
] | [((387, 412), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (402, 412), False, 'import pickle, os\n'), ((618, 651), 'pandas.to_datetime', 'pd.to_datetime', (["dataset['dteday']"], {}), "(dataset['dteday'])\n", (632, 651), True, 'import pandas as pd\n'), ((950, 978), 'pandas.to_datetime', 'pd... |
# Generated by Django 3.0.2 on 2020-01-16 16:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('alacode', '0002_auto_20200116_1512'),
]
operations = [
migrations.AlterField(
model_name='code',
name='q10',
... | [
"django.db.models.CharField",
"django.db.models.IntegerField"
] | [((331, 474), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'choices': "[(0, 'No'), (1, 'Yes')]", 'default': '(0)', 'help_text': '"""Does the tweet express feelings of anger?"""', 'verbose_name': '"""q10"""'}), "(choices=[(0, 'No'), (1, 'Yes')], default=0, help_text=\n 'Does the tweet express feeling... |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.cluster import KMeans
data = open( "cols.csv", "r" )
xs = [ ]
ys = [ ]
zs = [ ]
for l in data.readlines( ):
cs = l.split( ',' )
cs = list( map( lambda c: int( c ), cs ) )
xs.append( cs[ 0 ] )
ys.a... | [
"sklearn.cluster.KMeans",
"matplotlib.pyplot.figure",
"mpl_toolkits.mplot3d.Axes3D",
"matplotlib.pyplot.show"
] | [((384, 413), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {'figsize': '(1, 2)'}), '(1, figsize=(1, 2))\n', (394, 413), True, 'import matplotlib.pyplot as plt\n'), ((425, 436), 'mpl_toolkits.mplot3d.Axes3D', 'Axes3D', (['fig'], {}), '(fig)\n', (431, 436), False, 'from mpl_toolkits.mplot3d import Axes3D\n'), ((49... |
"""
game.py
Game class which contains the player, target, and all the walls.
"""
from math import cos, sin
import matplotlib.collections as mc
import pylab as plt
from numpy import asarray, pi
from config import Config
from environment.robot import Robot
from utils.dictionary import *
from utils.myutils import load_... | [
"pylab.ylim",
"environment.robot.Robot",
"pylab.arrow",
"utils.myutils.load_pickle",
"config.Config",
"utils.vec2d.Vec2d",
"numpy.asarray",
"pylab.plot",
"matplotlib.collections.LineCollection",
"math.cos",
"pylab.xlim",
"pylab.subplots",
"math.sin",
"utils.myutils.store_pickle"
] | [((7103, 7119), 'environment.robot.Robot', 'Robot', ([], {'game': 'self'}), '(game=self)\n', (7108, 7119), False, 'from environment.robot import Robot\n'), ((8882, 8935), 'utils.myutils.store_pickle', 'store_pickle', (['persist_dict', 'f"""{self.save_path}{self}"""'], {}), "(persist_dict, f'{self.save_path}{self}')\n",... |
import numpy as np
import torch as th
import torch.nn as nn
from rls.nn.mlps import MLP
from rls.nn.represent_nets import RepresentationNetwork
class QattenMixer(nn.Module):
def __init__(self,
n_agents: int,
state_spec,
rep_net_params,
agent_o... | [
"numpy.sqrt",
"torch.nn.ModuleList",
"torch.nn.Linear",
"rls.nn.mlps.MLP",
"torch.no_grad",
"torch.cat",
"rls.nn.represent_nets.RepresentationNetwork"
] | [((714, 787), 'rls.nn.represent_nets.RepresentationNetwork', 'RepresentationNetwork', ([], {'obs_spec': 'state_spec', 'rep_net_params': 'rep_net_params'}), '(obs_spec=state_spec, rep_net_params=rep_net_params)\n', (735, 787), False, 'from rls.nn.represent_nets import RepresentationNetwork\n'), ((1117, 1132), 'torch.nn.... |
import numpy as np
import os
import nibabel as nib
from skimage.transform import resize
from tqdm import tqdm
import matplotlib.pyplot as plt
import SimpleITK as sitk
spacing = {
0: [1.5, 0.8, 0.8],
1: [1.5, 0.8, 0.8],
2: [1.5, 0.8, 0.8],
3: [1.5, 0.8, 0.8],
4: [1.5, 0.8, 0.8],
5: [1.5, 0.8, 0.... | [
"os.path.exists",
"SimpleITK.GetImageFromArray",
"os.makedirs",
"numpy.round",
"os.path.join",
"SimpleITK.GetArrayFromImage",
"numpy.array",
"SimpleITK.ReadImage",
"os.walk"
] | [((445, 462), 'os.walk', 'os.walk', (['ori_path'], {}), '(ori_path)\n', (452, 462), False, 'import os\n'), ((3910, 3938), 'os.path.join', 'os.path.join', (['root1', 'i_dirs1'], {}), '(root1, i_dirs1)\n', (3922, 3938), False, 'import os\n'), ((736, 764), 'os.path.join', 'os.path.join', (['root1', 'i_dirs1'], {}), '(root... |
from PIL import Image
from PIL.ImageDraw import Draw
from svglib.svglib import svg2rlg as svg
from reportlab.graphics.renderPM import drawToFile as render
import os
from fcord import relative as rel
def start():
print("Converting images...")
pieces = ["images/chess-bishop.svg", "images/chess-king.svg", "images... | [
"PIL.Image.open",
"PIL.Image.new",
"fcord.relative",
"PIL.ImageDraw.Draw",
"svglib.svglib.svg2rlg",
"reportlab.graphics.renderPM.drawToFile",
"os.remove"
] | [((543, 549), 'svglib.svglib.svg2rlg', 'svg', (['p'], {}), '(p)\n', (546, 549), True, 'from svglib.svglib import svg2rlg as svg\n'), ((610, 643), 'reportlab.graphics.renderPM.drawToFile', 'render', (['s', 'f'], {'fmt': '"""PNG"""', 'bg': '(65280)'}), "(s, f, fmt='PNG', bg=65280)\n", (616, 643), True, 'from reportlab.gr... |
# Simple single neuron network to model a regression task
from __future__ import print_function
import numpy as np
#np.random.seed(1337) # for reproducibility
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.optimizers import SGD,... | [
"numpy.random.rand",
"datetime.datetime.utcnow",
"numpy.random.permutation",
"keras.models.Sequential",
"math.fabs",
"numpy.full",
"numpy.vectorize",
"keras.layers.core.Dense"
] | [((714, 726), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (724, 726), False, 'from keras.models import Sequential\n'), ((5385, 5409), 'numpy.vectorize', 'np.vectorize', (['Chromosome'], {}), '(Chromosome)\n', (5397, 5409), True, 'import numpy as np\n'), ((5455, 5507), 'numpy.full', 'np.full', (['(1, popu... |