code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import os
import pytest
from aml_pipeline_observability_func_sample.event_processor import process_event, to_run_metrics
from mock import patch, call, Mock
def test_process_event_raises_value_error_without_run_id():
# arrange
event = {}
# act/assert
with pytest.raises(ValueError):
process_eve... | [
"mock.patch",
"mock.patch.dict",
"aml_pipeline_observability_func_sample.event_processor.process_event",
"mock.Mock",
"aml_pipeline_observability_func_sample.event_processor.to_run_metrics",
"pytest.raises",
"mock.call"
] | [((333, 506), 'mock.patch.dict', 'patch.dict', (['os.environ', "{'SUBSCRIPTION_ID': 'test_subscription_id', 'AML_RESOURCE_GROUP':\n 'test_aml_resource_group', 'AML_WORKSPACE_NAME': 'test_aml_workspace_name'}"], {}), "(os.environ, {'SUBSCRIPTION_ID': 'test_subscription_id',\n 'AML_RESOURCE_GROUP': 'test_aml_resour... |
from coreapi import Document
from openapi_codec import OpenAPICodec
import os
test_filepath = os.path.join(os.path.dirname(__file__), 'petstore.json')
def test_decode():
test_content = open(test_filepath, 'rb').read()
codec = OpenAPICodec()
document = (codec.load(test_content))
assert isinstance(doc... | [
"os.path.dirname",
"openapi_codec.OpenAPICodec"
] | [((109, 134), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (124, 134), False, 'import os\n'), ((238, 252), 'openapi_codec.OpenAPICodec', 'OpenAPICodec', ([], {}), '()\n', (250, 252), False, 'from openapi_codec import OpenAPICodec\n')] |
"""
trajectory/log.py
Author: <NAME>
Configure a global logging system.
"""
import logging
def global_logger(name, debug=False):
"""
Generate a global logger object.
"""
#formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(module)s - %(message)s')
formatter = logging.Formatter(f... | [
"logging.getLogger",
"logging.Formatter",
"logging.StreamHandler"
] | [((301, 367), 'logging.Formatter', 'logging.Formatter', ([], {'fmt': '"""%(asctime)s - %(levelname)s - %(message)s"""'}), "(fmt='%(asctime)s - %(levelname)s - %(message)s')\n", (318, 367), False, 'import logging\n'), ((383, 406), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (404, 406), False, 'im... |
import numpy as np
import mfd
from matplotlib import pyplot as pl
n = 30
xr = np.linspace(0, 2*1.5, int(n*1.5))
yr = np.linspace(0, 2, n)
x, y = np.meshgrid(xr, yr)
z = np.exp(-x*x-y*y)
w = abs(xr[0]-xr[1])
a = mfd.sca(z, w)
b = np.load('data.npy')
pl.pcolormesh(x, y, (a-b)/a)
pl.colorbar()
ax = pl.gca()
ax.set_aspect... | [
"matplotlib.pyplot.gca",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.pcolormesh",
"numpy.exp",
"numpy.linspace",
"numpy.meshgrid",
"numpy.load",
"mfd.sca",
"matplotlib.pyplot.show"
] | [((118, 138), 'numpy.linspace', 'np.linspace', (['(0)', '(2)', 'n'], {}), '(0, 2, n)\n', (129, 138), True, 'import numpy as np\n'), ((146, 165), 'numpy.meshgrid', 'np.meshgrid', (['xr', 'yr'], {}), '(xr, yr)\n', (157, 165), True, 'import numpy as np\n'), ((170, 192), 'numpy.exp', 'np.exp', (['(-x * x - y * y)'], {}), '... |
import json
import logging
import os
from django.core.management.base import BaseCommand
from django.db import transaction
from inventory.models import Part, PartExternalId
logger = logging.getLogger(__name__) # pylint: disable=invalid-name
class Command(BaseCommand):
def add_arguments(self, parser):
... | [
"logging.getLogger",
"os.path.exists",
"inventory.models.Part.objects.filter",
"django.db.transaction.atomic",
"inventory.models.Part.objects.values_list",
"json.load",
"inventory.models.PartExternalId.objects.filter"
] | [((185, 212), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (202, 212), False, 'import logging\n'), ((495, 525), 'os.path.exists', 'os.path.exists', (['json_file_path'], {}), '(json_file_path)\n', (509, 525), False, 'import os\n'), ((940, 987), 'inventory.models.Part.objects.values_list'... |
# -*- coding: utf-8 -*-
from datetime import datetime
from watson.framework.support.jinja2 import filters
from watson.form import fields
class TestFilters(object):
def test_qualified_name(self):
assert filters.get_qualified_name(self) == 'tests.watson.framework.support.jinja2.test_filters.TestFilters'
... | [
"watson.framework.support.jinja2.filters.date",
"watson.framework.support.jinja2.filters.label",
"datetime.datetime.strptime",
"watson.form.fields.Text",
"watson.framework.support.jinja2.filters.merge_query_string",
"watson.framework.support.jinja2.filters.get_qualified_name"
] | [((361, 417), 'watson.form.fields.Text', 'fields.Text', ([], {'label': '"""Test"""', 'name': '"""test"""', 'definition': '(False)'}), "(label='Test', name='test', definition=False)\n", (372, 417), False, 'from watson.form import fields\n'), ((579, 653), 'watson.framework.support.jinja2.filters.merge_query_string', 'fil... |
"""
Duplex audio:
record from a source, play back on another output.
"""
import miniaudio
from time import sleep
backends = []
def choose_devices():
devices = miniaudio.Devices(backends=backends)
print("Available capture devices:")
captures = devices.get_captures()
for d in enumerate(captures, 1):
... | [
"miniaudio.DuplexStream",
"miniaudio.Devices",
"time.sleep"
] | [((168, 204), 'miniaudio.Devices', 'miniaudio.Devices', ([], {'backends': 'backends'}), '(backends=backends)\n', (185, 204), False, 'import miniaudio\n'), ((1000, 1140), 'miniaudio.DuplexStream', 'miniaudio.DuplexStream', ([], {'sample_rate': '(48000)', 'backends': 'backends', 'playback_device_id': "playback_dev['id']"... |
import pyaf.Bench.TS_datasets as tsds
import pyaf.Bench.MComp as mcomp
#tester1 = mcomp.cMComp_Tester(tsds.load_M1_comp());
#tester1.testSignals('')
#tester1.testAllSignals()
#tester2 = mcomp.cMComp_Tester(tsds.load_M2_comp());
#tester1.testSignals('')
#tester2.testAllSignals()
#tester3 = mcomp.cMComp_Tester(tsds.... | [
"pyaf.Bench.TS_datasets.load_M4_comp"
] | [((746, 774), 'pyaf.Bench.TS_datasets.load_M4_comp', 'tsds.load_M4_comp', (['"""FINANCE"""'], {}), "('FINANCE')\n", (763, 774), True, 'import pyaf.Bench.TS_datasets as tsds\n')] |
from django.db import models
# Create your models here.
class Category(models.Model):
name=models.CharField(max_length=50)
def __str__(self):
return self.name
def save_category(self):
self.save()
class Location(models.Model):
name= models.CharField(max_length=50)
def save_locati... | [
"django.db.models.TextField",
"django.db.models.ForeignKey",
"django.db.models.DateTimeField",
"django.db.models.ImageField",
"django.db.models.CharField"
] | [((96, 127), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)'}), '(max_length=50)\n', (112, 127), False, 'from django.db import models\n'), ((268, 299), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)'}), '(max_length=50)\n', (284, 299), False, 'from django.db imp... |
import functools
import operator
from aorta.router.criterion import Criterion
from aorta.router.criterion import NullCriterion
from aorta.router.criterion import And
class Rule(object):
"""Specifies a routing rule consisting of one or
more :class:`Criterion` instances.
"""
def __init__(self, destina... | [
"aorta.router.criterion.Criterion",
"aorta.router.criterion.NullCriterion"
] | [((1978, 2007), 'aorta.router.criterion.Criterion', 'Criterion', (['element', 'op', 'value'], {}), '(element, op, value)\n', (1987, 2007), False, 'from aorta.router.criterion import Criterion\n'), ((1123, 1138), 'aorta.router.criterion.NullCriterion', 'NullCriterion', ([], {}), '()\n', (1136, 1138), False, 'from aorta.... |
import pandas
import matplotlib.pyplot as plt
from ETF import get_split_name_and_isin, get_combined_name_and_isin
from pypfopt import expected_returns, risk_models, plotting, discrete_allocation
from pypfopt.efficient_frontier import EfficientFrontier
import base64
import io
import numpy as np
import math
from timeit i... | [
"pypfopt.discrete_allocation.DiscreteAllocation",
"ETF.get_split_name_and_isin",
"pypfopt.risk_models.sample_cov",
"timeit.default_timer",
"pypfopt.discrete_allocation.get_latest_prices",
"ETF.get_combined_name_and_isin",
"io.BytesIO",
"numpy.diag",
"pypfopt.plotting._ef_default_returns_range",
"p... | [((736, 751), 'timeit.default_timer', 'default_timer', ([], {}), '()\n', (749, 751), False, 'from timeit import default_timer\n'), ((1225, 1272), 'pypfopt.expected_returns.mean_historical_return', 'expected_returns.mean_historical_return', (['prices'], {}), '(prices)\n', (1264, 1272), False, 'from pypfopt import expect... |
from bs4 import BeautifulSoup
from OSMPythonTools.element import Element
from OSMPythonTools.internal.cacheObject import CacheObject
def _raiseException(prefix, msg):
sys.tracebacklimit = None
raise(Exception('[OSMPythonTools.' + prefix + '] ' + msg))
class Api(CacheObject):
def __init__(self, endpoint='... | [
"bs4.BeautifulSoup"
] | [((985, 1010), 'bs4.BeautifulSoup', 'BeautifulSoup', (['xml', '"""xml"""'], {}), "(xml, 'xml')\n", (998, 1010), False, 'from bs4 import BeautifulSoup\n')] |
# -*- coding:utf-8 -*-
# -*- coding=utf-8 -*-
# coding=utf-8
# python version 3.5
import urllib
import urllib.request
import json
import logging
import traceback
import time
import os
url = "http://10.45.62.250/ac_portal/login.php"
url = url.encode('utf-8').decode('utf-8')
print(url)
oridata = {"opr": "pwdLogin",
... | [
"urllib.request.Request",
"time.strftime",
"time.sleep",
"logging.exception",
"io.TextIOWrapper",
"urllib.parse.urlencode",
"os.system",
"time.time",
"urllib.request.urlopen"
] | [((472, 522), 'urllib.request.Request', 'urllib.request.Request', (['url'], {'data': 'data', 'headers': '{}'}), '(url, data=data, headers={})\n', (494, 522), False, 'import urllib\n'), ((1104, 1156), 'io.TextIOWrapper', 'io.TextIOWrapper', (['sys.stdout.buffer'], {'encoding': '"""utf8"""'}), "(sys.stdout.buffer, encodi... |
import numpy as np
def magnitude(x):
"""Returns magnitude of a vector"""
return np.linalg.norm(np.array(x))
def distance(p1, p2):
"""Returns distance between two positions p1 and p2"""
return magnitude(np.array(p2) - np.array(p1))
def unit_vector(x):
"""Returns unit_vector of a vector"""
retu... | [
"numpy.arccos",
"numpy.array",
"numpy.cos",
"numpy.random.seed",
"numpy.random.uniform",
"numpy.sin"
] | [((631, 651), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (645, 651), True, 'import numpy as np\n'), ((686, 723), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(2 * np.pi)', 'size'], {}), '(0, 2 * np.pi, size)\n', (703, 723), True, 'import numpy as np\n'), ((737, 767), 'numpy.random.unif... |
from django.shortcuts import render
from rest_framework import viewsets
from .models import Alimento, Arquivo
from .serializers import AlimentoSerializer, ArquivoSerializer
from rest_framework.response import Response
from rest_framework.decorators import action
from helpers import limpar_arquivos, limpar_tabelas
from... | [
"extractor.extrair_db",
"rest_framework.response.Response",
"helpers.limpar_arquivos",
"rest_framework.decorators.action",
"helpers.limpar_tabelas"
] | [((2115, 2155), 'rest_framework.decorators.action', 'action', ([], {'methods': "['delete']", 'detail': '(False)'}), "(methods=['delete'], detail=False)\n", (2121, 2155), False, 'from rest_framework.decorators import action\n'), ((2313, 2350), 'rest_framework.decorators.action', 'action', ([], {'methods': "['put']", 'de... |
import asyncio
from irrexplorer.backends.bgp import BGPImporter
from irrexplorer.backends.rirstats import RIRStatsImporter
from irrexplorer.state import RIR
async def main():
"""
Run an import for all backends with local data.
All imports are run "simultaneously" (one CPU, but async)
"""
tasks = ... | [
"irrexplorer.backends.rirstats.RIRStatsImporter",
"irrexplorer.backends.bgp.BGPImporter",
"asyncio.gather"
] | [((455, 477), 'asyncio.gather', 'asyncio.gather', (['*tasks'], {}), '(*tasks)\n', (469, 477), False, 'import asyncio\n'), ((417, 430), 'irrexplorer.backends.bgp.BGPImporter', 'BGPImporter', ([], {}), '()\n', (428, 430), False, 'from irrexplorer.backends.bgp import BGPImporter\n'), ((364, 385), 'irrexplorer.backends.rir... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-11-17 00:02
from __future__ import unicode_literals
import django.contrib.gis.db.models.fields
from django.db import migrations, models
import django.utils.timezone
import easy_thumbnails.fields
import model_utils.fields
class Migration(migrations.Migratio... | [
"django.db.models.TextField",
"django.db.models.BooleanField",
"django.db.models.AutoField",
"django.db.models.URLField",
"django.db.models.CharField"
] | [((529, 622), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (545, 622), False, 'from django.db import migrations, models\... |
import json
import os
import sys
import argparse
import subprocess
import tempfile
import shutil
from collections import namedtuple
from molotov import __version__
from molotov.run import run
def clone_repo(github):
# XXX security
subprocess.check_call('git clone %s .' % github, shell=True)
def create_virt... | [
"argparse.ArgumentParser",
"subprocess.check_call",
"os.path.join",
"os.getcwd",
"os.chdir",
"shutil.rmtree",
"tempfile.mkdtemp",
"molotov.run.run",
"sys.exit"
] | [((242, 302), 'subprocess.check_call', 'subprocess.check_call', (["('git clone %s .' % github)"], {'shell': '(True)'}), "('git clone %s .' % github, shell=True)\n", (263, 302), False, 'import subprocess\n'), ((371, 450), 'subprocess.check_call', 'subprocess.check_call', (["('%s --python %s venv' % (virtualenv, python))... |
class KelvinHelmholtzUniform:
"""
Kelvin-Helmholtz instability with anisotropic viscosity and a constant
magnetic field in the x-direction. The equilibrium is assumed to have
constant density, temperature and pressure. The velocity profile varies
smoothly and the setup is periodic.
... | [
"numpy.sqrt",
"sympy.lambdify",
"sympy.symbols",
"sympy.diff",
"sympy.tanh"
] | [((1277, 1303), 'numpy.sqrt', 'np.sqrt', (['(2 * self.p / beta)'], {}), '(2 * self.p / beta)\n', (1284, 1303), True, 'import numpy as np\n'), ((2996, 3008), 'sympy.symbols', 'symbols', (['"""z"""'], {}), "('z')\n", (3003, 3008), False, 'from sympy import tanh, diff, lambdify, symbols\n'), ((3248, 3262), 'sympy.diff', '... |
# -*- coding: utf-8 -
try:
# CKAN 2.7 and later
from ckan.common import config
except ImportError:
# CKAN 2.6 and earlier
from pylons import config
import logging
import ckan.logic as l
import ckan.model as m
import ckan.plugins.toolkit as tk
import ckan.model as model
import ckan.lib.navl.dictization_f... | [
"logging.getLogger",
"ckan.model.Vocabulary.get",
"ckan.plugins.toolkit.get_action",
"ckan.plugins.toolkit.c.page.pager",
"ckan.logic.validators.tag_in_vocabulary_validator",
"ckan.common._",
"ckan.model.Session.query",
"ckan.authz.get_user_id_for_username"
] | [((487, 514), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (504, 514), False, 'import logging\n'), ((793, 840), 'ckan.authz.get_user_id_for_username', 'get_user_id_for_username', (['user'], {'allow_none': '(True)'}), '(user, allow_none=True)\n', (817, 840), False, 'from ckan.authz impor... |
import cv2
import numpy as np
import torch
import torch.nn as nn
from torch.nn import functional as F
class GradCAM():
def __init__(self, model, target_layer, use_cuda):
self.model = model.eval()
self.target_layer = target_layer
self.use_cuda = use_cuda
self.feature_map = 0
... | [
"numpy.uint8",
"torch.from_numpy",
"numpy.max",
"numpy.sum",
"torch.sum",
"numpy.maximum",
"numpy.float32"
] | [((2103, 2122), 'numpy.uint8', 'np.uint8', (['(255 * cam)'], {}), '(255 * cam)\n', (2111, 2122), True, 'import numpy as np\n'), ((1236, 1261), 'torch.from_numpy', 'torch.from_numpy', (['one_hot'], {}), '(one_hot)\n', (1252, 1261), False, 'import torch\n'), ((1701, 1763), 'numpy.sum', 'np.sum', (['(self.feature_map * se... |
from st2common.runners.base_action import Action
import packer
import os
class BaseAction(Action):
def __init__(self, config):
super(BaseAction, self).__init__(config)
self.atlas_token = self.config.get('atlas_token', None)
self._exec_path = self.config.get('exec_path', '/usr/local/bin/pac... | [
"os.chdir"
] | [((765, 784), 'os.chdir', 'os.chdir', (['directory'], {}), '(directory)\n', (773, 784), False, 'import os\n')] |
# -*- coding: utf-8 -*-
import re
from datetime import datetime
from django.db import models
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from django.template.defaultfilters import slugify
from cms.models import CMSPlugin, Page
from cms.models.fields import Place... | [
"django.utils.translation.ugettext_lazy",
"django.db.models.TextField",
"django.db.models.ForeignKey",
"cms.models.fields.PlaceholderField",
"cmskit.articles.managers.ArticleManager",
"datetime.datetime.now",
"django.template.defaultfilters.slugify",
"django.db.models.SlugField",
"re.sub",
"django... | [((658, 681), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Page'], {}), '(Page)\n', (675, 681), False, 'from django.db import models\n'), ((704, 748), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(216)', 'blank': '(True)'}), '(max_length=216, blank=True)\n', (720, 748), False, 'from ... |
import asyncio
import random
from datetime import datetime, timedelta
import discord
from discord.ext import commands, tasks
from web3 import Web3
from joeBot import JoePic, JoeSubGraph, Constants, Utils
from joeBot.JoeMakerBot import JoeMaker
from joeBot.Utils import readable, Ticker
# web3
w3 = Web3(Web3.HTTPProvi... | [
"joeBot.Utils.readable",
"joeBot.JoePic.JoePic",
"joeBot.JoeSubGraph.getJoeBuyBackLast7d",
"joeBot.Constants.Channels",
"joeBot.JoeSubGraph.getJoePrice",
"joeBot.JoeSubGraph.addJoeBuyBackToLast7d",
"datetime.timedelta",
"datetime.datetime.now",
"joeBot.JoeSubGraph.getRatio",
"joeBot.JoeSubGraph.ge... | [((306, 364), 'web3.Web3.HTTPProvider', 'Web3.HTTPProvider', (['"""https://api.avax.network/ext/bc/C/rpc"""'], {}), "('https://api.avax.network/ext/bc/C/rpc')\n", (323, 364), False, 'from web3 import Web3\n'), ((782, 802), 'discord.ext.tasks.loop', 'tasks.loop', ([], {'hours': '(24)'}), '(hours=24)\n', (792, 802), Fals... |
#! /usr/bin/env python3
'''
Author: <NAME>, ORCID 0000-0003-4248-4528
Copyleft: MIT License (https://en.wikipedia.org/wiki/MIT_License)
Construct labeled Gaifman graph of a transactional dataset.
Produce either DOT output on stdout for the Gaifman graph
or an AGraph from pygraphviz with separate singletons and
rep... | [
"argparse.ArgumentParser",
"itertools.combinations",
"collections.defaultdict",
"sgton.Sgton",
"auxfun.q",
"auxfun.delbl"
] | [((1197, 1217), 'collections.defaultdict', 'defaultdict', (['Counter'], {}), '(Counter)\n', (1208, 1217), False, 'from collections import Counter, defaultdict\n'), ((3068, 3084), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (3079, 3084), False, 'from collections import Counter, defaultdict\n'), (... |
from rest_framework import serializers
from drf_yasg.utils import swagger_serializer_method
from cart.models import ProductCart, Cart
from product.serializers import ProductSerializer
from product.models import Product
class ProductCartSerializer(serializers.ModelSerializer):
product = serializers.SerializerMethod... | [
"product.models.Product.objects.get",
"rest_framework.serializers.SerializerMethodField",
"cart.models.ProductCart.objects.filter",
"product.serializers.ProductSerializer"
] | [((292, 327), 'rest_framework.serializers.SerializerMethodField', 'serializers.SerializerMethodField', ([], {}), '()\n', (325, 327), False, 'from rest_framework import serializers\n'), ((750, 785), 'rest_framework.serializers.SerializerMethodField', 'serializers.SerializerMethodField', ([], {}), '()\n', (783, 785), Fal... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
class DeliveryMethod(models.Model):
name = models.CharField(_('Name'), max_length=255)
code = models.CharField(_('Code'), max_length=255, unique=True)
def __str__(self):
return self.name
class Meta:
... | [
"django.utils.translation.ugettext_lazy"
] | [((153, 162), 'django.utils.translation.ugettext_lazy', '_', (['"""Name"""'], {}), "('Name')\n", (154, 162), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((209, 218), 'django.utils.translation.ugettext_lazy', '_', (['"""Code"""'], {}), "('Code')\n", (210, 218), True, 'from django.utils.translatio... |
l = [1, 2, 4, 7, 2, 1, 8, 6, 1]
# 字典取键法可以保证原列表元素顺序
print(list(dict.fromkeys(l).keys()))
# 集合法则不可以
print(list(set(l)))
# 还有一种方法:有序字典取键法
# 其实在 Python 3.6 及后续版本这个方法等价于字典取键法
from collections import OrderedDict
print(list(OrderedDict.fromkeys(l).keys()))
| [
"collections.OrderedDict.fromkeys"
] | [((218, 241), 'collections.OrderedDict.fromkeys', 'OrderedDict.fromkeys', (['l'], {}), '(l)\n', (238, 241), False, 'from collections import OrderedDict\n')] |
# avax-python : Python tools for the exploration of the Avalanche AVAX network.
#
# Find tutorials and use cases at https://crypto.bi
"""
Copyright (C) 2021 - crypto.bi
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), t... | [
"hashlib.sha256",
"bip_utils.bip.bip_keys.BipPublicKey",
"hashlib.new",
"avaxpython.wallet.bech32.bech32_encode",
"avaxpython.wallet.bech32.convertbits",
"bip_utils.Bip32.FromSeed"
] | [((1670, 1690), 'bip_utils.Bip32.FromSeed', 'Bip32.FromSeed', (['seed'], {}), '(seed)\n', (1684, 1690), False, 'from bip_utils import Bip32\n'), ((1832, 1848), 'hashlib.sha256', 'hashlib.sha256', ([], {}), '()\n', (1846, 1848), False, 'import hashlib\n'), ((1898, 1922), 'hashlib.new', 'hashlib.new', (['"""ripemd160"""'... |
from rest_framework import serializers
from rest_framework.fields import empty
from .base_execution_method_serializer import BaseExecutionMethodSerializer
class BaseExecutionMethodCapabilitySerializer(BaseExecutionMethodSerializer):
def __init__(self, instance=None, data=empty, omit_details=False, **kwarg... | [
"rest_framework.serializers.SerializerMethodField"
] | [((553, 618), 'rest_framework.serializers.SerializerMethodField', 'serializers.SerializerMethodField', ([], {'method_name': '"""get_capabilities"""'}), "(method_name='get_capabilities')\n", (586, 618), False, 'from rest_framework import serializers\n')] |
import json
from controller.base_request import BaseRequest
from models.deal import Deal
class Deals(BaseRequest):
def post(self, deal_id):
deal_json = json.loads(self.request.body)['deal']
deal_new = Deal(namespace='ac-abc123')
deal_key = Deal.prepare_deal(deal_new, deal_json).put()
... | [
"json.loads",
"models.deal.Deal",
"models.deal.Deal.query",
"models.deal.Deal.prepare_deal",
"models.deal.Deal.get_deal"
] | [((225, 252), 'models.deal.Deal', 'Deal', ([], {'namespace': '"""ac-abc123"""'}), "(namespace='ac-abc123')\n", (229, 252), False, 'from models.deal import Deal\n'), ((1440, 1462), 'models.deal.Deal.get_deal', 'Deal.get_deal', (['deal_id'], {}), '(deal_id)\n', (1453, 1462), False, 'from models.deal import Deal\n'), ((16... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import numpy as np
from scipy.stats import entropy, normaltest, mode, kurtosis, skew, pearsonr, moment
import pandas as pd
from collections import OrderedDict
from feature_extraction.helpers import *
from feature_extraction.type_detection import detect_field_type, data_type_... | [
"feature_extraction.type_detection.detect_field_type",
"scipy.stats.normaltest",
"scipy.stats.pearsonr",
"numpy.divide",
"numpy.mean",
"numpy.sort",
"scipy.stats.kurtosis",
"numpy.diff",
"numpy.subtract",
"numpy.max",
"numpy.min",
"collections.OrderedDict",
"scipy.stats.entropy",
"numpy.ma... | [((364, 400), 'numpy.warnings.filterwarnings', 'np.warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (390, 400), True, 'import numpy as np\n'), ((5107, 5178), 'collections.OrderedDict', 'OrderedDict', (["[(f['name'], None) for f in field_existence_features_list]"], {}), "([(f['name'], None) for f in fie... |
import re
rule1 = rule2 = 0
policy = re.compile("^(\d+)-(\d+)\s([a-z]):\s(.*)$")
with open("input02.txt") as f:
for line in f:
m = policy.match(line)
nr1, nr2, char, password = m.groups()
nr1, nr2 = int(nr1), int(nr2)
if nr1 <= password.count(char) <= nr2:
rule1 += 1
... | [
"re.compile"
] | [((38, 85), 're.compile', 're.compile', (['"""^(\\\\d+)-(\\\\d+)\\\\s([a-z]):\\\\s(.*)$"""'], {}), "('^(\\\\d+)-(\\\\d+)\\\\s([a-z]):\\\\s(.*)$')\n", (48, 85), False, 'import re\n')] |
#/usr/bin/env python
from __future__ import print_function
import numpy
import copy
import saveVTK
class Upwind:
def __init__(self, velocity, lengths, numCells):
self.numCells = numCells
self.ndims = len(velocity)
self.deltas = numpy.zeros( (self.ndims,), numpy.float64 )
self.upDirection = numpy.z... | [
"numpy.identity",
"numpy.ones",
"numpy.sum",
"numpy.zeros",
"numpy.dot",
"sys.exit",
"numpy.arange"
] | [((3192, 3227), 'numpy.ones', 'numpy.ones', (['(ndims,)', 'numpy.float64'], {}), '((ndims,), numpy.float64)\n', (3202, 3227), False, 'import numpy\n'), ((3242, 3277), 'numpy.ones', 'numpy.ones', (['(ndims,)', 'numpy.float64'], {}), '((ndims,), numpy.float64)\n', (3252, 3277), False, 'import numpy\n'), ((246, 287), 'num... |
from django import forms
from LetsCook.common.models import Comment
from LetsCook.core.mixins import AddBootstrapFormControlMixin
from LetsCook.recipes.models import Recipe
class CommentForm(AddBootstrapFormControlMixin, forms.ModelForm):
"""
Form for creating a comment. Relates the comment to a recipe objec... | [
"django.forms.HiddenInput",
"LetsCook.recipes.models.Recipe.objects.get",
"LetsCook.common.models.Comment"
] | [((700, 732), 'LetsCook.recipes.models.Recipe.objects.get', 'Recipe.objects.get', ([], {'pk': 'recipe_pk'}), '(pk=recipe_pk)\n', (718, 732), False, 'from LetsCook.recipes.models import Recipe\n'), ((751, 805), 'LetsCook.common.models.Comment', 'Comment', ([], {'text': "self.cleaned_data['text']", 'recipe': 'recipe'}), ... |
import importlib
import os
import re
import cli_ui
import rubrik_cdm
def config_class(module_name):
class_name = module_name.title().replace('_', '') + 'Config'
klass = getattr(importlib.import_module('rubrik_config.'+module_name), class_name)
return klass
def config_name(obj):
matches = re.findall... | [
"importlib.import_module",
"cli_ui.ask_string",
"re.compile",
"cli_ui.info",
"cli_ui.read_input",
"cli_ui.info_1",
"unicodedata.normalize"
] | [((636, 725), 'cli_ui.info', 'cli_ui.info', (['cli_ui.green', '"""::"""', 'cli_ui.lightgray', 'ask', '"""(blank line will terminate)"""'], {}), "(cli_ui.green, '::', cli_ui.lightgray, ask,\n '(blank line will terminate)')\n", (647, 725), False, 'import cli_ui\n'), ((188, 243), 'importlib.import_module', 'importlib.i... |
from django.db import models
from datetime import date
# Create your models here.
class LanguageDisability(models.Model):
disability_name = models.CharField(max_length=200)
def __str__(self):
return self.disability_name
# student = models.ForeignKey(StudentInfo, on_delete=models.CASCADE)
class Ma... | [
"django.db.models.EmailField",
"django.db.models.DateField",
"django.db.models.TextField",
"django.db.models.ForeignKey",
"django.db.models.IntegerField",
"django.db.models.ManyToManyField",
"django.db.models.CharField"
] | [((145, 177), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(200)'}), '(max_length=200)\n', (161, 177), False, 'from django.db import models\n'), ((378, 410), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(200)'}), '(max_length=200)\n', (394, 410), False, 'from django.d... |
# coding: utf-8
# In[1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from skimage.color import lab2rgb
from sklearn import model_selection
from sklearn.naive_bayes import GaussianNB
import sys
from sklearn.metrics import accuracy_score
from skimage import color
from sklearn import pipeline... | [
"matplotlib.pyplot.imshow",
"skimage.color.rgb2lab",
"matplotlib.pyplot.title",
"pandas.read_csv",
"matplotlib.pyplot.savefig",
"skimage.color.lab2rgb",
"sklearn.model_selection.train_test_split",
"sklearn.naive_bayes.GaussianNB",
"numpy.ones",
"matplotlib.pyplot.subplot",
"numpy.stack",
"nump... | [((939, 1006), 'numpy.vectorize', 'np.vectorize', (['COLOUR_RGB.get'], {'otypes': '[np.uint8, np.uint8, np.uint8]'}), '(COLOUR_RGB.get, otypes=[np.uint8, np.uint8, np.uint8])\n', (951, 1006), True, 'import numpy as np\n'), ((497, 520), 'skimage.color.rgb2lab', 'color.rgb2lab', (['reshaped'], {}), '(reshaped)\n', (510, ... |
import multiprocessing
class PipelineStep:
max_number_of_processes = max(multiprocessing.cpu_count() - 2, 1)
chunksize = None
def __init__(self, processes=None, execute_args=[]):
self.processes = processes
self.execute_args = execute_args
def get_items(self) -> list:
raise Ex... | [
"multiprocessing.get_context",
"multiprocessing.cpu_count"
] | [((544, 573), 'multiprocessing.get_context', 'multiprocessing.get_context', ([], {}), '()\n', (571, 573), False, 'import multiprocessing\n'), ((79, 106), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (104, 106), False, 'import multiprocessing\n')] |
from testcase import TestCase
from testcase import PROP_NAME
from testcase import PROP_VALUE
from testcase import REDACTED
from testcase import find_by_prop
PROP_ENV = "Environment"
PROP_CHANGE = "Change"
PROP_PROJ = "Project"
PROP_SECRET = "Secret"
UPDATED = "updated"
UNCHANGED = "unchanged"
CREATED = "created"
INHE... | [
"testcase.find_by_prop"
] | [((940, 979), 'testcase.find_by_prop', 'find_by_prop', (['projects', 'PROP_NAME', 'name'], {}), '(projects, PROP_NAME, name)\n', (952, 979), False, 'from testcase import find_by_prop\n'), ((1236, 1279), 'testcase.find_by_prop', 'find_by_prop', (['environments', 'PROP_NAME', 'name'], {}), '(environments, PROP_NAME, name... |
"""Module implementing the F1 Score metric."""
from tensorflow.keras.backend import epsilon
from .binary_metric import BinaryMetric
class F1Score(BinaryMetric):
def _custom_metric(self):
return self.tp / (self.tp + 0.5 * (self.fp + self.fn) + epsilon())
| [
"tensorflow.keras.backend.epsilon"
] | [((258, 267), 'tensorflow.keras.backend.epsilon', 'epsilon', ([], {}), '()\n', (265, 267), False, 'from tensorflow.keras.backend import epsilon\n')] |
import pathlib
import pytest
import pymatgen as pmg
from pymatgen.io.cif import CifParser
from dftfit.potential import Potential
from dftfit.training import Training
@pytest.fixture
def structure():
def f(filename, conventional=True, oxidized=False):
filename = pathlib.Path(filename)
if not file... | [
"dftfit.potential.Potential.from_file",
"dftfit.training.Training.from_file",
"pathlib.Path"
] | [((278, 300), 'pathlib.Path', 'pathlib.Path', (['filename'], {}), '(filename)\n', (290, 300), False, 'import pathlib\n'), ((934, 978), 'dftfit.potential.Potential.from_file', 'Potential.from_file', (['filename'], {'format': 'format'}), '(filename, format=format)\n', (953, 978), False, 'from dftfit.potential import Pote... |
""" Unit tests for ``wheezy.validation.model``.
"""
import unittest
from datetime import date, datetime, time
from decimal import Decimal
from wheezy.validation.model import (
bool_value_provider,
boolean_true_values,
bytes_value_provider,
date_value_provider,
datetime_value_provider,
float_va... | [
"datetime.datetime",
"datetime.time",
"wheezy.validation.model.time_value_provider",
"wheezy.validation.model.int_value_provider",
"wheezy.validation.model.try_update_model",
"wheezy.validation.model.decimal_value_provider",
"wheezy.validation.model.datetime_value_provider",
"wheezy.validation.model.b... | [((7435, 7445), 'decimal.Decimal', 'Decimal', (['(0)'], {}), '(0)\n', (7442, 7445), False, 'from decimal import Decimal\n'), ((1026, 1069), 'wheezy.validation.model.try_update_model', 'try_update_model', (['user', 'self.values', 'errors'], {}), '(user, self.values, errors)\n', (1042, 1069), False, 'from wheezy.validati... |
"""This module provides the :py:class:`typespec_ctypes` class.
It is used to map the C types found in the 'dwf.h' header file to specific *ctypes* types.
"""
import ctypes
class typespec_ctypes:
"""Map the type specifications from :py:mod:`pydwf.core.auxiliary.dwf_function_signatures` to *ctypes* types."""
... | [
"ctypes.POINTER"
] | [((693, 715), 'ctypes.POINTER', 'ctypes.POINTER', (['c_char'], {}), '(c_char)\n', (707, 715), False, 'import ctypes\n'), ((1050, 1073), 'ctypes.POINTER', 'ctypes.POINTER', (['c_short'], {}), '(c_short)\n', (1064, 1073), False, 'import ctypes\n'), ((1176, 1197), 'ctypes.POINTER', 'ctypes.POINTER', (['c_int'], {}), '(c_i... |
import gemmi
from relion.cryolo_relion_it import icebreaker_histogram
def test_create_json_histogram(tmp_path):
# Prep
icebreaker_dir = tmp_path / "External" / "Icebreaker_group_batch_001"
icebreaker_dir.mkdir(parents=True)
particles_file = icebreaker_dir / "particles.star"
particles_file.write_t... | [
"relion.cryolo_relion_it.icebreaker_histogram.create_pdf_histogram",
"gemmi.cif.Document",
"relion.cryolo_relion_it.icebreaker_histogram.create_json_histogram"
] | [((2083, 2103), 'gemmi.cif.Document', 'gemmi.cif.Document', ([], {}), '()\n', (2101, 2103), False, 'import gemmi\n'), ((2304, 2356), 'relion.cryolo_relion_it.icebreaker_histogram.create_json_histogram', 'icebreaker_histogram.create_json_histogram', (['tmp_path'], {}), '(tmp_path)\n', (2346, 2356), False, 'from relion.c... |
from Product.Database.DBConn import create_session, Recommendation
from Product.DataManager.restrict import get_restricted_match
from Product.RecommendationManager import gets_from_database as gets_from_database
"""
Author: <NAME>
Date: 2017-11-15
Last update:
Purpose: Illustrate how restrict.py can be used to generat... | [
"Product.DataManager.restrict.get_restricted_match",
"Product.Database.DBConn.create_session",
"Product.RecommendationManager.gets_from_database.get_movie_title"
] | [((361, 377), 'Product.Database.DBConn.create_session', 'create_session', ([], {}), '()\n', (375, 377), False, 'from Product.Database.DBConn import create_session, Recommendation\n'), ((935, 1008), 'Product.DataManager.restrict.get_restricted_match', 'get_restricted_match', (['"""User"""', 'feature_list', 'list_of_matc... |
from bs4 import BeautifulSoup as bs4
import requests
names = []
pages = []
sizes = []
links = []
magnets = []
seeders = []
leachers = []
headers = {
'User-Agent': 'Mozilla/5.0'
}
base_url = "https://1337x.to/"
pages_to_scrape = 1
movie_name = "ludo"
def linkSearch():
for i in range(1, pages_to_scrape+1):
... | [
"bs4.BeautifulSoup",
"requests.get"
] | [((2008, 2042), 'requests.get', 'requests.get', (['url'], {'headers': 'headers'}), '(url, headers=headers)\n', (2020, 2042), False, 'import requests\n'), ((2072, 2101), 'bs4.BeautifulSoup', 'bs4', (['page.text', '"""html.parser"""'], {}), "(page.text, 'html.parser')\n", (2075, 2101), True, 'from bs4 import BeautifulSou... |
import sys, os, getopt, time, datetime
from wxpy import *
def filesExist(fileList):
for i, aFile in enumerate(fileList):
if not os.path.exists(aFile):
print("warning: the {}th file, {}, doesn't exist.".format(i + 1, aFile))
return False
return True
def readFile(filename):
... | [
"os.path.exists",
"getopt.getopt",
"time.sleep",
"datetime.datetime.now",
"sys.exit",
"datetime.timedelta"
] | [((494, 517), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (515, 517), False, 'import sys, os, getopt, time, datetime\n'), ((533, 559), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(0)'}), '(days=0)\n', (551, 559), False, 'import sys, os, getopt, time, datetime\n'), ((681, 718), 'ge... |
import numpy as np
import pandas as pd
from scipy.stats import beta
import matplotlib.pyplot as plt
import json
def t2d_beta_data(min_val,max_val,alpha_val, beta_val,no_default):
# Calculation
tad = np.array([range(1,max_val+1)])
beta_pdf = beta.pdf(tad, alpha_val, beta_val, loc=min_val, scale=max_val-min... | [
"json.dump",
"scipy.stats.beta.pdf",
"numpy.round"
] | [((255, 327), 'scipy.stats.beta.pdf', 'beta.pdf', (['tad', 'alpha_val', 'beta_val'], {'loc': 'min_val', 'scale': '(max_val - min_val)'}), '(tad, alpha_val, beta_val, loc=min_val, scale=max_val - min_val)\n', (263, 327), False, 'from scipy.stats import beta\n'), ((385, 420), 'numpy.round', 'np.round', (['(beta_pdf_std *... |
import numpy as np
def bound_linear(z,z_low,z_high,val_low,val_high):
z0 = val_low + (val_high - val_low) * (z - z_low) / (z_high - z_low)
z0 = np.maximum(z0,val_low)
z0 = np.minimum(z0,val_high)
return z0 | [
"numpy.maximum",
"numpy.minimum"
] | [((153, 176), 'numpy.maximum', 'np.maximum', (['z0', 'val_low'], {}), '(z0, val_low)\n', (163, 176), True, 'import numpy as np\n'), ((185, 209), 'numpy.minimum', 'np.minimum', (['z0', 'val_high'], {}), '(z0, val_high)\n', (195, 209), True, 'import numpy as np\n')] |
import json
import os
import random
import string
from math import asin
from math import ceil
from math import cos
from math import degrees
from math import pi
from math import radians
from math import sin
from math import sqrt
from math import tan
from pyaedt.generic.general_methods import _retry_ntimes
from pyaedt.g... | [
"pyaedt.modeler.actors.Vehicle",
"math.sqrt",
"math.cos",
"os.path.exists",
"os.listdir",
"math.tan",
"pyaedt.modeler.GeometryOperators.GeometryOperators.cs_plane_to_axis_str",
"pyaedt.modeler.multiparts.MultiPartComponent.start",
"pyaedt.modeler.GeometryOperators.GeometryOperators.points_distance",... | [((1373, 1398), 'pyaedt.generic.general_methods.pyaedt_function_handler', 'pyaedt_function_handler', ([], {}), '()\n', (1396, 1398), False, 'from pyaedt.generic.general_methods import pyaedt_function_handler\n'), ((3119, 3144), 'pyaedt.generic.general_methods.pyaedt_function_handler', 'pyaedt_function_handler', ([], {}... |
from tests import random_account_gen
import sys
from sqlalchemy import create_engine
from flask import Flask
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: build_test_users [number of users] ")
exit()
num = sys.argv[1]
api = Flask(__name__)
api.config.from_pyfile("fadz... | [
"flask.Flask"
] | [((272, 287), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (277, 287), False, 'from flask import Flask\n')] |
import os
import subprocess
build_dir=".\\build\RelWithDebInfo"
visus_cmd= "%s\\visus.exe" % (build_dir,)
python_dir="C:\\Python36"
qt5_dir="C:\\Qt\\Qt5.9.2\\5.9.2\\msvc2017_64\\bin"
cmd_env={
**os.environ,
"PATH": python_dir + ";" + python_dir + "\\Scripts" + ";" + qt5_dir + "\\bin;" + ".\\bin" + os.environ['P... | [
"subprocess.Popen"
] | [((767, 801), 'subprocess.Popen', 'subprocess.Popen', (['cmd'], {'env': 'cmd_env'}), '(cmd, env=cmd_env)\n', (783, 801), False, 'import subprocess\n')] |
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import hashlib
import json
import re
import unittest
from collections import OrderedDict
from enum import Enum
from pants.base.hash_utils import CoercingEncoder, hash_all, json_hash
from ... | [
"collections.OrderedDict",
"re.escape",
"json.dumps",
"pants.base.hash_utils.hash_all",
"pants.util.ordered_set.OrderedSet",
"hashlib.sha1",
"pants.base.hash_utils.json_hash"
] | [((456, 470), 'hashlib.sha1', 'hashlib.sha1', ([], {}), '()\n', (468, 470), False, 'import hashlib\n'), ((715, 749), 'json.dumps', 'json.dumps', (['o'], {'cls': 'CoercingEncoder'}), '(o, cls=CoercingEncoder)\n', (725, 749), False, 'import json\n'), ((566, 593), 'pants.base.hash_utils.hash_all', 'hash_all', (["['jake', ... |
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. 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... | [
"pynini.lib.pynutil.insert",
"pynini.lib.pynutil.delete",
"pynini.closure",
"pynini.accep",
"pynini.cdrewrite",
"nemo_text_processing.text_normalization.de.utils.get_abs_path",
"pynini.cross",
"pynini.union",
"pynini.lib.pynutil.add_weight"
] | [((3962, 3983), 'pynini.union', 'pynini.union', (['*min_30'], {}), '(*min_30)\n', (3974, 3983), False, 'import pynini\n'), ((4049, 4070), 'pynini.union', 'pynini.union', (['*min_29'], {}), '(*min_29)\n', (4061, 4070), False, 'import pynini\n'), ((2781, 2800), 'pynini.lib.pynutil.delete', 'pynutil.delete', (['"""\\""""'... |
from marshmallow import fields
from .field_set import FieldSet, FieldSetSchema
class HttpRequest(FieldSet):
def __init__(self,
body_bytes: int = None,
body_content: str = None,
bytes: int = None,
method: str = None,
referrer: s... | [
"marshmallow.fields.Integer",
"marshmallow.fields.String"
] | [((704, 720), 'marshmallow.fields.Integer', 'fields.Integer', ([], {}), '()\n', (718, 720), False, 'from marshmallow import fields\n'), ((740, 755), 'marshmallow.fields.String', 'fields.String', ([], {}), '()\n', (753, 755), False, 'from marshmallow import fields\n'), ((768, 784), 'marshmallow.fields.Integer', 'fields.... |
import os
import shutil
import sys
dest = 'py2only'
futures_dirname = 'concurrent'
DIST_DIR = os.path.realpath('kolibri/dist')
def hide_py2_modules():
"""
Move the directory of 'futures' and python2-only modules of 'future'
inside the directory 'py2only'
"""
# Move the directory of 'futures' ins... | [
"os.path.realpath",
"os.path.join",
"shutil.move"
] | [((95, 127), 'os.path.realpath', 'os.path.realpath', (['"""kolibri/dist"""'], {}), "('kolibri/dist')\n", (111, 127), False, 'import os\n'), ((857, 892), 'os.path.join', 'os.path.join', (['DIST_DIR', 'module_name'], {}), '(DIST_DIR, module_name)\n', (869, 892), False, 'import os\n'), ((915, 956), 'os.path.join', 'os.pat... |
from collections import Counter
import os
from celery import shared_task
import json
import requests
import re
from main.models import City, GloboVideo
# Imports the Google Cloud client library
# @shared_task(bind=True, name='Video crawler')
def run_crawler(self):
response = requests.get('https://especiais.g1.g... | [
"json.loads",
"json.dumps",
"requests.get",
"re.search"
] | [((284, 387), 'requests.get', 'requests.get', (['"""https://especiais.g1.globo.com/o-brasil-que-eu-quero/2018/videos/js/data.json"""'], {}), "(\n 'https://especiais.g1.globo.com/o-brasil-que-eu-quero/2018/videos/js/data.json'\n )\n", (296, 387), False, 'import requests\n'), ((1336, 1401), 're.search', 're.search'... |
import traceback
import sys
import depgraph
from common import utils
from common.constants import UNKNOWN_LABEL, VOID, LOC_VAR, FUN_ARG, INT
from common.constants import ENUM_DW_FORM_exprloc, ENUM_ABBREV_CODE, TTYPES
from elements.ttype import Ttype
from elements.givs import Node
class Offset(Node):
total = 0
... | [
"common.utils.encode_address",
"common.utils.encode_sleb128",
"elements.ttype.Ttype"
] | [((2370, 2387), 'elements.ttype.Ttype', 'Ttype', ([], {'owner': 'self'}), '(owner=self)\n', (2375, 2387), False, 'from elements.ttype import Ttype\n'), ((5008, 5054), 'common.utils.encode_address', 'utils.encode_address', (['self.offset', 'self.binary'], {}), '(self.offset, self.binary)\n', (5028, 5054), False, 'from c... |
import win10toast
toaster=win10toast.ToastNotifier()
toaster.show_toast('python','<NAME>',duration = 10) | [
"win10toast.ToastNotifier"
] | [((27, 53), 'win10toast.ToastNotifier', 'win10toast.ToastNotifier', ([], {}), '()\n', (51, 53), False, 'import win10toast\n')] |
"""
m2critic.utils
~~~~~~~~~~~~~~~
Utility functions.
@author: z33k
"""
import random
import sys
import time
from typing import Union
def getdelay(base=1.5, offset=0.5) -> Union[float, int]:
"""Get random delay based on provided number.
Keyword Arguments:
base {float/int} -- a num... | [
"random.uniform",
"time.sleep",
"sys.stdout.flush",
"random.randint",
"sys.stdout.write"
] | [((1431, 1479), 'sys.stdout.write', 'sys.stdout.write', (["'\\rComplete! \\n'"], {}), "('\\rComplete! \\n')\n", (1447, 1479), False, 'import sys\n'), ((508, 552), 'random.uniform', 'random.uniform', (['(base - offset)', '(base + offset)'], {}), '(base - offset, base + offset)\n', (522, 552),... |
'''
_ooOoo_
o8888888o
88" . "88
(| -_- |)
O\ = /O
____/`---'\____
.' \\| |// `.
/ \\||| : |||// \
... | [
"struct.calcsize",
"numpy.reshape",
"torch.utils.data.TensorDataset",
"numpy.array",
"torch.utils.data.DataLoader",
"struct.unpack_from"
] | [((1321, 1345), 'struct.calcsize', 'struct.calcsize', (['""">IIII"""'], {}), "('>IIII')\n", (1336, 1345), False, 'import struct\n'), ((1688, 1710), 'struct.calcsize', 'struct.calcsize', (['""">II"""'], {}), "('>II')\n", (1703, 1710), False, 'import struct\n'), ((2125, 2165), 'torch.utils.data.TensorDataset', 'TensorDat... |
import asyncio
from datetime import date
import aiohttp
from sqlalchemy import Column, Float, String
from seabird.plugin import Plugin, CommandMixin
from .db import Base, DatabaseMixin
from .utils import fetch_location, LocationException, Location
FORECAST_URL = "https://api.forecast.io/forecast/{}/{:.4f},{:.4f}"
... | [
"aiohttp.ClientSession",
"datetime.date.fromtimestamp",
"asyncio.get_event_loop",
"sqlalchemy.Column"
] | [((403, 435), 'sqlalchemy.Column', 'Column', (['String'], {'primary_key': '(True)'}), '(String, primary_key=True)\n', (409, 435), False, 'from sqlalchemy import Column, Float, String\n'), ((450, 464), 'sqlalchemy.Column', 'Column', (['String'], {}), '(String)\n', (456, 464), False, 'from sqlalchemy import Column, Float... |
# Source code distributed under the Copyright (c) 2008, <NAME>
# Original author: <NAME> (www.jfunge.com)
#
# Licensed under the Academic Free License version 3.0
# (for details see LICENSE.txt in this directory).
import pygame
# time is measured in milliseconds
ticksPerSec = 1000.0
def getTime():
return pygame... | [
"pygame.time.get_ticks"
] | [((314, 337), 'pygame.time.get_ticks', 'pygame.time.get_ticks', ([], {}), '()\n', (335, 337), False, 'import pygame\n')] |
from common.generic_template_tag import GenericTemplateTag
from ..utils import get_what_teams_called, make_tournament_link
from ..models import PollMap
class DisplayTournamentMenuNode(GenericTemplateTag):
template = 'display_tournament_menu.html'
def __init__(self, tourney, double_br=1, extra_admin=0):
... | [
"django.template.Library"
] | [((1120, 1129), 'django.template.Library', 'Library', ([], {}), '()\n', (1127, 1129), False, 'from django.template import Library\n')] |
# Copyright 2017 The dm_control 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 law or agreed to i... | [
"dm_control.mujoco.wrapper.mjbindings.mjlib.mju_rotVecQuat",
"dm_control.mujoco.engine.Physics.from_xml_string",
"absl.testing.absltest.main",
"dm_control.suite.utils.randomizers.randomize_limited_and_rotational_joints",
"numpy.array",
"numpy.zeros",
"six.moves.xrange",
"numpy.sum",
"numpy.dot",
"... | [((6034, 6049), 'absl.testing.absltest.main', 'absltest.main', ([], {}), '()\n', (6047, 6049), False, 'from absl.testing import absltest\n'), ((1233, 1259), 'numpy.random.RandomState', 'np.random.RandomState', (['(100)'], {}), '(100)\n', (1254, 1259), True, 'import numpy as np\n'), ((1319, 2260), 'dm_control.mujoco.eng... |
#!/usr/bin/env python
from setuptools import setup
setup(
name = 'bip32utils',
version = '0.3-3',
author = '<NAME>, Corgan Labs',
author_email = '<EMAIL>',
maintainer = '<NAME>',
maintainer_email = '<EMAIL>',
url = 'http://github.com/prusnak/bip32utils',
description = 'Utilities for ge... | [
"setuptools.setup"
] | [((53, 457), 'setuptools.setup', 'setup', ([], {'name': '"""bip32utils"""', 'version': '"""0.3-3"""', 'author': '"""<NAME>, Corgan Labs"""', 'author_email': '"""<EMAIL>"""', 'maintainer': '"""<NAME>"""', 'maintainer_email': '"""<EMAIL>"""', 'url': '"""http://github.com/prusnak/bip32utils"""', 'description': '"""Utiliti... |
from scrapy.item import Item, Field
class Website(Item):
name = Field()
description = Field()
url = Field()
Stadt_URL = Field()
URL_Datei = Field()
URL_Text = Field()
URL_Dateiname = Field()
Format = Field()
URL_PARENT = Field()
Title_PARENT = Field()
geo = Field()
| [
"scrapy.item.Field"
] | [((71, 78), 'scrapy.item.Field', 'Field', ([], {}), '()\n', (76, 78), False, 'from scrapy.item import Item, Field\n'), ((97, 104), 'scrapy.item.Field', 'Field', ([], {}), '()\n', (102, 104), False, 'from scrapy.item import Item, Field\n'), ((115, 122), 'scrapy.item.Field', 'Field', ([], {}), '()\n', (120, 122), False, ... |
import os
from flask import Flask, current_app, send_file, request, current_app, session, abort
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine
from sqlalchemy_utils import database_exists, create_database
from flask_socketio import SocketIO
from flask_cors import CORS
import hashlib
impor... | [
"logging.basicConfig",
"sqlalchemy_utils.database_exists",
"flask_cors.CORS",
"flask.Flask",
"logging.Formatter",
"sqlalchemy.create_engine",
"flask.current_app.route",
"os.path.join",
"flask_socketio.SocketIO",
"redis.Redis",
"logging.FileHandler",
"flask_sqlalchemy.SQLAlchemy",
"flask.send... | [((350, 424), 'flask.Flask', 'Flask', (['__name__'], {'static_folder': '"""../dist/static"""', 'static_url_path': '"""/static"""'}), "(__name__, static_folder='../dist/static', static_url_path='/static')\n", (355, 424), False, 'from flask import Flask, current_app, send_file, request, current_app, session, abort\n'), (... |
import scipy.ndimage.filters as filters
def smooth_opt(array, smoothing_kernel=None, smoothing_type="gaussian"):
"""
Smoothes an array, but does nothing is smoothing=None
:param array: Input nD array
:param smoothing_kernel: Smoothing kernel default: None
:param smoothing_type: How to smooth, e.g.... | [
"scipy.ndimage.filters.gaussian_filter"
] | [((477, 525), 'scipy.ndimage.filters.gaussian_filter', 'filters.gaussian_filter', (['array', 'smoothing_kernel'], {}), '(array, smoothing_kernel)\n', (500, 525), True, 'import scipy.ndimage.filters as filters\n')] |
import cv2
import numpy as np
from paz.backend.image.draw import put_text, draw_rectangle
from paz.backend.image.draw import GREEN
def draw_box(image, coordinates, class_name, score,
color=GREEN, scale=0.7, weighted=False):
x_min, y_min, x_max, y_max = coordinates
if weighted:
color = [in... | [
"cv2.rectangle",
"cv2.fillPoly",
"paz.backend.image.draw.draw_rectangle",
"numpy.array",
"cv2.circle",
"paz.backend.image.draw.put_text",
"cv2.resize"
] | [((416, 475), 'paz.backend.image.draw.put_text', 'put_text', (['image', 'text', '(x_min, y_min - 10)', 'scale', 'color', '(1)'], {}), '(image, text, (x_min, y_min - 10), scale, color, 1)\n', (424, 475), False, 'from paz.backend.image.draw import put_text, draw_rectangle\n'), ((480, 543), 'paz.backend.image.draw.draw_re... |
# -*- coding: utf-8 -*-
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from model import MetaModel, save
def main():
parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument('--data-dir', type=str, default='data/corona',
help='dat... | [
"model.save",
"model.MetaModel",
"argparse.ArgumentParser"
] | [((154, 215), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'formatter_class': 'ArgumentDefaultsHelpFormatter'}), '(formatter_class=ArgumentDefaultsHelpFormatter)\n', (168, 215), False, 'from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter\n'), ((1935, 1946), 'model.MetaModel', 'MetaModel', ([], {}),... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ~~~~~~~~~~~~~~IMPORTS~~~~~~~~~~~~~~ #
# Standard library imports
import argparse
# Local imports
import NanoCount as pkg
from NanoCount.NanoCount import NanoCount as nc
from NanoCount.common import *
# ~~~~~~~~~~~~~~MAIN PARSER ENTRY POINT~~~~~~~~~~~~~~ #
def main(... | [
"argparse.ArgumentParser"
] | [((366, 422), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': 'pkg.__description__'}), '(description=pkg.__description__)\n', (389, 422), False, 'import argparse\n')] |
#!/usr/bin/env python
# reference: c041828_ISO_IEC_14496-12_2005(E).pdf
##################################################
# reader and writer
##################################################
import struct
from io import BytesIO
def skip(stream, n):
stream.seek(stream.tell() + n)
def skip_zeros(stream, n):... | [
"getopt.getopt",
"io.BytesIO",
"struct.pack",
"struct.unpack",
"sys.exit"
] | [((557, 577), 'struct.pack', 'struct.pack', (['""">I"""', 'n'], {}), "('>I', n)\n", (568, 577), False, 'import struct\n'), ((626, 646), 'struct.pack', 'struct.pack', (['""">Q"""', 'n'], {}), "('>Q', n)\n", (637, 646), False, 'import struct\n'), ((4387, 4400), 'io.BytesIO', 'BytesIO', (['body'], {}), '(body)\n', (4394, ... |
import boto3
from botocore.exceptions import ClientError
import time
import json
import os
import decimal
from boto3.dynamodb.conditions import Key, Attr
from datetime import datetime
from datetime import timedelta
dynamodb = boto3.resource('dynamodb')
sbk_device_list_table = dynamodb.Table(os.environ['SBKDeviceListT... | [
"datetime.datetime",
"boto3.client",
"datetime.datetime.now",
"boto3.resource",
"datetime.datetime.timestamp"
] | [((228, 254), 'boto3.resource', 'boto3.resource', (['"""dynamodb"""'], {}), "('dynamodb')\n", (242, 254), False, 'import boto3\n'), ((601, 620), 'boto3.client', 'boto3.client', (['"""iot"""'], {}), "('iot')\n", (613, 620), False, 'import boto3\n'), ((763, 777), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n',... |
# pylint: disable=W0614
import os
import click
from common.click_ext import MyGroup
from common.click_ext import MyCommand
from common import click_ext
from cmds import *
manage_cmds = {
"host": "Manage host networks",
"container": "Manage containers and networks"
}
host_cmds = {
"create": "Create a new c... | [
"common.click_ext.group",
"click.Choice",
"click.argument",
"click.Path",
"click.version_option",
"click.confirmation_option"
] | [((1026, 1150), 'common.click_ext.group', 'click_ext.group', ([], {'cls': 'MyGroup', 'help': '"""A client for UTE to create containers and configure networks with openvswitch"""'}), "(cls=MyGroup, help=\n 'A client for UTE to create containers and configure networks with openvswitch'\n )\n", (1041, 1150), False, ... |
from datetime import datetime
import socket
sock = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_TCP)
PORT = 3000
address = ('127.0.0.1', PORT)
sock.bind(address)
try:
sock.listen(1)
print('--- Starting server on port {} at {} ---'.format(PORT, datetime.now().strftime('%H:%... | [
"datetime.datetime.now",
"socket.socket"
] | [((52, 121), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM', 'socket.IPPROTO_TCP'], {}), '(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)\n', (65, 121), False, 'import socket\n'), ((1074, 1088), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1086, 1088), False, 'from da... |
"""
Transform an XML corpus to and from other data formats.
"""
import os
import os.path
from setuptools import setup
here = os.path.abspath(os.path.dirname(__file__))
about = {}
with open(os.path.join(here, "corpus_converter", "__about__.py")) as f:
exec(f.read(), about)
setup(
name='corpus_converter',
... | [
"os.path.join",
"os.path.dirname",
"setuptools.setup"
] | [((280, 1300), 'setuptools.setup', 'setup', ([], {'name': '"""corpus_converter"""', 'version': "about['__version__']", 'url': "about['__url__']", 'license': "about['__license__']", 'author': "about['__author__']", 'author_email': "about['__author_email__']", 'maintainer': "about['__maintainer__']", 'maintainer_email': ... |
import pytest
import spacy
from dfm.description import MatchCounter
class TestMatchCounter:
@pytest.fixture(scope="class")
def texts(self):
texts = [
"Der kom en soldat marcherende hen ad landevejen: én, to! én, to! Han havde sit tornyster på ryggen og en sabel ved siden, for han havde vær... | [
"spacy.blank",
"dfm.description.MatchCounter.term_list_to_spacy_match_patterns",
"dfm.description.MatchCounter.list_of_labelled_term_lists_to_spacy_match_patterns",
"dfm.description.MatchCounter",
"pytest.fixture",
"dfm.description.description_patterns.get_religion_patterns"
] | [((99, 128), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""class"""'}), "(scope='class')\n", (113, 128), False, 'import pytest\n'), ((679, 708), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""class"""'}), "(scope='class')\n", (693, 708), False, 'import pytest\n'), ((886, 915), 'pytest.fixture', 'pytest... |
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http:#www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | [
"sling.RecordDatabase",
"sling.Store",
"sling.Document",
"sling.api.tolex",
"sling.DocumentSchema"
] | [((7302, 7329), 'sling.api.tolex', 'sling.api.tolex', (['self.frame'], {}), '(self.frame)\n', (7317, 7329), False, 'import sling\n'), ((8294, 8324), 'sling.RecordDatabase', 'sling.RecordDatabase', (['filename'], {}), '(filename)\n', (8314, 8324), False, 'import sling\n'), ((8793, 8833), 'sling.Document', 'sling.Documen... |
import time
from chatty.sessions.interface import Session
from chatty.signals.interface import Signal
class EchoSession(Session):
"""
A session which simply echos any signal it is asked to send back to its own bots.
"""
def __init__(self):
super().__init__()
self._alive = True
d... | [
"time.sleep"
] | [((522, 541), 'time.sleep', 'time.sleep', (['timeout'], {}), '(timeout)\n', (532, 541), False, 'import time\n'), ((482, 495), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (492, 495), False, 'import time\n')] |
import torch
import torch.nn as nn
from torchtext import data, datasets
import spacy
spacy.load('en')
class SNLI():
def __init__(self, device, batch_size=128):
self.inputs = data.Field(lower=True, tokenize='spacy', batch_first=True)
self.targets = data.Field(sequential=False, unk_token=None, is_target=True)
s... | [
"spacy.load",
"torchtext.data.Iterator",
"torchtext.datasets.SNLI.splits",
"torchtext.data.Field"
] | [((86, 102), 'spacy.load', 'spacy.load', (['"""en"""'], {}), "('en')\n", (96, 102), False, 'import spacy\n'), ((180, 238), 'torchtext.data.Field', 'data.Field', ([], {'lower': '(True)', 'tokenize': '"""spacy"""', 'batch_first': '(True)'}), "(lower=True, tokenize='spacy', batch_first=True)\n", (190, 238), False, 'from t... |
import torch
import torch.nn as nn
'''
采用RNNCell、LSTMCell、GRUCell重构RNN、LSTM和GRU模型,解决序列对齐问题并做灵活扩充
LSTMCell (input_size, hidden_size, bias=True)
输入: input, (h_0, c_0)
input (seq_len, batch, input_size): 包含输入序列特征的Tensor。也可以是packed variable
h_0 (batch, hidden_size): 保存着batch中每个元素的初始化隐状态的Tensor
... | [
"torch.bernoulli",
"torch.nn.ModuleList",
"torch.zeros",
"torch.randn",
"torch.cat",
"torch.device"
] | [((3187, 3202), 'torch.nn.ModuleList', 'nn.ModuleList', ([], {}), '()\n', (3200, 3202), True, 'import torch.nn as nn\n'), ((3228, 3243), 'torch.nn.ModuleList', 'nn.ModuleList', ([], {}), '()\n', (3241, 3243), True, 'import torch.nn as nn\n'), ((5930, 5949), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\... |
import xlrd
import typing
import re
# from termcolor import colored
class Controle:
def __init__(self) -> None:
self.__planilha_esocial = None
self.__planilha_candidata = None
self.__relatorio:typing.IO = None
def set_planilha_esocial(self, nome_pasta_esocial:str) -> None:
... | [
"re.sub",
"xlrd.open_workbook"
] | [((358, 396), 'xlrd.open_workbook', 'xlrd.open_workbook', (['nome_pasta_esocial'], {}), '(nome_pasta_esocial)\n', (376, 396), False, 'import xlrd\n'), ((762, 802), 'xlrd.open_workbook', 'xlrd.open_workbook', (['nome_pasta_candidata'], {}), '(nome_pasta_candidata)\n', (780, 802), False, 'import xlrd\n'), ((1984, 2019), ... |
import numpy as np
from sklearn.metrics.pairwise import pairwise_distances
class MahaDist:
def __init__(self, bandwidth_factor=1.0):
self.bandwidth = 1.
if type(bandwidth_factor) in [float, int]:
self.bandwidth_factor = bandwidth_factor
elif type(bandwidth_factor) in [list, tu... | [
"numpy.isscalar",
"numpy.diag",
"sklearn.metrics.pairwise.pairwise_distances",
"numpy.array",
"numpy.zeros",
"numpy.einsum"
] | [((704, 769), 'sklearn.metrics.pairwise.pairwise_distances', 'pairwise_distances', (['X', 'Y'], {'metric': '"""mahalanobis"""', 'VI': 'self.bandwidth'}), "(X, Y, metric='mahalanobis', VI=self.bandwidth)\n", (722, 769), False, 'from sklearn.metrics.pairwise import pairwise_distances\n'), ((821, 844), 'numpy.zeros', 'np.... |
import os
import numpy as np
import SharedArray as SA
from torch.utils.data import Dataset
from util.data_util import sa_create
from util.data_util import data_prepare
class S3DIS(Dataset):
def __init__(self, split='train', data_root='trainval', test_area=5, voxel_size=0.04, voxel_max=None, transform=None, shuf... | [
"os.listdir",
"os.path.join",
"util.data_util.data_prepare",
"numpy.load"
] | [((1582, 1700), 'util.data_util.data_prepare', 'data_prepare', (['coord', 'feat', 'label', 'self.split', 'self.voxel_size', 'self.voxel_max', 'self.transform', 'self.shuffle_index'], {}), '(coord, feat, label, self.split, self.voxel_size, self.\n voxel_max, self.transform, self.shuffle_index)\n', (1594, 1700), False... |
import os
import subprocess
from distutils import spawn
import fire
import toml
from cookiecutter import exceptions
from cookiecutter.main import cookiecutter
from loguru import logger
class Main:
@property
def version(self):
try:
return self._version
except AttributeError:
... | [
"distutils.spawn.find_executable",
"loguru.logger.info",
"fire.Fire",
"subprocess.run",
"loguru.logger.warning",
"cookiecutter.main.cookiecutter",
"os.chdir",
"loguru.logger.error",
"toml.load"
] | [((1947, 1962), 'fire.Fire', 'fire.Fire', (['Main'], {}), '(Main)\n', (1956, 1962), False, 'import fire\n'), ((570, 598), 'distutils.spawn.find_executable', 'spawn.find_executable', (['"""git"""'], {}), "('git')\n", (591, 598), False, 'from distutils import spawn\n'), ((612, 662), 'loguru.logger.warning', 'logger.warni... |
#!/usr/bin/env python
"""
MiP Sound tester.
To Use:
mip_test_sound.py -i hci0 -b D0:39:72:C4:7A:01 -s <n>
<n> 1 - 106
1 = beep
2 = burp
3 = ewwp - ah
4 = la la la la (lower)
5 = small raspberry?
6 = rerrr
7 = punching sound
8 = punching sound
9 = harder punching sound
10 = lep
11 = lep
12 = lep
13 = lep
14 = ahhh! (in... | [
"mippy.add_arguments",
"mippy.GattTool",
"argparse.ArgumentParser",
"mippy.Mip"
] | [((2537, 2592), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Test MiP Sounds."""'}), "(description='Test MiP Sounds.')\n", (2560, 2592), False, 'import argparse\n'), ((2597, 2624), 'mippy.add_arguments', 'mippy.add_arguments', (['parser'], {}), '(parser)\n', (2616, 2624), False, 'impor... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Sample script to print a list of events from the specified controller and app.
"""
from __future__ import print_function
from appd.cmdline import parse_argv
from appd.request import AppDynamicsClient
__author__ = '<NAME>'
__copyright__ = 'Copyright (c) 2013-2017 Ap... | [
"appd.request.AppDynamicsClient",
"appd.cmdline.parse_argv"
] | [((345, 357), 'appd.cmdline.parse_argv', 'parse_argv', ([], {}), '()\n', (355, 357), False, 'from appd.cmdline import parse_argv\n'), ((362, 451), 'appd.request.AppDynamicsClient', 'AppDynamicsClient', (['args.url', 'args.username', 'args.password', 'args.account', 'args.verbose'], {}), '(args.url, args.username, args.... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Pretrained models used by unit tests.
"""
from parlai.core.build_data import download_models
def download(datapat... | [
"parlai.core.build_data.download_models"
] | [((585, 650), 'parlai.core.build_data.download_models', 'download_models', (['opt', 'model_filenames', '"""unittest"""'], {'version': '"""v5.0"""'}), "(opt, model_filenames, 'unittest', version='v5.0')\n", (600, 650), False, 'from parlai.core.build_data import download_models\n')] |
import os
import json
import datetime
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def timeConversion(value):
if value==0:
return "UNKNOWN"
else:
return datetime.datetime.fromtimestamp(value).isoformat()
def main():
file_path="facebook-data\likes_and_reac... | [
"matplotlib.pyplot.grid",
"datetime.datetime.fromtimestamp",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.rcParams.update",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.bar",
"datetime.datetime.today",
"json.load",
"matplotlib.pyplot.ti... | [((418, 433), 'json.load', 'json.load', (['file'], {}), '(file)\n', (427, 433), False, 'import json\n'), ((2378, 2406), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(30, 10)'}), '(figsize=(30, 10))\n', (2388, 2406), True, 'import matplotlib.pyplot as plt\n'), ((2422, 2462), 'matplotlib.pyplot.rcParams.up... |
import os
import numpy as np
import pandas as pd
import torch
from torch.nn import functional as F
from transformers import AutoTokenizer, AutoConfig
from built.registry import Registry
@Registry.register(category='dataset')
class TweetSentimentDataset(torch.utils.data.Dataset):
def __init__(self, transformer_pa... | [
"built.registry.Registry.register",
"transformers.AutoConfig.from_pretrained",
"pandas.read_csv",
"torch.tensor",
"transformers.AutoTokenizer.from_pretrained",
"torch.squeeze"
] | [((190, 227), 'built.registry.Registry.register', 'Registry.register', ([], {'category': '"""dataset"""'}), "(category='dataset')\n", (207, 227), False, 'from built.registry import Registry\n'), ((433, 454), 'pandas.read_csv', 'pd.read_csv', (['csv_path'], {}), '(csv_path)\n', (444, 454), True, 'import pandas as pd\n')... |
import gym, os
from os import path
import gym_solventx
from DQAgent import DQAgent
env = gym.make('gym_solventx-v0')
root_path = './best_results/'
agent_opts = {
#hyperparameters
'REPLAY_BATCH_SIZE': 64,
'LEARNING_BATCH_SIZE': 8,
'DISCOUNT... | [
"gym.make",
"DQAgent.DQAgent"
] | [((95, 122), 'gym.make', 'gym.make', (['"""gym_solventx-v0"""'], {}), "('gym_solventx-v0')\n", (103, 122), False, 'import gym, os\n'), ((1566, 1592), 'DQAgent.DQAgent', 'DQAgent', (['env'], {}), '(env, **agent_opts)\n', (1573, 1592), False, 'from DQAgent import DQAgent\n'), ((1879, 1905), 'DQAgent.DQAgent', 'DQAgent', ... |
import numpy as np
from sklearn.decomposition import PCA
def project_embeddings_and_centroids_together(embeddings, centroids, masks):
original_embeddings_shape = embeddings.shape
embeddings = np.reshape(embeddings, (-1, embeddings.shape[2]))
points = np.concatenate([centroids, embeddings], axis=0)
m... | [
"sklearn.decomposition.PCA",
"numpy.reshape",
"numpy.concatenate"
] | [((203, 252), 'numpy.reshape', 'np.reshape', (['embeddings', '(-1, embeddings.shape[2])'], {}), '(embeddings, (-1, embeddings.shape[2]))\n', (213, 252), True, 'import numpy as np\n'), ((266, 313), 'numpy.concatenate', 'np.concatenate', (['[centroids, embeddings]'], {'axis': '(0)'}), '([centroids, embeddings], axis=0)\n... |
#!/usr/bin/env python
# coding=utf-8
import os
import re
import shutil
SOURCE_DIR = '../../data/gtFine'
subpaths = os.listdir(SOURCE_DIR)
OUT_DIR = '../../data/Json_files'
pattern = r'.+.json$'
# for subpath in ['train', 'test', 'val']
for subpath in subpaths:
# join the './gtFine' for walk dir
tmp_subpath ... | [
"os.listdir",
"os.path.join",
"re.match",
"shutil.copy",
"os.walk"
] | [((118, 140), 'os.listdir', 'os.listdir', (['SOURCE_DIR'], {}), '(SOURCE_DIR)\n', (128, 140), False, 'import os\n'), ((322, 355), 'os.path.join', 'os.path.join', (['SOURCE_DIR', 'subpath'], {}), '(SOURCE_DIR, subpath)\n', (334, 355), False, 'import os\n'), ((513, 543), 'os.path.join', 'os.path.join', (['OUT_DIR', 'subp... |
#
# Copyright (c) 2016 Juniper Networks, Inc. All rights reserved.
#
from vnc_api.vnc_api import *
from kube_manager.vnc.config_db import *
import uuid
LOG = logging.getLogger(__name__)
class ServiceLbManager(object):
def __init__(self, vnc_lib=None, logger=None):
self._vnc_lib = vnc_lib
self.l... | [
"uuid.uuid1",
"uuid.uuid4"
] | [((996, 1008), 'uuid.uuid1', 'uuid.uuid1', ([], {}), '()\n', (1006, 1008), False, 'import uuid\n'), ((3079, 3091), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (3089, 3091), False, 'import uuid\n'), ((6707, 6719), 'uuid.uuid1', 'uuid.uuid1', ([], {}), '()\n', (6717, 6719), False, 'import uuid\n'), ((8448, 8460), 'uuid... |
from typing import Union, List
import emojis
from InquirerPy import prompt
from project.interface import ISkill
def select_skill(available_skills: List[ISkill]) -> Union[str, bool, list, ISkill]:
"""
Question function, to query user for available skills to use.
:param List[ISkill] available_skills: Ski... | [
"InquirerPy.prompt",
"emojis.encode"
] | [((1652, 1685), 'InquirerPy.prompt', 'prompt', ([], {'questions': 'skill_questions'}), '(questions=skill_questions)\n', (1658, 1685), False, 'from InquirerPy import prompt\n'), ((1224, 1252), 'emojis.encode', 'emojis.encode', (['"""Cancel :x: """'], {}), "('Cancel :x: ')\n", (1237, 1252), False, 'import emojis\n'), ((1... |
from django.urls import path
from . import views
urlpatterns = [
path('api/stories', views.StoryList.as_view()),
path('api/stories/profile/<int:author_pk>', views.author_stories),
path('api/stories/profile/<int:author_pk>/drafts/<int:drafts>', views.author_stories),
path('api/stories/popular', views.po... | [
"django.urls.path"
] | [((122, 187), 'django.urls.path', 'path', (['"""api/stories/profile/<int:author_pk>"""', 'views.author_stories'], {}), "('api/stories/profile/<int:author_pk>', views.author_stories)\n", (126, 187), False, 'from django.urls import path\n'), ((193, 283), 'django.urls.path', 'path', (['"""api/stories/profile/<int:author_p... |
import numpy as np
from scattertext.termscoring.CohensDCalculator import CohensDCalculator
from scattertext.termscoring.CorpusBasedTermScorer import CorpusBasedTermScorer
class CohensD(CorpusBasedTermScorer, CohensDCalculator):
'''
Cohen's d scores
term_scorer = (CohensD(corpus).set_categories('Positive... | [
"numpy.isnan"
] | [((1592, 1603), 'numpy.isnan', 'np.isnan', (['X'], {}), '(X)\n', (1600, 1603), True, 'import numpy as np\n')] |
import argparse
import json
from PIL import Image
import torch
import numpy as np
from math import ceil
from train import check_gpu
from torchvision import models, transforms
def arg_parser():
parser = argparse.ArgumentParser(description="Prediction settings")
parser.add_argument('-i', '--image', ty... | [
"torchvision.transforms.CenterCrop",
"PIL.Image.open",
"argparse.ArgumentParser",
"torch.load",
"torchvision.transforms.Resize",
"torch.exp",
"train.check_gpu",
"numpy.array",
"torchvision.transforms.Normalize",
"json.load",
"torch.no_grad",
"torchvision.transforms.ToTensor",
"torchvision.mo... | [((213, 271), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Prediction settings"""'}), "(description='Prediction settings')\n", (236, 271), False, 'import argparse\n'), ((903, 930), 'torch.load', 'torch.load', (['checkpoint_path'], {}), '(checkpoint_path)\n', (913, 930), False, 'import ... |