code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
"""Bayesian polynomial mixture model."""
# pylint: disable=invalid-name
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
tfd = tfp.distributions
tfb = tfp.bijectors
class BayesianPolynomialMixture: # pylint: disable=too-few-public-methods
"""Handles creation of a polynomial mixtu... | [
"numpy.float64",
"tensorflow.linalg.LinearOperatorDiag",
"numpy.expand_dims",
"tensorflow.linalg.matmul"
] | [((973, 1019), 'numpy.expand_dims', 'np.expand_dims', (['self.coefficient_precisions', '(0)'], {}), '(self.coefficient_precisions, 0)\n', (987, 1019), True, 'import numpy as np\n'), ((1863, 1878), 'numpy.float64', 'np.float64', (['(0.0)'], {}), '(0.0)\n', (1873, 1878), True, 'import numpy as np\n'), ((1886, 1901), 'num... |
# Copyright 2020 Makani Technologies LLC
#
# 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... | [
"numpy.cross",
"numpy.arcsin",
"numpy.array",
"makani.analysis.aero.hover_model.hover_model.GetParams",
"numpy.arctan2",
"numpy.expand_dims",
"numpy.linalg.norm",
"numpy.concatenate",
"numpy.shape",
"numpy.rad2deg"
] | [((5190, 5223), 'numpy.linalg.norm', 'np.linalg.norm', (['local_vel'], {'axis': '(1)'}), '(local_vel, axis=1)\n', (5204, 5223), True, 'import numpy as np\n'), ((1303, 1371), 'makani.analysis.aero.hover_model.hover_model.GetParams', 'hover_model.GetParams', (['wing_model', 'wing_serial'], {'use_wake_model': '(False)'}),... |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2019 Fetch.AI Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the ... | [
"aea.helpers.search.models.Description",
"typing.cast",
"pathlib.Path"
] | [((1418, 1496), 'pathlib.Path', 'Path', (['ROOT_DIR', '"""packages"""', '"""fetchai"""', '"""skills"""', '"""simple_service_registration"""'], {}), "(ROOT_DIR, 'packages', 'fetchai', 'skills', 'simple_service_registration')\n", (1422, 1496), False, 'from pathlib import Path\n'), ((1644, 1715), 'typing.cast', 'cast', ([... |
from django.urls import path
from evap.results import views
app_name = "results"
urlpatterns = [
path("", views.index, name="index"),
path("semester/<int:semester_id>/course/<int:course_id>", views.course_detail, name="course_detail"),
]
| [
"django.urls.path"
] | [((105, 140), 'django.urls.path', 'path', (['""""""', 'views.index'], {'name': '"""index"""'}), "('', views.index, name='index')\n", (109, 140), False, 'from django.urls import path\n'), ((146, 251), 'django.urls.path', 'path', (['"""semester/<int:semester_id>/course/<int:course_id>"""', 'views.course_detail'], {'name'... |
import argparse
import os
import random
import time
import numpy as np
import torch
import torch.nn as nn
from sklearn.metrics import accuracy_score
from sklearn.utils import shuffle
from analysis import rocstories as rocstories_analysis
from analysis import pw as pw_analysis
from analysis import pw_retrieved as pw_r... | [
"torch.nn.CrossEntropyLoss",
"utils.make_path",
"torch.cuda.device_count",
"numpy.array",
"torch.cuda.is_available",
"datasets.pw",
"numpy.arange",
"utils.ResultLogger",
"text_utils.TextEncoder",
"argparse.ArgumentParser",
"numpy.random.seed",
"numpy.concatenate",
"loss.MultipleChoiceLossCom... | [((805, 853), 'numpy.zeros', 'np.zeros', (['(n_batch, 2, n_ctx, 2)'], {'dtype': 'np.int32'}), '((n_batch, 2, n_ctx, 2), dtype=np.int32)\n', (813, 853), True, 'import numpy as np\n'), ((864, 911), 'numpy.zeros', 'np.zeros', (['(n_batch, 2, n_ctx)'], {'dtype': 'np.float32'}), '((n_batch, 2, n_ctx), dtype=np.float32)\n', ... |
from openapi_server.models.tool import Tool # noqa: E501
from openapi_server.models.tool_dependencies import ToolDependencies # noqa: E501
from openapi_server.models.tool_type import ToolType # noqa: E501
from openapi_server.models.license import License
from openapi_server.config import config
def get_tool(): # ... | [
"openapi_server.models.tool_dependencies.ToolDependencies",
"openapi_server.models.tool.Tool"
] | [((446, 915), 'openapi_server.models.tool.Tool', 'Tool', ([], {'name': 'f"""phi-annotator-spark-nlp-{config.config_name}"""', 'version': '"""0.2.3"""', 'license': 'License.NONE', 'repository': '"""github:nlpsandbox/phi-annotator-spark-nlp"""', 'description': "('Spark NLP-based PHI annotator (NER model: ' +\n f'{conf... |
import nltk
from nltk.corpus import brown
cfd = nltk.ConditionalFreqDist(
(genre, word)
for genre in brown.categories()
for word in brown.words(categories=genre))
genres = ['religion', 'news', 'humor', 'reviews', 'adventure']
modals = ['who', 'what', 'when', 'where', 'why', 'how']
cfd.tabulate(conditions=g... | [
"nltk.corpus.brown.words",
"nltk.corpus.brown.categories"
] | [((110, 128), 'nltk.corpus.brown.categories', 'brown.categories', ([], {}), '()\n', (126, 128), False, 'from nltk.corpus import brown\n'), ((145, 174), 'nltk.corpus.brown.words', 'brown.words', ([], {'categories': 'genre'}), '(categories=genre)\n', (156, 174), False, 'from nltk.corpus import brown\n')] |
import os
import hmac
import base64
import hashlib
from datetime import datetime
from urllib import urlencode, quote_plus
from tornado.httpclient import AsyncHTTPClient, HTTPRequest
from tornado.ioloop import PeriodicCallback
import logging
log = logging.getLogger(__name__)
# you can publish up to 20 data points in ... | [
"logging.getLogger",
"hmac.new",
"urllib.quote_plus",
"os.getenv",
"tornado.httpclient.HTTPRequest",
"datetime.datetime.utcnow",
"tornado.ioloop.PeriodicCallback",
"base64.encodestring",
"tornado.httpclient.AsyncHTTPClient"
] | [((249, 276), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (266, 276), False, 'import logging\n'), ((2943, 3029), 'tornado.httpclient.HTTPRequest', 'HTTPRequest', ([], {'url': "('%s://%s/' % (protocol, self.endpoint))", 'method': '"""POST"""', 'body': 'body'}), "(url='%s://%s/' % (proto... |
import cv2
import numpy as np
from imutils.video import FileVideoStream
import imutils
import time
vs = FileVideoStream('messi.webm').start()
while vs.more():
frame=vs.read()
if frame is None:
continue
output=frame.copy()
gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
gray=cv2.medianBlur(gray,5)
gray=cv2.adaptiveT... | [
"numpy.ones",
"imutils.video.FileVideoStream",
"cv2.erode",
"cv2.medianBlur",
"cv2.HoughCircles",
"cv2.imshow",
"cv2.adaptiveThreshold",
"cv2.circle",
"cv2.destroyAllWindows",
"numpy.around",
"cv2.cvtColor",
"cv2.dilate",
"cv2.waitKey"
] | [((976, 999), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (997, 999), False, 'import cv2\n'), ((233, 272), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2GRAY'], {}), '(frame, cv2.COLOR_BGR2GRAY)\n', (245, 272), False, 'import cv2\n'), ((278, 301), 'cv2.medianBlur', 'cv2.medianBlur', ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by <NAME> at 1/25/21
"""paper_plot_fig3.py
:description : script
:param :
:returns:
:rtype:
"""
import os
import matplotlib
import numpy as np
import pandas as pd
matplotlib.rc('font', family="Arial")
matplotlib.rcParams["font.family"] = 'Arial' # 'sans-s... | [
"pandas.read_csv",
"pandas.DataFrame.from_dict",
"os.chdir",
"numpy.array",
"matplotlib.rc",
"matplotlib.pyplot.cm.get_cmap",
"matplotlib.pyplot.subplots"
] | [((226, 263), 'matplotlib.rc', 'matplotlib.rc', (['"""font"""'], {'family': '"""Arial"""'}), "('font', family='Arial')\n", (239, 263), False, 'import matplotlib\n'), ((377, 436), 'os.chdir', 'os.chdir', (['"""../../ComplementaryData/Step_04_Pan_Core_model/"""'], {}), "('../../ComplementaryData/Step_04_Pan_Core_model/')... |
"""Tests for distutils.util."""
import os
import sys
import unittest
import sysconfig as stdlib_sysconfig
from copy import copy
from test.support import run_unittest
from unittest import mock
from distutils.errors import DistutilsPlatformError, DistutilsByteCompileError
from distutils.util import (
get_platform,
... | [
"unittest.mock.patch.dict",
"pwd.struct_passwd",
"sysconfig.get_platform",
"copy.copy",
"unittest.mock.patch",
"distutils.util.get_host_platform",
"os.uname",
"distutils.util.change_root",
"distutils.util.get_platform",
"distutils.util.check_environ",
"distutils.util.rfc822_escape",
"unittest.... | [((5378, 5438), 'unittest.skipUnless', 'unittest.skipUnless', (["(os.name == 'posix')", '"""specific to posix"""'], {}), "(os.name == 'posix', 'specific to posix')\n", (5397, 5438), False, 'import unittest\n'), ((1051, 1079), 'copy.copy', 'copy', (['sysconfig._config_vars'], {}), '(sysconfig._config_vars)\n', (1055, 10... |
import argparse
import os
import sys
from collocator import CollocationFinder, DependencyBasedCollocationFinder, SentenceLevelCollocationFinder, SyntacticCollocationFinder
def load_lexicon(filename):
lexicon = set()
with open(filename, encoding='utf-8') as f:
for line in f:
word = line.strip()
word = word.... | [
"argparse.ArgumentParser",
"os.makedirs",
"os.path.join",
"os.path.isfile",
"czeng.open_filtered_files"
] | [((914, 961), 'os.makedirs', 'os.makedirs', (['"""data/collocations"""'], {'exist_ok': '(True)'}), "('data/collocations', exist_ok=True)\n", (925, 961), False, 'import os\n'), ((1643, 1693), 'os.path.join', 'os.path.join', (['"""data"""', '"""collocations"""', 'col_filename'], {}), "('data', 'collocations', col_filenam... |
#!/usr/bin/env python3
import geopandas as gpd
import pandas as pd
import rasterio
from rasterio.mask import mask
from rasterio.io import DatasetReader
from os.path import splitext
import fiona
from fiona.errors import DriverError
from collections import deque
import numpy as np
from tqdm import tqdm
from shapely.ops ... | [
"random.sample",
"collections.deque",
"geopandas.read_file",
"scipy.stats.mode",
"geopandas.clip",
"rasterio.open",
"os.path.splitext",
"shapely.ops.linemerge",
"pandas.DataFrame.from_dict",
"shapely.geometry.Point",
"fiona.open",
"pandas.DataFrame",
"rasterio.mask.mask",
"geopandas.GeoDat... | [((2924, 2964), 'geopandas.read_file', 'gpd.read_file', (['filename', '*args'], {}), '(filename, *args, **kwargs)\n', (2937, 2964), True, 'import geopandas as gpd\n'), ((2985, 3003), 'geopandas.GeoDataFrame', 'gpd.GeoDataFrame', ([], {}), '()\n', (3001, 3003), True, 'import geopandas as gpd\n'), ((6014, 6049), 'pandas.... |
from GameObject import *
import pygame
from Constants import IMAGE_BRICKS_PATH, ITEM_BRICKS_WIDTH, ITEM_BRICKS_HEIGHT
class ItemBricks(GameObject):
def __init__(self,gameObject):
super(GameObject, self).__init__()
pygame.sprite.Sprite.__init__(self) # call Sprite intializer
self.width = ... | [
"pygame.image.load",
"pygame.sprite.Sprite.__init__",
"pygame.sprite.spritecollide"
] | [((237, 272), 'pygame.sprite.Sprite.__init__', 'pygame.sprite.Sprite.__init__', (['self'], {}), '(self)\n', (266, 272), False, 'import pygame\n'), ((1101, 1154), 'pygame.sprite.spritecollide', 'pygame.sprite.spritecollide', (['self', 'spriteGroup', '(False)'], {}), '(self, spriteGroup, False)\n', (1128, 1154), False, '... |
"""Work class"""
import re
from bs4 import BeautifulSoup
RESOURCE_DICT = {
'oil': 'oil',
'ore': 'ore',
'yellow': 'gold',
'uranium': 'uranium',
'diamond': 'diamond'
}
class Work():
"""Wrapper class for work"""
def __init__(self, api_wrapper):
self.api_wrapper = api_wrapper
... | [
"bs4.BeautifulSoup"
] | [((447, 485), 'bs4.BeautifulSoup', 'BeautifulSoup', (['response', '"""html.parser"""'], {}), "(response, 'html.parser')\n", (460, 485), False, 'from bs4 import BeautifulSoup\n')] |
# Generated by Django 2.2.10 on 2020-05-28 16:19
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
from django.utils.timezone import utc
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappab... | [
"datetime.datetime",
"django.db.models.OneToOneField",
"django.db.models.IntegerField",
"django.db.models.BooleanField",
"django.db.models.AutoField",
"django.db.migrations.swappable_dependency",
"django.db.models.CharField"
] | [((302, 359), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (333, 359), False, 'from django.db import migrations, models\n'), ((492, 585), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)... |
from os.path import abspath, dirname, join, normpath
from setuptools import find_packages, setup
from django_twilio import __version__ as version
setup(
# Basic package information:
name = 'django-twilio',
version = version,
packages = find_packages(),
# Packaging options:
zip_safe = False,
include_package_... | [
"os.path.abspath",
"setuptools.find_packages"
] | [((244, 259), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (257, 259), False, 'from setuptools import find_packages, setup\n'), ((700, 717), 'os.path.abspath', 'abspath', (['__file__'], {}), '(__file__)\n', (707, 717), False, 'from os.path import abspath, dirname, join, normpath\n')] |
#!/usr/bin/env python3
import base64
from gevent.pywsgi import WSGIServer
import io
import os
import signal
import sys
import shutil
from threading import Thread
def get_parent_dir(n=1):
""" returns the n-th parent dicrectory of the current
working directory """
current_path = os.path.dirname(os.path.abs... | [
"signal.signal",
"PIL.Image.open",
"os.getenv",
"flask.Flask",
"os.path.join",
"io.BytesIO",
"flask.json.dumps",
"os.path.realpath",
"os.path.dirname",
"flask.request.get_json",
"os._exit",
"gevent.pywsgi.WSGIServer",
"ServeVideo.main",
"os.path.abspath",
"threading.Thread",
"sys.path.... | [((492, 517), 'sys.path.append', 'sys.path.append', (['src_path'], {}), '(src_path)\n', (507, 517), False, 'import sys\n'), ((990, 1029), 'os.path.join', 'os.path.join', (['MODEL_PATH', '"""anchors.txt"""'], {}), "(MODEL_PATH, 'anchors.txt')\n", (1002, 1029), False, 'import os\n'), ((1045, 1084), 'os.path.join', 'os.pa... |
import sentiment_mod as s
import nltk
from nltk.tokenize import sent_tokenize
text = '''
I love going down to the farmers' market. I love really being able to interact with the farmers and i love going down and just being able to see everyone there.
'''
tokenized_text = sent_tokenize(text)
for sent in tokenized_text:
... | [
"sentiment_mod.sentiment",
"nltk.tokenize.sent_tokenize"
] | [((272, 291), 'nltk.tokenize.sent_tokenize', 'sent_tokenize', (['text'], {}), '(text)\n', (285, 291), False, 'from nltk.tokenize import sent_tokenize\n'), ((372, 430), 'sentiment_mod.sentiment', 's.sentiment', (['"""I like that all of those options are there."""'], {}), "('I like that all of those options are there.')\... |
import logging
def welcome():
logging.info('')
logging.info(' ,@;@,')
logging.info(' ,@;@;@;@;@;@/ )@;@;')
logging.info(' ,;@;@;@;@;@;@|_/@\' e\\')
logging.info(' (|@;@:@\\@;@;@;@:@( \\ ')
logging.info(' \'@;@;@|@;@;@;@;\'`"--\' ')
logging.info(... | [
"logging.info"
] | [((36, 52), 'logging.info', 'logging.info', (['""""""'], {}), "('')\n", (48, 52), False, 'import logging\n'), ((57, 99), 'logging.info', 'logging.info', (['""" ,@;@,"""'], {}), "(' ,@;@,')\n", (69, 99), False, 'import logging\n'), ((104, 147), 'logging.info', 'logging.info', (['"... |
import boto3
class BaseS3Action:
def __init__(self):
self.client = boto3.client('s3')
@classmethod
def default_directory(cls, bucket_name: str) -> str:
return f'./backups/{bucket_name}'
| [
"boto3.client"
] | [((81, 99), 'boto3.client', 'boto3.client', (['"""s3"""'], {}), "('s3')\n", (93, 99), False, 'import boto3\n')] |
from tgbot import plugintest, pluginbase
from tgbot.botapi import Message
from sample_plugin import TestPlugin
import threading
import time
class IssuesTest(plugintest.PluginTestCase):
def setUp(self):
self.plugin = TestPlugin()
self.bot = self.fake_bot('', plugins=[self.plugin])
def test_us... | [
"mock.patch",
"time.sleep",
"tgbot.pluginbase.TGCommandBase",
"os.unlink",
"tgbot.botapi.Message.from_result",
"threading.Thread",
"sample_plugin.TestPlugin",
"tempfile.mkstemp"
] | [((231, 243), 'sample_plugin.TestPlugin', 'TestPlugin', ([], {}), '()\n', (241, 243), False, 'from sample_plugin import TestPlugin\n'), ((3630, 3648), 'tempfile.mkstemp', 'tempfile.mkstemp', ([], {}), '()\n', (3646, 3648), False, 'import tempfile\n'), ((4080, 4096), 'time.sleep', 'time.sleep', (['(0.05)'], {}), '(0.05)... |
from typing import Any, Optional, Sequence, List
import numpy as np
import pandas as pd
import xgboost as xgb
from xgboost_ray.data_sources.data_source import DataSource, RayFileType
from xgboost_ray.data_sources.pandas import Pandas
class Numpy(DataSource):
"""Read from numpy arrays."""
@staticmethod
... | [
"xgboost_ray.data_sources.pandas.Pandas.load_data"
] | [((1016, 1074), 'xgboost_ray.data_sources.pandas.Pandas.load_data', 'Pandas.load_data', (['local_df'], {'ignore': 'ignore', 'indices': 'indices'}), '(local_df, ignore=ignore, indices=indices)\n', (1032, 1074), False, 'from xgboost_ray.data_sources.pandas import Pandas\n')] |
from skimage import exposure
from scipy.misc import imread
from scipy import ndimage
import numpy as np
import random
import os
from data_augmentation import *
from AxonDeepSeg.patch_management_tools import apply_legacy_preprocess, apply_preprocess
import functools
import copy
def generate_list_transformations(transf... | [
"numpy.mean",
"scipy.ndimage.distance_transform_edt",
"random.choice",
"numpy.reshape",
"numpy.multiply",
"os.listdir",
"numpy.where",
"AxonDeepSeg.patch_management_tools.apply_legacy_preprocess",
"numpy.random.choice",
"numpy.asarray",
"numpy.max",
"numpy.stack",
"numpy.zeros",
"functools... | [((3080, 3100), 'numpy.zeros_like', 'np.zeros_like', (['patch'], {}), '(patch)\n', (3093, 3100), True, 'import numpy as np\n'), ((2665, 2697), 'random.choice', 'random.choice', (['L_transformations'], {}), '(L_transformations)\n', (2678, 2697), False, 'import random\n'), ((3289, 3353), 'numpy.where', 'np.where', (['((p... |
from core.advbase import *
from slot.a import *
def module():
return Yuya
class Yuya(Adv):
a3 = ('primed_crit_chance', 0.05,5)
conf = {}
conf['slots.burn.a'] = Twinfold_Bonds()+Me_and_My_Bestie()
conf['acl'] = """
`dragon, s=1
`s3, not self.s3_buff
`s4
`s1
... | [
"core.simulate.test_with_argv"
] | [((734, 765), 'core.simulate.test_with_argv', 'test_with_argv', (['None', '*sys.argv'], {}), '(None, *sys.argv)\n', (748, 765), False, 'from core.simulate import test_with_argv\n')] |
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_noop, ugettext as _
from dimagi.utils.decorators.memoized import memoized
from corehq.apps.hqwebapp.models import UITab, format_submenu_context
from corehq.apps.styleguide.examples.simple_crispy_form.views import (
DefaultSim... | [
"django.utils.translation.ugettext_noop",
"corehq.apps.hqwebapp.models.format_submenu_context",
"django.core.urlresolvers.reverse",
"django.utils.translation.ugettext"
] | [((866, 901), 'django.utils.translation.ugettext_noop', 'ugettext_noop', (['"""Simple Crispy Form"""'], {}), "('Simple Crispy Form')\n", (879, 901), False, 'from django.utils.translation import ugettext_noop, ugettext as _\n'), ((1952, 1980), 'django.utils.translation.ugettext_noop', 'ugettext_noop', (['"""Style Guide"... |
from treys import Evaluator, Deck
from treys.card import pretty
d = Deck.fresh()
print(d)
print(pretty(d))
| [
"treys.Deck.fresh",
"treys.card.pretty"
] | [((69, 81), 'treys.Deck.fresh', 'Deck.fresh', ([], {}), '()\n', (79, 81), False, 'from treys import Evaluator, Deck\n'), ((97, 106), 'treys.card.pretty', 'pretty', (['d'], {}), '(d)\n', (103, 106), False, 'from treys.card import pretty\n')] |
import dpctl
import syclbuffer as sb
import numpy as np
X = np.full((10 ** 4, 4098), 1e-4, dtype="d")
# warm-up
print("=" * 10 + " Executing warm-up " + "=" * 10)
print("NumPy result: ", X.sum(axis=0))
dpctl.set_default_queue("opencl", "cpu", 0)
print(
"SYCL({}) result: {}".format(
dpctl.get_current_queu... | [
"syclbuffer.columnwise_total",
"numpy.full",
"dpctl.get_current_queue",
"dpctl.set_default_queue"
] | [((61, 104), 'numpy.full', 'np.full', (['(10 ** 4, 4098)', '(0.0001)'], {'dtype': '"""d"""'}), "((10 ** 4, 4098), 0.0001, dtype='d')\n", (68, 104), True, 'import numpy as np\n'), ((205, 248), 'dpctl.set_default_queue', 'dpctl.set_default_queue', (['"""opencl"""', '"""cpu"""', '(0)'], {}), "('opencl', 'cpu', 0)\n", (228... |
"""
Example of scoring images with MLflow model deployed to a REST API endpoint.
The MLflow model to be scored is expected to be an instance of KerasImageClassifierPyfunc
(e.g. produced by running this project) and deployed with MLflow prior to invoking this script.
"""
import os
import base64
import requests
import ... | [
"click.argument",
"os.listdir",
"click.option",
"os.path.join",
"os.path.isdir",
"click.command"
] | [((1589, 1624), 'click.command', 'click.command', ([], {'help': '"""Score images."""'}), "(help='Score images.')\n", (1602, 1624), False, 'import click\n'), ((1626, 1726), 'click.option', 'click.option', (['"""--port"""'], {'type': 'click.INT', 'default': '(80)', 'help': '"""Port at which the model is deployed."""'}), ... |
#!/usr/bin/python3
import brownie
# Confirm that a full withdraw occurs
def test_exit_withdraws(multi, alice, bob, base_token, reward_token, chain):
amount = base_token.balanceOf(bob)
base_token.approve(multi, amount, {"from": bob})
multi.stake(amount, {"from": bob})
assert base_token.balanceOf(bob) =... | [
"brownie.reverts"
] | [((1442, 1459), 'brownie.reverts', 'brownie.reverts', ([], {}), '()\n', (1457, 1459), False, 'import brownie\n')] |
import pandas as pd
import datetime as dt
from src.fileDataExtractor import FileDataExtractor
from src.scadaDbAdapter import ScadaDbAdapter
class FileHandler:
# extract data from file
dataExtractor = FileDataExtractor()
# push file data to db
dataAdapter = ScadaDbAdapter()
def pushFileDataToDb(se... | [
"datetime.datetime.now",
"datetime.timedelta",
"src.fileDataExtractor.FileDataExtractor",
"src.scadaDbAdapter.ScadaDbAdapter"
] | [((210, 229), 'src.fileDataExtractor.FileDataExtractor', 'FileDataExtractor', ([], {}), '()\n', (227, 229), False, 'from src.fileDataExtractor import FileDataExtractor\n'), ((275, 291), 'src.scadaDbAdapter.ScadaDbAdapter', 'ScadaDbAdapter', ([], {}), '()\n', (289, 291), False, 'from src.scadaDbAdapter import ScadaDbAda... |
"""Module to enable loading configuration from pyproject.toml files."""
import logging
import os.path
LOG = logging.getLogger(__name__)
# max depth to search for
MAX_RECURSION = 25
def parse_py_project_toml():
"""Attempt to find and load configuration from a pyproject.toml file."""
try:
import toml... | [
"logging.getLogger",
"toml.load"
] | [((110, 137), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (127, 137), False, 'import logging\n'), ((669, 681), 'toml.load', 'toml.load', (['f'], {}), '(f)\n', (678, 681), False, 'import toml\n')] |
from typing import List
from ..error.friendly_error import FriendlyError
from discord.ext import commands
from discord_slash import cog_ext
from discord_slash.context import SlashContext
from discord_slash.model import SlashCommandOptionType
from discord_slash.utils.manage_commands import create_option
from googlesearc... | [
"discord_slash.utils.manage_commands.create_option",
"modules.search.search_functions.get_wiki_intro",
"modules.search.search_functions.format_message",
"googlesearch.search"
] | [((1221, 1253), 'modules.search.search_functions.get_wiki_intro', 'sf.get_wiki_intro', (['wiki_links[0]'], {}), '(wiki_links[0])\n', (1238, 1253), True, 'import modules.search.search_functions as sf\n'), ((990, 1003), 'googlesearch.search', 'search', (['query'], {}), '(query)\n', (996, 1003), False, 'from googlesearch ... |
import discord
import json
from discord.ext import commands
from discord.utils import get
sigma = commands.Bot(command_prefix='*', help_command=None)
warnings = {}
token = "TOKEN_BOT"
#Permet de mettre un statut au bot ^^
@sigma.event
async def on_ready():
print("Sigma est prêt !")
await sigma.... | [
"discord.ext.commands.has_permissions",
"discord.Color.blurple",
"discord.Game",
"discord.ext.commands.Bot",
"discord.Permissions",
"discord.Color.green",
"discord.Embed",
"discord.Color.red"
] | [((104, 155), 'discord.ext.commands.Bot', 'commands.Bot', ([], {'command_prefix': '"""*"""', 'help_command': 'None'}), "(command_prefix='*', help_command=None)\n", (116, 155), False, 'from discord.ext import commands\n'), ((5483, 5529), 'discord.ext.commands.has_permissions', 'commands.has_permissions', ([], {'manage_m... |
from django.test import TestCase
from taggit.models import Tag
from .literals import COLOR_RED
from .models import TagProperties
class TagTestCase(TestCase):
def setUp(self):
self.tag = Tag(name='test')
self.tag.save()
self.tp = TagProperties(tag=self.tag, color=COLOR_RED)
self.t... | [
"taggit.models.Tag"
] | [((202, 218), 'taggit.models.Tag', 'Tag', ([], {'name': '"""test"""'}), "(name='test')\n", (205, 218), False, 'from taggit.models import Tag\n')] |
import os
from collections import Iterable
def flat(lis):
for item in lis:
if isinstance(item, list):# and not isinstance(item, basestring):
for x in flat(item):
yield x
else:
yield item
def flatten(lis):
return list(flat(lis))
def... | [
"os.path.dirname",
"os.path.exists",
"os.makedirs"
] | [((345, 363), 'os.path.dirname', 'os.path.dirname', (['f'], {}), '(f)\n', (360, 363), False, 'import os\n'), ((376, 393), 'os.path.exists', 'os.path.exists', (['d'], {}), '(d)\n', (390, 393), False, 'import os\n'), ((404, 418), 'os.makedirs', 'os.makedirs', (['d'], {}), '(d)\n', (415, 418), False, 'import os\n')] |
from django.db import models
# Create your models here.
class DefaultNetworkSettings(models.Model):
setting_type_id = models.CharField(max_length=20,default="default")
default_subnet_name = models.CharField(max_length=24,blank=True)
default_address_range = models.CharField(max_length=100,blank=True)
de... | [
"django.db.models.CharField"
] | [((123, 173), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(20)', 'default': '"""default"""'}), "(max_length=20, default='default')\n", (139, 173), False, 'from django.db import models\n'), ((199, 242), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(24)', 'blank': '(Tr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import multiprocessing
import time
def func(num):
print("message {0}".format(num))
time.sleep(3)
print("{0} end".format(num))
return num
if __name__ == "__main__":
pool = multiprocessing.Pool(processes = 3)
result = []
for i in xrange(30):
... | [
"multiprocessing.Pool",
"time.sleep"
] | [((139, 152), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (149, 152), False, 'import time\n'), ((240, 273), 'multiprocessing.Pool', 'multiprocessing.Pool', ([], {'processes': '(3)'}), '(processes=3)\n', (260, 273), False, 'import multiprocessing\n')] |
# Copyright (C) 2012 <NAME> and The Pepper Developers
# Released under the MIT License. See the file COPYING.txt for details.
from assert_parser_result import assert_parser_result
def test_import():
assert_parser_result(
r"""
0001:0001 "import"(import)
0001:0008 SYMBOL(sys)
0001:0011 NEWLINE
""... | [
"assert_parser_result.assert_parser_result"
] | [((207, 403), 'assert_parser_result.assert_parser_result', 'assert_parser_result', (['"""\n0001:0001 "import"(import)\n0001:0008 SYMBOL(sys)\n0001:0011 NEWLINE\n"""', '"""\n["import":import]\n [SYMBOL:sys]\n[EOF:]\n"""', '"""\nPepImport(\'sys\')\n"""'], {}), '(\n """\n0001:0001 "import"(import)\n0001:0... |
import os
os.environ['KMP_DUPLICATE_LIB_OK']='True'
import warnings
warnings.filterwarnings("ignore")
import gym
import pybullet_envs
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.distributions import Normal
import torch.multiprocessing as mp
import time
impo... | [
"torch.nn.ReLU",
"torch.nn.Tanh",
"torch.nn.init.constant_",
"numpy.array",
"torch.cuda.is_available",
"gym.make",
"collections.deque",
"torch.distributions.Normal",
"torch.nn.LeakyReLU",
"time.time",
"warnings.filterwarnings",
"torch.cat",
"torch.nn.init.normal_",
"statistics.mean",
"to... | [((69, 102), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (92, 102), False, 'import warnings\n'), ((422, 457), 'gym.make', 'gym.make', (['"""HalfCheetahBulletEnv-v0"""'], {}), "('HalfCheetahBulletEnv-v0')\n", (430, 457), False, 'import gym\n'), ((737, 762), 'torch.cuda.i... |
# -*- coding: utf-8 -*-
'''
Copyright 2019, University of Freiburg.
Chair of Algorithms and Data Structures.
<NAME> <<EMAIL>>
'''
from typing import Dict, List
import itertools
import warnings
from overrides import overrides
from fairseq.common.util import pad_sequence_to_length
from fairseq.data.tokenizers.token im... | [
"itertools.chain",
"fairseq.data.tokenizers.token.Token",
"fairseq.data.token_indexers.token_indexer.TokenIndexer.register",
"itertools.zip_longest",
"fairseq.common.util.pad_sequence_to_length",
"fairseq.data.tokenizers.character_tokenizer.CharacterTokenizer"
] | [((522, 557), 'fairseq.data.token_indexers.token_indexer.TokenIndexer.register', 'TokenIndexer.register', (['"""characters"""'], {}), "('characters')\n", (543, 557), False, 'from fairseq.data.token_indexers.token_indexer import TokenIndexer\n'), ((900, 920), 'fairseq.data.tokenizers.character_tokenizer.CharacterTokeniz... |
from flask_login import login_user
from flaskbb.forum.models import Topic
def test_guest_user_cannot_see_hidden_posts(guest, topic, user,
request_context):
topic.hide(user)
login_user(guest)
assert Topic.query.filter(Topic.id == topic.id).first() is None
def ... | [
"flask_login.login_user",
"flaskbb.forum.models.Topic.query.filter"
] | [((228, 245), 'flask_login.login_user', 'login_user', (['guest'], {}), '(guest)\n', (238, 245), False, 'from flask_login import login_user\n'), ((418, 434), 'flask_login.login_user', 'login_user', (['user'], {}), '(user)\n', (428, 434), False, 'from flask_login import login_user\n'), ((671, 697), 'flask_login.login_use... |
from django.db import models
from django.core.validators import MinValueValidator, MaxLengthValidator
class Brand(models.Model):
class Genre(models.TextChoices):
HIP_HOP = 'HH'
SYNTH_POP = 'SP'
ALTERNATIVE_ROCK = 'AR'
genre = models.fields.CharField(choices=Genre.choices, max_length=5... | [
"django.db.models.ForeignKey",
"django.db.models.fields.IntegerField",
"django.db.models.fields.URLField",
"django.db.models.fields.BooleanField",
"django.db.models.fields.CharField"
] | [((261, 321), 'django.db.models.fields.CharField', 'models.fields.CharField', ([], {'choices': 'Genre.choices', 'max_length': '(5)'}), '(choices=Genre.choices, max_length=5)\n', (284, 321), False, 'from django.db import models\n'), ((333, 372), 'django.db.models.fields.CharField', 'models.fields.CharField', ([], {'max_... |
# -*- coding: utf-8 -*-
# Copyright (c) 2016 by University of Kassel and Fraunhofer Institute for Wind Energy and Energy
# System Technology (IWES), Kassel. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
from sys import stderr
from numpy imp... | [
"numpy.ones",
"numpy.conj",
"numpy.exp",
"sys.stderr.write",
"numpy.zeros",
"numba.jit",
"numpy.empty",
"numpy.argsort",
"numpy.nonzero",
"numpy.resize",
"scipy.sparse.csr_matrix"
] | [((606, 636), 'numba.jit', 'jit', ([], {'nopython': '(True)', 'cache': '(True)'}), '(nopython=True, cache=True)\n', (609, 636), False, 'from numba import jit\n'), ((945, 976), 'numpy.empty', 'empty', (['(nb * 5)'], {'dtype': 'complex128'}), '(nb * 5, dtype=complex128)\n', (950, 976), False, 'from numpy import ones, con... |
import pyftdi.ftdi as ftdi
import threading
import time
vendor = 0x0403
product = 0x6001
class OpenDmxUsb(threading.Thread):
def __init__(self):
super().__init__()
self.baud_rate = 250000
self.data_bits = 8
self.stop_bits = 2
self.parity = 'N'
self.flow_ctrl = ''
... | [
"pyftdi.ftdi.Ftdi",
"time.sleep"
] | [((457, 468), 'pyftdi.ftdi.Ftdi', 'ftdi.Ftdi', ([], {}), '()\n', (466, 468), True, 'import pyftdi.ftdi as ftdi\n'), ((1405, 1420), 'time.sleep', 'time.sleep', (['(0.1)'], {}), '(0.1)\n', (1415, 1420), False, 'import time\n')] |
### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed... | [
"bpy.types.UILayout.icon",
"hashlib.md5"
] | [((1167, 1180), 'hashlib.md5', 'hashlib.md5', ([], {}), '()\n', (1178, 1180), False, 'import bpy, time, sys, hashlib\n'), ((2394, 2416), 'bpy.types.UILayout.icon', 'UILayout.icon', (['id_data'], {}), '(id_data)\n', (2407, 2416), False, 'from bpy.types import UILayout\n')] |
import setuptools
requirements = [
'xmltodict',
'requests',
]
setuptools.setup(
name="wmapi",
version="0.1",
url="https://github.com/sellerzoncom/wmapi",
author="SellerZon",
author_email="<EMAIL>",
description="Python Client for Walmart Canada Marketplace API",
long_description=op... | [
"setuptools.find_packages"
] | [((410, 436), 'setuptools.find_packages', 'setuptools.find_packages', ([], {}), '()\n', (434, 436), False, 'import setuptools\n')] |
# Databricks notebook source
# MAGIC %md
# MAGIC #### PALET Sprint Demo:
# MAGIC 1. Income Bracket by Group
# MAGIC 2. Age Range by Group
# MAGIC 3. Eligible but Not Enrolled
# MAGIC 4. Enhanced Class Function Logging
# MAGIC %md
# MAGIC Start by importing Enrollment, Eligibility, and PaletMetadata from PALET.
# COM... | [
"palet.Eligibility.Eligibility",
"palet.Enrollment.Enrollment"
] | [((2238, 2254), 'palet.Eligibility.Eligibility', 'Eligibility', (['api'], {}), '(api)\n', (2249, 2254), False, 'from palet.Eligibility import Eligibility\n'), ((705, 717), 'palet.Enrollment.Enrollment', 'Enrollment', ([], {}), '()\n', (715, 717), False, 'from palet.Enrollment import Enrollment\n')] |
"""Simple hello world Nodejs example based on the serverless pattern:
Amazon API Gateway to AWS Lambda: https://serverlessland.com/patterns/apigw-lambda-cdk
Source: https://github.com/aws-samples/serverless-patterns/tree/main/apigw-lambda-cdk
"""
import logging
import json
import os
BENCHMARK_CONFIG = """
apigw_node... | [
"json.load",
"logging.info"
] | [((1309, 1321), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1318, 1321), False, 'import json\n'), ((1420, 1472), 'logging.info', 'logging.info', (['f"""service endpoint={spec[\'endpoint\']}"""'], {}), '(f"service endpoint={spec[\'endpoint\']}")\n', (1432, 1472), False, 'import logging\n')] |
# Generated by Django 3.1.7 on 2021-02-24 06:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('portfolio', '0006_client'),
]
operations = [
migrations.RemoveField(
model_name='client',
name='icon',
),
... | [
"django.db.migrations.RemoveField",
"django.db.models.ManyToManyField"
] | [((225, 281), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""client"""', 'name': '"""icon"""'}), "(model_name='client', name='icon')\n", (247, 281), False, 'from django.db import migrations, models\n'), ((326, 386), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([]... |
import argparse
import sys
import click
import matplotlib.pyplot as plt
import torch
import torch.nn.functional as F
from torch import nn, optim
from torch.utils.data import DataLoader, Dataset
#from data import mnist
from src.models.model import MyAwesomeConvolutionalModel # MyAwesomeModel
@click.command()
@click... | [
"click.argument",
"matplotlib.pyplot.savefig",
"torch.load",
"torch.exp",
"torch.utils.data.Dataset",
"matplotlib.pyplot.figure",
"torch.nn.NLLLoss",
"torch.utils.data.DataLoader",
"src.models.model.MyAwesomeConvolutionalModel",
"click.command"
] | [((298, 313), 'click.command', 'click.command', ([], {}), '()\n', (311, 313), False, 'import click\n'), ((315, 349), 'click.argument', 'click.argument', (['"""lr_1"""'], {'type': 'float'}), "('lr_1', type=float)\n", (329, 349), False, 'import click\n'), ((351, 387), 'click.argument', 'click.argument', (['"""epochs_1"""... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-08-25 18:41
from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pinax_stripe', '0008_auto_20170509_1736'),
]
operati... | [
"django.db.models.ForeignKey"
] | [((438, 579), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'blank': '(True)', 'null': '(True)', 'on_delete': 'django.db.models.deletion.CASCADE', 'related_name': '"""transfers"""', 'to': '"""pinax_stripe.Event"""'}), "(blank=True, null=True, on_delete=django.db.models.\n deletion.CASCADE, related_name='... |
from datetime import datetime
from pretty_timedelta import pretty_timedelta
__author__ = 'gautam'
def pretty_time(datetime_value):
now = datetime.now()
delta = datetime_value - now
return pretty_timedelta(delta)
| [
"datetime.datetime.now",
"pretty_timedelta.pretty_timedelta"
] | [((143, 157), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (155, 157), False, 'from datetime import datetime\n'), ((203, 226), 'pretty_timedelta.pretty_timedelta', 'pretty_timedelta', (['delta'], {}), '(delta)\n', (219, 226), False, 'from pretty_timedelta import pretty_timedelta\n')] |
import numpy as np
from scipy import optimize
import math
import matplotlib.pyplot as plt
import matplotlib as mpl
import ipywidgets as widgets
from ipywidgets import interact, interact_manual
def interactive_capdemand(q_0,a,a_base,amin,amax,b_0,b_base,bmin,bmax,k_0,k_base,kmin,kmax,theta,theta_base,thetamin,thetamax,... | [
"numpy.ones",
"matplotlib.pyplot.figure",
"numpy.empty",
"ipywidgets.FloatSlider",
"matplotlib.pyplot.legend"
] | [((388, 406), 'numpy.empty', 'np.empty', (['q_0.size'], {}), '(q_0.size)\n', (396, 406), True, 'import numpy as np\n'), ((752, 802), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'frameon': '(False)', 'figsize': '(8, 5)', 'dpi': '(100)'}), '(frameon=False, figsize=(8, 5), dpi=100)\n', (762, 802), True, 'import matplo... |
import os
import malmoenv
import argparse
from pathlib import Path
import time
from PIL import Image
from collections import deque
import gym
from gym import spaces
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from a2c_ppo_acktr import algo, utils
f... | [
"a2c_ppo_acktr.storage.RolloutStorage",
"time.sleep",
"torch.from_numpy",
"torch.cuda.is_available",
"numpy.mean",
"a2c_ppo_acktr.utils.cleanup_log_dir",
"collections.deque",
"malmoenv.make",
"pathlib.Path",
"torch.set_num_threads",
"numpy.max",
"numpy.min",
"arguments.get_args",
"os.path.... | [((596, 606), 'arguments.get_args', 'get_args', ([], {}), '()\n', (604, 606), False, 'from arguments import get_args\n'), ((717, 745), 'torch.manual_seed', 'torch.manual_seed', (['args.seed'], {}), '(args.seed)\n', (734, 745), False, 'import torch\n'), ((750, 787), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_... |
#!/usr/bin/env python
# Copyright 2014-2019 The PySCF Developers. 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
#
# U... | [
"pyscf.gto.Mole",
"pyscf.scf.UHF",
"pyscf.lib.logger.timer",
"pyscf.gto.M",
"time.clock",
"pyscf.prop.magnetizability.rhf._get_dia_1e",
"pyscf.lib.logger.Logger",
"numpy.dot",
"numpy.einsum",
"pyscf.lib.finger",
"pyscf.prop.nmr.uhf.solve_mo1",
"pyscf.scf.jk.get_jk",
"time.time"
] | [((1332, 1357), 'numpy.dot', 'numpy.dot', (['orboa', 'orboa.T'], {}), '(orboa, orboa.T)\n', (1341, 1357), False, 'import numpy\n'), ((1369, 1394), 'numpy.dot', 'numpy.dot', (['orbob', 'orbob.T'], {}), '(orbob, orbob.T)\n', (1378, 1394), False, 'import numpy\n'), ((1429, 1484), 'numpy.dot', 'numpy.dot', (['(orboa * mo_e... |
import os
import sys
from setuptools import setup, find_packages
from fnmatch import fnmatchcase
from distutils.util import convert_path
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
standard_exclude = ('*.pyc', '*~... | [
"os.listdir",
"fnmatch.fnmatchcase",
"distutils.util.convert_path",
"setuptools.find_packages",
"os.path.join",
"os.path.dirname",
"os.path.isdir"
] | [((161, 186), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (176, 186), False, 'import os\n'), ((198, 229), 'os.path.join', 'os.path.join', (['here', '"""README.md"""'], {}), "(here, 'README.md')\n", (210, 229), False, 'import os\n'), ((717, 734), 'os.listdir', 'os.listdir', (['where'], {}),... |
import os
import shutil
import tempfile
from tuf_on_a_plane.models.common import Filepath
from tuf_on_a_plane.repository import Config, JSONRepository, Target
def test_e2e_succeeds():
orig_metadata_cache = "tests/data/repository/metadata"
temp_metadata_cache = tempfile.TemporaryDirectory()
temp_targets_... | [
"tempfile.TemporaryDirectory",
"tuf_on_a_plane.repository.Config",
"os.path.exists",
"shutil.copytree",
"tuf_on_a_plane.repository.JSONRepository"
] | [((273, 302), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (300, 302), False, 'import tempfile\n'), ((328, 357), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (355, 357), False, 'import tempfile\n'), ((363, 449), 'shutil.copytree', 'shutil.copytree', ... |
from main.models import AbstractArticlePage
from taggit.models import TaggedItemBase
from modelcluster.fields import ParentalKey
from modelcluster.contrib.taggit import ClusterTaggableManager
from django.db import models
class BlogPanelTag(TaggedItemBase):
content_object = ParentalKey(
'ArticleEx',
... | [
"modelcluster.fields.ParentalKey",
"modelcluster.contrib.taggit.ClusterTaggableManager"
] | [((281, 366), 'modelcluster.fields.ParentalKey', 'ParentalKey', (['"""ArticleEx"""'], {'related_name': '"""tagged_items2"""', 'on_delete': 'models.CASCADE'}), "('ArticleEx', related_name='tagged_items2', on_delete=models.CASCADE\n )\n", (292, 366), False, 'from modelcluster.fields import ParentalKey\n'), ((444, 502)... |
from serpent.game_launcher import GameLauncher, GameLauncherException
from serpent.utilities import is_linux, is_macos, is_windows
import shlex
import subprocess
import webbrowser
class SteamGameLauncher(GameLauncher):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def launch(self, **kwar... | [
"shlex.split",
"webbrowser.open",
"serpent.utilities.is_macos",
"serpent.game_launcher.GameLauncherException",
"serpent.utilities.is_windows",
"serpent.utilities.is_linux"
] | [((734, 744), 'serpent.utilities.is_linux', 'is_linux', ([], {}), '()\n', (742, 744), False, 'from serpent.utilities import is_linux, is_macos, is_windows\n'), ((451, 508), 'serpent.game_launcher.GameLauncherException', 'GameLauncherException', (['"""An \'app_id\' kwarg is required..."""'], {}), '("An \'app_id\' kwarg ... |
# Calls Music 1 - Telegram bot for streaming audio in group calls
# Copyright (C) 2021 <NAME>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at y... | [
"DaisyXMusic.services.queues.queues.get",
"DaisyXMusic.services.queues.queues.clear",
"DaisyXMusic.services.queues.queues.is_empty",
"pytgcalls.GroupCall",
"DaisyXMusic.services.queues.queues.task_done"
] | [((1090, 1107), 'pytgcalls.GroupCall', 'GroupCall', (['client'], {}), '(client)\n', (1099, 1107), False, 'from pytgcalls import GroupCall\n'), ((1209, 1234), 'DaisyXMusic.services.queues.queues.task_done', 'queues.task_done', (['chat_id'], {}), '(chat_id)\n', (1225, 1234), False, 'from DaisyXMusic.services.queues impor... |
import asyncio
import json
import pytest
import privatebinapi
from privatebinapi import common, deletion, download, upload
from tests import MESSAGE, RESPONSE_DATA, SERVERS_AND_FILES
@pytest.mark.parametrize("server, file", SERVERS_AND_FILES)
def test_full(server, file):
send_data = privatebinapi.send(
... | [
"privatebinapi.deletion.process_url",
"privatebinapi.send",
"privatebinapi.delete",
"privatebinapi.get",
"pytest.mark.parametrize",
"privatebinapi.download.extract_passphrase",
"asyncio.sleep",
"json.JSONDecodeError",
"privatebinapi.send_async",
"privatebinapi.get_async",
"privatebinapi.delete_a... | [((188, 246), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""server, file"""', 'SERVERS_AND_FILES'], {}), "('server, file', SERVERS_AND_FILES)\n", (211, 246), False, 'import pytest\n'), ((1445, 1500), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""server, _"""', 'SERVERS_AND_FILES'], {}), "('s... |
from django.db import models
from django.contrib.auth.models import User
from django import forms
# Create your models here.
class Parceiro(models.Model):
class Meta:
verbose_name = "Parceiro"
verbose_name_plural = "Parceiros"
razao_social = models.CharField(max_length=80, verbose_name="Razão... | [
"django.db.models.OneToOneField",
"django.db.models.ForeignKey",
"django.db.models.ManyToManyField",
"django.db.models.BooleanField",
"django.db.models.DateTimeField",
"django.db.models.DecimalField",
"django.db.models.CharField"
] | [((269, 329), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(80)', 'verbose_name': '"""Razão social"""'}), "(max_length=80, verbose_name='Razão social')\n", (285, 329), False, 'from django.db import models\n'), ((350, 381), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '... |
import re
import string
import numpy as np
import random
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import seaborn as sns
from plotly import graph_objs as go
import plotly.express as px
import plotly.figure_factory as ff
from collections import Counter
from datet... | [
"re.escape",
"nltk.corpus.stopwords.words",
"read_file.dataframe_from_file",
"plotly.express.bar",
"pandas.Grouper",
"collections.Counter",
"matplotlib.pyplot.figure",
"seaborn.kdeplot",
"re.sub"
] | [((647, 676), 'read_file.dataframe_from_file', 'dataframe_from_file', (['filename'], {}), '(filename)\n', (666, 676), False, 'from read_file import dataframe_from_file\n'), ((979, 1008), 're.sub', 're.sub', (['"""\\\\[.*?\\\\]"""', '""""""', 'text'], {}), "('\\\\[.*?\\\\]', '', text)\n", (985, 1008), False, 'import re\... |
import json
import logging
import os
import sys
from typing import Any, Iterator, Optional
import boto3
from botocore.exceptions import ClientError
from chalice import Chalice
app = Chalice(app_name="swarm-lifecycle-event-handler")
LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(os.getenv("GRAPL_LOG_LEVEL", "ER... | [
"logging.getLogger",
"json.loads",
"logging.StreamHandler",
"boto3.client",
"os.getenv",
"json.dumps",
"os.environ.get",
"boto3.resource",
"chalice.Chalice"
] | [((184, 233), 'chalice.Chalice', 'Chalice', ([], {'app_name': '"""swarm-lifecycle-event-handler"""'}), "(app_name='swarm-lifecycle-event-handler')\n", (191, 233), False, 'from chalice import Chalice\n'), ((244, 271), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (261, 271), False, 'impor... |
### ------------------------------------------------------------------------- ###
### Create binary files of raw stim vid luminance values fitted to world cam stim vid presentation timings
### use world camera vids for timing, use raw vid luminance values extracted via bonsai
### also save world cam luminance as sanity... | [
"zipfile.ZipFile",
"matplotlib.image.imread",
"time.sleep",
"numpy.array",
"cv2.destroyAllWindows",
"datetime.timedelta",
"logging.info",
"numpy.genfromtxt",
"numpy.save",
"os.remove",
"os.path.exists",
"os.listdir",
"argparse.ArgumentParser",
"shutil.copy2",
"logging.INFO",
"numpy.emp... | [((1262, 1273), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1271, 1273), False, 'import os\n'), ((1388, 1411), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (1409, 1411), False, 'import datetime\n'), ((2942, 2985), 'os.path.join', 'os.path.join', (['analysed_drive', '"""rawStimLums"""'], {}), "(a... |
import copy
from datetime import datetime
from typing import Callable
import numpy as np
import torch
from ga.individual import statistics
from utils.timing import timing
class Population:
def __init__(self, individual, pop_size, max_generation, p_mutation, p_crossover, p_inversion):
self.pop_size = pop... | [
"ga.individual.statistics",
"datetime.datetime.now",
"torch.save",
"copy.deepcopy",
"numpy.save"
] | [((2579, 2610), 'ga.individual.statistics', 'statistics', (['self.new_population'], {}), '(self.new_population)\n', (2589, 2610), False, 'from ga.individual import statistics\n'), ((2852, 2883), 'ga.individual.statistics', 'statistics', (['self.new_population'], {}), '(self.new_population)\n', (2862, 2883), False, 'fro... |
""" Basic tests for ParaRead """
import itertools
import os
import pytest
from pysam import AlignmentFile
from pararead.exceptions import \
CommandOrderException, IllegalChunkException, \
MissingHeaderException, MissingOutputFileException
from pararead.processor import ParaReadProcessor
from tests import \
... | [
"os.path.exists",
"pytest.mark.skip",
"itertools.product",
"os.path.isfile",
"pytest.mark.parametrize",
"tests.helpers.IdentityProcessor",
"pytest.raises",
"pytest.fixture",
"tests.helpers.loglines"
] | [((13483, 13518), 'pytest.mark.skip', 'pytest.mark.skip', (['"""Not implemented"""'], {}), "('Not implemented')\n", (13499, 13518), False, 'import pytest\n'), ((585, 685), 'pytest.mark.parametrize', 'pytest.mark.parametrize', ([], {'argnames': '"""filepath"""', 'argvalues': '[PATH_ALIGNED_FILE, PATH_UNALIGNED_FILE]'}),... |
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import List
import numpy as np
import pandas as pd
@dataclass
class Recall:
docid: str
n_items: int
score: float
@classmethod
def from_line(cls, line: str) -> Recall:
try:
... | [
"pandas.DataFrame",
"numpy.array"
] | [((1547, 1638), 'pandas.DataFrame', 'pd.DataFrame', (['mat'], {'index': 'docids', 'columns': '[r.n_items for r in info_list[:mat.shape[1]]]'}), '(mat, index=docids, columns=[r.n_items for r in info_list[:mat.\n shape[1]]])\n', (1559, 1638), True, 'import pandas as pd\n'), ((1462, 1510), 'numpy.array', 'np.array', ([... |
#!/usr/bin/env python3
""" Generate TERRA REF canopy cover """
import argparse
import logging
import os
import stat
import subprocess
from typing import Optional
import globus_sdk
GLOBUS_ENDPOINT = 'Terraref'
GLOBUS_PATH = '/ua-mac/public/season-6/Level_2/rgb_fullfield/'
LOCAL_SAVE_PATH = os.path.realpath(os.getcwd(... | [
"globus_sdk.TransferClient",
"logging.getLogger",
"logging.debug",
"logging.error",
"os.remove",
"os.path.exists",
"argparse.ArgumentParser",
"subprocess.run",
"os.chmod",
"globus_sdk.TransferData",
"globus_sdk.NativeAppAuthClient",
"os.path.splitext",
"logging.warning",
"os.path.dirname",... | [((310, 321), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (319, 321), False, 'import os\n'), ((721, 769), 'globus_sdk.NativeAppAuthClient', 'globus_sdk.NativeAppAuthClient', (['GLOBUS_CLIENT_ID'], {}), '(GLOBUS_CLIENT_ID)\n', (751, 769), False, 'import globus_sdk\n'), ((1319, 1498), 'globus_sdk.RefreshTokenAuthorizer',... |
"""
Copyright 2021 ETH Zurich, author: <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writin... | [
"numpy.tile",
"numpy.abs",
"xarray.ufuncs.log",
"numpy.isnan",
"numpy.timedelta64",
"numpy.meshgrid",
"numpy.arange"
] | [((1453, 1478), 'xarray.ufuncs.log', 'xu.log', (['data.loc[varname]'], {}), '(data.loc[varname])\n', (1459, 1478), True, 'import xarray.ufuncs as xu\n'), ((2873, 2933), 'numpy.meshgrid', 'np.meshgrid', (['constant_maps.longitude', 'constant_maps.latitude'], {}), '(constant_maps.longitude, constant_maps.latitude)\n', (2... |
# Import modules
from ctypes import windll
""" Open cdrom """
def Open():
return windll.WINMM.mciSendStringW(u"set cdaudio door open", None, 0, None)
""" Close cdrom """
def Close():
return windll.WINMM.mciSendStringW(u"set cdaudio door closed", None, 0, None) | [
"ctypes.windll.WINMM.mciSendStringW"
] | [((93, 161), 'ctypes.windll.WINMM.mciSendStringW', 'windll.WINMM.mciSendStringW', (['u"""set cdaudio door open"""', 'None', '(0)', 'None'], {}), "(u'set cdaudio door open', None, 0, None)\n", (120, 161), False, 'from ctypes import windll\n'), ((211, 281), 'ctypes.windll.WINMM.mciSendStringW', 'windll.WINMM.mciSendStrin... |
import cv2
import numpy as np
import matplotlib.pyplot as plt
from glob import glob
# K-means step1
def k_means_step1(img, Class=5):
# get shape
H, W, C = img.shape
# initiate random seed
np.random.seed(0)
# reshape
img = np.reshape(img, (H * W, -1))
# select one index randomly
i = np.random.choice(np.ara... | [
"numpy.reshape",
"cv2.imshow",
"numpy.sum",
"numpy.zeros",
"cv2.destroyAllWindows",
"numpy.random.seed",
"numpy.argmin",
"cv2.waitKey",
"numpy.arange",
"cv2.imread"
] | [((826, 851), 'cv2.imshow', 'cv2.imshow', (['"""result"""', 'out'], {}), "('result', out)\n", (836, 851), False, 'import cv2\n'), ((852, 866), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (863, 866), False, 'import cv2\n'), ((867, 890), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (888, ... |
from unittest.mock import patch
from django.core.management import call_command
from django.db.utils import OperationalError
from django.test import TestCase
# Uses Mocking to test the database.
class CommandsTestCase(TestCase):
def test_wait_for_db_ready(self):
# Test to wait for the db to become avail... | [
"unittest.mock.patch",
"django.core.management.call_command"
] | [((689, 727), 'unittest.mock.patch', 'patch', (['"""time.sleep"""'], {'return_value': 'None'}), "('time.sleep', return_value=None)\n", (694, 727), False, 'from unittest.mock import patch\n'), ((499, 553), 'unittest.mock.patch', 'patch', (['"""django.db.utils.ConnectionHandler.__getitem__"""'], {}), "('django.db.utils.C... |
from django_bleach.models import BleachField
from tinymce.models import HTMLField
from django.conf import settings
from django.core.validators import URLValidator
from django.db.models import URLField
from django.forms.fields import URLField as FormURLField
################
# JobsURLField #
################
JobsURLV... | [
"django.core.validators.URLValidator"
] | [((331, 373), 'django.core.validators.URLValidator', 'URLValidator', ([], {'schemes': 'settings.URL_SCHEMES'}), '(schemes=settings.URL_SCHEMES)\n', (343, 373), False, 'from django.core.validators import URLValidator\n')] |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | [
"msrest.pipeline.ClientRawResponse"
] | [((2548, 2589), 'msrest.pipeline.ClientRawResponse', 'ClientRawResponse', (['deserialized', 'response'], {}), '(deserialized, response)\n', (2565, 2589), False, 'from msrest.pipeline import ClientRawResponse\n'), ((4163, 4204), 'msrest.pipeline.ClientRawResponse', 'ClientRawResponse', (['deserialized', 'response'], {})... |
import numpy as np
from scipy import stats
def uma_função_fictícia():
"""Não faz nada, mas tem requisitos. :)"""
matriz1 = np.random.rand(5, 5)
print(stats.describe(matriz1))
if __name__ == '__main__':
uma_função_fictícia()
| [
"scipy.stats.describe",
"numpy.random.rand"
] | [((133, 153), 'numpy.random.rand', 'np.random.rand', (['(5)', '(5)'], {}), '(5, 5)\n', (147, 153), True, 'import numpy as np\n'), ((164, 187), 'scipy.stats.describe', 'stats.describe', (['matriz1'], {}), '(matriz1)\n', (178, 187), False, 'from scipy import stats\n')] |
import os
import tarfile
from github3 import login
token = os.getenv('GITHUB_TOKEN')
gh = login(token=token)
repo = gh.repository('gamechanger', 'dusty')
version = os.getenv('VERSION')
prerelease = os.getenv('PRERELEASE') == 'true'
release_name = version
release = repo.create_release(version, name=release_name, pre... | [
"github3.login",
"tarfile.open",
"os.path.join",
"os.getenv"
] | [((61, 86), 'os.getenv', 'os.getenv', (['"""GITHUB_TOKEN"""'], {}), "('GITHUB_TOKEN')\n", (70, 86), False, 'import os\n'), ((92, 110), 'github3.login', 'login', ([], {'token': 'token'}), '(token=token)\n', (97, 110), False, 'from github3 import login\n'), ((167, 187), 'os.getenv', 'os.getenv', (['"""VERSION"""'], {}), ... |
from pygears.typing import Tuple, Unit, TemplateArgumentsError, Uint
from nose.tools import raises
def test_inheritance():
assert Tuple[1, 2].base is Tuple
def test_equality():
assert Tuple[1] == Tuple[1]
assert Tuple[1, 2] != Tuple[1, 3]
assert Tuple[1, 2] != Tuple[1, 2, 3]
assert Tuple[1, Tupl... | [
"nose.tools.raises"
] | [((2010, 2040), 'nose.tools.raises', 'raises', (['TemplateArgumentsError'], {}), '(TemplateArgumentsError)\n', (2016, 2040), False, 'from nose.tools import raises\n'), ((2684, 2702), 'nose.tools.raises', 'raises', (['IndexError'], {}), '(IndexError)\n', (2690, 2702), False, 'from nose.tools import raises\n'), ((3362, 3... |
from app import app
from flask import render_template
@app.route('/')
def index():
page = { 'title': 'Home',
'meta_title': 'A meta title',
'meta_description': 'A meta description' }
return render_template("index.html", page=page)
| [
"flask.render_template",
"app.app.route"
] | [((56, 70), 'app.app.route', 'app.route', (['"""/"""'], {}), "('/')\n", (65, 70), False, 'from app import app\n'), ((224, 264), 'flask.render_template', 'render_template', (['"""index.html"""'], {'page': 'page'}), "('index.html', page=page)\n", (239, 264), False, 'from flask import render_template\n')] |
import io
from typing import List, Any, IO, TYPE_CHECKING
from quo.ansi import AnsiDecoder
from quo.text import Text
if TYPE_CHECKING:
from .termimal import Terminal
class FileProxy(io.TextIOBase):
"""Wraps a file (e.g. sys.stdout) and redirects writes to a console."""
def __init__(self, console: "Term... | [
"quo.ansi.AnsiDecoder",
"quo.text.Text"
] | [((479, 492), 'quo.ansi.AnsiDecoder', 'AnsiDecoder', ([], {}), '()\n', (490, 492), False, 'from quo.ansi import AnsiDecoder\n'), ((1291, 1301), 'quo.text.Text', 'Text', (['"""\n"""'], {}), "('\\n')\n", (1295, 1301), False, 'from quo.text import Text\n')] |
"""Utilities used in the Kadenze Academy Course on Deep Learning w/ Tensorflow.
Creative Applications of Deep Learning w/ Tensorflow.
Kadenze, Inc.
<NAME>
Copyright <NAME>, June 2016.
"""
import matplotlib.pyplot as plt
import tensorflow as tf
import urllib
import numpy as np
import zipfile
import os
from scipy.io im... | [
"tarfile.open",
"numpy.sqrt",
"tensorflow.shape",
"zipfile.ZipFile",
"tensorflow.multiply",
"numpy.array",
"tensorflow.log",
"os.walk",
"os.path.exists",
"tensorflow.Graph",
"numpy.mean",
"numpy.reshape",
"tensorflow.random_normal",
"os.listdir",
"tensorflow.pow",
"tensorflow.Session",... | [((664, 685), 'os.path.exists', 'os.path.exists', (['fname'], {}), '(fname)\n', (678, 685), False, 'import os\n'), ((1004, 1073), 'six.moves.urllib.request.urlretrieve', 'urllib.request.urlretrieve', (['path'], {'filename': 'fname', 'reporthook': 'progress'}), '(path, filename=fname, reporthook=progress)\n', (1030, 107... |
import numpy
import time
class TrainingLog:
def __init__(self, file_name, iteartions_skip_log = 10):
self.iterations = 0
self.episodes = 0
self.episode_score_sum = 0.0
self.episode_iterations = 0.0
self.episode_iterations_filtered = 0.0
se... | [
"time.time"
] | [((429, 440), 'time.time', 'time.time', ([], {}), '()\n', (438, 440), False, 'import time\n'), ((474, 485), 'time.time', 'time.time', ([], {}), '()\n', (483, 485), False, 'import time\n'), ((1382, 1393), 'time.time', 'time.time', ([], {}), '()\n', (1391, 1393), False, 'import time\n')] |
import logging
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from common.customized_logging import configure_logging
from style.api.middleware import add_middleware
from style.api.routers import prediction
from style.config import settings
configure_logging()
logger = logging.getLo... | [
"logging.getLogger",
"fastapi.FastAPI",
"uvicorn.run",
"common.customized_logging.configure_logging",
"style.api.middleware.add_middleware"
] | [((278, 297), 'common.customized_logging.configure_logging', 'configure_logging', ([], {}), '()\n', (295, 297), False, 'from common.customized_logging import configure_logging\n'), ((307, 334), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (324, 334), False, 'import logging\n'), ((342, 3... |
__version__ = '0.9.20'
__app_name__ = 'bauh'
import os
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
LOGS_PATH = '/tmp/{}/logs'.format(__app_name__)
| [
"os.path.abspath"
] | [((83, 108), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (98, 108), False, 'import os\n')] |
"""
Unit tests for EDD's REST API.
Note that tests here purposefully hard-code simple object serialization that's
also coded seperately in EDD's REST API. This should help to detect when REST
API code changes in EDD accidentally affect client code.
"""
import codecs
import csv
import logging
from django.contrib.auth... | [
"logging.getLogger",
"edd.profile.factory.UserFactory",
"django.contrib.auth.get_user_model",
"codecs.iterdecode",
"django.contrib.contenttypes.models.ContentType.objects.get_for_model",
"threadlocals.threadlocals.set_thread_variable",
"main.tests.factory.MeasurementFactory",
"main.tests.factory.Strai... | [((782, 809), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (799, 809), False, 'import logging\n'), ((862, 902), 'django.contrib.contenttypes.models.ContentType.objects.get_for_model', 'ContentType.objects.get_for_model', (['model'], {}), '(model)\n', (895, 902), False, 'from django.cont... |
import discord
from core.classes import Cog_Extension
from discord.ext import commands
from core.setup import client, rsp
import core.functions as func
import asyncio
class Main(Cog_Extension):
@commands.command()
async def ping(self, ctx):
await ctx.send(f':stopwatch: {round(self.bot.latency * 1000)... | [
"discord.ext.commands.Cog.listener",
"discord.utils.get",
"discord.ext.commands.command",
"asyncio.sleep"
] | [((202, 220), 'discord.ext.commands.command', 'commands.command', ([], {}), '()\n', (218, 220), False, 'from discord.ext import commands\n'), ((335, 358), 'discord.ext.commands.Cog.listener', 'commands.Cog.listener', ([], {}), '()\n', (356, 358), False, 'from discord.ext import commands\n'), ((521, 539), 'discord.ext.c... |
import unittest
import sys
from panoptes_client.workflow import Workflow
from panoptes_client.caesar import Caesar
if sys.version_info <= (3, 0):
from mock import patch
else:
from unittest.mock import patch
class TestWorkflow(unittest.TestCase):
def setUp(self):
super().setUp()
caesar_po... | [
"panoptes_client.workflow.Workflow",
"unittest.mock.patch.object"
] | [((331, 364), 'unittest.mock.patch.object', 'patch.object', (['Caesar', '"""http_post"""'], {}), "(Caesar, 'http_post')\n", (343, 364), False, 'from unittest.mock import patch\n'), ((392, 424), 'unittest.mock.patch.object', 'patch.object', (['Caesar', '"""http_get"""'], {}), "(Caesar, 'http_get')\n", (404, 424), False,... |
import unittest
import os
import torch
from torch.optim import Optimizer
import apex
from apex.multi_tensor_apply import multi_tensor_applier
from itertools import product
class RefLAMB(Optimizer):
r"""Implements Lamb algorithm.
It has been proposed in `Large Batch Optimization for Deep Learning: Training BE... | [
"apex.multi_tensor_apply.multi_tensor_applier",
"torch.rand_like",
"torch.cuda.device",
"itertools.product",
"torch.cuda.device_count",
"torch.cuda.manual_seed",
"os.path.realpath",
"torch.tensor",
"torch.cuda.synchronize",
"torch.zeros_like",
"unittest.main",
"unittest.skip",
"torch.zeros",... | [((8994, 9064), 'unittest.skip', 'unittest.skip', (['"""PyTorch optimizer is not numerically correct for fp16"""'], {}), "('PyTorch optimizer is not numerically correct for fp16')\n", (9007, 9064), False, 'import unittest\n'), ((11520, 11590), 'unittest.skip', 'unittest.skip', (['"""PyTorch optimizer is not numerically... |
# -*- coding: utf-8 -*-
import os
import sys
import time
import sys
import pycurl
def test():
URL = "http://www.baidu.com"
c = pycurl.Curl()
c.setopt(pycurl.URL, URL)
# 连接超时时间,5秒
c.setopt(pycurl.CONNECTTIMEOUT, 5)
# 下载超时时间,5秒
c.setopt(pycurl.TIMEOUT, 5)
c.setopt(pycurl.FORBID_REUSE, ... | [
"pycurl.Curl",
"sys.exit"
] | [((137, 150), 'pycurl.Curl', 'pycurl.Curl', ([], {}), '()\n', (148, 150), False, 'import pycurl\n'), ((713, 723), 'sys.exit', 'sys.exit', ([], {}), '()\n', (721, 723), False, 'import sys\n')] |
from unittest.mock import patch
from tacticalrmm.test import TacticalTestCase
from model_bakery import baker, seq
from itertools import cycle
from agents.models import Agent
from winupdate.models import WinUpdatePolicy
from .serializers import (
PolicyTableSerializer,
PolicySerializer,
PolicyTaskStatusSeri... | [
"model_bakery.baker.make",
"autotasks.models.AutomatedTask.objects.get",
"itertools.cycle",
"agents.models.Agent.objects.get",
"model_bakery.seq",
"model_bakery.baker.make_recipe",
"clients.models.Client.objects.all",
"winupdate.models.WinUpdatePolicy.objects.filter",
"agents.models.Agent.objects.fi... | [((2894, 2966), 'unittest.mock.patch', 'patch', (['"""automation.tasks.generate_agent_checks_from_policies_task.delay"""'], {}), "('automation.tasks.generate_agent_checks_from_policies_task.delay')\n", (2899, 2966), False, 'from unittest.mock import patch\n'), ((4146, 4218), 'unittest.mock.patch', 'patch', (['"""automa... |
#!/bin/python
from sys import exit
LOGFILE="access_log"
ERROR="404"
REDIRECTT=("303","301")
SUCCESS="200"
def parse_log(filename):
'''Parse log file and count errors'''
errors=redirects=oks=0
with open(filename) as file:
for line in file:
code = line.split()[-4]
... | [
"sys.exit"
] | [((602, 609), 'sys.exit', 'exit', (['(0)'], {}), '(0)\n', (606, 609), False, 'from sys import exit\n')] |
import pandas
import numpy as np
from sklearn import linear_model
#load the csv file
df = pandas.read_csv('heights_weights.csv')
# update the value with numbers
df['Gender'] = df['Gender'].replace(['Female'],0)
df['Gender'] = df['Gender'].replace(['Male'],1)
# convert to numpy array
data = df.to_numpy()
# taking the ... | [
"pandas.read_csv",
"sklearn.linear_model.LogisticRegression"
] | [((90, 128), 'pandas.read_csv', 'pandas.read_csv', (['"""heights_weights.csv"""'], {}), "('heights_weights.csv')\n", (105, 128), False, 'import pandas\n'), ((450, 510), 'sklearn.linear_model.LogisticRegression', 'linear_model.LogisticRegression', ([], {'C': '(1e+40)', 'solver': '"""newton-cg"""'}), "(C=1e+40, solver='n... |
#!/usr/bin/env python3
import os
import argparse
import gatenlphiltlab
import hiltnlp
from pycorenlp import StanfordCoreNLP
def get_sentiment(annotation,
server,
verbose=False,
normalize=True):
if normalize:
annotation_text = gatenlphiltlab.normalize(... | [
"argparse.ArgumentParser",
"gatenlphiltlab.AnnotationFile",
"gatenlphiltlab.normalize",
"pycorenlp.StanfordCoreNLP",
"hiltnlp.tag_speakers"
] | [((952, 1077), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Adds sentiment annotations over sentences within a HiLT GATE annotation file"""'}), "(description=\n 'Adds sentiment annotations over sentences within a HiLT GATE annotation file'\n )\n", (975, 1077), False, 'import argp... |
from collections import OrderedDict
from django.core.urlresolvers import reverse
from .drf_fields import drf_field_to_field
from .fields import Field
class ReactFormMeta(object):
def __init__(self, options=None):
self.fields = []
self.serializer_class = None
self.exclude = []
if o... | [
"collections.OrderedDict",
"django.core.urlresolvers.reverse"
] | [((951, 964), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (962, 964), False, 'from collections import OrderedDict\n'), ((1890, 1919), 'django.core.urlresolvers.reverse', 'reverse', (['self.create_url_name'], {}), '(self.create_url_name)\n', (1897, 1919), False, 'from django.core.urlresolvers import reve... |
import numpy as np
import logging
from collections import Counter
import pandas as pd
import jieba
import shelve
import gensim
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
# model = gensim.models.word2vec.Word2Vec.load('F:\\YX\\word2vec\\word2vec\\word2vec_wx')
... | [
"logging.basicConfig",
"jieba.cut",
"numpy.logaddexp",
"collections.Counter",
"numpy.dot",
"shelve.open"
] | [((134, 229), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s : %(levelname)s : %(message)s"""', 'level': 'logging.INFO'}), "(format='%(asctime)s : %(levelname)s : %(message)s',\n level=logging.INFO)\n", (153, 229), False, 'import logging\n'), ((535, 561), 'numpy.dot', 'np.dot', (['iwor... |
from os.path import join as path_join, \
isfile as path_isfile
from os import environ as os_environ
from msbuildpy.private.finder_util import parse_dotnetcli_msbuild_ver_output
from msbuildpy.searcher import add_default_finder
from msbuildpy.sysinspect import ARCH32, ARCH64, is_windows
def _win_dotnetcli_msbuil... | [
"msbuildpy.sysinspect.is_windows",
"os.path.join",
"os.path.isfile",
"msbuildpy.private.finder_util.parse_dotnetcli_msbuild_ver_output",
"msbuildpy.searcher.add_default_finder"
] | [((828, 870), 'msbuildpy.searcher.add_default_finder', 'add_default_finder', (['_win_dotnetcli_msbuild'], {}), '(_win_dotnetcli_msbuild)\n', (846, 870), False, 'from msbuildpy.searcher import add_default_finder\n'), ((486, 534), 'os.path.join', 'path_join', (['program_files', '"""dotnet"""', '"""dotnet.exe"""'], {}), "... |
import random
def minfree(l:list):
N = len(l) + 1
buffer = [False for i in range(0, N)]
for i in l:
if i < N:
buffer[i] = True
for i, flag in enumerate(buffer):
if flag is False:
return i
def main():
test_list = [random.randint(0, 100) for x in range(0, 99)]... | [
"random.randint"
] | [((275, 297), 'random.randint', 'random.randint', (['(0)', '(100)'], {}), '(0, 100)\n', (289, 297), False, 'import random\n')] |
from alexandria import app
app.run(port=5001)
| [
"alexandria.app.run"
] | [((28, 46), 'alexandria.app.run', 'app.run', ([], {'port': '(5001)'}), '(port=5001)\n', (35, 46), False, 'from alexandria import app\n')] |
import requests
from bs4 import BeautifulSoup
from ..common_functions import common_functions
from ..oger.ctrl.router import Router, PipelineServer
import codecs
import math
import os
def get_arrays_equality(arr1, arr2):
# This functions returns an array containing 0s and 1s
# 0 when arr1[i] != arr2[i] and 1 ... | [
"bs4.BeautifulSoup",
"requests.get"
] | [((7788, 7805), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (7800, 7805), False, 'import requests\n'), ((8724, 8762), 'bs4.BeautifulSoup', 'BeautifulSoup', (['response.content', '"""xml"""'], {}), "(response.content, 'xml')\n", (8737, 8762), False, 'from bs4 import BeautifulSoup\n')] |