code stringlengths 20 1.04M | apis list | extract_api stringlengths 75 9.94M |
|---|---|---|
from typing import Callable
import pytest
from starlette.background import BackgroundTask, BackgroundTasks
from starlette.responses import Response
from starlette.testclient import TestClient
def test_async_task(test_client_factory):
TASK_COMPLETE = False
async def async_task():
nonlocal TASK_COMPL... | [
"starlette.background.BackgroundTasks",
"starlette.background.BackgroundTask",
"starlette.responses.Response",
"pytest.raises"
] | [((365, 391), 'starlette.background.BackgroundTask', 'BackgroundTask', (['async_task'], {}), '(async_task)\n', (379, 391), False, 'from starlette.background import BackgroundTask, BackgroundTasks\n'), ((870, 895), 'starlette.background.BackgroundTask', 'BackgroundTask', (['sync_task'], {}), '(sync_task)\n', (884, 895),... |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import tensorflow as tf
from fewshot.utils.logger import get as get_logger
log = get_logger()
class VariableManager():
def __init__(self):
self.scope_list = []
self.var_dict = {}
def enter_scop... | [
"fewshot.utils.logger.get"
] | [((192, 204), 'fewshot.utils.logger.get', 'get_logger', ([], {}), '()\n', (202, 204), True, 'from fewshot.utils.logger import get as get_logger\n')] |
#!/usr/bin/python
# garaged.py - Daemon to generate alerts when garage door is left open
#
# Copyright (c) 2015 <NAME>
#
# 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, ... | [
"json.load",
"syslog.syslog",
"socket.socket",
"time.sleep",
"datetime.timedelta",
"lockfile.FileLock",
"datetime.datetime.now",
"twilio.rest.TwilioRestClient"
] | [((1896, 1958), 'syslog.syslog', 'syslog.syslog', (["('garaged: door ' + state + ' since ' + texttime)"], {}), "('garaged: door ' + state + ' since ' + texttime)\n", (1909, 1958), False, 'import syslog\n'), ((2293, 2354), 'twilio.rest.TwilioRestClient', 'TwilioRestClient', (["config['account_sid']", "config['auth_token... |
import os
from sanic import Sanic
from sanic_cors import CORS
import settings
from manifests.routes import setup_routes
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(BASE_DIR, "version.txt")) as v_file:
VERSION = v_file.read()
try:
import sentry_sdk
from sentry_sdk.integra... | [
"os.path.abspath",
"sentry_sdk.integrations.sanic.SanicIntegration",
"sanic_cors.CORS",
"sanic.Sanic",
"manifests.routes.setup_routes",
"os.path.join"
] | [((578, 615), 'sanic.Sanic', 'Sanic', (['__file__'], {'strict_slashes': '(False)'}), '(__file__, strict_slashes=False)\n', (583, 615), False, 'from sanic import Sanic\n'), ((617, 634), 'manifests.routes.setup_routes', 'setup_routes', (['app'], {}), '(app)\n', (629, 634), False, 'from manifests.routes import setup_route... |
import numpy as np
import sys
sys.path.append("/data")
def sigmoid(x):
return 1 / (1 + np.exp(-x))
x = np.arange(-5.0, 5.0, 0.1)
y = sigmoid(x)
x = np.arange(-5.0, 5.0, 0.1)
y1 = sigmoid(0.5 * x)
y2 = sigmoid(x)
y3 = sigmoid(2 * x)
x = np.arange(-5.0, 5.0, 0.1)
y1 = sigmoid(0.5 + x)
y2 = sigmoid(1 + x)
y3 = s... | [
"sys.path.append",
"torch.nn.functional.binary_cross_entropy",
"torch.manual_seed",
"torch.FloatTensor",
"numpy.arange",
"numpy.exp",
"torch.zeros",
"scripts.utils.torch_utils.TorchScheduler",
"torch.log",
"torch.optim.SGD"
] | [((30, 54), 'sys.path.append', 'sys.path.append', (['"""/data"""'], {}), "('/data')\n", (45, 54), False, 'import sys\n'), ((111, 136), 'numpy.arange', 'np.arange', (['(-5.0)', '(5.0)', '(0.1)'], {}), '(-5.0, 5.0, 0.1)\n', (120, 136), True, 'import numpy as np\n'), ((157, 182), 'numpy.arange', 'np.arange', (['(-5.0)', '... |
from flask import url_for
def test_get_token(client):
response = client.get(url_for("get_token"))
assert response.status_code == 200
def test_retrieve_accounts(client):
response = client.post(url_for("retrieve_accounts"), json={})
assert response.status_code == 200
| [
"flask.url_for"
] | [((82, 102), 'flask.url_for', 'url_for', (['"""get_token"""'], {}), "('get_token')\n", (89, 102), False, 'from flask import url_for\n'), ((208, 236), 'flask.url_for', 'url_for', (['"""retrieve_accounts"""'], {}), "('retrieve_accounts')\n", (215, 236), False, 'from flask import url_for\n')] |
from tensorflow import keras as keras
import tensorflow as tf
import numpy as np
from sklearn.feature_extraction import image
import sys
n = 64
model = keras.models.Sequential()
input_dim = n
dim_net = int(n*n)
#FC1 - INPUT
input_layer = keras.layers.InputLayer(input_shape=(input_dim,input_dim,1))
model.add( input... | [
"numpy.load",
"tensorflow.summary.image",
"tensorflow.keras.layers.Conv2D",
"tensorflow.keras.layers.Reshape",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.regularizers.l1",
"numpy.expand_dims",
"tensorflow.keras.layers.InputLayer",
"tensorflow.keras.layers.Conv2DTranspose",
"tensorflow.kera... | [((155, 180), 'tensorflow.keras.models.Sequential', 'keras.models.Sequential', ([], {}), '()\n', (178, 180), True, 'from tensorflow import keras as keras\n'), ((243, 305), 'tensorflow.keras.layers.InputLayer', 'keras.layers.InputLayer', ([], {'input_shape': '(input_dim, input_dim, 1)'}), '(input_shape=(input_dim, input... |
#-----------------------------------------------------------------------------
# Copyright (c) 2020, <NAME>
# All rights reserved.
#
# The full license is in the LICENSE file, distributed with this software.
#-----------------------------------------------------------------------------
from rdkit import Chem
import pa... | [
"pandas.read_csv",
"rdkit.Chem.MolFromSmarts",
"rdkit.Chem.MolFromSmiles",
"pandas.DataFrame"
] | [((1466, 1520), 'pandas.read_csv', 'pd.read_csv', (['self._fname'], {'nrows': '(1)'}), '(self._fname, nrows=1, **self._supplkwargs)\n', (1477, 1520), True, 'import pandas as pd\n'), ((2051, 2096), 'pandas.read_csv', 'pd.read_csv', (['self._fname'], {}), '(self._fname, **self._supplkwargs)\n', (2062, 2096), True, 'impor... |
import pandas as pd
from collections import Counter
import pprint as pp
import datetime as dt
class wordle_game:
def __init__(
self,
game_num: int,
folder: str = None,
filename: str = "wordle_scores.csv",
):
self.game_num = game_num
self.roun... | [
"pandas.DataFrame",
"pandas.read_csv",
"datetime.date.today",
"pprint.pprint",
"collections.Counter",
"pandas.concat"
] | [((791, 805), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (803, 805), True, 'import pandas as pd\n'), ((827, 841), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (839, 841), True, 'import pandas as pd\n'), ((1334, 1369), 'pandas.read_csv', 'pd.read_csv', (['f"""{folder}/{filename}"""'], {}), "(f'{folde... |
#!/usr/bin/python3
import math
import json
import urllib3
from pathlib import Path
import requests
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
def cn_js_info(api_url):
info = requests.get(api_url, verify=False).json()
_height = info['lastblock']['height']
_hash_rate = info['po... | [
"json.load",
"math.pow",
"json.dumps",
"pathlib.Path",
"requests.get",
"urllib3.disable_warnings"
] | [((103, 170), 'urllib3.disable_warnings', 'urllib3.disable_warnings', (['urllib3.exceptions.InsecureRequestWarning'], {}), '(urllib3.exceptions.InsecureRequestWarning)\n', (127, 170), False, 'import urllib3\n'), ((3687, 3721), 'json.dumps', 'json.dumps', (['active_pools'], {'indent': '(4)'}), '(active_pools, indent=4)\... |
#coding=utf-8
from django.shortcuts import render
from django.views.generic import View
from django.http import JsonResponse
import json
from api.transmitters import Transmitters2D
from api.hungarian_algorithm import Hungarian
class TransmitterDataWrapper:
def __init__(self, request):
# type: (Dict) ->... | [
"django.shortcuts.render",
"api.hungarian_algorithm.Hungarian",
"api.transmitters.Transmitters2D",
"django.http.JsonResponse"
] | [((1257, 1326), 'django.shortcuts.render', 'render', (['request', 'self.template_name', "{'info': 'Podaj dane dla grafu'}"], {}), "(request, self.template_name, {'info': 'Podaj dane dla grafu'})\n", (1263, 1326), False, 'from django.shortcuts import render\n'), ((2744, 2766), 'api.hungarian_algorithm.Hungarian', 'Hunga... |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2019 Fetch.AI 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 ... | [
"os.environ.copy",
"time.time",
"time.sleep",
"platform.system",
"pexpect.exceptions.TIMEOUT",
"aea.helpers.base.send_control_c"
] | [((1494, 1509), 'time.sleep', 'time.sleep', (['(0.1)'], {}), '(0.1)\n', (1504, 1509), False, 'import time\n'), ((1557, 1588), 'aea.helpers.base.send_control_c', 'send_control_c', (['self.proc', '(True)'], {}), '(self.proc, True)\n', (1571, 1588), False, 'from aea.helpers.base import send_control_c\n'), ((2144, 2155), '... |
from flask import Flask
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_uploads import UploadSet, IMAGES, configure_uploads
plotterapp = Flask(__name__)
plotterapp.config.from_object(Config)
db = SQLAlchemy(plotterapp)
migrate = Migrate(plotterapp, db)
ima... | [
"flask_uploads.UploadSet",
"flask.Flask",
"flask_sqlalchemy.SQLAlchemy",
"flask_migrate.Migrate",
"flask_uploads.configure_uploads"
] | [((201, 216), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (206, 216), False, 'from flask import Flask\n'), ((260, 282), 'flask_sqlalchemy.SQLAlchemy', 'SQLAlchemy', (['plotterapp'], {}), '(plotterapp)\n', (270, 282), False, 'from flask_sqlalchemy import SQLAlchemy\n'), ((293, 316), 'flask_migrate.Migrat... |
from pyomo.environ import Block, Constraint, Expression, NonNegativeReals, Var, units as pyunits
from watertap3.utils import financials
from watertap3.wt_units.wt_unit import WT3UnitProcess
module_name = 'reverse_osmosis'
basis_year = 2007
tpec_or_tic = 'TIC'
class UnitProcess(WT3UnitProcess):
def fixed_cap(self... | [
"pyomo.environ.Block",
"pyomo.environ.Constraint",
"pyomo.environ.Var",
"pyomo.environ.units.convert",
"watertap3.utils.financials.get_complete_costing",
"watertap3.utils.financials.create_costing_block"
] | [((1653, 1712), 'pyomo.environ.Var', 'Var', (['time'], {'units': 'pyunits.dimensionless', 'doc': '"""mass_fraction"""'}), "(time, units=pyunits.dimensionless, doc='mass_fraction')\n", (1656, 1712), False, 'from pyomo.environ import Block, Constraint, Expression, NonNegativeReals, Var, units as pyunits\n'), ((1799, 1858... |
from typing import Type, Union
import numpy as np
from genrl.core import PrioritizedBuffer, ReplayBuffer
from genrl.trainers import Trainer
from genrl.utils import safe_mean
class OffPolicyTrainer(Trainer):
"""Off Policy Trainer Class
Trainer class for all the Off Policy Agents: DQN (all variants), DDPG, T... | [
"numpy.any",
"genrl.utils.safe_mean",
"numpy.zeros"
] | [((2993, 3018), 'numpy.zeros', 'np.zeros', (['self.env.n_envs'], {}), '(self.env.n_envs)\n', (3001, 3018), True, 'import numpy as np\n'), ((3032, 3057), 'numpy.zeros', 'np.zeros', (['self.env.n_envs'], {}), '(self.env.n_envs)\n', (3040, 3057), True, 'import numpy as np\n'), ((4096, 4108), 'numpy.any', 'np.any', (['done... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
import logging
logger = logging.getLogger(__name__)
def check_save_load(
self,
model,
expected_num_params,
expected_num_inputs,
expected_num_outputs,
check_equality=True,
):
# TODO: remove the... | [
"logging.getLogger"
] | [((122, 149), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (139, 149), False, 'import logging\n')] |
"""NEKOS MODULE FOR PEPEBOT
Plugin Made by [NIKITA](https://t.me/kirito6969)
**DON'T EVEN TRY TO CHANGE CREDITS**'
"""
import os
import nekos
import requests
from fake_useragent import UserAgent
from PIL import Image
from simplejson.errors import JSONDecodeError
from ..core.managers import edit_delete, edit_or_reply... | [
"nekos.img",
"os.remove",
"fake_useragent.UserAgent",
"PIL.Image.open",
"requests.get"
] | [((1369, 1391), 'nekos.img', 'nekos.img', (['f"""{choose}"""'], {}), "(f'{choose}')\n", (1378, 1391), False, 'import nekos\n'), ((2972, 2994), 'PIL.Image.open', 'Image.open', (['"""temp.png"""'], {}), "('temp.png')\n", (2982, 2994), False, 'from PIL import Image\n'), ((3144, 3166), 'os.remove', 'os.remove', (['"""temp.... |
# Copyright 2021 Datum Technology Corporation
# SPDX-License-Identifier: Apache-2.0 WITH SHL-2.1
########################################################################################################################
# Licensed under the Solderpad Hardware License v 2.1 (the "License"); you may not use this file excep... | [
"docopt.docopt"
] | [((3478, 3531), 'docopt.docopt', 'docopt', (['__doc__'], {'argv': 'upper_args', 'options_first': '(False)'}), '(__doc__, argv=upper_args, options_first=False)\n', (3484, 3531), False, 'from docopt import docopt\n')] |
"""
:Authors: - <NAME>
"""
import numpy as np
def create_synthetic_data(path, nb_samples=10000, vocab_size=10, length_range=[2, 20], cat_params=None, alpha=None):
"""
:param path: where to save the data
:param nb_samples: number of sequences
:param vocab_size: number of known tokens [1, vocab_size]
... | [
"numpy.full",
"numpy.random.randint",
"numpy.random.choice"
] | [((1018, 1090), 'numpy.random.randint', 'np.random.randint', (['length_range[0]', '(length_range[1] + 1)'], {'size': 'nb_samples'}), '(length_range[0], length_range[1] + 1, size=nb_samples)\n', (1035, 1090), True, 'import numpy as np\n'), ((896, 974), 'numpy.random.choice', 'np.random.choice', (['vocab_size'], {'size':... |
# coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | [
"jax.numpy.logical_not",
"jax.random.categorical",
"jax.random.uniform",
"jax.numpy.tile",
"jax.random.normal",
"jax.numpy.einsum",
"jax.numpy.linalg.norm",
"jax.numpy.diag",
"jax.numpy.ones_like",
"jax.numpy.sin",
"jax.scipy.stats.norm.logpdf",
"functools.partial",
"jax.vmap",
"jax.numpy.... | [((21381, 21415), 'functools.partial', 'partial', (['jax.jit'], {'static_argnums': '(5)'}), '(jax.jit, static_argnums=5)\n', (21388, 21415), False, 'from functools import partial\n'), ((22697, 22713), 'functools.partial', 'partial', (['jax.jit'], {}), '(jax.jit)\n', (22704, 22713), False, 'from functools import partial... |
from typing import Final
import numpy as np
def brightness(rgb: np.ndarray, b: float):
b /= 255.0
input_shape = rgb.shape
normalized: np.ndarray = (rgb / (np.ones(input_shape) * 255)).reshape(-1, 3)
normalized = np.concatenate((normalized, np.ones((normalized.shape[0], 1), dtype=float)), axis=1)
... | [
"numpy.array",
"numpy.ones",
"numpy.matmul"
] | [((355, 421), 'numpy.array', 'np.array', (['[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [b, b, b, 1]]'], {}), '([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [b, b, b, 1]])\n', (363, 421), True, 'import numpy as np\n'), ((578, 611), 'numpy.matmul', 'np.matmul', (['normalized', 'bright_mat'], {}), '(normalized, bright_mat)\... |
from random import random
import wikipedia as wiki
random_article = wiki.random(pages=1)
# If it starts with a year, draw another article
if random_article[0:3].isnumeric():
random_article = wiki.random(pages=1)
# If it's a list, remove "List of"
if (random_article.startswith("List of")):
random_article = r... | [
"wikipedia.random"
] | [((70, 90), 'wikipedia.random', 'wiki.random', ([], {'pages': '(1)'}), '(pages=1)\n', (81, 90), True, 'import wikipedia as wiki\n'), ((198, 218), 'wikipedia.random', 'wiki.random', ([], {'pages': '(1)'}), '(pages=1)\n', (209, 218), True, 'import wikipedia as wiki\n')] |
from src.database import SqliteDatabase
class PeopleRepository:
def __init__(self):
self.repository = SqliteDatabase("people.sqlite3")
def getPeople(self):
sql = """
SELECT name, birth_date, gender FROM people
ORDER BY name;
"""
try:
self.repository.cursor.execute(sql)
result = self.repositor... | [
"src.database.SqliteDatabase"
] | [((106, 138), 'src.database.SqliteDatabase', 'SqliteDatabase', (['"""people.sqlite3"""'], {}), "('people.sqlite3')\n", (120, 138), False, 'from src.database import SqliteDatabase\n')] |
from random import randint
itens = ('Pedra', 'Papel', 'Tesoura')
computador = randint(0,2)
print('''Suas opções:'
[ 0 ] PEDRA
[ 1 ] PAPEL
[ 2 } TESOURA''')
jogador = int(input('Qual é a sua jogada? '))
print('-=-' * 11)
print('Computador jogou {}'.format(itens[computador]))
print('Jogador escolheu {}'.format(itens[joga... | [
"random.randint"
] | [((78, 91), 'random.randint', 'randint', (['(0)', '(2)'], {}), '(0, 2)\n', (85, 91), False, 'from random import randint\n')] |
import os
import csv
# Read csv file
election_data = os.path.join("python-challenge","pypoll","Resources", "election_data.csv")
# open election_data
with open(election_data) as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
next(csvreader)
# define variables
total_votes = 0
candidates = ... | [
"csv.reader",
"os.path.join",
"csv.writer"
] | [((54, 130), 'os.path.join', 'os.path.join', (['"""python-challenge"""', '"""pypoll"""', '"""Resources"""', '"""election_data.csv"""'], {}), "('python-challenge', 'pypoll', 'Resources', 'election_data.csv')\n", (66, 130), False, 'import os\n'), ((950, 1027), 'os.path.join', 'os.path.join', (['"""python-challenge"""', '... |
import pytest
from keyset_pagination.paginator import KeysetPaginator, InvalidPage
from ..models import Event
@pytest.fixture
def events():
Event.objects.bulk_create([
Event(timestamp='2017-01-01T01:23:45Z', group="bar", reading=2),
Event(timestamp='2017-01-01T01:23:45Z', group="baz", reading=3)... | [
"pytest.raises"
] | [((1395, 1421), 'pytest.raises', 'pytest.raises', (['InvalidPage'], {}), '(InvalidPage)\n', (1408, 1421), False, 'import pytest\n')] |
import sst
import sst.actions
sst.actions.set_base_url('http://localhost:%s/' % sst.DEVSERVER_PORT)
sst.actions.go_to('/')
# unique id
elem = sst.actions.get_element(id='longscroll_link')
sst.actions.assert_text(elem, 'link to longscroll page')
# unique id + tag
elem = sst.actions.get_element(tag='a', id='longscrol... | [
"sst.actions.set_base_url",
"sst.actions.get_element",
"sst.actions.go_to",
"sst.actions.assert_radio",
"sst.actions.assert_text"
] | [((32, 101), 'sst.actions.set_base_url', 'sst.actions.set_base_url', (["('http://localhost:%s/' % sst.DEVSERVER_PORT)"], {}), "('http://localhost:%s/' % sst.DEVSERVER_PORT)\n", (56, 101), False, 'import sst\n'), ((102, 124), 'sst.actions.go_to', 'sst.actions.go_to', (['"""/"""'], {}), "('/')\n", (119, 124), False, 'imp... |
# Sliding windows code template is most used in substring match or maximum/minimum problems.
# It uses two-pointer as boundary of sliding window to traverse, and use a counter(dict) maintain current state,
# and a count as condition checker, update it when trigger some key changes.
#
# Time: O(n)
# Space: O(k) k = len... | [
"collections.Counter"
] | [((632, 642), 'collections.Counter', 'Counter', (['p'], {}), '(p)\n', (639, 642), False, 'from collections import Counter\n')] |
from toontown.building import DistributedToonInteriorAI
class DistributedToonyLabInteriorAI(DistributedToonInteriorAI.DistributedToonInteriorAI):
def __init__(self, block, air, zoneId, building):
DistributedToonInteriorAI.DistributedToonInteriorAI.__init__(self, block, air, zoneId, building) | [
"toontown.building.DistributedToonInteriorAI.DistributedToonInteriorAI.__init__"
] | [((210, 310), 'toontown.building.DistributedToonInteriorAI.DistributedToonInteriorAI.__init__', 'DistributedToonInteriorAI.DistributedToonInteriorAI.__init__', (['self', 'block', 'air', 'zoneId', 'building'], {}), '(self, block,\n air, zoneId, building)\n', (270, 310), False, 'from toontown.building import Distribut... |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import jsonobject
from commcare_cloud.colors import color_notice, color_code
GitUriProperty = jsonobject.StringProperty
TimezoneProperty = jsonobject.StringProperty
class FabSettingsConfig(jsonobject... | [
"jsonobject.StringProperty",
"jsonobject.BooleanProperty",
"jsonobject.ObjectProperty",
"jsonobject.IntegerProperty",
"commcare_cloud.colors.color_code",
"commcare_cloud.colors.color_notice"
] | [((388, 415), 'jsonobject.StringProperty', 'jsonobject.StringProperty', ([], {}), '()\n', (413, 415), False, 'import jsonobject\n'), ((437, 464), 'jsonobject.StringProperty', 'jsonobject.StringProperty', ([], {}), '()\n', (462, 464), False, 'import jsonobject\n'), ((476, 503), 'jsonobject.StringProperty', 'jsonobject.S... |
'''Main tests in API'''
import unittest
import pandas as pd
from folium.folium import Map as FoliumMap
from model.charts.maps.base import BaseMap
class BaseMapGetHeadersTest():
# class BaseMapGetHeadersTest(unittest.TestCase):
''' Test behaviours linked to fetching or changing headers from YAML options '''... | [
"pandas.DataFrame",
"model.charts.maps.base.BaseMap",
"model.charts.maps.base.BaseMap.get_headers",
"model.charts.maps.base.BaseMap.get_location_columns",
"model.charts.maps.base.BaseMap.get_au_title"
] | [((5099, 5250), 'pandas.DataFrame', 'pd.DataFrame', (["[{'cd_mun_ibge': 123456, 'cd_indicador': 1}, {'cd_mun_ibge': 234567,\n 'cd_indicador': 2}, {'cd_mun_ibge': 345678, 'cd_indicador': 3}]"], {}), "([{'cd_mun_ibge': 123456, 'cd_indicador': 1}, {'cd_mun_ibge': \n 234567, 'cd_indicador': 2}, {'cd_mun_ibge': 345678... |
import unittest
import shutil
from pathlib import Path
import pytest
from spikeinterface import extract_waveforms, WaveformExtractor
from spikeinterface.extractors import toy_example
from spikeinterface.toolkit.postprocessing import calculate_template_metrics, get_template_channel_sparsity
if hasattr(pytest, "globa... | [
"spikeinterface.extractors.toy_example",
"spikeinterface.toolkit.postprocessing.get_template_channel_sparsity",
"pathlib.Path",
"spikeinterface.extract_waveforms",
"shutil.rmtree",
"spikeinterface.WaveformExtractor.load_from_folder",
"spikeinterface.toolkit.postprocessing.calculate_template_metrics"
] | [((672, 713), 'spikeinterface.extractors.toy_example', 'toy_example', ([], {'num_segments': '(2)', 'num_units': '(10)'}), '(num_segments=2, num_units=10)\n', (683, 713), False, 'from spikeinterface.extractors import toy_example\n'), ((852, 1011), 'spikeinterface.extract_waveforms', 'extract_waveforms', (['recording', '... |
import pandas as pd
import random
def restaurant_data(r1_cuisine, r2_cuisine, r2_restaurant, r):
if r2_cuisine == r1_cuisine:
r = r + str(r2_restaurant) + "% "
elif r2_cuisine in r1_cuisine:
r = r + str(r2_restaurant) + "% "
elif r1_cuisine == 'Punjabi' and r2_cuisine ==... | [
"pandas.read_csv",
"random.randrange"
] | [((1866, 1912), 'pandas.read_csv', 'pd.read_csv', (['"""Cleaned_Indian_Food_Dataset.csv"""'], {}), "('Cleaned_Indian_Food_Dataset.csv')\n", (1877, 1912), True, 'import pandas as pd\n'), ((1923, 1949), 'pandas.read_csv', 'pd.read_csv', (['"""Cuisine.csv"""'], {}), "('Cuisine.csv')\n", (1934, 1949), True, 'import pandas ... |
import numpy as np
def parse_fibers(fiber_string) :
if fiber_string is None :
return None
fibers=[]
for sub in fiber_string.split(',') :
if sub.isdigit() :
fibers.append(int(sub))
continue
tmp = sub.split(':')
if ((len(tmp) is 2) an... | [
"numpy.array"
] | [((698, 714), 'numpy.array', 'np.array', (['fibers'], {}), '(fibers)\n', (706, 714), True, 'import numpy as np\n')] |
'''
Date: 2021-08-15 19:47:03
LastEditors: xgy
LastEditTime: 2021-08-15 20:09:44
FilePath: \code\crnn_ctc\src\callback.py
'''
"""loss callback"""
import time
from mindspore.train.callback import Callback
from .util import AverageMeter
class LossCallBack(Callback):
"""
Monitor the loss in training.
If the... | [
"time.time"
] | [((885, 896), 'time.time', 'time.time', ([], {}), '()\n', (894, 896), False, 'import time\n'), ((1312, 1323), 'time.time', 'time.time', ([], {}), '()\n', (1321, 1323), False, 'import time\n'), ((1429, 1440), 'time.time', 'time.time', ([], {}), '()\n', (1438, 1440), False, 'import time\n'), ((1368, 1379), 'time.time', '... |
from numba import jit, njit
import numpy as np
import random
import PIL.Image as Image
import timeit
Version = "0.1.7"
LearningRate = 0.1
ImageSize = 110
TargetEpochs = 20000
output_path = "D:\\jonod\\Pictures\\BackpropExperiment\\Outputs" # path to output folder, also folder with training data in it.
m... | [
"PIL.Image.new",
"numpy.multiply",
"numpy.subtract",
"timeit.default_timer",
"random.shuffle",
"numpy.power",
"numpy.zeros",
"numpy.transpose",
"numpy.asarray",
"numpy.ones"
] | [((654, 702), 'numpy.zeros', 'np.zeros', (['(ImageSize * ImageSize, 8)', 'np.float64'], {}), '((ImageSize * ImageSize, 8), np.float64)\n', (662, 702), True, 'import numpy as np\n'), ((3656, 3678), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (3676, 3678), False, 'import timeit\n'), ((2675, 2715), '... |
# Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
import numpy
import torch
import pyro
import pyro.distributions as dist
import pyro.poutine as poutine
from pyro.distributions.util import broadcast_shape
from pyro.ops.special import safe_log
def clamp(tensor, *, min=None, max=None... | [
"pyro.distributions.Categorical",
"torch.from_numpy",
"torch.stack",
"pyro.distributions.util.broadcast_shape",
"torch.nn.functional.pad",
"torch.cat",
"torch.max",
"numpy.array",
"torch.arange",
"pyro.poutine.condition",
"pyro.poutine.block",
"pyro.deterministic",
"torch.no_grad",
"pyro.p... | [((1629, 1644), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1642, 1644), False, 'import torch\n'), ((4410, 4426), 'numpy.array', 'numpy.array', (['W16'], {}), '(W16)\n', (4421, 4426), False, 'import numpy\n'), ((8634, 8663), 'torch.max', 'torch.max', (['x', '(2 * min - 1 - x)'], {}), '(x, 2 * min - 1 - x)\n', ... |
import torch
import os
from omegaconf import DictConfig
import logging
import random
import numpy as np
def validation(self, dataloader):
if self.loss_fn is None or dataloader is None:
return 0.0, 0.0
self.model.to(self.device)
self.model.eval()
loss = 0
correct = 0
tmpcnt = 0
t... | [
"os.mkdir",
"numpy.random.seed",
"logging.FileHandler",
"os.path.isdir",
"torch.manual_seed",
"torch.load",
"logging.StreamHandler",
"os.path.exists",
"torch.cuda.manual_seed",
"torch.save",
"random.seed",
"torch.no_grad",
"torch.round"
] | [((1335, 1359), 'os.path.exists', 'os.path.exists', (['filename'], {}), '(filename)\n', (1349, 1359), False, 'import os\n'), ((1524, 1547), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (1545, 1547), False, 'import logging\n'), ((1564, 1593), 'logging.FileHandler', 'logging.FileHandler', (['filena... |
from evsim.behavior_model_executor import BehaviorModelExecutor
from evsim.definition import *
class Government(BehaviorModelExecutor):
def __init__(self, instance_time, destruct_time, name, engine_name):
BehaviorModelExecutor.__init__(self, instance_time, destruct_time, name, engine_name)
self.i... | [
"evsim.behavior_model_executor.BehaviorModelExecutor.__init__"
] | [((219, 308), 'evsim.behavior_model_executor.BehaviorModelExecutor.__init__', 'BehaviorModelExecutor.__init__', (['self', 'instance_time', 'destruct_time', 'name', 'engine_name'], {}), '(self, instance_time, destruct_time, name,\n engine_name)\n', (249, 308), False, 'from evsim.behavior_model_executor import Behavio... |
import os
import time
from os.path import join as pjoin
from nibabel.tmpdirs import TemporaryDirectory
from dipy.data import get_fnames
from dipy.workflows.segment import MedianOtsuFlow
from dipy.workflows.workflow import Workflow
import numpy.testing as npt
def test_force_overwrite():
with TemporaryDirectory()... | [
"dipy.data.get_fnames",
"numpy.testing.assert_raises",
"time.sleep",
"nibabel.tmpdirs.TemporaryDirectory",
"os.path.getmtime",
"dipy.workflows.workflow.Workflow",
"os.path.join",
"dipy.workflows.segment.MedianOtsuFlow"
] | [((1452, 1462), 'dipy.workflows.workflow.Workflow', 'Workflow', ([], {}), '()\n', (1460, 1462), False, 'from dipy.workflows.workflow import Workflow\n'), ((1529, 1539), 'dipy.workflows.workflow.Workflow', 'Workflow', ([], {}), '()\n', (1537, 1539), False, 'from dipy.workflows.workflow import Workflow\n'), ((1544, 1586)... |
from collections import namedtuple, defaultdict
import time
Cell = namedtuple("Cell", ["x", "y"])
def getNeighbors(cell):
for x in range(cell.x - 1, cell.x + 2):
for y in range(cell.y - 1, cell.y + 2):
if (x, y) != (cell.x, cell.y):
yield Cell(x, y)
def getNeighborCount(boar... | [
"collections.defaultdict",
"collections.namedtuple",
"time.sleep"
] | [((68, 98), 'collections.namedtuple', 'namedtuple', (['"""Cell"""', "['x', 'y']"], {}), "('Cell', ['x', 'y'])\n", (78, 98), False, 'from collections import namedtuple, defaultdict\n'), ((346, 362), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (357, 362), False, 'from collections import namedtuple... |
from typing import Tuple
from django.conf import settings
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fast_api.v2.routers import api_router_v2
API_VERSIONS_ROUTERS = {
"v2": api_router_v2,
}
def create_application(api_versions: Tuple[str] = ("v2",)) -> FastAPI:
appli... | [
"fastapi.FastAPI"
] | [((329, 563), 'fastapi.FastAPI', 'FastAPI', ([], {'title': '"""SkillHunter API"""', 'description': '"""This is a public API for obtaining either the skills required for\n a particular job or a vacancies tailored to the resume provided.\n """', 'version': 'api_versions[0]'}), '(title=\'SkillHunter API\', d... |
# -*- coding: utf-8 -*-
"""
Microsoft-Windows-PushNotifications-Platform
GUID : 88cd9180-4491-4640-b571-e3bee2527943
"""
from construct import Int8sl, Int8ul, Int16ul, Int16sl, Int32sl, Int32ul, Int64sl, Int64ul, Bytes, Double, Float32l, Struct
from etl.utils import WString, CString, SystemTime, Guid
from etl.dtyp impo... | [
"construct.Bytes",
"construct.Struct",
"etl.parsers.etw.core.guid"
] | [((539, 644), 'construct.Struct', 'Struct', (["('FileName' / WString)", "('FunctionName' / WString)", "('LineNumber' / Int32sl)", "('ErrorCode' / Int32ul)"], {}), "('FileName' / WString, 'FunctionName' / WString, 'LineNumber' /\n Int32sl, 'ErrorCode' / Int32ul)\n", (545, 644), False, 'from construct import Int8sl, I... |
##########################################################################
#
# 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:
#
# * Red... | [
"Gaffer.Despatcher._uniqueTasks",
"Gaffer.Context",
"Gaffer.ExecutableNode.Task",
"Gaffer.Despatcher.__init__",
"IECore.registerRunTimeTyped"
] | [((2610, 2695), 'IECore.registerRunTimeTyped', 'IECore.registerRunTimeTyped', (['LocalDespatcher'], {'typeName': '"""Gaffer::LocalDespatcher"""'}), "(LocalDespatcher, typeName='Gaffer::LocalDespatcher'\n )\n", (2637, 2695), False, 'import IECore\n'), ((1936, 1968), 'Gaffer.Despatcher.__init__', 'Gaffer.Despatcher.__... |
# FROM https://github.com/python/cpython/blob/6292be7adf247589bbf03524f8883cb4cb61f3e9/Lib/typing.py
import collections
import sys
from typing import Dict, List, Tuple, Type, _GenericAlias, _SpecialForm, get_type_hints
if sys.version_info < (3, 9):
# Python 3.9 does not include `_special`, so use the function from... | [
"typing.get_args",
"typing.get_type_hints"
] | [((1232, 1244), 'typing.get_args', 'get_args', (['tp'], {}), '(tp)\n', (1240, 1244), True, 'from typing import get_args as get_args\n'), ((1832, 1858), 'typing.get_type_hints', 'get_type_hints', (['class_type'], {}), '(class_type)\n', (1846, 1858), False, 'from typing import Dict, List, Tuple, Type, _GenericAlias, _Spe... |
# -*- coding: utf-8 -*-
import os
from tempfile import TemporaryDirectory
from unittest import main
from tester.unittest.async_test_case import AsyncTestCase
from tester.plugins.copy_plugin import copy_plugin
from recc.plugin.plugin import Plugin
class PluginSimpleTestCase(AsyncTestCase):
async def setUp(self):
... | [
"unittest.main",
"tempfile.TemporaryDirectory",
"recc.plugin.plugin.Plugin",
"os.path.isfile",
"tester.plugins.copy_plugin.copy_plugin"
] | [((1202, 1208), 'unittest.main', 'main', ([], {}), '()\n', (1206, 1208), False, 'from unittest import main\n'), ((344, 364), 'tempfile.TemporaryDirectory', 'TemporaryDirectory', ([], {}), '()\n', (362, 364), False, 'from tempfile import TemporaryDirectory\n'), ((493, 546), 'tester.plugins.copy_plugin.copy_plugin', 'cop... |
#!/usr/bin/env python
#
# __COPYRIGHT__
#
# 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 use, copy, modify, merge, publish,
... | [
"TestSCons.TestSCons"
] | [((2325, 2346), 'TestSCons.TestSCons', 'TestSCons.TestSCons', ([], {}), '()\n', (2344, 2346), False, 'import TestSCons\n')] |
import urllib.request
import json
import asyncio
from random import randint
from pyrogram import filters
from wbb import app, arq
from wbb.utils.errors import capture_err
__MODULE__ = "Images"
__HELP__ = '''/cat - Get Cute Cats Images
/wall - Get Wallpapers'''
async def delete_message_with_delay(delay, message):
... | [
"wbb.arq.wall",
"random.randint",
"asyncio.sleep",
"pyrogram.filters.command"
] | [((1353, 1378), 'random.randint', 'randint', (['(0)', '(selection - 1)'], {}), '(0, selection - 1)\n', (1360, 1378), False, 'from random import randint\n'), ((328, 348), 'asyncio.sleep', 'asyncio.sleep', (['delay'], {}), '(delay)\n', (341, 348), False, 'import asyncio\n'), ((394, 416), 'pyrogram.filters.command', 'filt... |
from __future__ import unicode_literals
from django.test import TestCase
from django.urls import reverse
class TestRawFieldPruning(TestCase):
"""
Tests that endpoints can easily be
"""
def test_default_rest_framework_behavior(self):
"""
This is more of an example really, showing defa... | [
"django.urls.reverse"
] | [((359, 378), 'django.urls.reverse', 'reverse', (['"""raw-data"""'], {}), "('raw-data')\n", (366, 378), False, 'from django.urls import reverse\n')] |
import numpy as np
from typing import Dict
from sim_components.configuration import config as cfg
from sim_components.positions import Vector_2D
NUTRITIVE_VALUE = cfg.conf['food_values']['default_nutritive_value']
class Instance:
'''Standard reward type, no change to actor stats, food and poison inherit from th... | [
"sim_components.positions.Vector_2D",
"numpy.random.random"
] | [((499, 514), 'sim_components.positions.Vector_2D', 'Vector_2D', (['x', 'y'], {}), '(x, y)\n', (508, 514), False, 'from sim_components.positions import Vector_2D\n'), ((1027, 1045), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (1043, 1045), True, 'import numpy as np\n'), ((398, 416), 'numpy.random.rando... |
#!/usr/bin/python
#
# Copyright 2002-2021 Barcelona Supercomputing Center (www.bsc.es)
#
# 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
... | [
"pycompss.worker.piper.commons.executor.executor",
"os.getpid",
"storage.api.finishWorker",
"pycompss.worker.piper.cache.setup.stop_cache",
"pycompss.util.context.set_pycompss_context",
"pycompss.util.tracing.helpers.trace_mpi_worker",
"pycompss.runtime.commons.get_temporary_directory",
"pycompss.util... | [((4200, 4247), 'signal.signal', 'signal.signal', (['signal.SIGTERM', 'shutdown_handler'], {}), '(signal.SIGTERM, shutdown_handler)\n', (4213, 4247), False, 'import signal\n'), ((4312, 4362), 'signal.signal', 'signal.signal', (['signal.SIGUSR2', 'user_signal_handler'], {}), '(signal.SIGUSR2, user_signal_handler)\n', (4... |
# relaxed_sync.py COPYRIGHT Fujitsu Limited 2021
import torch
import torch.distributed as dist
from torch.autograd import Variable
from apex.parallel import DistributedDataParallel as DDP
from apex.parallel.distributed import flatten, unflatten, split_half_float_double
from apex.multi_tensor_apply import multi_tensor_... | [
"torch.distributed.all_gather",
"torch.distributed.get_backend",
"torch.distributed.get_world_size",
"apex.parallel.distributed.unflatten",
"torch.utils.data.DataLoader",
"torch.distributed.get_rank",
"torch.cuda.FloatTensor",
"torch.utils.data.distributed.DistributedSampler",
"apex.parallel.distrib... | [((5786, 5838), 'torch.cuda.Event', 'torch.cuda.Event', ([], {'enable_timing': '(True)', 'blocking': '(False)'}), '(enable_timing=True, blocking=False)\n', (5802, 5838), False, 'import torch\n'), ((5864, 5916), 'torch.cuda.Event', 'torch.cuda.Event', ([], {'enable_timing': '(True)', 'blocking': '(False)'}), '(enable_ti... |
# coding=utf-8
# Copyright 2020 The TensorFlow Datasets Authors and the HuggingFace Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LI... | [
"datasets.Version",
"datasets.Value",
"datasets.logging.get_logger",
"datasets.SplitGenerator"
] | [((821, 858), 'datasets.logging.get_logger', 'datasets.logging.get_logger', (['__name__'], {}), '(__name__)\n', (848, 858), False, 'import datasets\n'), ((9302, 9379), 'datasets.SplitGenerator', 'datasets.SplitGenerator', ([], {'name': 'split', 'gen_kwargs': "{'filepath': downloaded_path}"}), "(name=split, gen_kwargs={... |
#!/usr/bin/env python
import rospy
from geometry_msgs.msg import Twist
#PI = 3.1415926535897
toRAD = 0.0174533
def rotate():
# Starts a new node
rospy.init_node('tb3_cleaner', anonymous=True)
pub = rospy.Publisher('/cmd_vel', Twist, queue_size=10)
msg = Twist()
# Receiveing the user's input
p... | [
"rospy.Time.now",
"rospy.Publisher",
"rospy.sleep",
"geometry_msgs.msg.Twist",
"rospy.init_node",
"rospy.spin",
"rospy.Duration"
] | [((155, 201), 'rospy.init_node', 'rospy.init_node', (['"""tb3_cleaner"""'], {'anonymous': '(True)'}), "('tb3_cleaner', anonymous=True)\n", (170, 201), False, 'import rospy\n'), ((212, 261), 'rospy.Publisher', 'rospy.Publisher', (['"""/cmd_vel"""', 'Twist'], {'queue_size': '(10)'}), "('/cmd_vel', Twist, queue_size=10)\n... |
#!/usr/bin/env python
# <NAME>
# <EMAIL>
#
########################################################################
# Copyright 2012 Mandiant
# Copyright 2014 FireEye
#
# Mandiant licenses this file to you under the Apache License, Version
# 2.0 (the "License"); you may not use this file except in compliance with the
... | [
"idaapi.require"
] | [((1426, 1449), 'idaapi.require', 'idaapi.require', (['"""flare"""'], {}), "('flare')\n", (1440, 1449), False, 'import idaapi\n'), ((1458, 1503), 'idaapi.require', 'idaapi.require', (['"""flare.shellcode_hash_search"""'], {}), "('flare.shellcode_hash_search')\n", (1472, 1503), False, 'import idaapi\n')] |
import json
import time
import redis
__all__ = ['RedisSyncer']
class RedisSyncer(object):
def __init__(self, logger, channel, conn_url='redis://localhost:6379/0'):
self._logger = logger
self._channel = channel
self._conn = redis.from_url(conn_url)
def pub(self, threshold, src, dst, ... | [
"redis.from_url",
"json.dumps",
"time.sleep"
] | [((255, 279), 'redis.from_url', 'redis.from_url', (['conn_url'], {}), '(conn_url)\n', (269, 279), False, 'import redis\n'), ((402, 478), 'json.dumps', 'json.dumps', (["{'threshold': threshold, 'src': src, 'dst': dst, 'count': count}"], {}), "({'threshold': threshold, 'src': src, 'dst': dst, 'count': count})\n", (412, 4... |
#!/usr/bin/env python
import os
import xarray as xr
import pprint
import pycurl
import itertools
from joblib import Parallel, delayed
import click
try:
from cdo import Cdo
cdo = Cdo()
cdo.debug = True
except ImportError:
cdo = None
pp = pprint.PrettyPrinter(indent=2)
loca_root = 'ftp://gdo-dcp.ucllnl... | [
"os.remove",
"os.makedirs",
"os.stat",
"os.path.basename",
"os.path.dirname",
"xarray.open_dataset",
"click.option",
"click.command",
"joblib.Parallel",
"pprint.PrettyPrinter",
"os.path.isfile",
"itertools.product",
"cdo.Cdo",
"pycurl.Curl",
"os.path.join",
"joblib.delayed"
] | [((255, 285), 'pprint.PrettyPrinter', 'pprint.PrettyPrinter', ([], {'indent': '(2)'}), '(indent=2)\n', (275, 285), False, 'import pprint\n'), ((995, 1010), 'click.command', 'click.command', ([], {}), '()\n', (1008, 1010), False, 'import click\n'), ((1012, 1084), 'click.option', 'click.option', (['"""--kind"""'], {'defa... |
# This file is part of the Indico plugins.
# Copyright (C) 2002 - 2022 CERN
#
# The Indico plugins are free software; you can redistribute
# them and/or modify them under the terms of the MIT License;
# see the LICENSE file for more details.
from indico.core import signals
from indico.util.i18n import make_bound_gette... | [
"indico.util.i18n.make_bound_gettext"
] | [((329, 359), 'indico.util.i18n.make_bound_gettext', 'make_bound_gettext', (['"""livesync"""'], {}), "('livesync')\n", (347, 359), False, 'from indico.util.i18n import make_bound_gettext\n')] |
# -*- coding: utf-8 -*-
from setuptools import setup
version = '0.1'
setup(
name = 'pysocks5',
version = version,
py_packages = ['pysocks5'],
# entry_points = {
# 'console_scripts': [
# 'xxx = xxx:main',
# ]
# },
# install_requires = ['requests==2.7.0', 'certifi==2015... | [
"setuptools.setup"
] | [((72, 506), 'setuptools.setup', 'setup', ([], {'name': '"""pysocks5"""', 'version': 'version', 'py_packages': "['pysocks5']", 'description': '"""pysocks5: A lightweight forward and backward socks5 proxy server written with python."""', 'author': '"""pandolia"""', 'author_email': '"""<EMAIL>"""', 'url': '"""https://git... |
__doc__ = """
Title: ArcPy Logging Helper
Description: A helper function to setup the ArcPy logging on the logging root.
Usage:
"""
import logging
from .arcpylogger import ArcpyMessageHandler
def setup_logging(log_file=None, level=logging.DEBUG):
""" Add an ArcpyMessageHandler to the root logger
:param ... | [
"logging.basicConfig",
"logging.getLogger"
] | [((1046, 1065), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (1063, 1065), False, 'import logging\n'), ((629, 787), 'logging.basicConfig', 'logging.basicConfig', ([], {'filename': 'log_file', 'filemode': '"""w"""', 'format': '"""%(asctime)s %(levelname)-8s %(message)s"""', 'datefmt': '"""%a, %d %b %Y %H:... |
#import cv2
import numpy as np
import os
import base64
from PIL import Image, ImageDraw
from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = os.path.join(os.path.dirname(__file__), "google_cloud_vision.json")
DISCOVERY_URL='https://{a... | [
"numpy.average",
"os.path.dirname",
"oauth2client.client.GoogleCredentials.get_application_default",
"PIL.Image.open",
"numpy.fabs",
"numpy.linalg.norm",
"numpy.asmatrix",
"PIL.ImageDraw.Draw",
"googleapiclient.discovery.build"
] | [((239, 264), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (254, 264), False, 'import os\n'), ((423, 466), 'oauth2client.client.GoogleCredentials.get_application_default', 'GoogleCredentials.get_application_default', ([], {}), '()\n', (464, 466), False, 'from oauth2client.client import Goog... |
from plugin.core.libraries.helpers.arm import ArmHelper
def test_lookup():
assert ArmHelper.lookup({}, {}) == (None, None, None)
assert ArmHelper.lookup({0: {}}, {}) == (None, None, None)
assert ArmHelper.lookup({
0: {
'cpu_implementer': '0x41',
'cpu_part': '0xB02'
... | [
"plugin.core.libraries.helpers.arm.ArmHelper.lookup",
"plugin.core.libraries.helpers.arm.ArmHelper.cpu_identifier"
] | [((88, 112), 'plugin.core.libraries.helpers.arm.ArmHelper.lookup', 'ArmHelper.lookup', (['{}', '{}'], {}), '({}, {})\n', (104, 112), False, 'from plugin.core.libraries.helpers.arm import ArmHelper\n'), ((146, 177), 'plugin.core.libraries.helpers.arm.ArmHelper.lookup', 'ArmHelper.lookup', (['{(0): {}}', '{}'], {}), '({(... |
__all__ = ['OnnxSlice']
from typing import List
from typing import Optional
from typing import Tuple
from typing import Union
import numpy as np
import torch
import torch._C as torch_C
from torch import nn
from onnx2torch.node_converters.registry import add_converter
from onnx2torch.onnx_graph import OnnxGraph
from ... | [
"torch.flip",
"onnx2torch.node_converters.registry.add_converter",
"torch.onnx.is_in_onnx_export",
"onnx2torch.utils.common.onnx_mapping_from_node"
] | [((3544, 3592), 'onnx2torch.node_converters.registry.add_converter', 'add_converter', ([], {'operation_type': '"""Slice"""', 'version': '(9)'}), "(operation_type='Slice', version=9)\n", (3557, 3592), False, 'from onnx2torch.node_converters.registry import add_converter\n'), ((4017, 4066), 'onnx2torch.node_converters.re... |
"""Controller and routes for ."""
import os
import logger
from flask import request, jsonify
# from flask_cors import cross_origin
from api import app, mongo
from api.schemas import validate_location
from api.decorators import roles_required
from flask_jwt_extended import (jwt_required, get_jwt_identity)
ROOT_PATH = o... | [
"flask_jwt_extended.get_jwt_identity",
"os.environ.get",
"flask.jsonify",
"api.app.route",
"api.schemas.validate_location",
"api.decorators.roles_required",
"os.path.join",
"flask.request.get_json"
] | [((319, 346), 'os.environ.get', 'os.environ.get', (['"""ROOT_PATH"""'], {}), "('ROOT_PATH')\n", (333, 346), False, 'import os\n'), ((485, 524), 'api.app.route', 'app.route', (['"""/location"""'], {'methods': "['GET']"}), "('/location', methods=['GET'])\n", (494, 524), False, 'from api import app, mongo\n'), ((693, 736)... |
import numpy as np
from ConfigSpace import ConfigurationSpace, UniformFloatHyperparameter, CategoricalHyperparameter
class CountingOnes(object):
"""
Proposed by BOHB
"""
def __init__(self, n_cat, n_cont, max_samples=729, seed=47, **kwargs):
self.dim = n_cat+n_cont
self.n_cat = n_cat
... | [
"ConfigSpace.ConfigurationSpace",
"numpy.sum",
"ConfigSpace.UniformFloatHyperparameter",
"ConfigSpace.CategoricalHyperparameter",
"numpy.random.RandomState"
] | [((485, 512), 'numpy.random.RandomState', 'np.random.RandomState', (['seed'], {}), '(seed)\n', (506, 512), True, 'import numpy as np\n'), ((1048, 1068), 'ConfigSpace.ConfigurationSpace', 'ConfigurationSpace', ([], {}), '()\n', (1066, 1068), False, 'from ConfigSpace import ConfigurationSpace, UniformFloatHyperparameter,... |
# -*- coding: utf-8 -*-
"""
Created on Mon May 3 20:04:24 2021
@author: <NAME>
Class ImageProducer: This class is capable of getting the
Image srtameing from the first camera
detected in the system.
This image will be displayed and the
... | [
"cv2.waitKey",
"cv2.imshow",
"time.sleep",
"cv2.VideoCapture",
"numpy.random.randint",
"cv2.destroyAllWindows"
] | [((772, 791), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (788, 791), False, 'import cv2\n'), ((3404, 3427), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (3425, 3427), False, 'import cv2\n'), ((2671, 2686), 'time.sleep', 'time.sleep', (['(0.5)'], {}), '(0.5)\n', (2681, 2686), ... |
#!/usr/bin/env python3
import json
import os
import shutil
import struct
import threading
import time
from coco_helper import (load_preprocessed_batch, image_filenames, original_w_h, class_labels,
MODEL_DATA_LAYOUT, MODEL_COLOURS_BGR, MODEL_INPUT_DATA_TYPE, MODEL_DATA_TYPE, MODEL_USE_DLA, MODEL_MAX_BATCH_SIZE,
... | [
"threading.Thread",
"os.mkdir",
"json.dump",
"os.getcwd",
"os.path.isdir",
"coco_helper.load_preprocessed_batch",
"numpy.asarray",
"struct.pack",
"time.time",
"time.sleep",
"numpy.split",
"numpy.mean",
"numpy.array",
"os.path.splitext",
"shutil.rmtree",
"os.path.join",
"os.getenv",
... | [((854, 912), 'os.getenv', 'os.getenv', (['"""ML_MODEL_SKIPS_ORIGINAL_DATASET_CLASSES"""', 'None'], {}), "('ML_MODEL_SKIPS_ORIGINAL_DATASET_CLASSES', None)\n", (863, 912), False, 'import os\n'), ((1121, 1159), 'os.getenv', 'os.getenv', (['"""CK_TRANSFER_MODE"""', '"""numpy"""'], {}), "('CK_TRANSFER_MODE', 'numpy')\n", ... |
from tqdm.notebook import tqdm
import numpy as np
import torch
from ImputationDataLoader import ImputationDataLoader
import copy
import util
from util import calc_rmse
from InterpRealNVP import InterpRealNVP
from LatentToLatentApprox import LatentToLatentApprox
import itertools
# A class to impute values by MCFlow
c... | [
"ImputationDataLoader.ImputationDataLoader",
"itertools.chain.from_iterable",
"torch.utils.data.DataLoader",
"util.endtoend_train",
"copy.copy",
"torch.cuda.is_available",
"util.calc_rmse",
"util.init_flow_model",
"torch.no_grad"
] | [((6400, 6427), 'ImputationDataLoader.ImputationDataLoader', 'ImputationDataLoader', (['array'], {}), '(array)\n', (6420, 6427), False, 'from ImputationDataLoader import ImputationDataLoader\n'), ((6450, 6529), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['ldr'], {'batch_size': '(32)', 'shuffle': '(F... |
from polytropes import monotrope
from polytropes import polytrope
import units as cgs
##################################################
#SLy (Skyrme) crust
KSLy = [6.80110e-9, 1.06186e-6, 5.32697e1, 3.99874e-8] #Scaling constants
GSLy = [1.58425, 1.28733, 0.62223, 1.35692] #polytropic indices
RSLy = [1.e4, 2.44034e7... | [
"polytropes.polytrope",
"polytropes.monotrope"
] | [((790, 814), 'polytropes.polytrope', 'polytrope', (['tropes', 'trans'], {}), '(tropes, trans)\n', (799, 814), False, 'from polytropes import polytrope\n'), ((449, 477), 'polytropes.monotrope', 'monotrope', (['(K * cgs.c ** 2)', 'G'], {}), '(K * cgs.c ** 2, G)\n', (458, 477), False, 'from polytropes import monotrope\n'... |
import pytest
from opath import ObjChain, ChainList
# TODO: better testing for push_up = False
def test_chain_list():
x = ["the", "cow", "jumped"]
x = ChainList(x)
print(x)
list(x)
x.strip()
assert [y.replace('e', 'a') for y in x] == list(x.replace("e", "a"))
empty = ChainList([])
a... | [
"opath.ChainList",
"pytest.raises",
"pytest.fixture",
"opath.ObjChain"
] | [((711, 747), 'pytest.fixture', 'pytest.fixture', ([], {'params': '[True, False]'}), '(params=[True, False])\n', (725, 747), False, 'import pytest\n'), ((163, 175), 'opath.ChainList', 'ChainList', (['x'], {}), '(x)\n', (172, 175), False, 'from opath import ObjChain, ChainList\n'), ((301, 314), 'opath.ChainList', 'Chain... |
"""
The :mod:`fatf.utils.data.datasets` module holds examples of data sets.
The iris data set is returned as a classic numpy array, whereas the health
records data set is a structured numpy array.
"""
# Author: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# License: new BSD
import csv
import os
from typing import Dic... | [
"fatf.utils.array.validation.is_1d_array",
"csv.reader",
"os.path.dirname",
"fatf.utils.array.validation.is_2d_array",
"numpy.dtype",
"numpy.genfromtxt",
"numpy.array",
"fatf.utils.tools.at_least_verion",
"numpy.version.version.split",
"fatf.utils.array.validation.is_structured_array",
"os.path.... | [((578, 622), 'fatf.utils.tools.at_least_verion', 'fut.at_least_verion', (['[1, 14]', '_NUMPY_VERSION'], {}), '([1, 14], _NUMPY_VERSION)\n', (597, 622), True, 'import fatf.utils.tools as fut\n'), ((650, 675), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (665, 675), False, 'import os\n'), ((... |
import torch
torch.backends.cudnn.benchmark = True
import torch.nn.functional as F
from .iqn import IQN
from .utils import stable_scaled_log_softmax, stable_softmax
class M_IQN(IQN):
def __init__(self, alpha=0.9, tau=0.03, l_0=-1, **kwargs):
super(M_IQN, self).__init__(**kwargs)
self.alpha = al... | [
"torch.eye",
"torch.where",
"torch.argmax",
"torch.broadcast_tensors",
"torch.clip",
"torch.max",
"torch.unsqueeze",
"torch.no_grad",
"torch.sum",
"torch.min",
"torch.transpose"
] | [((892, 939), 'torch.eye', 'torch.eye', (['self.action_size'], {'device': 'self.device'}), '(self.action_size, device=self.device)\n', (901, 939), False, 'import torch\n'), ((1103, 1118), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1116, 1118), False, 'import torch\n'), ((1409, 1452), 'torch.argmax', 'torch.ar... |
#!/usr/bin/env python3
import argparse
import base64
import json
import math
import threading
import time
import tkinter as tk
import zlib
from tkinter import BOTH, BOTTOM, END, LEFT, RAISED, RIGHT, TOP, N, Text, X
from tkinter.ttk import Button, Entry, Frame, Label, LabelFrame, Style
import numpy as np
import pyaudio... | [
"tkinter.ttk.Label",
"argparse.ArgumentParser",
"numpy.zeros",
"pyaudio.PyAudio",
"tkinter.Tk",
"tkinter.ttk.LabelFrame"
] | [((3687, 3694), 'tkinter.Tk', 'tk.Tk', ([], {}), '()\n', (3692, 3694), True, 'import tkinter as tk\n'), ((3944, 3969), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (3967, 3969), False, 'import argparse\n'), ((818, 862), 'tkinter.ttk.LabelFrame', 'LabelFrame', (['self'], {'text': '"""Words you... |
import random
import re
import socket
from omniduct.utils.debug import logger
def is_local_port_free(local_port):
"""
Checks if local port is free.
Parameters
----------
local_port : int
Local port to check.
Returns
-------
out : boolean
Whether local port is free.
... | [
"random.shuffle",
"socket.socket",
"re.compile"
] | [((335, 350), 'socket.socket', 'socket.socket', ([], {}), '()\n', (348, 350), False, 'import socket\n'), ((640, 655), 'socket.socket', 'socket.socket', ([], {}), '()\n', (653, 655), False, 'import socket\n'), ((857, 906), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET... |
# Generated by Django 3.1.7 on 2021-04-15 21:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("gtfs", "0015_add_fare_extra_attributes"),
]
operations = [
migrations.AddField(
model_name="fare",
name="routes",
... | [
"django.db.models.ManyToManyField"
] | [((336, 462), 'django.db.models.ManyToManyField', 'models.ManyToManyField', ([], {'blank': '(True)', 'related_name': '"""fares"""', 'through': '"""gtfs.FareRule"""', 'to': '"""gtfs.Route"""', 'verbose_name': '"""routes"""'}), "(blank=True, related_name='fares', through=\n 'gtfs.FareRule', to='gtfs.Route', verbose_na... |
"""
Prepare training and testing datasets as CSV dictionaries
Created on 11/26/2018
@author: RH
"""
import os
import pandas as pd
import sklearn.utils as sku
import numpy as np
# get all full paths of images
def image_ids_in(root_dir, ignore=['.DS_Store','dict.csv', 'all.csv']):
ids = []
for id in os.listdi... | [
"pandas.DataFrame",
"os.mkdir",
"pandas.read_csv",
"os.path.isdir",
"Cutter.cut",
"sklearn.utils.shuffle",
"pandas.concat",
"os.listdir",
"numpy.random.shuffle"
] | [((311, 331), 'os.listdir', 'os.listdir', (['root_dir'], {}), '(root_dir)\n', (321, 331), False, 'import os\n'), ((1019, 1076), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['slide', 'level', 'path', 'label']"}), "(columns=['slide', 'level', 'path', 'label'])\n", (1031, 1076), True, 'import pandas as pd\n'), (... |
# Copyright 2013 <NAME>
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softwa... | [
"unittest.main"
] | [((10742, 10757), 'unittest.main', 'unittest.main', ([], {}), '()\n', (10755, 10757), False, 'import unittest\n')] |
#!/usr/bin/env python
from constructs import Construct
from cdk8s import App, Chart
class MyChart(Chart):
def __init__(self, scope: Construct, id: str):
super().__init__(scope, id)
# define resources here
app = App()
MyChart(app, "{{ $base }}")
app.synth()
| [
"cdk8s.App"
] | [((236, 241), 'cdk8s.App', 'App', ([], {}), '()\n', (239, 241), False, 'from cdk8s import App, Chart\n')] |
"""
This script extracts number and string
values from API.java and writes them to
api.json so they can be used in JS.
"""
from json import dump
from re import findall, MULTILINE
f = open("API.java", "r")
c = f.read()
f.close()
result = {}
for m in findall(r"(int|long) ([A-Z_0-9]+) = ([0-9]+);$", c, MULTILINE):
... | [
"re.findall"
] | [((252, 313), 're.findall', 'findall', (['"""(int|long) ([A-Z_0-9]+) = ([0-9]+);$"""', 'c', 'MULTILINE'], {}), "('(int|long) ([A-Z_0-9]+) = ([0-9]+);$', c, MULTILINE)\n", (259, 313), False, 'from re import findall, MULTILINE\n'), ((354, 418), 're.findall', 'findall', (['"""String ([A-Z_0-9]+) = \\\\"([^\\\\"]+)\\\\";$"... |
# TuyaPower Module
# Python module to pull power and state data from Tuya WiFi smart devices
#
# Author: <NAME>
# For more information see https://github.com/jasonacox/powermonitor
#
# Functions and Usage
# (on, w, mA, V, err) = tuyapower.deviceInfo(id, ip, key, vers)
# tuyapower.devicePrint(id, ip, key, vers)
# ... | [
"datetime.datetime.utcnow",
"pytuya.OutletDevice",
"logging.getLogger",
"time.sleep"
] | [((965, 992), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (982, 992), False, 'import logging\n'), ((1343, 1369), 'datetime.datetime.utcnow', 'datetime.datetime.utcnow', ([], {}), '()\n', (1367, 1369), False, 'import datetime\n'), ((4683, 4709), 'datetime.datetime.utcnow', 'datetime.dat... |
from __future__ import print_function, division
import os,unittest
from pyscf.nao import system_vars_c, prod_basis_c, tddft_iter_c
from numpy import allclose, float32, einsum
dname = os.path.dirname(os.path.abspath(__file__))
sv = system_vars_c().init_siesta_xml(label='water', cd=dname)
pb = prod_basis_c().init_prod_b... | [
"unittest.main",
"os.path.abspath",
"pyscf.nao.system_vars_c",
"numpy.allclose",
"numpy.einsum",
"pyscf.nao.tddft_iter_c",
"pyscf.nao.prod_basis_c"
] | [((200, 225), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (215, 225), False, 'import os, unittest\n'), ((1970, 1985), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1983, 1985), False, 'import os, unittest\n'), ((232, 247), 'pyscf.nao.system_vars_c', 'system_vars_c', ([], {}), '()\n'... |
# -*- coding: utf-8 -*-
# *****************************************************************************
# NICOS, the Networked Instrument Control System of the MLZ
# Copyright (c) 2009-2022 by the NICOS contributors (see AUTHORS)
#
# This program is free software; you can redistribute it and/or modify it under
# the t... | [
"ast.literal_eval",
"nicos.guisupport.widget.PropDef",
"nicos.guisupport.led.ClickableOutputLed.mousePressEvent",
"nicos.guisupport.led.ClickableOutputLed.__init__"
] | [((2143, 2192), 'nicos.guisupport.widget.PropDef', 'PropDef', (['"""toState"""', 'str', '"""1"""', '"""Target for action"""'], {}), "('toState', str, '1', 'Target for action')\n", (2150, 2192), False, 'from nicos.guisupport.widget import PropDef\n'), ((1412, 1465), 'nicos.guisupport.led.ClickableOutputLed.__init__', 'C... |
import numpy as np
from pylot.utils import Location, Rotation, Transform
def create_rgb_camera_setup(camera_name,
camera_location,
width,
height,
fov=90):
"""Creates an RGBCameraSetup instance with the... | [
"pylot.utils.Transform",
"pylot.utils.Rotation",
"numpy.identity",
"numpy.tan",
"numpy.array",
"pylot.utils.Location"
] | [((4923, 4933), 'pylot.utils.Rotation', 'Rotation', ([], {}), '()\n', (4931, 4933), False, 'from pylot.utils import Location, Rotation, Transform\n'), ((5069, 5098), 'pylot.utils.Transform', 'Transform', (['left_loc', 'rotation'], {}), '(left_loc, rotation)\n', (5078, 5098), False, 'from pylot.utils import Location, Ro... |
# -*- coding: utf-8 -*-
""" Custom command definitions for the project. """
from __future__ import absolute_import, unicode_literals
from peltak.commands import root_cli, click
@root_cli.command('hello-world')
def hello_world():
""" Hello world command. """
print('Hello, World!')
@root_cli.command('lint')
... | [
"peltak.commands.click.Path",
"peltak.commands.click.option",
"peltak.commands.root_cli.command",
"custom_commands_logic.check",
"peltak.core.log.info"
] | [((181, 212), 'peltak.commands.root_cli.command', 'root_cli.command', (['"""hello-world"""'], {}), "('hello-world')\n", (197, 212), False, 'from peltak.commands import root_cli, click\n'), ((295, 319), 'peltak.commands.root_cli.command', 'root_cli.command', (['"""lint"""'], {}), "('lint')\n", (311, 319), False, 'from p... |
import json
from telebot import types
from collections import defaultdict
from utilities import download_picture
import config
import os
import universal_reply as ureply
from copy import deepcopy
class QuizQuestion:
def __init__(self, name, question_dict, last=False, first=False, parse_mode='Markdown', tick_symbo... | [
"copy.deepcopy",
"json.load",
"utilities.download_picture",
"telebot.types.KeyboardButton",
"telebot.types.ReplyKeyboardMarkup",
"collections.defaultdict",
"os.path.join"
] | [((3555, 3623), 'telebot.types.ReplyKeyboardMarkup', 'types.ReplyKeyboardMarkup', ([], {'row_width': 'row_width', 'resize_keyboard': '(True)'}), '(row_width=row_width, resize_keyboard=True)\n', (3580, 3623), False, 'from telebot import types\n'), ((3761, 3811), 'telebot.types.KeyboardButton', 'types.KeyboardButton', ([... |
#!/usr/bin/python
import os
for kernel in ['plain', 'blas', 'block4', 'block8', 'block16', 'block32', 'block64']:
for k in range(8,12):
cmd = './gemm ' + str(2**k) + ' 1 ' + kernel
os.system(cmd)
| [
"os.system"
] | [((203, 217), 'os.system', 'os.system', (['cmd'], {}), '(cmd)\n', (212, 217), False, 'import os\n')] |
from foundations_rest_api.v2beta.models.property_model import PropertyModel
class Job(PropertyModel):
job_id = PropertyModel.define_property()
user = PropertyModel.define_property()
project = PropertyModel.define_property()
job_parameters = PropertyModel.define_property()
output_metrics = Propert... | [
"foundations_rest_api.global_state.JobDataRedis.get_all_jobs_data",
"foundations_rest_api.utils.is_string",
"foundations_rest_api.v2beta.models.property_model.PropertyModel.define_property",
"datetime.datetime.utcfromtimestamp",
"foundations_rest_api.v2beta.models.extract_type.extract_type",
"datetime.dat... | [((118, 149), 'foundations_rest_api.v2beta.models.property_model.PropertyModel.define_property', 'PropertyModel.define_property', ([], {}), '()\n', (147, 149), False, 'from foundations_rest_api.v2beta.models.property_model import PropertyModel\n'), ((161, 192), 'foundations_rest_api.v2beta.models.property_model.Propert... |
#!/usr/bin/env python
import setuptools
setuptools.setup(
setup_requires=['setuptools_scm'],
use_scm_version=True,
)
| [
"setuptools.setup"
] | [((41, 114), 'setuptools.setup', 'setuptools.setup', ([], {'setup_requires': "['setuptools_scm']", 'use_scm_version': '(True)'}), "(setup_requires=['setuptools_scm'], use_scm_version=True)\n", (57, 114), False, 'import setuptools\n')] |
import torch
import torch.nn as nn
#
# Loss Functions
#
class RootedDependencyLoss(nn.Module):
def __init__(self):
super(RootedDependencyLoss, self).__init__()
# set up spatial loss
self._distance_loss = DependencyDistanceLoss()
# set up label loss (ignore -1 padding labels)
self._label_loss = torch.nn.Cr... | [
"torch.flatten",
"torch.nn.CrossEntropyLoss",
"torch.abs",
"torch.sum"
] | [((309, 351), 'torch.nn.CrossEntropyLoss', 'torch.nn.CrossEntropyLoss', ([], {'ignore_index': '(-1)'}), '(ignore_index=-1)\n', (334, 351), False, 'import torch\n'), ((796, 852), 'torch.flatten', 'torch.flatten', (['pred_label_logits'], {'start_dim': '(0)', 'end_dim': '(1)'}), '(pred_label_logits, start_dim=0, end_dim=1... |
from PropertiesCanvas import PropertiesCanvas
from PropertiesCanvas import PropertiesObserver
import cad
import ToolImage
import wx
EXTRA_TOOLBAR_HEIGHT = 7
class InputModeObserver(PropertiesObserver):
def __init__(self, window):
PropertiesObserver.__init__(self, window)
def OnSelectionChange... | [
"cad.GetSelectedObjects",
"wx.Bitmap",
"cad.RegisterObserver",
"ToolImage.GetBitmapSize",
"PropertiesCanvas.PropertiesObserver.__init__",
"cad.GetInputMode",
"cad.MessageBox",
"PropertiesCanvas.PropertiesCanvas.__init__",
"wx.ToolBar",
"wx.GetApp"
] | [((244, 285), 'PropertiesCanvas.PropertiesObserver.__init__', 'PropertiesObserver.__init__', (['self', 'window'], {}), '(self, window)\n', (271, 285), False, 'from PropertiesCanvas import PropertiesObserver\n'), ((375, 399), 'cad.GetSelectedObjects', 'cad.GetSelectedObjects', ([], {}), '()\n', (397, 399), False, 'impor... |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from config import Config
from flask_bootstrap import Bootstrap
from flask_cors import CORS
from flask_login import LoginManager
app = Flask(__name__)
app.config.from_object(Config)
supported = app.config["SUPPORTED_LANGU... | [
"flask_cors.CORS",
"flask.Flask",
"flask_sqlalchemy.SQLAlchemy",
"flask_migrate.Migrate",
"flask_login.LoginManager",
"flask_bootstrap.Bootstrap"
] | [((234, 249), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (239, 249), False, 'from flask import Flask\n'), ((339, 353), 'flask_bootstrap.Bootstrap', 'Bootstrap', (['app'], {}), '(app)\n', (348, 353), False, 'from flask_bootstrap import Bootstrap\n'), ((359, 374), 'flask_sqlalchemy.SQLAlchemy', 'SQLAlche... |
import numpy as np
from tqdm import trange, tqdm
import tensorflow as tf
from flearn.optimizer.pgd import PerturbedGradientDescent
from flearn.utils.tf_utils import process_grad, process_sparse_grad
from flearn.models.client_pd import Client_PD
from flearn.utils.model_utils import Metrics
from flearn.utils.utils impo... | [
"flearn.utils.utils.History",
"tqdm.tqdm.write",
"flearn.utils.tf_utils.process_grad",
"numpy.random.seed",
"flearn.models.client_pd.Client_PD",
"numpy.sum",
"tensorflow.reset_default_graph",
"numpy.asarray",
"numpy.square",
"numpy.zeros",
"numpy.arange",
"flearn.optimizer.pgd.PerturbedGradien... | [((795, 819), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (817, 819), True, 'import tensorflow as tf\n'), ((3012, 3036), 'numpy.zeros', 'np.zeros', (['self.model_len'], {}), '(self.model_len)\n', (3020, 3036), True, 'import numpy as np\n'), ((4726, 4748), 'numpy.arange', 'np.arange', (... |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
class AcademicEarthCourseIE(InfoExtractor):
_VALID_URL = r'^https?://(?:www\.)?academicearth\.org/playlists/(?P<id>[^?#/]+)'
IE_NAME = 'AcademicEarth:Course'
_TEST = {
'url': 'http://academicearth.org/... | [
"re.findall"
] | [((1067, 1166), 're.findall', 're.findall', (['"""<li class="lecture-preview">\\\\s*?<a target="_blank" href="([^"]+)">"""', 'webpage'], {}), '(\n \'<li class="lecture-preview">\\\\s*?<a target="_blank" href="([^"]+)">\',\n webpage)\n', (1077, 1166), False, 'import re\n')] |
import torch
import torch.nn.functional as F
import numpy as np
from tqdm import tqdm
from sklearn.metrics import roc_curve
from scipy.optimize import brentq
from scipy.interpolate import interp1d
from sklearn.metrics import confusion_matrix
from collections import OrderedDict
from utils import *
from metric import c... | [
"tqdm.tqdm",
"numpy.sum",
"numpy.zeros",
"torch.nn.functional.softmax",
"numpy.mean",
"numpy.array",
"torch.set_grad_enabled",
"collections.OrderedDict",
"sklearn.metrics.confusion_matrix",
"metric.calculate_per_class_lwlrap",
"numpy.concatenate"
] | [((7016, 7046), 'numpy.concatenate', 'np.concatenate', (['y_true'], {'axis': '(0)'}), '(y_true, axis=0)\n', (7030, 7046), True, 'import numpy as np\n'), ((7060, 7090), 'numpy.concatenate', 'np.concatenate', (['y_pred'], {'axis': '(0)'}), '(y_pred, axis=0)\n', (7074, 7090), True, 'import numpy as np\n'), ((7104, 7134), ... |
import os
import subprocess
import sys
if __name__ == "__main__":
"""Examine status of bags listed in bagnames_file which are
stored under bags_dir without subfolders.""" # pylint: disable=pointless-string-statement
if len(sys.argv) < 3:
print('Usage: {} bagnames_file bags_dir'.format(sys.argv[0]... | [
"subprocess.check_output",
"os.path.join",
"sys.exit",
"os.path.basename"
] | [((331, 342), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (339, 342), False, 'import sys\n'), ((864, 985), 'subprocess.check_output', 'subprocess.check_output', (["['rosbag', 'info', bagname]"], {'stdin': 'None', 'stderr': 'None', 'shell': '(False)', 'universal_newlines': '(False)'}), "(['rosbag', 'info', bagname],... |
# Title: 제곱ㄴㄴ수
# Link: https://www.acmicpc.net/problem/1016
import math
import sys
sys.setrecursionlimit(10 ** 6)
def read_list_int():
return list(map(int, sys.stdin.readline().strip().split(' ')))
def read_single_int():
return int(sys.stdin.readline().strip())
def num_nn_square(minimum, maximum):
nu... | [
"sys.setrecursionlimit",
"sys.stdin.readline"
] | [((84, 114), 'sys.setrecursionlimit', 'sys.setrecursionlimit', (['(10 ** 6)'], {}), '(10 ** 6)\n', (105, 114), False, 'import sys\n'), ((245, 265), 'sys.stdin.readline', 'sys.stdin.readline', ([], {}), '()\n', (263, 265), False, 'import sys\n'), ((163, 183), 'sys.stdin.readline', 'sys.stdin.readline', ([], {}), '()\n',... |
import json
import multiprocessing
import pickle
import pandas as pd
from setting import *
from utils.preprocess.data import *
from utils.vsqxt import vsqx
def __dataset_load():
# 读取2020json source
with open(dataset_source_file_path[0], 'r', encoding='utf-8') as f:
source = json.load(f)
data... | [
"pandas.DataFrame",
"pickle.dump",
"json.load",
"pandas.read_csv",
"pickle.load",
"multiprocessing.cpu_count"
] | [((576, 616), 'pandas.read_csv', 'pd.read_csv', (['dataset_source_file_path[1]'], {}), '(dataset_source_file_path[1])\n', (587, 616), True, 'import pandas as pd\n'), ((966, 1030), 'pandas.DataFrame', 'pd.DataFrame', (['vsqx_file_name_path_pair'], {'columns': "['name', 'path']"}), "(vsqx_file_name_path_pair, columns=['n... |
# -*- coding: utf-8 -*-
"""
author: zengbin93
email: <EMAIL>
create_dt: 2021/12/13 17:48
describe: A股股票实盘仿真
环境变量设置说明:
strategy_id 掘金研究策略ID
account_id 账户ID
wx_key 企业微信群聊机器人Key
max_all_pos 总仓位限制
max_sym_pos 单仓位限制
path_gm_logs ... | [
"czsc.signals.bxt.get_s_three_bi",
"czsc.objects.Signal",
"czsc.signals.ta.get_s_macd"
] | [((1161, 1184), 'czsc.signals.bxt.get_s_three_bi', 'get_s_three_bi', (['c'], {'di': '(1)'}), '(c, di=1)\n', (1175, 1184), False, 'from czsc.signals.bxt import get_s_three_bi\n'), ((1203, 1222), 'czsc.signals.ta.get_s_macd', 'get_s_macd', (['c'], {'di': '(1)'}), '(c, di=1)\n', (1213, 1222), False, 'from czsc.signals.ta ... |
import logging
import pandas as pd
import numpy as np
try:
import tensorflow as tf
import tensorflow.keras as k
except ImportError:
tf = None
from lenskit import util
from .. import Predictor
from .util import init_tf_rng, check_tensorflow
_log = logging.getLogger(__name__)
if tf is not None:
class... | [
"tensorflow.keras.Model.from_config",
"tensorflow.keras.layers.Flatten",
"tensorflow.keras.layers.Dot",
"tensorflow.keras.Input",
"numpy.unique",
"lenskit.util.Stopwatch",
"tensorflow.keras.Model",
"numpy.mean",
"numpy.array",
"pandas.Series",
"tensorflow.Variable",
"tensorflow.keras.layers.Em... | [((262, 289), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (279, 289), False, 'import logging\n'), ((3352, 3368), 'lenskit.util.Stopwatch', 'util.Stopwatch', ([], {}), '()\n', (3366, 3368), False, 'from lenskit import util\n'), ((3592, 3637), 'numpy.mean', 'np.mean', (["ratings['rating'... |
# Copyright (c) ZenML GmbH 2022. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | [
"zenml.logger.get_logger",
"zenml.integrations.seldon.services.seldon_deployment.SeldonDeploymentService",
"typing.cast",
"zenml.repository.Repository",
"zenml.integrations.seldon.services.seldon_deployment.SeldonDeploymentConfig",
"datetime.datetime.strptime",
"zenml.integrations.seldon.seldon_client.S... | [((1277, 1297), 'zenml.logger.get_logger', 'get_logger', (['__name__'], {}), '(__name__)\n', (1287, 1297), False, 'from zenml.logger import get_logger\n'), ((8412, 8448), 'typing.cast', 'cast', (['SeldonDeploymentConfig', 'config'], {}), '(SeldonDeploymentConfig, config)\n', (8416, 8448), False, 'from typing import Cla... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.