code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import psycopg2
import sys
import config
class InitDatabase():
def __init__(self, db):
self.db = db
self.db_connection = psycopg2.connect(self.db)
self.db_cursor = self.db_connection.cursor()
def tables_creation(self):
tables = ("""CREATE TABLE IF NOT EXISTS users (user_id ... | [
"sys.exc_info",
"psycopg2.connect"
] | [((145, 170), 'psycopg2.connect', 'psycopg2.connect', (['self.db'], {}), '(self.db)\n', (161, 170), False, 'import psycopg2\n'), ((1911, 1925), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (1923, 1925), False, 'import sys\n')] |
# coding: utf-8
'''
получив список удаленных веток (git branch -r) можно сделать список ненужных
и удалить использую этот скрипт
'''
remote_names = ["back",
"bug_speed_4",
"change_vtv",
"deploy",
"feat_new_log",
"feat_no_conn_msg",
"feature253",
"feature_iss22",
"hotfix10",
"hotfix211",
"hotfix221",
"... | [
"subprocess.call"
] | [((1573, 1627), 'subprocess.call', 'subprocess.call', (["['git', 'push', 'origin', ':' + name]"], {}), "(['git', 'push', 'origin', ':' + name])\n", (1588, 1627), False, 'import subprocess\n')] |
#Adapte o código do desafio 107, criando uma função adicional chamada moeda() que consiga mostrar os valores como um valor
#monetário formatado.
import moeda
p = float(input('Preço: R$'))
t = int(input('Taxa %: '))
print(f'{t}% de {moeda.moeda(p)} é igual a {moeda.moeda(moeda.aumentar(p,t))} ')
print(f'-{t}% de {moed... | [
"moeda.dobro",
"moeda.metade",
"moeda.moeda",
"moeda.aumentar",
"moeda.diminuir"
] | [((234, 248), 'moeda.moeda', 'moeda.moeda', (['p'], {}), '(p)\n', (245, 248), False, 'import moeda\n'), ((316, 330), 'moeda.moeda', 'moeda.moeda', (['p'], {}), '(p)\n', (327, 330), False, 'import moeda\n'), ((397, 411), 'moeda.moeda', 'moeda.moeda', (['p'], {}), '(p)\n', (408, 411), False, 'import moeda\n'), ((466, 480... |
import unittest
from context import parser as pr
from context import entities as en
class StatementTest(unittest.TestCase):
def test_factory(self):
# a single product
p=pr.Statement.factory("product p1=10 high")
self.assertEqual(p.get_type(), pr.StatementType.PROD_DEF)
# a single... | [
"unittest.main",
"context.parser.Statement.factory"
] | [((5165, 5180), 'unittest.main', 'unittest.main', ([], {}), '()\n', (5178, 5180), False, 'import unittest\n'), ((192, 234), 'context.parser.Statement.factory', 'pr.Statement.factory', (['"""product p1=10 high"""'], {}), "('product p1=10 high')\n", (212, 234), True, 'from context import parser as pr\n'), ((341, 379), 'c... |
#!/usr/bin/env python
"""
@file test.py
@author <NAME>
@date 2016-11-25
@version $Id$
python script used by sikulix for testing netedit
SUMO, Simulation of Urban MObility; see http://sumo.dlr.de/
Copyright (C) 2009-2017 DLR/TS, Germany
This file is part of SUMO.
SUMO is free software; you can redistribute it ... | [
"sys.path.append",
"neteditTestFunctions.undo",
"neteditTestFunctions.saveNetwork",
"neteditTestFunctions.modifyAttribute",
"neteditTestFunctions.saveAdditionals",
"neteditTestFunctions.selectAdditionalChild",
"neteditTestFunctions.additionalMode",
"neteditTestFunctions.leftClick",
"neteditTestFunct... | [((732, 764), 'sys.path.append', 'sys.path.append', (['neteditTestRoot'], {}), '(neteditTestRoot)\n', (747, 764), False, 'import sys\n'), ((852, 890), 'neteditTestFunctions.setupAndStart', 'netedit.setupAndStart', (['neteditTestRoot'], {}), '(neteditTestRoot)\n', (873, 890), True, 'import neteditTestFunctions as netedi... |
import json
import requests
import shapely
import shapely.geometry as geom
from shapely.geometry import Point, box, Polygon, MultiPoint
def search(place,local):
if (',') in place:
place.split(',')
real=''.join(place)
r=requests.get('https://nominatim.openstreetmap.org/search?q='+real+'&form... | [
"shapely.geometry.mapping",
"requests.get"
] | [((248, 339), 'requests.get', 'requests.get', (["('https://nominatim.openstreetmap.org/search?q=' + real + '&format=jsonv2')"], {}), "('https://nominatim.openstreetmap.org/search?q=' + real +\n '&format=jsonv2')\n", (260, 339), False, 'import requests\n'), ((1425, 1517), 'requests.get', 'requests.get', (["('https://... |
import doctest
import k3cat
def load_tests(loader, tests, ignore):
tests.addTests(doctest.DocTestSuite(k3cat))
return tests
| [
"doctest.DocTestSuite"
] | [((89, 116), 'doctest.DocTestSuite', 'doctest.DocTestSuite', (['k3cat'], {}), '(k3cat)\n', (109, 116), False, 'import doctest\n')] |
# Plot Linked Subreddits
# Import Modules
import os
import pandas as pd
import numpy as np
import csv
import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter
linked_sr = pd.read_csv('Outputs/CS_FULL/LinkedSubreddits_CS_FULL.csv')
linked_sr = linked_sr.sort_values(by=['Times_Linked'],ascending=... | [
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylim",
"pandas.read_csv",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.yticks",
"numpy.arange",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.subplots"
] | [((195, 254), 'pandas.read_csv', 'pd.read_csv', (['"""Outputs/CS_FULL/LinkedSubreddits_CS_FULL.csv"""'], {}), "('Outputs/CS_FULL/LinkedSubreddits_CS_FULL.csv')\n", (206, 254), True, 'import pandas as pd\n'), ((1414, 1456), 'numpy.arange', 'np.arange', (['(0)', '(max_links + spacing)', 'spacing'], {}), '(0, max_links + ... |
import binascii
from unittest import mock
import ldap3
import pytest
from mitmproxy import exceptions
from mitmproxy.addons import proxyauth
from mitmproxy.test import taddons
from mitmproxy.test import tflow
class TestMkauth:
def test_mkauth_scheme(self):
assert proxyauth.mkauth('username', 'password')... | [
"mitmproxy.addons.proxyauth.mkauth",
"mitmproxy.test.tflow.tflow",
"mitmproxy.addons.proxyauth.ProxyAuth",
"unittest.mock.patch",
"pytest.raises",
"mitmproxy.addons.proxyauth.parse_http_basic_auth",
"mitmproxy.test.taddons.context",
"binascii.b2a_base64",
"pytest.mark.parametrize"
] | [((365, 558), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""scheme, expected"""', '[(\'\', \' dXNlcm5hbWU6cGFzc3dvcmQ=\\n\'), (\'basic\',\n \'basic dXNlcm5hbWU6cGFzc3dvcmQ=\\n\'), (\'foobar\',\n """foobar dXNlcm5hbWU6cGFzc3dvcmQ=\n""")]'], {}), '(\'scheme, expected\', [(\'\',\n \' dXNlcm5hbWU6cGF... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 15 18:45:40 2020
@author: <NAME>
App initializer
"""
from flask import Flask
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
app = Flask(__name__)
app.config.from_object(Config)
# Initialize the database & the migra... | [
"flask_sqlalchemy.SQLAlchemy",
"flask.Flask",
"flask_migrate.Migrate"
] | [((235, 250), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (240, 250), False, 'from flask import Flask\n'), ((345, 360), 'flask_sqlalchemy.SQLAlchemy', 'SQLAlchemy', (['app'], {}), '(app)\n', (355, 360), False, 'from flask_sqlalchemy import SQLAlchemy\n'), ((371, 387), 'flask_migrate.Migrate', 'Migrate',... |
from re import L
import disnake
import itertools
from disnake.ext import commands
from disnake.ext.commands.cooldowns import C
from fuzzywuzzy import fuzz
from docs import cog
from core.utils.pagination import Paginator
from core.Context import Context
from core.utils.docs import *
ZEN_OF_PYTHON = """\
Beautiful is... | [
"fuzzywuzzy.fuzz.ratio",
"disnake.Embed",
"disnake.ext.commands.command",
"disnake.utils.escape_markdown",
"itertools.cycle"
] | [((1348, 1410), 'itertools.cycle', 'itertools.cycle', (['(Colours.yellow, Colours.blue, Colours.white)'], {}), '((Colours.yellow, Colours.blue, Colours.white))\n', (1363, 1410), False, 'import itertools\n'), ((2309, 2327), 'disnake.ext.commands.command', 'commands.command', ([], {}), '()\n', (2325, 2327), False, 'from ... |
# -*- coding: utf-8 -*-
"""
All spiders should yield data shaped according to the Open Civic Data
specification (http://docs.opencivicdata.org/en/latest/data/event.html).
"""
import re
from datetime import datetime
from pytz import timezone
from time import strptime
from documenters_aggregator.spider import Spider
... | [
"re.match",
"pytz.timezone",
"datetime.datetime"
] | [((1002, 1036), 're.match', 're.match', (['"""(\\\\d{4}) (.*?)s"""', 'title'], {}), "('(\\\\d{4}) (.*?)s', title)\n", (1010, 1036), False, 'import re\n'), ((1430, 1462), 're.match', 're.match', (['"""(\\\\w+) +(\\\\d+)"""', 'text'], {}), "('(\\\\w+) +(\\\\d+)', text)\n", (1438, 1462), False, 'import re\n'), ((1633, 166... |
import numpy as np
import pyglet
from glearn.viewers.modes.viewer_mode import ViewerMode
from glearn.networks.layers.conv2d import Conv2dLayer
class CNNViewerMode(ViewerMode):
def __init__(self, config, visualize_grid=[1, 1], **kwargs):
super().__init__(config, **kwargs)
self.visualize_grid = vis... | [
"numpy.zeros",
"numpy.multiply"
] | [((3247, 3282), 'numpy.multiply', 'np.multiply', (['self.input.shape', 'grid'], {}), '(self.input.shape, grid)\n', (3258, 3282), True, 'import numpy as np\n'), ((3372, 3392), 'numpy.zeros', 'np.zeros', (['image_size'], {}), '(image_size)\n', (3380, 3392), True, 'import numpy as np\n'), ((5314, 5346), 'numpy.zeros', 'np... |
"""
``rosteron``: Read-only RosterOn Mobile roster access
=====================================================
The ``rosteron`` module allows read-only access
to rostering information in instances of RosterOn Mobile,
a workforce management product from `Allocate Software`_.
>>> import rosteron
>>> with rosteron.Sess... | [
"attr.s",
"attr.ib",
"email.utils.parsedate_to_datetime",
"datetime.datetime.strptime",
"pathlib.Path",
"datetime.datetime.now"
] | [((1792, 1811), 'attr.s', 'attr.s', ([], {'frozen': '(True)'}), '(frozen=True)\n', (1798, 1811), False, 'import attr\n'), ((3175, 3194), 'attr.s', 'attr.s', ([], {'frozen': '(True)'}), '(frozen=True)\n', (3181, 3194), False, 'import attr\n'), ((4442, 4461), 'attr.s', 'attr.s', ([], {'frozen': '(True)'}), '(frozen=True)... |
from vocabulary.utils import get_next_sort_type, find_word, \
get_words_from_db, translate_text, insert_word_to_db, update_word_in_db, \
delete_row_in_db
from vocabulary.consts import Lang, SortType, SortOrder
from vocabulary.ui.vocabulary_ui import Ui_MainWindow
from vocabulary.tableItem import VocItem
import... | [
"vocabulary.utils.update_word_in_db",
"PyQt5.QtCore.QRegExp",
"PyQt5.QtGui.QKeySequence",
"vocabulary.tableItem.VocItem",
"os.path.dirname",
"vocabulary.utils.get_words_from_db",
"datetime.datetime.now",
"vocabulary.utils.get_next_sort_type",
"PyQt5.QtWidgets.QFileDialog.getSaveFileName",
"vocabul... | [((1190, 1241), 'os.path.join', 'os.path.join', (['PATH_HERE', '"""db"""', '"""dictionary.sqlite3"""'], {}), "(PATH_HERE, 'db', 'dictionary.sqlite3')\n", (1202, 1241), False, 'import os\n'), ((1262, 1306), 'os.path.join', 'os.path.join', (['PATH_HERE', '"""icons"""', '"""book.png"""'], {}), "(PATH_HERE, 'icons', 'book.... |
from random import randint, sample, uniform
from acme import Product
#Name Generator
ADJECTIVES = ['Awesome', 'Shiny', 'Impressive', 'Portable', 'Improved']
NOUNS = ['Anvil', 'Catapult', 'Disguise', 'Mousetrap', '???']
def generate_products(num_products=30):
products = []
for i in range(num_products):
... | [
"random.sample",
"random.randint",
"random.uniform"
] | [((492, 507), 'random.randint', 'randint', (['(5)', '(100)'], {}), '(5, 100)\n', (499, 507), False, 'from random import randint, sample, uniform\n'), ((539, 554), 'random.randint', 'randint', (['(5)', '(100)'], {}), '(5, 100)\n', (546, 554), False, 'from random import randint, sample, uniform\n'), ((586, 601), 'random.... |
"""Test the auth script to manage local users."""
from unittest.mock import Mock, patch
import pytest
from homeassistant.scripts import auth as script_auth
from homeassistant.auth_providers import homeassistant as hass_auth
MOCK_PATH = '/bla/users.json'
def test_list_user(capsys):
"""Test we can list users."""... | [
"unittest.mock.patch.object",
"unittest.mock.Mock",
"pytest.raises",
"homeassistant.scripts.auth.list_users",
"homeassistant.auth_providers.homeassistant.Data"
] | [((332, 363), 'homeassistant.auth_providers.homeassistant.Data', 'hass_auth.Data', (['MOCK_PATH', 'None'], {}), '(MOCK_PATH, None)\n', (346, 363), True, 'from homeassistant.auth_providers import homeassistant as hass_auth\n'), ((461, 495), 'homeassistant.scripts.auth.list_users', 'script_auth.list_users', (['data', 'No... |
"""
This module provides tools for stacking a model on top of other
models without information leakage from a target variable to
predictions made by base models.
@author: <NAME>
"""
from typing import List, Dict, Tuple, Callable, Union, Optional, Any
from abc import ABC, abstractmethod
import numpy as np
from skle... | [
"sklearn.base.clone",
"sklearn.utils.validation.check_X_y",
"numpy.unique",
"numpy.zeros",
"sklearn.model_selection.KFold",
"sklearn.utils.validation.check_is_fitted",
"numpy.hstack",
"numpy.apply_along_axis",
"joblib.Parallel",
"joblib.delayed",
"sklearn.utils.multiclass.check_classification_ta... | [((10472, 10515), 'numpy.hstack', 'np.hstack', (['(meta_features, ordering_column)'], {}), '((meta_features, ordering_column))\n', (10481, 10515), True, 'import numpy as np\n'), ((11569, 11592), 'numpy.vstack', 'np.vstack', (['meta_feature'], {}), '(meta_feature)\n', (11578, 11592), True, 'import numpy as np\n'), ((130... |
from src.compound_model.CompoundModelFactory import CompoundModelFactory
from src.controller.ControllerRegistry import ControllerRegistry
import src.util.PromptUtil as PU
from src.phase_utils import (
confirm_lists,
select_dataset,
select_attributes,
select_controllers,
select_generators,
)
DEFAU... | [
"src.phase_utils.select_dataset",
"src.util.PromptUtil.push_indent",
"src.util.PromptUtil.prompt_yes_no",
"src.phase_utils.select_attributes",
"src.util.PromptUtil.print_with_border",
"src.phase_utils.select_generators",
"src.util.PromptUtil.input_int",
"src.util.PromptUtil.print_with_indent",
"src.... | [((464, 480), 'src.phase_utils.select_dataset', 'select_dataset', ([], {}), '()\n', (478, 480), False, 'from src.phase_utils import confirm_lists, select_dataset, select_attributes, select_controllers, select_generators\n'), ((498, 524), 'src.phase_utils.select_attributes', 'select_attributes', (['dataset'], {}), '(dat... |
#!./python27-gcc482/bin/python
# coding: utf-8
"""
BAIDU CLOUD action
"""
import os
import sys
import pickle
import json
import time
import shutil
import numpy as np
sys.path.append(
"/home/aistudio/work/PaddleVideo/applications/TableTennis/predict/action_detect"
)
import models.bmn_infer as prop_model
from util... | [
"sys.path.append",
"logger.info",
"os.mkdir",
"logger.Logger",
"os.fsdecode",
"os.path.exists",
"models.bmn_infer.predict",
"time.time",
"json.dumps",
"utils.config_utils.parse_config",
"numpy.array",
"models.bmn_infer.InferModel",
"os.fsencode",
"utils.config_utils.print_configs",
"os.l... | [((169, 276), 'sys.path.append', 'sys.path.append', (['"""/home/aistudio/work/PaddleVideo/applications/TableTennis/predict/action_detect"""'], {}), "(\n '/home/aistudio/work/PaddleVideo/applications/TableTennis/predict/action_detect'\n )\n", (184, 276), False, 'import sys\n'), ((477, 492), 'logger.Logger', 'logge... |
from __future__ import print_function
from __future__ import division
from . import _C
import numpy as np
import matplotlib.pyplot as plt
from fuzzytools.strings import get_string_from_dict
import fuzzytools.matplotlib.bars as bars
######################################################################################... | [
"fuzzytools.matplotlib.bars.plot_norm_percentile_bar"
] | [((1029, 1114), 'fuzzytools.matplotlib.bars.plot_norm_percentile_bar', 'bars.plot_norm_percentile_bar', (['ax', 'new_days', 'obs', 'obse'], {'color': 'color', 'alpha': 'alpha'}), '(ax, new_days, obs, obse, color=color, alpha=alpha\n )\n', (1058, 1114), True, 'import fuzzytools.matplotlib.bars as bars\n')] |
from copy import deepcopy
import emanager.accounting.accounts as acc
from emanager.utils.data_types import CUSTOMER_DATA
from emanager.utils.directories import SELL_DATA_DIR
from emanager.utils.stakeholder import *
SELL_DATA_FILE_NAME = "customer_data.csv"
SELL_DATA_FILE_PATH = f"{SELL_DATA_DIR}/{SELL_DATA_FILE_NAME}... | [
"copy.deepcopy",
"emanager.accounting.accounts.check_account_existance"
] | [((959, 982), 'copy.deepcopy', 'deepcopy', (['CUSTOMER_DATA'], {}), '(CUSTOMER_DATA)\n', (967, 982), False, 'from copy import deepcopy\n'), ((1350, 1404), 'emanager.accounting.accounts.check_account_existance', 'acc.check_account_existance', (['self.name', 'self.mobile_no'], {}), '(self.name, self.mobile_no)\n', (1377,... |
import numpy as np
def ood_p_value(cost, bound, ubound=True):
"""Compute p-value"""
violations = cost - bound if ubound else bound - cost
violation = np.mean(violations)
tau = max(violation, 0)
m = len(cost)
p_val = np.exp(-2 * m * (tau ** 2))
return 1 - p_val
def ood_confidence(cost, bo... | [
"numpy.log",
"numpy.cumsum",
"numpy.max",
"numpy.mean",
"numpy.exp"
] | [((164, 183), 'numpy.mean', 'np.mean', (['violations'], {}), '(violations)\n', (171, 183), True, 'import numpy as np\n'), ((242, 267), 'numpy.exp', 'np.exp', (['(-2 * m * tau ** 2)'], {}), '(-2 * m * tau ** 2)\n', (248, 267), True, 'import numpy as np\n'), ((447, 466), 'numpy.mean', 'np.mean', (['violations'], {}), '(v... |
import copy
import re
import sys
from typing import Dict, Set
from const import WORDLE_LENGTH
from util import max_by
class Game:
def __init__(self, wordles, substr_to_freq, wordle_to_usage=None, debug=False):
self._candidates = copy.copy(wordles)
self._candidates_dirty = False
se... | [
"util.max_by",
"copy.copy",
"re.compile"
] | [((243, 261), 'copy.copy', 'copy.copy', (['wordles'], {}), '(wordles)\n', (252, 261), False, 'import copy\n'), ((3854, 3881), 're.compile', 're.compile', (['candidate_regex'], {}), '(candidate_regex)\n', (3864, 3881), False, 'import re\n'), ((1580, 1616), 'util.max_by', 'max_by', (['self.candidates', 'self._score'], {}... |
import numpy as np
from matplotlib.path import Path
import matplotlib.patches as patches
import scipy.linalg as lin
import matplotlib.pyplot as plt
def plotGMM(Mu, Sigma, color,display_mode, ax):
a, nbData = np.shape(Mu)
lightcolor = np.asarray(color) + np.asarray([0.6,0.6,0.6])
a = np.nonzero(lightcolor >... | [
"numpy.asarray",
"numpy.transpose",
"numpy.shape",
"numpy.nonzero",
"matplotlib.path.Path",
"scipy.linalg.sqrtm",
"numpy.sin",
"numpy.linspace",
"numpy.real",
"numpy.cos",
"matplotlib.patches.PathPatch"
] | [((213, 225), 'numpy.shape', 'np.shape', (['Mu'], {}), '(Mu)\n', (221, 225), True, 'import numpy as np\n'), ((297, 323), 'numpy.nonzero', 'np.nonzero', (['(lightcolor > 1)'], {}), '(lightcolor > 1)\n', (307, 323), True, 'import numpy as np\n'), ((243, 260), 'numpy.asarray', 'np.asarray', (['color'], {}), '(color)\n', (... |
import pytest
from tests.conftest import config_file
from tests.utils import invoke_cli, check_requirements_snapshot
def test_uninstall(tmpdir, mock_pip, config_file, snapshot):
requirements_file = tmpdir.join('requirements.txt')
requirements_file.write('-e editable1\nold1\na~=1.0.0\nold2~=1.0.0 --hash=anc\\... | [
"tests.utils.check_requirements_snapshot",
"tests.utils.invoke_cli"
] | [((343, 389), 'tests.utils.invoke_cli', 'invoke_cli', (['"""uninstall old1 old2"""', 'config_file'], {}), "('uninstall old1 old2', config_file)\n", (353, 389), False, 'from tests.utils import invoke_cli, check_requirements_snapshot\n'), ((394, 439), 'tests.utils.check_requirements_snapshot', 'check_requirements_snapsho... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'nnc_utils.ui'
#
# Created by: PyQt5 UI code generator 5.10
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObject... | [
"PyQt5.QtWidgets.QComboBox",
"PyQt5.QtWidgets.QLabel",
"PyQt5.QtWidgets.QSizePolicy",
"PyQt5.QtWidgets.QFrame",
"PyQt5.QtWidgets.QWidget",
"PyQt5.QtCore.QRect",
"PyQt5.QtWidgets.QLineEdit",
"PyQt5.QtWidgets.QPushButton",
"PyQt5.QtCore.QSize",
"PyQt5.QtWidgets.QPlainTextEdit",
"PyQt5.QtCore.QMeta... | [((388, 467), 'PyQt5.QtWidgets.QSizePolicy', 'QtWidgets.QSizePolicy', (['QtWidgets.QSizePolicy.Fixed', 'QtWidgets.QSizePolicy.Fixed'], {}), '(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)\n', (409, 467), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((804, 832), 'PyQt5.QtWidgets.QTabWidget', 'QtWi... |
#!/usr/bin/env python
"""
Initiates the services `getAction` and `publishLoss`.
TODO:
* Run this script as a node in a launch script
"""
import argparse
from posthoc_learn.algoserver import create_server, N_FEATURES
from posthoc_learn.banalg import HardConstraint, Greedy, EpsilonGreedy, LinUCB
from posthoc_learn.c... | [
"posthoc_learn.banalg.LinUCB",
"argparse.ArgumentParser",
"posthoc_learn.algoserver.create_server",
"posthoc_learn.conban_dataset.ConBanDataset",
"posthoc_learn.banalg.Greedy",
"posthoc_learn.banalg.EpsilonGreedy",
"rospy.spin",
"posthoc_learn.banalg.HardConstraint"
] | [((473, 498), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (496, 498), False, 'import argparse\n'), ((2556, 2625), 'posthoc_learn.conban_dataset.ConBanDataset', 'ConBanDataset', (['args.dataset', 'config.visual_model', 'config.haptic_model'], {}), '(args.dataset, config.visual_model, config.h... |
#!/usr/bin/env python3
#
# (c) <NAME> 2017
#
# This file will be a utility to help facilitate the comparison of performance
# metrics across arbitrary commits. The file will produce a table comparing
# metrics between measurements taken for given commits in the environment
# (which defaults to 'local' if not given by ... | [
"argparse.ArgumentParser",
"subprocess.check_output",
"time.sleep",
"testutil.failBecause",
"re.findall",
"collections.namedtuple",
"testutil.passed",
"subprocess.check_call",
"re.compile"
] | [((1280, 1350), 'collections.namedtuple', 'namedtuple', (['"""PerfStat"""', "['test_env', 'test', 'way', 'metric', 'value']"], {}), "('PerfStat', ['test_env', 'test', 'way', 'metric', 'value'])\n", (1290, 1350), False, 'from collections import namedtuple\n'), ((2772, 2859), 'subprocess.check_output', 'subprocess.check_... |
#-*- coding: utf-8 -*-
"""
what : Single Encoder Model for text - bidirectional
data : IEMOCAP
"""
import tensorflow as tf
from tensorflow.contrib import rnn
from tensorflow.contrib.rnn import DropoutWrapper
from tensorflow.core.framework import summary_pb2
from random import shuffle
import numpy as np
from la... | [
"tensorflow.maximum",
"tensorflow.reshape",
"model_luong_attention.luong_attention",
"tensorflow.matmul",
"tensorflow.Variable",
"tensorflow.abs",
"tensorflow.random.uniform",
"tensorflow.compat.v1.placeholder",
"layers.add_GRU",
"tensorflow.nn.softmax_cross_entropy_with_logits_v2",
"tensorflow.... | [((1503, 1570), 'tensorflow.Variable', 'tf.Variable', (['(0)'], {'dtype': 'tf.int32', 'trainable': '(False)', 'name': '"""global_step"""'}), "(0, dtype=tf.int32, trainable=False, name='global_step')\n", (1514, 1570), True, 'import tensorflow as tf\n'), ((1671, 1704), 'tensorflow.name_scope', 'tf.name_scope', (['"""text... |
import io
import multiprocessing
import re
import subprocess
import sys
import time
import unicodedata
from pathlib import Path
from tqdm.auto import tqdm
fname = sys.argv[1]
def process_line(line: str):
"""
There is a complex mess of stuff down there
Use this function to do processing stuff to your lin... | [
"unicodedata.normalize",
"unicodedata.category",
"time.time",
"tqdm.auto.tqdm",
"pathlib.Path",
"multiprocessing.Pool",
"re.sub",
"multiprocessing.cpu_count"
] | [((557, 600), 're.sub', 're.sub', (['"""[\'\\\\"(){}\\\\[\\\\]]"""', '""""""', 'no_accents'], {}), '(\'[\\\'\\\\"(){}\\\\[\\\\]]\', \'\', no_accents)\n', (563, 600), False, 'import re\n'), ((2095, 2106), 'time.time', 'time.time', ([], {}), '()\n', (2104, 2106), False, 'import time\n'), ((2969, 2980), 'pathlib.Path', 'P... |
from typing import Any, Dict, Mapping, Optional
from abc import ABC, abstractmethod
from collections import defaultdict, OrderedDict
import torch
from torch.utils.data import DataLoader, DistributedSampler
from catalyst.core.callback import Callback, ICallback
from catalyst.core.engine import Engine
from catalyst.cor... | [
"catalyst.core.misc.get_loader_num_samples",
"catalyst.utils.misc.maybe_recursive_call",
"catalyst.core.misc.get_loader_batch_size",
"collections.defaultdict",
"catalyst.core.misc.check_callbacks",
"torch.set_grad_enabled",
"catalyst.core.misc.is_str_intersections"
] | [((2642, 2659), 'collections.defaultdict', 'defaultdict', (['None'], {}), '(None)\n', (2653, 2659), False, 'from collections import defaultdict, OrderedDict\n'), ((2706, 2723), 'collections.defaultdict', 'defaultdict', (['None'], {}), '(None)\n', (2717, 2723), False, 'from collections import defaultdict, OrderedDict\n'... |
from django.urls import path
from news.views import ArticleListView, ArticleDetailView, ArticleCreateView, TopicListView, TopicDetailView, TopicCreateView
urlpatterns = [
path('topic_list/', TopicListView.as_view()),
path('topic_create/', TopicCreateView.as_view()),
path('topic/<int:pk>/', TopicDetailView.... | [
"news.views.ArticleDetailView.as_view",
"news.views.TopicDetailView.as_view",
"news.views.ArticleCreateView.as_view",
"news.views.TopicListView.as_view",
"news.views.TopicCreateView.as_view",
"news.views.ArticleListView.as_view"
] | [((196, 219), 'news.views.TopicListView.as_view', 'TopicListView.as_view', ([], {}), '()\n', (217, 219), False, 'from news.views import ArticleListView, ArticleDetailView, ArticleCreateView, TopicListView, TopicDetailView, TopicCreateView\n'), ((248, 273), 'news.views.TopicCreateView.as_view', 'TopicCreateView.as_view'... |
import subprocess
import sys
import pkg_resources
from GridCal.__version__ import __GridCal_VERSION__
def find_latest_version(name='GridCal'):
"""
Find the latest version of a package
:param name: name of the Package
:return: version string
"""
latest_version = str(subprocess.run([sys.executab... | [
"pkg_resources.parse_version"
] | [((1005, 1048), 'pkg_resources.parse_version', 'pkg_resources.parse_version', (['latest_version'], {}), '(latest_version)\n', (1032, 1048), False, 'import pkg_resources\n'), ((1066, 1114), 'pkg_resources.parse_version', 'pkg_resources.parse_version', (['__GridCal_VERSION__'], {}), '(__GridCal_VERSION__)\n', (1093, 1114... |
#
# Copyright 2021 Ocean Protocol Foundation
# SPDX-License-Identifier: Apache-2.0
#
import pytest
from ocean_lib.assets.utils import (
add_publisher_trusted_algorithm,
create_publisher_trusted_algorithms,
generate_trusted_algo_dict,
remove_publisher_trusted_algorithm,
)
from tests.resources.ddo_helper... | [
"ocean_lib.assets.utils.add_publisher_trusted_algorithm",
"tests.resources.helper_functions.get_publisher_wallet",
"ocean_lib.assets.utils.create_publisher_trusted_algorithms",
"pytest.raises",
"ocean_lib.assets.utils.remove_publisher_trusted_algorithm",
"tests.resources.ddo_helpers.get_registered_ddo_wit... | [((665, 687), 'tests.resources.helper_functions.get_publisher_wallet', 'get_publisher_wallet', ([], {}), '()\n', (685, 687), False, 'from tests.resources.helper_functions import get_publisher_wallet\n'), ((709, 774), 'tests.resources.ddo_helpers.get_registered_algorithm_ddo', 'get_registered_algorithm_ddo', (['publishe... |
'''
Now You Code 4: Syracuse Weather
Write a program to load the Syracuse weather data from Dec 2015 in
JSON format into a Python list of dictionary. The file is:
"NYC4-syr-weather-dec-2015.json"
After you load this data calculate the number of days where the
'Mean TemperatureF' is above freezing ( > 32 degrees)
St... | [
"json.loads"
] | [((784, 800), 'json.loads', 'json.loads', (['file'], {}), '(file)\n', (794, 800), False, 'import json\n')] |
import sqlite3
import time
import datetime
db_path = ""
prev_day = ""
url_dict = {}
prev_urls = {}
changed = 0
def set_db_path(path):
global db_path, prev_day
db_path = path
prev_day = str(datetime.datetime.now()).split(" ")[0]
def receive_url(url):
global url_dict, changed
changed = 1
if ... | [
"sqlite3.connect",
"datetime.datetime.now",
"time.sleep"
] | [((1664, 1677), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (1674, 1677), False, 'import time\n'), ((731, 755), 'sqlite3.connect', 'sqlite3.connect', (['db_path'], {}), '(db_path)\n', (746, 755), False, 'import sqlite3\n'), ((205, 228), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (226, 2... |
"""Self-Attention Transformer.
"""
import torch
from torch import distributions
from torchtext.data.metrics import bleu_score
import textformer.utils.logging as l
from textformer.core.model import Model
from textformer.models.decoders import SelfAttentionDecoder
from textformer.models.encoders import SelfAttentionEnc... | [
"torch.ones",
"textformer.models.decoders.SelfAttentionDecoder",
"torch.LongTensor",
"torchtext.data.metrics.bleu_score",
"torch.cat",
"textformer.utils.logging.get_logger",
"torch.no_grad",
"textformer.models.encoders.SelfAttentionEncoder"
] | [((335, 357), 'textformer.utils.logging.get_logger', 'l.get_logger', (['__name__'], {}), '(__name__)\n', (347, 357), True, 'import textformer.utils.logging as l\n'), ((1845, 1939), 'textformer.models.encoders.SelfAttentionEncoder', 'SelfAttentionEncoder', (['n_input', 'n_hidden', 'n_forward', 'n_layers', 'n_heads', 'dr... |
import torch
def _load_biggan_model(model_name='biggan-deep-256'):
from models.biggan.pytorch_pretrained_biggan import BigGAN
assert model_name in [
'biggan-deep-128',
'biggan-deep-256',
'biggan-deep-512',
]
G = BigGAN.from_pretrained(model_name).eval()
return G
def _load... | [
"models.stylegan1.stylegan1.StyleGAN.load_from_pth",
"models.mit_semseg.config.cfg.MODEL.arch_encoder.lower",
"torch.load",
"models.face_bisenet.model.BiSeNet",
"os.path.exists",
"models.deeplab.deeplabv2.DeepLabV2",
"models.mit_semseg.mit_models.models.ModelBuilder.build_decoder",
"models.mit_semseg.... | [((903, 937), 'models.stylegan1.stylegan1.StyleGAN.load_from_pth', 'StyleGAN.load_from_pth', (['model_path'], {}), '(model_path)\n', (925, 937), False, 'from models.stylegan1.stylegan1 import StyleGAN\n'), ((1208, 1229), 'models.face_bisenet.model.BiSeNet', 'BiSeNet', ([], {'n_classes': '(19)'}), '(n_classes=19)\n', (1... |
import json
import os
import pickle
from pathlib import Path
from shapely.geometry import MultiPolygon
import shapely.wkt
from pointcloud.pointcloud import PointCloud
from pointcloud.tile import Tile
from pointcloud.utils import misc
import gc
def save_project(project):
"""
:type project: Project
:param... | [
"json.load",
"os.makedirs",
"os.path.exists",
"shapely.geometry.MultiPolygon",
"pathlib.Path",
"pointcloud.pointcloud.PointCloud"
] | [((655, 670), 'json.load', 'json.load', (['read'], {}), '(read)\n', (664, 670), False, 'import json\n'), ((2046, 2061), 'pathlib.Path', 'Path', (['workspace'], {}), '(workspace)\n', (2050, 2061), False, 'from pathlib import Path\n'), ((3419, 3575), 'pointcloud.pointcloud.PointCloud', 'PointCloud', (['name', 'workspace'... |
#Library Used: requests
#https://requests.readthedocs.io/en/master/
import requests
url = 'https://icanhazdadjoke.com'
# plain text
# response = requests.get(url, headers={'Accept':'text/plain'})
# JSON
response = requests.get(url, headers={'Accept':'application/json'})
data = response.json()
print(data['joke'])
| [
"requests.get"
] | [((218, 275), 'requests.get', 'requests.get', (['url'], {'headers': "{'Accept': 'application/json'}"}), "(url, headers={'Accept': 'application/json'})\n", (230, 275), False, 'import requests\n')] |
"""
Created on Wed Jun 17 14:01:23 2020
Correlation matrix of maps, rearranged correlation matrix
@author: Jyotika.bahuguna
"""
import os
import glob
import numpy as np
import pylab as pl
import scipy.io as sio
from copy import copy, deepcopy
import pickle
import matplotlib.cm as cm
import pdb
import h5py
import... | [
"os.mkdir",
"numpy.abs",
"pandas.read_csv",
"numpy.isnan",
"numpy.arange",
"pylab.figure",
"numpy.linalg.norm",
"graph_prop_funcs_analyze.calc_participation_coef_sign",
"numpy.unique",
"sys.path.append",
"graph_prop_funcs_analyze.calc_module_degree_zscore",
"graph_prop_funcs_analyze.get_re_arr... | [((467, 493), 'sys.path.append', 'sys.path.append', (['"""common/"""'], {}), "('common/')\n", (482, 493), False, 'import sys\n'), ((835, 855), 'os.listdir', 'os.listdir', (['data_dir'], {}), '(data_dir)\n', (845, 855), False, 'import os\n'), ((935, 981), 'pandas.read_csv', 'pd.read_csv', (["(data_target_dir + 'meta_dat... |
# Generated by Django 3.2.5 on 2021-08-23 03:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('participant_profile', '0010_majorstudent_charity'),
]
operations = [
migrations.AlterField(
model_name='majorstudent',
... | [
"django.db.models.CharField",
"django.db.models.TextField"
] | [((357, 775), 'django.db.models.CharField', 'models.CharField', ([], {'choices': "[('0', 'Rp. 0'), ('25', 'Rp. 250.000,-'), ('50', 'Rp. 500.000,-'), ('150',\n 'Rp. 1.500.000,-'), ('200', 'Rp. 2.000.000,-'), ('250',\n 'Rp. 2.500.000,-'), ('300', 'Rp. 3.000.000,-')]", 'help_text': '"""Dana Sukarela nantinya akan di... |
import numpy as np
import torch
import torchvision
import torchvision.transforms as transforms
import pandas as pd
import torch.optim as optim
from torch.autograd import Variable
import torch.nn.functional as F
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
from skimage.color import rgb2gray
from skle... | [
"torch.nn.Dropout",
"matplotlib.image.imread",
"pandas.read_csv",
"torch.autograd.Variable",
"torch.load",
"torch.nn.Conv2d",
"torch.nn.CrossEntropyLoss",
"os.path.exists",
"torch.FloatTensor",
"torch.max",
"torch.nn.Linear",
"torch.nn.MaxPool2d",
"torch.nn.functional.relu",
"torch.from_nu... | [((439, 465), 'pandas.read_csv', 'pd.read_csv', (['"""../test.csv"""'], {}), "('../test.csv')\n", (450, 465), True, 'import pandas as pd\n'), ((776, 803), 'torch.from_numpy', 'torch.from_numpy', (['test_data'], {}), '(test_data)\n', (792, 803), False, 'import torch\n'), ((941, 977), 'pandas.read_csv', 'pd.read_csv', ([... |
import os
import copy
import yaml
import numpy as np
import autumn.post_processing as post_proc
from autumn.tool_kit.scenarios import Scenario
from ..countries import Country, CountryModel
FILE_DIR = os.path.dirname(os.path.abspath(__file__))
OPTI_PARAMS_PATH = os.path.join(FILE_DIR, "opti_params.yml")
with open(... | [
"copy.deepcopy",
"os.path.abspath",
"autumn.post_processing.PostProcessing",
"numpy.zeros",
"numpy.ones",
"autumn.tool_kit.scenarios.Scenario",
"yaml.safe_load",
"os.path.join"
] | [((267, 308), 'os.path.join', 'os.path.join', (['FILE_DIR', '"""opti_params.yml"""'], {}), "(FILE_DIR, 'opti_params.yml')\n", (279, 308), False, 'import os\n'), ((221, 246), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (236, 246), False, 'import os\n'), ((375, 400), 'yaml.safe_load', 'yaml.... |
# Bank note authenticator
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, confusion_matrix
import tensorflow as tf
if __name__ == "__main__... | [
"pandas.DataFrame",
"matplotlib.pyplot.show",
"sklearn.preprocessing.StandardScaler",
"tensorflow.feature_column.numeric_column",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"sklearn.metrics.classification_report",
"seaborn.pairplot",
"tensorflow.estimator.inputs.pandas_input_fn",... | [((343, 387), 'pandas.read_csv', 'pd.read_csv', (['"""TensorFlow/bank_note_data.csv"""'], {}), "('TensorFlow/bank_note_data.csv')\n", (354, 387), True, 'import pandas as pd\n'), ((409, 438), 'seaborn.pairplot', 'sns.pairplot', (['df'], {'hue': '"""Class"""'}), "(df, hue='Class')\n", (421, 438), True, 'import seaborn as... |
import discord
from discord.ext import commands
class funkomut(commands.Cog):
def __init__(self,bot):
self.bot = bot
@commands.command()
async def dayyip(self, mesaj):
await mesaj.send("Evren Başkanı.")
@commands.command()
async def tr(self, mesaj):
await me... | [
"discord.ext.commands.command"
] | [((145, 163), 'discord.ext.commands.command', 'commands.command', ([], {}), '()\n', (161, 163), False, 'from discord.ext import commands\n'), ((252, 270), 'discord.ext.commands.command', 'commands.command', ([], {}), '()\n', (268, 270), False, 'from discord.ext import commands\n'), ((364, 382), 'discord.ext.commands.co... |
import random
# Random
random.seed(3)
print(random.random())
print(random.random())
print(random.randrange(1, 10))
print(random.sample(range(100), 10))
# print with separator
print(1, 2, 3, sep='|')
| [
"random.random",
"random.seed",
"random.randrange"
] | [((24, 38), 'random.seed', 'random.seed', (['(3)'], {}), '(3)\n', (35, 38), False, 'import random\n'), ((45, 60), 'random.random', 'random.random', ([], {}), '()\n', (58, 60), False, 'import random\n'), ((68, 83), 'random.random', 'random.random', ([], {}), '()\n', (81, 83), False, 'import random\n'), ((91, 114), 'rand... |
import json
from django.views import View
from django.http import HttpResponse, JsonResponse
from django.db import models
from django.shortcuts import get_object_or_404
from django.core.exceptions import ImproperlyConfigured
from django.db.models import QuerySet
from custom_table.models import Metadata
class CustomTa... | [
"django.shortcuts.get_object_or_404",
"django.core.exceptions.ImproperlyConfigured"
] | [((5206, 5245), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (['self.queryset'], {'pk': 'pk'}), '(self.queryset, pk=pk)\n', (5223, 5245), False, 'from django.shortcuts import get_object_or_404\n'), ((6097, 6136), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (['self.queryset'], {'pk': 'pk'}),... |
from django.utils.translation import gettext_lazy as _
headings = {
"/amendments/amendsReleaseID": _("Amendment Amended Release (identifier)"),
"/amendments/date": _("Amendment Date"),
"/amendments/description": _("Amendment Description"),
"/amendments/id": _("Amendment Id"),
"/amendments/rationale... | [
"django.utils.translation.gettext_lazy"
] | [((104, 147), 'django.utils.translation.gettext_lazy', '_', (['"""Amendment Amended Release (identifier)"""'], {}), "('Amendment Amended Release (identifier)')\n", (105, 147), True, 'from django.utils.translation import gettext_lazy as _\n'), ((173, 192), 'django.utils.translation.gettext_lazy', '_', (['"""Amendment Da... |
import re
from typing import NamedTuple, Callable, Dict, List, Optional, Union
from py_pdf_parser.components import PDFElement, PDFDocument, ElementOrdering
from py_pdf_parser.sectioning import Section
from pdfminer.layout import LTComponent
from py_pdf_parser.common import BoundingBox
from py_pdf_parser.loaders imp... | [
"py_pdf_parser.components.PDFDocument",
"py_pdf_parser.sectioning.Section",
"py_pdf_parser.loaders.Page",
"py_pdf_parser.common.BoundingBox"
] | [((2145, 2168), 'py_pdf_parser.common.BoundingBox', 'BoundingBox', (['(0)', '(1)', '(0)', '(1)'], {}), '(0, 1, 0, 1)\n', (2156, 2168), False, 'from py_pdf_parser.common import BoundingBox\n'), ((3812, 4019), 'py_pdf_parser.components.PDFDocument', 'PDFDocument', ([], {'pages': 'pages', 'font_mapping': 'font_mapping', '... |
"""
Wrapper for Datacube.load_data
"""
from typing import (
Any,
Optional,
Union,
Dict,
Callable,
Sequence,
)
from warnings import warn
import xarray as xr
from datacube import Datacube
from datacube.model import Dataset
from datacube.utils.geometry import GeoBox
from datacube.api.core import ... | [
"datacube.Datacube.group_datasets",
"datacube.Datacube.load_data"
] | [((1991, 2033), 'datacube.Datacube.group_datasets', 'Datacube.group_datasets', (['datasets', 'groupby'], {}), '(datasets, groupby)\n', (2014, 2033), False, 'from datacube import Datacube\n'), ((2096, 2285), 'datacube.Datacube.load_data', 'Datacube.load_data', (['grouped', 'geobox', 'mm'], {'resampling': 'resampling', '... |
import json
from json.encoder import JSONEncoder
from typing import Optional
import zmq
from django.db.models import QuerySet
from django.db.models.base import ModelBase
from django.forms import model_to_dict
from django.http.response import HttpResponseBase
class DataEncoder(JSONEncoder):
def default(self, o):
... | [
"django.forms.model_to_dict",
"json.dumps",
"zmq.Context"
] | [((2069, 2107), 'json.dumps', 'json.dumps', (['self.data'], {'cls': 'DataEncoder'}), '(self.data, cls=DataEncoder)\n', (2079, 2107), False, 'import json\n'), ((810, 823), 'zmq.Context', 'zmq.Context', ([], {}), '()\n', (821, 823), False, 'import zmq\n'), ((465, 530), 'django.forms.model_to_dict', 'model_to_dict', (['o'... |
from dataclasses import dataclass, field
from typing import List
__NAMESPACE__ = "NISTSchema-SV-IV-list-hexBinary-pattern-1-NS"
@dataclass
class NistschemaSvIvListHexBinaryPattern1:
class Meta:
name = "NISTSchema-SV-IV-list-hexBinary-pattern-1"
namespace = "NISTSchema-SV-IV-list-hexBinary-pattern... | [
"dataclasses.field"
] | [((351, 505), 'dataclasses.field', 'field', ([], {'default_factory': 'list', 'metadata': "{'pattern':\n '[0-9A-F]{22} [0-9A-F]{70} [0-9A-F]{66} [0-9A-F]{2} [0-9A-F]{30} [0-9A-F]{38}'\n , 'tokens': True}"}), "(default_factory=list, metadata={'pattern':\n '[0-9A-F]{22} [0-9A-F]{70} [0-9A-F]{66} [0-9A-F]{2} [0-9A... |
from ctypes import Array
from pathlib import Path
from typing import Tuple, List, Dict, Optional
from OpenGL.GL import *
from cubelang.cube import Cube as CubeModel
from cubelang.orientation import Orientation, Color, Side
from .label import Label
from .engine.linalg import Matrix, translate, change_axis, C_IDENTITY,... | [
"pathlib.Path",
"cubelang.orientation.Orientation.regular"
] | [((5060, 5085), 'cubelang.orientation.Orientation.regular', 'Orientation.regular', (['side'], {}), '(side)\n', (5079, 5085), False, 'from cubelang.orientation import Orientation, Color, Side\n'), ((4382, 4418), 'cubelang.orientation.Orientation.regular', 'Orientation.regular', (['self.label.side'], {}), '(self.label.si... |
import json
import unittest
import responses
import pyfacebook
class ApiHashtagTest(unittest.TestCase):
BASE_PATH = "testdata/instagram/apidata/hashtags/"
BASE_URL = "https://graph.facebook.com/{}/".format(pyfacebook.Api.VALID_API_VERSIONS[-1])
with open(BASE_PATH + "hashtag_search.json", "rb") as f:
... | [
"pyfacebook.IgProApi",
"responses.RequestsMock"
] | [((1968, 2105), 'pyfacebook.IgProApi', 'pyfacebook.IgProApi', ([], {'app_id': '"""123456"""', 'app_secret': '"""secret"""', 'long_term_token': '"""token"""', 'instagram_business_id': 'self.instagram_business_id'}), "(app_id='123456', app_secret='secret', long_term_token=\n 'token', instagram_business_id=self.instagr... |
# Generated by Django 2.1.5 on 2019-04-01 01:37
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='DataFile',
fields=[
('id', models.AutoField... | [
"django.db.models.FileField",
"django.db.models.DateTimeField",
"django.db.models.BooleanField",
"django.db.models.AutoField"
] | [((304, 397), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (320, 397), False, 'from django.db import migrations, models\... |
from setuptools import setup, find_packages
with open('README.md') as f:
readme = f.read()
with open('LICENSE') as f:
homedashlicense = f.read()
setup(
name='homedash',
version='0.0.1',
packages=find_packages(),
url='',
license=homedashlicense,
author='<NAME>',
author_email='',
... | [
"setuptools.find_packages"
] | [((218, 233), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (231, 233), False, 'from setuptools import setup, find_packages\n')] |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-06-07 14:28
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('froide_food', '0004_auto_20180607_1618'),
]
operations = [
migrations.RemoveField(... | [
"django.db.migrations.RemoveField"
] | [((297, 365), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""venuerequest"""', 'name': '"""foirequest"""'}), "(model_name='venuerequest', name='foirequest')\n", (319, 365), False, 'from django.db import migrations\n'), ((410, 478), 'django.db.migrations.RemoveField', 'migrations.R... |
import random
import pybullet
import math
def worldGen(size, amplitude=4):
"""Temporary worldgen function. Will be replaced later with something
that actually looks nice. Takes size and noise amplitude
and returns chunk vertices for use in other functions."""
worlda = []
worldb = []
world = []
if size > 4:
... | [
"pybullet.resetSimulation",
"random.randint",
"math.floor",
"pybullet.removeBody",
"pybullet.createCollisionShape"
] | [((1854, 1880), 'pybullet.resetSimulation', 'pybullet.resetSimulation', ([], {}), '()\n', (1878, 1880), False, 'import pybullet\n'), ((1826, 1850), 'pybullet.removeBody', 'pybullet.removeBody', (['box'], {}), '(box)\n', (1845, 1850), False, 'import pybullet\n'), ((1984, 2057), 'pybullet.createCollisionShape', 'pybullet... |
import json
import fire
from tqdm import tqdm
from metrics import cal_entropy, cal_length, calculate_metrics
def validate(file_name):
with open(file_name, "r", encoding='utf-8') as f:
json_data = f.read()
data = json.loads(json_data)
bleu_2scores = 0
bleu_4scores = 0
nist_2scores... | [
"metrics.cal_length",
"tqdm.tqdm",
"metrics.calculate_metrics",
"fire.Fire",
"json.loads",
"metrics.cal_entropy"
] | [((401, 411), 'tqdm.tqdm', 'tqdm', (['data'], {}), '(data)\n', (405, 411), False, 'from tqdm import tqdm\n'), ((902, 924), 'metrics.cal_entropy', 'cal_entropy', (['sentences'], {}), '(sentences)\n', (913, 924), False, 'from metrics import cal_entropy, cal_length, calculate_metrics\n'), ((949, 970), 'metrics.cal_length'... |
"""
Utils operations
----------------
Collection of util operations for timeseries.
"""
import numpy as np
from scipy import signal, interpolate
def join_regimes(times, magnitudes):
"""Join different time series which represents events time series of
different regimes and join altogether creating random va... | [
"numpy.argsort",
"numpy.arange",
"scipy.signal.gaussian",
"scipy.signal.convolve",
"numpy.concatenate",
"numpy.atleast_2d"
] | [((972, 993), 'numpy.concatenate', 'np.concatenate', (['times'], {}), '(times)\n', (986, 993), True, 'import numpy as np\n'), ((1007, 1029), 'numpy.concatenate', 'np.concatenate', (['values'], {}), '(values)\n', (1021, 1029), True, 'import numpy as np\n'), ((1041, 1058), 'numpy.argsort', 'np.argsort', (['times'], {}), ... |
import numpy as np
x1 = [1, 2, 3]
x2 = [1, 1, 1]
result = np.subtract(x1, x2)
print(result)
print(range(4))
| [
"numpy.subtract"
] | [((60, 79), 'numpy.subtract', 'np.subtract', (['x1', 'x2'], {}), '(x1, x2)\n', (71, 79), True, 'import numpy as np\n')] |
import logging
import httpx
from aiogram import Bot, types
from aiogram.contrib.middlewares.logging import LoggingMiddleware
from aiogram.dispatcher import Dispatcher
from aiogram.utils.executor import start_webhook
from bot.settings import *
bot = Bot(token=BOT_TOKEN)
dp = Dispatcher(bot)
dp.middleware.setup(Logging... | [
"logging.basicConfig",
"logging.warning",
"aiogram.contrib.middlewares.logging.LoggingMiddleware",
"aiogram.Bot",
"aiogram.dispatcher.Dispatcher",
"aiogram.utils.executor.start_webhook",
"httpx.post"
] | [((251, 271), 'aiogram.Bot', 'Bot', ([], {'token': 'BOT_TOKEN'}), '(token=BOT_TOKEN)\n', (254, 271), False, 'from aiogram import Bot, types\n'), ((277, 292), 'aiogram.dispatcher.Dispatcher', 'Dispatcher', (['bot'], {}), '(bot)\n', (287, 292), False, 'from aiogram.dispatcher import Dispatcher\n'), ((313, 332), 'aiogram.... |
import pke
import pandas as pd
import regex_extraction
pos = {'NOUN', 'PROPN', 'ADJ'}
extractor = pke.unsupervised.TextRank()
def getCandidatePhrases(transcript):
key_pos = {}
transcript = [regex_extraction.cleantext(transcript)]
for seg in transcript:
extractor.load_document(input=seg, language='... | [
"pandas.DataFrame",
"pke.unsupervised.TextRank",
"regex_extraction.cleantext"
] | [((99, 126), 'pke.unsupervised.TextRank', 'pke.unsupervised.TextRank', ([], {}), '()\n', (124, 126), False, 'import pke\n'), ((200, 238), 'regex_extraction.cleantext', 'regex_extraction.cleantext', (['transcript'], {}), '(transcript)\n', (226, 238), False, 'import regex_extraction\n'), ((482, 576), 'pandas.DataFrame', ... |
"""Support methods providing available stretching algorithms."""
# type annotations
from __future__ import annotations
from typing import TYPE_CHECKING
# standard libraries
import os
from dataclasses import dataclass, field, InitVar
from functools import partial
import importlib
# internal libraries
from ..resources... | [
"functools.partial",
"numpy.arctanh",
"importlib.util.spec_from_loader",
"numpy.genfromtxt",
"numpy.linspace",
"os.path.join",
"importlib.util.module_from_spec"
] | [((3074, 3109), 'numpy.linspace', 'numpy.linspace', (['low', 'high', '(size + 1)'], {}), '(low, high, size + 1)\n', (3088, 3109), False, 'import numpy\n'), ((5110, 5142), 'functools.partial', 'partial', (['tanh_mid'], {'alpha': 's_alpha'}), '(tanh_mid, alpha=s_alpha)\n', (5117, 5142), False, 'from functools import part... |
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
version = '0.0.4'
if sys.argv[-1] == 'publish':
try:
import wheel
print("Wheel version: ", wheel.__version__)
except ImportError:
print('Wheel library missing. Please ru... | [
"os.system",
"sys.exit",
"distutils.core.setup"
] | [((697, 1731), 'distutils.core.setup', 'setup', ([], {'name': '"""django-cloud-tasks"""', 'version': 'version', 'description': '"""Google Cloud Tasks integration for Django. Forked from https://github.com/GeorgeLubaretsi/django-cloud-tasks"""', 'long_description': 'readme', 'author': '"""rgutierrez-cotech"""', 'author_... |
import distutils.core
import json
import os
import re
import sys
import time
from distutils.version import LooseVersion
from glob import glob
from pathlib import Path
from typing import Any, Dict, List, Optional, cast
import click
import requests
import yaml
from bs4 import BeautifulSoup
from loguru import logger as l... | [
"json.load",
"loguru.logger.error",
"typing.cast",
"distutils.version.LooseVersion",
"loguru.logger.warning",
"click.option",
"re.match",
"loguru.logger.critical",
"time.sleep",
"click.command",
"pathlib.Path",
"controller.print_and_exit",
"yaml.safe_load_all",
"requests.get",
"glob.glob... | [((11437, 11452), 'click.command', 'click.command', ([], {}), '()\n', (11450, 11452), False, 'import click\n'), ((11454, 11513), 'click.option', 'click.option', (['"""--skip-angular"""'], {'is_flag': '(True)', 'default': '(False)'}), "('--skip-angular', is_flag=True, default=False)\n", (11466, 11513), False, 'import cl... |
from django.contrib import admin
from modeltranslation.admin import TranslationAdmin
from django import forms
from django.utils.translation import gettext as _
from dal import autocomplete
from . import models, translation
class TopicCollectionForm(forms.ModelForm):
class Meta:
model = models.TopicCollec... | [
"dal.autocomplete.ModelSelect2Multiple",
"django.contrib.admin.register",
"django.utils.translation.gettext"
] | [((485, 523), 'django.contrib.admin.register', 'admin.register', (['models.TopicCollection'], {}), '(models.TopicCollection)\n', (499, 523), False, 'from django.contrib import admin\n'), ((802, 848), 'django.contrib.admin.register', 'admin.register', (['models.ExternalTopicCollection'], {}), '(models.ExternalTopicColle... |
import socket
import json
import paho.mqtt.client as mqtt
def start_udp_server(ip: str = "0.0.0.0", port: int = 7000, broker_ip: str = "127.0.0.1", broker_port: int = 7000,
buffer_size: int = 2048):
# Create a datagram socket and bind ip:port
udp_server_socket = socket.socket(family=socke... | [
"paho.mqtt.client.Client",
"socket.socket",
"json.loads"
] | [((294, 354), 'socket.socket', 'socket.socket', ([], {'family': 'socket.AF_INET', 'type': 'socket.SOCK_DGRAM'}), '(family=socket.AF_INET, type=socket.SOCK_DGRAM)\n', (307, 354), False, 'import socket\n'), ((1355, 1371), 'json.loads', 'json.loads', (['file'], {}), '(file)\n', (1365, 1371), False, 'import json\n'), ((147... |
#########################################
## Written by <EMAIL>
## The script will migrate specified fargate services to EC2 services to be managed by Spot.io Ocean.
## The script will do the following:
## 1) Clone each fargate service/s task definition to to an EC2 task definition
## 2) Create a duplicate service run... | [
"json.loads",
"time.sleep",
"requests.get",
"requests.post",
"sys.exit"
] | [((880, 926), 'requests.post', 'requests.post', (['url'], {'json': 'data', 'headers': 'headers'}), '(url, json=data, headers=headers)\n', (893, 926), False, 'import requests\n'), ((1300, 1310), 'sys.exit', 'sys.exit', ([], {}), '()\n', (1308, 1310), False, 'import sys\n'), ((1425, 1439), 'time.sleep', 'time.sleep', (['... |
'''
Class for loading data into Pytorch float tensor
From: https://gitlab.com/acasamitjana/latentmodels_ad
'''
import torch
from torch.functional import Tensor
from torchvision import transforms
from torch.utils.data import Dataset
import numpy as np
import pandas as pd
class MyDataset(Dataset):
def __init__(sel... | [
"numpy.shape",
"torch.from_numpy"
] | [((603, 625), 'numpy.shape', 'np.shape', (['self.data[0]'], {}), '(self.data[0])\n', (611, 625), True, 'import numpy as np\n'), ((1595, 1617), 'numpy.shape', 'np.shape', (['self.data[0]'], {}), '(self.data[0])\n', (1603, 1617), True, 'import numpy as np\n'), ((789, 808), 'numpy.shape', 'np.shape', (['self.data'], {}), ... |
# Generated by Django 3.1.6 on 2022-01-18 09:41
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('datasets', '0058_auto_20211215_0715'),
]
operations = [
migrations.RemoveField(
model_name='connection',
name='time_out',
... | [
"django.db.migrations.RemoveField"
] | [((228, 292), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""connection"""', 'name': '"""time_out"""'}), "(model_name='connection', name='time_out')\n", (250, 292), False, 'from django.db import migrations\n')] |
from matplotlib import pyplot as plt
import argparse
import matplotlib as mpl
import numpy as np
import cv2
import json
from pathlib import Path
from datetime import datetime
def draw_marker(x, y, img, color=(0, 0, 255), cross_size=5):
"""Draw marker location on image."""
x, y = int(x), int(y)
cv2.line(im... | [
"argparse.ArgumentParser",
"cv2.solvePnP",
"pathlib.Path",
"numpy.linalg.norm",
"cv2.imshow",
"cv2.line",
"cv2.setMouseCallback",
"cv2.drawFrameAxes",
"cv2.destroyAllWindows",
"datetime.datetime.now",
"json.dump",
"cv2.circle",
"cv2.waitKey",
"cv2.projectPoints",
"cv2.resizeWindow",
"j... | [((309, 384), 'cv2.line', 'cv2.line', (['img', '(x - cross_size, y)', '(x + cross_size, y)', 'color'], {'thickness': '(1)'}), '(img, (x - cross_size, y), (x + cross_size, y), color, thickness=1)\n', (317, 384), False, 'import cv2\n'), ((389, 464), 'cv2.line', 'cv2.line', (['img', '(x, y - cross_size)', '(x, y + cross_s... |
from CGATReport.Tracker import *
import pandas as pd
from pandas.io import sql
class GenderPlotter(TrackerSQL):
pattern = "(.+)"
def __call__(self, track, slice=None):
column = "f_31_0_0"
statement = "SELECT f_eid, %(column)s from ukb4882"
df = sql.read_sql(statement,
... | [
"pandas.io.sql.read_sql"
] | [((283, 330), 'pandas.io.sql.read_sql', 'sql.read_sql', (['statement', 'dbh'], {'index_col': '"""f_eid"""'}), "(statement, dbh, index_col='f_eid')\n", (295, 330), False, 'from pandas.io import sql\n')] |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 15 18:24:03 2021
@author: <NAME>
"""
import os
import numpy as np
import nibabel as nib
# input_path = r'G:\MINCVM\PCLKO\PCP2-DTR\maps\\'
# output_path = r'G:\MINCVM\PCLKO\PCP2-DTR\maps\Extracted\\'
input_path = r'G:\MINCVM\PCLKO\HOPX-DTR\maps\\'
output_path = r'G:\MI... | [
"nibabel.Nifti1Image",
"nibabel.load",
"numpy.empty",
"numpy.asarray",
"nibabel.save",
"numpy.diag",
"os.listdir"
] | [((371, 393), 'os.listdir', 'os.listdir', (['input_path'], {}), '(input_path)\n', (381, 393), False, 'import os\n'), ((486, 519), 'nibabel.load', 'nib.load', (['(input_path + image_name)'], {}), '(input_path + image_name)\n', (494, 519), True, 'import nibabel as nib\n'), ((585, 605), 'numpy.asarray', 'np.asarray', (['i... |
import numpy as np
import scipy.ndimage as nd
def interpolate_nn(data: np.array) -> np.array:
"""
Function to fill nan values in a 2D array using nearest neighbor
interpolation.
Source: https://stackoverflow.com/a/27745627
Parameters
----------
data : np.array
Data array (2D) in ... | [
"numpy.isnan"
] | [((503, 517), 'numpy.isnan', 'np.isnan', (['data'], {}), '(data)\n', (511, 517), True, 'import numpy as np\n')] |
#!/usr/bin/env python3.8
from password import User
import sys, pyperclip
def create_user(account,fname,lname,uname,phone,email,password):
'''
Function to create a new user
'''
new_user = User(account,fname,lname,uname,phone,email,password)
return new_user
def save_users(user):
'''
Functi... | [
"password.User",
"password.User.user_exist",
"password.User.copy_password",
"password.User.display_users",
"password.User.find_by_username"
] | [((206, 264), 'password.User', 'User', (['account', 'fname', 'lname', 'uname', 'phone', 'email', 'password'], {}), '(account, fname, lname, uname, phone, email, password)\n', (210, 264), False, 'from password import User\n'), ((572, 603), 'password.User.find_by_username', 'User.find_by_username', (['username'], {}), '(... |
# Generated by Django 3.1.4 on 2020-12-02 11:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('items', '0002_remove_item_category'),
]
operations = [
migrations.RemoveField(
model_name='item',
name='units',
... | [
"django.db.migrations.RemoveField",
"django.db.models.CharField"
] | [((235, 290), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""item"""', 'name': '"""units"""'}), "(model_name='item', name='units')\n", (257, 290), False, 'from django.db import migrations, models\n'), ((434, 481), 'django.db.models.CharField', 'models.CharField', ([], {'default': ... |
# This class should provide easy access to the different aspects of the
# buildsystem such as layers, bitbake location, etc.
import stat
import shutil
def _smart_copy(src, dest):
# smart_copy will choose the correct function depending on whether the
# source is a file or a directory.
mode = os.stat(src).st... | [
"shutil.copyfile",
"stat.S_ISDIR",
"shutil.copymode",
"shutil.copytree"
] | [((333, 351), 'stat.S_ISDIR', 'stat.S_ISDIR', (['mode'], {}), '(mode)\n', (345, 351), False, 'import stat\n'), ((361, 402), 'shutil.copytree', 'shutil.copytree', (['src', 'dest'], {'symlinks': '(True)'}), '(src, dest, symlinks=True)\n', (376, 402), False, 'import shutil\n'), ((421, 447), 'shutil.copyfile', 'shutil.copy... |
from pyspark import SparkContext
def minMaxData(temp):
return max(temp)+min(temp)
sparkContxt = SparkContext(appName="Lab-1_Task_3") #Name of the job
temperatureData = sparkContxt.textFile("BDA/input/temperature-readings.csv")
readLines = temperatureData.map(lambda line: line.split(";"))
stationTemperature = rea... | [
"pyspark.SparkContext"
] | [((102, 138), 'pyspark.SparkContext', 'SparkContext', ([], {'appName': '"""Lab-1_Task_3"""'}), "(appName='Lab-1_Task_3')\n", (114, 138), False, 'from pyspark import SparkContext\n')] |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | [
"absl.testing.absltest.main",
"io.BytesIO",
"tink.python.util.file_object_adapter.FileObjectAdapter"
] | [((3160, 3175), 'absl.testing.absltest.main', 'absltest.main', ([], {}), '()\n', (3173, 3175), False, 'from absl.testing import absltest\n'), ((897, 909), 'io.BytesIO', 'io.BytesIO', ([], {}), '()\n', (907, 909), False, 'import io\n'), ((924, 974), 'tink.python.util.file_object_adapter.FileObjectAdapter', 'file_object_... |
from nose.tools import assert_equal, assert_true
from numpy.testing import assert_array_equal
import numpy as np
import re
from seqlearn.evaluation import bio_f_score, SequenceKFold
def test_bio_f_score():
# Outputs from with the "conlleval" Perl script from CoNLL 2002.
examples = [
("OBIO", "OBIO",... | [
"numpy.testing.assert_array_equal",
"numpy.issubdtype",
"re.match",
"seqlearn.evaluation.bio_f_score"
] | [((590, 617), 'seqlearn.evaluation.bio_f_score', 'bio_f_score', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (601, 617), False, 'from seqlearn.evaluation import bio_f_score, SequenceKFold\n'), ((1761, 1793), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['(~train)', 'test'], {}), '(~train, test)\n', (... |
# Generated by Django 2.2.6 on 2019-11-06 21:59
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('betting', '0008_punter_user'),
]
operations = [
migrations.RenameField(
model_name='betplacing',
old_name='runner',
... | [
"django.db.migrations.RenameField"
] | [((220, 314), 'django.db.migrations.RenameField', 'migrations.RenameField', ([], {'model_name': '"""betplacing"""', 'old_name': '"""runner"""', 'new_name': '"""competitor"""'}), "(model_name='betplacing', old_name='runner', new_name\n ='competitor')\n", (242, 314), False, 'from django.db import migrations\n')] |
import threading
import uuid
import logging
log = logging.getLogger(__name__)
def bypass(fa, fb):
def mix(*args, **kwargs):
fa(*args, **kwargs)
fb(*args, **kwargs)
return mix
class ProcWorker(threading.Thread):
def __init__(self, i_q, o_q):
super(ProcWorker, self).__init__()
... | [
"uuid.uuid4",
"threading.Event",
"logging.getLogger"
] | [((51, 78), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (68, 78), False, 'import logging\n'), ((337, 349), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (347, 349), False, 'import uuid\n'), ((442, 459), 'threading.Event', 'threading.Event', ([], {}), '()\n', (457, 459), False, 'import ... |
"""
MIT License
Copyright (c) 2021 UltronRoBo
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, di... | [
"UltronRoBo.modules.sql.blacklistusers_sql.get_reason",
"UltronRoBo.modules.sql.blacklistusers_sql.blacklist_user",
"UltronRoBo.modules.helper_funcs.extraction.extract_user",
"UltronRoBo.modules.sql.blacklistusers_sql.unblacklist_user",
"UltronRoBo.modules.sql.blacklistusers_sql.is_user_blacklisted",
"Ult... | [((5545, 5578), 'telegram.ext.CommandHandler', 'CommandHandler', (['"""ignore"""', 'bl_user'], {}), "('ignore', bl_user)\n", (5559, 5578), False, 'from telegram.ext import CallbackContext, CommandHandler, run_async\n'), ((5594, 5629), 'telegram.ext.CommandHandler', 'CommandHandler', (['"""notice"""', 'unbl_user'], {}),... |
"""
6_problem.py
In this problem, we will look for smallest and largest integer from a list of
unsorted integers. The code should run in O(n) time. Do not use Python's
built-in functions to find min and max.
Bonus Challenge: Is it possible to find the max and min in a single traversal?
"""
def find_min_max(input_lis... | [
"random.shuffle"
] | [((1275, 1292), 'random.shuffle', 'random.shuffle', (['l'], {}), '(l)\n', (1289, 1292), False, 'import random\n')] |
from aiogram.dispatcher.filters.state import StatesGroup, State
class Request(StatesGroup):
# if 'создать заявку' нажал админ ('admin') заявителем будет чейндж
# if 'создать заявку' нажал чейндж ('changer') заявителем будет чейндж
request_numb = State()
applicant = State()
operation_type = State()... | [
"aiogram.dispatcher.filters.state.State"
] | [((260, 267), 'aiogram.dispatcher.filters.state.State', 'State', ([], {}), '()\n', (265, 267), False, 'from aiogram.dispatcher.filters.state import StatesGroup, State\n'), ((284, 291), 'aiogram.dispatcher.filters.state.State', 'State', ([], {}), '()\n', (289, 291), False, 'from aiogram.dispatcher.filters.state import S... |
from gtfs_util.model import MixIn
from gtfs_util.realtime import data
from collections import namedtuple
class VehiclePosition(namedtuple(
'VehiclePosition',
[
'trip',
'position',
'timestamp',
'stop_id',
'vehicle',
],
), MixIn):
NAME_MAPPING = {}
DATA_MAPPI... | [
"collections.namedtuple"
] | [((130, 220), 'collections.namedtuple', 'namedtuple', (['"""VehiclePosition"""', "['trip', 'position', 'timestamp', 'stop_id', 'vehicle']"], {}), "('VehiclePosition', ['trip', 'position', 'timestamp', 'stop_id',\n 'vehicle'])\n", (140, 220), False, 'from collections import namedtuple\n')] |
import os
import signal
from time import sleep
import sys
from flask import Flask
from flask import request
app = Flask(__name__)
@app.route("/")
def hello():
return str(os.environ['SERVICE_NAME'])
def handler(signum, frame):
sleep(4)
sys.exit(0)
if __name__ == '__main__':
signal.signal(signal.SIG... | [
"signal.signal",
"flask.Flask",
"sys.exit",
"time.sleep"
] | [((115, 130), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (120, 130), False, 'from flask import Flask\n'), ((239, 247), 'time.sleep', 'sleep', (['(4)'], {}), '(4)\n', (244, 247), False, 'from time import sleep\n'), ((252, 263), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (260, 263), False, 'import s... |
import collections
import six
from ..compat \
import \
OrderedDict
from ..errors \
import \
DepSolverError
from ..requirement \
import \
Requirement
from ..version \
import \
MaxVersion
R = Requirement.from_string
class DefaultPolicy(object):
"""A Policy class tha... | [
"six.itervalues",
"collections.deque"
] | [((3035, 3065), 'six.itervalues', 'six.itervalues', (['package_queues'], {}), '(package_queues)\n', (3049, 3065), False, 'import six\n'), ((1463, 1482), 'collections.deque', 'collections.deque', ([], {}), '()\n', (1480, 1482), False, 'import collections\n')] |
# -*- coding: utf-8 -*-
"""
Created on 2020.05.19
@author: <NAME>, <NAME>, <NAME>, <NAME>
Code based on:
Shang et al "Edge Attention-based Multi-Relational Graph Convolutional Networks" -> https://github.com/Luckick/EAGCN
Coley et al "Convolutional Embedding of Attributed Molecular Graphs for Physical Property Predic... | [
"torch.nn.Dropout",
"torch.diagonal",
"torch.nn.Embedding",
"torch.nn.init._no_grad_normal_",
"torch.nn.Softmax",
"torch.nn.functional.leaky_relu",
"torch.ones",
"torch.exp",
"torch.Tensor",
"torch.nn.Linear",
"torch.zeros",
"torch.nn.GRU",
"copy.deepcopy",
"math.sqrt",
"torch.nn.Tanh",
... | [((15190, 15219), 'torch.nn.functional.softmax', 'F.softmax', (['out_scores'], {'dim': '(-1)'}), '(out_scores, dim=-1)\n', (15199, 15219), True, 'import torch.nn.functional as F\n'), ((15234, 15262), 'torch.nn.functional.softmax', 'F.softmax', (['in_scores'], {'dim': '(-1)'}), '(in_scores, dim=-1)\n', (15243, 15262), T... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
##################################################
# GNU Radio Python Flow Graph
# Title: Top Block
# Generated: Fri Apr 19 11:25:15 2019
##################################################
from gnuradio import blocks
from gnuradio import eng_notation
from gnuradio import... | [
"gnuradio.blocks.vector_sink_b",
"gnuradio.blocks.head",
"gnuradio.blocks.vector_source_b",
"gnuradio.blocks.unpack_k_bits_bb",
"gnuradio.gr.top_block.__init__",
"gnuradio.blocks.throttle"
] | [((567, 607), 'gnuradio.gr.top_block.__init__', 'gr.top_block.__init__', (['self', '"""Top Block"""'], {}), "(self, 'Top Block')\n", (588, 607), False, 'from gnuradio import gr\n'), ((1007, 1061), 'gnuradio.blocks.vector_source_b', 'blocks.vector_source_b', (['self.source_tuple', '(True)', '(1)', '[]'], {}), '(self.sou... |
import numpy as np
import pandas as pd
from typing import Union
def unit_vector(azi:Union[int,float]) -> np.array:
"""
Get the unit vector2D of a given azimuth
Input:
azi -> (int,float) Azimuth in Degrees
Return:
u -> (np.ndarray) numpy array with a shape of (2,1) with the x and y com... | [
"numpy.deg2rad",
"numpy.sin",
"numpy.array",
"numpy.cos",
"numpy.dot",
"numpy.atleast_1d"
] | [((438, 455), 'numpy.deg2rad', 'np.deg2rad', (['alpha'], {}), '(alpha)\n', (448, 455), True, 'import numpy as np\n'), ((464, 481), 'numpy.cos', 'np.cos', (['alpha_rad'], {}), '(alpha_rad)\n', (470, 481), True, 'import numpy as np\n'), ((490, 507), 'numpy.sin', 'np.sin', (['alpha_rad'], {}), '(alpha_rad)\n', (496, 507),... |
from django import forms
from django.forms.widgets import CheckboxInput
from .models import Topic, Entry
class TopicForm(forms.ModelForm):
private = forms.BooleanField(required = False)
class Meta:
model = Topic
fields = ['text']
labels = {'text': ''}
widgets = {
'... | [
"django.forms.BooleanField",
"django.forms.widgets.CheckboxInput",
"django.forms.Textarea"
] | [((155, 189), 'django.forms.BooleanField', 'forms.BooleanField', ([], {'required': '(False)'}), '(required=False)\n', (173, 189), False, 'from django import forms\n'), ((331, 373), 'django.forms.widgets.CheckboxInput', 'CheckboxInput', ([], {'attrs': "{'class': 'checkbox'}"}), "(attrs={'class': 'checkbox'})\n", (344, 3... |
import time
import numpy as np
import analyzer
import config as cfg
import explots
import fileutils
import motifutils as motif
import visutils
def _analysis(analysis_name, audio, fs, length, methods, name='audio', show_plot=(),
k=cfg.N_ClUSTERS, title_hook='{}', threshold=cfg.K_THRESH):
G_dict = {... | [
"fileutils.write_audio",
"numpy.ceil",
"analyzer.analyze",
"time.time",
"visutils.show",
"motifutils.pack_motif",
"fileutils.load_audio",
"explots.draw_results",
"numpy.unique"
] | [((6261, 6305), 'fileutils.load_audio', 'fileutils.load_audio', (['name'], {'audio_dir': 'in_dir'}), '(name, audio_dir=in_dir)\n', (6281, 6305), False, 'import fileutils\n'), ((7285, 7300), 'visutils.show', 'visutils.show', ([], {}), '()\n', (7298, 7300), False, 'import visutils\n'), ((2297, 2341), 'motifutils.pack_mot... |
# Python solution for 'First non-repeating character' codewars question.
# Level: 5 kyu
# Tags: ALGORITHMS, STRINGS, and SEARCH.
# Author: <NAME>
# Date: 26/05/2020
import unittest
def first_non_repeating_letter(string):
"""
Finds and returns the first non repeating character inside a string.
:param stri... | [
"unittest.main"
] | [((1419, 1434), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1432, 1434), False, 'import unittest\n')] |
import numpy as np
import cv2
import matplotlib.pyplot as plt
from keras.models import load_model
print('model loading...')
model = load_model('face_CET.h5')
print('model loaded')
def preprocess(img):
img = cv2.resize(img,(200,200))
img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
img = img.reshape(1,200,200,1... | [
"keras.models.load_model",
"cv2.putText",
"cv2.cvtColor",
"cv2.waitKey",
"cv2.imshow",
"cv2.VideoCapture",
"cv2.rectangle",
"cv2.CascadeClassifier",
"cv2.destroyAllWindows",
"cv2.resize"
] | [((134, 159), 'keras.models.load_model', 'load_model', (['"""face_CET.h5"""'], {}), "('face_CET.h5')\n", (144, 159), False, 'from keras.models import load_model\n'), ((421, 477), 'cv2.CascadeClassifier', 'cv2.CascadeClassifier', (['(cv2.data.haarcascades + face_data)'], {}), '(cv2.data.haarcascades + face_data)\n', (44... |
#!/usr/bin/env python
# coding:utf-8
"""
permission.py
~~~~~~~~~~~~~
Permissions and Role
"""
from fine import db
class Permission(object):
READ_POST = 0x01
WRITE_POST = 0x02
DELETE_POST = 0x04
FOLLOW = 0X08
COMMENT = 0X10
EDIT_COMMENT = 0x20
DELETE_COMMENT = 0x40
ADMIN =... | [
"fine.db.session.commit",
"fine.db.session.add",
"fine.db.String",
"fine.db.Column"
] | [((387, 426), 'fine.db.Column', 'db.Column', (['db.Integer'], {'primary_key': '(True)'}), '(db.Integer, primary_key=True)\n', (396, 426), False, 'from fine import db\n'), ((490, 538), 'fine.db.Column', 'db.Column', (['db.Boolean'], {'default': '(False)', 'index': '(True)'}), '(db.Boolean, default=False, index=True)\n',... |
__all__ = ["predict", "predict_from_dl", "convert_raw_predictions", "end2end_detect"]
from icevision.imports import *
from icevision.utils import *
from icevision.core import *
from icevision.data import *
from icevision.models.utils import _predict_from_dl
from icevision.models.ross.efficientdet.dataloaders import *
... | [
"effdet.unwrap_bench",
"icevision.models.utils._predict_from_dl"
] | [((1875, 2018), 'icevision.models.utils._predict_from_dl', '_predict_from_dl', ([], {'predict_fn': '_predict_batch', 'model': 'model', 'infer_dl': 'infer_dl', 'show_pbar': 'show_pbar', 'keep_images': 'keep_images'}), '(predict_fn=_predict_batch, model=model, infer_dl=infer_dl,\n show_pbar=show_pbar, keep_images=keep... |