code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import base64
import hashlib
from Crypto import Random
from Crypto.Cipher import AES
'''
Encryption
@description For arbitrary encryption and decryption of data
@author <NAME>
Usage:
e = Encryption()
encrypted_string = e.encrypt("Encrypt me!", "password")
decrypted = e.decrypt(encrypted_str... | [
"hashlib.sha256",
"Crypto.Random.new",
"Crypto.Cipher.AES.new",
"base64.b64decode"
] | [((569, 599), 'Crypto.Cipher.AES.new', 'AES.new', (['key', 'AES.MODE_CBC', 'iv'], {}), '(key, AES.MODE_CBC, iv)\n', (576, 599), False, 'from Crypto.Cipher import AES\n'), ((766, 794), 'base64.b64decode', 'base64.b64decode', (['ciphertext'], {}), '(ciphertext)\n', (782, 794), False, 'import base64\n'), ((829, 859), 'Cry... |
import pandas as pd
import os
def ensure_dir(file_path):
directory = os.path.dirname(file_path)
if directory and not os.path.exists(directory):
print("Creating new directory", directory)
os.makedirs(directory)
import json
def get_cfg_str(x):
# json.dumps(r.to_dict(), sort_keys=True, separators = (',', ... | [
"pandas.DataFrame",
"os.makedirs",
"pandas.read_csv",
"os.path.dirname",
"os.path.exists",
"PyPDF2.PdfFileMerger"
] | [((72, 98), 'os.path.dirname', 'os.path.dirname', (['file_path'], {}), '(file_path)\n', (87, 98), False, 'import os\n'), ((562, 576), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (574, 576), True, 'import pandas as pd\n'), ((1086, 1101), 'PyPDF2.PdfFileMerger', 'PdfFileMerger', ([], {}), '()\n', (1099, 1101), ... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: create_task.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf... | [
"google.protobuf.symbol_database.Default",
"google.protobuf.descriptor.FieldDescriptor",
"google.protobuf.reflection.GeneratedProtocolMessageType"
] | [((465, 491), 'google.protobuf.symbol_database.Default', '_symbol_database.Default', ([], {}), '()\n', (489, 491), True, 'from google.protobuf import symbol_database as _symbol_database\n'), ((8242, 8414), 'google.protobuf.reflection.GeneratedProtocolMessageType', '_reflection.GeneratedProtocolMessageType', (['"""Creat... |
#!/usr/bin/python
import sys, json, os, datetime
import logging, logging.handlers
import splunk.entity as entity
import splunk
import requests
# Tower Connect
#
# This script is used as wrapper to connect to Ansible Tower API.
## Original from:
# __author__ = "<NAME>"
# __email__ = "<EMAIL>"
# __version__ = "1.0"
#... | [
"sys.stdin.read",
"json.loads",
"splunk.setupSplunkLogger",
"sys.exit",
"splunk.entity.getEntities",
"json.dumps",
"logging.Formatter",
"requests.post",
"os.path.join",
"logging.getLogger"
] | [((447, 484), 'logging.getLogger', 'logging.getLogger', (['"""splunk.tower_api"""'], {}), "('splunk.tower_api')\n", (464, 484), False, 'import logging, logging.handlers\n'), ((557, 600), 'os.path.join', 'os.path.join', (['SPLUNK_HOME', '"""etc"""', '"""log.cfg"""'], {}), "(SPLUNK_HOME, 'etc', 'log.cfg')\n", (569, 600),... |
import os
from dotenv import load_dotenv
from sqlalchemy import create_engine, Column, String, Date, Numeric, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
load_dotenv(verbose=True)
db_link = os.getenv("DB_LINK")
db = create_engine(db_link)
base = declarative_base()
class JS020(base):
__ta... | [
"sqlalchemy.String",
"sqlalchemy.ForeignKey",
"dotenv.load_dotenv",
"sqlalchemy.ext.declarative.declarative_base",
"sqlalchemy.Numeric",
"sqlalchemy.Column",
"sqlalchemy.create_engine",
"os.getenv"
] | [((179, 204), 'dotenv.load_dotenv', 'load_dotenv', ([], {'verbose': '(True)'}), '(verbose=True)\n', (190, 204), False, 'from dotenv import load_dotenv\n'), ((216, 236), 'os.getenv', 'os.getenv', (['"""DB_LINK"""'], {}), "('DB_LINK')\n", (225, 236), False, 'import os\n'), ((242, 264), 'sqlalchemy.create_engine', 'create... |
from bilibili import bilibili
import requests
import asyncio
import time
class LotteryResult(bilibili):
async def query(self):
while 1:
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), "检查抽奖结果")
# print(self.activity_raffleid_list)
if s... | [
"requests.get",
"asyncio.sleep",
"time.time"
] | [((3016, 3033), 'asyncio.sleep', 'asyncio.sleep', (['(60)'], {}), '(60)\n', (3029, 3033), False, 'import asyncio\n'), ((1146, 1180), 'requests.get', 'requests.get', (['url'], {'headers': 'headers'}), '(url, headers=headers)\n', (1158, 1180), False, 'import requests\n'), ((2457, 2491), 'requests.get', 'requests.get', ([... |
#!/usr/bin/env python
from telegram import TelegramObject
class Message(TelegramObject):
def __init__(self,
message_id,
from_user,
date,
chat,
forward_from=None,
forward_date=None,
... | [
"telegram.Contact.de_json",
"telegram.Audio.de_json",
"telegram.Video.de_json",
"telegram.GroupChat.de_json",
"telegram.Document.de_json",
"telegram.Location.de_json",
"telegram.PhotoSize.de_json",
"telegram.User.de_json",
"telegram.Sticker.de_json"
] | [((1925, 1951), 'telegram.User.de_json', 'User.de_json', (["data['from']"], {}), "(data['from'])\n", (1937, 1951), False, 'from telegram import User\n'), ((2457, 2491), 'telegram.User.de_json', 'User.de_json', (["data['forward_from']"], {}), "(data['forward_from'])\n", (2469, 2491), False, 'from telegram import User\n'... |
from setuptools import setup
setup(
name='graphs',
packages=['graphs'],
include_package_data=True,
install_requires=[
'flask',
'matplotlib',
]
) | [
"setuptools.setup"
] | [((30, 144), 'setuptools.setup', 'setup', ([], {'name': '"""graphs"""', 'packages': "['graphs']", 'include_package_data': '(True)', 'install_requires': "['flask', 'matplotlib']"}), "(name='graphs', packages=['graphs'], include_package_data=True,\n install_requires=['flask', 'matplotlib'])\n", (35, 144), False, 'from... |
__author__ = "<NAME>"
__copyright__ = "Copyright (c) 2020 <NAME> (lullimat/idea.deploy), <EMAIL>"
__credits__ = ["<NAME>"]
__license__ = """
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 ... | [
"sympy.symbols",
"sympy.solvers.solve",
"idpy.Utils.ManageData.ManageData.__init__",
"sympy.Rational",
"scipy.integrate.quad",
"sympy.diff",
"sympy.lambdify",
"idpy.Utils.ManageData.ManageData.WhichData",
"sympy.exp",
"scipy.optimize.bisect",
"idpy.Utils.ManageData.ManageData.PullData",
"idpy.... | [((3469, 3513), 'sympy.symbols', 'sp_symbols', (['"""n G \\\\theta \\\\psi \\\\psi\' e_{2}"""'], {}), '("n G \\\\theta \\\\psi \\\\psi\' e_{2}")\n', (3479, 3513), True, 'from sympy import symbols as sp_symbols\n'), ((3230, 3268), 'scipy.optimize.bisect', 'bisect', (['d_func', 'z_range[0]', 'z_range[1]'], {}), '(d_func,... |
from flask import render_template,request,redirect,url_for
from . import main
from ..requests import get_news, get_articles
from ..models import Source, Article
# Views
@main.route('/')
def index():
'''
Function that returns the index page and its data
'''
general_list = get_news('general')
health... | [
"flask.render_template"
] | [((533, 718), 'flask.render_template', 'render_template', (['"""index.html"""'], {'general': 'general_list', 'health': 'health_list', 'business': 'business_list', 'sports': 'sports_list', 'technology': 'technology_list', 'entertainment': 'entertainment_list'}), "('index.html', general=general_list, health=health_list,\... |
import sys
import types
import inspect
def isstring(s):
# if we use Python 3
if (sys.version_info[0] >= 3):
return isinstance(s, str)
# we use Python 2
return isinstance(s, basestring)
def normalize_func(func):
# return None for builtins
if (inspect.isbuiltin(func)):
return N... | [
"inspect.getargspec",
"inspect.isbuiltin",
"inspect.getdoc",
"inspect.getfullargspec"
] | [((278, 301), 'inspect.isbuiltin', 'inspect.isbuiltin', (['func'], {}), '(func)\n', (295, 301), False, 'import inspect\n'), ((368, 388), 'inspect.getdoc', 'inspect.getdoc', (['func'], {}), '(func)\n', (382, 388), False, 'import inspect\n'), ((500, 520), 'inspect.getdoc', 'inspect.getdoc', (['func'], {}), '(func)\n', (5... |
# -*- coding: utf-8 -*-
# *****************************************************************************
# ufit, a universal scattering fitting suite
#
# Copyright (c) 2013-2019, <NAME> and contributors. All rights reserved.
# Licensed under a 2-clause BSD license, see LICENSE.
# **************************************... | [
"numpy.log",
"numpy.sin",
"numpy.exp",
"numpy.cos",
"numpy.sqrt"
] | [((2370, 2382), 'numpy.sqrt', 'sqrt', (['(2 * pi)'], {}), '(2 * pi)\n', (2374, 2382), False, 'from numpy import exp, log, sqrt, sin, cos, pi\n'), ((8778, 8789), 'numpy.cos', 'cos', (['p[pth]'], {}), '(p[pth])\n', (8781, 8789), False, 'from numpy import exp, log, sqrt, sin, cos, pi\n'), ((8791, 8802), 'numpy.sin', 'sin'... |
# Generated by Django 2.1 on 2020-03-12 15:05
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('myCarApp', '0006_auto_20200312_1502'),
]
operations = [
migrations.RemoveField(
model_name='user',
name='groups',
),
... | [
"django.db.migrations.RemoveField",
"django.db.migrations.DeleteModel",
"django.db.migrations.RenameField"
] | [((226, 282), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""user"""', 'name': '"""groups"""'}), "(model_name='user', name='groups')\n", (248, 282), False, 'from django.db import migrations\n'), ((327, 393), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'mode... |
import numpy as np
from skopt.space import Space
from skopt.sampler import Grid
import matplotlib.pyplot as plt
import seaborn as sns
def plot_teacher_action():
space = Space([(-1., 1.), (-1., 1.)])
grid = Grid(border="include", use_full_layout=False)
action_manipulated = grid.generate(space.dimensions, 1... | [
"seaborn.set_style",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.show",
"seaborn.scatterplot",
"matplotlib.pyplot.ylim",
"skopt.sampler.Grid",
"skopt.space.Space",
"numpy.append",
"matplotlib.pyplot.figure",
"numpy.array",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.... | [((175, 208), 'skopt.space.Space', 'Space', (['[(-1.0, 1.0), (-1.0, 1.0)]'], {}), '([(-1.0, 1.0), (-1.0, 1.0)])\n', (180, 208), False, 'from skopt.space import Space\n'), ((216, 261), 'skopt.sampler.Grid', 'Grid', ([], {'border': '"""include"""', 'use_full_layout': '(False)'}), "(border='include', use_full_layout=False... |
import json
import os
import torch
from torch import nn
from root import from_root
from src.adversaries.adversary import Adversary, AdversaryOutput
from src.experiments.config import create_resnet
from src.misc.collection_object import DictObject
from src.misc.utils import model_device
class MomentumFgsmTransfer(Ad... | [
"src.misc.utils.model_device",
"json.load",
"root.from_root",
"torch.zeros_like",
"torch.norm",
"src.adversaries.adversary.AdversaryOutput",
"torch.sign",
"src.experiments.config.create_resnet",
"torch.no_grad"
] | [((1146, 1164), 'src.experiments.config.create_resnet', 'create_resnet', (['cfg'], {}), '(cfg)\n', (1159, 1164), False, 'from src.experiments.config import create_resnet\n'), ((2026, 2050), 'torch.zeros_like', 'torch.zeros_like', (['images'], {}), '(images)\n', (2042, 2050), False, 'import torch\n'), ((2670, 2710), 'sr... |
from random import randint
from time import sleep
itens = ('Pedra', 'Papel','Tesoura')
computador = randint(0, 2)
print('''\033[1;31mSuas opções\033[m:
[ 0 ] PEDRA
[ 1 ] PAPEL
[ 2 ] TESOURA''')
jogador = int(input('\033[1;34mQual é a sua Jogada?\033[m '))
print('\033[1;30mJO\033[m')
sleep(1)
print('\033[1;34mKEN\033[m'... | [
"random.randint",
"time.sleep"
] | [((100, 113), 'random.randint', 'randint', (['(0)', '(2)'], {}), '(0, 2)\n', (107, 113), False, 'from random import randint\n'), ((284, 292), 'time.sleep', 'sleep', (['(1)'], {}), '(1)\n', (289, 292), False, 'from time import sleep\n'), ((322, 330), 'time.sleep', 'sleep', (['(1)'], {}), '(1)\n', (327, 330), False, 'fro... |
# from distutils.core import setup
from setuptools import setup
import os
from docpie import __version__
setup(
name="docpie",
packages=["docpie"],
package_data={
'': [
'README.rst',
'LICENSE',
'CHANGELOG.md'
],
'docpie': [
'example/*... | [
"os.path.dirname"
] | [((822, 847), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (837, 847), False, 'import os\n')] |
# Test convolving to different resolutions
# Test the effect of convolving straight to 20000 and convolving first to an intermediate resolution say 80000.
import matplotlib.pyplot as plt
import numpy as np
from IP_multi_Convolution import ip_convolution, unitary_Gauss
def main():
# fwhm = lambda/R
fwhm = 2... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"numpy.ones_like",
"matplotlib.pyplot.legend",
"IP_multi_Convolution.unitary_Gauss",
"matplotlib.pyplot.figure",
"numpy.max",
"IP_multi_Convolution.ip_convolution",
"numpy.linspace",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel"
] | [((367, 397), 'numpy.linspace', 'np.linspace', (['(2040)', '(2050)', '(20000)'], {}), '(2040, 2050, 20000)\n', (378, 397), True, 'import numpy as np\n'), ((678, 764), 'IP_multi_Convolution.ip_convolution', 'ip_convolution', (['wav', 'flux', 'chip_limits', 'R'], {'fwhm_lim': '(5.0)', 'plot': '(False)', 'verbose': '(True... |
#!/usr/bin/env python3
""" Module to define API routes
"""
from api.v1.views import app_views
from flask import jsonify, request, abort, make_response
from engine.score_engine import score_engine
import requests
@app_views.route('/status', methods=['GET'], strict_slashes=False)
def status():
""" Status of API """... | [
"engine.score_engine.score_engine",
"flask.jsonify",
"api.v1.views.app_views.route",
"requests.get"
] | [((215, 280), 'api.v1.views.app_views.route', 'app_views.route', (['"""/status"""'], {'methods': "['GET']", 'strict_slashes': '(False)'}), "('/status', methods=['GET'], strict_slashes=False)\n", (230, 280), False, 'from api.v1.views import app_views\n'), ((360, 428), 'api.v1.views.app_views.route', 'app_views.route', (... |
import random
import time
random.seed(time.time())
def create_zero(count):
char_list = '0Oo***.\、.----。、~!O@0o/L#$%0/LOg/Lo^./L**&00.00*()0。g/L、、--/L---+|/0Oo[]#%$¥0~-/L--!/L@#oo*~~~¥0O%&*OO。[]0Oog/L'
lines = ''
for i in range(count):
# print("{} random {}".format(i, random.randint(3, 10)))
... | [
"random.shuffle",
"random.randint",
"time.time"
] | [((39, 50), 'time.time', 'time.time', ([], {}), '()\n', (48, 50), False, 'import time\n'), ((2698, 2723), 'random.shuffle', 'random.shuffle', (['line_list'], {}), '(line_list)\n', (2712, 2723), False, 'import random\n'), ((339, 360), 'random.randint', 'random.randint', (['(3)', '(10)'], {}), '(3, 10)\n', (353, 360), Fa... |
import os
import random
import re
import ssl
import tempfile
from urllib import request
import cv2
import imageio
import numpy as np
import tensorflow as tf
import tensorflow_hub as tfhub
UCF_ROOT = 'https://www.crcv.ucf.edu/THUMOS14/UCF101/UCF101/'
KINETICS_URL = ('https://raw.githubusercontent.com/deepmind/'
... | [
"cv2.resize",
"tensorflow.nn.softmax",
"tensorflow_hub.load",
"os.path.join",
"cv2.cvtColor",
"os.path.exists",
"random.choice",
"tensorflow.constant",
"numpy.clip",
"cv2.VideoCapture",
"urllib.request.urlopen",
"numpy.argsort",
"tempfile.mkdtemp",
"re.findall",
"numpy.array",
"ssl._cr... | [((385, 403), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (401, 403), False, 'import tempfile\n'), ((425, 457), 'ssl._create_unverified_context', 'ssl._create_unverified_context', ([], {}), '()\n', (455, 457), False, 'import ssl\n'), ((3091, 3113), 'tensorflow_hub.load', 'tfhub.load', (['model_path'], {})... |
import io
import json
from collections import defaultdict
from unittest.mock import patch
import responses
from httmock import HTTMock, response, urlmatch
from tests.helpers import DummyHttpResponse
from filestack import Client
from filestack.config import MULTIPART_START_URL
from filestack.uploads.multipart import u... | [
"io.BytesIO",
"httmock.response",
"httmock.urlmatch",
"responses.add",
"tests.helpers.DummyHttpResponse",
"filestack.Client",
"json.dumps",
"unittest.mock.patch",
"collections.defaultdict",
"httmock.HTTMock",
"responses.add_callback",
"filestack.uploads.multipart.upload_chunk",
"filestack.up... | [((1492, 1541), 'unittest.mock.patch', 'patch', (['"""filestack.uploads.multipart.requests.put"""'], {}), "('filestack.uploads.multipart.requests.put')\n", (1497, 1541), False, 'from unittest.mock import patch\n'), ((1543, 1593), 'unittest.mock.patch', 'patch', (['"""filestack.uploads.multipart.requests.post"""'], {}),... |
from construct import (
Float32l,
Float64l,
If,
Int8sl,
Int16sl,
Int16ul,
Int32sl,
Int32ul,
PaddedString,
Padding,
PrefixedArray,
Struct,
len_,
this,
)
def array(subcon):
return PrefixedArray(Int32ul, subcon)
Bend = Struct("time" / Float32l, "step" / Float... | [
"construct.len_",
"construct.PaddedString",
"construct.PrefixedArray",
"construct.Struct",
"construct.Padding"
] | [((361, 477), 'construct.Struct', 'Struct', (["('time' / Float32l)", "('measure' / Int16ul)", "('beat' / Int16ul)", "('phraseIteration' / Int32ul)", "('mask' / Int32ul)"], {}), "('time' / Float32l, 'measure' / Int16ul, 'beat' / Int16ul, \n 'phraseIteration' / Int32ul, 'mask' / Int32ul)\n", (367, 477), False, 'from c... |
# coding=utf-8
"""Given the dataset object, make a multithread enqueuer"""
import os
import queue
import threading
import contextlib
import multiprocessing
import time
import random
import sys
import utils
import traceback
import cv2
# modified from keras
class DatasetEnqueuer(object):
def __init__(
self,
... | [
"threading.Thread",
"multiprocessing.pool.ThreadPool",
"traceback.print_tb",
"utils.grouper",
"time.sleep",
"threading.Event",
"sys.exc_info",
"queue.Queue",
"cv2.resize"
] | [((1300, 1332), 'queue.Queue', 'queue.Queue', (['self.max_queue_size'], {}), '(self.max_queue_size)\n', (1311, 1332), False, 'import queue\n'), ((1360, 1377), 'threading.Event', 'threading.Event', ([], {}), '()\n', (1375, 1377), False, 'import threading\n'), ((1405, 1439), 'threading.Thread', 'threading.Thread', ([], {... |
import unittest
import events
from tests.testing_utils import is_valid_response, ValidResponseObjectTester
class TestEvents(unittest.TestCase):
def test_on_launch(self):
response = events.on_launch()
self.assertTrue(is_valid_response(response))
response_tester = ValidResponseObjectTester(... | [
"events.on_launch",
"tests.testing_utils.ValidResponseObjectTester",
"tests.testing_utils.is_valid_response"
] | [((196, 214), 'events.on_launch', 'events.on_launch', ([], {}), '()\n', (212, 214), False, 'import events\n'), ((294, 329), 'tests.testing_utils.ValidResponseObjectTester', 'ValidResponseObjectTester', (['response'], {}), '(response)\n', (319, 329), False, 'from tests.testing_utils import is_valid_response, ValidRespon... |
import imp
import os
import sys
from corsproxy.wsgi import application
sys.path.insert(0, os.path.dirname(__file__))
# wsgi = imp.load_source('wsgi', 'passenger_wsgi.py')
# application = wsgi.application
| [
"os.path.dirname"
] | [((91, 116), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (106, 116), False, 'import os\n')] |
#!/usr/bin/env python
from dataclasses import dataclass
from math import log2
from typing import Callable, Optional, Tuple, Union
import click
import PIL.Image
import PIL.ImageMath
from PIL.Image import Image
from PIL.ImageChops import darker, lighter
def _normalize_offset(offset: int, size: int) -> int:
return... | [
"click.option",
"click.argument",
"click.command"
] | [((2690, 2705), 'click.command', 'click.command', ([], {}), '()\n', (2703, 2705), False, 'import click\n'), ((2707, 2735), 'click.argument', 'click.argument', (['"""input_path"""'], {}), "('input_path')\n", (2721, 2735), False, 'import click\n'), ((2737, 2766), 'click.argument', 'click.argument', (['"""output_path"""']... |
from flask_task import Task
from models import *
import time
task = Task()
print(task)
@task.decorator
def proceso():
users = Users.query.all()
print(users)
time.sleep(7) | [
"flask_task.Task",
"time.sleep"
] | [((69, 75), 'flask_task.Task', 'Task', ([], {}), '()\n', (73, 75), False, 'from flask_task import Task\n'), ((171, 184), 'time.sleep', 'time.sleep', (['(7)'], {}), '(7)\n', (181, 184), False, 'import time\n')] |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.core.exceptions import ValidationError
from django.forms.models import model_to_dict, modelform_factory
from model_mommy.mommy import M... | [
"fakeapp.models.GenericIPAddressFieldModel.objects.get",
"django.forms.models.modelform_factory",
"fakeapp.models.GenericIPAddressFieldModel",
"model_mommy.mommy.Mommy",
"pytest.raises",
"django.forms.models.model_to_dict",
"fakeapp.models.GenericIPAddressFieldModel.objects.create",
"fakeapp.models.Ge... | [((501, 529), 'fakeapp.models.GenericIPAddressFieldModel', 'GenericIPAddressFieldModel', ([], {}), '()\n', (527, 529), False, 'from fakeapp.models import GenericIPAddressFieldModel\n'), ((608, 653), 'fakeapp.models.GenericIPAddressFieldModel', 'GenericIPAddressFieldModel', ([], {'field': '"""127.0.0.1"""'}), "(field='1... |
from peewee import SqliteDatabase, Model
from peewee import IntegerField, CharField, PrimaryKeyField, TimestampField
from pathlib import Path
from configparser import ConfigParser
config = ConfigParser()
config.read("config.ini", encoding="utf-8")
db = SqliteDatabase(Path.cwd() / config.get('main', 'database_... | [
"peewee.PrimaryKeyField",
"peewee.IntegerField",
"peewee.CharField",
"peewee.TimestampField",
"pathlib.Path.cwd",
"configparser.ConfigParser"
] | [((195, 209), 'configparser.ConfigParser', 'ConfigParser', ([], {}), '()\n', (207, 209), False, 'from configparser import ConfigParser\n'), ((436, 463), 'peewee.PrimaryKeyField', 'PrimaryKeyField', ([], {'null': '(False)'}), '(null=False)\n', (451, 463), False, 'from peewee import IntegerField, CharField, PrimaryKeyFie... |
from warnings import filterwarnings
PAD = "<PAD>"
UNK = "<UNK>"
MASK = "<MASK>"
BOS = "<BOS>"
EOS = "<EOS>"
def filter_warnings():
# "The dataloader does not have many workers which may be a bottleneck."
filterwarnings("ignore", category=UserWarning, module="pytorch_lightning.trainer.data_loading", lineno=10... | [
"warnings.filterwarnings"
] | [((215, 327), 'warnings.filterwarnings', 'filterwarnings', (['"""ignore"""'], {'category': 'UserWarning', 'module': '"""pytorch_lightning.trainer.data_loading"""', 'lineno': '(102)'}), "('ignore', category=UserWarning, module=\n 'pytorch_lightning.trainer.data_loading', lineno=102)\n", (229, 327), False, 'from warni... |
import logging
import re
import yaml
LOG = logging.getLogger(__name__)
def error_override_vars(override_vars, spec_filepath):
"""
Warn user if any given variable name isn't found in the original spec file.
"""
if override_vars is None:
return
original_text = open(spec_filepath, "r").rea... | [
"yaml.dump",
"re.sub",
"logging.getLogger",
"re.compile"
] | [((46, 73), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (63, 73), False, 'import logging\n'), ((1128, 1193), 'yaml.dump', 'yaml.dump', (['updated_env'], {'default_flow_style': '(False)', 'sort_keys': '(False)'}), '(updated_env, default_flow_style=False, sort_keys=False)\n', (1137, 1193... |
# coding: utf-8
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... | [
"oci.util.formatted_flat_dict"
] | [((3128, 3153), 'oci.util.formatted_flat_dict', 'formatted_flat_dict', (['self'], {}), '(self)\n', (3147, 3153), False, 'from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel\n')] |
import pygame
import pyscroll
from project.entities.player import Player
from .constants import FONTS, SCREEN_SCALE
from .world import World
class Renderer:
def __init__(self, width: int, height: int):
self.screen: pygame.Surface = None
self.surface: pygame.Surface = None
self._set_screen... | [
"pygame.Surface",
"pyscroll.PyscrollGroup",
"pygame.display.set_mode",
"pygame.Color",
"pygame.display.flip",
"pyscroll.BufferedRenderer",
"pygame.font.Font"
] | [((497, 599), 'pyscroll.BufferedRenderer', 'pyscroll.BufferedRenderer', (['world.map_data', '(w / SCREEN_SCALE, h / SCREEN_SCALE)'], {'clamp_camera': '(True)'}), '(world.map_data, (w / SCREEN_SCALE, h /\n SCREEN_SCALE), clamp_camera=True)\n', (522, 599), False, 'import pyscroll\n'), ((719, 784), 'pyscroll.PyscrollGr... |
from Main.Environments.Connect4 import Constants, Utils
from Tests.Environments.Connect4 import testCasesRawEvaluate
from unittest import TestCase
import numpy as np
class TestCreateMirroredStateAndPolicy(TestCase):
def testMirrorState(self):
AMOUNT_OF_TESTS_PER_CASE = 10
for case in te... | [
"Main.Environments.Connect4.Utils.state2ConvState",
"Main.Environments.Connect4.Utils.createMirroredStateAndPolicy",
"numpy.random.random",
"numpy.array",
"numpy.array_equal"
] | [((372, 389), 'numpy.array', 'np.array', (['case[0]'], {}), '(case[0])\n', (380, 389), True, 'import numpy as np\n'), ((450, 481), 'Main.Environments.Connect4.Utils.state2ConvState', 'Utils.state2ConvState', (['board', 'p'], {}), '(board, p)\n', (471, 481), False, 'from Main.Environments.Connect4 import Constants, Util... |
from PyQt5.QtCore import QThread, pyqtSignal
import settings
import socket
import Hotkey_Press
class Sock_Conn(QThread):
closeDiag = pyqtSignal()
def __init__(self):
QThread.__init__(self)
def __del__(self):
self.wait()
def run(self):
s = socket.socket(socket... | [
"PyQt5.QtCore.pyqtSignal",
"socket.socket",
"Hotkey_Press.Hotkey",
"PyQt5.QtCore.QThread.__init__"
] | [((146, 158), 'PyQt5.QtCore.pyqtSignal', 'pyqtSignal', ([], {}), '()\n', (156, 158), False, 'from PyQt5.QtCore import QThread, pyqtSignal\n'), ((195, 217), 'PyQt5.QtCore.QThread.__init__', 'QThread.__init__', (['self'], {}), '(self)\n', (211, 217), False, 'from PyQt5.QtCore import QThread, pyqtSignal\n'), ((300, 349), ... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | [
"superset.sql_parse.ParsedQuery",
"sqlparse.parse"
] | [((1015, 1221), 'superset.sql_parse.ParsedQuery', 'ParsedQuery', (['"""WITH blah AS\n (SELECT * FROM core_dev.manager_team),\n\nblah2 AS\n (SELECT * FROM core_dev.manager_workspace)\n\nSELECT * FROM blah\nINNER JOIN blah2 ON blah2.team_id = blah.team_id"""'], {}), '(\n """WITH blah AS\n (SELECT * FROM core_dev.ma... |
"""updateByLine.py Begun Apr 10, 2014
This program is intended to be rather general.
The 'changein' file consists of a sequence of line pairs:
nn old old-text
nn new new-text
nn is the line number (starting at 1) in the input vcp file.
'old' and 'new' are fixed.
old-text should be identical to the text of line ... | [
"re.search",
"codecs.open"
] | [((2283, 2332), 'codecs.open', 'codecs.open', (['changein'], {'encoding': '"""utf-8"""', 'mode': '"""r"""'}), "(changein, encoding='utf-8', mode='r')\n", (2294, 2332), False, 'import codecs\n'), ((4660, 4694), 'codecs.open', 'codecs.open', (['fileout', '"""w"""', '"""utf-8"""'], {}), "(fileout, 'w', 'utf-8')\n", (4671,... |
'''
VizUtil.py
Utilities for displaying satellite images,
with (optional) bound-box annotations
'''
import numpy as np
from matplotlib import pylab
import os
import skimage.color
def imshow(Im, block=False, figID=1):
figH = pylab.figure(num=figID)
figH.clf()
pylab.imshow(Im)
pylab.draw()
pylab.show(block=bl... | [
"matplotlib.pylab.savefig",
"matplotlib.pylab.xticks",
"numpy.minimum",
"numpy.maximum",
"matplotlib.pylab.subplot",
"matplotlib.pylab.imshow",
"numpy.asarray",
"matplotlib.pylab.figure",
"os.path.exists",
"matplotlib.pylab.axis",
"matplotlib.pylab.yticks",
"matplotlib.pylab.subplots",
"nump... | [((228, 251), 'matplotlib.pylab.figure', 'pylab.figure', ([], {'num': 'figID'}), '(num=figID)\n', (240, 251), False, 'from matplotlib import pylab\n'), ((267, 283), 'matplotlib.pylab.imshow', 'pylab.imshow', (['Im'], {}), '(Im)\n', (279, 283), False, 'from matplotlib import pylab\n'), ((286, 298), 'matplotlib.pylab.dra... |
#
# Collective Knowledge (caffe CK front-end)
#
# See CK LICENSE.txt for licensing details
# See CK COPYRIGHT.txt for copyright details
#
# Developer: cTuning foundation, <EMAIL>, http://cTuning.org
#
cfg={} # Will be updated by CK (meta description of this module)
work={} # Will be updated by CK (temporal data)
ck=N... | [
"cv2.VideoCapture",
"cv2.imwrite",
"os.path.join",
"time.sleep"
] | [((2291, 2318), 'os.path.join', 'os.path.join', (['p', 'image_name'], {}), '(p, image_name)\n', (2303, 2318), False, 'import os\n'), ((2419, 2439), 'cv2.VideoCapture', 'cv2.VideoCapture', (['ci'], {}), '(ci)\n', (2435, 2439), False, 'import cv2\n'), ((2768, 2782), 'time.sleep', 'time.sleep', (['dl'], {}), '(dl)\n', (27... |
import re
from node import Node
last_result = {'line':'','level':0}
def convertStringListToNode(str_list, rex_list, current_level=0, node=Node()):
while len(str_list) > 0:
line = str_list[0]
line_level = getLineLevel(line, rex_list)
if (line_level > current_level):
ch... | [
"node.Node"
] | [((145, 151), 'node.Node', 'Node', ([], {}), '()\n', (149, 151), False, 'from node import Node\n'), ((330, 336), 'node.Node', 'Node', ([], {}), '()\n', (334, 336), False, 'from node import Node\n'), ((939, 945), 'node.Node', 'Node', ([], {}), '()\n', (943, 945), False, 'from node import Node\n')] |
# -*- coding: utf-8 -*-
# Copyright 2015-2016 Telefónica Investigación y Desarrollo, S.A.U
#
# This file is part of FIWARE project.
#
# 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:
#
# htt... | [
"mock.patch.object",
"fiwareskuld.utils.rotated_files.rotate_files",
"mock.patch"
] | [((1128, 1173), 'mock.patch', 'patch', (['"""fiwareskuld.utils.rotated_files.glob"""'], {}), "('fiwareskuld.utils.rotated_files.glob')\n", (1133, 1173), False, 'from mock import patch\n'), ((2346, 2391), 'mock.patch', 'patch', (['"""fiwareskuld.utils.rotated_files.glob"""'], {}), "('fiwareskuld.utils.rotated_files.glob... |
from integration_test import __version__
import os
import subprocess
import urllib.request
import json
import time
from pathlib import Path
def test_basic():
tm = os.getenv('TENDERMINT')
tmhome = os.getenv('TMHOME')
tmkms = os.getenv('TMKMS')
kmsconfig = os.getenv('TMKMSCONFIG')
tmkms_proc = subpro... | [
"subprocess.Popen",
"json.loads",
"time.perf_counter",
"os.system",
"time.sleep",
"pathlib.Path",
"os.getenv"
] | [((168, 191), 'os.getenv', 'os.getenv', (['"""TENDERMINT"""'], {}), "('TENDERMINT')\n", (177, 191), False, 'import os\n'), ((205, 224), 'os.getenv', 'os.getenv', (['"""TMHOME"""'], {}), "('TMHOME')\n", (214, 224), False, 'import os\n'), ((237, 255), 'os.getenv', 'os.getenv', (['"""TMKMS"""'], {}), "('TMKMS')\n", (246, ... |
# pylint: disable=C0111
from setuptools import setup
with open("README.md", "r") as fh:
README = fh.read()
setup(
name='oneforge',
version='0.1.0',
description='1Forge REST API wrapper',
long_description=README,
long_description_content_type='text/markdown',
author='<NAME>',
author_ema... | [
"setuptools.setup"
] | [((113, 999), 'setuptools.setup', 'setup', ([], {'name': '"""oneforge"""', 'version': '"""0.1.0"""', 'description': '"""1Forge REST API wrapper"""', 'long_description': 'README', 'long_description_content_type': '"""text/markdown"""', 'author': '"""<NAME>"""', 'author_email': '"""<EMAIL>"""', 'maintainer': '"""<NAME>""... |
import math
from datetime import datetime
from fortnite_api.enums import BrCosmeticType, BrCosmeticRarity
class NewBrCosmetics:
def __init__(self, data):
self.build = data.get('build')
self.previous_build = data.get('previousBuild')
self.hash = data.get('hash')
try:
s... | [
"datetime.datetime.utcnow",
"datetime.datetime.strptime",
"math.sqrt"
] | [((7046, 7063), 'datetime.datetime.utcnow', 'datetime.utcnow', ([], {}), '()\n', (7061, 7063), False, 'from datetime import datetime\n'), ((7434, 7449), 'math.sqrt', 'math.sqrt', (['size'], {}), '(size)\n', (7443, 7449), False, 'import math\n'), ((6643, 6689), 'datetime.datetime.strptime', 'datetime.strptime', (['date'... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging
if __name__ == '__main__':
logging.basicConfig()
_log = logging.getLogger(__name__)
import sys
import pyxb
import unittest
class TestTrac0132 (unittest.TestCase):
message = 'bad character \u2620'
def testDecode (self):
... | [
"unittest.main",
"logging.basicConfig",
"pyxb.PyXBException",
"logging.getLogger"
] | [((139, 166), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (156, 166), False, 'import logging\n'), ((110, 131), 'logging.basicConfig', 'logging.basicConfig', ([], {}), '()\n', (129, 131), False, 'import logging\n'), ((485, 500), 'unittest.main', 'unittest.main', ([], {}), '()\n', (498, ... |
import copy
def merge(target, *args):
"""Merges arbitrary data - copied from http://blog.impressiver.com/post/31434674390/deep-merge-multiple-python-dicts
:param target: the data structure to fill
:param args: a list of data structures to merge into target
:return: target, with all data in args merg... | [
"copy.deepcopy"
] | [((779, 799), 'copy.deepcopy', 'copy.deepcopy', (['value'], {}), '(value)\n', (792, 799), False, 'import copy\n')] |
'''
Created on Jan 26, 2017
@author: tommi
'''
from enum import Enum
from handeval import pcg_brand
class Action(Enum):
CHECKFOLD = 1
CHECKCALL = 2
BETRAISE = 3
class Street(Enum):
PREFLOP = 0
FLOP = 3
TURN = 4
RIVER = 5
SHOWDOWN = 6
class PlayerState:
ST... | [
"handeval.pcg_brand"
] | [((1827, 1843), 'handeval.pcg_brand', 'pcg_brand', (['(10000)'], {}), '(10000)\n', (1836, 1843), False, 'from handeval import pcg_brand\n'), ((1808, 1820), 'handeval.pcg_brand', 'pcg_brand', (['(3)'], {}), '(3)\n', (1817, 1820), False, 'from handeval import pcg_brand\n')] |
from typing import Callable
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from src.domain_logic.engagement_domain import EngagementDomain
from src.model import get_database_session
from src.model.engagement import Engagement
async def update_engagement(engagement_domain: EngagementDo... | [
"sqlalchemy.select"
] | [((470, 488), 'sqlalchemy.select', 'select', (['Engagement'], {}), '(Engagement)\n', (476, 488), False, 'from sqlalchemy import select\n')] |
from unittest import TestCase
from unittest.mock import MagicMock
from unittest.mock import patch
from takeoff import *
import os
class WebProjectGeneratorTest(TestCase):
def setUp(self):
os.system('rm -rf test_dist/blog')
self.g = WebProjectGenerator('blog', [])
self.real_system_call = se... | [
"unittest.mock.MagicMock",
"os.system"
] | [((202, 236), 'os.system', 'os.system', (['"""rm -rf test_dist/blog"""'], {}), "('rm -rf test_dist/blog')\n", (211, 236), False, 'import os\n'), ((366, 377), 'unittest.mock.MagicMock', 'MagicMock', ([], {}), '()\n', (375, 377), False, 'from unittest.mock import MagicMock\n'), ((412, 447), 'unittest.mock.MagicMock', 'Ma... |
import time
from functools import wraps
from operators.operator import register_operators, delete_operators, operator_detail
from pipeline.pipeline import create_pipeline, delete_pipeline
from application.application import new_application, delete_application
def pre_operator(name="pytest_op_1", type="encoder",
... | [
"application.application.new_application",
"pipeline.pipeline.delete_pipeline",
"operators.operator.delete_operators",
"time.sleep",
"pipeline.pipeline.create_pipeline",
"functools.wraps",
"operators.operator.register_operators",
"operators.operator.operator_detail",
"application.application.delete_... | [((490, 501), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (495, 501), False, 'from functools import wraps\n'), ((908, 919), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (913, 919), False, 'from functools import wraps\n'), ((1382, 1393), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (138... |
#coding:utf-8
# return candidate position set of one pitch duration near center of the frame
# by differential change point and threshold from bottom line.
# return 0 if there is no.
#
# 中心付近の1ピッチ分の候補インデックス[sp,ep]を返す。
# 候補が無いときは零を返す。
#
# 微分の変化点と閾値により候補を選出する。
import numpy as np
import matplotlib.pyplot as ... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"numpy.amin",
"numpy.amax",
"matplotlib.pyplot.figure",
"numpy.where",
"numpy.array",
"numpy.sign",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"numpy.gradient"
] | [((477, 491), 'numpy.gradient', 'np.gradient', (['y'], {}), '(y)\n', (488, 491), True, 'import numpy as np\n'), ((1440, 1458), 'numpy.array', 'np.array', (['[sp, ep]'], {}), '([sp, ep])\n', (1448, 1458), True, 'import numpy as np\n'), ((679, 689), 'numpy.amin', 'np.amin', (['y'], {}), '(y)\n', (686, 689), True, 'import... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__project__ = 'leetcode'
__file__ = '__init__.py'
__author__ = 'king'
__time__ = '2019/11/18 16:54'
_ooOoo_
o8888888o
88" . "88
(| -_- |)
... | [
"leetcode.lessons.linked_list.ListNode.generate",
"leetcode.lessons.linked_list.ListNode"
] | [((3306, 3340), 'leetcode.lessons.linked_list.ListNode.generate', 'ListNode.generate', (['[1, 2, 3, 4, 5]'], {}), '([1, 2, 3, 4, 5])\n', (3323, 3340), False, 'from leetcode.lessons.linked_list import ListNode\n'), ((3390, 3424), 'leetcode.lessons.linked_list.ListNode.generate', 'ListNode.generate', (['[1, 2, 3, 4, 5]']... |
# coding: UTF-8
import unittest
from usig_normalizador_amba.Callejero import Callejero
from usig_normalizador_amba.Partido import Partido
from usig_normalizador_amba.Calle import Calle
from tests.test_commons import cargarCallejeroEstatico
class CallejeroTestCase(unittest.TestCase):
p = Partido('jose_c_paz', '... | [
"usig_normalizador_amba.Partido.Partido",
"usig_normalizador_amba.Callejero.Callejero",
"tests.test_commons.cargarCallejeroEstatico"
] | [((297, 358), 'usig_normalizador_amba.Partido.Partido', 'Partido', (['"""jose_c_paz"""', '"""<NAME>"""', '"""Partido de <NAME>"""', '(2430431)'], {}), "('jose_c_paz', '<NAME>', 'Partido de <NAME>', 2430431)\n", (304, 358), False, 'from usig_normalizador_amba.Partido import Partido\n'), ((367, 379), 'usig_normalizador_a... |
try:
import pygame
except ImportError:
raise ImportError("\n<pygame> library is missing on your system."
"\nTry: \n C:\\pip install pygame on a window command prompt.")
from SoundServer import *
if __name__ == "__main__":
pygame.mixer.init()
sound1 = pygame.mixer.Sound('Ala... | [
"pygame.display.set_mode",
"pygame.event.pump",
"pygame.Rect",
"pygame.mixer.init",
"pygame.display.flip",
"pygame.mixer.Sound"
] | [((263, 282), 'pygame.mixer.init', 'pygame.mixer.init', ([], {}), '()\n', (280, 282), False, 'import pygame\n'), ((297, 329), 'pygame.mixer.Sound', 'pygame.mixer.Sound', (['"""Alarm9.ogg"""'], {}), "('Alarm9.ogg')\n", (315, 329), False, 'import pygame\n'), ((348, 376), 'pygame.Rect', 'pygame.Rect', (['(0)', '(0)', '(80... |
import paho.mqtt.client as mqttw
class MqttClient :
def __init__( self , address = "localhost", port = 1883 , id_ = "" , subscribe = "" , message = None ) :
self.address = address
self.port = port
self.subscribe = subscribe
self.message = message
self.client = mqttw.Clie... | [
"paho.mqtt.client.Client"
] | [((310, 337), 'paho.mqtt.client.Client', 'mqttw.Client', ([], {'client_id': 'id_'}), '(client_id=id_)\n', (322, 337), True, 'import paho.mqtt.client as mqttw\n')] |
import airflow
from airflow import DAG
from airflow.operators.python_operator import PythonOperator
from airflow.contrib.hooks.aws_hook import AwsHook
from airflow.hooks.postgres_hook import PostgresHook
from airflow.operators.postgres_operator import PostgresOperator
from datetime import datetime, timedelta
import pan... | [
"airflow.operators.postgres_operator.PostgresOperator",
"airflow.DAG",
"airflow.contrib.hooks.aws_hook.AwsHook",
"airflow.operators.python_operator.PythonOperator",
"datetime.datetime",
"datetime.datetime.strptime",
"datetime.timedelta",
"airflow.hooks.postgres_hook.PostgresHook"
] | [((1998, 2166), 'airflow.DAG', 'DAG', (['"""log_reviews"""'], {'default_args': 'default_args', 'description': '"""Load and transform data in Redshift with Airflow"""', 'max_active_runs': '(1)', 'schedule_interval': '"""0 0 * * *"""'}), "('log_reviews', default_args=default_args, description=\n 'Load and transform da... |
#!/usr/bin/env python
import optparse, sys, os, logging
from collections import defaultdict
optparser = optparse.OptionParser()
optparser.add_option("-d", "--datadir", dest="datadir", default="data", help="data directory (default=data)")
optparser.add_option("-p", "--prefix", dest="fileprefix", default="hansards", he... | [
"sys.stdout.write",
"logging.basicConfig",
"optparse.OptionParser",
"collections.defaultdict",
"sys.stderr.write",
"os.path.join"
] | [((106, 129), 'optparse.OptionParser', 'optparse.OptionParser', ([], {}), '()\n', (127, 129), False, 'import optparse, sys, os, logging\n'), ((1333, 1383), 'sys.stderr.write', 'sys.stderr.write', (['"""Training using EM algorithm..."""'], {}), "('Training using EM algorithm...')\n", (1349, 1383), False, 'import optpars... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.utils.translation import ugettext_lazy as _
import re
__all__ = ['DriverFactory']
class DriverFactory(object):
@classmethod
def is_driver_available(cls, name):
try:
cls.get_driver_class(name)
... | [
"django.utils.translation.ugettext_lazy",
"re.match"
] | [((560, 593), 're.match', 're.match', (['"""^mongo.*"""', 'driver_name'], {}), "('^mongo.*', driver_name)\n", (568, 593), False, 'import re\n'), ((677, 710), 're.match', 're.match', (['"""^mysql.*"""', 'driver_name'], {}), "('^mysql.*', driver_name)\n", (685, 710), False, 'import re\n'), ((790, 823), 're.match', 're.ma... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import pdb
from config import cfg
from misc.utils import *
if cfg.DATASET == 'SHHB':
from datasets.SHHB.setting import cfg_data
elif cfg.DATASET == 'SHHA':
from datasets.SHHA.setting import cfg_data
elif cfg.DATASET == 'UCSD':
from datasets... | [
"torch.ones",
"torch.nn.L1Loss",
"torch.nn.functional.conv2d",
"torch.unsqueeze",
"torch.nn.DataParallel"
] | [((1303, 1329), 'torch.unsqueeze', 'torch.unsqueeze', (['gt_map', '(1)'], {}), '(gt_map, 1)\n', (1318, 1329), False, 'import torch\n'), ((2063, 2105), 'torch.nn.functional.conv2d', 'F.conv2d', (['gt_map_', 'filter5'], {'stride': 'kernel5'}), '(gt_map_, filter5, stride=kernel5)\n', (2071, 2105), True, 'import torch.nn.f... |
import numpy as np
from sklearn.ensemble import ExtraTreesRegressor, RandomForestRegressor
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn import preprocessing, svm
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn ... | [
"matplotlib.pyplot.title",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.xticks",
"sklearn.metrics.mean_squared_error",
"sklearn.linear_model.Lasso",
"sklearn.linear_model.Ridge",
"matplotlib.pyplot.show",
"pandas.get_dummies",
"matplo... | [((836, 876), 'pandas.read_csv', 'pd.read_csv', (['"""Original_with_dummies.csv"""'], {}), "('Original_with_dummies.csv')\n", (847, 876), True, 'import pandas as pd\n'), ((1157, 1197), 'pandas.read_csv', 'pd.read_csv', (['"""Original_with_dummies.csv"""'], {}), "('Original_with_dummies.csv')\n", (1168, 1197), True, 'im... |
# class for the truck object
# max of 16 packages
# travel at 18mph
# 3 trucks but only 2 drivers
# 8am earliest departure from hub
import Location
import Utility
import Package
# the truck object, initializes with parameters set in the assessment
# time_space complexity of O(1)
class Truck:
de... | [
"Utility.format_min_to_time",
"Location.get_distance",
"Location.get_location"
] | [((521, 545), 'Location.get_location', 'Location.get_location', (['(0)'], {}), '(0)\n', (542, 545), False, 'import Location\n'), ((2643, 2667), 'Location.get_location', 'Location.get_location', (['(0)'], {}), '(0)\n', (2664, 2667), False, 'import Location\n'), ((3028, 3065), 'Location.get_location', 'Location.get_locat... |
# -*- coding:utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the ... | [
"vega.core.common.class_factory.ClassFactory.register"
] | [((581, 622), 'vega.core.common.class_factory.ClassFactory.register', 'ClassFactory.register', (['ClassType.CALLBACK'], {}), '(ClassType.CALLBACK)\n', (602, 622), False, 'from vega.core.common.class_factory import ClassFactory, ClassType\n')] |
import pyftdc
import datetime
p = pyftdc.FTDCParser()
start = datetime.datetime.now()
p.parse_dir('/home/jorge/diagnostic.data', lazy=False)
end = datetime.datetime.now()
t = end - start
print(t)
| [
"pyftdc.FTDCParser",
"datetime.datetime.now"
] | [((35, 54), 'pyftdc.FTDCParser', 'pyftdc.FTDCParser', ([], {}), '()\n', (52, 54), False, 'import pyftdc\n'), ((64, 87), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (85, 87), False, 'import datetime\n'), ((149, 172), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (170, 172), ... |
from constructs import Construct
from aws_cdk import (
Duration,
aws_sqs as sqs,
aws_sns as sns,
aws_lambda as _lambda,
aws_lambda_event_sources as events,
)
lambda_timeout = Duration.seconds(15)
visibility_timeout = lambda_timeout.plus(Duration.seconds(5))
retention_period = Duration.minutes(60)
... | [
"aws_cdk.aws_lambda_event_sources.SqsEventSource",
"aws_cdk.Duration.seconds",
"aws_cdk.aws_lambda_event_sources.SnsEventSource",
"aws_cdk.Duration.minutes",
"aws_cdk.aws_lambda.Alias"
] | [((196, 216), 'aws_cdk.Duration.seconds', 'Duration.seconds', (['(15)'], {}), '(15)\n', (212, 216), False, 'from aws_cdk import Duration, aws_sqs as sqs, aws_sns as sns, aws_lambda as _lambda, aws_lambda_event_sources as events\n'), ((298, 318), 'aws_cdk.Duration.minutes', 'Duration.minutes', (['(60)'], {}), '(60)\n', ... |
from sentence_transformers import SentenceTransformer
from process import processing_combined
import pickle as pkl
# Corpus with example sentences
def model_transformer(query_data):
df_sentences_list, df = processing_combined(query_data)
embedder = SentenceTransformer('bert-base-nli-mean-tokens')
corpus =... | [
"sentence_transformers.SentenceTransformer",
"process.processing_combined"
] | [((212, 243), 'process.processing_combined', 'processing_combined', (['query_data'], {}), '(query_data)\n', (231, 243), False, 'from process import processing_combined\n'), ((259, 307), 'sentence_transformers.SentenceTransformer', 'SentenceTransformer', (['"""bert-base-nli-mean-tokens"""'], {}), "('bert-base-nli-mean-t... |
from django.http import HttpResponse
from django.shortcuts import render_to_response
import json
from . import feature_vector
from . import dist
from . import top_k
import re
import codecs
#import sys
#import imp
# imp.reload(sys)
# sys.setdefaultencoding('utf-8') #python3 don't has this method,the default on Pyth... | [
"django.shortcuts.render_to_response",
"django.http.HttpResponse",
"json.dumps",
"re.compile"
] | [((476, 510), 'django.shortcuts.render_to_response', 'render_to_response', (['"""faq.html"""', '{}'], {}), "('faq.html', {})\n", (494, 510), False, 'from django.shortcuts import render_to_response\n'), ((550, 589), 'django.shortcuts.render_to_response', 'render_to_response', (['"""liscense.html"""', '{}'], {}), "('lisc... |
import re
input = open("inputs/day4.txt", "r")
#credit to themanush on r/adventofcode I was very confused how to nicely read this in
lines = [line.replace("\n", " ") for line in input.read().split("\n\n")]
#part1
requiredItems = ["byr","iyr","eyr","hgt","hcl","ecl","pid"]
acceptedPP = 0
for line in lines:
if all(... | [
"re.search"
] | [((570, 599), 're.search', 're.search', (['"""byr:\\\\d{4}"""', 'line'], {}), "('byr:\\\\d{4}', line)\n", (579, 599), False, 'import re\n'), ((794, 823), 're.search', 're.search', (['"""iyr:\\\\d{4}"""', 'line'], {}), "('iyr:\\\\d{4}', line)\n", (803, 823), False, 'import re\n'), ((1016, 1045), 're.search', 're.search'... |
import random
import numpy as np
import matplotlib.pyplot as plt
from torch import tensor
from torch import cat
from torch import clamp
from torch.distributions import normal
from torch import nn
import torch.nn.functional as F
from torch import optim
from torch.utils.tensorboard import SummaryWriter
import torch
imp... | [
"matplotlib.pyplot.title",
"gym.make",
"matplotlib.pyplot.hist",
"numpy.asarray",
"random.choices",
"torch.cat",
"torch.distributions.normal.Normal",
"torch.nn.Linear",
"torch.exp",
"numpy.mean",
"torch.utils.tensorboard.SummaryWriter",
"torch.device",
"matplotlib.pyplot.ylabel",
"torch.te... | [((672, 751), 'torch.utils.tensorboard.SummaryWriter', 'SummaryWriter', ([], {'log_dir': '"""./runs/v0-1mil-iter-256-node-hidden-layers-buffer-1mil"""'}), "(log_dir='./runs/v0-1mil-iter-256-node-hidden-layers-buffer-1mil')\n", (685, 751), False, 'from torch.utils.tensorboard import SummaryWriter\n'), ((836, 855), 'torc... |
"""Embed a 3D scene
in a webpage with x3d"""
from vedo import dataurl, Plotter, Volume, Text3D
plt = Plotter(size=(800,600), bg='GhostWhite')
embryo = Volume(dataurl+'embryo.tif').isosurface().decimate(0.5)
coords = embryo.points()
embryo.cmap('PRGn', coords[:,1]) # add dummy colors along y
txt = Text3D(__doc__, fon... | [
"vedo.Plotter",
"vedo.Text3D",
"vedo.Volume"
] | [((102, 143), 'vedo.Plotter', 'Plotter', ([], {'size': '(800, 600)', 'bg': '"""GhostWhite"""'}), "(size=(800, 600), bg='GhostWhite')\n", (109, 143), False, 'from vedo import dataurl, Plotter, Volume, Text3D\n'), ((301, 360), 'vedo.Text3D', 'Text3D', (['__doc__'], {'font': '"""Bongas"""', 's': '(350)', 'c': '"""red2"""'... |
import h5py
import os
import argparse
import numpy as np
import pandas as pd
import scanpy as sc
def cluster(args):
"""
Clustering cells after computing pca and neiborhood distances.
"""
input = args.input
out = args.out
dpi = args.dpi
figsize = args.figsize
figure_type = args.figure_ty... | [
"scanpy.tl.umap",
"scanpy.logging.print_versions",
"argparse.ArgumentParser",
"scanpy.settings.set_figure_params",
"scanpy.pp.neighbors",
"scanpy.read_h5ad",
"scanpy.tl.leiden",
"scanpy.logging.print_version_and_date",
"scanpy.pl.umap"
] | [((823, 858), 'scanpy.logging.print_version_and_date', 'sc.logging.print_version_and_date', ([], {}), '()\n', (856, 858), True, 'import scanpy as sc\n'), ((863, 890), 'scanpy.logging.print_versions', 'sc.logging.print_versions', ([], {}), '()\n', (888, 890), True, 'import scanpy as sc\n'), ((986, 1060), 'scanpy.setting... |
import sys
from collections import OrderedDict
from makefun import wraps
try: # python 3+
from inspect import signature, Signature
except ImportError:
from funcsigs import signature, Signature
try: # python 3.5+
from typing import Tuple, Callable, Union, Iterable
except ImportError:
pass
from deco... | [
"collections.OrderedDict",
"autoclass.utils.read_fields_from_init",
"makefun.wraps"
] | [((2387, 2473), 'autoclass.utils.read_fields_from_init', 'read_fields_from_init', (['func'], {'include': 'include', 'exclude': 'exclude', 'caller': '"""@autoargs"""'}), "(func, include=include, exclude=exclude, caller=\n '@autoargs')\n", (2408, 2473), False, 'from autoclass.utils import read_fields_from_init\n'), ((... |
from operator import itemgetter
from shapefile import Reader
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import cartopy.io.img_tiles as cimgt
import matplotlib.pyplot as plt
from metpy.plots import USCOUNTIES
from statsmodels.nonparametric.smoothers_lowess import lowess
# Constants
EF_COLORS = {
... | [
"matplotlib.pyplot.show",
"cartopy.feature.OCEAN.with_scale",
"metpy.plots.USCOUNTIES.with_scale",
"statsmodels.nonparametric.smoothers_lowess.lowess",
"cartopy.feature.LAND.with_scale",
"matplotlib.pyplot.figure",
"cartopy.crs.PlateCarree",
"cartopy.io.img_tiles.Stamen",
"operator.itemgetter",
"s... | [((537, 570), 'shapefile.Reader', 'Reader', (['"""nws_dat_damage_pnts.shp"""'], {}), "('nws_dat_damage_pnts.shp')\n", (543, 570), False, 'from shapefile import Reader\n'), ((785, 819), 'cartopy.io.img_tiles.Stamen', 'cimgt.Stamen', (['"""terrain-background"""'], {}), "('terrain-background')\n", (797, 819), True, 'impor... |
# Databricks notebook source
# MAGIC %md
# MAGIC
# MAGIC # Spark integration with Azure Cognitive Services
# MAGIC
# MAGIC At Spark + AI Summit 2019, Microsoft announced a new set of models in the SparkML ecosystem that make it easy to leverage the Azure Cognitive Services at terabyte scales. With only a few lines of... | [
"mmlspark.cognitive.TextSentiment",
"pyspark.sql.functions.col",
"msrest.authentication.CognitiveServicesCredentials"
] | [((2663, 2710), 'msrest.authentication.CognitiveServicesCredentials', 'CognitiveServicesCredentials', (['textanalytics_key'], {}), '(textanalytics_key)\n', (2691, 2710), False, 'from msrest.authentication import CognitiveServicesCredentials\n'), ((5287, 5318), 'pyspark.sql.functions.col', 'col', (['"""StoreCommentSenti... |
import h5py
import os, sys, glob
import numpy as np
import plotly.offline as offline
from preprocessing import analysis_pp
from analysis.general_utils import aqua_utils, saving_utils, plotly_utils, general_utils, compare_astro_utils, correlation_utils, stat_utils
from scipy.stats.stats import power_divergence
from scip... | [
"matplotlib.rc",
"scipy.stats.skewnorm.pdf",
"numpy.sum",
"powerlaw.Fit",
"scipy.stats.skewnorm.fit",
"analysis.general_utils.plotly_utils.plot_scatter_mult_with_avg",
"numpy.histogram",
"os.path.isfile",
"scipy.stats.skewnorm.stats",
"analysis.general_utils.plotly_utils.apply_fun_axis_fig",
"an... | [((1460, 1527), 'os.path.join', 'os.path.join', (['output_experiment_path', '"""plots"""', '"""behaviour_heatmaps"""'], {}), "(output_experiment_path, 'plots', 'behaviour_heatmaps')\n", (1472, 1527), False, 'import os, sys, glob\n'), ((1988, 2066), 'os.path.join', 'os.path.join', (['output_experiment_path', '"""plots""... |
# -*- coding: utf-8 -*-
# @Time : 2020/12/24 3:48 PM
# @Author : Kevin
from src.chat import dataset
from src.chat.seq2seq import ChatSeq2Seq
from torch.optim import Adam
import torch.nn.functional as F
import torch
from src import config
from tqdm import tqdm
from src.lib import device,chat_answer_word_sequence_mod... | [
"src.chat.dataset.get_dataloader",
"torch.nn.functional.cross_entropy",
"src.chat.seq2seq.ChatSeq2Seq"
] | [((393, 417), 'src.chat.dataset.get_dataloader', 'dataset.get_dataloader', ([], {}), '()\n', (415, 417), False, 'from src.chat import dataset\n'), ((1300, 1404), 'torch.nn.functional.cross_entropy', 'F.cross_entropy', (['decoder_outputs_softmax', 'answers'], {'ignore_index': 'chat_answer_word_sequence_model.PAD'}), '(d... |
from flask_sqlalchemy import SQLAlchemy
from flask_admin import Admin
db = SQLAlchemy()
admin = Admin(template_mode='bootstrap3')
def register_extensions(app):
db.init_app(app)
admin.init_app(app)
from app.admin_ import register_modelviews
register_modelviews(admin, app)
| [
"flask_admin.Admin",
"app.admin_.register_modelviews",
"flask_sqlalchemy.SQLAlchemy"
] | [((77, 89), 'flask_sqlalchemy.SQLAlchemy', 'SQLAlchemy', ([], {}), '()\n', (87, 89), False, 'from flask_sqlalchemy import SQLAlchemy\n'), ((98, 131), 'flask_admin.Admin', 'Admin', ([], {'template_mode': '"""bootstrap3"""'}), "(template_mode='bootstrap3')\n", (103, 131), False, 'from flask_admin import Admin\n'), ((260,... |
# 2018/11/01~2018/07/12
# <NAME>, <EMAIL>.
"""
graphML.py Module for basic GSP and graph machine learning functions.
Functionals
LSIGF: Applies a linear shift-invariant graph filter
spectralGF: Applies a linear shift-invariant graph filter in spectral form
NVGF: Applies a node-variant graph filter
EVGF: Applies an ed... | [
"torch.eye",
"torch.empty",
"torch.cat",
"torch.arange",
"torch.nn.functional.leaky_relu",
"torch.ones",
"torch.median",
"torch.gather",
"numpy.linalg.eig",
"torch.Tensor",
"utils.graphUtils.graphTools.splineBasis",
"torch.zeros",
"torch.matmul",
"utils.graphUtils.graphTools.computeNeighbo... | [((10592, 10617), 'torch.matmul', 'torch.matmul', (['Vdiagh', 'VHx'], {}), '(Vdiagh, VHx)\n', (10604, 10617), False, 'import torch\n'), ((10781, 10800), 'torch.sum', 'torch.sum', (['y'], {'dim': '(3)'}), '(y, dim=3)\n', (10790, 10800), False, 'import torch\n'), ((10844, 10863), 'torch.sum', 'torch.sum', (['y'], {'dim':... |
import array
import math
import chuong_1
import chuong_2
def bien_ap_t1():
s_max=abs(chuong_2.s_a)
s_dm_B=s_max/1.4
d_p_n=260
d_p_0=100
u_n=14
i_0=0.045
r_b1=d_p_n*110**2/20000**2*10**3
z_b1=u_n*110**2/20000*10
x_b1=math.sqrt(z_b1**2-r_b1**2)
d_q_FE=i_0*20000/100
print('S_ptm... | [
"math.sqrt"
] | [((252, 284), 'math.sqrt', 'math.sqrt', (['(z_b1 ** 2 - r_b1 ** 2)'], {}), '(z_b1 ** 2 - r_b1 ** 2)\n', (261, 284), False, 'import math\n'), ((709, 741), 'math.sqrt', 'math.sqrt', (['(z_b1 ** 2 - r_b1 ** 2)'], {}), '(z_b1 ** 2 - r_b1 ** 2)\n', (718, 741), False, 'import math\n'), ((1164, 1196), 'math.sqrt', 'math.sqrt'... |
# Useful starting lines
# %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
# %load_ext autoreload
# %autoreload 2
from sklearn import linear_model
# from __future__ import absolute_import
from labs.ex03.template import helpers
from labs.ex04.template.costs import compute_rmse, compute_mse
from la... | [
"numpy.random.seed",
"numpy.logspace",
"labs.ex04.template.plots.cross_validation_visualization_for_degree",
"labs.ex04.template.costs.compute_mse_for_ridge",
"numpy.sin",
"labs.ex04.template.plots.bias_variance_decomposition_visualization",
"labs.ex04.template.ridge_regression.ridge_regression",
"lab... | [((904, 923), 'labs.ex03.template.helpers.load_data', 'helpers.load_data', ([], {}), '()\n', (921, 923), False, 'from labs.ex03.template import helpers\n'), ((1067, 1087), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (1081, 1087), True, 'import numpy as np\n'), ((1102, 1132), 'numpy.random.permuta... |
import time
from roslibpy import Topic
from compas_fab.backends import RosClient
def receive_message(message):
print("Received: " + message["data"])
with RosClient("localhost") as client:
print("Waiting for messages...")
listener = Topic(client, "/messages", "std_msgs/String")
listener.subscribe(r... | [
"roslibpy.Topic",
"compas_fab.backends.RosClient",
"time.sleep"
] | [((163, 185), 'compas_fab.backends.RosClient', 'RosClient', (['"""localhost"""'], {}), "('localhost')\n", (172, 185), False, 'from compas_fab.backends import RosClient\n'), ((250, 295), 'roslibpy.Topic', 'Topic', (['client', '"""/messages"""', '"""std_msgs/String"""'], {}), "(client, '/messages', 'std_msgs/String')\n",... |
import os
import sys
sys.path.insert(0, os.getcwd())
try:
from easygui_qt import easygui_qt
except ImportError:
print("problem with import")
name = easygui_qt.text_input(message="What is your name?",
title="Mine is Reeborg.")
print(name, end='')
| [
"os.getcwd",
"easygui_qt.easygui_qt.text_input"
] | [((158, 235), 'easygui_qt.easygui_qt.text_input', 'easygui_qt.text_input', ([], {'message': '"""What is your name?"""', 'title': '"""Mine is Reeborg."""'}), "(message='What is your name?', title='Mine is Reeborg.')\n", (179, 235), False, 'from easygui_qt import easygui_qt\n'), ((40, 51), 'os.getcwd', 'os.getcwd', ([], ... |
from django import forms
from imagr_users.models import ImagrUser
from registration.forms import RegistrationForm
class ImagrUserRegistrationForm(RegistrationForm):
def clean_username(self):
"""Validate that the username is alphanumeric and is not already in use.
"""
existing = ImagrUser.o... | [
"django.forms.ValidationError",
"imagr_users.models.ImagrUser.objects.filter"
] | [((309, 381), 'imagr_users.models.ImagrUser.objects.filter', 'ImagrUser.objects.filter', ([], {'username__iexact': "self.cleaned_data['username']"}), "(username__iexact=self.cleaned_data['username'])\n", (333, 381), False, 'from imagr_users.models import ImagrUser\n'), ((452, 518), 'django.forms.ValidationError', 'form... |
from typing import Optional
import pytest
import hopeit.app.api as api
from hopeit.app.config import EventType
from hopeit.server.api import APIError
from mock_app import mock_app_api_get, MockData, mock_app_api_post, mock_app_api_get_list
from mock_app import mock_api_app_config, mock_api_spec # noqa: F401
def te... | [
"hopeit.app.api.api_from_config",
"pytest.raises",
"hopeit.app.api.event_api",
"hopeit.app.api.app_base_route_name"
] | [((466, 583), 'hopeit.app.api.api_from_config', 'api.api_from_config', (['mock_app_api_get'], {'app_config': 'mock_api_app_config', 'event_name': '"""mock-app-api-get"""', 'plugin': 'None'}), "(mock_app_api_get, app_config=mock_api_app_config,\n event_name='mock-app-api-get', plugin=None)\n", (485, 583), True, 'impo... |
import asyncio
from urllib.parse import urlencode
import pytest
from phx_events.client import PHXChannelsClient
pytestmark = pytest.mark.asyncio
class TestPHXChannelsClientInit:
def setup(self):
self.socket_url = 'ws://test.socket/url/'
self.channel_auth_token = '<PASSWORD>'
self.phx_... | [
"phx_events.client.PHXChannelsClient",
"asyncio.get_event_loop",
"urllib.parse.urlencode"
] | [((338, 397), 'phx_events.client.PHXChannelsClient', 'PHXChannelsClient', (['self.socket_url', 'self.channel_auth_token'], {}), '(self.socket_url, self.channel_auth_token)\n', (355, 397), False, 'from phx_events.client import PHXChannelsClient\n'), ((679, 713), 'phx_events.client.PHXChannelsClient', 'PHXChannelsClient'... |
"""Vertical structure functions for ROMS
:func:`sdepth`
Depth of s-levels
:func:`zslice`
Slice a 3D field in s-coordinates to fixed depth
:func:`multi_zslice`
Slice a 3D field to several depth levels
:func:`z_average`
Vertical average of a 3D field
:func:`s_stretch`
Compute vertical stretching arrays Cs_r or... | [
"numpy.outer",
"numpy.sum",
"numpy.tanh",
"numpy.abs",
"numpy.asarray",
"numpy.arange",
"xarray.DataArray",
"numpy.linspace",
"numpy.array",
"numpy.cosh",
"numpy.exp",
"numpy.sinh"
] | [((1334, 1347), 'numpy.asarray', 'np.asarray', (['H'], {}), '(H)\n', (1344, 1347), True, 'import numpy as np\n'), ((1462, 1475), 'numpy.asarray', 'np.asarray', (['C'], {}), '(C)\n', (1472, 1475), True, 'import numpy as np\n'), ((3411, 3424), 'numpy.asarray', 'np.asarray', (['F'], {}), '(F)\n', (3421, 3424), True, 'impo... |
import sys
sys.path.insert(1, "lib/")
# This going against PEP-8 will refactor once we have a build pipeline
import os
import json
import logging
import requests
import cachetools.func
class MovieApis:
api_key = os.environ.get("API_KEY")
# instance method
@cachetools.func.ttl_cache(maxsize=20, ttl=300)
... | [
"logging.exception",
"json.loads",
"sys.path.insert",
"os.environ.get",
"requests.get"
] | [((11, 37), 'sys.path.insert', 'sys.path.insert', (['(1)', '"""lib/"""'], {}), "(1, 'lib/')\n", (26, 37), False, 'import sys\n'), ((218, 243), 'os.environ.get', 'os.environ.get', (['"""API_KEY"""'], {}), "('API_KEY')\n", (232, 243), False, 'import os\n'), ((746, 764), 'json.loads', 'json.loads', (['r.text'], {}), '(r.t... |
# Dependencies
# Python SQL toolkit and Object Relational Mapper
import sqlalchemy
# Go to existing database with automap_base
from sqlalchemy.ext.automap import automap_base
# Work through mapper to use python code
from sqlalchemy.orm import Session, relationship
# Inspect with python
from sqlalchemy import create_eng... | [
"pandas.DataFrame",
"sqlalchemy.String",
"sqlalchemy.orm.Session",
"sqlalchemy.ext.declarative.declarative_base",
"datetime.datetime.strptime",
"sqlalchemy.Column",
"sqlalchemy.desc",
"sqlalchemy.create_engine",
"sqlalchemy.ext.automap.automap_base"
] | [((709, 727), 'sqlalchemy.ext.declarative.declarative_base', 'declarative_base', ([], {}), '()\n', (725, 727), False, 'from sqlalchemy.ext.declarative import declarative_base\n'), ((1586, 1638), 'sqlalchemy.create_engine', 'create_engine', (['"""sqlite:///earthquake_weather.sqlite"""'], {}), "('sqlite:///earthquake_wea... |
import numpy as np
import sys
#for calculate the loss
from sklearn.metrics import log_loss
from sklearn.metrics import make_scorer
#import three machine learning models
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn.model_selection import StratifiedShuffleSplit
#for stan... | [
"numpy.load",
"numpy.random.seed",
"argparse.ArgumentParser",
"logging.StreamHandler",
"sklearn.preprocessing.MinMaxScaler",
"logging.Formatter",
"sklearn.metrics.make_scorer",
"random.seed",
"numpy.array",
"sklearn.svm.SVC",
"configparser.ConfigParser",
"logging.getLogger"
] | [((675, 701), 'logging.getLogger', 'logging.getLogger', (['"""cumul"""'], {}), "('cumul')\n", (692, 701), False, 'import logging\n'), ((702, 719), 'random.seed', 'random.seed', (['(1123)'], {}), '(1123)\n', (713, 719), False, 'import random\n'), ((720, 740), 'numpy.random.seed', 'np.random.seed', (['(1123)'], {}), '(11... |
# -*- coding: utf-8 -*-
import os
import json
import jieba.analyse
import jieba
CURRENT_PATH = os.path.dirname(os.path.abspath(__file__))
sentiment_path = os.path.join(CURRENT_PATH, 'data', 'sentimentDict.json')
stopwords_path = os.path.join(CURRENT_PATH, 'data', 'stopwords.txt.json')
degree_path = os.path.join(CUR... | [
"jieba.load_userdict",
"os.path.abspath",
"os.path.join",
"jieba.lcut"
] | [((159, 215), 'os.path.join', 'os.path.join', (['CURRENT_PATH', '"""data"""', '"""sentimentDict.json"""'], {}), "(CURRENT_PATH, 'data', 'sentimentDict.json')\n", (171, 215), False, 'import os\n'), ((233, 289), 'os.path.join', 'os.path.join', (['CURRENT_PATH', '"""data"""', '"""stopwords.txt.json"""'], {}), "(CURRENT_PA... |
#!/usr/bin/env python2
# Copyright 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
"""... | [
"collections.OrderedDict",
"os.environ.get",
"json.dumps"
] | [((10517, 10542), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (10540, 10542), False, 'import collections\n'), ((9585, 9617), 'os.environ.get', 'os.environ.get', (['"""BUCK_NONCE"""', '""""""'], {}), "('BUCK_NONCE', '')\n", (9599, 9617), False, 'import os\n'), ((9840, 9864), 'json.dumps', 'js... |
import requests
import json
print("register node 5000, 5001, 5002, 5003, 5004, 5005")
m_node = {
"nodes" : ["http://127.0.0.1:5000","http://127.0.0.1:5001",
"http://127.0.0.1:5002","http://127.0.0.1:5003","http://127.0.0.1:5004","http://127.0.0.1:5005"]
}
r = requests.post('http://127.0.0.1:5000/nodes/regis... | [
"requests.post",
"requests.get"
] | [((272, 338), 'requests.post', 'requests.post', (['"""http://127.0.0.1:5000/nodes/register"""'], {'json': 'm_node'}), "('http://127.0.0.1:5000/nodes/register', json=m_node)\n", (285, 338), False, 'import requests\n'), ((465, 508), 'requests.get', 'requests.get', (['"""http://127.0.0.1:5000/chain"""'], {}), "('http://12... |
# Taken from: https://github.com/jhollowayj/tensorflow_slurm_manager
# ref:
# https://github.com/jhollowayj/tensorflow_slurm_manager/blob/master/slurm_manager.py
# @IgnorePep8
'''
'''
from __future__ import print_function
import os
import re
# import socket
# depends on hostlist: pip install python-hostlist
import ho... | [
"re.findall",
"hostlist.expand_hostlist"
] | [((1964, 2022), 'hostlist.expand_hostlist', 'hostlist.expand_hostlist', (["os.environ['SLURM_JOB_NODELIST']"], {}), "(os.environ['SLURM_JOB_NODELIST'])\n", (1988, 2022), False, 'import hostlist\n'), ((4421, 4445), 're.findall', 're.findall', (['"""\\\\d+"""', 'node'], {}), "('\\\\d+', node)\n", (4431, 4445), False, 'im... |
from flask import Flask, render_template, request, jsonify
import conversation
# import traceback
app = Flask(__name__)
app.config["DEBUG"] = True
conversation.initBrain()
@app.route('/')
def index():
return render_template('main_page.html')
@app.route('/api/', methods=["GET","POST"])
def api():
try:
... | [
"apis.quotes.getQuote",
"conversation.botAnswer",
"conversation.initBrain",
"flask.Flask",
"flask.jsonify",
"flask.render_template",
"flask.request.get_json"
] | [((106, 121), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (111, 121), False, 'from flask import Flask, render_template, request, jsonify\n'), ((149, 173), 'conversation.initBrain', 'conversation.initBrain', ([], {}), '()\n', (171, 173), False, 'import conversation\n'), ((216, 249), 'flask.render_templat... |
import sys
import csv
import json
icsv = csv.DictReader(sys.stdin)
ojson = { "departments": [] }
dept_data = ojson["departments"]
dept_name_idx = {}
for line in icsv:
dept_name = line["dept_name"]
dept = dept_name_idx.get(dept_name)
if dept is None:
dept = dept_name_idx[dept_name] = { "name": dep... | [
"json.dump",
"csv.DictReader"
] | [((43, 68), 'csv.DictReader', 'csv.DictReader', (['sys.stdin'], {}), '(sys.stdin)\n', (57, 68), False, 'import csv\n'), ((590, 668), 'json.dump', 'json.dump', (['ojson', 'sys.stdout'], {'indent': '(2)', 'sort_keys': '(True)', 'separators': "(',', ': ')"}), "(ojson, sys.stdout, indent=2, sort_keys=True, separators=(',',... |
import logging
import threading
from typing import Any
from cobald.daemon.debug import NameRepr
class BaseRunner(object):
flavour = None # type: Any
def __init__(self):
self._logger = logging.getLogger(
"cobald.runtime.runner.%s" % NameRepr(self.flavour)
)
self._payloads... | [
"threading.Lock",
"threading.Event",
"cobald.daemon.debug.NameRepr"
] | [((347, 363), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (361, 363), False, 'import threading\n'), ((440, 457), 'threading.Event', 'threading.Event', ([], {}), '()\n', (455, 457), False, 'import threading\n'), ((524, 541), 'threading.Event', 'threading.Event', ([], {}), '()\n', (539, 541), False, 'import thr... |
import argparse
import subprocess
from pathlib import Path
from multiprocessing import Pool
picard_jar = None
def normalized_unique_reads(number_of_reads, bam):
try:
downsampled_library = downsample(number_of_reads, bam)
unique_bam = remove_duplicates(downsampled_library)
unique_reads = count_bam_reads(unique_... | [
"subprocess.run",
"pathlib.Path",
"argparse.ArgumentParser",
"multiprocessing.Pool"
] | [((458, 551), 'subprocess.run', 'subprocess.run', (["['samtools', 'view', '-c', filename]"], {'check': '(True)', 'stdout': 'subprocess.PIPE'}), "(['samtools', 'view', '-c', filename], check=True, stdout=\n subprocess.PIPE)\n", (472, 551), False, 'import subprocess\n'), ((903, 912), 'pathlib.Path', 'Path', (['bam'], ... |
#!/usr/bin/python
import logging
import logging.handlers
import configparser
from time import sleep
from SolarManager import SolarManager
def log_setup():
formatter = logging.Formatter("%(asctime)s :: %(name)s :: %(levelname)s :: %(message)s")
logLevel = logging.INFO
log_handler = logging.handlers.... | [
"time.sleep",
"logging.Formatter",
"logging.handlers.TimedRotatingFileHandler",
"configparser.ConfigParser",
"logging.getLogger"
] | [((608, 649), 'logging.getLogger', 'logging.getLogger', (['"""SolarManager.Service"""'], {}), "('SolarManager.Service')\n", (625, 649), False, 'import logging\n'), ((179, 255), 'logging.Formatter', 'logging.Formatter', (['"""%(asctime)s :: %(name)s :: %(levelname)s :: %(message)s"""'], {}), "('%(asctime)s :: %(name)s :... |
from django.core.management.base import BaseCommand
from observations.models import Datasourcetype
class Command(BaseCommand):
def handle(self, *args, **options):
Datasourcetype.objects.get_or_create(
name="Digital Matter Sensornode LoRaWAN",
defaults={
"descriptio... | [
"observations.models.Datasourcetype.objects.get_or_create"
] | [((178, 352), 'observations.models.Datasourcetype.objects.get_or_create', 'Datasourcetype.objects.get_or_create', ([], {'name': '"""Digital Matter Sensornode LoRaWAN"""', 'defaults': "{'description': 'Digital Matter Sensornode LoRaWAN', 'parser': 'sensornode'}"}), "(name=\n 'Digital Matter Sensornode LoRaWAN', defau... |
from django.urls import path
from rest_framework.routers import SimpleRouter
from apps.userAuth.views.v1.views import SendCodeView, UserViewSet
router = SimpleRouter(trailing_slash=False)
router.register('user', UserViewSet, base_name='user')
urlpatterns = [
path('sendcode', SendCodeView.as_view(), name='sendco... | [
"apps.userAuth.views.v1.views.SendCodeView.as_view",
"rest_framework.routers.SimpleRouter"
] | [((156, 190), 'rest_framework.routers.SimpleRouter', 'SimpleRouter', ([], {'trailing_slash': '(False)'}), '(trailing_slash=False)\n', (168, 190), False, 'from rest_framework.routers import SimpleRouter\n'), ((284, 306), 'apps.userAuth.views.v1.views.SendCodeView.as_view', 'SendCodeView.as_view', ([], {}), '()\n', (304,... |