code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import gzip
import pickle
import validators
def gzip_to_plaintext(path, destination):
"""
Saves a file unzipped and unpickled, for manual inspection
:param path: input file path
:param destination: where the plain text file will be saved
:return: None
"""
with gzip.open(path, "rb") as infi... | [
"validators.url",
"pickle.dump",
"pickle.load",
"gzip.open"
] | [((1271, 1293), 'validators.url', 'validators.url', (['string'], {}), '(string)\n', (1285, 1293), False, 'import validators\n'), ((291, 312), 'gzip.open', 'gzip.open', (['path', '"""rb"""'], {}), "(path, 'rb')\n", (300, 312), False, 'import gzip\n'), ((338, 357), 'pickle.load', 'pickle.load', (['infile'], {}), '(infile... |
# coding: utf-8
from collections import Counter
n, k = [int(i) for i in input().split()]
card = input()
c = Counter(card)
ans = 0
while k > 0:
tmp = c.pop(c.most_common(1)[0][0])
if k > tmp:
ans += tmp*tmp
k -= tmp
else:
ans += k*k
k = 0
print(ans)
| [
"collections.Counter"
] | [((108, 121), 'collections.Counter', 'Counter', (['card'], {}), '(card)\n', (115, 121), False, 'from collections import Counter\n')] |
import os
import warnings
import itertools
import pandas
import time
class SlurmJobArray():
""" Selects a single condition from an array of parameters using the SLURM_ARRAY_TASK_ID environment variable.
The parameters need to be supplied as a dictionary. if the task is not in a slurm environment,
... | [
"warnings.warn",
"itertools.product",
"time.strftime",
"pandas.Series"
] | [((3691, 3716), 'time.strftime', 'time.strftime', (['"""%Y_%m_%d"""'], {}), "('%Y_%m_%d')\n", (3704, 3716), False, 'import time\n'), ((1997, 2046), 'itertools.product', 'itertools.product', (['*[parameters[k] for k in keys]'], {}), '(*[parameters[k] for k in keys])\n', (2014, 2046), False, 'import itertools\n'), ((1818... |
# Tout ce code est un snippet volé sur plusieurs threads Stackoverflow
# Il permet de créer un décorateur qui vérifie si un utilisateur est bien identifié,
# et le redirige vers la page de login sinon. Django ne fait pas cette dernière partie seul...
try:
from functools import wraps
except ImportError:
from django... | [
"django.contrib.messages.error",
"steam.steamid.SteamID",
"sourcebans.models.SbAdmins.objects.get",
"django.contrib.auth.decorators.login_required"
] | [((1733, 1789), 'django.contrib.auth.decorators.login_required', 'login_required', (['function', 'redirect_field_name', 'login_url'], {}), '(function, redirect_field_name, login_url)\n', (1747, 1789), False, 'from django.contrib.auth.decorators import login_required\n'), ((2266, 2302), 'sourcebans.models.SbAdmins.objec... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
from collections import OrderedDict
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy.dialects import postgresql
from sqlalchemy.types import TypeDecorator
db = SQLAlchemy()
cla... | [
"collections.OrderedDict",
"flask.ext.sqlalchemy.SQLAlchemy",
"sqlalchemy.dialects.postgresql.ARRAY"
] | [((303, 315), 'flask.ext.sqlalchemy.SQLAlchemy', 'SQLAlchemy', ([], {}), '()\n', (313, 315), False, 'from flask.ext.sqlalchemy import SQLAlchemy\n'), ((1847, 1872), 'sqlalchemy.dialects.postgresql.ARRAY', 'postgresql.ARRAY', (['db.REAL'], {}), '(db.REAL)\n', (1863, 1872), False, 'from sqlalchemy.dialects import postgre... |
import pltk as pl
from pltk import load_data
from pltk import get_file_contents # Load single file
from pltk import get_folder_contents # Load all files in folder
from pltk import tokenize # create desired tokens
from pltk import vectorize # convert list of string to list of vectors
from pltk import unvectorize #... | [
"pltk.tokenize",
"pltk.vectorize",
"pltk.split_lists",
"pltk.unvectorize",
"sklearn.feature_extraction.text.CountVectorizer",
"pltk.change_list_dimensions",
"pltk.join_lists",
"pltk.load_data",
"pltk.vectorize_file",
"pltk.vectorize_folder"
] | [((1067, 1093), 'pltk.load_data', 'load_data', (['"""good_strcpy.c"""'], {}), "('good_strcpy.c')\n", (1076, 1093), False, 'from pltk import load_data\n'), ((1126, 1216), 'pltk.load_data', 'load_data', (['"""/home/rod/PycharmProjects/ProgrammingLanguageToolkit/input/good_strcpy.c"""'], {}), "(\n '/home/rod/PycharmPro... |
from django.contrib import admin
from fridge.models import (FridgeEnvirontment, MeasureUnit, Stock,
StockCategory, Supplier)
# Register your models here.
@admin.register(Stock)
class StockAdmin(admin.ModelAdmin):
list_display = ('name','category','quantity','measure_unit','supplier')
... | [
"django.contrib.admin.register",
"django.contrib.admin.site.register"
] | [((185, 206), 'django.contrib.admin.register', 'admin.register', (['Stock'], {}), '(Stock)\n', (199, 206), False, 'from django.contrib import admin\n'), ((375, 399), 'django.contrib.admin.register', 'admin.register', (['Supplier'], {}), '(Supplier)\n', (389, 399), False, 'from django.contrib import admin\n'), ((511, 54... |
import pickle
import pytest
import numpy as np
from astropy import units as u
from astropy import modeling
from specutils.utils import QuantityModel
from ..utils.wcs_utils import refraction_index, vac_to_air, air_to_vac
wavelengths = [300, 500, 1000] * u.nm
data_index_refraction = {
'Griesen2006': np.array([3.073... | [
"astropy.modeling.models.Chebyshev1D",
"pickle.dump",
"specutils.utils.QuantityModel",
"numpy.isclose",
"pickle.load",
"numpy.array",
"numpy.all"
] | [((305, 349), 'numpy.array', 'np.array', (['[3.07393068, 2.9434858, 2.8925797]'], {}), '([3.07393068, 2.9434858, 2.8925797])\n', (313, 349), True, 'import numpy as np\n'), ((369, 415), 'numpy.array', 'np.array', (['[2.91557413, 2.78963801, 2.74148172]'], {}), '([2.91557413, 2.78963801, 2.74148172])\n', (377, 415), True... |
import logging
import os
from datetime import timedelta
# layers
import sys
sys.path.append('/opt')
import cv2
from common.config import LOG_LEVEL, FRAME_RESIZE_WIDTH, FRAME_RESIZE_HEIGHT, STORE_FRAMES, \
DDB_FRAME_TABLE, UTC_TIME_FMT
from common.utils import upload_to_s3, put_item_ddb
logger = logging.getLogger... | [
"logging.getLogger",
"cv2.resize",
"cv2.imencode",
"cv2.destroyAllWindows",
"cv2.VideoCapture",
"datetime.timedelta",
"common.utils.put_item_ddb",
"sys.path.append"
] | [((77, 100), 'sys.path.append', 'sys.path.append', (['"""/opt"""'], {}), "('/opt')\n", (92, 100), False, 'import sys\n'), ((303, 338), 'logging.getLogger', 'logging.getLogger', (['"""FrameExtractor"""'], {}), "('FrameExtractor')\n", (320, 338), False, 'import logging\n'), ((973, 1002), 'cv2.VideoCapture', 'cv2.VideoCap... |
"""Collection of mixins."""
import json
from typing import Any, Dict, List, Union, Generator, Optional, Callable
import asyncpraw
import asyncprawcore
from asyncpraw.models import ListingGenerator
from client.models import RedditHelper
class Storage:
"""Mixin for storing data."""
def __init__(self, filenam... | [
"json.load",
"client.models.RedditHelper",
"json.dump",
"asyncpraw.Reddit"
] | [((1768, 1881), 'asyncpraw.Reddit', 'asyncpraw.Reddit', ([], {'client_id': 'client_id', 'client_secret': 'client_secret', 'user_agent': 'f"""DISCORD_BOT:{client_id}:1.0"""'}), "(client_id=client_id, client_secret=client_secret,\n user_agent=f'DISCORD_BOT:{client_id}:1.0')\n", (1784, 1881), False, 'import asyncpraw\n... |
from __future__ import absolute_import
import re
import os
import json
import xml.etree.ElementTree as ET
from svtplay_dl.service import Service, OpenGraphThumbMixin
from svtplay_dl.utils import is_py2_old
from svtplay_dl.error import ServiceError
from svtplay_dl.log import log
from svtplay_dl.fetcher.rtmp import RTMP... | [
"json.loads",
"xml.etree.ElementTree.XML",
"svtplay_dl.log.log.error",
"svtplay_dl.error.ServiceError",
"os.path.join",
"os.path.dirname",
"os.path.basename",
"re.search"
] | [((643, 751), 're.search', 're.search', (['"""data-mrss=[\\\\\'"](http://gakusei-cluster.mtvnn.com/v2/mrss.xml[^\\\\\'"]+)[\\\\\'"]"""', 'data'], {}), '(\n \'data-mrss=[\\\\\\\'"](http://gakusei-cluster.mtvnn.com/v2/mrss.xml[^\\\\\\\'"]+)[\\\\\\\'"]\'\n , data)\n', (652, 751), False, 'import re\n'), ((919, 931), ... |
##############################################################################
# Copyright 2019 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LI... | [
"pyds8k.resources.ds8k.v1.pprc.PPRC"
] | [((1433, 1466), 'pyds8k.resources.ds8k.v1.pprc.PPRC', 'PPRC', (['self.client'], {'info': 'pprc_info'}), '(self.client, info=pprc_info)\n', (1437, 1466), False, 'from pyds8k.resources.ds8k.v1.pprc import PPRC\n')] |
import os
os.environ['QT_MAC_WANTS_LAYER'] = '1'
import sys
import random
from PySide2.QtCore import Qt
from PySide2.QtWidgets import (QApplication, QWidget,
QPushButton, QLabel, QGridLayout)
import chess
import aiagents
class Board(QWidget):
def __init__(self, player1=None, player2=None, board=chess.Board()):... | [
"PySide2.QtWidgets.QGridLayout",
"PySide2.QtWidgets.QPushButton",
"chess.Board",
"PySide2.QtWidgets.QApplication",
"aiagents.createPVS",
"PySide2.QtWidgets.QWidget.__init__",
"chess.Move"
] | [((4204, 4226), 'PySide2.QtWidgets.QApplication', 'QApplication', (['sys.argv'], {}), '(sys.argv)\n', (4216, 4226), False, 'from PySide2.QtWidgets import QApplication, QWidget, QPushButton, QLabel, QGridLayout\n'), ((305, 318), 'chess.Board', 'chess.Board', ([], {}), '()\n', (316, 318), False, 'import chess\n'), ((329,... |
#!/usr/bin/env python
import ncs as ncs
import _ncs
from ncs.dp import Action, Daemon
from ncs.maapi import Maapi
from ncs.log import Log
import socket
import sys
import signal
from lxml import etree
import time
class MyLog(object):
def info(self, arg):
print("info: %s" % arg)
def error(self, arg):
... | [
"socket.socket",
"ncs.dp.Daemon",
"signal.pause",
"ncs.maapi.Maapi",
"time.sleep",
"ncs.maapi.single_read_trans",
"_ncs.stream_connect"
] | [((1676, 1712), 'ncs.dp.Daemon', 'Daemon', ([], {'name': '"""myactiond"""', 'log': 'logger'}), "(name='myactiond', log=logger)\n", (1682, 1712), False, 'from ncs.dp import Action, Daemon\n'), ((1876, 1890), 'signal.pause', 'signal.pause', ([], {}), '()\n', (1888, 1890), False, 'import signal\n'), ((904, 919), 'socket.s... |
import kivy
kivy.require('1.7.2')
from kivy.app import App
from kivy.clock import Clock
from kivy.metrics import Metrics
from kivy.properties import NumericProperty
from kivy.properties import ObjectProperty
from kivy.properties import StringProperty
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.boxlay... | [
"kivy.require",
"kivy.config.Config.set",
"kivy.properties.NumericProperty"
] | [((13, 34), 'kivy.require', 'kivy.require', (['"""1.7.2"""'], {}), "('1.7.2')\n", (25, 34), False, 'import kivy\n'), ((726, 764), 'kivy.config.Config.set', 'Config.set', (['"""graphics"""', '"""width"""', '"""600"""'], {}), "('graphics', 'width', '600')\n", (736, 764), False, 'from kivy.config import Config\n'), ((765,... |
import pytest
from pymlconf import Root
def test_delattribute():
root = Root('''
app:
name: MyApp
''')
assert hasattr(root.app, 'name')
del root.app.name
assert not hasattr(root.app, 'name')
with pytest.raises(AttributeError):
del root.app.invalidattribute
| [
"pymlconf.Root",
"pytest.raises"
] | [((79, 131), 'pymlconf.Root', 'Root', (['"""\n app:\n name: MyApp\n """'], {}), '("""\n app:\n name: MyApp\n """)\n', (83, 131), False, 'from pymlconf import Root\n'), ((243, 272), 'pytest.raises', 'pytest.raises', (['AttributeError'], {}), '(AttributeError)\n', (256, 272), False, ... |
# Generated by Django 2.1.4 on 2019-03-03 19:33
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
("filamentcolors", "0004_filamenttype_manufacturer"),
]
operations = [
migrations.AddField(
model... | [
"django.db.models.ForeignKey"
] | [((388, 512), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'blank': '(True)', 'null': '(True)', 'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""filamentcolors.FilamentType"""'}), "(blank=True, null=True, on_delete=django.db.models.\n deletion.CASCADE, to='filamentcolors.FilamentType')\n", (4... |
"""Test the Poem model."""
import pytest
from run.models import Meter, Poet, Poem
def test_Poem_repr():
"""Test the __repr__ method."""
assert repr(
Poem(
title='title',
keyword='keyword',
raw_text='raw text',
poet_id=1,
meter_id=1,
... | [
"run.models.Poem.query.first",
"run.models.Poem",
"run.models.Poem.query.all",
"run.models.Poet.insert_samples",
"pytest.raises",
"run.models.Poem.insert_samples",
"run.models.Meter.insert_samples"
] | [((601, 622), 'run.models.Poet.insert_samples', 'Poet.insert_samples', ([], {}), '()\n', (620, 622), False, 'from run.models import Meter, Poet, Poem\n'), ((907, 929), 'run.models.Meter.insert_samples', 'Meter.insert_samples', ([], {}), '()\n', (927, 929), False, 'from run.models import Meter, Poet, Poem\n'), ((934, 95... |
import logging
from datetime import datetime
from django.contrib.staticfiles.templatetags.staticfiles import static
from django.core import cache, exceptions
from django.core.urlresolvers import reverse
from geo.models import Country, Currency
from pytz import timezone
from rest_framework import serializers, paginatio... | [
"geo.models.Country.objects.all"
] | [((1580, 1601), 'geo.models.Country.objects.all', 'Country.objects.all', ([], {}), '()\n', (1599, 1601), False, 'from geo.models import Country, Currency\n')] |
#数値微分の例
import numpy as np
from common_function import function_1, numerical_diff
import matplotlib.pylab as plt
def tangent_line(f, x):
d = numerical_diff(f, x)
print(d)
y = f(x) - d*x
return lambda t: d*t + y
x = np.arange(0.0, 20.0, 0.1) #0から20まで0.1刻みのx配列
y = function_1(x)
plt.xlabel("x")
plt.yla... | [
"matplotlib.pylab.xlabel",
"common_function.function_1",
"matplotlib.pylab.show",
"common_function.numerical_diff",
"matplotlib.pylab.plot",
"numpy.arange",
"matplotlib.pylab.ylabel"
] | [((234, 259), 'numpy.arange', 'np.arange', (['(0.0)', '(20.0)', '(0.1)'], {}), '(0.0, 20.0, 0.1)\n', (243, 259), True, 'import numpy as np\n'), ((282, 295), 'common_function.function_1', 'function_1', (['x'], {}), '(x)\n', (292, 295), False, 'from common_function import function_1, numerical_diff\n'), ((297, 312), 'mat... |
import platform
import sys
from datetime import datetime, timedelta
from functools import partial
from types import ModuleType
import pytest
import pytz
from apscheduler.util import (
datetime_ceil, get_callable_name, obj_to_ref, ref_to_obj, maybe_ref, check_callable_args)
class DummyClass(object):
def meth... | [
"apscheduler.util.maybe_ref",
"datetime.datetime",
"platform.python_implementation",
"apscheduler.util.get_callable_name",
"apscheduler.util.datetime_ceil",
"types.ModuleType",
"apscheduler.util.ref_to_obj",
"apscheduler.util.obj_to_ref",
"pytest.mark.parametrize",
"pytest.raises",
"functools.pa... | [((3911, 4045), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""input,expected"""', "[('datetime:timedelta', timedelta), (timedelta, timedelta)]"], {'ids': "['textref', 'direct']"}), "('input,expected', [('datetime:timedelta', timedelta\n ), (timedelta, timedelta)], ids=['textref', 'direct'])\n", (3934, ... |
import re
import os
class Twitter():
def __init__(self):
pass
def removeHastag(self, tweet):
"""
Remove hastag in a tweet. (Tweet içerisindeki hastag'i kaldırır.)
Example:
Input:
\ttext [string] => "Merhaba #Hello"
Ou... | [
"re.sub",
"os.system"
] | [((399, 425), 're.sub', 're.sub', (['"""#\\\\S+"""', '""""""', 'tweet'], {}), "('#\\\\S+', '', tweet)\n", (405, 425), False, 'import re\n'), ((1131, 1160), 're.sub', 're.sub', (['"""\\\\brt\\\\b"""', '""""""', 'tweet'], {}), "('\\\\brt\\\\b', '', tweet)\n", (1137, 1160), False, 'import re\n'), ((2459, 2593), 'os.system... |
from telethon import events
import asyncio
from userbot.utils import admin_cmd
@borg.on(admin_cmd("mc"))
async def _(event):
if event.fwd_from:
return
animation_interval = 0.3
animation_ttl = range(0, 5)
await event.edit("mein")
animation_chars = [
"madarchod",
"Hu... | [
"userbot.utils.admin_cmd",
"asyncio.sleep"
] | [((91, 106), 'userbot.utils.admin_cmd', 'admin_cmd', (['"""mc"""'], {}), "('mc')\n", (100, 106), False, 'from userbot.utils import admin_cmd\n'), ((477, 510), 'asyncio.sleep', 'asyncio.sleep', (['animation_interval'], {}), '(animation_interval)\n', (490, 510), False, 'import asyncio\n')] |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# *****************************************************************************/
# * Authors: <NAME>, <NAME>
# *****************************************************************************/
"""
Brief:
telemetry_util.py - Utility routines for Telemetry data processin... | [
"os.path.exists",
"os.listdir",
"array.array",
"os.path.join",
"os.getcwd",
"os.path.isfile",
"os.mkdir",
"os.remove"
] | [((1970, 1992), 'os.path.exists', 'os.path.exists', (['folder'], {}), '(folder)\n', (1984, 1992), False, 'import os\n'), ((1836, 1859), 'os.path.exists', 'os.path.exists', (['dirName'], {}), '(dirName)\n', (1850, 1859), False, 'import os\n'), ((2020, 2038), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (2... |
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from backend.views import app_urls
from server import settings
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'server.views.home', name='home'),
# url(... | [
"django.conf.urls.include",
"django.conf.urls.static.static",
"django.contrib.admin.autodiscover"
] | [((193, 213), 'django.contrib.admin.autodiscover', 'admin.autodiscover', ([], {}), '()\n', (211, 213), False, 'from django.contrib import admin\n'), ((524, 585), 'django.conf.urls.static.static', 'static', (['settings.MEDIA_URL'], {'document_root': 'settings.MEDIA_ROOT'}), '(settings.MEDIA_URL, document_root=settings.M... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from perlin import generate_perlin
def gaussian_2d_fast(size, amp, mu_x, mu_y, sigma):
x = np.arange(0, 1, 1/size[0])
y = np.arange(0, 1, 1/size[1])
xs, ys = np.meshgrid(x,y)
dxs = np.minimum(np.abs(xs-mu_x), 1-np.abs(xs-mu_x)... | [
"numpy.sin",
"numpy.arange",
"matplotlib.pyplot.imshow",
"numpy.mean",
"numpy.multiply",
"numpy.reshape",
"numpy.random.random",
"numpy.where",
"numpy.exp",
"matplotlib.cm.ScalarMappable",
"perlin.generate_perlin",
"numpy.meshgrid",
"numpy.abs",
"matplotlib.pyplot.quiver",
"numpy.amin",
... | [((172, 200), 'numpy.arange', 'np.arange', (['(0)', '(1)', '(1 / size[0])'], {}), '(0, 1, 1 / size[0])\n', (181, 200), True, 'import numpy as np\n'), ((207, 235), 'numpy.arange', 'np.arange', (['(0)', '(1)', '(1 / size[1])'], {}), '(0, 1, 1 / size[1])\n', (216, 235), True, 'import numpy as np\n'), ((247, 264), 'numpy.m... |
"""
Module: libfmp.c8.c8s2_salience
Author: <NAME>, <NAME>
License: The MIT license, https://opensource.org/licenses/MIT
This file is part of the FMP Notebooks (https://www.audiolabs-erlangen.de/FMP)
"""
import numpy as np
import librosa
from scipy import ndimage
from numba import jit
import libfmp.b
import libfmp.c... | [
"numpy.hanning",
"numpy.abs",
"numpy.copy",
"numpy.logical_and",
"numpy.angle",
"numpy.array",
"numpy.zeros",
"numba.jit",
"librosa.stft",
"numpy.log2",
"numpy.mod",
"numpy.float32",
"numpy.arange"
] | [((325, 343), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (328, 343), False, 'from numba import jit\n'), ((709, 727), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (712, 727), False, 'from numba import jit\n'), ((1672, 1690), 'numba.jit', 'jit', ([], {'nopython': '(Tr... |
#a2.t2 #This program is to create a function to assess humidity
#taking advantage of python statistics library
import statistics
def get_humidity_value(humidity_value):
if statistics.median(humidity_value) < 30:
return "It is Dry"
elif statistics.median(humidity_value) > 60:
return "High Humidit... | [
"statistics.median"
] | [((176, 209), 'statistics.median', 'statistics.median', (['humidity_value'], {}), '(humidity_value)\n', (193, 209), False, 'import statistics\n'), ((252, 285), 'statistics.median', 'statistics.median', (['humidity_value'], {}), '(humidity_value)\n', (269, 285), False, 'import statistics\n')] |
import argparse
import ast
class PrintStatementParser(ast.NodeVisitor):
def __init__(self):
self.print_nodes = []
def visit_Call(self, node):
if not isinstance(node.func, ast.Name):
return
if node.func.id != 'print':
return
self.print_nodes.append(nod... | [
"ast.parse",
"argparse.ArgumentParser"
] | [((359, 384), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (382, 384), False, 'import argparse\n'), ((648, 690), 'ast.parse', 'ast.parse', (['file_content'], {'filename': 'filename'}), '(file_content, filename=filename)\n', (657, 690), False, 'import ast\n')] |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from typing import Any, Optional, Tuple
import torch
import torch.distributed as dist
from colossalai.communication import all_gather, all_reduce, reduce_scatter
from colossalai.context.parallel_mode import ParallelMode
from colossalai.core import global_context as gpc
... | [
"torch.cuda.amp.custom_fwd",
"torch.mul",
"colossalai.core.global_context.get_local_rank",
"colossalai.communication.all_gather",
"torch.unsqueeze",
"colossalai.communication.reduce_scatter",
"torch.stack",
"torch.sqrt",
"colossalai.core.global_context.get_group",
"torch.matmul",
"torch.sum",
... | [((462, 499), 'torch.cuda.amp.custom_fwd', 'custom_fwd', ([], {'cast_inputs': 'torch.float16'}), '(cast_inputs=torch.float16)\n', (472, 499), False, 'from torch.cuda.amp import custom_bwd, custom_fwd\n'), ((5920, 5957), 'torch.cuda.amp.custom_fwd', 'custom_fwd', ([], {'cast_inputs': 'torch.float16'}), '(cast_inputs=tor... |
from django.contrib.auth import get_user_model
from django.contrib.postgres.fields import ArrayField
from django.db import models
from django.utils.timezone import now
from ordered_model.models import OrderedModel
User = get_user_model()
class Habit(OrderedModel):
name = models.CharField(max_length=255)
days... | [
"django.contrib.auth.get_user_model",
"django.db.models.DateField",
"django.db.models.ForeignKey",
"django.db.models.IntegerField",
"django.db.models.BooleanField",
"django.db.models.BigIntegerField",
"django.db.models.CharField"
] | [((222, 238), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (236, 238), False, 'from django.contrib.auth import get_user_model\n'), ((279, 311), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(255)'}), '(max_length=255)\n', (295, 311), False, 'from django.db import mo... |
from pandas import Series
from igraph import *
from numba import jit
import numpy as np
import os
# import time
# Gather all the files.
files = os.listdir('timeseries/')
# Concatenate (or stack) all the files.
# Approx 12.454981 seconds
i = 0
for f in files:
if i == 0:
ts_matrix = np.loadtxt('timeseries/'... | [
"pandas.Series",
"os.listdir",
"numpy.hstack",
"numpy.where",
"numpy.corrcoef",
"numpy.loadtxt",
"numpy.arange"
] | [((145, 170), 'os.listdir', 'os.listdir', (['"""timeseries/"""'], {}), "('timeseries/')\n", (155, 170), False, 'import os\n'), ((504, 528), 'numpy.corrcoef', 'np.corrcoef', (['ts_matrix.T'], {}), '(ts_matrix.T)\n', (515, 528), True, 'import numpy as np\n'), ((1929, 1940), 'numpy.where', 'np.where', (['X'], {}), '(X)\n'... |
import tensorflow as tf
from tensorflow import keras
def build_mlp(
mlp_input,
output_size,
n_layers,
size,
output_activation = None):
x = mlp_input
for _ in range(n_layers) :
x = keras.layers.Dense(units = size, activation = 'relu')(x)
return keras.layers.Dense(units = output_... | [
"tensorflow.keras.layers.Dense"
] | [((286, 353), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', ([], {'units': 'output_size', 'activation': 'output_activation'}), '(units=output_size, activation=output_activation)\n', (304, 353), False, 'from tensorflow import keras\n'), ((218, 267), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', ([], {'... |
import numpy as np
# Part 1
data = np.loadtxt('data.csv')
def get_number_of_times_count_increased(data):
increased_counter = 0
for i in range(len(data)-1):
if data[i+1]>data[i]:
increased_counter +=1
return increased_counter
data = np.loadtxt('data.csv')
increased_counter = get_numbe... | [
"numpy.sum",
"numpy.loadtxt"
] | [((37, 59), 'numpy.loadtxt', 'np.loadtxt', (['"""data.csv"""'], {}), "('data.csv')\n", (47, 59), True, 'import numpy as np\n'), ((268, 290), 'numpy.loadtxt', 'np.loadtxt', (['"""data.csv"""'], {}), "('data.csv')\n", (278, 290), True, 'import numpy as np\n'), ((568, 599), 'numpy.sum', 'np.sum', (['data[i:i + window_size... |
from flask import render_template, request, redirect, url_for
from flask_login import login_user, logout_user
from application import app
from application.auth.models import User
from application.auth.forms import LoginForm
@app.route("/auth/login", methods = ["GET", "POST"])
def auth_login():
if request.method... | [
"flask.render_template",
"flask_login.login_user",
"flask_login.logout_user",
"application.auth.forms.LoginForm",
"flask.url_for",
"application.app.route",
"application.auth.models.User.query.filter_by"
] | [((229, 278), 'application.app.route', 'app.route', (['"""/auth/login"""'], {'methods': "['GET', 'POST']"}), "('/auth/login', methods=['GET', 'POST'])\n", (238, 278), False, 'from application import app\n'), ((792, 817), 'application.app.route', 'app.route', (['"""/auth/logout"""'], {}), "('/auth/logout')\n", (801, 817... |
# Copyright (c) 2019 Intel Corporation.
#
# 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, ... | [
"logging.getLogger",
"cv2.createBackgroundSubtractorMOG2",
"cv2.threshold",
"cv2.morphologyEx",
"numpy.sum",
"cv2.getStructuringElement",
"cv2.boundingRect"
] | [((2080, 2111), 'logging.getLogger', 'logging.getLogger', (['"""PCB_FILTER"""'], {}), "('PCB_FILTER')\n", (2097, 2111), False, 'import logging\n'), ((2242, 2278), 'cv2.createBackgroundSubtractorMOG2', 'cv2.createBackgroundSubtractorMOG2', ([], {}), '()\n', (2276, 2278), False, 'import cv2\n'), ((3565, 3616), 'cv2.getSt... |
import requests
import base64
from flask import Flask, request
from flask_restful import Resource, Api
from web import common
app = Flask(__name__)
api = Api(app)
class PyOpenOcrBase64(Resource):
def post(self):
decoded = base64.decodebytes(request.data)
return common.data_to_text(decoded, req... | [
"flask_restful.Api",
"flask.Flask",
"flask.request.data.decode",
"requests.get",
"web.common.data_to_text",
"base64.decodebytes"
] | [((136, 151), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (141, 151), False, 'from flask import Flask, request\n'), ((158, 166), 'flask_restful.Api', 'Api', (['app'], {}), '(app)\n', (161, 166), False, 'from flask_restful import Resource, Api\n'), ((240, 272), 'base64.decodebytes', 'base64.decodebytes',... |
import numpy as np
from scipy.sparse import diags
from sklearn.metrics import pairwise_distances
from fclsp.reshaping_utils import vec_hollow_sym
def get_lap_coef(V, w, var_type, shape):
"""
Computes the Laplacian coefficent vector
TODO: finish documenting
Parameters
----------
V: array-lik... | [
"fclsp.reshaping_utils.vec_hollow_sym",
"numpy.sqrt"
] | [((1688, 1708), 'fclsp.reshaping_utils.vec_hollow_sym', 'vec_hollow_sym', (['coef'], {}), '(coef)\n', (1702, 1708), False, 'from fclsp.reshaping_utils import vec_hollow_sym\n'), ((1579, 1589), 'numpy.sqrt', 'np.sqrt', (['w'], {}), '(w)\n', (1586, 1589), True, 'import numpy as np\n')] |
#
#
import sys, bisect
from file_ops import (
read_sb_solution_wordlist,
read_sb_wordlist,
read_found_wordlist,
write_sb_wordlist,
)
from utils import add_words, remove_words, get_solve_date
def main(days_ago=1):
# First, determine the solve date in iso format
iso_solve_date = get_solve_date(d... | [
"file_ops.read_sb_solution_wordlist",
"file_ops.write_sb_wordlist",
"utils.add_words",
"file_ops.read_sb_wordlist",
"utils.remove_words",
"utils.get_solve_date",
"file_ops.read_found_wordlist"
] | [((304, 328), 'utils.get_solve_date', 'get_solve_date', (['days_ago'], {}), '(days_ago)\n', (318, 328), False, 'from utils import add_words, remove_words, get_solve_date\n'), ((432, 450), 'file_ops.read_sb_wordlist', 'read_sb_wordlist', ([], {}), '()\n', (448, 450), False, 'from file_ops import read_sb_solution_wordlis... |
# See ciDifference.ipynb for derivation, implementation notes, and test
def cidifference(datagen, umin, umax, wmin, wmax, alpha=0.05,
rmin=0, rmax=1, raiseonerr=False):
import numpy as np
from cvxopt import solvers, matrix
from math import log, exp
from scipy.stats import f
from .es... | [
"scipy.stats.f.isf",
"numpy.ones",
"pprint.pformat",
"math.log",
"numpy.array",
"numpy.zeros",
"numpy.outer",
"cvxopt.matrix",
"math.exp"
] | [((3035, 3144), 'numpy.array', 'np.array', (['[[1, u, w] for u in (umin, umax) for w in (wmin, wmax) for r in (rmin, rmax)]'], {'dtype': '"""float64"""'}), "([[1, u, w] for u in (umin, umax) for w in (wmin, wmax) for r in (\n rmin, rmax)], dtype='float64')\n", (3043, 3144), True, 'import numpy as np\n'), ((633, 667)... |
from nimblenet.activation_functions import sigmoid_function
from nimblenet.cost_functions import *
from nimblenet.learning_algorithms import *
from nimblenet.neuralnet import NeuralNet
from nimblenet.preprocessing import construct_preprocessor, standarize
from nimblenet.data_structures import Instance
from nimblenet.to... | [
"nimblenet.neuralnet.NeuralNet",
"task.Task",
"rehearsal.recency",
"rehearsal.sweep",
"rehearsal.catastrophicForgetting",
"rehearsal.pseudoSweep",
"nimblenet.data_structures.Instance",
"rehearsal.pseudo"
] | [((1303, 1504), 'task.Task', 'task.Task', ([], {'inputNodes': 'inputNodes', 'hiddenNodes': 'hiddenNodes', 'outputNodes': 'outputNodes', 'populationSize': 'numPatterns', 'auto': 'auto', 'learningConstant': 'learningConstant', 'momentumConstant': 'momentumConstant'}), '(inputNodes=inputNodes, hiddenNodes=hiddenNodes, out... |
from django.urls import reverse, resolve
from rest_framework.test import APITestCase
from product.views import (
ProduceAPI,
AddProductAPI,
ProduceDetailsAPI,
ProduceEditDelete
)
class TestProduceUrlsCase(APITestCase):
def test_get_produce_resolves(self):
url = reverse('products')
... | [
"django.urls.resolve",
"django.urls.reverse"
] | [((294, 313), 'django.urls.reverse', 'reverse', (['"""products"""'], {}), "('products')\n", (301, 313), False, 'from django.urls import reverse, resolve\n'), ((438, 460), 'django.urls.reverse', 'reverse', (['"""add-product"""'], {}), "('add-product')\n", (445, 460), False, 'from django.urls import reverse, resolve\n'),... |
from urllib.request import urlopen
from bs4 import BeautifulSoup
from youtube_dl import YoutubeDL
import pyexcel
# Part 1
url = "https://www.apple.com/itunes/charts/songs/"
html_content = urlopen(url).read().decode('utf-8')
soup = BeautifulSoup(html_content,"html.parser")
section = soup.find("section","section chart-g... | [
"bs4.BeautifulSoup",
"youtube_dl.YoutubeDL",
"urllib.request.urlopen",
"pyexcel.save_as"
] | [((232, 274), 'bs4.BeautifulSoup', 'BeautifulSoup', (['html_content', '"""html.parser"""'], {}), "(html_content, 'html.parser')\n", (245, 274), False, 'from bs4 import BeautifulSoup\n'), ((505, 575), 'pyexcel.save_as', 'pyexcel.save_as', ([], {'records': 'table', 'dest_file_name': '"""itunes_top_songs.xlsx"""'}), "(rec... |
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
import matplotlib.animation as animation
filename = "experiment_data/012522-16_29_48-data.csv"
data = np.genfromtxt(filename, delimiter=',', skip_header=2)
timestamps = data[:, 0]
timestamps -= timestamps[0]
cf1_actual_posi... | [
"mpl_toolkits.mplot3d.axes3d.Axes3D",
"matplotlib.pyplot.figure",
"numpy.genfromtxt",
"matplotlib.pyplot.show"
] | [((197, 250), 'numpy.genfromtxt', 'np.genfromtxt', (['filename'], {'delimiter': '""","""', 'skip_header': '(2)'}), "(filename, delimiter=',', skip_header=2)\n", (210, 250), True, 'import numpy as np\n'), ((832, 844), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (842, 844), True, 'import matplotlib.pyplot... |
import pygame
import random
from constants import *
class Snake:
def __init__(self, start: Vector = START, colour=BLUE, target: Vector = START):
self.body = [start.copy()]
self.speed_factor = 1.0
self.colour = colour
self.direction = Vector()
self.target = target
s... | [
"random.randint",
"pygame.time.get_ticks"
] | [((1912, 1935), 'pygame.time.get_ticks', 'pygame.time.get_ticks', ([], {}), '()\n', (1933, 1935), False, 'import pygame\n'), ((3358, 3388), 'random.randint', 'random.randint', (['(0)', 'self.radius'], {}), '(0, self.radius)\n', (3372, 3388), False, 'import random\n'), ((3439, 3469), 'random.randint', 'random.randint', ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# This file is part of Simple Wallpaper Randomizer
#
# Copyright (c) 2019 <NAME> <<EMAIL>>
#
# 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 w... | [
"os.path.exists",
"comun.get_desktop_environment",
"simplewallpaperrandomizer.add_file_to_displayed_files",
"os.getuid",
"simplewallpaperrandomizer.get_not_displayed_files",
"shutil.copyfile",
"os.system"
] | [((1469, 1520), 'shutil.copyfile', 'shutil.copyfile', (['filename', 'comun.SELECTED_WALLPAPER'], {}), '(filename, comun.SELECTED_WALLPAPER)\n', (1484, 1520), False, 'import shutil\n'), ((2036, 2076), 'os.path.exists', 'os.path.exists', (['comun.SELECTED_WALLPAPER'], {}), '(comun.SELECTED_WALLPAPER)\n', (2050, 2076), Fa... |
from http.server import HTTPServer
from http.server import BaseHTTPRequestHandler
from .log import Log
class HttpServer(BaseHTTPRequestHandler):
request_handler_class = None
@staticmethod
def start(url, port, request_handler_class):
HttpServer.request_handler_class = request_handler_class
... | [
"http.server.HTTPServer"
] | [((330, 365), 'http.server.HTTPServer', 'HTTPServer', (['(url, port)', 'HttpServer'], {}), '((url, port), HttpServer)\n', (340, 365), False, 'from http.server import HTTPServer\n')] |
# Generated by Django 3.1.1 on 2020-09-28 19:15
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('sales', '0015_auto_20200920_1049'),
]
operations = [
migrations.AlterField(
model_name='orderli... | [
"django.db.models.ForeignKey"
] | [((377, 495), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'blank': '(True)', 'null': '(True)', 'on_delete': 'django.db.models.deletion.DO_NOTHING', 'to': '"""sales.buyerproduct"""'}), "(blank=True, null=True, on_delete=django.db.models.\n deletion.DO_NOTHING, to='sales.buyerproduct')\n", (394, 495), Fa... |
# ////////////////////////////////////////////////////////////////////////////
# // This file is part of NIID-Net. For more information
# // see <https://github.com/zju3dv/NIID-Net>.
# // If you use this code, please cite the corresponding publications as
# // listed on the above website.
# //
# // Copyright (c) Z... | [
"torch.cuda.manual_seed_all",
"torch.manual_seed",
"random.seed",
"numpy.random.seed",
"torch.cuda.manual_seed"
] | [((1479, 1502), 'torch.manual_seed', 'torch.manual_seed', (['SEED'], {}), '(SEED)\n', (1496, 1502), False, 'import torch\n'), ((1511, 1539), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['SEED'], {}), '(SEED)\n', (1533, 1539), False, 'import torch\n'), ((1548, 1580), 'torch.cuda.manual_seed_all', 'torch.cuda.ma... |
from city import City
from zoo import Zoo
vienna = City("vienna")
assert vienna.zoo
assert isinstance(vienna.zoo, Zoo)
assert vienna.zoo.size == 130
assert vienna.zoo._owner_name == "<NAME>"
print(
f"City: {vienna.name}\n"
f"Zoo owner: {vienna.zoo._owner_name}\n"
f"Zoo's size: {vienna.zoo.size}\n"
f... | [
"city.City"
] | [((53, 67), 'city.City', 'City', (['"""vienna"""'], {}), "('vienna')\n", (57, 67), False, 'from city import City\n')] |
"""
test specfile helpers
"""
import unittest
from pathlib import Path
from packaging_utils.specfile import helpers
class TestSpecfileHelpers(unittest.TestCase):
def test_source_filenames_diffoscope(self):
source_path = Path(__file__).parent / 'diffoscope.spec'
self.assertListEqual(
he... | [
"pathlib.Path"
] | [((234, 248), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (238, 248), False, 'from pathlib import Path\n'), ((501, 515), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (505, 515), False, 'from pathlib import Path\n')] |
from twisted.internet import defer
import config
import log
from color import colorize
from err import *
class Scanner(object):
def __init__(self, target, checks, title=None, verbose=False, runningResults=False):
self.target = target
self.checks = checks
self.title = title
self.sc... | [
"color.colorize",
"twisted.internet.defer.DeferredList"
] | [((1887, 1912), 'color.colorize', 'colorize', (['"""@B[@R!!!@B]@x"""'], {}), "('@B[@R!!!@B]@x')\n", (1895, 1912), False, 'from color import colorize\n'), ((1766, 1785), 'color.colorize', 'colorize', (['"""@B--@x """'], {}), "('@B--@x ')\n", (1774, 1785), False, 'from color import colorize\n'), ((3208, 3260), 'twisted.i... |
from typing import Dict, Generator, Optional, Tuple, Union
import numpy as np
from joblib import ( # type: ignore
delayed,
Parallel,
)
from numpy import linalg
from sklearn.metrics import accuracy_score
from sklearn.base import BaseEstimator
from libifbtsvm.functions import (
fuzzy_membership,
trai... | [
"numpy.reshape",
"numpy.unique",
"numpy.ones",
"libifbtsvm.functions.train_model",
"numpy.delete",
"numpy.where",
"numpy.asarray",
"joblib.Parallel",
"numpy.array",
"numpy.append",
"numpy.argwhere",
"numpy.matmul",
"numpy.ndarray",
"numpy.concatenate",
"numpy.linalg.norm",
"joblib.dela... | [((1870, 1901), 'numpy.delete', 'np.delete', (['score[0]', 'candidates'], {}), '(score[0], candidates)\n', (1879, 1901), True, 'import numpy as np\n'), ((1917, 1948), 'numpy.delete', 'np.delete', (['score[1]', 'candidates'], {}), '(score[1], candidates)\n', (1926, 1948), True, 'import numpy as np\n'), ((1966, 1990), 'n... |
import threading
import random
import time
import datetime
import pickle, os
class session:
def __init__(self, sesid, timeout = 259200):
self.id = sesid
self.timeout = timeout
self.idle = datetime.datetime.now()
self.data = {}
def setData(self, param, value):
self.data[pa... | [
"threading.Thread.__init__",
"pickle.dump",
"pickle.load",
"threading.Event",
"datetime.datetime.now",
"os.path.isfile",
"datetime.timedelta",
"random.randint"
] | [((216, 239), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (237, 239), False, 'import datetime\n'), ((353, 376), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (374, 376), False, 'import datetime\n'), ((621, 644), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '(... |
# Simple Python script to compute feature importance using univariate statistical analysis, recursive feature elimination, and elastic net
# by <NAME> and <NAME>, 2018
import numpy as np
import sys
# feature selection methods
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import Gene... | [
"sklearn.linear_model.ElasticNetCV",
"sklearn.feature_selection.SelectKBest",
"datetime.datetime.now",
"genericFunctions.loadTCGADataset",
"numpy.isnan",
"sklearn.svm.SVC"
] | [((876, 894), 'sklearn.feature_selection.SelectKBest', 'SelectKBest', ([], {'k': '(100)'}), '(k=100)\n', (887, 894), False, 'from sklearn.feature_selection import SelectKBest\n'), ((1141, 1155), 'sklearn.linear_model.ElasticNetCV', 'ElasticNetCV', ([], {}), '()\n', (1153, 1155), False, 'from sklearn.linear_model import... |
# MIT License
#
# Copyright (c) 2019 Creative Commons
#
# 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, me... | [
"linkedin.message.Template"
] | [((4314, 4411), 'linkedin.message.Template', 'Template', (['None'], {'var_template': 'None', 'grammar_check': '(False)', 'use_template': '"""template_ben_franklin"""'}), "(None, var_template=None, grammar_check=False, use_template=\n 'template_ben_franklin')\n", (4322, 4411), False, 'from linkedin.message import Tem... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-06-01 09:56
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
... | [
"django.db.models.DateTimeField",
"django.db.models.AutoField",
"django.db.models.CharField"
] | [((387, 480), '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", (403, 480), False, 'from django.db import migrations, models\... |
import pyswan
# # 梁山108好汉!
# print(pyswan.digitize("梁山一百零八好汉!"))
# # 今天是周7
# print(pyswan.digitize("今天是周日"))
# # TODO
# pyswan.digitize("明天是劳动节")
# # [{'dim': 'time', 'body': '12点30分', 'start': 0, 'end': 0, 'value': '2022-01-06 12:30:51 +08:00'}]
# pyswan.parse('十二点三十分', dim=['time', 'number'])
# # [{'type': 'equ... | [
"arrow.utcnow"
] | [((666, 680), 'arrow.utcnow', 'arrow.utcnow', ([], {}), '()\n', (678, 680), False, 'import arrow\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import cv2
class VideoInputStreamIterator:
"""
iterator through the read video
"""
def __init__(self, input_stream):
self._stream = input_stream
def __next__(self):
return self._stream.grab_frame()
class VideoInputStream:
"""
... | [
"os.path.exists",
"tqdm.tqdm",
"cv2.imshow",
"cv2.VideoCapture",
"cv2.VideoWriter_fourcc",
"cv2.waitKey"
] | [((4611, 4629), 'tqdm.tqdm', 'tqdm', (['video_stream'], {}), '(video_stream)\n', (4615, 4629), False, 'from tqdm import tqdm\n'), ((4922, 4940), 'tqdm.tqdm', 'tqdm', (['video_stream'], {}), '(video_stream)\n', (4926, 4940), False, 'from tqdm import tqdm\n'), ((677, 705), 'cv2.VideoCapture', 'cv2.VideoCapture', (['video... |
"""Module contains an approximate garbage score estimator
See ags_.
"""
from typing import Optional
from FaceEngine import IAGSEstimatorPtr # pylint: disable=E0611,E0401
from lunavl.sdk.errors.errors import LunaVLError
from lunavl.sdk.errors.exceptions import CoreExceptionWrap, LunaSDKException
from lunavl.sdk.esti... | [
"lunavl.sdk.errors.exceptions.CoreExceptionWrap",
"lunavl.sdk.errors.errors.LunaVLError.fromSDKError"
] | [((838, 887), 'lunavl.sdk.errors.exceptions.CoreExceptionWrap', 'CoreExceptionWrap', (['LunaVLError.EstimationAGSError'], {}), '(LunaVLError.EstimationAGSError)\n', (855, 887), False, 'from lunavl.sdk.errors.exceptions import CoreExceptionWrap, LunaSDKException\n'), ((1953, 1984), 'lunavl.sdk.errors.errors.LunaVLError.... |
import gzip
import json
import re
import string
import unicodedata
from collections import defaultdict
from pathlib import Path
import pandas as pd
import click
from sentencepiece import SentencePieceProcessor
from tqdm import tqdm
import ast
import nltk
nltk.download('punkt')
nltk.download('stopwords')
nltk.download('... | [
"nltk.pos_tag",
"nltk.corpus.stopwords.words",
"nltk.word_tokenize",
"nltk.download",
"pandas.read_csv",
"json.dumps",
"tqdm.tqdm",
"collections.Counter",
"ast.literal_eval"
] | [((255, 277), 'nltk.download', 'nltk.download', (['"""punkt"""'], {}), "('punkt')\n", (268, 277), False, 'import nltk\n'), ((278, 304), 'nltk.download', 'nltk.download', (['"""stopwords"""'], {}), "('stopwords')\n", (291, 304), False, 'import nltk\n'), ((305, 348), 'nltk.download', 'nltk.download', (['"""averaged_perce... |
import random
import pygame
class GameObject(pygame.sprite.Sprite):
'''
All sprites should inherit from this class.
'''
def __init__(self, game, name):
'''
Sets the sprite image and rect Surface.
'''
# Call the parent class (Sprite) constructor
pygame.sprite.Spr... | [
"pygame.time.set_timer",
"random.randrange",
"pygame.sprite.Sprite.__init__",
"pygame.time.wait",
"pygame.mixer.music.stop",
"pygame.mixer.music.get_busy",
"pygame.mixer.Sound",
"pygame.image.load",
"pygame.display.update",
"pygame.mixer.music.play",
"pygame.font.SysFont"
] | [((303, 338), 'pygame.sprite.Sprite.__init__', 'pygame.sprite.Sprite.__init__', (['self'], {}), '(self)\n', (332, 338), False, 'import pygame\n'), ((411, 443), 'pygame.image.load', 'pygame.image.load', (["(name + '.png')"], {}), "(name + '.png')\n", (428, 443), False, 'import pygame\n'), ((2890, 2918), 'pygame.image.lo... |
"""Collage renderer."""
import itertools
import logger
import numpy
from PIL import Image, ImageEnhance
from distance_matrix import imageMSE
ENABLE_POST_OPTIMIZATION = True
def adjustImage(image, parameters):
"""Adjusts the brightness, contrast, and saturation of the given image."""
(brightness, contrast, satur... | [
"distance_matrix.imageMSE",
"PIL.Image.new",
"PIL.Image.blend",
"itertools.product",
"logger.info",
"PIL.ImageEnhance.Brightness",
"PIL.ImageEnhance.Contrast",
"PIL.ImageEnhance.Color",
"logger.progress",
"numpy.arange"
] | [((898, 926), 'numpy.arange', 'numpy.arange', (['(0.6)', '(1.3)', '(0.05)'], {}), '(0.6, 1.3, 0.05)\n', (910, 926), False, 'import numpy\n'), ((943, 971), 'numpy.arange', 'numpy.arange', (['(0.9)', '(1.2)', '(0.05)'], {}), '(0.9, 1.2, 0.05)\n', (955, 971), False, 'import numpy\n'), ((990, 1018), 'numpy.arange', 'numpy.... |
import aiohttp
import asyncio
import os
import sys
import time
import random
import contextlib
seaweedfs_url = 'http://127.0.0.1:9081'
def random_content():
return os.urandom(random.randint(1, 10) * 1024)
def random_fid(volumes):
volume_id = random.choice(volumes)
file_key = random.randint(0, 1 << 24)... | [
"aiohttp.ClientSession",
"random.choice",
"random.shuffle",
"asyncio.gather",
"time.monotonic",
"aiohttp.FormData",
"asyncio.get_event_loop",
"random.randint"
] | [((256, 278), 'random.choice', 'random.choice', (['volumes'], {}), '(volumes)\n', (269, 278), False, 'import random\n'), ((294, 320), 'random.randint', 'random.randint', (['(0)', '(1 << 24)'], {}), '(0, 1 << 24)\n', (308, 320), False, 'import random\n'), ((1376, 1394), 'aiohttp.FormData', 'aiohttp.FormData', ([], {}), ... |
#-*-coding:UTF-8-*-
#Modules
from tkinter import *
from tkinter import messagebox as msg
from requests import *
#Function
def start():
global usr
url="http://www."+etry_url.get()
#url="http://172.16.58.3/index.html"
a=usr.get()
if a==0:
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 6.... | [
"tkinter.messagebox.showinfo"
] | [((680, 717), 'tkinter.messagebox.showinfo', 'msg.showinfo', ([], {'title': '"""Info"""', 'message': 'r'}), "(title='Info', message=r)\n", (692, 717), True, 'from tkinter import messagebox as msg\n')] |
import json
from django.conf import settings
from django.template.loader import render_to_string
from api_v3.factories import (
ProfileFactory, TicketFactory, ResponderFactory, SubscriberFactory)
from api_v3.factories.support import Faker
from api_v3.models import Subscriber, Action
from api_v3.serializers import... | [
"json.loads",
"api_v3.models.Subscriber.objects.last",
"api_v3.factories.ResponderFactory.create",
"api_v3.factories.TicketFactory.create",
"json.dumps",
"api_v3.factories.SubscriberFactory.create",
"api_v3.models.Action",
"api_v3.models.Subscriber.objects.count",
"api_v3.factories.ProfileFactory.cr... | [((1200, 1268), 'api_v3.factories.SubscriberFactory.create', 'SubscriberFactory.create', ([], {'ticket': 'self.tickets[0]', 'user': 'self.users[0]'}), '(ticket=self.tickets[0], user=self.users[0])\n', (1224, 1268), False, 'from api_v3.factories import ProfileFactory, TicketFactory, ResponderFactory, SubscriberFactory\n... |
from time import sleep
import emoji
nome = str(input('Qual seu nome completo? ')).strip()
nom = nome.split()
print('É um prazer conhecer você\n{}, {}'.format(nom[0].capitalize(), nom[len(nom) - 1].capitalize()))
print(emoji.emojize('Serei seu mestre em alguns anos...não pera, estão me desligandooo..:dizzy_face:',use_al... | [
"emoji.emojize",
"time.sleep"
] | [((333, 341), 'time.sleep', 'sleep', (['(4)'], {}), '(4)\n', (338, 341), False, 'from time import sleep\n'), ((218, 342), 'emoji.emojize', 'emoji.emojize', (['"""Serei seu mestre em alguns anos...não pera, estão me desligandooo..:dizzy_face:"""'], {'use_aliases': '(True)'}), "(\n 'Serei seu mestre em alguns anos...n... |
def capitalcities(user_input):
import pandas as pd
caps = pd.read_html('https://en.wikipedia.org/wiki/List_of_national_capitals')
capital = caps[1]
capital.drop('Notes', axis = 1, inplace = True)
capital.columns = ['Capital', 'Country']
capital[capital['Country'] == 'Sri Lanka']
capital.d... | [
"pandas.read_html"
] | [((69, 140), 'pandas.read_html', 'pd.read_html', (['"""https://en.wikipedia.org/wiki/List_of_national_capitals"""'], {}), "('https://en.wikipedia.org/wiki/List_of_national_capitals')\n", (81, 140), True, 'import pandas as pd\n')] |
import json
import os
import sys
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow as tf
import sentencepiece as spm
seq_length = 256
max_predictions_per_seq = 20
name_to_features = {
'input_ids':
tf.io.FixedLenFeature([seq_length], tf.int64),
'input_mask':
tf.io.FixedLenFeature([se... | [
"tensorflow.data.TFRecordDataset",
"tensorflow.io.parse_single_example",
"sentencepiece.SentencePieceProcessor",
"tensorflow.io.FixedLenFeature",
"tensorflow.cast"
] | [((1243, 1271), 'sentencepiece.SentencePieceProcessor', 'spm.SentencePieceProcessor', ([], {}), '()\n', (1269, 1271), True, 'import sentencepiece as spm\n'), ((2703, 2734), 'tensorflow.data.TFRecordDataset', 'tf.data.TFRecordDataset', (['[name]'], {}), '([name])\n', (2726, 2734), True, 'import tensorflow as tf\n'), ((2... |
# Universidade Federal de Viçosa - Campus Rio Paranaíba
# Sistemas de Informação - Processamento Digital de Imagens
#
# Professor: <NAME>
# Autores:
# - MatheusRV (3929)
# - iguit0 (3902)
# - ThiagoMunich (3628)
#
# Filtragem espacial para suavização - Filtro de máximo e mínimo
# Como Executa... | [
"scipy.ndimage.filters.median_filter",
"scipy.misc.imsave",
"scipy.misc.imread"
] | [((789, 824), 'scipy.ndimage.filters.median_filter', 'filters.median_filter', (['img'], {'size': 'ms'}), '(img, size=ms)\n', (810, 824), False, 'from scipy.ndimage import filters\n'), ((838, 869), 'scipy.misc.imsave', 'misc.imsave', (['saida', 'img_mediana'], {}), '(saida, img_mediana)\n', (849, 869), False, 'from scip... |
import torch
import torch.nn as nn
from .segmentation import deeplabv3_resnet50, deeplabv3_resnet101
__ALL__ = ["get_model"]
BatchNorm2d = nn.BatchNorm2d
BN_MOMENTUM = 0.01
class Transform(nn.Module):
def forward(self, input):
return 2 * input / 255 - 1
def load_pretrain_model(model, pretrain: str, cit... | [
"torch.nn.ReLU",
"torch.load",
"torch.nn.Conv2d",
"torch.nn.Identity",
"torch.nn.ConvTranspose2d"
] | [((3250, 3346), 'torch.nn.Conv2d', 'nn.Conv2d', (['input_channels', '(64)'], {'kernel_size': '(7, 7)', 'stride': '(2, 2)', 'padding': '(3, 3)', 'bias': '(False)'}), '(input_channels, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3,\n 3), bias=False)\n', (3259, 3346), True, 'import torch.nn as nn\n'), ((458, 498), ... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 29 16:39:41 2021
@author: harsh
"""
import numpy as np
import math as mm
import opensees as op
import time as tt
##################################################################
# #
# Effective s... | [
"opensees.updateMaterialStage",
"opensees.wipe",
"math.floor",
"opensees.nDMaterial",
"opensees.pattern",
"math.cos",
"opensees.getTime",
"opensees.numberer",
"opensees.integrator",
"opensees.constraints",
"math.atan",
"opensees.element",
"opensees.wipeAnalysis",
"opensees.timeSeries",
"... | [((1778, 1787), 'opensees.wipe', 'op.wipe', ([], {}), '()\n', (1785, 1787), True, 'import opensees as op\n'), ((2056, 2080), 'numpy.zeros', 'np.zeros', (['(numLayers, 1)'], {}), '((numLayers, 1))\n', (2064, 2080), True, 'import numpy as np\n'), ((2540, 2564), 'numpy.zeros', 'np.zeros', (['(numLayers, 1)'], {}), '((numL... |
#!/usr/bin/env python3
# sync-folders.py
from datetime import datetime, date, time
import os
from shutil import copyfile
import sys
# DEBUG
# import pdb
def usage():
print("\tsync-folders.py usage:\n\t$sync-folders.py [command] [source folder] [target folder]\n\n\tCommands:\n- scan: Will scan through the specifie... | [
"os.path.getsize",
"os.path.join",
"os.path.isfile",
"shutil.copyfile",
"os.path.isdir",
"os.mkdir",
"os.walk"
] | [((849, 871), 'os.walk', 'os.walk', (['source_folder'], {}), '(source_folder)\n', (856, 871), False, 'import os\n'), ((1800, 1822), 'os.walk', 'os.walk', (['source_folder'], {}), '(source_folder)\n', (1807, 1822), False, 'import os\n'), ((1091, 1115), 'os.path.join', 'os.path.join', (['path', 'name'], {}), '(path, name... |
#! /root/anaconda3/bin/python
import time
from threading import Thread
from threading import current_thread
print('父线程%s启动' % current_thread().getName())
class MyThread(Thread):
def __init__(self, num, name, args):
super().__init__(name=name)
self.args = args
self.num = num
def run(... | [
"threading.current_thread",
"time.sleep"
] | [((650, 663), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (660, 663), False, 'import time\n'), ((389, 402), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (399, 402), False, 'import time\n'), ((137, 153), 'threading.current_thread', 'current_thread', ([], {}), '()\n', (151, 153), False, 'from threading imp... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2016-2017 by I3py Authors, see AUTHORS for more details.
#
# Distributed under the terms of the BSD license.
#
# The full license is in the file LICENCE, distributed with this software.
# ----------------... | [
"i3py.core.composition.customize",
"i3py.core.limits.FloatLimitsValidator",
"i3py.core.features.scalars.Str",
"i3py.core.declarative.limit",
"i3py.core.features.scalars.Int",
"i3py.core.unit.get_unit_registry",
"i3py.core.limits.IntLimitsValidator",
"pytest.raises",
"i3py.core.declarative.set_feat",... | [((1255, 1293), 'i3py.core.features.scalars.Str', 'Str', ([], {'setter': '(True)', 'values': "['On', 'Off']"}), "(setter=True, values=['On', 'Off'])\n", (1258, 1293), False, 'from i3py.core.features.scalars import Str, Int, Float\n'), ((1487, 1519), 'i3py.core.features.scalars.Str', 'Str', ([], {'mapping': "{'On': 1, '... |
from pyopenproject.api_connection.exceptions.request_exception import RequestError
from pyopenproject.api_connection.requests.post_request import PostRequest
from pyopenproject.business.exception.business_error import BusinessError
from pyopenproject.business.services.command.time_entry.time_entry_command import TimeEn... | [
"pyopenproject.model.form.Form",
"pyopenproject.business.exception.business_error.BusinessError",
"pyopenproject.api_connection.requests.post_request.PostRequest"
] | [((860, 874), 'pyopenproject.model.form.Form', 'Form', (['json_obj'], {}), '(json_obj)\n', (864, 874), False, 'from pyopenproject.model.form import Form\n'), ((928, 983), 'pyopenproject.business.exception.business_error.BusinessError', 'BusinessError', (['f"""Error updating form: {self.form.name}"""'], {}), "(f'Error u... |
import bpy
from bpy.props import *
from ...nodes.BASE.node_tree import RenderStackNode
def update_node(self, context):
self.update_parms()
class RenderNodeSceneRenderEngine(RenderStackNode):
"""A simple input node"""
bl_idname = 'RenderNodeSceneRenderEngine'
bl_label = 'Scene Render Engine'
_en... | [
"bpy.utils.unregister_class",
"bpy.utils.register_class",
"bpy.types.RenderEngine.__subclasses__"
] | [((1362, 1415), 'bpy.utils.register_class', 'bpy.utils.register_class', (['RenderNodeSceneRenderEngine'], {}), '(RenderNodeSceneRenderEngine)\n', (1386, 1415), False, 'import bpy\n'), ((1440, 1495), 'bpy.utils.unregister_class', 'bpy.utils.unregister_class', (['RenderNodeSceneRenderEngine'], {}), '(RenderNodeSceneRende... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable=W0611, W0613, W0621, E1101
from __future__ import unicode_literals
import time
import json
from io import BytesIO
import pytest
import tabun_api as api
from tabun_api.compat import text
from testutil import UserTest, load_file, form_intercept, as_gues... | [
"testutil.user.get_posts",
"testutil.user.add_post",
"time.strftime",
"testutil.load_file",
"pytest.mark.parametrize",
"testutil.user.edit_post",
"pytest.raises",
"testutil.user.get_post",
"tabun_api.compat.text",
"testutil.assert_data",
"testutil.set_mock",
"testutil.user.add_poll",
"testut... | [((6917, 7272), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""blog_id,blog,result_url,draft,tags,forbid_comment"""', "[(6, 'news', 'https://tabun.everypony.ru/blog/news/1.html', False, ['Т2',\n 'Т3'], False), (6, 'news',\n 'https://tabun.everypony.ru/blog/news/1.html', False, ['Т2, Т3'], True),\n ... |
# -*- coding: utf-8 -*-
import re
from django.utils import simplejson as json
rx_circle_float = re.compile(r'<\(([\d\.\-]*),([\d\.\-]*)\),([\d\.\-]*)>')
rx_line = re.compile(r'\[\(([\d\.\-]*),\s*([\w\.\-]*)\),\s*\(([\d\.\-]*),\s*([\d\.\+]*)\)\]')
rx_point = re.compile(r'\(([\d\.\-]*),\s*([\d\.\-]*)\)')
rx_box = re.co... | [
"re.compile",
"psycopg2.extensions.register_type",
"django.db.connection.close",
"psycopg2.extensions.adapt",
"psycopg2.extensions.new_type",
"django.db.connection.cursor",
"psycopg2.extensions.register_adapter"
] | [((98, 164), 're.compile', 're.compile', (['"""<\\\\(([\\\\d\\\\.\\\\-]*),([\\\\d\\\\.\\\\-]*)\\\\),([\\\\d\\\\.\\\\-]*)>"""'], {}), "('<\\\\(([\\\\d\\\\.\\\\-]*),([\\\\d\\\\.\\\\-]*)\\\\),([\\\\d\\\\.\\\\-]*)>')\n", (108, 164), False, 'import re\n'), ((165, 278), 're.compile', 're.compile', (['"""\\\\[\\\\(([\\\\d\\\\... |
from starcluster.clustersetup import ClusterSetup
from starcluster.logger import log
class RInstaller(ClusterSetup):
def run(self, nodes, master, user, user_shell, volumes):
for node in nodes:
log.info("Installing R 3.1.1 on %s" % (node.alias))
log.info("...installing dependencies")
node.ssh.execute('apt-g... | [
"starcluster.logger.log.info"
] | [((200, 249), 'starcluster.logger.log.info', 'log.info', (["('Installing R 3.1.1 on %s' % node.alias)"], {}), "('Installing R 3.1.1 on %s' % node.alias)\n", (208, 249), False, 'from starcluster.logger import log\n'), ((255, 293), 'starcluster.logger.log.info', 'log.info', (['"""...installing dependencies"""'], {}), "('... |
import unittest
import os
from os import listdir, path
from pathlib import Path
class TestSwap(unittest.TestCase):
def test_imports(self):
from pytube import YouTube
def test_get_video(self):
from main import get_video
rickroll = 'https://youtu.be/dQw4w9WgXcQ'
video_path = get_v... | [
"main.cut_video",
"os.path.exists",
"pathlib.Path",
"main.swap_faces",
"main.get_video",
"unittest.main"
] | [((1103, 1118), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1116, 1118), False, 'import unittest\n'), ((315, 334), 'main.get_video', 'get_video', (['rickroll'], {}), '(rickroll)\n', (324, 334), False, 'from main import get_video\n'), ((508, 611), 'pathlib.Path', 'Path', (['"""C:/Users/ru1072781/Repo/yt-swap/vi... |
from helpers import Tags
# Controls
# Button tag class
class Button(Tags):
def __init__(self, attrs):
Tags.__init__(self, "button", attrs)
# Label tag class
class Label(Tags):
def __init__(self, attrs):
Tags.__init__(self, "label", attrs)
# Input tag class
class Input(Tags):
def __i... | [
"helpers.Tags.__init__",
"helpers.Tags.getPrintableTag"
] | [((117, 153), 'helpers.Tags.__init__', 'Tags.__init__', (['self', '"""button"""', 'attrs'], {}), "(self, 'button', attrs)\n", (130, 153), False, 'from helpers import Tags\n'), ((233, 268), 'helpers.Tags.__init__', 'Tags.__init__', (['self', '"""label"""', 'attrs'], {}), "(self, 'label', attrs)\n", (246, 268), False, 'f... |
import logging
from typing import Union, Tuple
import threading
import numpy as np
from pyobs.comm import RemoteException
from pyobs.interfaces import IFocuser, ICamera, IAutoFocus, IFilters, ICameraExposureTime, IImageType
from pyobs.events import FocusFoundEvent
from pyobs.object import get_object
from pyobs.mixins ... | [
"logging.getLogger",
"pyobs.mixins.CameraSettingsMixin.__init__",
"pyobs.object.get_object",
"threading.Event",
"pyobs.modules.Module.open",
"pyobs.modules.timeout",
"numpy.linspace",
"numpy.isnan",
"pyobs.modules.Module.__init__",
"pyobs.events.FocusFoundEvent"
] | [((484, 511), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (501, 511), False, 'import logging\n'), ((2078, 2090), 'pyobs.modules.timeout', 'timeout', (['(600)'], {}), '(600)\n', (2085, 2090), False, 'from pyobs.modules import timeout, Module\n'), ((7549, 7560), 'pyobs.modules.timeout', ... |
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright © 2019, SAS Institute Inc., Cary, NC, USA. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
from unittest import mock
from sasctl.services import model_publish as mp
def test_publish_name():
assert 'ModuleName' == mp._publish_name('Module Name') ... | [
"sasctl.services.model_publish.create_cas_destination",
"sasctl.services.model_publish.create_mas_destination",
"sasctl.services.model_publish._publish_name",
"unittest.mock.patch"
] | [((287, 318), 'sasctl.services.model_publish._publish_name', 'mp._publish_name', (['"""Module Name"""'], {}), "('Module Name')\n", (303, 318), True, 'from sasctl.services import model_publish as mp\n'), ((363, 393), 'sasctl.services.model_publish._publish_name', 'mp._publish_name', (['"""1st Module"""'], {}), "('1st Mo... |
from flask import json
import unittest
from app import app
class BasicTestCase(unittest.TestCase):
def test_ok(self):
assert(1)
def test_ping(self):
tester = app.test_client(self)
response = tester.get('/ping', content_type='html/text')
self.assertEqual(response.status_code, ... | [
"flask.json.loads",
"app.app.test_client"
] | [((186, 207), 'app.app.test_client', 'app.test_client', (['self'], {}), '(self)\n', (201, 207), False, 'from app import app\n'), ((422, 443), 'app.app.test_client', 'app.test_client', (['self'], {}), '(self)\n', (437, 443), False, 'from app import app\n'), ((557, 582), 'flask.json.loads', 'json.loads', (['response.data... |
import matplotlib.pylab as plt
import numpy as np
def plotFlow(env,policy,x2d):
flow = []
for s in range(env.nx):
env.reset(s)
x = x2d(s)
a = policy(s)
snext,r = env.step(a)
xnext = x2d(snext)
flow.append( [x,xnext-x] )
flow=np.array( [ np.concatenate(a) for... | [
"matplotlib.pylab.quiver",
"numpy.concatenate"
] | [((342, 400), 'matplotlib.pylab.quiver', 'plt.quiver', (['flow[:, 0]', 'flow[:, 1]', 'flow[:, 2]', 'flow[:, 3]'], {}), '(flow[:, 0], flow[:, 1], flow[:, 2], flow[:, 3])\n', (352, 400), True, 'import matplotlib.pylab as plt\n'), ((299, 316), 'numpy.concatenate', 'np.concatenate', (['a'], {}), '(a)\n', (313, 316), True, ... |
#!/usr/local/bin/python3
import subprocess
import signal
import sys
from pathlib import Path
import click
import requests
MIGRATE_CHART_SCRIPT = '/migrate_chart.sh'
HELM_CMD = '/linux-amd64/helm'
CA_UPDATE_CMD = 'update-ca-certificates'
CHART_URL_PATTERN = "https://{host}/api/v2.0/projects/{project}/repositories/{na... | [
"signal.signal",
"requests.auth.HTTPBasicAuth",
"pathlib.Path",
"click.option",
"subprocess.run",
"click.echo",
"sys.exit",
"click.command"
] | [((364, 386), 'pathlib.Path', 'Path', (['"""/chart_storage"""'], {}), "('/chart_storage')\n", (368, 386), False, 'from pathlib import Path\n'), ((624, 667), 'signal.signal', 'signal.signal', (['signal.SIGINT', 'graceful_exit'], {}), '(signal.SIGINT, graceful_exit)\n', (637, 667), False, 'import signal\n'), ((668, 712),... |
# -*- coding: utf-8 -*-
"""
Created on July 2017
@author: JulienWuthrich
"""
import time
import datetime
import dateutil.parser
def val2date(val, nformat="%d-%m-%Y"):
if isinstance(val, str):
return dateutil.parser.parse(val).date().strftime(nformat)
if isinstance(val, datetime.date):
retur... | [
"datetime.timedelta"
] | [((1285, 1311), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(1)'}), '(days=1)\n', (1303, 1311), False, 'import datetime\n')] |
import pytest
from metagraph.tests.util import default_plugin_resolver
from . import RoundTripper
from metagraph.plugins.python.types import PythonNodeSetType
from metagraph.plugins.numpy.types import NumpyNodeSet, NumpyNodeMap
import numpy as np
def test_nodeset_roundtrip(default_plugin_resolver):
rt = RoundTrip... | [
"numpy.array"
] | [((514, 535), 'numpy.array', 'np.array', (['[0, 10, 20]'], {}), '([0, 10, 20])\n', (522, 535), True, 'import numpy as np\n'), ((593, 612), 'numpy.array', 'np.array', (['[0, 1, 2]'], {}), '([0, 1, 2])\n', (601, 612), True, 'import numpy as np\n'), ((807, 826), 'numpy.array', 'np.array', (['[9, 5, 1]'], {}), '([9, 5, 1])... |
from types import ClassMethodDescriptorType
import requests, colorgram, os
import time as t
import spotipy.util as util
from PIL import Image, ImageDraw, ImageFont
from spotipy.oauth2 import SpotifyOAuth
# Get creds please enter your creds in creds.txt
global spotify_token, client_id, client_secret, username, displa... | [
"PIL.Image.open",
"colorgram.extract",
"PIL.Image.new",
"PIL.ImageFont.truetype",
"requests.get",
"spotipy.util.prompt_for_user_token",
"os.getcwd",
"time.sleep",
"PIL.ImageDraw.Draw",
"os.system"
] | [((868, 968), 'spotipy.util.prompt_for_user_token', 'util.prompt_for_user_token', (['username', 'scope', 'client_id', 'client_secret', '"""https://www.google.com/"""'], {}), "(username, scope, client_id, client_secret,\n 'https://www.google.com/')\n", (894, 968), True, 'import spotipy.util as util\n'), ((1208, 1298)... |
'''
Created on 25 sty 2015
@author: <NAME>
'''
import unittest
from probability.metric import ExpectedValue, Variation, StandardDeviation
class MetricTest(unittest.TestCase):
def testShouldCalculateExpectedValue(self):
# given
metric = ExpectedValue()
probabilities = {1: ... | [
"unittest.main",
"probability.metric.StandardDeviation",
"probability.metric.ExpectedValue",
"probability.metric.Variation"
] | [((1692, 1707), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1705, 1707), False, 'import unittest\n'), ((275, 290), 'probability.metric.ExpectedValue', 'ExpectedValue', ([], {}), '()\n', (288, 290), False, 'from probability.metric import ExpectedValue, Variation, StandardDeviation\n'), ((746, 757), 'probability... |
import example
import pytest
def test_hunger_is_a_read_only_attribute():
"""
A Pet() object should have an attribute called hunger, and
it should be read only.
"""
pet = example.Pet("Odie")
assert hasattr(pet, "hunger")
with pytest.raises(AttributeError):
pet.hunger = 5
def test... | [
"pytest.raises",
"example.Pet"
] | [((193, 212), 'example.Pet', 'example.Pet', (['"""Odie"""'], {}), "('Odie')\n", (204, 212), False, 'import example\n'), ((442, 461), 'example.Pet', 'example.Pet', (['"""Odie"""'], {}), "('Odie')\n", (453, 461), False, 'import example\n'), ((628, 657), 'example.Pet', 'example.Pet', (['"""Odie"""'], {'hunger': '(3)'}), "... |
# Copyright (c) 2021, Hitachi America Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | [
"os.path.join",
"pdf_struct.core.utils.get_filename",
"collections.defaultdict"
] | [((4245, 4262), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (4256, 4262), False, 'from collections import defaultdict\n'), ((4115, 4133), 'pdf_struct.core.utils.get_filename', 'get_filename', (['path'], {}), '(path)\n', (4127, 4133), False, 'from pdf_struct.core.utils import get_filename\n'), ... |
"""
Definition of direct collocation problem.
Authors: <NAME>, <NAME>
Date: 05/01/2021
"""
# third party imports
try:
import ipyopt
_ipyopt_imported = True
except:
_ipyopt_imported = False
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import minimize, NonlinearConstraint
from scipy.inte... | [
"sympy.Symbol",
"numpy.ones",
"sympy.core.function.BadArgumentsError",
"scipy.optimize.minimize",
"scipy.integrate.solve_ivp",
"sympy.Matrix",
"scipy.optimize.NonlinearConstraint",
"numpy.sum",
"numpy.linspace",
"numpy.zeros",
"numpy.array",
"ipyopt.Problem",
"matplotlib.pyplot.subplots",
... | [((1312, 1323), 'sympy.Symbol', 'Symbol', (['"""h"""'], {}), "('h')\n", (1318, 1323), False, 'from sympy import Matrix, Symbol, lambdify\n'), ((1973, 1991), 'sympy.Matrix', 'Matrix', (['state_vars'], {}), '(state_vars)\n', (1979, 1991), False, 'from sympy import Matrix, Symbol, lambdify\n'), ((1998, 2018), 'sympy.Matri... |
from sqlalchemy import Column, Integer, String, DateTime
from .database import Base
class Website(Base):
__tablename__ = "websites"
id = Column(Integer, primary_key=True, index=True, unique=True)
url = Column(String)
started_at = Column(DateTime)
status = Column(String, default="pending")
co... | [
"sqlalchemy.Column"
] | [((149, 207), 'sqlalchemy.Column', 'Column', (['Integer'], {'primary_key': '(True)', 'index': '(True)', 'unique': '(True)'}), '(Integer, primary_key=True, index=True, unique=True)\n', (155, 207), False, 'from sqlalchemy import Column, Integer, String, DateTime\n'), ((218, 232), 'sqlalchemy.Column', 'Column', (['String'... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
linear_math_tests.test_transform
"""
from __future__ import unicode_literals, print_function, absolute_import
import unittest
import math
import bullet
class TestTransform(unittest.TestCase):
def setUp(self):
self.v1 = tuple(float(i) for i in range(0, 9)... | [
"bullet.btMatrix3x3",
"bullet.btTransform",
"bullet.btQuaternion",
"bullet.btVector3"
] | [((341, 366), 'bullet.btVector3', 'bullet.btVector3', (['(0)', '(0)', '(0)'], {}), '(0, 0, 0)\n', (357, 366), False, 'import bullet\n'), ((430, 458), 'bullet.btMatrix3x3', 'bullet.btMatrix3x3', (['*self.v1'], {}), '(*self.v1)\n', (448, 458), False, 'import bullet\n'), ((477, 497), 'bullet.btTransform', 'bullet.btTransf... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import distributed
from torch.nn import init
from torch.nn.parameter import Parameter
from torch.autograd import Function
# ********************* range_trackers *********************
class RangeTracker(nn.Module):
def __init__(self, q_le... | [
"torch.nn.ReLU",
"torch.nn.functional.conv1d",
"torch.max",
"torch.sqrt",
"torch.min",
"torch.nn.BatchNorm1d",
"torch.nn.functional.avg_pool1d",
"torch.nn.functional.linear",
"torch.mean",
"torch.nn.init.zeros_",
"torch.zeros_like",
"torch.nn.init.uniform_",
"torch.abs",
"torch.Tensor",
... | [((472, 487), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (485, 487), False, 'import torch\n'), ((2892, 2910), 'torch.round', 'torch.round', (['input'], {}), '(input)\n', (2903, 2910), False, 'import torch\n'), ((3622, 3668), 'torch.clamp', 'torch.clamp', (['input', 'self.min_val', 'self.max_val'], {}), '(input... |
import pandas as pd
def build_columns():
columns = ['pid']
for i in range(1, 501):
columns.append('trackuri_%s' % i)
return columns
def build_output(df_list, id_cloumn, song_column):
output = pd.DataFrame(columns=build_columns())
for df in df_list:
output = output.append(format_... | [
"pandas.concat"
] | [((982, 1008), 'pandas.concat', 'pd.concat', (['[first_row, df]'], {}), '([first_row, df])\n', (991, 1008), True, 'import pandas as pd\n')] |
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 12 01:38:00 2020
@author: 45063883
"""
import networkx as nx
from networkx import karate_club_graph, to_numpy_matrix
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.layers import Dense, Flatten,Embedding,Dropout
from keras.models import Sequent... | [
"NexGCN.ExperimentalGCN",
"networkx.gnm_random_graph",
"NexGCN.feature_kernels"
] | [((793, 821), 'networkx.gnm_random_graph', 'nx.gnm_random_graph', (['(70)', '(140)'], {}), '(70, 140)\n', (812, 821), True, 'import networkx as nx\n'), ((825, 848), 'NexGCN.ExperimentalGCN', 'venom.ExperimentalGCN', ([], {}), '()\n', (846, 848), True, 'import NexGCN as venom\n'), ((856, 879), 'NexGCN.feature_kernels', ... |
#!/usr/bin/env python
from imutils.video import VideoStream
import argparse
import imagezmq
import socket
import time
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--server-ip', required=True,
help='IP address of server to which client will connect')
parser.add_argument('-p', '--pi-... | [
"imutils.video.VideoStream",
"imagezmq.ImageSender",
"argparse.ArgumentParser",
"time.sleep",
"socket.gethostname"
] | [((128, 153), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (151, 153), False, 'import argparse\n'), ((466, 532), 'imagezmq.ImageSender', 'imagezmq.ImageSender', ([], {'connect_to': 'f"""tcp://{args[\'server_ip\']}:5555"""'}), '(connect_to=f"tcp://{args[\'server_ip\']}:5555")\n', (486, 532), F... |