code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
"""WizardKit: Hardware objects (mostly)"""
# vim: sts=2 sw=2 ts=2
import logging
import pathlib
import plistlib
import re
from collections import OrderedDict
from wk.cfg.hw import (
ATTRIBUTE_COLORS,
KEY_NVME,
KEY_SMART,
KNOWN_DISK_ATTRIBUTES,
KNOWN_DISK_MODELS,
KNOWN_RAM_VENDOR_IDS,
REGEX_POWER_ON_TIM... | [
"wk.std.string_to_bytes",
"wk.cfg.hw.KNOWN_RAM_VENDOR_IDS.get",
"wk.std.color_string",
"wk.cfg.hw.KNOWN_DISK_ATTRIBUTES.copy",
"wk.std.bytes_to_string",
"wk.cfg.hw.KNOWN_DISK_MODELS.items",
"plistlib.loads",
"wk.exe.get_json_from_command",
"wk.std.sleep",
"pathlib.Path",
"collections.OrderedDict... | [((547, 574), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (564, 574), False, 'import logging\n'), ((753, 811), 're.compile', 're.compile', (['f"""{KIT_NAME_SHORT}_(LINUX|UFD)"""', 're.IGNORECASE'], {}), "(f'{KIT_NAME_SHORT}_(LINUX|UFD)', re.IGNORECASE)\n", (763, 811), False, 'import re... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import math
import networkx as nx
import logging
import timeit
from collections import deque
from visualSHARK.models import Commit
def tag_filter(tags, discard_qualifiers=True, discard_patch=False):
versions = []
# qualifiers are expected at the end o... | [
"visualSHARK.models.Commit.objects.get",
"timeit.default_timer",
"networkx.dag_longest_path",
"math.floor",
"networkx.shortest_path",
"networkx.has_path",
"re.sub",
"logging.getLogger"
] | [((653, 687), 'visualSHARK.models.Commit.objects.get', 'Commit.objects.get', ([], {'id': 't.commit_id'}), '(id=t.commit_id)\n', (671, 687), False, 'from visualSHARK.models import Commit\n'), ((1392, 1416), 're.sub', 're.sub', (['"""[a-z]"""', '""""""', 'tmp'], {}), "('[a-z]', '', tmp)\n", (1398, 1416), False, 'import r... |
# Copyright 2020 Open Climate Tech 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... | [
"csv.reader",
"firecam.lib.weather.normalizeWeather",
"os.path.isfile",
"os.path.join",
"shapely.geometry.Point",
"logging.error",
"json.loads",
"shapely.geometry.Polygon",
"logging.warning",
"firecam.lib.img_archive.getHeading",
"firecam.lib.weather.getWeatherData",
"firecam.lib.db_manager.Db... | [((1465, 1487), 'json.loads', 'json.loads', (['polygonStr'], {}), '(polygonStr)\n', (1475, 1487), False, 'import json\n'), ((1499, 1521), 'shapely.geometry.Polygon', 'Polygon', (['polygonCoords'], {}), '(polygonCoords)\n', (1506, 1521), False, 'from shapely.geometry import Polygon, Point\n'), ((1697, 1712), 'random.ran... |
from PIL import Image
from pathlib import Path
from glob import glob
from os.path import basename
from tqdm import tqdm
import os
class Compression:
def __init__(self, compress_level, optimize=True, log=True, resize=False, resize_params=(0, 0)):
"""
Init compression params
:param compress_... | [
"os.makedirs",
"os.path.basename",
"PIL.Image.open",
"pathlib.Path",
"glob.glob"
] | [((928, 944), 'PIL.Image.open', 'Image.open', (['path'], {}), '(path)\n', (938, 944), False, 'from PIL import Image\n'), ((1826, 1836), 'pathlib.Path', 'Path', (['path'], {}), '(path)\n', (1830, 1836), False, 'from pathlib import Path\n'), ((1311, 1332), 'os.makedirs', 'os.makedirs', (['save_dir'], {}), '(save_dir)\n',... |
"""Defines spiders related to schools that NFL players have attended."""
import scrapy
from nfldata.common.pfr import pfr_request, PRO_FOOTBALL_REFERENCE_DOMAIN
from nfldata.items.schools import School
class SchoolsSpider(scrapy.Spider):
"""The spider that crawls and stores information about schools that players
... | [
"nfldata.common.pfr.pfr_request",
"nfldata.items.schools.School.sql_create",
"nfldata.items.schools.School"
] | [((537, 564), 'nfldata.items.schools.School.sql_create', 'School.sql_create', (['database'], {}), '(database)\n', (554, 564), False, 'from nfldata.items.schools import School\n'), ((612, 634), 'nfldata.common.pfr.pfr_request', 'pfr_request', (['"""schools"""'], {}), "('schools')\n", (623, 634), False, 'from nfldata.com... |
"""
Created on 7/17/16 10:08 AM
@author: <NAME>, <NAME>
"""
from __future__ import division, print_function, absolute_import
import numpy as np
import psutil
import joblib
import time as tm
import h5py
import itertools
from numbers import Number
from multiprocessing import cpu_count
try:
from mpi4py import MPI
... | [
"numpy.floor",
"numpy.random.randint",
"numpy.mean",
"pyUSID.io.io_utils.recommend_cpu_cores",
"mpi4py.MPI.COMM_WORLD.barrier",
"numpy.unique",
"psutil.cpu_count",
"multiprocessing.cpu_count",
"mpi4py.MPI.Get_processor_name",
"mpi4py.MPI.COMM_WORLD.Get_size",
"pyUSID.io.io_utils.get_available_me... | [((4798, 4822), 'mpi4py.MPI.Get_processor_name', 'MPI.Get_processor_name', ([], {}), '()\n', (4820, 4822), False, 'from mpi4py import MPI\n'), ((5083, 5100), 'numpy.array', 'np.array', (['recvbuf'], {}), '(recvbuf)\n', (5091, 5100), True, 'import numpy as np\n'), ((5122, 5140), 'numpy.unique', 'np.unique', (['recvbuf']... |
import numpy as np
class TicTacToeGame:
def __init__(self, size):
self.m_SizeSize = size;
self.m_Grid = np.zeros((size, size), np.int8)
self.m_Grid.fill(-1)
self.m_CurentPlayer = 0
def Move(self, player, row, col):
if self.IsMoveAllowed(player, row, col) =... | [
"numpy.zeros"
] | [((134, 165), 'numpy.zeros', 'np.zeros', (['(size, size)', 'np.int8'], {}), '((size, size), np.int8)\n', (142, 165), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Measure',
fields=[
('id', models.AutoField(verb... | [
"django.db.models.CharField",
"django.db.models.ForeignKey",
"django.db.models.BooleanField",
"django.db.models.AutoField",
"django.db.models.IntegerField"
] | [((299, 392), 'django.db.models.AutoField', 'models.AutoField', ([], {'verbose_name': '"""ID"""', 'serialize': '(False)', 'auto_created': '(True)', 'primary_key': '(True)'}), "(verbose_name='ID', serialize=False, auto_created=True,\n primary_key=True)\n", (315, 392), False, 'from django.db import models, migrations\... |
"""Add role seed data for flask-security
Revision ID: 7b2d863b105
Revises: <PASSWORD>
Create Date: 2015-07-02 10:48:35.805882
"""
# revision identifiers, used by Alembic.
revision = '7b2d863b105'
down_revision = '<PASSWORD>'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto gener... | [
"sqlalchemy.sql.text",
"alembic.op.bulk_insert",
"alembic.op.get_bind",
"sqlalchemy.String",
"sqlalchemy.Integer"
] | [((600, 3914), 'alembic.op.bulk_insert', 'op.bulk_insert', (['role_table', "[{'id': 2, 'name': 'product_category_view', 'description':\n 'View product categories'}, {'id': 3, 'name': 'product_category_create',\n 'description': 'Create product category'}, {'id': 4, 'name':\n 'product_category_edit', 'descriptio... |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
import unittest
from unittest import TestCase
import pkgutil
import io
import numpy as np
import pandas as pd
from kats.consts import... | [
"unittest.main",
"pkgutil.get_data",
"io.BytesIO",
"pandas.DataFrame",
"numpy.sum",
"kats.models.harmonic_regression.HarmonicRegressionModel",
"os.getcwd",
"kats.models.harmonic_regression.HarmonicRegressionParams",
"pandas.Series",
"kats.models.harmonic_regression.HarmonicRegressionModel.fourier_... | [((606, 646), 'pkgutil.get_data', 'pkgutil.get_data', (['ROOT', '(path + file_name)'], {}), '(ROOT, path + file_name)\n', (622, 646), False, 'import pkgutil\n'), ((1861, 1876), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1874, 1876), False, 'import unittest\n'), ((670, 693), 'io.BytesIO', 'io.BytesIO', (['data... |
import argparse
import torch
import numpy as np
import os
import data
from networks import domain_generator, domain_classifier
from utils import util
def optimize(opt):
dataset_name = 'cifar10'
generator_name = 'stylegan2-cc' # class conditional stylegan
transform = data.get_transform(dataset_name, 'imv... | [
"numpy.save",
"argparse.ArgumentParser",
"data.get_dataset",
"os.makedirs",
"networks.domain_classifier.define_classifier",
"data.get_transform",
"os.path.isfile",
"networks.domain_generator.define_generator",
"torch.no_grad",
"os.path.join",
"utils.util.set_requires_grad"
] | [((283, 324), 'data.get_transform', 'data.get_transform', (['dataset_name', '"""imval"""'], {}), "(dataset_name, 'imval')\n", (301, 324), False, 'import data\n'), ((337, 422), 'data.get_dataset', 'data.get_dataset', (['dataset_name', 'opt.partition'], {'load_w': '(False)', 'transform': 'transform'}), '(dataset_name, op... |
################################################################################
# Module: plot.py
# Description: Plot functions
# License: Apache v2.0
# Author: <NAME>
# Web: https://github.com/pedroswits/anprx
################################################################################
import math
import adjustT... | [
"matplotlib.colors.Normalize",
"math.sqrt",
"osmnx.bbox_from_point",
"osmnx.plot_graph",
"matplotlib.pyplot.cm.ScalarMappable",
"adjustText.adjust_text",
"matplotlib.colorbar.ColorbarBase"
] | [((4844, 4902), 'osmnx.bbox_from_point', 'ox.bbox_from_point', ([], {'point': 'camera.point', 'distance': 'bbox_side'}), '(point=camera.point, distance=bbox_side)\n', (4862, 4902), True, 'import osmnx as ox\n'), ((5863, 6257), 'osmnx.plot_graph', 'ox.plot_graph', (['camera.network'], {'bbox': 'bbox', 'margin': 'margin'... |
#! ../env/bin/python
# -*- coding: utf-8 -*-
import sys
print("TestURLs sys.path: {0}".format(sys.path))
import unittest
from mathsonmars.models import db, User, Role
from mathsonmars import create_app
from mathsonmars.constants.modelconstants import RoleTypes, DefaultUserName
import logging
logging.basicConfig(level... | [
"unittest.main",
"logging.basicConfig",
"mathsonmars.models.db.session.remove",
"mathsonmars.models.db.drop_all",
"mathsonmars.models.db.session.flush",
"mathsonmars.models.db.session.add",
"mathsonmars.models.db.session.commit",
"mathsonmars.models.Role",
"mathsonmars.create_app",
"mathsonmars.mo... | [((295, 335), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG'}), '(level=logging.DEBUG)\n', (314, 335), False, 'import logging\n'), ((345, 372), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (362, 372), False, 'import logging\n'), ((2282, 2297), 'unittest.mai... |
from datetime import date
maior = 0
menor = 0
for c in range(1, 8):
ano = int(input('Digite o ano de nascimento: '))
if date.today().year - ano >= 18:
maior += 1
else:
menor += 1
print('Das sete pessoas digitadas {} são MAIORES DE IDADE.' .format(maior))
print('As outras {} pessoas são MENOR... | [
"datetime.date.today"
] | [((128, 140), 'datetime.date.today', 'date.today', ([], {}), '()\n', (138, 140), False, 'from datetime import date\n')] |
# -*- coding: utf-8 -*-
# Resource object code
#
# Created by: The Resource Compiler for PyQt5 (Qt v5.9.1)
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore
qt_resource_data = b"\
\x00\x00\xe5\x76\
\x47\
\x49\x46\x38\x39\x61\xb3\x00\xa2\x00\xd5\x22\x00\xf4\xf4\xf4\xf3\
\xf3\xf3\xc3\xc... | [
"PyQt5.QtCore.qUnregisterResourceData",
"PyQt5.QtCore.qVersion",
"PyQt5.QtCore.qRegisterResourceData"
] | [((408212, 408313), 'PyQt5.QtCore.qRegisterResourceData', 'QtCore.qRegisterResourceData', (['rcc_version', 'qt_resource_struct', 'qt_resource_name', 'qt_resource_data'], {}), '(rcc_version, qt_resource_struct,\n qt_resource_name, qt_resource_data)\n', (408240, 408313), False, 'from PyQt5 import QtCore\n'), ((408340,... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2008 <NAME>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
import doctest
import unittest
from couchbase_mapping import design
from couchbase_mapping.tests import testutil
... | [
"unittest.main",
"couchbase_mapping.design.ViewDefinition",
"unittest.TestSuite",
"doctest.DocTestSuite",
"unittest.makeSuite"
] | [((1498, 1518), 'unittest.TestSuite', 'unittest.TestSuite', ([], {}), '()\n', (1516, 1518), False, 'import unittest\n'), ((1671, 1705), 'unittest.main', 'unittest.main', ([], {'defaultTest': '"""suite"""'}), "(defaultTest='suite')\n", (1684, 1705), False, 'import unittest\n'), ((473, 572), 'couchbase_mapping.design.Vie... |
# -*- coding: utf-8 -*-
'''
@Author : Xu
@Software: PyCharm
@File : bert_bilstm_crf_entity_extractor.py
@Time : 2019-09-26 11:09
@Desc :
'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
... | [
"logging.getLogger"
] | [((885, 912), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (902, 912), False, 'import logging\n')] |
from classifiers import BaseRGCN
from dgl.nn.pytorch import RelGraphConv
from functools import partial
import torch
import torch.nn.functional as F
import torch.nn as nn
from dgl.nn import RelGraphConv
from layers import RelGraphConvHetero, EmbeddingLayer, RelGraphAttentionHetero,MiniBatchRelGraphEmbed
class Encoder... | [
"torch.nn.Dropout",
"torch.ones",
"functools.partial",
"torch.nn.ModuleList",
"layers.EmbeddingLayer",
"torch.nn.init.xavier_uniform_",
"layers.MiniBatchRelGraphEmbed",
"layers.RelGraphConvHetero",
"layers.RelGraphAttentionHetero",
"torch.nn.functional.softmax",
"torch.nn.Linear",
"torch.sigmo... | [((386, 414), 'torch.arange', 'torch.arange', (['self.num_nodes'], {}), '(self.num_nodes)\n', (398, 414), False, 'import torch\n'), ((553, 712), 'dgl.nn.RelGraphConv', 'RelGraphConv', (['self.inp_dim', 'self.h_dim', 'self.num_rels', '"""basis"""', 'self.num_bases'], {'activation': 'F.relu', 'self_loop': 'self.use_self_... |
#!/usr/bin/env python
#textMyself.py - Defines the textmyself() function that texts a message passed to it as a string
from twilio.rest import TwilioRestClient
# Read in account information
with open('/Users/RyanRobertson21/PycharmProjects/CoolProjects/twilioAccountInfo') as f:
info=f.read().splitlines()
# Prese... | [
"twilio.rest.TwilioRestClient"
] | [((494, 533), 'twilio.rest.TwilioRestClient', 'TwilioRestClient', (['accountSID', 'authToken'], {}), '(accountSID, authToken)\n', (510, 533), False, 'from twilio.rest import TwilioRestClient\n')] |
from random import randint
class Solution:
'''
TASK DESCRIPTION
Преобразуйте список целых чисел: оставьте только кратные пяти.
Примечание, ввод производится в синтаксисе списка
EXAMPLES:
Sample Input:
[4, 5, 7, 237895, 32, 432, 45, 0]
Sample Output:
5 237895 45 0
'''
... | [
"random.randint"
] | [((898, 916), 'random.randint', 'randint', (['(-500)', '(500)'], {}), '(-500, 500)\n', (905, 916), False, 'from random import randint\n'), ((932, 946), 'random.randint', 'randint', (['(5)', '(30)'], {}), '(5, 30)\n', (939, 946), False, 'from random import randint\n')] |
"""Base classes for paper rock scissors game
"""
# Author: <NAME> <<EMAIL>>
from abc import ABCMeta, abstractmethod
from enum import Enum, auto
import time
import warnings
class MoveChoice(Enum):
ROCK = auto()
PAPER = auto()
SCISSORS = auto()
class Outcome(Enum):
WIN = auto()
LOSE = auto()
... | [
"enum.auto",
"warnings.warn",
"time.sleep"
] | [((211, 217), 'enum.auto', 'auto', ([], {}), '()\n', (215, 217), False, 'from enum import Enum, auto\n'), ((230, 236), 'enum.auto', 'auto', ([], {}), '()\n', (234, 236), False, 'from enum import Enum, auto\n'), ((252, 258), 'enum.auto', 'auto', ([], {}), '()\n', (256, 258), False, 'from enum import Enum, auto\n'), ((29... |
import time
import sys
import quimb.tensor as qtn
import cotengra as ctg
import tqdm
from opt_einsum import contract, contract_expression, contract_path, helpers
from opt_einsum.paths import linear_to_ssa, ssa_to_linear
def load_circuit(
n=53,
depth=10,
seed=0 ,
elided=0,
sequence='ABCDCDAB',
... | [
"quimb.tensor.MPS_rand_computational_state",
"quimb.tensor.Circuit.from_qasm_file",
"time.time",
"quimb.tensor.MPS_computational_state"
] | [((748, 789), 'quimb.tensor.MPS_computational_state', 'qtn.MPS_computational_state', (["('0' * circ.N)"], {}), "('0' * circ.N)\n", (775, 789), True, 'import quimb.tensor as qtn\n'), ((1511, 1522), 'time.time', 'time.time', ([], {}), '()\n', (1520, 1522), False, 'import time\n'), ((1569, 1580), 'time.time', 'time.time',... |
'''Provide fundamental geometry calculations used by the scheduling.
'''
import math
import numpy as np
import brahe.data_models as bdm
from brahe.utils import fcross
from brahe.constants import RAD2DEG
from brahe.coordinates import sECEFtoENZ, sENZtoAZEL, sECEFtoGEOD, sGEODtoECEF
from brahe.relative_coordinates impo... | [
"brahe.coordinates.sENZtoAZEL",
"brahe.relative_coordinates.rCARTtoRTN",
"numpy.asarray",
"brahe.coordinates.sECEFtoGEOD",
"brahe.coordinates.sGEODtoECEF",
"brahe.coordinates.sECEFtoENZ",
"brahe.utils.fcross",
"numpy.array",
"numpy.linalg.norm",
"numpy.sign",
"numpy.dot"
] | [((923, 943), 'numpy.asarray', 'np.asarray', (['sat_ecef'], {}), '(sat_ecef)\n', (933, 943), True, 'import numpy as np\n'), ((959, 979), 'numpy.asarray', 'np.asarray', (['loc_ecef'], {}), '(loc_ecef)\n', (969, 979), True, 'import numpy as np\n'), ((1038, 1101), 'brahe.coordinates.sECEFtoENZ', 'sECEFtoENZ', (['loc_ecef[... |
# -*- coding: utf-8 -*-
import importlib
def gen_task_name_via_func(func):
"""生成函数对象对应的 task name"""
return '{name}'.format(name=func.__name__)
def import_object_from_path(path, default_obj_name='app'):
"""从定义的字符串信息中导入对象
:param path: ``task.app``
"""
module_name, obj_name = path.rsplit('.',... | [
"importlib.import_module"
] | [((395, 431), 'importlib.import_module', 'importlib.import_module', (['module_name'], {}), '(module_name)\n', (418, 431), False, 'import importlib\n')] |
import unittest
import graph
class BreadthFirstSearchTest(unittest.TestCase):
__runSlowTests = False
def testTinyGraph(self):
g = graph.Graph.from_file('tinyG.txt')
bfs = graph.BreadthFirstSearch(g, 0)
self.assertEqual(7, bfs.count())
self.assertFalse(bfs.connected(7))
... | [
"unittest.main",
"graph.Graph.from_file",
"graph.BreadthFirstSearch"
] | [((2290, 2305), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2303, 2305), False, 'import unittest\n'), ((150, 184), 'graph.Graph.from_file', 'graph.Graph.from_file', (['"""tinyG.txt"""'], {}), "('tinyG.txt')\n", (171, 184), False, 'import graph\n'), ((199, 229), 'graph.BreadthFirstSearch', 'graph.BreadthFirstSe... |
import logging
import sys
import yaml
def load_config(filename):
with open(filename, 'r') as stream:
try:
return yaml.safe_load(stream)
except yaml.YAMLError as exc:
print('Invalid configuration')
print(exc)
sys.exit(1)
class LoadAndPreprocessConfig... | [
"logging.warning",
"yaml.safe_load",
"sys.exit"
] | [((139, 161), 'yaml.safe_load', 'yaml.safe_load', (['stream'], {}), '(stream)\n', (153, 161), False, 'import yaml\n'), ((278, 289), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (286, 289), False, 'import sys\n'), ((3726, 3775), 'logging.warning', 'logging.warning', (['f"""Missing config element: {err}"""'], {}), "(f... |
from collections import Counter
from itertools import product
with open('02.txt') as fd:
inp = [l.strip() for l in fd.readlines()]
twos = 0
thre = 0
for row in inp:
c = Counter(row)
if 2 in c.values():
twos += 1
if 3 in c.values():
thre += 1
print(twos*thre)
def diff(sa,sb):
c = ... | [
"collections.Counter",
"itertools.product"
] | [((402, 419), 'itertools.product', 'product', (['inp', 'inp'], {}), '(inp, inp)\n', (409, 419), False, 'from itertools import product\n'), ((184, 196), 'collections.Counter', 'Counter', (['row'], {}), '(row)\n', (191, 196), False, 'from collections import Counter\n')] |
import numpy as np
class LidarTools(object):
'''
Collection of helpers for processing LiDAR point cloud.
'''
def get_bev(self, points, resolution=0.1, pixel_values=None, generate_img=None):
'''
Returns bird's eye view of a LiDAR point cloud for a given resolution.
Optional pixe... | [
"numpy.full_like",
"numpy.arctan2",
"numpy.logical_and",
"numpy.floor",
"numpy.zeros",
"numpy.argwhere",
"numpy.sqrt"
] | [((2055, 2076), 'numpy.full_like', 'np.full_like', (['x', '(True)'], {}), '(x, True)\n', (2067, 2076), True, 'import numpy as np\n'), ((1428, 1477), 'numpy.zeros', 'np.zeros', (['[img_height, img_width]'], {'dtype': 'np.uint8'}), '([img_height, img_width], dtype=np.uint8)\n', (1436, 1477), True, 'import numpy as np\n')... |
"""
This example requires uvicorn and fastapi.
pip install fastapi uvicorn
Run:
uvicorn examples.fast_api:app
then open http://localhost:8000
Access http://localhost:8000 to list all users.
Access http://localhost:8000/create to create a new user.
"""
import os
import sqlalchemy as sa
import typing as t
from fa... | [
"aerie.Aerie",
"os.environ.get",
"fastapi.Depends",
"sqlalchemy.Column",
"fastapi.FastAPI"
] | [((408, 470), 'os.environ.get', 'os.environ.get', (['"""DATABASE_URL"""', '"""sqlite+aiosqlite:///:memory:"""'], {}), "('DATABASE_URL', 'sqlite+aiosqlite:///:memory:')\n", (422, 470), False, 'import os\n'), ((477, 496), 'aerie.Aerie', 'Aerie', (['DATABASE_URL'], {}), '(DATABASE_URL)\n', (482, 496), False, 'from aerie i... |
import argparse
import os
import os.path as osp
import pickle
import shutil
import tempfile
import mmcv
import torch
import torch.distributed as dist
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import get_dist_info, load_checkpoint
from mmdet.apis import init_dist... | [
"mmcv.runner.get_dist_info",
"argparse.ArgumentParser",
"mmcv.mkdir_or_exist",
"torch.full",
"torch.distributed.all_gather",
"mmcv.Config.fromfile",
"shutil.rmtree",
"torch.no_grad",
"os.path.join",
"mmcv.imread",
"numpy.full",
"mmdet.models.build_detector",
"cv2.imwrite",
"os.path.exists"... | [((781, 803), 'mmcv.image.imread', 'mmcv.image.imread', (['img'], {}), '(img)\n', (798, 803), False, 'import mmcv\n'), ((4896, 4911), 'mmcv.runner.get_dist_info', 'get_dist_info', ([], {}), '()\n', (4909, 4911), False, 'from mmcv.runner import get_dist_info, load_checkpoint\n'), ((5631, 5646), 'mmcv.runner.get_dist_inf... |
import numpy as np
import gym
import torch
import random
from argparse import ArgumentParser
import os
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')
from scipy.ndimage.filters import gaussian_filter1d
class Stats():
def __init__(self, num_episodes=20000, num_states = 6, log_dir... | [
"scipy.ndimage.filters.gaussian_filter1d",
"argparse.ArgumentParser",
"random.sample",
"matplotlib.pyplot.style.use",
"numpy.mean",
"numpy.exp",
"os.path.join",
"collections.deque",
"pandas.DataFrame",
"numpy.std",
"matplotlib.pyplot.cla",
"numpy.linspace",
"pandas.Series",
"matplotlib.pyp... | [((163, 186), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (176, 186), True, 'import matplotlib.pyplot as plt\n'), ((1243, 1284), 'numpy.mean', 'np.mean', (['overall_stats_q_learning'], {'axis': '(0)'}), '(overall_stats_q_learning, axis=0)\n', (1250, 1284), True, 'import numpy... |
import os
import pandas as pd
os.system(f"{sys.executable} -m pip install -U pytd==0.8.0 td-client")
import pytd
from tdclient.errors import NotFoundError
def database_exists(database, client):
try:
client.api_client.database(database)
return True
except NotFoundError:
pass
re... | [
"pytd.Client",
"pandas.read_csv",
"os.system"
] | [((32, 102), 'os.system', 'os.system', (['f"""{sys.executable} -m pip install -U pytd==0.8.0 td-client"""'], {}), "(f'{sys.executable} -m pip install -U pytd==0.8.0 td-client')\n", (41, 102), False, 'import os\n'), ((933, 979), 'pytd.Client', 'pytd.Client', ([], {'apikey': 'apikey', 'endpoint': 'apiserver'}), '(apikey=... |
# Generated by Django 3.2 on 2021-06-26 00:30
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('backend', '0004_alter_item_description'),
]
operations = [
migrations.AlterField(
model_name='item',
name='category',
... | [
"django.db.models.CharField"
] | [((338, 391), 'django.db.models.CharField', 'models.CharField', ([], {'default': '"""Dinosaurs"""', 'max_length': '(200)'}), "(default='Dinosaurs', max_length=200)\n", (354, 391), False, 'from django.db import migrations, models\n')] |
# coding=utf-8
"""
Data and actions for user
"""
from typing import List
import pypi_xmlrpc
from pypi_librarian.class_package import Package
class User(object):
"""
Properties and methods
"""
def __init__(self, name: str) -> None:
"""
Initialize values
:param name:
"... | [
"pypi_xmlrpc.user_packages"
] | [((508, 544), 'pypi_xmlrpc.user_packages', 'pypi_xmlrpc.user_packages', (['self.name'], {}), '(self.name)\n', (533, 544), False, 'import pypi_xmlrpc\n')] |
from app.game_state.game_state_models import (
FibbingItQuestion,
FibbingItState,
GameState,
NextQuestion,
UpdateQuestionRoundState,
)
from app.player.player_models import Player
from app.room.games.abstract_game import AbstractGame
from app.room.games.exceptions import UnexpectedGameStateType
from ... | [
"app.room.games.exceptions.UnexpectedGameStateType",
"app.room.room_events_models.GotQuestionFibbingIt"
] | [((625, 715), 'app.room.games.exceptions.UnexpectedGameStateType', 'UnexpectedGameStateType', (['"""expected `game_state.state` to be of type `FibbingItState`"""'], {}), "(\n 'expected `game_state.state` to be of type `FibbingItState`')\n", (648, 715), False, 'from app.room.games.exceptions import UnexpectedGameStat... |
import os
# os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import math
import argparse
import math
import h5py
import numpy as np
import tensorflow as tf
# os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
# tf.logging.set_verbosity(tf.logging.ERROR)
import socket
import sys
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
RO... | [
"os.mkdir",
"numpy.sum",
"argparse.ArgumentParser",
"numpy.argmax",
"tensorflow.maximum",
"tensorflow.ConfigProto",
"tensorflow.Variable",
"sys.stdout.flush",
"os.path.join",
"provider.loadDataFile",
"sys.path.append",
"os.path.abspath",
"os.path.dirname",
"tensorflow.to_int64",
"os.path... | [((329, 354), 'os.path.dirname', 'os.path.dirname', (['BASE_DIR'], {}), '(BASE_DIR)\n', (344, 354), False, 'import os\n'), ((355, 380), 'sys.path.append', 'sys.path.append', (['BASE_DIR'], {}), '(BASE_DIR)\n', (370, 380), False, 'import sys\n'), ((381, 406), 'sys.path.append', 'sys.path.append', (['ROOT_DIR'], {}), '(R... |
from datetime import datetime
from pprint import pprint
import extensible_provn.view.mutable_prov
import annotations as prov
HIDE = prov.HIDE
SPECIFIC = prov.SPECIFIC
prov.reset_prov("../generated/mutable_prov/")
prov.STATS_VIEW = 1
def time():
return datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%f")
def cond(en... | [
"annotations.entity",
"annotations.accessed",
"annotations.desc",
"annotations.calc_label",
"annotations.activity",
"annotations.reset_prov",
"annotations.value",
"annotations.finish",
"datetime.datetime.now",
"annotations.derivedByInsertion",
"annotations.defined"
] | [((170, 215), 'annotations.reset_prov', 'prov.reset_prov', (['"""../generated/mutable_prov/"""'], {}), "('../generated/mutable_prov/')\n", (185, 215), True, 'import annotations as prov\n'), ((11085, 11114), 'annotations.finish', 'prov.finish', ([], {'show_count': '(False)'}), '(show_count=False)\n', (11096, 11114), Tru... |
# -*- coding: utf-8 -*-
"""
201901, Dr. <NAME>, Beijing & Xinglong, NAOC
202101-? Dr. <NAME> & Dr./Prof. <NAME>
Light_Curve_Pipeline
v3 (2021A) Upgrade from former version, remove unused code
"""
import numpy as np
import matplotlib
#matplotlib.use('Agg')
from matplotlib import pyplot as plt
from .JZ_... | [
"numpy.isscalar",
"matplotlib.pyplot.close",
"matplotlib.pyplot.figure",
"numpy.where"
] | [((655, 697), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(nx / 50.0, ny / 50.0)'}), '(figsize=(nx / 50.0, ny / 50.0))\n', (665, 697), True, 'from matplotlib import pyplot as plt\n'), ((959, 978), 'numpy.where', 'np.where', (['(err < 0.1)'], {}), '(err < 0.1)\n', (967, 978), True, 'import numpy as np\n'... |
from collections import defaultdict
class Leaf: # pylint: disable=too-few-public-methods,missing-class-docstring
def __init__(self):
self.payloads = []
self.children = defaultdict(Leaf)
class Trie:
"""
`Trie <https://en.wikipedia.org/wiki/Trie>`_ is a data structure for effective pre... | [
"collections.defaultdict"
] | [((194, 211), 'collections.defaultdict', 'defaultdict', (['Leaf'], {}), '(Leaf)\n', (205, 211), False, 'from collections import defaultdict\n')] |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-09-15 15:42
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import vmprofile.models
import uuid
def forward_func(apps, schema_editor):
RuntimeData = apps.... | [
"django.db.migrations.RunPython",
"django.db.models.OneToOneField",
"django.db.models.FileField",
"django.db.migrations.swappable_dependency",
"django.db.models.TextField",
"django.db.migrations.RenameField",
"django.db.migrations.RemoveField",
"django.db.models.CharField",
"django.db.models.Foreign... | [((1200, 1257), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (1231, 1257), False, 'from django.db import migrations, models\n'), ((2007, 2105), 'django.db.migrations.RenameField', 'migrations.RenameField', ([], {'mode... |
from Classes.Wrappers.PlayerDisplayData import PlayerDisplayData
class BattleLogPlayerEntry:
def encode(calling_instance, fields):
pass
def decode(calling_instance, fields):
fields["BattleLogEntry"] = {}
fields["BattleLogEntry"]["Unkown1"] = calling_instance.readVInt()
fields["... | [
"Classes.Wrappers.PlayerDisplayData.PlayerDisplayData.decode"
] | [((1258, 1308), 'Classes.Wrappers.PlayerDisplayData.PlayerDisplayData.decode', 'PlayerDisplayData.decode', (['calling_instance', 'fields'], {}), '(calling_instance, fields)\n', (1282, 1308), False, 'from Classes.Wrappers.PlayerDisplayData import PlayerDisplayData\n')] |
# -*- coding: utf-8 -*-
"""
Beeline.ru
"""
from html2text import convert
from . import by_subj, NBSP, BUTTONS
MARK_INBOX = 'В Ваш почтовый ящик '
MARK_CLOUD_GO = 'Прослушать сообщение можно в web-интерфейсе управления услугой'
def voice_mail(_subj, text):
"""
voice mail
"""
pos_start = text.index(MAR... | [
"html2text.convert"
] | [((816, 829), 'html2text.convert', 'convert', (['body'], {}), '(body)\n', (823, 829), False, 'from html2text import convert\n')] |
import bcrypt
from sqlalchemy import (
Column,
Index,
Integer,
Unicode,
Date,
)
from .meta import Base
class Entry(Base):
__tablename__ = 'entries'
id = Column(Integer, primary_key=True)
title = Column(Unicode)
body = Column(Unicode)
category = Column(Unicode)
tags = Colum... | [
"sqlalchemy.Column"
] | [((184, 217), 'sqlalchemy.Column', 'Column', (['Integer'], {'primary_key': '(True)'}), '(Integer, primary_key=True)\n', (190, 217), False, 'from sqlalchemy import Column, Index, Integer, Unicode, Date\n'), ((230, 245), 'sqlalchemy.Column', 'Column', (['Unicode'], {}), '(Unicode)\n', (236, 245), False, 'from sqlalchemy ... |
# Generated by Django 3.2.8 on 2021-11-20 23:06
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
("players", "0001_initial"),
]
operations = [
migrations.CreateModel(
name="M... | [
"django.db.models.OneToOneField",
"django.db.models.BigAutoField",
"django.db.models.CharField",
"django.db.models.BooleanField",
"django.db.models.DateTimeField"
] | [((413, 509), 'django.db.models.BigAutoField', 'models.BigAutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (432, 509), False, 'from django.db import migrations, m... |
import warnings
class AuthlibDeprecationWarning(DeprecationWarning):
pass
warnings.simplefilter('always', AuthlibDeprecationWarning)
def deprecate(message, version=None, link_uid=None, link_file=None):
if version:
message += '\nIt will be compatible before version {}.'.format(version)
if link_... | [
"warnings.simplefilter"
] | [((82, 140), 'warnings.simplefilter', 'warnings.simplefilter', (['"""always"""', 'AuthlibDeprecationWarning'], {}), "('always', AuthlibDeprecationWarning)\n", (103, 140), False, 'import warnings\n')] |
import boto.ec2
import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('aws_access_key_id')
parser.add_argument('aws_secret_access_key')
parser.add_argument('region')
config = parser.parse_args()
conn = boto.ec2.connect_to_region(config.region,
aws_access_... | [
"argparse.ArgumentParser"
] | [((54, 79), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (77, 79), False, 'import argparse\n')] |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2020 by <NAME> <<EMAIL>>
# All rights reserved.
# This file is part of vagrancyCtrl (https://github.com/seeraven/vagrancyCtrl)
# and is released under the "BSD 3-Clause License". Please see the LICENSE file
# that is included as part of this package.
#
"""Command line interface... | [
"argcomplete.autocomplete",
"sys.exit"
] | [((1524, 1556), 'argcomplete.autocomplete', 'argcomplete.autocomplete', (['parser'], {}), '(parser)\n', (1548, 1556), False, 'import argcomplete\n'), ((1698, 1709), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (1706, 1709), False, 'import sys\n')] |
# *-* coding: utf-8 *-*
"""Context manager for easily using a pymemcache mutex.
The `acquire_lock` context manager makes it easy to use :mod:`pymemcache` (which
uses memcached) to create a mutex for a certain portion of code. Of course,
this requires the :mod:`pymemcache` library to be installed, which in turn
require... | [
"pymemcache.client.base.Client",
"json.loads",
"json.dumps",
"time.sleep"
] | [((1213, 1306), 'pymemcache.client.base.Client', 'Client', (["('localhost', 11211)"], {'serializer': 'json_serializer', 'deserializer': 'json_deserializer'}), "(('localhost', 11211), serializer=json_serializer, deserializer=\n json_deserializer)\n", (1219, 1306), False, 'from pymemcache.client.base import Client\n')... |
'''
#*************************************************************************
Useless App:
#*************************************************************************
Description: - useless but hopefully beautiful;
- app that changes its color and themes;
... | [
"sys.path.append",
"maya.cmds.iconTextButton",
"maya.cmds.deleteUI",
"maya.cmds.rowLayout",
"maya.cmds.text",
"maya.cmds.intSliderGrp",
"maya.cmds.separator",
"maya.cmds.window",
"maya.cmds.formLayout",
"maya.cmds.columnLayout",
"maya.cmds.showWindow",
"maya.cmds.setParent"
] | [((988, 1013), 'sys.path.append', 'sys.path.append', (['USERPATH'], {}), '(USERPATH)\n', (1003, 1013), False, 'import sys\n'), ((1019, 1046), 'sys.path.append', 'sys.path.append', (['PATH_ICONS'], {}), '(PATH_ICONS)\n', (1034, 1046), False, 'import sys\n'), ((1297, 1331), 'maya.cmds.window', 'cmds.window', (['ui_title'... |
import torch
import torch.nn as nn
class OurModule(nn.Module):
def __init__(self, num_inputs, num_classes, dropout_prob=0.3):
super().__init__()
self.pipe = nn.Sequential(nn.Linear(num_inputs, 5),
nn.ReLU(),
nn.Linear(5, 20),
... | [
"torch.nn.Dropout",
"torch.nn.ReLU",
"torch.FloatTensor",
"torch.nn.Softmax",
"torch.nn.Linear"
] | [((680, 707), 'torch.FloatTensor', 'torch.FloatTensor', (['[[2, 3]]'], {}), '([[2, 3]])\n', (697, 707), False, 'import torch\n'), ((194, 218), 'torch.nn.Linear', 'nn.Linear', (['num_inputs', '(5)'], {}), '(num_inputs, 5)\n', (203, 218), True, 'import torch.nn as nn\n'), ((254, 263), 'torch.nn.ReLU', 'nn.ReLU', ([], {})... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 15 15:16:06 2018
@author: Arpit
"""
import numpy as np
import matplotlib.pyplot as plt
import threading
from settings import charts_folder
class GraphPlot:
lock = threading.Lock()
def __init__(self, name, xCnt=1, yCnt=1, labels=None):
... | [
"matplotlib.pyplot.plot",
"numpy.empty",
"matplotlib.pyplot.close",
"matplotlib.pyplot.legend",
"threading.Lock",
"matplotlib.pyplot.figure"
] | [((239, 255), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (253, 255), False, 'import threading\n'), ((471, 502), 'numpy.empty', 'np.empty', (['(yCnt,)'], {'dtype': 'object'}), '((yCnt,), dtype=object)\n', (479, 502), True, 'import numpy as np\n'), ((781, 793), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}... |
"""
Test for launch config's personality validation.
"""
import base64
from test_repo.autoscale.fixtures import AutoscaleFixture
class LaunchConfigPersonalityTest(AutoscaleFixture):
"""
Verify launch config.
"""
def setUp(self):
"""
Create a scaling group.
"""
super(... | [
"base64.b64encode"
] | [((2455, 2480), 'base64.b64encode', 'base64.b64encode', (['"""tests"""'], {}), "('tests')\n", (2471, 2480), False, 'import base64\n'), ((1618, 1643), 'base64.b64encode', 'base64.b64encode', (['"""tests"""'], {}), "('tests')\n", (1634, 1643), False, 'import base64\n'), ((2064, 2094), 'base64.b64encode', 'base64.b64encod... |
import os
import random
import numpy as np
from scipy.spatial.distance import cdist
import cv2
import time
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
# import torch.multiprocessing as mp
from torch.utils.data import DataLoader
from torch.optim import Adam, SGD
... | [
"package.loss.regularization._Regularization",
"numpy.stack",
"numpy.multiply",
"numpy.copy",
"torch.utils.data.DataLoader",
"torch.load",
"time.time",
"numpy.mean",
"package.loss.cmt_loss._CMT_loss",
"package.args.cmt_args.parse_config",
"torch.cuda.empty_cache",
"torch.nn.kneighbors",
"num... | [((1129, 1145), 'numpy.mean', 'np.mean', (['matches'], {}), '(matches)\n', (1136, 1145), True, 'import numpy as np\n'), ((1185, 1202), 'numpy.copy', 'np.copy', (['inputArr'], {}), '(inputArr)\n', (1192, 1202), True, 'import numpy as np\n'), ((1365, 1391), 'numpy.multiply', 'np.multiply', (['dup', 'inputArr'], {}), '(du... |
import pandas as pd
from utils import new_RF_model
# since processing of the symptoms data has several related elements, I deceided to wrap it into a class
# this makes it easier for someone reading the code that all these function address on the synptoms data and has nothing to do with the image data
class ProcessS... | [
"pandas.DataFrame",
"utils.new_RF_model.predict",
"utils.new_RF_model.predict_proba"
] | [((2813, 2839), 'pandas.DataFrame', 'pd.DataFrame', (['[user_input]'], {}), '([user_input])\n', (2825, 2839), True, 'import pandas as pd\n'), ((3143, 3185), 'utils.new_RF_model.predict_proba', 'new_RF_model.predict_proba', (['self.dataframe'], {}), '(self.dataframe)\n', (3169, 3185), False, 'from utils import new_RF_mo... |
import os
import sys
import glob
import tqdm
import pickle
import logging
from indra_world.corpus import Corpus
from indra_world.assembly.operations import *
from indra_world.sources.dart import process_reader_outputs
from indra.pipeline import AssemblyPipeline
logger = logging.getLogger('dec2020_compositional')
HERE ... | [
"os.path.abspath",
"tqdm.tqdm",
"os.path.basename",
"indra_world.sources.dart.process_reader_outputs",
"indra.pipeline.AssemblyPipeline.from_json_file",
"glob.glob",
"indra_world.corpus.Corpus",
"os.path.join",
"logging.getLogger"
] | [((272, 314), 'logging.getLogger', 'logging.getLogger', (['"""dec2020_compositional"""'], {}), "('dec2020_compositional')\n", (289, 314), False, 'import logging\n'), ((338, 363), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (353, 363), False, 'import os\n'), ((2034, 2083), 'indra_world.sour... |
import argparse
import torch
def get_args():
parser = argparse.ArgumentParser(
description='Goal-Oriented-Semantic-Exploration')
# General Arguments
parser.add_argument('--seed', type=int, default=1,
help='random seed (default: 1)')
parser.add_argument('--auto_gpu_conf... | [
"torch.cuda.get_device_properties",
"torch.cuda.is_available",
"argparse.ArgumentParser",
"torch.cuda.device_count"
] | [((60, 133), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Goal-Oriented-Semantic-Exploration"""'}), "(description='Goal-Oriented-Semantic-Exploration')\n", (83, 133), False, 'import argparse\n'), ((9196, 9221), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (92... |
#
# Control of the Forktools configuration and services
#
from flask import Flask, jsonify, abort, request, flash, g
from common.models import alerts as a
from web import app, db, utils
from . import worker as wk
def load_config(farmer, blockchain):
return utils.send_get(farmer, "/configs/tools/"+ blockchain, d... | [
"flask.flash",
"web.utils.send_get",
"web.utils.send_put"
] | [((265, 332), 'web.utils.send_get', 'utils.send_get', (['farmer', "('/configs/tools/' + blockchain)"], {'debug': '(False)'}), "(farmer, '/configs/tools/' + blockchain, debug=False)\n", (279, 332), False, 'from web import app, db, utils\n'), ((403, 478), 'web.utils.send_put', 'utils.send_put', (['farmer', "('/configs/to... |
'''
This module handles the covid API, covid data, key statistics calculations and
scheduling covid updates.
'''
import logging
import sched
import datetime
import time
from re import match
import requests
from uk_covid19 import Cov19API
import uk_covid19
covid_data = {}
national_covid_data = {}
sched... | [
"logging.debug",
"logging.warning",
"re.match",
"datetime.datetime.now",
"sched.scheduler",
"logging.info",
"datetime.timedelta",
"uk_covid19.Cov19API"
] | [((383, 421), 'sched.scheduler', 'sched.scheduler', (['time.time', 'time.sleep'], {}), '(time.time, time.sleep)\n', (398, 421), False, 'import sched\n'), ((2644, 2794), 'logging.info', 'logging.info', (['"""convert_covid_csv_data_to_list_dict called:\n Converting CSV file to list of dictionaries for further data pro... |
#!/usr/bin/env python
# coding: utf-8
# This software component is licensed by ST under BSD 3-Clause license,
# the "License"; You may not use this file except in compliance with the
# License. You may obtain a copy of the License at:
# https://opensource.org/licenses/BSD-3-Clause
... | [
"numpy.load",
"tensorflow.lite.TFLiteConverter.from_keras_model_file"
] | [((723, 773), 'numpy.load', 'np.load', (['"""Asc_quant_representative_data_dummy.npz"""'], {}), "('Asc_quant_representative_data_dummy.npz')\n", (730, 773), True, 'import numpy as np\n'), ((1075, 1153), 'tensorflow.lite.TFLiteConverter.from_keras_model_file', 'tf.lite.TFLiteConverter.from_keras_model_file', (['"""Sessi... |
# Generated by Django 3.1.8 on 2021-07-20 13:34
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
('django_workflow_system', '0004_auto_20210701_0910'),
]
operations = [
migrations.CreateModel(
... | [
"django.db.models.ForeignKey",
"django.db.models.DateTimeField",
"django.db.models.ManyToManyField",
"django.db.models.UUIDField"
] | [((1614, 1868), 'django.db.models.ManyToManyField', 'models.ManyToManyField', ([], {'blank': '(True)', 'help_text': '"""Specify which collections a user must complete before accessing this Collection."""', 'through': '"""django_workflow_system.WorkflowCollectionDependency"""', 'to': '"""django_workflow_system.WorkflowC... |
import os
import time
breakout=False
crimeseverity=False
crimesevereaction=False
# variables =
# text
# gender
# name
# age
# height
# drunk
print ("Welcome to the test, Citizen.")
time.sleep(1)
print("Today you are applying for a job at the Agency.")
time.sleep(1)
print("By participating in this test, you agree to... | [
"os.system",
"time.sleep"
] | [((185, 198), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (195, 198), False, 'import time\n'), ((256, 269), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (266, 269), False, 'import time\n'), ((349, 362), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (359, 362), False, 'import time\n'), ((796, 814), ... |
# -*- coding: utf-8 -*-
import networkx as nx
import itertools
def is_subset(node_types):
"""Judge if the given aspect is a subset of the Selected ones"""
global Selected_Aspects
nt_set = set(node_types)
for sa in Selected_Aspects:
if nt_set.issubset(sa):
return True
return Fal... | [
"networkx.is_connected",
"networkx.Graph"
] | [((445, 472), 'networkx.is_connected', 'nx.is_connected', (['type_graph'], {}), '(type_graph)\n', (460, 472), True, 'import networkx as nx\n'), ((3108, 3118), 'networkx.Graph', 'nx.Graph', ([], {}), '()\n', (3116, 3118), True, 'import networkx as nx\n'), ((3911, 3921), 'networkx.Graph', 'nx.Graph', ([], {}), '()\n', (3... |
'''
Copyright (c) 2011-2018, Hortonworks Inc. All rights reserved.
Except as expressly permitted in a written agreement between you
or your company and Hortonworks, Inc, any use, reproduction,
modification,
redistribution, sharing, lending or other exploitation
of all or any part of the contents of this file is strict... | [
"ambari_commons.os_family_impl.OsFamilyFuncImpl"
] | [((484, 532), 'ambari_commons.os_family_impl.OsFamilyFuncImpl', 'OsFamilyFuncImpl', ([], {'os_family': 'OsFamilyImpl.DEFAULT'}), '(os_family=OsFamilyImpl.DEFAULT)\n', (500, 532), False, 'from ambari_commons.os_family_impl import OsFamilyFuncImpl, OsFamilyImpl\n'), ((927, 976), 'ambari_commons.os_family_impl.OsFamilyFun... |
import spacy
import typer
from pathlib import Path
def main(
input_vectors: Path, input_model: Path, input_oracle: Path, output_vectors: Path
):
nlp = spacy.load(input_model)
vectors = {}
with open(input_vectors) as fileh:
for line in fileh.readlines():
parts = line.strip().split()... | [
"spacy.load",
"typer.run"
] | [((161, 184), 'spacy.load', 'spacy.load', (['input_model'], {}), '(input_model)\n', (171, 184), False, 'import spacy\n'), ((810, 825), 'typer.run', 'typer.run', (['main'], {}), '(main)\n', (819, 825), False, 'import typer\n')] |
from flowjax.flows import Flow, RealNVPFlow, NeuralSplineFlow
from flowjax.bijections.utils import Permute
import jax.numpy as jnp
from jax import random
import pytest
def test_Flow():
key = random.PRNGKey(0)
bijection = Permute(jnp.array([2, 1, 0]))
dim = 3
flow = Flow(bijection, dim)
x = flow.sa... | [
"flowjax.flows.Flow",
"jax.random.uniform",
"jax.numpy.array",
"flowjax.flows.NeuralSplineFlow",
"flowjax.flows.RealNVPFlow",
"jax.random.PRNGKey",
"pytest.raises",
"jax.numpy.ones",
"jax.numpy.zeros",
"pytest.approx"
] | [((197, 214), 'jax.random.PRNGKey', 'random.PRNGKey', (['(0)'], {}), '(0)\n', (211, 214), False, 'from jax import random\n'), ((284, 304), 'flowjax.flows.Flow', 'Flow', (['bijection', 'dim'], {}), '(bijection, dim)\n', (288, 304), False, 'from flowjax.flows import Flow, RealNVPFlow, NeuralSplineFlow\n'), ((1518, 1535),... |
#!/usr/bin/python
import subprocess
subprocess.call("ifconfig enp2s0 down",shell=True)
subprocess.call("ifconfig enp2s0 hw ether 00:11:22:33:44:55",shell=True)
subprocess.call("ifconfig enp2s0 up",shell=True) | [
"subprocess.call"
] | [((38, 89), 'subprocess.call', 'subprocess.call', (['"""ifconfig enp2s0 down"""'], {'shell': '(True)'}), "('ifconfig enp2s0 down', shell=True)\n", (53, 89), False, 'import subprocess\n'), ((89, 162), 'subprocess.call', 'subprocess.call', (['"""ifconfig enp2s0 hw ether 00:11:22:33:44:55"""'], {'shell': '(True)'}), "('if... |
#!/usr/bin/python3
import os
import sys
import subprocess
import logging
import time
from djangoroku.djangoroku.linux import DeployOnLinux
class DjangoHerokuDeploy():
#I: SELECTING OS
os_name = input('Which OS are you using?\n1.Linux\n2.Windows')
if os_name == '1':
DeployOnLinux()
# I:THE DJANG... | [
"djangoroku.djangoroku.linux.DeployOnLinux",
"os.system",
"os.chdir",
"time.sleep"
] | [((286, 301), 'djangoroku.djangoroku.linux.DeployOnLinux', 'DeployOnLinux', ([], {}), '()\n', (299, 301), False, 'from djangoroku.djangoroku.linux import DeployOnLinux\n'), ((747, 760), 'time.sleep', 'time.sleep', (['(4)'], {}), '(4)\n', (757, 760), False, 'import time\n'), ((1037, 1050), 'time.sleep', 'time.sleep', ([... |
import numpy as np
from .utils import Timer
def run(size='large', repeats=3 ):
sizes = {'huge': 28000, 'large': 15000, 'small': 6000, 'tiny': 2000, 'test': 2}
n = sizes[size]
A = np.array(np.random.rand(n,n))
A = A@A.T
num_runs = repeats
print('num_runs =', num_runs)
results = []
... | [
"numpy.random.rand",
"numpy.linalg.cholesky"
] | [((208, 228), 'numpy.random.rand', 'np.random.rand', (['n', 'n'], {}), '(n, n)\n', (222, 228), True, 'import numpy as np\n'), ((417, 438), 'numpy.linalg.cholesky', 'np.linalg.cholesky', (['A'], {}), '(A)\n', (435, 438), True, 'import numpy as np\n')] |
"""ST-Link/V2 USB communication"""
import logging as _logging
import usb.core as _usb
import pyswd.swd._log as _log
class StlinkComException(Exception):
"""Exception"""
class StlinkComNotFound(Exception):
"""Exception"""
class StlinkComV2Usb():
"""ST-Link/V2 USB communication class"""
ID_VENDOR =... | [
"pyswd.swd._log.log",
"logging.log",
"usb.core.find"
] | [((633, 654), 'pyswd.swd._log.log', '_log.log', (['_log.DEBUG4'], {}), '(_log.DEBUG4)\n', (641, 654), True, 'import pyswd.swd._log as _log\n'), ((1161, 1182), 'pyswd.swd._log.log', '_log.log', (['_log.DEBUG4'], {}), '(_log.DEBUG4)\n', (1169, 1182), True, 'import pyswd.swd._log as _log\n'), ((2503, 2524), 'pyswd.swd._lo... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from other import keys_and_strings
def convert_to_cap_greek( s : str ) -> str:
dict_accented_caps = { 'Ό' : 'Ο', 'Ά' : 'Α', 'Ί' : 'Ι', 'Έ' : 'Ε', 'Ύ' : 'Υ', 'Ή' : 'Η', 'Ώ' : 'Ω'}
res = s.upper()
for orig, new in dict_accented_caps.i... | [
"selenium.webdriver.ChromeOptions",
"selenium.webdriver.Chrome"
] | [((469, 494), 'selenium.webdriver.ChromeOptions', 'webdriver.ChromeOptions', ([], {}), '()\n', (492, 494), False, 'from selenium import webdriver\n'), ((634, 707), 'selenium.webdriver.Chrome', 'webdriver.Chrome', (['keys_and_strings.PATH_TO_DRIVER'], {'options': 'chrome_options'}), '(keys_and_strings.PATH_TO_DRIVER, op... |
# coding: utf-8
from os.path import dirname, realpath, join
from subprocess import check_output
from hamcrest import assert_that, equal_to
BASE_DIR = dirname(realpath(__file__))
DATA_DIR = join(BASE_DIR, 'data')
MODEL_DIR = join(DATA_DIR, 'model')
PATTERN_DIR = join(DATA_DIR, 'pattern')
MATCH_DIR = join(DATA_DIR, 'ma... | [
"os.path.realpath",
"os.path.join",
"subprocess.check_output"
] | [((191, 213), 'os.path.join', 'join', (['BASE_DIR', '"""data"""'], {}), "(BASE_DIR, 'data')\n", (195, 213), False, 'from os.path import dirname, realpath, join\n'), ((226, 249), 'os.path.join', 'join', (['DATA_DIR', '"""model"""'], {}), "(DATA_DIR, 'model')\n", (230, 249), False, 'from os.path import dirname, realpath,... |
##########################################################################
#
# Copyright (c) 2013, Image Engine Design 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:
#
# * Redistribu... | [
"IECore.TransformationMatrixdData",
"os.remove",
"IECore.M44dData",
"IECore.DoubleData",
"IECoreMaya.FnSceneShape",
"IECore.M44fData",
"IECoreMaya.TestProgram",
"IECoreScene.MeshPrimitive.createBox",
"IECoreMaya.FnSceneShape.create",
"IECore.FloatData",
"os.path.exists",
"IECore.Int64Data",
... | [((23183, 23225), 'IECoreMaya.TestProgram', 'IECoreMaya.TestProgram', ([], {'plugins': "['ieCore']"}), "(plugins=['ieCore'])\n", (23205, 23225), False, 'import IECoreMaya\n'), ((2028, 2117), 'IECoreScene.SceneCache', 'IECoreScene.SceneCache', (['FnSceneShapeTest.__testFile', 'IECore.IndexedIO.OpenMode.Write'], {}), '(F... |
'''Module to load and use GloVe Models.
Code Inspiration from:
https://www.kaggle.com/jhoward/improved-lstm-baseline-glove-dropout
'''
import os
import numpy as np
import pandas as pd
import urllib.request
from zipfile import ZipFile
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.cluster import... | [
"numpy.pad",
"pandas.DataFrame",
"sklearn.cluster.KMeans",
"numpy.asarray",
"os.path.realpath",
"numpy.array",
"pandas.Series",
"numpy.random.normal"
] | [((354, 380), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (370, 380), False, 'import os\n'), ((4413, 4485), 'numpy.random.normal', 'np.random.normal', (['self.emb_mean', 'self.emb_std', '(nb_words, self.emb_size)'], {}), '(self.emb_mean, self.emb_std, (nb_words, self.emb_size))\n', (4429... |
"""
This file contains a function to generate a single synthetic tree, prepared for
multiprocessing.
"""
import pandas as pd
import numpy as np
# import dill as pickle
# import gzip
from syn_net.data_generation.make_dataset import synthetic_tree_generator
from syn_net.utils.data_utils import ReactionSet
path_reactio... | [
"syn_net.utils.data_utils.ReactionSet",
"pandas.read_csv",
"numpy.random.seed",
"syn_net.data_generation.make_dataset.synthetic_tree_generator"
] | [((584, 597), 'syn_net.utils.data_utils.ReactionSet', 'ReactionSet', ([], {}), '()\n', (595, 597), False, 'from syn_net.utils.data_utils import ReactionSet\n'), ((807, 824), 'numpy.random.seed', 'np.random.seed', (['_'], {}), '(_)\n', (821, 824), True, 'import numpy as np\n'), ((844, 904), 'syn_net.data_generation.make... |
import glob
import json
import os
import re
import sys
from urllib.parse import quote, quote_plus
import nbgrader.exchange.abc as abc
from dateutil import parser
from traitlets import Bool, Unicode
from .exchange import Exchange
# "outbound" is files released by instructors (.... but there may be local copies!)
# "... | [
"os.path.isdir",
"traitlets.Unicode",
"urllib.parse.quote",
"urllib.parse.quote_plus",
"os.path.split",
"os.path.join"
] | [((585, 647), 'traitlets.Unicode', 'Unicode', (['""""""'], {'help': '"""Root location for files to be fetched into"""'}), "('', help='Root location for files to be fetched into')\n", (592, 647), False, 'from traitlets import Bool, Unicode\n'), ((4580, 4613), 'os.path.join', 'os.path.join', (['self.assignment_dir'], {})... |
"""Contains the ansXpl class."""
import json
import pathlib
import random
import string
import weakref
from ansys.api.mapdl.v0 import mapdl_pb2
import numpy as np
from .common_grpc import ANSYS_VALUE_TYPE
from .errors import MapdlRuntimeError
def id_generator(size=6, chars=string.ascii_uppercase):
"""Generate a... | [
"pathlib.Path",
"weakref.ref",
"random.choice",
"json.loads"
] | [((1306, 1324), 'weakref.ref', 'weakref.ref', (['mapdl'], {}), '(mapdl)\n', (1317, 1324), False, 'import weakref\n'), ((7630, 7646), 'json.loads', 'json.loads', (['text'], {}), '(text)\n', (7640, 7646), False, 'import json\n'), ((387, 407), 'random.choice', 'random.choice', (['chars'], {}), '(chars)\n', (400, 407), Fal... |
import os
import random
import string
def create_init_file(base_dir):
open(os.path.join(base_dir, '__init__.py'), 'a').close()
def create_file(base_dir, name, other):
with open(os.path.join(base_dir, name), 'w') as f:
with open(other) as o:
f.write(o.read())
def create_git_ignore(base_dir):
path = os.pat... | [
"os.path.join",
"os.path.exists",
"random.SystemRandom"
] | [((314, 350), 'os.path.join', 'os.path.join', (['base_dir', '""".gitignore"""'], {}), "(base_dir, '.gitignore')\n", (326, 350), False, 'import os\n'), ((359, 379), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (373, 379), False, 'import os\n'), ((184, 212), 'os.path.join', 'os.path.join', (['base_dir'... |
# Conversor de temperatura de C° para F°
import colorama
colorama.init()
print('\033[32;1mConversor de temperaturas\033[m')
temp = float(input('Digite a temperatura em C°: '))
print(f'{temp} C° é equivalente a {(9*temp/5)+32} F°')
| [
"colorama.init"
] | [((57, 72), 'colorama.init', 'colorama.init', ([], {}), '()\n', (70, 72), False, 'import colorama\n')] |
import logging
import numpy as np
import tensorflow as tf
from collections import OrderedDict
import utils
from clf_model_multitask import predict
def get_latest_checkpoint_and_log(logdir, filename):
init_checkpoint_path = utils.get_latest_model_checkpoint_path(logdir, filename)
logging.info('Checkpoint pat... | [
"tensorflow.random_uniform",
"tensorflow.train.Saver",
"tensorflow.gather",
"tensorflow.global_variables_initializer",
"numpy.asarray",
"logging.info",
"utils.get_latest_model_checkpoint_path",
"tensorflow.placeholder",
"numpy.array",
"clf_model_multitask.predict",
"tensorflow.Graph",
"collect... | [((231, 287), 'utils.get_latest_model_checkpoint_path', 'utils.get_latest_model_checkpoint_path', (['logdir', 'filename'], {}), '(logdir, filename)\n', (269, 287), False, 'import utils\n'), ((292, 350), 'logging.info', 'logging.info', (["('Checkpoint path: %s' % init_checkpoint_path)"], {}), "('Checkpoint path: %s' % i... |
import requests
import os
import zipfile
def buster_captcha_solver(dir, unzip = False):
url = "https://api.github.com/repos/dessant/buster/releases/latest"
r = requests.get(url)
# Chrome
name = r.json()["assets"][0]["name"]
dl_url = r.json()["assets"][0]["browser_download_url"]
pa... | [
"os.path.abspath",
"zipfile.ZipFile",
"os.path.exists",
"os.path.splitext",
"requests.get"
] | [((175, 192), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (187, 192), False, 'import requests\n'), ((357, 377), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (371, 377), False, 'import os\n'), ((392, 425), 'requests.get', 'requests.get', (['dl_url'], {'stream': '(True)'}), '(dl_url, stre... |
# -*- coding: utf-8 -*-
from __future__ import division
import gensim
import nltk
import smart_open
import json
from sentence_extracor import segment_sentences_tok
from gensim.models import TfidfModel
from gensim.corpora import Dictionary
import warnings
warnings.filterwarnings("ignore", message="numpy.dtype size chang... | [
"gensim.utils.simple_preprocess",
"smart_open.smart_open",
"warnings.filterwarnings"
] | [((255, 324), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'message': '"""numpy.dtype size changed"""'}), "('ignore', message='numpy.dtype size changed')\n", (278, 324), False, 'import warnings\n'), ((325, 394), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'mess... |
import re
import json
import inject
import logging
import requests
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
from celery import Celery
from block.celery import APITask
from block.config import RedisCache, Config
from block.libs.dingding import DingDing
logger = logging.getLogger(__name__)
curre... | [
"block.libs.dingding.DingDing",
"fake_useragent.UserAgent",
"json.dumps",
"requests.get",
"inject.instance",
"bs4.BeautifulSoup",
"block.config.Config.scan_url.get",
"logging.getLogger",
"re.compile"
] | [((287, 314), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (304, 314), False, 'import logging\n'), ((329, 352), 'inject.instance', 'inject.instance', (['Celery'], {}), '(Celery)\n', (344, 352), False, 'import inject\n'), ((610, 637), 'inject.instance', 'inject.instance', (['RedisCache']... |
# -*- coding:UTF-8 -*-
import requests
import warnings
import os
import re
from nltk import Tree
from subprocess import Popen
import subprocess
import time
import shlex
import multiprocessing
from urllib import parse
class CoreNLP:
def __init__(self, url=None, lang="en", annotators=None, corenlp_dir=None, local_po... | [
"os.mkdir",
"os.path.abspath",
"subprocess.Popen",
"nltk.Tree.fromstring",
"shlex.split",
"os.path.exists",
"os.system",
"time.sleep",
"urllib.parse.quote",
"requests.get",
"re.sub",
"multiprocessing.cpu_count"
] | [((348, 375), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (373, 375), False, 'import multiprocessing\n'), ((2979, 2995), 'shlex.split', 'shlex.split', (['cmd'], {}), '(cmd)\n', (2990, 2995), False, 'import shlex\n'), ((3030, 3040), 'subprocess.Popen', 'Popen', (['cmd'], {}), '(cmd)\n', (... |
import dash
import dash_bootstrap_components as dbc
from flask import Flask
from ai4good.runner.facade import Facade
from ai4good.webapp.model_runner import ModelRunner
flask_app = Flask(__name__)
dash_app = dash.Dash(
__name__,
server=flask_app,
routes_pathname_prefix='/sim/',
suppress_callback_excep... | [
"flask.Flask",
"dash.Dash",
"ai4good.runner.facade.Facade.simple",
"ai4good.webapp.model_runner.ModelRunner"
] | [((182, 197), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (187, 197), False, 'from flask import Flask\n'), ((210, 368), 'dash.Dash', 'dash.Dash', (['__name__'], {'server': 'flask_app', 'routes_pathname_prefix': '"""/sim/"""', 'suppress_callback_exceptions': '(True)', 'external_stylesheets': '[dbc.themes... |
from django.contrib import admin
from .models import UserData
from .models import Posts
from .models import HazardType
from .models import Message
from .models import Comments
from .models import PostImageCollection
# Register your models here.
admin.site.register(HazardType)
admin.site.register(UserData)
admin.site.... | [
"django.contrib.admin.site.register"
] | [((247, 278), 'django.contrib.admin.site.register', 'admin.site.register', (['HazardType'], {}), '(HazardType)\n', (266, 278), False, 'from django.contrib import admin\n'), ((279, 308), 'django.contrib.admin.site.register', 'admin.site.register', (['UserData'], {}), '(UserData)\n', (298, 308), False, 'from django.contr... |
#-*- coding: utf-8 -*-
import xmind
from xmind.core.const import TOPIC_DETACHED
from xmind.core.markerref import MarkerId
w = xmind.load("test.xmind") # load an existing file or create a new workbook if nothing is found
s1=w.getPrimarySheet() # get the first sheet
s1.setTitle("first sheet") # set its title
r1=s1.getR... | [
"xmind.save",
"xmind.load"
] | [((127, 151), 'xmind.load', 'xmind.load', (['"""test.xmind"""'], {}), "('test.xmind')\n", (137, 151), False, 'import xmind\n'), ((1739, 1767), 'xmind.save', 'xmind.save', (['w', '"""test2.xmind"""'], {}), "(w, 'test2.xmind')\n", (1749, 1767), False, 'import xmind\n')] |
import concurrent.futures
import csv
from ctrace.utils import max_neighbors
import functools
import itertools
import logging
import time
from collections import namedtuple
from typing import Dict, Callable, List, Any, NamedTuple
import traceback
import shortuuid
import tracemalloc
from tqdm import tqdm
... | [
"tqdm.tqdm",
"logging.FileHandler",
"shortuuid.uuid",
"tracemalloc.take_snapshot",
"time.perf_counter",
"traceback.format_exc",
"functools.wraps",
"logging.getLogger",
"csv.DictWriter"
] | [((425, 452), 'tracemalloc.take_snapshot', 'tracemalloc.take_snapshot', ([], {}), '()\n', (450, 452), False, 'import tracemalloc\n'), ((3300, 3321), 'functools.wraps', 'functools.wraps', (['func'], {}), '(func)\n', (3315, 3321), False, 'import functools\n'), ((5220, 5249), 'logging.getLogger', 'logging.getLogger', (['"... |
from simulations import simulation, simulation2
from pandas import DataFrame
from pandas import Series
from pandas import concat
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, Bidirectional
from keras.laye... | [
"pandas.DataFrame",
"matplotlib.pyplot.show",
"math.sqrt",
"matplotlib.pyplot.plot",
"pandas.concat",
"keras.models.Sequential",
"matplotlib.pyplot.legend",
"sklearn.preprocessing.MinMaxScaler",
"keras.layers.LSTM",
"simulations.simulation.Simulation",
"keras.layers.Dense",
"numpy.array",
"p... | [((2515, 2540), 'simulations.simulation2.Simulator', 'simulation2.Simulator', (['(50)'], {}), '(50)\n', (2536, 2540), False, 'from simulations import simulation, simulation2\n'), ((2561, 2690), 'simulations.simulation.Simulation', 'simulation.Simulation', (['[[1, 1]]', '[[0.1, [0.2, 0.1], [15, 2], [30, 2]]]', '[[70.0, ... |
#coding=utf-8
"""
1. SQLAlchemy-migration现在是openstack社区维护的一个项目,主要用于实现SQLAlchemy相
关数据误置的创建、版本管理、迁移等功能;它对SQLAlchemy的版本有一定要求;它对于一般项
目而言并不是必需的;
2. 下面的db_create、db_migrate、db_upgrade、db_downgrade等方法均使用SQLAlchemy-
migration实现;
3. 如果不需要实现数据库版本管理及迁移,可以不使用SQLAlchemy-migration。
"""
import os.path
# from migrate.versioning imp... | [
"sqlalchemy.create_engine",
"sqlalchemy.ext.declarative.declarative_base",
"sqlalchemy.orm.sessionmaker"
] | [((594, 683), 'sqlalchemy.create_engine', 'create_engine', (["app.config['SQLALCHEMY_DATABASE_URI']"], {'convert_unicode': '(True)', 'echo': '(True)'}), "(app.config['SQLALCHEMY_DATABASE_URI'], convert_unicode=True,\n echo=True)\n", (607, 683), False, 'from sqlalchemy import create_engine\n'), ((860, 878), 'sqlalche... |
import boto3
import json
def get_client() -> boto3.Session:
return boto3.client("lambda")
def external_lambda_tests() -> None:
basic_call()
def basic_call() -> None:
lambda_client = get_client()
response = lambda_client.list_functions(
MaxItems=10
)
pretty_print(... | [
"boto3.client",
"json.dumps"
] | [((73, 95), 'boto3.client', 'boto3.client', (['"""lambda"""'], {}), "('lambda')\n", (85, 95), False, 'import boto3\n'), ((382, 428), 'json.dumps', 'json.dumps', (['response'], {'indent': '(4)', 'sort_keys': '(True)'}), '(response, indent=4, sort_keys=True)\n', (392, 428), False, 'import json\n')] |
import re
import os
import sys
import time
import atexit
import platform
import traceback
import logging
import base64
import random
from contextlib import contextmanager
from blackfire import profiler, VERSION, agent, generate_config, DEFAULT_CONFIG_FILE
from blackfire.utils import IS_PY3, get_home_dir, ConfigParser, ... | [
"atexit.register",
"blackfire.profiler.stop",
"blackfire.profiler.clear_traces",
"blackfire.agent.Connection",
"blackfire.utils.get_load_avg",
"random.randint",
"blackfire.utils.json_prettify",
"blackfire.utils.get_probed_runtime",
"traceback.format_exc",
"blackfire.generate_config",
"blackfire.... | [((565, 585), 'blackfire.utils.get_logger', 'get_logger', (['__name__'], {}), '(__name__)\n', (575, 585), False, 'from blackfire.utils import IS_PY3, get_home_dir, ConfigParser, urlparse, urljoin, urlencode, get_load_avg, get_logger, quote, parse_qsl, Request, urlopen, json_prettify, get_probed_runtime\n'), ((7014, 707... |
# MIT License
#
# Copyright (c) 2017 <NAME> and (c) 2020 Google LLC
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to u... | [
"logging.Formatter",
"torch.set_num_threads",
"numpy.mean",
"third_party.a2c_ppo_acktr.algo.PPO",
"torch.device",
"third_party.a2c_ppo_acktr.algo.A2C_ACKTR",
"third_party.a2c_ppo_acktr.storage.RolloutStorage",
"torch.no_grad",
"os.path.join",
"third_party.a2c_ppo_acktr.utils.get_vec_normalize",
... | [((1657, 1687), 'sys.path.append', 'sys.path.append', (['"""third_party"""'], {}), "('third_party')\n", (1672, 1687), False, 'import sys\n'), ((1725, 1735), 'third_party.a2c_ppo_acktr.arguments.get_args', 'get_args', ([], {}), '()\n', (1733, 1735), False, 'from third_party.a2c_ppo_acktr.arguments import get_args\n'), (... |
from search_test import SearchTest, SearchTestElastic
if __name__ == "__main__":
test = SearchTestElastic(timeout=50, file_for_save=
'/home/roman/Projects/ElasticMongoTest/test_results_csv/ElasticsearchTest.csv')
# test.search_substrings_or(['Colorado', 'USA', 'President', 'Washi... | [
"search_test.SearchTestElastic"
] | [((95, 228), 'search_test.SearchTestElastic', 'SearchTestElastic', ([], {'timeout': '(50)', 'file_for_save': '"""/home/roman/Projects/ElasticMongoTest/test_results_csv/ElasticsearchTest.csv"""'}), "(timeout=50, file_for_save=\n '/home/roman/Projects/ElasticMongoTest/test_results_csv/ElasticsearchTest.csv'\n )\n",... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Parameter
V1 = Parameter(torch.randn(3, 3, requires_grad=True))
V2 = Parameter(torch.randn(3, 3, requires_grad=True))
W = torch.randn(2, 2)
bias = torch.zeros(2)
def update(V, W):
V = torch.matmul(V1, V2.transpose(0, 1))
... | [
"torch.zeros",
"torch.ones",
"torch.randn",
"torch.nn.functional.linear"
] | [((211, 228), 'torch.randn', 'torch.randn', (['(2)', '(2)'], {}), '(2, 2)\n', (222, 228), False, 'import torch\n'), ((236, 250), 'torch.zeros', 'torch.zeros', (['(2)'], {}), '(2)\n', (247, 250), False, 'import torch\n'), ((609, 623), 'torch.randn', 'torch.randn', (['(2)'], {}), '(2)\n', (620, 623), False, 'import torch... |
# Copyright 2019 Nine Entertainment Co.
#
# 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 w... | [
"secretupdater.app.config.get",
"requests.get",
"secretupdater.app.logger.debug"
] | [((813, 858), 'secretupdater.app.logger.debug', 'app.logger.debug', (['"""Initialising HeaderClient"""'], {}), "('Initialising HeaderClient')\n", (829, 858), False, 'from secretupdater import app\n'), ((904, 947), 'secretupdater.app.logger.debug', 'app.logger.debug', (['"""DummyClient.get_service"""'], {}), "('DummyCli... |
import pytest
import datetime
import pandas as pd
import pyarrow as pa
import numpy as np
from arrow_pd_parser.parse import (
pa_read_csv_to_pandas,
pa_read_json_to_pandas,
)
def pd_datetime_series_to_list(s, series_type, date=False):
fmt = "%Y-%m-%d" if date else "%Y-%m-%d %H:%M:%S"
if series_type ==... | [
"pyarrow.schema",
"pyarrow.string",
"pandas.read_csv",
"pytest.warns",
"arrow_pd_parser.parse.pa_read_csv_to_pandas",
"pytest.mark.parametrize",
"pandas.isna",
"pytest.mark.skip",
"pyarrow.timestamp"
] | [((869, 1560), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""in_type,pd_timestamp_type,out_type"""', "[('timestamp[s]', 'datetime_object', 'object'), ('timestamp[s]',\n 'pd_timestamp', 'datetime64[ns]'), ('timestamp[s]', 'pd_period',\n 'period[S]'), ('timestamp[ms]', 'datetime_object', 'object'), (\... |
import sklearn
from sklearn.linear_model import LinearRegression
import catboost
import pandas as pd
import copy
import lightgbm as lgb
import xgboost as xgb
from sklearn.model_selection import train_test_split, KFold, cross_val_score, StratifiedKFold, GridSearchCV
from sklearn.metrics import mean_absolute_error, r2_sc... | [
"pandas.DataFrame",
"sklearn.externals.joblib.dump",
"copy.deepcopy",
"inspect.getfullargspec",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"skopt.space.Integer",
"skopt.BayesSearchCV",
"sklearn.model_selection.KFold",
"skopt.space.Real",
"pandas.Series",
"skopt.callbacks.De... | [((2405, 2421), 'pandas.DataFrame', 'pd.DataFrame', (['[]'], {}), '([])\n', (2417, 2421), True, 'import pandas as pd\n'), ((2427, 2440), 'pandas.Series', 'pd.Series', (['[]'], {}), '([])\n', (2436, 2440), True, 'import pandas as pd\n'), ((10289, 10354), 'pandas.read_csv', 'pd.read_csv', (['"""../input/sample_submission... |
import asyncio
import pytest
from motor.motor_asyncio import AsyncIOMotorClient
from blog.repositories import PostRepository
@pytest.mark.asyncio
async def test_create_blog(db):
post_repository = PostRepository()
collection = db['posts']
result = await collection.insert_one({'name': 'Rob'})
assert ... | [
"blog.repositories.PostRepository"
] | [((204, 220), 'blog.repositories.PostRepository', 'PostRepository', ([], {}), '()\n', (218, 220), False, 'from blog.repositories import PostRepository\n')] |
import os
import xlrd
from xlrd import XLRDError
from xlrd.book import Book
from xlrd.sheet import Sheet
from collections import OrderedDict
from typing import Iterable, List, Dict, Tuple
import logging
import traceback
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
def read_xml_files(... | [
"xlrd.open_workbook",
"logging.getLogger",
"traceback.format_exc",
"logging.NullHandler",
"collections.OrderedDict",
"os.scandir"
] | [((230, 257), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (247, 257), False, 'import logging\n'), ((276, 297), 'logging.NullHandler', 'logging.NullHandler', ([], {}), '()\n', (295, 297), False, 'import logging\n'), ((447, 472), 'os.scandir', 'os.scandir', ([], {'path': 'root_dir'}), '(... |
from classier.decorators.has_state_decorator.options import ATTRIBUTE_OPTIONS
from classier.decorators.has_state_decorator.options import METHOD_OPTIONS
from classier.objects import ClassMarker
from classier.decorators import _MARK_ATTRIBUTE_NAME
from classier.decorators.has_state_decorator import _MARK_TYPE_NAME
impor... | [
"classier.decorators.has_state_decorator.options.METHOD_OPTIONS.METHOD_POINTER_EXISTS.get_option",
"json.loads",
"classier.decorators.has_state_decorator.options.METHOD_OPTIONS.METHOD_SAVER.get_option",
"classier.decorators.has_state_decorator.options.METHOD_OPTIONS.METHOD_INDEX.get_option",
"classier.utils... | [((416, 475), 'classier.decorators.has_state_decorator.options.METHOD_OPTIONS.METHOD_STATE_TRANSFORMER.get_option', 'METHOD_OPTIONS.METHOD_STATE_TRANSFORMER.get_option', (['options'], {}), '(options)\n', (466, 475), False, 'from classier.decorators.has_state_decorator.options import METHOD_OPTIONS\n'), ((497, 553), 'cl... |