code stringlengths 20 1.04M | apis list | extract_api stringlengths 75 9.94M |
|---|---|---|
import math
def problem_20():
"Find the sum of the digits in the number 100!"
# Calculate 100! and convert to a string
factorial = str(math.factorial(100))
# Calculate the sum of the digits in the string
total = sum(int(digit) for digit in factorial)
return total
if __name__ == "__main__":... | [
"math.factorial"
] | [((149, 168), 'math.factorial', 'math.factorial', (['(100)'], {}), '(100)\n', (163, 168), False, 'import math\n')] |
import collections
import pickle
from typing import Optional
from pfrl.collections.random_access_queue import RandomAccessQueue
from pfrl import replay_buffer
class ReplayBuffer(replay_buffer.AbstractReplayBuffer):
"""Experience Replay Buffer
As described in
https://storage.googleapis.com/deepmind-media... | [
"pfrl.collections.random_access_queue.RandomAccessQueue",
"pickle.load",
"collections.deque",
"pickle.dump"
] | [((810, 844), 'pfrl.collections.random_access_queue.RandomAccessQueue', 'RandomAccessQueue', ([], {'maxlen': 'capacity'}), '(maxlen=capacity)\n', (827, 844), False, 'from pfrl.collections.random_access_queue import RandomAccessQueue\n'), ((2865, 2892), 'pickle.dump', 'pickle.dump', (['self.memory', 'f'], {}), '(self.me... |
"""Test displacement handler classes: Ignore, IgnoreVector, Displace, Perturb, Reporter"""
import numpy as np
from sequence_jacobian.blocks.support.simple_displacement import (
IgnoreInt, IgnoreFloat, IgnoreVector, Displace, AccumulatedDerivative, numeric_primitive
)
# Define useful helper functions for testing
... | [
"sequence_jacobian.blocks.support.simple_displacement.AccumulatedDerivative",
"numpy.log",
"numpy.array",
"sequence_jacobian.blocks.support.simple_displacement.numeric_primitive",
"sequence_jacobian.blocks.support.simple_displacement.IgnoreFloat",
"sequence_jacobian.blocks.support.simple_displacement.Igno... | [((1567, 1579), 'sequence_jacobian.blocks.support.simple_displacement.IgnoreInt', 'IgnoreInt', (['(1)'], {}), '(1)\n', (1576, 1579), False, 'from sequence_jacobian.blocks.support.simple_displacement import IgnoreInt, IgnoreFloat, IgnoreVector, Displace, AccumulatedDerivative, numeric_primitive\n'), ((1599, 1613), 'sequ... |
# -*- coding: utf-8 -*-
import json
class StateMachineField:
Comment = "Comment"
StartAt = "StartAt"
TimeoutSeconds = "TimeoutSeconds"
States = "States"
class StateField:
Type = "Type"
Comment = "Comment"
Next = "Next"
Resource = "Resource"
# Data Input Output
InputPath = "... | [
"json.dumps"
] | [((2136, 2187), 'json.dumps', 'json.dumps', (['state_machine'], {'indent': '(4)', 'sort_keys': '(True)'}), '(state_machine, indent=4, sort_keys=True)\n', (2146, 2187), False, 'import json\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@File : main.py
@Time : 2022-02-01 10:55:43
@Author : <NAME>
@Email : <EMAIL>
@License : Apache License 2.0
"""
import os
import cv2
from core import *
def main():
img_name = 'misery.png'
img = cv2.imread(os.path.join('examples', img_n... | [
"cv2.waitKey",
"cv2.destroyAllWindows",
"cv2.imshow",
"os.path.join"
] | [((352, 374), 'cv2.imshow', 'cv2.imshow', (['"""img"""', 'img'], {}), "('img', img)\n", (362, 374), False, 'import cv2\n'), ((575, 615), 'cv2.imshow', 'cv2.imshow', (['"""img_scaled2x"""', 'img_scaled2x'], {}), "('img_scaled2x', img_scaled2x)\n", (585, 615), False, 'import cv2\n'), ((826, 866), 'cv2.imshow', 'cv2.imsho... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow... | [
"PyQt5.QtWidgets.QLabel",
"PyQt5.QtGui.QIcon",
"PyQt5.QtWidgets.QListWidgetItem",
"PyQt5.QtWidgets.QWidget",
"PyQt5.QtWidgets.QRadioButton",
"PyQt5.QtCore.QRect",
"PyQt5.QtWidgets.QGridLayout",
"PyQt5.QtWidgets.QMainWindow",
"PyQt5.QtWidgets.QPushButton",
"PyQt5.QtWidgets.QMenu",
"PyQt5.QtWidget... | [((9552, 9584), 'PyQt5.QtWidgets.QApplication', 'QtWidgets.QApplication', (['sys.argv'], {}), '(sys.argv)\n', (9574, 9584), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((9602, 9625), 'PyQt5.QtWidgets.QMainWindow', 'QtWidgets.QMainWindow', ([], {}), '()\n', (9623, 9625), False, 'from PyQt5 import QtCore, QtG... |
import json
class ColorPicker:
"""
This class supposed for work with config which contains block's info(color, ids, etc...)
"""
def __init__(self, config_name='config.json'):
self.__config_name = config_name
self.__colors = self.__load_config()
self.EMPTY = -1
def get_config(self):
return self.__load_c... | [
"json.load"
] | [((485, 497), 'json.load', 'json.load', (['f'], {}), '(f)\n', (494, 497), False, 'import json\n')] |
import logging
from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def PerformanceManagerCounterLevelMapping(vim, *args, **kwargs):
'''PerformanceManagerCou... | [
"logging.getLogger"
] | [((198, 225), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (215, 225), False, 'import logging\n')] |
import numpy as np
from scipy.signal import convolve2d
def conv2d(input_feature_map, filters, mode = "full"):
"""
Convolution operation that functions as same as `theano.tensor.nnet.conv.conv2d`
Refer to: [the theano documentation](http://deeplearning.net/software/theano/library/tensor/nnet/conv.html#... | [
"numpy.sum",
"scipy.signal.convolve2d",
"numpy.argmax",
"numpy.zeros",
"numpy.arange",
"numpy.exp",
"numpy.dot"
] | [((722, 814), 'numpy.zeros', 'np.zeros', (['(batch_size, output_feature_n, input_w + filter_w - 1, input_h + filter_h - 1)'], {}), '((batch_size, output_feature_n, input_w + filter_w - 1, input_h +\n filter_h - 1))\n', (730, 814), True, 'import numpy as np\n'), ((1590, 1599), 'numpy.exp', 'np.exp', (['w'], {}), '(w)... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Run the shepherd gym env with dog heuristic model.
"""
# core modules
import os
import gym
import shutil
import argparse
import numpy as np
import matplotlib.pyplot as plt
# ipython debugging
from IPython.terminal.debugger import set_trace as keyboard
# shepherd_gym... | [
"os.mkdir",
"matplotlib.pyplot.show",
"gym.make",
"argparse.ArgumentParser",
"shutil.rmtree",
"os.path.isdir",
"matplotlib.pyplot.legend",
"shepherd_gym.wrappers.SamplerWrapper",
"numpy.zeros",
"matplotlib.pyplot.figure",
"numpy.random.randint",
"numpy.array",
"numpy.arange",
"shepherd_gym... | [((471, 539), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Heuristic model with shepherd"""'}), "(description='Heuristic model with shepherd')\n", (494, 539), False, 'import argparse\n'), ((2818, 2836), 'gym.make', 'gym.make', (['env_name'], {}), '(env_name)\n', (2826, 2836), False, 'i... |
from django.shortcuts import get_object_or_404
from django.views.decorators.http import condition
from rest_framework import generics
from rest_framework.response import Response
from rest_framework.decorators import api_view
from . import models
from . import serializers
from ..cache import etag_profile_updated, l... | [
"django.shortcuts.get_object_or_404",
"rest_framework.decorators.api_view",
"rest_framework.response.Response",
"django.views.decorators.http.condition"
] | [((676, 772), 'django.views.decorators.http.condition', 'condition', ([], {'etag_func': 'etag_profile_updated', 'last_modified_func': 'last_modified_profile_updated'}), '(etag_func=etag_profile_updated, last_modified_func=\n last_modified_profile_updated)\n', (685, 772), False, 'from django.views.decorators.http imp... |
#!/usr/bin/env python
import os
import sys
import numpy as np
if len(sys.argv) < 3:
print('Usage: gen_input.py <sms_grd_file> <nobc>')
sys.exit(0)
sms_grd_file = sys.argv[1]
nobc = int(sys.argv[2])
# read grid and depth from sms .grd file
fl = open(sms_grd_file, 'r')
# read head info
fl.readline()
header = fl.r... | [
"numpy.abs",
"numpy.zeros",
"numpy.sin",
"numpy.fromstring",
"sys.exit"
] | [((478, 493), 'numpy.zeros', 'np.zeros', (['nvert'], {}), '(nvert)\n', (486, 493), True, 'import numpy as np\n'), ((498, 513), 'numpy.zeros', 'np.zeros', (['nvert'], {}), '(nvert)\n', (506, 513), True, 'import numpy as np\n'), ((518, 533), 'numpy.zeros', 'np.zeros', (['nvert'], {}), '(nvert)\n', (526, 533), True, 'impo... |
"""
Scrapper implementation
"""
import datetime
import json
import pathlib
import re
import shutil
from bs4 import BeautifulSoup, Tag
import requests
from constants import CRAWLER_CONFIG_PATH, ASSETS_PATH, HEADERS, DOMAIN
from core_utils.article import Article
from core_utils.pdf_utils import PDFRawFile
class Incor... | [
"json.load",
"re.fullmatch",
"re.match",
"core_utils.pdf_utils.PDFRawFile",
"pathlib.Path",
"datetime.datetime.strptime",
"requests.get",
"bs4.BeautifulSoup",
"shutil.rmtree",
"core_utils.article.Article"
] | [((5017, 5040), 'pathlib.Path', 'pathlib.Path', (['base_path'], {}), '(base_path)\n', (5029, 5040), False, 'import pathlib\n'), ((2094, 2136), 'core_utils.article.Article', 'Article', (['self.article_url', 'self.article_id'], {}), '(self.article_url, self.article_id)\n', (2101, 2136), False, 'from core_utils.article im... |
from __future__ import absolute_import, division, print_function, unicode_literals
import six
from .axislines import Axes, Subplot, AxesZero, SubplotZero, GridHelperRectlinear, \
AxisArtistHelperRectlinear, AxisArtistHelper, GridHelperBase, AxisArtist
from .axis_artist import AxisArtist, GridlinesCollection
fro... | [
"mpl_toolkits.axes_grid1.parasite_axes.parasite_axes_class_factory",
"mpl_toolkits.axes_grid1.parasite_axes.subplot_class_factory",
"mpl_toolkits.axes_grid1.parasite_axes.parasite_axes_auxtrans_class_factory",
"mpl_toolkits.axes_grid1.parasite_axes.host_axes_class_factory"
] | [((636, 669), 'mpl_toolkits.axes_grid1.parasite_axes.parasite_axes_class_factory', 'parasite_axes_class_factory', (['Axes'], {}), '(Axes)\n', (663, 669), False, 'from mpl_toolkits.axes_grid1.parasite_axes import subplot_class_factory, parasite_axes_class_factory, parasite_axes_auxtrans_class_factory, host_axes_class_fa... |
#!/usr/bin/env python
import os
import sys
import platform
import re
import subprocess
import pathlib
import stat
from typing import Tuple
def lief_samples_dir() -> str:
dir = os.getenv("LIEF_SAMPLES_DIR", None)
if dir is None:
print("LIEF_SAMPES_DIR is not set", file=sys.stderr)
sys.exit(1)
... | [
"sys.platform.startswith",
"subprocess.Popen",
"os.stat",
"os.path.isdir",
"subprocess.check_output",
"os.path.exists",
"os.path.isfile",
"platform.machine",
"re.search",
"os.getenv",
"sys.exit"
] | [((181, 216), 'os.getenv', 'os.getenv', (['"""LIEF_SAMPLES_DIR"""', 'None'], {}), "('LIEF_SAMPLES_DIR', None)\n", (190, 216), False, 'import os\n'), ((555, 579), 'os.path.exists', 'os.path.exists', (['fullpath'], {}), '(fullpath)\n', (569, 579), False, 'import os\n'), ((591, 615), 'os.path.isfile', 'os.path.isfile', ([... |
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from .models import BlackHole, FactionPoint, JumpPoint, JumpLine, Planet, Ship
def index(request):
template = loader.get_template('nav/index.html')
Jump_Points = JumpPoint.objects.order_by('-id')
... | [
"django.template.loader.get_template"
] | [((226, 263), 'django.template.loader.get_template', 'loader.get_template', (['"""nav/index.html"""'], {}), "('nav/index.html')\n", (245, 263), False, 'from django.template import loader\n')] |
"""
CORE APP
This module is used to additional functionality provided to the app.
"""
from django.conf import settings
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.decorators import login_required
from django.contrib.auth.views import redirect_to_login
from django.core.exceptions impor... | [
"django.utils.translation.ugettext_lazy",
"django.utils.decorators.method_decorator",
"django.core.paginator.Paginator",
"django.template.RequestContext"
] | [((3986, 4018), 'django.utils.decorators.method_decorator', 'method_decorator', (['login_required'], {}), '(login_required)\n', (4002, 4018), False, 'from django.utils.decorators import method_decorator\n'), ((4525, 4557), 'django.utils.decorators.method_decorator', 'method_decorator', (['login_required'], {}), '(login... |
__source__ = 'https://leetcode.com/problems/factor-combinations/description/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/factor-combinations.py
# Time: O(nlogn)
# Space: O(logn)
#
# Description: Leetcode # 254. Factor Combinations
#
# Numbers can be regarded as product of its factors. For example,
#
# 8... | [
"unittest.main",
"math.sqrt"
] | [((3256, 3271), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3269, 3271), False, 'import unittest\n'), ((2774, 2786), 'math.sqrt', 'math.sqrt', (['n'], {}), '(n)\n', (2783, 2786), False, 'import math\n')] |
"""Utility functions."""
import numpy as np
__all__ = ['spherical_to_cartesian', 'search_around_sky']
def spherical_to_cartesian(ra, dec):
"""Convert spherical coordinates into cartesian coordinates on a unit
sphere.
Parameters
----------
ra, dec : float or numpy array
Spherical coordi... | [
"numpy.array",
"numpy.sqrt",
"numpy.zeros",
"numpy.deg2rad"
] | [((555, 570), 'numpy.deg2rad', 'np.deg2rad', (['dec'], {}), '(dec)\n', (565, 570), True, 'import numpy as np\n'), ((1705, 1716), 'numpy.zeros', 'np.zeros', (['(0)'], {}), '(0)\n', (1713, 1716), True, 'import numpy as np\n'), ((441, 455), 'numpy.deg2rad', 'np.deg2rad', (['ra'], {}), '(ra)\n', (451, 455), True, 'import n... |
# -*- coding: utf-8 -*-
"""
===============================================================================
Custom iterator functions (:mod:`sknano.core._itertools`)
===============================================================================
.. currentmodule:: sknano.core._itertools
"""
from __future__ import abs... | [
"itertools.repeat",
"itertools.filterfalse",
"random.sample",
"itertools.zip_longest",
"random.choice",
"itertools.count",
"itertools.combinations",
"random.randrange",
"itertools.islice",
"itertools.tee",
"collections.deque"
] | [((1300, 1313), 'itertools.tee', 'tee', (['iterable'], {}), '(iterable)\n', (1303, 1313), False, 'from itertools import chain, combinations, count, cycle, filterfalse, islice, repeat, starmap, tee, zip_longest\n'), ((3274, 3287), 'itertools.tee', 'tee', (['iterable'], {}), '(iterable)\n', (3277, 3287), False, 'from ite... |
from django.contrib import admin
from .models import Catagories, Partner, Feedback
# Register your models here.
admin.site.register(Catagories)
admin.site.register(Partner)
admin.site.register(Feedback) | [
"django.contrib.admin.site.register"
] | [((113, 144), 'django.contrib.admin.site.register', 'admin.site.register', (['Catagories'], {}), '(Catagories)\n', (132, 144), False, 'from django.contrib import admin\n'), ((145, 173), 'django.contrib.admin.site.register', 'admin.site.register', (['Partner'], {}), '(Partner)\n', (164, 173), False, 'from django.contrib... |
import dash
import numpy as np
from dash import Input, Output, dcc, html
import plotly.express as px
import dash_bootstrap_components as dbc
app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])
inputs = dbc.Card(
dbc.CardBody(
[
html.P("lambda (must be >= 0): ", style={'display': 'inl... | [
"dash.Output",
"dash.Dash",
"dash.dcc.Input",
"dash.dcc.Graph",
"dash.html.P",
"dash.html.H1",
"dash_bootstrap_components.Col",
"dash.Input",
"dash.dcc.Markdown",
"plotly.express.histogram",
"dash.html.Hr"
] | [((148, 202), 'dash.Dash', 'dash.Dash', ([], {'external_stylesheets': '[dbc.themes.BOOTSTRAP]'}), '(external_stylesheets=[dbc.themes.BOOTSTRAP])\n', (157, 202), False, 'import dash\n'), ((1524, 1576), 'dash.Output', 'Output', (['"""poisson-distribution-x-histogram"""', '"""figure"""'], {}), "('poisson-distribution-x-hi... |
# -*- coding: utf-8 -*-
'''
This module is Alpha
Module for working with Windows PowerShell DSC (Desired State Configuration)
This module applies DSC Configurations in the form of PowerShell scripts or
MOF (Managed Object Format) schema files.
Use the ``psget`` module to manage PowerShell resources.
The idea is to ... | [
"salt.exceptions.CommandExecutionError",
"json.loads",
"salt.exceptions.SaltInvocationError",
"os.path.basename",
"os.path.dirname",
"os.path.exists",
"os.path.normpath",
"os.getenv",
"logging.getLogger"
] | [((663, 690), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (680, 690), False, 'import logging\n'), ((9904, 9925), 'os.path.dirname', 'os.path.dirname', (['path'], {}), '(path)\n', (9919, 9925), False, 'import os\n'), ((11340, 11368), 'salt.exceptions.CommandExecutionError', 'CommandExec... |
#!/usr/bin/env python3.5
import unittest
from neuralmonkey.evaluators.ter import TER
from neuralmonkey.tests.test_bleu import DECODED, REFERENCE
class TestBLEU(unittest.TestCase):
def test_empty_decoded(self):
self.assertEqual(TER([[] for _ in DECODED], REFERENCE), 1.0)
def test_empty_reference(se... | [
"unittest.main",
"neuralmonkey.evaluators.ter.TER"
] | [((876, 891), 'unittest.main', 'unittest.main', ([], {}), '()\n', (889, 891), False, 'import unittest\n'), ((341, 378), 'neuralmonkey.evaluators.ter.TER', 'TER', (['DECODED', '[[] for _ in REFERENCE]'], {}), '(DECODED, [[] for _ in REFERENCE])\n', (344, 378), False, 'from neuralmonkey.evaluators.ter import TER\n'), ((6... |
from django.contrib.syndication.views import Feed
from django.http import Http404
from django.template.defaultfilters import slugify
from django.shortcuts import get_object_or_404
from django.conf import settings
from .models import NewsPosterProfile
from postgresqleu.util.db import exec_to_dict, ensure_conference_ti... | [
"django.template.defaultfilters.slugify",
"postgresqleu.util.db.ensure_conference_timezone",
"django.http.Http404"
] | [((765, 790), 'django.http.Http404', 'Http404', (['"""Feed not found"""'], {}), "('Feed not found')\n", (772, 790), False, 'from django.http import Http404\n'), ((1396, 1428), 'postgresqleu.util.db.ensure_conference_timezone', 'ensure_conference_timezone', (['None'], {}), '(None)\n', (1422, 1428), False, 'from postgres... |
#!/usr/bin/env python
import sys
import numpy as np
import time
import matplotlib.pyplot as plt
from math import sqrt
from optparse import OptionParser
class Atom:
def __init__(self, atom_type, coords, dipole):
self.atom_type = atom_type
self.coords = coords
self.dipole = dipole
def ... | [
"matplotlib.pyplot.subplot",
"numpy.set_printoptions",
"numpy.arctan2",
"optparse.OptionParser",
"math.sqrt",
"matplotlib.pyplot.hist",
"numpy.zeros",
"numpy.cross",
"time.clock",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.array",
"numpy.linalg.norm",
"sys.stdout.flush",
"numpy.dot... | [((3816, 3828), 'time.clock', 'time.clock', ([], {}), '()\n', (3826, 3828), False, 'import time\n'), ((4413, 4438), 'numpy.mean', 'np.mean', (['measures'], {'axis': '(0)'}), '(measures, axis=0)\n', (4420, 4438), True, 'import numpy as np\n'), ((4451, 4463), 'time.clock', 'time.clock', ([], {}), '()\n', (4461, 4463), Fa... |
# coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | [
"sonnet.nets.ConvNet2D",
"tensorflow.compat.v1.concat",
"sonnet.Linear",
"tensorflow.compat.v1.reshape"
] | [((983, 1059), 'sonnet.nets.ConvNet2D', 'snt.nets.ConvNet2D', (['[16, 32, 64, 128]', '[3, 3, 3, 3]', '[2, 2, 2, 2]', "['VALID']"], {}), "([16, 32, 64, 128], [3, 3, 3, 3], [2, 2, 2, 2], ['VALID'])\n", (1001, 1059), True, 'import sonnet as snt\n'), ((1109, 1147), 'sonnet.Linear', 'snt.Linear', ([], {'output_size': '(512)... |
# test lndhub link creation
import asyncio
from aiohttp.client import ClientSession
from pylnbits.config import Config
from pylnbits.lndhub import LndHub
# TODO: make this a proper unit test with pytest
async def main():
c = Config(config_file="config.yml")
url = c.lnbits_url
print(f"url: {url}")
prin... | [
"aiohttp.client.ClientSession",
"pylnbits.lndhub.LndHub",
"pylnbits.config.Config",
"asyncio.get_event_loop"
] | [((630, 654), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (652, 654), False, 'import asyncio\n'), ((231, 263), 'pylnbits.config.Config', 'Config', ([], {'config_file': '"""config.yml"""'}), "(config_file='config.yml')\n", (237, 263), False, 'from pylnbits.config import Config\n'), ((414, 429),... |
#!/usr/bin/env python3
# Day 5: First Unique Character in a String
#
# Given a string, find the first non-repeating character in it and return it's
# index. If it doesn't exist, return -1.
# Note: You may assume the string contain only lowercase letters.
import collections
class Solution:
def firstUniqChar(self,... | [
"collections.Counter"
] | [((500, 522), 'collections.Counter', 'collections.Counter', (['s'], {}), '(s)\n', (519, 522), False, 'import collections\n')] |
from typing import Optional, Dict, Any
from fastapi import APIRouter
from jina.helper import ArgNamespace
from jina.parsers import set_deployment_parser
from daemon.excepts import PartialDaemon400Exception
from daemon.models import DeploymentModel
from daemon.models.partial import PartialStoreItem
from daemon.stores ... | [
"daemon.stores.partial_store.scale",
"jina.parsers.set_deployment_parser",
"daemon.stores.partial_store.rolling_update",
"daemon.stores.partial_store.delete",
"daemon.stores.partial_store.add",
"fastapi.APIRouter"
] | [((360, 412), 'fastapi.APIRouter', 'APIRouter', ([], {'prefix': '"""/deployment"""', 'tags': "['deployment']"}), "(prefix='/deployment', tags=['deployment'])\n", (369, 412), False, 'from fastapi import APIRouter\n'), ((2397, 2411), 'daemon.stores.partial_store.delete', 'store.delete', ([], {}), '()\n', (2409, 2411), Tr... |
import sys
import os
from PyQt4.QtCore import *
from portfolio import *
from stockData import *
from prefs import *
from chartWidget import *
import appGlobal
prefs = Prefs()
app = QApplication(sys.argv)
app.isOSX = True
appGlobal.setApp(app, os.path.dirname(__file__))
p = Portfolio("Scottrade")
stockData = StockD... | [
"os.path.dirname"
] | [((247, 272), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (262, 272), False, 'import os\n')] |
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import NMF, LatentDirichletAllocation
from time import time
import sqlite3
import os
import sys
import random
import gensim.models
from collections import defaultdict
from context import settings
model = gensim.models.Word2Vec.... | [
"sklearn.decomposition.NMF",
"sklearn.feature_extraction.text.TfidfVectorizer",
"time.time",
"collections.defaultdict",
"sqlite3.connect"
] | [((701, 718), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (712, 718), False, 'from collections import defaultdict\n'), ((1146, 1225), 'sklearn.feature_extraction.text.TfidfVectorizer', 'TfidfVectorizer', ([], {'max_df': '(0.95)', 'min_df': '(2)', 'max_features': '(1000)', 'stop_words': '"""eng... |
import logging
import os.path as osp
import tempfile
import mmcv
import numpy as np
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
from mmdet.core import eval_recalls
from mmdet.utils import print_log
from .custom import CustomDataset
from .registry import DATASETS
@DATASETS.register_mo... | [
"tempfile.TemporaryDirectory",
"numpy.zeros",
"pycocotools.coco.COCO",
"numpy.array",
"numpy.arange",
"mmcv.dump",
"pycocotools.cocoeval.COCOeval",
"os.path.join",
"mmdet.utils.print_log"
] | [((1497, 1511), 'pycocotools.coco.COCO', 'COCO', (['ann_file'], {}), '(ann_file)\n', (1501, 1511), False, 'from pycocotools.coco import COCO\n'), ((5605, 5655), 'mmcv.dump', 'mmcv.dump', (['segm_json_results', "result_files['segm']"], {}), "(segm_json_results, result_files['segm'])\n", (5614, 5655), False, 'import mmcv... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 3 09:13:28 2020
@author: antony
"""
import psycopg2
import json
config = json.load(open('edbw/settings.json', 'r'))
connection = psycopg2.connect(user = config['postgresql']['user'],
password = config['postgresql']... | [
"json.dumps",
"psycopg2.connect"
] | [((205, 418), 'psycopg2.connect', 'psycopg2.connect', ([], {'user': "config['postgresql']['user']", 'password': "config['postgresql']['password']", 'host': "config['postgresql']['host']", 'port': "config['postgresql']['port']", 'database': "config['postgresql']['name']"}), "(user=config['postgresql']['user'], password=... |
import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
X, y = datasets.make_regression(n_samples=100, n_features=1, noise=20, random_state=4)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1234)
# fig ... | [
"matplotlib.pyplot.show",
"matplotlib.pyplot.get_cmap",
"matplotlib.pyplot.plot",
"sklearn.model_selection.train_test_split",
"sklearn.datasets.make_regression",
"Linear_Regression.LinearRegression",
"matplotlib.pyplot.figure",
"numpy.mean"
] | [((141, 220), 'sklearn.datasets.make_regression', 'datasets.make_regression', ([], {'n_samples': '(100)', 'n_features': '(1)', 'noise': '(20)', 'random_state': '(4)'}), '(n_samples=100, n_features=1, noise=20, random_state=4)\n', (165, 220), False, 'from sklearn import datasets\n'), ((256, 312), 'sklearn.model_selectio... |
from os import path
import unittest
from hdlConvertor import HdlConvertor
from hdlConvertor.language import Language
SV = Language.SYSTEM_VERILOG_2012
SRC_DIR = path.join(path.dirname(__file__), 'sv_pp', 'src')
EXPECTED_DIR = path.join(path.dirname(__file__), 'sv_pp', 'expected')
class VerilogPreprocIncludeTC(unitt... | [
"unittest.TextTestRunner",
"unittest.TestSuite",
"os.path.dirname",
"unittest.makeSuite",
"hdlConvertor.HdlConvertor",
"os.path.join"
] | [((173, 195), 'os.path.dirname', 'path.dirname', (['__file__'], {}), '(__file__)\n', (185, 195), False, 'from os import path\n'), ((238, 260), 'os.path.dirname', 'path.dirname', (['__file__'], {}), '(__file__)\n', (250, 260), False, 'from os import path\n'), ((2193, 2213), 'unittest.TestSuite', 'unittest.TestSuite', ([... |
from abc import ABCMeta
from typing import Mapping
import numpy as np
from skimage import img_as_float32
from slicedimage import ImageFormat
from starfish.core.types import Axes
from .all_purpose import LocationAwareFetchedTile
X_COORDS = 0.01, 0.1
Y_COORDS = 0.001, 0.01
Z_COORDS = 0.0001, 0.001
def unique_data(
... | [
"numpy.empty",
"skimage.img_as_float32",
"numpy.linspace"
] | [((602, 654), 'numpy.empty', 'np.empty', (['(tile_height, tile_width)'], {'dtype': 'np.uint32'}), '((tile_height, tile_width), dtype=np.uint32)\n', (610, 654), True, 'import numpy as np\n'), ((1061, 1083), 'skimage.img_as_float32', 'img_as_float32', (['result'], {}), '(result)\n', (1075, 1083), False, 'from skimage imp... |
# Copyright 2011 Omniscale GmbH & Co. KG
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... | [
"marshal.dumps",
"imposm.parser.xml.util.log_file_on_exception",
"imposm.parser.xml.util.iterparse"
] | [((2057, 2083), 'imposm.parser.xml.util.log_file_on_exception', 'log_file_on_exception', (['xml'], {}), '(xml)\n', (2078, 2083), False, 'from imposm.parser.xml.util import log_file_on_exception, iterparse\n'), ((2278, 2292), 'imposm.parser.xml.util.iterparse', 'iterparse', (['xml'], {}), '(xml)\n', (2287, 2292), False,... |
from flask import Flask,request
import hashlib
import subprocess
import os
app = Flask(__name__)
@app.route("/")
def index_view():
sandbox_dir = int(hashlib.sha256(request.remote_addr.encode('utf-8')).hexdigest(), 16) % 10**8
if not os.path.isdir(f"sandbox/{sandbox_dir}"):
os.system(f"mkdir \"sandbox/... | [
"flask.request.remote_addr.encode",
"flask.request.args.get",
"os.path.isdir",
"subprocess.check_output",
"flask.Flask",
"os.system"
] | [((82, 97), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (87, 97), False, 'from flask import Flask, request\n'), ((357, 380), 'flask.request.args.get', 'request.args.get', (['"""cmd"""'], {}), "('cmd')\n", (373, 380), False, 'from flask import Flask, request\n'), ((243, 282), 'os.path.isdir', 'os.path.is... |
# @ GenYamlCfg.py
#
# Copyright (c) 2020 - 2021, Intel Corporation. All rights reserved.<BR>
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
#
import os
import sys
import re
import marshal
import string
import operator as op
import ast
import tkinter.messagebox as messagebox
import tkinter
from date... | [
"tkinter.Text",
"CommonUtility.get_bits_from_bytes",
"tkinter.Frame",
"CommonUtility.set_bits_to_bytes",
"os.path.join",
"tkinter.Button",
"os.path.dirname",
"os.path.exists",
"marshal.dump",
"ast.parse",
"re.sub",
"tkinter.Tk",
"re.split",
"os.path.basename",
"os.path.realpath",
"re.m... | [((2887, 2929), 're.match', 're.match', (['"""\\\\{\\\\s*FILE:(.+)\\\\}"""', 'value_str'], {}), "('\\\\{\\\\s*FILE:(.+)\\\\}', value_str)\n", (2895, 2929), False, 'import re\n'), ((2580, 2600), 'os.path.exists', 'os.path.exists', (['file'], {}), '(file)\n', (2594, 2600), False, 'import os\n'), ((2623, 2645), 'os.path.b... |
from unittest import TestCase
from cartodb_services.refactor.storage.redis_connection_config import *
from cartodb_services.refactor.storage.mem_config import InMemoryConfigStorage
from cartodb_services.refactor.config.exceptions import ConfigException
class TestRedisConnectionConfig(TestCase):
def test_config_ho... | [
"cartodb_services.refactor.storage.mem_config.InMemoryConfigStorage"
] | [((808, 831), 'cartodb_services.refactor.storage.mem_config.InMemoryConfigStorage', 'InMemoryConfigStorage', ([], {}), '()\n', (829, 831), False, 'from cartodb_services.refactor.storage.mem_config import InMemoryConfigStorage\n'), ((1092, 1115), 'cartodb_services.refactor.storage.mem_config.InMemoryConfigStorage', 'InM... |
from django.contrib import admin
from hackdayproject.repo.models \
import Repository, Commit, Organization
admin.site.register(Repository)
admin.site.register(Commit)
admin.site.register(Organization)
| [
"django.contrib.admin.site.register"
] | [((112, 143), 'django.contrib.admin.site.register', 'admin.site.register', (['Repository'], {}), '(Repository)\n', (131, 143), False, 'from django.contrib import admin\n'), ((144, 171), 'django.contrib.admin.site.register', 'admin.site.register', (['Commit'], {}), '(Commit)\n', (163, 171), False, 'from django.contrib i... |
##################
## dependencies ##
##################
# pip install requests
# pip install playsound
##################
import requests
import time
from datetime import datetime
import urllib3
from playsound import playsound
urllib3.disable_warnings()
wavFile_status200 = "servers back online speech.wav"
wavFile_st... | [
"playsound.playsound",
"time.sleep",
"requests.get",
"datetime.datetime.now",
"urllib3.disable_warnings"
] | [((230, 256), 'urllib3.disable_warnings', 'urllib3.disable_warnings', ([], {}), '()\n', (254, 256), False, 'import urllib3\n'), ((1451, 1465), 'time.sleep', 'time.sleep', (['(10)'], {}), '(10)\n', (1461, 1465), False, 'import time\n'), ((475, 489), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (487, 489), ... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 5 11:21:15 2019
@author: <NAME>
"""
import csv
# from datetime import date
#import numpy as np
#from yellowbrick.text import FreqDistVisualizer
#from yellowbrick.text import TSNEVisualizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature... | [
"nltk.tokenize.RegexpTokenizer",
"sklearn.feature_extraction.text.CountVectorizer",
"csv.reader",
"sklearn.feature_extraction.text.TfidfVectorizer",
"sklearn.decomposition.LatentDirichletAllocation",
"nltk.corpus.stopwords.words",
"nltk.FreqDist"
] | [((2646, 2669), 'nltk.tokenize.RegexpTokenizer', 'RegexpTokenizer', (['"""\\\\w+"""'], {}), "('\\\\w+')\n", (2661, 2669), False, 'from nltk.tokenize import RegexpTokenizer\n'), ((3429, 3463), 'nltk.FreqDist', 'nltk.FreqDist', (['self.stopped_corpus'], {}), '(self.stopped_corpus)\n', (3442, 3463), False, 'import nltk\n'... |
# _________________________________________________________________________
#
# PyUtilib: A Python utility library.
# Copyright (c) 2008 Sandia Corporation.
# This software is distributed under the BSD License.
# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
# the U.S. Government retains ... | [
"sys.path.append",
"os.path.expanduser",
"os.path.abspath",
"sys.path.remove",
"os.path.basename",
"os.getcwd",
"imp.find_module",
"os.path.dirname",
"os.path.exists",
"sys.path.insert",
"imp.load_source",
"sys.stdout.flush",
"sys.exc_info",
"traceback.extract_tb",
"sys.stderr.flush",
... | [((1980, 2005), 'os.path.dirname', 'os.path.dirname', (['filename'], {}), '(filename)\n', (1995, 2005), False, 'import os\n'), ((2164, 2190), 'os.path.basename', 'os.path.basename', (['filename'], {}), '(filename)\n', (2180, 2190), False, 'import os\n'), ((7132, 7150), 'sys.stderr.flush', 'sys.stderr.flush', ([], {}), ... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from random import randint
import tensorflow as tf
from tensor2tensor.data_generators import generator_utils
from tensor2tensor.data_generators import problem
from tensor2tensor.data_generators impo... | [
"os.mkdir",
"tensorflow.gfile.Exists",
"tensorflow.logging.info",
"tensor2tensor.data_generators.generator_utils.shuffle_dataset",
"os.path.exists",
"tensorflow.concat",
"tensor2tensor.utils.registry.default_name",
"tensor2tensor.data_generators.text_problems.text2text_generate_encoded",
"tensor2ten... | [((1488, 1521), 'os.path.join', 'os.path.join', (['data_dir', 'self.name'], {}), '(data_dir, self.name)\n', (1500, 1521), False, 'import os\n'), ((3106, 3148), 'tensor2tensor.data_generators.generator_utils.shuffle_dataset', 'generator_utils.shuffle_dataset', (['all_paths'], {}), '(all_paths)\n', (3137, 3148), False, '... |
import cv2
import random
import numpy as np
from random import shuffle
import bc_const
class BcProcesssImage():
def __init__(self):
self.counter=0
total = getattr(self, "total", 0)
if total ==0 :
self.total = 0
# print("BcProcesssImage " + total)
def process_img(s... | [
"random.randint",
"cv2.cvtColor",
"cv2.imread",
"cv2.split",
"cv2.flip",
"cv2.merge"
] | [((1815, 1830), 'cv2.imread', 'cv2.imread', (['url'], {}), '(url)\n', (1825, 1830), False, 'import cv2\n'), ((1847, 1861), 'cv2.split', 'cv2.split', (['img'], {}), '(img)\n', (1856, 1861), False, 'import cv2\n'), ((1876, 1896), 'cv2.merge', 'cv2.merge', (['[r, g, b]'], {}), '([r, g, b])\n', (1885, 1896), False, 'import... |
# coding=utf-8
# Copyright 2018 The Tensor2Tensor Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | [
"uuid.uuid4",
"inspect.stack",
"logging.FileHandler",
"logging.StreamHandler",
"json.dumps",
"time.time",
"re.sub",
"os.getenv",
"logging.getLogger",
"re.compile"
] | [((1810, 1836), 're.compile', 're.compile', (['"""[a-zA-Z0-9]+"""'], {}), "('[a-zA-Z0-9]+')\n", (1820, 1836), False, 'import re\n'), ((1849, 1877), 'os.getenv', 'os.getenv', (['"""COMPLIANCE_FILE"""'], {}), "('COMPLIANCE_FILE')\n", (1858, 1877), False, 'import os\n'), ((1928, 1966), 'logging.getLogger', 'logging.getLog... |
#!/usr/bin/env python3
import sys
import struct
import numpy as np
import os
from pathlib import Path
def progressbar(name, value, endvalue, bar_length=50):
percent = float(value) / endvalue
arrow = '-' * int(round(percent * bar_length) - 1) + '|'
spaces = ' ' * (bar_length - len(arrow))
sys.stdout.write("\r... | [
"sys.stdout.write",
"os.walk",
"os.path.exists",
"struct.unpack",
"struct.pack",
"pathlib.Path",
"sys.stdout.flush",
"os.path.join"
] | [((300, 322), 'sys.stdout.write', 'sys.stdout.write', (["'\\r'"], {}), "('\\r')\n", (316, 322), False, 'import sys\n'), ((325, 351), 'sys.stdout.write', 'sys.stdout.write', (["(' ' * 80)"], {}), "(' ' * 80)\n", (341, 351), False, 'import sys\n'), ((481, 499), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (4... |
from rlkit.envs.gridcraft import REW_ARENA_64
from rlkit.envs.gridcraft.grid_env import GridEnv
from rlkit.envs.gridcraft.grid_spec import *
from rlkit.envs.gridcraft.mazes import MAZE_ANY_START1
import gym.spaces.prng as prng
import numpy as np
if __name__ == "__main__":
prng.seed(2)
maze_spec = \
sp... | [
"gym.spaces.prng.seed",
"numpy.array",
"rlkit.envs.gridcraft.grid_env.GridEnv"
] | [((278, 290), 'gym.spaces.prng.seed', 'prng.seed', (['(2)'], {}), '(2)\n', (287, 290), True, 'import gym.spaces.prng as prng\n'), ((710, 779), 'rlkit.envs.gridcraft.grid_env.GridEnv', 'GridEnv', (['maze_spec'], {'one_hot': '(True)', 'add_eyes': '(True)', 'coordinate_wise': '(True)'}), '(maze_spec, one_hot=True, add_eye... |
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2010, 2013, 2degrees Limited.
# All Rights Reserved.
#
# This file is part of django-pastedeploy-settings
# <https://github.com/2degrees/django-pastedeploy-settings>, which is subject
# to the provis... | [
"zc.buildout.UserError"
] | [((1148, 1247), 'zc.buildout.UserError', 'UserError', (['("Part [%s] must define the PasteDeploy config URI in \'paste_config_uri\'" %\n name)'], {}), '(\n "Part [%s] must define the PasteDeploy config URI in \'paste_config_uri\'" %\n name)\n', (1157, 1247), False, 'from zc.buildout import UserError\n')] |
from address.models import Address, Locality, State
from rest_framework import serializers
from attendees.whereabouts.serializers import AddressSerializer
from attendees.whereabouts.models import Place
class PlaceSerializer(serializers.ModelSerializer):
"""
Generic relation: https://www.django-rest-framework... | [
"rest_framework.serializers.CharField",
"attendees.whereabouts.models.Place.objects.update_or_create",
"address.models.Address.objects.update_or_create",
"address.models.Locality.objects.update_or_create",
"attendees.whereabouts.serializers.AddressSerializer"
] | [((390, 427), 'rest_framework.serializers.CharField', 'serializers.CharField', ([], {'read_only': '(True)'}), '(read_only=True)\n', (411, 427), False, 'from rest_framework import serializers\n'), ((442, 475), 'attendees.whereabouts.serializers.AddressSerializer', 'AddressSerializer', ([], {'required': '(False)'}), '(re... |
from distutils.core import setup
setup(
name = 'readinglistlib',
version = '0.1',
description = 'Python module to read contents of Safari Reading List.',
author = '<NAME>',
author_email = '<EMAIL>',
url = 'https://github.com/anoved/ReadingListReader',
license = 'MIT License',
platforms = ['darwin'],
py_module... | [
"distutils.core.setup"
] | [((34, 334), 'distutils.core.setup', 'setup', ([], {'name': '"""readinglistlib"""', 'version': '"""0.1"""', 'description': '"""Python module to read contents of Safari Reading List."""', 'author': '"""<NAME>"""', 'author_email': '"""<EMAIL>"""', 'url': '"""https://github.com/anoved/ReadingListReader"""', 'license': '""... |
# rballBestOfN.py
# A program that calculates who will win best of n racquetball matches.
"""Revise the racquetball simulation so that it computes the results for best
of n game matches. First service alternates, so player A serves first in the
odd games of the match, and player B serves first in the even games."""
... | [
"random.random"
] | [((3281, 3289), 'random.random', 'random', ([], {}), '()\n', (3287, 3289), False, 'from random import random\n'), ((3432, 3440), 'random.random', 'random', ([], {}), '()\n', (3438, 3440), False, 'from random import random\n'), ((3672, 3680), 'random.random', 'random', ([], {}), '()\n', (3678, 3680), False, 'from random... |
# Generated by Django 3.2.5 on 2021-07-26 19:52
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("shop", "0064_add_product_comment_and_cost"),
("tickets", "0016_populate_opr"),
]
operations = [
mig... | [
"django.db.models.ForeignKey"
] | [((419, 546), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.PROTECT', 'related_name': '"""shoptickets"""', 'to': '"""shop.orderproductrelation"""'}), "(on_delete=django.db.models.deletion.PROTECT, related_name\n ='shoptickets', to='shop.orderproductrelation')\n", (... |
import torch
import torch.optim as optim
import numpy as np
def to_numpy(v):
if torch.is_tensor(v):
return v.cpu().numpy()
return v
def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
class Rescaler:
def __init__(self, data):
channels =... | [
"torch.is_tensor",
"torch.optim.lr_scheduler.StepLR"
] | [((86, 104), 'torch.is_tensor', 'torch.is_tensor', (['v'], {}), '(v)\n', (101, 104), False, 'import torch\n'), ((1019, 1089), 'torch.optim.lr_scheduler.StepLR', 'optim.lr_scheduler.StepLR', (['optimizer'], {'step_size': 'step_size', 'gamma': 'gamma'}), '(optimizer, step_size=step_size, gamma=gamma)\n', (1044, 1089), Tr... |
# coding: utf-8
#
# Copyright 2014 The Oppia Authors. 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 requi... | [
"core.platform.models.Registry.import_models",
"utils.get_random_int",
"google.appengine.ext.ndb.TextProperty",
"utils.get_current_time_in_millisecs",
"google.appengine.ext.ndb.IntegerProperty",
"google.appengine.ext.ndb.StringProperty"
] | [((751, 807), 'core.platform.models.Registry.import_models', 'models.Registry.import_models', (['[models.NAMES.base_model]'], {}), '([models.NAMES.base_model])\n', (780, 807), False, 'from core.platform import models\n'), ((1485, 1532), 'google.appengine.ext.ndb.StringProperty', 'ndb.StringProperty', ([], {'required': ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 4 12:11:23 2020
@author: ali
"""
from kafka import KafkaProducer
import json
def publish_message(producer_instance, topic_name, key, value):
try:
key_bytes = bytes(key, encoding='utf-8')
value_bytes = bytes(value, encoding='u... | [
"kafka.KafkaProducer"
] | [((866, 951), 'kafka.KafkaProducer', 'KafkaProducer', ([], {'bootstrap_servers': "['localhost:' + kafkaPort]", 'api_version': '(0, 10)'}), "(bootstrap_servers=['localhost:' + kafkaPort], api_version=(0, 10)\n )\n", (879, 951), False, 'from kafka import KafkaProducer\n')] |
# vim: set fileencoding=utf-8 :
from __future__ import absolute_import, print_function, unicode_literals
import argparse
import collections
from twisted.internet import defer
from twisted.internet import task
import arrow
import logbook
import six
import yaml
import stethoscope.api.factory
import stethoscope.plugin... | [
"twisted.internet.task.Cooperator",
"logbook.Logger",
"six.moves.range",
"argparse.ArgumentParser",
"twisted.internet.defer.gatherResults",
"twisted.internet.task.react",
"yaml.safe_dump",
"argparse.FileType",
"logbook.more.ColorizedStderrHandler",
"logbook.NullHandler",
"collections.defaultdict... | [((339, 363), 'logbook.Logger', 'logbook.Logger', (['__name__'], {}), '(__name__)\n', (353, 363), False, 'import logbook\n'), ((1527, 1571), 'collections.defaultdict', 'collections.defaultdict', (['collections.Counter'], {}), '(collections.Counter)\n', (1550, 1571), False, 'import collections\n'), ((1595, 1625), 'six.i... |
from django import template
from django.utils.html import format_html
from django.utils.safestring import mark_safe
from ..fullcalendar import get_url
register = template.Library()
@register.simple_tag
def calendar(calendar_id: str = 'calendar'):
return format_html("<div id='{}'></div>", calendar_id)
@register... | [
"django.template.Library",
"django.utils.safestring.mark_safe",
"django.utils.html.format_html"
] | [((163, 181), 'django.template.Library', 'template.Library', ([], {}), '()\n', (179, 181), False, 'from django import template\n'), ((261, 308), 'django.utils.html.format_html', 'format_html', (['"""<div id=\'{}\'></div>"""', 'calendar_id'], {}), '("<div id=\'{}\'></div>", calendar_id)\n', (272, 308), False, 'from djan... |
from config import *
import pandas as pd
import numpy as np
import networkx as nx
import glob, os
import bct
from sklearn import preprocessing
def normalize(df):
'''
normalize dataframe columns by mean
'''
min_max_scaler = preprocessing.MinMaxScaler()
x = df.valu... | [
"numpy.load",
"networkx.nodes",
"networkx.transitivity",
"pandas.read_csv",
"sklearn.preprocessing.MinMaxScaler",
"networkx.eccentricity",
"networkx.current_flow_closeness_centrality",
"networkx.closeness_centrality",
"networkx.connected_components",
"glob.glob",
"networkx.read_gexf",
"network... | [((258, 286), 'sklearn.preprocessing.MinMaxScaler', 'preprocessing.MinMaxScaler', ([], {}), '()\n', (284, 286), False, 'from sklearn import preprocessing\n'), ((430, 452), 'pandas.DataFrame', 'pd.DataFrame', (['x_scaled'], {}), '(x_scaled)\n', (442, 452), True, 'import pandas as pd\n'), ((692, 710), 'bct.degrees_und', ... |
#!venv/bin/python
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
from Graph import Graph
from Movie import Movie
from Actor import Actor
import json
from analysis import mainprocess
#age vs income plot
graph = mainprocess()
graph.setconnect()
x = []
y = []
for i in range(len(graph... | [
"numpy.corrcoef",
"analysis.mainprocess",
"matplotlib.pyplot.show",
"matplotlib.pyplot.scatter"
] | [((247, 260), 'analysis.mainprocess', 'mainprocess', ([], {}), '()\n', (258, 260), False, 'from analysis import mainprocess\n'), ((513, 530), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'y'], {}), '(x, y)\n', (524, 530), True, 'import matplotlib.pyplot as plt\n'), ((531, 541), 'matplotlib.pyplot.show', 'plt.show... |
# !/usr/bin/python
try:
import sys, os, logging
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) + "\\.site_packages\\riverpy\\")
import cDefinitions as cDef
import config
import fGlobal as fGl
except:
print("ExceptionError: Could not find own packages (./si... | [
"arcpy.ListRasters",
"arcpy.CheckOutExtension",
"arcpy.ListFeatureClasses",
"arcpy.PolygonToRaster_conversion",
"fGlobal.del_ovr_files",
"arcpy.Delete_management",
"fGlobal.write_dict2xlsx",
"os.path.dirname",
"arcpy.Exists",
"fGlobal.read_txt",
"arcpy.Raster",
"arcpy.CreateRasterDataset_manag... | [((899, 927), 'logging.getLogger', 'logging.getLogger', (['"""logfile"""'], {}), "('logfile')\n", (916, 927), False, 'import sys, os, logging\n'), ((1018, 1048), 'cDefinitions.FeatureDefinitions', 'cDef.FeatureDefinitions', (['(False)'], {}), '(False)\n', (1041, 1048), True, 'import cDefinitions as cDef\n'), ((1281, 13... |
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
class Mjrecomendationform(FlaskForm):
getrecomendations = StringField("Type how you're feeling, and we'll recomend some strains")
submit = SubmitField('Lets Toke!') | [
"wtforms.SubmitField",
"wtforms.StringField"
] | [((140, 211), 'wtforms.StringField', 'StringField', (['"""Type how you\'re feeling, and we\'ll recomend some strains"""'], {}), '("Type how you\'re feeling, and we\'ll recomend some strains")\n', (151, 211), False, 'from wtforms import StringField, SubmitField\n'), ((225, 250), 'wtforms.SubmitField', 'SubmitField', (['... |
from typing import Callable, List
from time import perf_counter, sleep
from matplotlib import pyplot as plt
import logging
logger = logging.getLogger(__name__)
class BenchmarkResults:
def __init__(
self,
func: Callable,
name_of_argument_to_modify: str,
sizes_checked: List[int],
... | [
"logging.StreamHandler",
"time.perf_counter",
"itertools.count",
"time.sleep",
"logging.getLogger"
] | [((133, 160), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (150, 160), False, 'import logging\n'), ((2362, 2376), 'time.perf_counter', 'perf_counter', ([], {}), '()\n', (2374, 2376), False, 'from time import perf_counter, sleep\n'), ((2890, 2913), 'logging.StreamHandler', 'logging.Strea... |
#!/usr/bin/python
#
# Copyright 2002-2019 Barcelona Supercomputing Center (www.bsc.es)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
... | [
"os.path.abspath",
"os.makedirs",
"os.system",
"socket.gethostbyaddr",
"shutil.rmtree",
"os.path.join"
] | [((1100, 1145), 'os.path.join', 'os.path.join', (['SANDBOX_PATH', 'host', "('%d' % port)"], {}), "(SANDBOX_PATH, host, '%d' % port)\n", (1112, 1145), False, 'import os\n'), ((1205, 1231), 'os.makedirs', 'os.makedirs', (['instance_path'], {}), '(instance_path)\n', (1216, 1231), False, 'import os\n'), ((1510, 1532), 'os.... |
import numpy as np
def accuracy(prediction, target):
"""
N-dimensional accuracy.
Args:
prediction:
target:
"""
correct = (prediction == target).sum().item()
total = np.prod(target.shape)
return correct / total
def categorical_accuracy(output, target):
prediction = output.... | [
"numpy.prod"
] | [((203, 224), 'numpy.prod', 'np.prod', (['target.shape'], {}), '(target.shape)\n', (210, 224), True, 'import numpy as np\n')] |
" Imports XML files into Spells DB "
import os
import xml.etree.ElementTree as ET
from collections import deque, defaultdict
def import_spells(dir_name):
"""Import all spells from Utils/Data/Spells/*
To import:
_name=None,
_level=None,
_school=None,
_time=None,
_range=... | [
"collections.defaultdict",
"os.path.join",
"os.listdir",
"collections.deque"
] | [((485, 492), 'collections.deque', 'deque', ([], {}), '()\n', (490, 492), False, 'from collections import deque, defaultdict\n'), ((515, 535), 'os.listdir', 'os.listdir', (['dir_name'], {}), '(dir_name)\n', (525, 535), False, 'import os\n'), ((1154, 1161), 'collections.deque', 'deque', ([], {}), '()\n', (1159, 1161), F... |
import requests
import uuid
import json
from config import config
def validate_captcha(response):
req = requests.post('https://www.google.com/recaptcha/api/siteverify',
data={
'secret': config['recaptcha-secretkey'],
'response': resp... | [
"requests.post",
"uuid.UUID",
"json.loads"
] | [((111, 250), 'requests.post', 'requests.post', (['"""https://www.google.com/recaptcha/api/siteverify"""'], {'data': "{'secret': config['recaptcha-secretkey'], 'response': response}"}), "('https://www.google.com/recaptcha/api/siteverify', data={\n 'secret': config['recaptcha-secretkey'], 'response': response})\n", (... |
import logging
import numpy as np
from numpy import array
from pprint import pprint
import esutil as eu
import ngmix
from ngmix.gexceptions import GMixRangeError
from ngmix.observation import Observation
from ngmix.gexceptions import GMixMaxIterEM
from ngmix.gmix import GMixModel
from ngmix.gexceptions import BootPSFF... | [
"images.multiview",
"ngmix.bootstrap.MaxMetacalBootstrapper",
"ngmix.em.prep_image",
"mof.MOF",
"mof.priors.PriorBDFSepMulti",
"ngmix.priors.LogNormal",
"numpy.rot90",
"ngmix.guessers.PriorGuesser",
"esutil.numpy_util.combine_arrlist",
"ngmix.bootstrap.PSFRunnerCoellip",
"ngmix.bootstrap.Bootstr... | [((415, 442), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (432, 442), False, 'import logging\n'), ((16333, 16372), 'esutil.numpy_util.combine_arrlist', 'eu.numpy_util.combine_arrlist', (['datalist'], {}), '(datalist)\n', (16362, 16372), True, 'import esutil as eu\n'), ((18019, 18094), ... |
from typing import TypeVar, Any
import PIL.Image
import torch
from torchvision.prototype import features
from torchvision.prototype.transforms import kernels as K
from torchvision.transforms import functional as _F
from ._utils import dispatch
T = TypeVar("T", bound=features._Feature)
@dispatch(
{
torc... | [
"typing.TypeVar"
] | [((251, 288), 'typing.TypeVar', 'TypeVar', (['"""T"""'], {'bound': 'features._Feature'}), "('T', bound=features._Feature)\n", (258, 288), False, 'from typing import TypeVar, Any\n')] |
"""
Usage: pylinkedin -u url
Options:
--url : Url of the profile you want to scrape
--user : username portion of the url (linkedin.com/in/USER)
-a --attribute : Display only a specific attribute, display everything by default
-i --input_file : Raw path to html of the profile you want to scrape
-o --output_fil... | [
"json.dump",
"click.option",
"click.ClickException",
"click.Choice",
"click.command",
"pprint.pprint",
"click.Path"
] | [((846, 861), 'click.command', 'click.command', ([], {}), '()\n', (859, 861), False, 'import click\n'), ((863, 940), 'click.option', 'click.option', (['"""--url"""'], {'type': 'str', 'help': '"""Url of the profile you want to scrape"""'}), "('--url', type=str, help='Url of the profile you want to scrape')\n", (875, 940... |
import sys
import os
import numpy
import pandas
import csv
historyFile="taskHistory.csv" # name of the csv file storing TaskHistory
class History:
def reader(self,file_r,selection_list): # to read history for csv,xlsx files only
# selection list is the list that contains the paramet... | [
"pandas.read_csv",
"csv.writer"
] | [((402, 425), 'pandas.read_csv', 'pandas.read_csv', (['file_r'], {}), '(file_r)\n', (417, 425), False, 'import pandas\n'), ((778, 793), 'csv.writer', 'csv.writer', (['var'], {}), '(var)\n', (788, 793), False, 'import csv\n')] |
from functools import wraps
from logger import logger
from inspect import isclass
def exception_handler(raises=None):
"""
Purpose:
Decorator to handle exceptions in wrapped functions.
Optional kwargs:
raises : Exception-like class : Class to raise if error occurs. Default=None.
Raises:
... | [
"inspect.isclass",
"logger.logger.error"
] | [((693, 708), 'inspect.isclass', 'isclass', (['raises'], {}), '(raises)\n', (700, 708), False, 'from inspect import isclass\n'), ((863, 923), 'logger.logger.error', 'logger.error', (['f"""Unexpected error caught: {e}. Continuing..."""'], {}), "(f'Unexpected error caught: {e}. Continuing...')\n", (875, 923), False, 'fro... |
from rest_framework.viewsets import ModelViewSet
from rest_framework import permissions
from equipamentos.models import Equipamento
from equipamentos.serializers import EquipamentoSerializer
from categorias.models import Categoria
from core.utils import iso_to_date
class EquipamentoViewSet(ModelViewSet):
"""View... | [
"core.utils.iso_to_date",
"equipamentos.models.Equipamento.objects.all",
"categorias.models.Categoria.objects.filter"
] | [((364, 389), 'equipamentos.models.Equipamento.objects.all', 'Equipamento.objects.all', ([], {}), '()\n', (387, 389), False, 'from equipamentos.models import Equipamento\n'), ((1867, 1913), 'categorias.models.Categoria.objects.filter', 'Categoria.objects.filter', ([], {'id__in': 'categoria_ids'}), '(id__in=categoria_id... |
from Tkinter import Tk, Label, Frame, BOTH
from tkFont import Font
from game2048 import Game2048, UP, DOWN, LEFT, RIGHT, ndenumerate, copy, isnan
key_map = {'Up': UP, 'Down': DOWN, 'Left': LEFT, 'Right': RIGHT}
color_map = {2: ('#776e65', '#eee4da'), 4: ('#776e65', '#ede0c8'), 8: ('#f9f6f2', '#f2b179'), 16: ('#f9f6f2'... | [
"Tkinter.Tk",
"Tkinter.Frame",
"game2048.ndenumerate",
"game2048.Game2048",
"tkFont.Font",
"game2048.isnan"
] | [((2194, 2211), 'game2048.ndenumerate', 'ndenumerate', (['grid'], {}), '(grid)\n', (2205, 2211), False, 'from game2048 import Game2048, UP, DOWN, LEFT, RIGHT, ndenumerate, copy, isnan\n'), ((1961, 1971), 'game2048.Game2048', 'Game2048', ([], {}), '()\n', (1969, 1971), False, 'from game2048 import Game2048, UP, DOWN, LE... |
#!/usr/bin/env python3
#
# Tool to crop/scale/pan through a sequence of images
import argparse
import json
from PIL import Image
from collections import namedtuple
from utils import cropargv, saveimage, formatoutname, computecrop, argtuple
# Pan specification:
#
# JSON structure
# {"image0": filename,
# "crop0":... | [
"utils.formatoutname",
"utils.argtuple",
"argparse.ArgumentParser",
"json.loads",
"utils.cropargv",
"PIL.Image.open",
"utils.saveimage",
"collections.namedtuple"
] | [((2553, 2639), 'collections.namedtuple', 'namedtuple', (['"""PanSpec"""', "('image0', 'crop0', 'image1', 'crop1', 'n')"], {'defaults': '(1,)'}), "('PanSpec', ('image0', 'crop0', 'image1', 'crop1', 'n'), defaults\n =(1,))\n", (2563, 2639), False, 'from collections import namedtuple\n'), ((6740, 6753), 'json.loads', ... |
# Copyright 2017 SAS Project Authors. 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 requ... | [
"math.abs",
"math.sqrt",
"math.radians",
"math.tan",
"math.sin",
"math.cos",
"math.degrees"
] | [((1872, 1893), 'math.radians', 'math.radians', (['fss_lat'], {}), '(fss_lat)\n', (1884, 1893), False, 'import math\n'), ((1906, 1927), 'math.radians', 'math.radians', (['fss_lon'], {}), '(fss_lon)\n', (1918, 1927), False, 'import math\n'), ((1940, 1961), 'math.radians', 'math.radians', (['sat_lon'], {}), '(sat_lon)\n'... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""This mo... | [
"six.moves.urllib.parse.quote",
"time.time"
] | [((2433, 2471), 'six.moves.urllib.parse.quote', 'urllib.parse.quote', (['self._uri'], {'safe': '""""""'}), "(self._uri, safe='')\n", (2451, 2471), True, 'import six.moves.urllib as urllib\n'), ((2890, 2928), 'six.moves.urllib.parse.quote', 'urllib.parse.quote', (['signature'], {'safe': '""""""'}), "(signature, safe='')... |
# Generated by Django 2.1.7 on 2019-04-10 23:47
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('main', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='parceiro',
old_name='usuario_id',
n... | [
"django.db.migrations.RenameField"
] | [((213, 305), 'django.db.migrations.RenameField', 'migrations.RenameField', ([], {'model_name': '"""parceiro"""', 'old_name': '"""usuario_id"""', 'new_name': '"""usuario"""'}), "(model_name='parceiro', old_name='usuario_id',\n new_name='usuario')\n", (235, 305), False, 'from django.db import migrations\n'), ((358, 4... |
import collections
import geopy.distance
from controllers import relevanceutils
def sort_age(artists):
return artists
def sort_location(artists, target_location):
artists = sorted(artists,
key = lambda x: geopy.distance.distance(target_location,
... | [
"controllers.relevanceutils.decorate_artist",
"controllers.relevanceutils.is_exact_match"
] | [((2074, 2181), 'controllers.relevanceutils.decorate_artist', 'relevanceutils.decorate_artist', (['artist', 'age_criteria', 'location_criteria', 'rate_criteria', 'gender_criteria'], {}), '(artist, age_criteria, location_criteria,\n rate_criteria, gender_criteria)\n', (2104, 2181), False, 'from controllers import rel... |
import kornia
import torch
import torch.nn as nn
import torch.nn.functional as F
class SSIM(nn.Module):
def __init__(self, window_size=11):
super(SSIM, self).__init__()
self.window_size = window_size
def forward(self, x, y):
if x.shape[1] == 3:
x = kornia.color.rgb_to_gray... | [
"kornia.losses.ssim",
"kornia.color.rgb_to_grayscale",
"torch.nn.functional.mse_loss",
"torch.log10"
] | [((851, 885), 'torch.nn.functional.mse_loss', 'F.mse_loss', (['x', 'y'], {'reduction': '"""mean"""'}), "(x, y, reduction='mean')\n", (861, 885), True, 'import torch.nn.functional as F\n'), ((296, 328), 'kornia.color.rgb_to_grayscale', 'kornia.color.rgb_to_grayscale', (['x'], {}), '(x)\n', (325, 328), False, 'import kor... |
#!/usr/bin/env python
#-------------------------------------------------------------------------------
# bob: tests_full/test_barevm.py
#
# Run the full tests for the Bob bare VM
#
# <NAME> (<EMAIL>)
# This code is in the public domain
#-------------------------------------------------------------------------------
imp... | [
"subprocess.Popen",
"os.remove",
"bob.py3compat.bytes2str",
"tempfile.mkstemp",
"bob.compiler.compile_code",
"testcases_utils.run_all_tests",
"os.close",
"bob.bytecode.Serializer",
"os.write"
] | [((1228, 1256), 'testcases_utils.run_all_tests', 'run_all_tests', (['barevm_runner'], {}), '(barevm_runner)\n', (1241, 1256), False, 'from testcases_utils import run_all_tests\n'), ((627, 645), 'bob.compiler.compile_code', 'compile_code', (['code'], {}), '(code)\n', (639, 645), False, 'from bob.compiler import compile_... |
import sqlite3
class DataBase:
DaBe = 0
cursor = 0
def __init__(self, dbname):
self.DaBe = sqlite3.connect(dbname)
self.cursor = self.DaBe.cursor()
def __del__(self):
self.DaBe.commit()
self.DaBe.close()
def CREATE_TABLE(self, TableName, data):
string = "CREATE TABLE " + TableName + "("
for i in range... | [
"sqlite3.connect"
] | [((97, 120), 'sqlite3.connect', 'sqlite3.connect', (['dbname'], {}), '(dbname)\n', (112, 120), False, 'import sqlite3\n')] |
import numpy as np
import lenstronomy.Util.util as util
import lenstronomy.Util.image_util as image_util
from scipy.optimize import minimize
__all__ = ['LensEquationSolver']
class LensEquationSolver(object):
"""
class to solve for image positions given lens model and source position
"""
def __init__(... | [
"numpy.random.uniform",
"scipy.optimize.minimize",
"lenstronomy.Util.util.selectBest",
"lenstronomy.Util.util.make_grid",
"numpy.zeros",
"numpy.argsort",
"lenstronomy.Util.util.neighborSelect",
"numpy.array",
"numpy.random.normal",
"lenstronomy.Util.image_util.findOverlap",
"lenstronomy.Util.uti... | [((2499, 2556), 'lenstronomy.Util.image_util.findOverlap', 'image_util.findOverlap', (['x_solve', 'y_solve', 'precision_limit'], {}), '(x_solve, y_solve, precision_limit)\n', (2521, 2556), True, 'import lenstronomy.Util.image_util as image_util\n'), ((4727, 4763), 'lenstronomy.Util.util.make_grid', 'util.make_grid', ([... |
'''
This module is made for generating QR barcodes on given qr data/link.
You must specify your data/link to qr.add_data("here!").
Generated Qr will be opened and you will see a feedback on terminal.
'''
import qrcode
from PIL import Image
from log import logger
import os
logging = logger()
class QrGenerator():
... | [
"qrcode.QRCode",
"log.logger",
"PIL.Image.open"
] | [((285, 293), 'log.logger', 'logger', ([], {}), '()\n', (291, 293), False, 'from log import logger\n'), ((357, 459), 'qrcode.QRCode', 'qrcode.QRCode', ([], {'version': '(1)', 'error_correction': 'qrcode.constants.ERROR_CORRECT_L', 'box_size': '(10)', 'border': '(4)'}), '(version=1, error_correction=qrcode.constants.ERR... |
from .strategy import Strategy
import numpy as np
import torch
from torch import nn
import random
import math
from scipy import stats
def init_centers(X, K, device):
pdist = nn.PairwiseDistance(p=2)
ind = np.argmax([np.linalg.norm(s, 2) for s in X])
mu = [X[ind]]
indsAll = [ind]
centInds = [0.] ... | [
"torch.flatten",
"torch.nn.PairwiseDistance",
"math.ceil",
"random.sample",
"numpy.linalg.norm",
"torch.zeros",
"torch.from_numpy"
] | [((182, 206), 'torch.nn.PairwiseDistance', 'nn.PairwiseDistance', ([], {'p': '(2)'}), '(p=2)\n', (201, 206), False, 'from torch import nn\n'), ((3701, 3748), 'math.ceil', 'math.ceil', (['(grad_embedding.shape[0] / batch_size)'], {}), '(grad_embedding.shape[0] / batch_size)\n', (3710, 3748), False, 'import math\n'), ((3... |
import numpy as np
from mindspore.train.serialization import export
from mindspore import Tensor
from mindspore.train.serialization import load_checkpoint, load_param_into_net
from src.musictagger import MusicTaggerCNN
from src.config import music_cfg as cfg
if __name__ == "__main__":
network = MusicTaggerCNN()
... | [
"numpy.random.uniform",
"mindspore.Tensor",
"mindspore.train.serialization.load_checkpoint",
"src.musictagger.MusicTaggerCNN",
"mindspore.train.serialization.load_param_into_net"
] | [((301, 317), 'src.musictagger.MusicTaggerCNN', 'MusicTaggerCNN', ([], {}), '()\n', (315, 317), False, 'from src.musictagger import MusicTaggerCNN\n'), ((335, 394), 'mindspore.train.serialization.load_checkpoint', 'load_checkpoint', (["(cfg.checkpoint_path + '/' + cfg.model_name)"], {}), "(cfg.checkpoint_path + '/' + c... |
import collections.abc
import numpy
import cupy
from cupy import core
from cupy.core import internal
from cupy.linalg._solve import inv
matmul = core.matmul
def dot(a, b, out=None):
"""Returns a dot product of two arrays.
For arrays with more than one axis, it computes the dot product along the
last ... | [
"cupy.rollaxis",
"cupy.asarray",
"cupy.promote_types",
"cupy.core.tensordot_core",
"cupy.empty",
"numpy.isscalar",
"cupy.identity",
"cupy.negative",
"cupy.linalg._solve.inv",
"cupy.broadcast",
"cupy.binary_repr",
"cupy.matmul",
"cupy.core.internal._normalize_axis_index",
"cupy.core.interna... | [((1382, 1431), 'cupy.core.tensordot_core', 'core.tensordot_core', (['a', 'b', 'None', '(1)', '(1)', 'a.size', '()'], {}), '(a, b, None, 1, 1, a.size, ())\n', (1401, 1431), False, 'from cupy import core\n'), ((3106, 3121), 'cupy.asarray', 'cupy.asarray', (['a'], {}), '(a)\n', (3118, 3121), False, 'import cupy\n'), ((31... |
from typing import *
class Solution:
# 84 ms, faster than 25.19% of Python3 online submissions for Make Two Arrays Equal by Reversing Sub-arrays.
# 14.5 MB, less than 31.19% of Python3 online submissions for Make Two Arrays Equal by Reversing Sub-arrays.
def canBeEqual(self, target: List[int], arr: List[int... | [
"collections.Counter"
] | [((394, 409), 'collections.Counter', 'Counter', (['target'], {}), '(target)\n', (401, 409), False, 'from collections import Counter\n'), ((432, 444), 'collections.Counter', 'Counter', (['arr'], {}), '(arr)\n', (439, 444), False, 'from collections import Counter\n')] |
"""
Copyright (c) 2018-2021 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in wri... | [
"openvino.tools.accuracy_checker.representation.DetectionPrediction",
"openvino.tools.accuracy_checker.postprocessor.PostprocessingExecutor",
"pytest.warns",
"numpy.zeros",
"pytest.raises",
"openvino.tools.accuracy_checker.representation.DetectionAnnotation",
"openvino.tools.accuracy_checker.representat... | [((2038, 2068), 'openvino.tools.accuracy_checker.postprocessor.PostprocessingExecutor', 'PostprocessingExecutor', (['config'], {}), '(config)\n', (2060, 2068), False, 'from openvino.tools.accuracy_checker.postprocessor import PostprocessingExecutor\n'), ((2509, 2539), 'openvino.tools.accuracy_checker.postprocessor.Post... |
self.send_200()
self.wfile.write('''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Upload/Download</title>
<style TYPE="text/css">
body {
background-color:#ADD8E6;
text-align:center;
margin:0px;
padding:0px;
... | [
"os.listdir"
] | [((1606, 1629), 'os.listdir', 'os.listdir', (['"""Downloads"""'], {}), "('Downloads')\n", (1616, 1629), False, 'import os\n')] |
from Models.Technology.European_power_plant.V001.db.db_declarative import Base, Brennstofftyp, Brennstoffpreis, \
Kraftwerkstyp, Kraftwerk, Kraftwerksleistung, VarOpex, Capex, Entsorgungspreis, Co2Preis
# imports for database
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalch... | [
"Models.Technology.European_power_plant.V001.db.db_declarative.Base.metadata.create_all",
"Models.Technology.European_power_plant.V001.db.db_declarative.Brennstofftyp",
"random.randint",
"random.choice",
"time.time",
"dotenv.load_dotenv",
"random.random",
"sqlalchemy.create_engine",
"sqlalchemy.orm.... | [((623, 636), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (634, 636), False, 'from dotenv import load_dotenv\n'), ((674, 696), 'sqlalchemy.create_engine', 'create_engine', (['db_path'], {}), '(db_path)\n', (687, 696), False, 'from sqlalchemy import create_engine\n'), ((718, 748), 'Models.Technology.European_... |
""" MetaInfoWindow Class """
import tkinter
from kalmus.tkinter_windows.meta_info_windows.SpecifyMetaDataWindow import SpecifyMetaDataWindow
from kalmus.tkinter_windows.gui_utils import resource_path
keys = ["Film Title", "Directors", "Country of Origin", "Produced Year", "Genre"]
class MetaInfoWindow():
"""
... | [
"tkinter.Button",
"kalmus.tkinter_windows.gui_utils.resource_path",
"kalmus.tkinter_windows.meta_info_windows.SpecifyMetaDataWindow.SpecifyMetaDataWindow",
"tkinter.Label",
"tkinter.Tk"
] | [((808, 820), 'tkinter.Tk', 'tkinter.Tk', ([], {}), '()\n', (818, 820), False, 'import tkinter\n'), ((1031, 1126), 'tkinter.Label', 'tkinter.Label', (['self.window'], {'text': '""""""', 'width': '(35)', 'bg': '"""white"""', 'anchor': '"""w"""', 'justify': 'tkinter.LEFT'}), "(self.window, text='', width=35, bg='white', ... |
#=======================================================================
# ast_helpers.py
#=======================================================================
from __future__ import print_function
import inspect
import ast, _ast
#-----------------------------------------------------------------------
# print_ast... | [
"ast.iter_fields",
"inspect.getsource",
"inspect.getargspec",
"ast.parse",
"re.compile"
] | [((3554, 3579), 're.compile', 're.compile', (['"""( *(@|def))"""'], {}), "('( *(@|def))')\n", (3564, 3579), False, 'import re\n'), ((5077, 5101), 'inspect.getargspec', 'inspect.getargspec', (['func'], {}), '(func)\n', (5095, 5101), False, 'import inspect\n'), ((3626, 3649), 'inspect.getsource', 'inspect.getsource', (['... |
# originally from https://github.com/aws-samples/chalice-workshop/blob/master/code/media-query/04-s3-event/recordresources.py
from __future__ import print_function
import argparse
import json
import os
import boto3
from botocore import xform_name
def get_cognito_app_secret(stage, data):
print("getting cognito cl... | [
"json.load",
"argparse.ArgumentParser",
"boto3.client",
"json.dumps",
"botocore.xform_name",
"os.path.join"
] | [((382, 409), 'boto3.client', 'boto3.client', (['"""cognito-idp"""'], {}), "('cognito-idp')\n", (394, 409), False, 'import boto3\n'), ((961, 991), 'boto3.client', 'boto3.client', (['"""cloudformation"""'], {}), "('cloudformation')\n", (973, 991), False, 'import boto3\n'), ((1834, 1859), 'argparse.ArgumentParser', 'argp... |
"""
Get Task Results
Debug by setting the environment variable:
::
export DEBUG_TASK=1
"""
import analysis_engine.consts as ae_consts
import spylunking.log.setup_logging as log_utils
log = log_utils.build_colorized_logger(name=__name__)
def get_task_results(
work_dict=None,
result=None,
... | [
"analysis_engine.consts.ppj",
"spylunking.log.setup_logging.build_colorized_logger",
"analysis_engine.consts.ev",
"analysis_engine.consts.is_celery_disabled",
"analysis_engine.consts.get_status"
] | [((203, 250), 'spylunking.log.setup_logging.build_colorized_logger', 'log_utils.build_colorized_logger', ([], {'name': '__name__'}), '(name=__name__)\n', (235, 250), True, 'import spylunking.log.setup_logging as log_utils\n'), ((932, 981), 'analysis_engine.consts.is_celery_disabled', 'ae_consts.is_celery_disabled', ([]... |
import modules.item as item
skull = item.Item("Skull", "A skull you found somewhere.", 10, 0.5, "You took the skull.", "You dropped the skull.")
| [
"modules.item.Item"
] | [((36, 148), 'modules.item.Item', 'item.Item', (['"""Skull"""', '"""A skull you found somewhere."""', '(10)', '(0.5)', '"""You took the skull."""', '"""You dropped the skull."""'], {}), "('Skull', 'A skull you found somewhere.', 10, 0.5,\n 'You took the skull.', 'You dropped the skull.')\n", (45, 148), True, 'import... |
from __future__ import print_function, division
from typing import Optional
import warnings
import os
import time
import math
import GPUtil
import numpy as np
from yacs.config import CfgNode
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.cuda.amp import autocast, GradScaler
from connec... | [
"numpy.abs",
"torch.cat",
"connectomics.data.augmentation.build_train_augmentor",
"torch.no_grad",
"os.path.join",
"torch.cuda.amp.autocast",
"numpy.zeros_like",
"torch.load",
"connectomics.utils.monitor.build_monitor",
"torch.zeros_like",
"time.perf_counter",
"torch.cuda.is_available",
"tor... | [((9853, 9872), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (9870, 9872), False, 'import time\n'), ((12999, 13018), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (13016, 13018), False, 'import time\n'), ((15693, 15715), 'torch.load', 'torch.load', (['checkpoint'], {}), '(checkpoint)\n', (1... |
import pytest
from openapi_spec_validator import validate_spec
from .schemas import FooSchema
from apiflask import Schema
from apiflask.fields import Field
from apiflask.fields import Integer
from apiflask.fields import String
class BaseResponseSchema(Schema):
message = String()
status_code = Integer()
d... | [
"apiflask.fields.String",
"openapi_spec_validator.validate_spec",
"apiflask.fields.Integer",
"apiflask.fields.Field",
"pytest.skip",
"pytest.raises",
"pytest.mark.parametrize"
] | [((1555, 1714), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""base_schema"""', "[BaseResponseSchema, base_response_schema_dict, BadBaseResponseSchema,\n bad_base_response_schema_dict, '', None]"], {}), "('base_schema', [BaseResponseSchema,\n base_response_schema_dict, BadBaseResponseSchema,\n bad... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.