code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import torch
import torch.nn.functional as F
from .gradcam import GradCAM
class GradCAMpp(GradCAM):
"""
GradCAM++, inherit from BaseCAM
"""
def __init__(self, model_dict):
super(GradCAMpp, self).__init__(model_dict)
def forward(self, input_image, class_idx=None, retain_graph=False):
... | [
"torch.ones_like",
"torch.nn.functional.interpolate",
"torch.nn.functional.relu"
] | [((1712, 1732), 'torch.nn.functional.relu', 'F.relu', (['saliency_map'], {}), '(saliency_map)\n', (1718, 1732), True, 'import torch.nn.functional as F\n'), ((1756, 1843), 'torch.nn.functional.interpolate', 'F.interpolate', (['saliency_map'], {'size': '(224, 224)', 'mode': '"""bilinear"""', 'align_corners': '(False)'}),... |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Teampro and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe, math, json
# import erpnext
from frappe import _
from frappe.utils import flt, rounded, add_months, nowdate, getdate, now_datetime
from paypro... | [
"frappe.utils.flt",
"frappe.utils.now_datetime",
"frappe.utils.rounded",
"math.ceil",
"frappe.whitelist",
"frappe.db.sql",
"frappe.db.get_value",
"frappe.db.set_value",
"frappe.new_doc",
"frappe.bold",
"frappe.get_doc",
"frappe._",
"frappe.utils.nowdate",
"frappe.utils.add_months",
"frap... | [((7256, 7274), 'frappe.whitelist', 'frappe.whitelist', ([], {}), '()\n', (7272, 7274), False, 'import frappe, math, json\n'), ((7588, 7606), 'frappe.whitelist', 'frappe.whitelist', ([], {}), '()\n', (7604, 7606), False, 'import frappe, math, json\n'), ((8156, 8174), 'frappe.whitelist', 'frappe.whitelist', ([], {}), '(... |
import importlib
import pkgutil
import sys
import logging
import re
from PySide2 import QtWidgets
from . import plugins
def dcc_plugins():
_plugins = all_plugins()
dcc_plugins = {key: value for key, value in _plugins.items() if '_' not in key}
return dcc_plugins
def all_plugins():
_plugins = {}
... | [
"re.escape",
"logging.error",
"pkgutil.iter_modules",
"importlib.import_module"
] | [((1145, 1205), 'pkgutil.iter_modules', 'pkgutil.iter_modules', (['ns_pkg.__path__', "(ns_pkg.__name__ + '.')"], {}), "(ns_pkg.__path__, ns_pkg.__name__ + '.')\n", (1165, 1205), False, 'import pkgutil\n'), ((1352, 1400), 'importlib.import_module', 'importlib.import_module', (['plugin'], {'package': 'package'}), '(plugi... |
import json
import logging
from typing import Generator, Optional, Type, TypeVar
from urllib.parse import urlencode, urljoin
from urllib.request import urlopen
import requests
from thenewboston_node.business_logic.blockchain.base import BlockchainBase
from thenewboston_node.business_logic.blockchain.file_blockchain.s... | [
"urllib.parse.urljoin",
"urllib.parse.urlencode",
"thenewboston_node.business_logic.blockchain.file_blockchain.sources.URLBlockSource",
"urllib.request.urlopen",
"thenewboston_node.business_logic.utils.blockchain_state.read_blockchain_state_file_from_source",
"requests.get",
"typing.TypeVar",
"logging... | [((595, 622), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (612, 622), False, 'import logging\n'), ((628, 660), 'typing.TypeVar', 'TypeVar', (['"""T"""'], {'bound': '"""NodeClient"""'}), "('T', bound='NodeClient')\n", (635, 660), False, 'from typing import Generator, Optional, Type, Typ... |
import unittest, time, sys
sys.path.extend(['.','..','py'])
import h2o, h2o_cmd, h2o_hosts, h2o_import as h2i
class Basic(unittest.TestCase):
def tearDown(self):
h2o.check_sandbox_for_errors()
@classmethod
def setUpClass(cls):
localhost = h2o.decide_if_localhost()
if (localhost):
... | [
"h2o.tear_down_cloud",
"h2o.unit_main",
"h2o_cmd.runRF",
"h2o.build_cloud",
"sys.path.extend",
"h2o_hosts.build_cloud_with_hosts",
"h2o_import.import_parse",
"h2o.check_sandbox_for_errors",
"h2o.decide_if_localhost"
] | [((27, 61), 'sys.path.extend', 'sys.path.extend', (["['.', '..', 'py']"], {}), "(['.', '..', 'py'])\n", (42, 61), False, 'import unittest, time, sys\n'), ((842, 857), 'h2o.unit_main', 'h2o.unit_main', ([], {}), '()\n', (855, 857), False, 'import h2o, h2o_cmd, h2o_hosts, h2o_import as h2i\n'), ((175, 205), 'h2o.check_sa... |
# Copyright 2013 OpenStack Foundation
#
# 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... | [
"oslo_log.log.getLogger",
"keystone.exception.UnexpectedError",
"keystone.exception.Unauthorized",
"keystone.common.dependency.requires",
"keystone.token.provider.audit_info",
"keystone.openstack.common.versionutils.deprecated",
"oslo_utils.timeutils.isotime",
"keystone.token.provider.default_expire_t... | [((1026, 1049), 'oslo_log.log.getLogger', 'log.getLogger', (['__name__'], {}), '(__name__)\n', (1039, 1049), False, 'from oslo_log import log\n'), ((1069, 1169), 'keystone.common.dependency.requires', 'dependency.requires', (['"""assignment_api"""', '"""catalog_api"""', '"""identity_api"""', '"""resource_api"""', '"""r... |
from __future__ import division
import numpy as np
from pdb import set_trace
class Counter:
def __init__(self, before, after, indx):
self.indx = indx
self.actual = before
self.predicted = after
self.TP, self.TN, self.FP, self.FN = 0, 0, 0, 0
for a, b in zip(self.actual, sel... | [
"numpy.sqrt"
] | [((1004, 1023), 'numpy.sqrt', 'np.sqrt', (['(Sen * Spec)'], {}), '(Sen * Spec)\n', (1011, 1023), True, 'import numpy as np\n')] |
"""
forms.py
Web forms based on Flask-WTForms
See: http://flask.pocoo.org/docs/patterns/wtforms/
http://wtforms.simplecodes.com/
"""
from flaskext import wtf
from flaskext.wtf import validators
from wtforms.ext.appengine.ndb import model_form
from .models import SchoolModel
class ClassicExampleForm(wtf.Form... | [
"flaskext.wtf.validators.Required"
] | [((376, 397), 'flaskext.wtf.validators.Required', 'validators.Required', ([], {}), '()\n', (395, 397), False, 'from flaskext.wtf import validators\n'), ((471, 492), 'flaskext.wtf.validators.Required', 'validators.Required', ([], {}), '()\n', (490, 492), False, 'from flaskext.wtf import validators\n'), ((630, 651), 'fla... |
"""Blocks of layers to build models.
"""
import tensorflow as tf
from tensorflow.keras import layers as kl
def conv2d_block(filters,
kernel_size=(3, 3),
strides=(1, 1),
padding='same',
activation='relu',
batch_normalization=True,
... | [
"tensorflow.keras.layers.Conv2D",
"tensorflow.keras.layers.BatchNormalization",
"tensorflow.concat",
"tensorflow.keras.layers.PReLU",
"tensorflow.keras.layers.Activation"
] | [((367, 439), 'tensorflow.keras.layers.Conv2D', 'kl.Conv2D', (['filters', 'kernel_size', 'strides', 'padding'], {'name': "(name + '/conv2d')"}), "(filters, kernel_size, strides, padding, name=name + '/conv2d')\n", (376, 439), True, 'from tensorflow.keras import layers as kl\n'), ((573, 613), 'tensorflow.keras.layers.Ba... |
import pytest
import mock
import json
from prometheus_udp_gateway import (
ReceiveMetricProtocol, UDPRegistry, Counter
)
@pytest.fixture()
def udp_registry():
return UDPRegistry(host='invalid', port=0000)
@pytest.fixture()
def counter(udp_registry):
counter = Counter('test_counter', '... | [
"pytest.fixture",
"json.dumps",
"prometheus_udp_gateway.Counter",
"prometheus_udp_gateway.UDPRegistry",
"mock.Mock",
"mock.MagicMock"
] | [((140, 156), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (154, 156), False, 'import pytest\n'), ((235, 251), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (249, 251), False, 'import pytest\n'), ((892, 908), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (906, 908), False, 'import pytest\n'), (... |
import json
import random
import networkx as nx
from tiledb.cloud.dag import status as st
def build_graph_node_details(nodes):
"""
:param nodes: List of nodes to get status of
:return: tuple of node_colors and node_text
"""
# Loop over statuses to set color and label.
# If you rerun this cel... | [
"networkx.drawing.nx_pydot.pydot_layout",
"networkx.descendants",
"networkx.topological_sort",
"networkx.node_connected_component",
"networkx.is_tree"
] | [((4470, 4483), 'networkx.is_tree', 'nx.is_tree', (['G'], {}), '(G)\n', (4480, 4483), True, 'import networkx as nx\n'), ((8439, 8472), 'networkx.drawing.nx_pydot.pydot_layout', 'pydot_layout', (['network'], {'prog': '"""dot"""'}), "(network, prog='dot')\n", (8451, 8472), False, 'from networkx.drawing.nx_pydot import py... |
from __future__ import annotations
import operator
from typing import Any, Collection, Dict, Literal, Optional, Union
import cytoolz
from .. import errors, types
from . import basics
WeightingType = Literal["count", "freq", "binary"]
SpanGroupByType = Literal["lemma", "lemma_", "lower", "lower_", "orth", "orth_"]
T... | [
"operator.attrgetter"
] | [((2670, 2693), 'operator.attrgetter', 'operator.attrgetter', (['by'], {}), '(by)\n', (2689, 2693), False, 'import operator\n'), ((6124, 6148), 'operator.attrgetter', 'operator.attrgetter', (['by_'], {}), '(by_)\n', (6143, 6148), False, 'import operator\n')] |
'''
Author : <NAME>
Description :
-------------
The following code lets you click on a set of points and then create a curve that fits the set of points.
In order to execute this code, you need to install bokeh,
'''
from bokeh.io import curdoc
from bokeh.plotting import figure, output_file
from bokeh.la... | [
"bokeh.models.ColumnDataSource",
"bokeh.models.PointDrawTool",
"bokeh.plotting.figure",
"bokeh.models.Button",
"os.system",
"numpy.append",
"bokeh.io.curdoc",
"numpy.array",
"bokeh.layouts.column",
"scipy.interpolate.interp1d",
"scipy.spatial.ConvexHull",
"bokeh.layouts.row"
] | [((1052, 1159), 'bokeh.plotting.figure', 'figure', ([], {'title': '"""CAD/Curves/Curve Fit"""', 'plot_width': '(800)', 'plot_height': '(500)', 'x_range': '(-5, 5)', 'y_range': '(-5, 5)'}), "(title='CAD/Curves/Curve Fit', plot_width=800, plot_height=500,\n x_range=(-5, 5), y_range=(-5, 5))\n", (1058, 1159), False, 'f... |
# -*- mode:python; coding:utf-8 -*-
# Copyright (c) 2021 IBM Corp. 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
#
# ... | [
"compliance.utils.data_parse.get_sha256_hash",
"compliance.utils.services.github.Github",
"compliance.evidence.RawEvidence",
"json.dumps"
] | [((1607, 1643), 'compliance.utils.data_parse.get_sha256_hash', 'get_sha256_hash', (["[config['url']]", '(10)'], {}), "([config['url']], 10)\n", (1622, 1643), False, 'from compliance.utils.data_parse import get_sha256_hash\n'), ((1949, 1996), 'compliance.evidence.RawEvidence', 'RawEvidence', (['path[1]', 'path[0]', 'DAY... |
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__copyright__ = 'Copyright (c) 2021, AdW Project'
import numpy as np
from scipy.stats import kstest
from copulas import get_instance
def select_univariate(X, candidates, margin_fit_method='AIC'):
best_mesure = np.inf
best_model = None
for model in candidates:
... | [
"scipy.stats.kstest",
"copulas.get_instance"
] | [((864, 888), 'copulas.get_instance', 'get_instance', (['best_model'], {}), '(best_model)\n', (876, 888), False, 'from copulas import get_instance\n'), ((1168, 1191), 'scipy.stats.kstest', 'kstest', (['X', 'instance.cdf'], {}), '(X, instance.cdf)\n', (1174, 1191), False, 'from scipy.stats import kstest\n'), ((357, 376)... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
from mpl_toolkits.axes_grid1 import make_axes_locatable
from .GetDataAvailability import GetDataAvailability
import DateTimeTools as TT
months = ['J','F','M','A','M','J','J','A','S','O','N','D']
def PlotDataAvailability(Stations,Da... | [
"numpy.meshgrid",
"matplotlib.colors.Normalize",
"numpy.float32",
"numpy.zeros",
"numpy.where",
"numpy.arange",
"DateTimeTools.DateSplit"
] | [((684, 703), 'numpy.meshgrid', 'np.meshgrid', (['xe', 'ye'], {}), '(xe, ye)\n', (695, 703), True, 'import numpy as np\n'), ((800, 815), 'DateTimeTools.DateSplit', 'TT.DateSplit', (['x'], {}), '(x)\n', (812, 815), True, 'import DateTimeTools as TT\n'), ((1404, 1450), 'matplotlib.colors.Normalize', 'colors.Normalize', (... |
'''
This creates a 3D pyramid pattern of blocks.
@author: MKC
'''
from karelcraft.karelcraft import *
import random
TEXTURES = ('grass', 'stone', 'brick', 'dirt', 'lava', 'rose',
'dlsu', 'diamond', 'emerald', 'gold', 'obsidian',
'leaves', 'sand', 'wood', 'stonebrick', 'sponge', 'snow')
def ... | [
"random.choice"
] | [((470, 493), 'random.choice', 'random.choice', (['TEXTURES'], {}), '(TEXTURES)\n', (483, 493), False, 'import random\n'), ((1053, 1076), 'random.choice', 'random.choice', (['TEXTURES'], {}), '(TEXTURES)\n', (1066, 1076), False, 'import random\n')] |
# -*- coding: utf-8 -*-
"""
Created on 23/11/17
Author : <NAME>
Project definitions
"""
import os
import getpass
import matplotlib.pyplot as plt
from astropy.coordinates import SkyCoord
import astropy.units as u
from dustmaps.config import config
from dustmaps import sfd
if getpass.getuser() == "kadu":
home ... | [
"getpass.getuser",
"os.path.join",
"dustmaps.sfd.SFDQuery",
"os.path.exists",
"matplotlib.pyplot.style.context",
"dustmaps.sfd.fetch",
"astropy.coordinates.SkyCoord"
] | [((453, 479), 'os.path.join', 'os.path.join', (['home', '"""data"""'], {}), "(home, 'data')\n", (465, 479), False, 'import os\n'), ((502, 536), 'os.path.join', 'os.path.join', (['data_dir', '"""dustmaps"""'], {}), "(data_dir, 'dustmaps')\n", (514, 536), False, 'import os\n'), ((1113, 1132), 'astropy.coordinates.SkyCoor... |
from ..molecule import Molecule
import path
class Linear(path.Path):
""" A linear interpolator that generates n-2 new molecules
"""
def __init__(self, initial, final, nsteps=10):
path.Path.__init__(self)
assert isinstance(nsteps, int)
self._molecules = [initial]
ci = ini... | [
"path.Path.__init__"
] | [((201, 225), 'path.Path.__init__', 'path.Path.__init__', (['self'], {}), '(self)\n', (219, 225), False, 'import path\n')] |
# Copyright 2014 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | [
"glance.i18n._LW",
"glance.scrubber.get_scrub_queue",
"oslo_log.log.getLogger",
"oslo_utils.encodeutils.exception_to_unicode",
"glance.i18n._LE",
"glance.db.get_api",
"glance_store.delete_from_backend",
"glance_store.get_known_schemes",
"sys.exc_info",
"six.moves.urllib.parse.urlparse"
] | [((887, 914), 'oslo_log.log.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (904, 914), True, 'from oslo_log import log as logging\n'), ((2585, 2611), 'glance.scrubber.get_scrub_queue', 'scrubber.get_scrub_queue', ([], {}), '()\n', (2609, 2611), False, 'from glance import scrubber\n'), ((1471, 1534... |
# steps to preprocess squad files
# 1. read squad json file, extract all context, write to file, one context per line
# 2. use corenlp to process the above file, write to a new annotated file
# 3. rea the annotated json file; for each context, create a vector of len(#words in context), indicate the sentence
# idx o... | [
"copy.deepcopy",
"json.load",
"codecs.open",
"argparse.ArgumentParser",
"json.loads",
"math.floor",
"os.path.join",
"os.listdir"
] | [((1665, 1726), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Process some integers."""'}), "(description='Process some integers.')\n", (1688, 1726), False, 'import argparse\n'), ((2378, 2390), 'json.load', 'json.load', (['f'], {}), '(f)\n', (2387, 2390), False, 'import json\n'), ((2243... |
# https://pytorchnlp.readthedocs.io/en/latest/_modules/torchnlp/nn/attention.html
import torch
import torch.nn as nn
class Attention(nn.Module):
""" Applies attention mechanism on the `context` using the `query`.
**Thank you** to IBM for their initial implementation of :class:`Attention`. Here is
their `L... | [
"torch.bmm",
"torch.nn.Tanh",
"torch.cat",
"torch.nn.Softmax",
"torch.nn.Linear"
] | [((1421, 1470), 'torch.nn.Linear', 'nn.Linear', (['(dimensions * 2)', 'dimensions'], {'bias': '(False)'}), '(dimensions * 2, dimensions, bias=False)\n', (1430, 1470), True, 'import torch.nn as nn\n'), ((1494, 1512), 'torch.nn.Softmax', 'nn.Softmax', ([], {'dim': '(-1)'}), '(dim=-1)\n', (1504, 1512), True, 'import torch... |
from app.common.adapter.repositories.sql import db
from ....domain.models import Author, Tag, TagId, Article, ArticleId
tag = db.Table(
'tag',
db.Column('id', db.BigInteger, primary_key=True, unique=True, key='__id'),
db.Column('name', db.String(50), unique=True)
)
TagId.__composite_values__ = lambda self... | [
"app.common.adapter.repositories.sql.db.ForeignKey",
"app.common.adapter.repositories.sql.db.DateTime",
"app.common.adapter.repositories.sql.db.String",
"app.common.adapter.repositories.sql.db.relationship",
"app.common.adapter.repositories.sql.db.composite",
"app.common.adapter.repositories.sql.db.Column... | [((152, 225), 'app.common.adapter.repositories.sql.db.Column', 'db.Column', (['"""id"""', 'db.BigInteger'], {'primary_key': '(True)', 'unique': '(True)', 'key': '"""__id"""'}), "('id', db.BigInteger, primary_key=True, unique=True, key='__id')\n", (161, 225), False, 'from app.common.adapter.repositories.sql import db\n'... |
# this script is based on ./examples/cars segmentation (camvid).ipynb
# ========== loading data ==========
'''
For this example, we will use PASCAL2012 dataset. It is a set of:
- train images + instance segmentation masks
- validation images + instance segmentation masks
'''
import os
os.environ['CUDA_VISIBLE_DEVICES']... | [
"numpy.absolute",
"segmentation_models_pytorch.utils.train.ValidEpoch",
"albumentations.Lambda",
"numpy.sum",
"scipy.ndimage.measurements.label",
"numpy.ones",
"segmentation_models_pytorch.utils.train.TrainEpoch",
"matplotlib.pyplot.figure",
"skimage.transform.resize",
"numpy.arange",
"segmentat... | [((702, 738), 'os.path.join', 'os.path.join', (['DATA_DIR', '"""JPEGImages"""'], {}), "(DATA_DIR, 'JPEGImages')\n", (714, 738), False, 'import os\n'), ((747, 791), 'os.path.join', 'os.path.join', (['DATA_DIR', '"""SegmentationObject"""'], {}), "(DATA_DIR, 'SegmentationObject')\n", (759, 791), False, 'import os\n'), ((8... |
import unittest.mock as umock
from argparse import ArgumentTypeError
import numpy as np
import pytest
from functions import do_embossing, do_edge_detection, do_blur_5x5, do_blur_3x3, do_sharpen, do_bw, do_darken, \
do_inverse, do_lighten, do_mirror, do_rotate, percentage, read_image, save_image
test_array = np.a... | [
"functions.do_bw",
"functions.do_lighten",
"unittest.mock.MagicMock",
"functions.percentage",
"functions.do_darken",
"functions.do_inverse",
"functions.do_blur_5x5",
"numpy.all",
"functions.do_rotate",
"functions.do_embossing",
"functions.save_image",
"pytest.raises",
"numpy.array",
"funct... | [((316, 359), 'numpy.array', 'np.array', (['[[1, 1, 1], [1, 1, 1], [1, 1, 1]]'], {}), '([[1, 1, 1], [1, 1, 1], [1, 1, 1]])\n', (324, 359), True, 'import numpy as np\n'), ((374, 412), 'functions.read_image', 'read_image', (['"""test_images/test_img.png"""'], {}), "('test_images/test_img.png')\n", (384, 412), False, 'fro... |
import math
def equation(x):
y = math.sqrt(1 - math.pow(x,2))
return y
def mean(big,small):
mean = (big+small)/2
return mean
piece, radius = 0, 1
n = int(input())
small = 0
bottom = []
for i in range(0,n):
piece = float("%.6f" % (piece+(radius/n)))
bottom.append(piece)
print(bottom)
top = []
f... | [
"math.pow"
] | [((51, 65), 'math.pow', 'math.pow', (['x', '(2)'], {}), '(x, 2)\n', (59, 65), False, 'import math\n')] |
from flask import Flask
from flask_cors import CORS, cross_origin
from conversational_wrapper import ConversationalWrapper
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--path', help='The path to your collection of Markdown files.', type=str)
args = parser.parse_args()
app = Flask(__name__)
... | [
"argparse.ArgumentParser",
"flask_cors.CORS",
"flask.Flask",
"flask_cors.cross_origin",
"conversational_wrapper.ConversationalWrapper"
] | [((149, 174), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (172, 174), False, 'import argparse\n'), ((304, 319), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (309, 319), False, 'from flask import Flask\n'), ((327, 336), 'flask_cors.CORS', 'CORS', (['app'], {}), '(app)\n', (331,... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | [
"pydolphinscheduler.tasks.switch.Switch",
"pydolphinscheduler.tasks.switch.Default",
"pydolphinscheduler.tasks.shell.Shell",
"pydolphinscheduler.tasks.switch.Branch",
"pydolphinscheduler.core.process_definition.ProcessDefinition"
] | [((1510, 1579), 'pydolphinscheduler.core.process_definition.ProcessDefinition', 'ProcessDefinition', ([], {'name': '"""task_switch_example"""', 'tenant': '"""tenant_exists"""'}), "(name='task_switch_example', tenant='tenant_exists')\n", (1527, 1579), False, 'from pydolphinscheduler.core.process_definition import Proces... |
# Copyright 2022 eprbell
#
# 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, soft... | [
"rp2.rp2_error.RP2ValueError"
] | [((2930, 2974), 'rp2.rp2_error.RP2ValueError', 'RP2ValueError', (['f"""Invalid keyword: {keyword}"""'], {}), "(f'Invalid keyword: {keyword}')\n", (2943, 2974), False, 'from rp2.rp2_error import RP2ValueError\n')] |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import sys
import numpy as np
import tensorflow as tf
from tensorflow.python.platform import flags
sys.path.append("../")
from nmutant_util.utils_file import get_data_... | [
"sys.path.append",
"tensorflow.python.platform.flags.DEFINE_string",
"tensorflow.reset_default_graph",
"nmutant_util.utils_file.get_data_file",
"numpy.asarray",
"nmutant_data.data.get_data",
"tensorflow.app.run"
] | [((251, 273), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (266, 273), False, 'import sys\n'), ((577, 601), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (599, 601), True, 'import tensorflow as tf\n'), ((641, 659), 'nmutant_data.data.get_data', 'get_data', (['d... |
from tensorflow.keras.layers import (Input, Reshape, Dense, Conv2D, Layer,
BatchNormalization, UpSampling2D,
Dropout, Flatten, Conv2DTranspose,
)
from tensorflow.keras.initializers import RandomNormal
from ten... | [
"tensorflow.python.framework.ops.disable_eager_execution",
"models.basemodel.np.ones",
"tensorflow.keras.layers.Reshape",
"tensorflow.keras.layers.Dense",
"models.basemodel.DataLoader",
"models.basemodel.plt.clf",
"tensorflow.keras.layers.Flatten",
"tensorflow.keras.layers.BatchNormalization",
"mode... | [((464, 489), 'tensorflow.python.framework.ops.disable_eager_execution', 'disable_eager_execution', ([], {}), '()\n', (487, 489), False, 'from tensorflow.python.framework.ops import disable_eager_execution\n'), ((963, 1007), 'tensorflow.keras.backend.random_uniform', 'K.random_uniform', (['(self.batch_size, 1, 1, 1)'],... |
from datetime import datetime
import traceback
import numpy as np
import face_recognition as fr
import glob
import datetime
import os
from stat import *
from scipy.spatial.distance import cdist
from sklearn.cluster import KMeans
import cv2
import matplotlib.pyplot as plt
import time
import sys
import re
... | [
"numpy.argmin",
"cv2.rectangle",
"glob.glob",
"numpy.unique",
"cv2.imwrite",
"face_recognition.face_encodings",
"sklearn.cluster.KMeans",
"traceback.format_exc",
"datetime.datetime.now",
"re.sub",
"numpy.save",
"os.stat",
"face_recognition.batch_face_locations",
"dlib.cuda.get_device",
"... | [((2125, 2154), 'numpy.asanyarray', 'np.asanyarray', (['face_encodings'], {}), '(face_encodings)\n', (2138, 2154), True, 'import numpy as np\n'), ((2392, 2428), 'numpy.argmin', 'np.argmin', (['dists[:, largest_cluster]'], {}), '(dists[:, largest_cluster])\n', (2401, 2428), True, 'import numpy as np\n'), ((2963, 2993), ... |
from functools import wraps
from rest_framework import status
from rest_framework.response import Response
from apps.core.backends import sudo_password_needed, sudo_renew
def api_sudo_required(view_func):
@wraps(view_func)
def _wrapped_view(request, *args, **kwargs):
if not request.user.has_usable_p... | [
"apps.core.backends.sudo_renew",
"rest_framework.response.Response",
"functools.wraps",
"apps.core.backends.sudo_password_needed"
] | [((214, 230), 'functools.wraps', 'wraps', (['view_func'], {}), '(view_func)\n', (219, 230), False, 'from functools import wraps\n'), ((542, 598), 'rest_framework.response.Response', 'Response', (['{}'], {'status': 'status.HTTP_412_PRECONDITION_FAILED'}), '({}, status=status.HTTP_412_PRECONDITION_FAILED)\n', (550, 598),... |
# Generated by Django 3.0.4 on 2021-04-07 10:16
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('blogs', '0003_auto_20210407_0913'),
]
operations = [
migrations.AlterModelOptions(
name='postcomment',
options={},
)... | [
"django.db.migrations.AlterModelTable",
"django.db.migrations.AlterModelOptions"
] | [((225, 285), 'django.db.migrations.AlterModelOptions', 'migrations.AlterModelOptions', ([], {'name': '"""postcomment"""', 'options': '{}'}), "(name='postcomment', options={})\n", (253, 285), False, 'from django.db import migrations\n'), ((330, 383), 'django.db.migrations.AlterModelTable', 'migrations.AlterModelTable',... |
import numpy
from tabulate import tabulate
import time
from threading import Lock
class MovRStats:
def __init__(self):
self.cumulative_counts = {}
self.instantiation_time = time.time()
self.mutex = Lock()
self.new_window()
# reset stats while keeping cumulative counts
de... | [
"threading.Lock",
"tabulate.tabulate",
"time.time"
] | [((197, 208), 'time.time', 'time.time', ([], {}), '()\n', (206, 208), False, 'import time\n'), ((230, 236), 'threading.Lock', 'Lock', ([], {}), '()\n', (234, 236), False, 'from threading import Lock\n'), ((419, 430), 'time.time', 'time.time', ([], {}), '()\n', (428, 430), False, 'import time\n'), ((1335, 1346), 'time.t... |
import logging
import re
import statistics
from pprint import pprint
from utils import functions as F
from .attribute import Attribute
from .inverted_index import InvertedIndex
from .occurrence import Occurrence
logger = logging.getLogger(__name__)
class KnowledgeBase:
'''A KnowledgeBase has the following prop... | [
"statistics.stdev",
"re.match",
"utils.functions.read_k_base",
"statistics.mean",
"logging.getLogger",
"utils.functions.normalize_str"
] | [((224, 251), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (241, 251), False, 'import logging\n'), ((1218, 1240), 'utils.functions.read_k_base', 'F.read_k_base', (['kb_file'], {}), '(kb_file)\n', (1231, 1240), True, 'from utils import functions as F\n'), ((1341, 1367), 'utils.functions.... |
import sys
if sys.version_info[:2] < (2, 7):
import unittest2 as unittest
else:
import unittest
from depsolver.debian_version \
import \
DebianVersion, is_valid_debian_version
V = DebianVersion.from_string
class TestVersionParsing(unittest.TestCase):
def test_valid_versions(self):
ve... | [
"depsolver.debian_version.is_valid_debian_version"
] | [((425, 457), 'depsolver.debian_version.is_valid_debian_version', 'is_valid_debian_version', (['version'], {}), '(version)\n', (448, 457), False, 'from depsolver.debian_version import DebianVersion, is_valid_debian_version\n')] |
import json
from .models import *
def cookieCart(request):
try:
cart = json.loads(request.COOKIES["cart"])
except:
cart = {}
print("Cart:", cart)
items = []
order = {"get_cart_total": 0, "get_cart_items": 0}
cartItems = order["get_cart_items"]
for i in cart:
try:... | [
"json.loads"
] | [((86, 121), 'json.loads', 'json.loads', (["request.COOKIES['cart']"], {}), "(request.COOKIES['cart'])\n", (96, 121), False, 'import json\n')] |
import abc
import six
from typing import Dict, Set, Any, Union # noqa: F401
NODE_KEY = 'KEY'
NODE_LABEL = 'LABEL'
NODE_REQUIRED_HEADERS = {NODE_LABEL, NODE_KEY}
RELATION_START_KEY = 'START_KEY'
RELATION_START_LABEL = 'START_LABEL'
RELATION_END_KEY = 'END_KEY'
RELATION_END_LABEL = 'END_LABEL'
RELATION_TYPE = 'TYPE'
... | [
"six.iteritems",
"six.add_metaclass"
] | [((679, 709), 'six.add_metaclass', 'six.add_metaclass', (['abc.ABCMeta'], {}), '(abc.ABCMeta)\n', (696, 709), False, 'import six\n'), ((4401, 4424), 'six.iteritems', 'six.iteritems', (['val_dict'], {}), '(val_dict)\n', (4414, 4424), False, 'import six\n')] |
# Copyright 2019 Google 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | [
"random.shuffle",
"json.dumps",
"tensorflow.ConfigProto",
"tensorflow.train.latest_checkpoint",
"tensorflow.tables_initializer",
"os.path.join",
"utils.misc_utils.add_summary",
"tensorflow.summary.FileWriter",
"tensorflow.contrib.training.wait_for_new_checkpoint",
"copy.deepcopy",
"numpy.average... | [((1737, 1776), 're.match', 're.match', (['"""<fl_(\\\\d+)>"""', 'pred_action[2]'], {}), "('<fl_(\\\\d+)>', pred_action[2])\n", (1745, 1776), False, 'import re\n'), ((1858, 1897), 're.match', 're.match', (['"""<st_(\\\\w+)>"""', 'pred_action[3]'], {}), "('<st_(\\\\w+)>', pred_action[3])\n", (1866, 1897), False, 'import... |
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | [
"st2common.util.file_system.get_file_list",
"os.path.dirname",
"os.path.join"
] | [((931, 956), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (946, 956), False, 'import os\n'), ((972, 1027), 'os.path.join', 'os.path.join', (['CURRENT_DIR', '"""../../../st2tests/st2tests"""'], {}), "(CURRENT_DIR, '../../../st2tests/st2tests')\n", (984, 1027), False, 'import os\n'), ((1170,... |
import os
from pypy.interpreter.error import operationerrfmt, OperationError
from pypy.interpreter.gateway import interp2app, unwrap_spec
from pypy.interpreter.typedef import (
TypeDef, interp_attrproperty, generic_new_descr)
from pypy.module.exceptions.interp_exceptions import W_IOError
from pypy.module._io.inter... | [
"pypy.interpreter.gateway.interp2app",
"pypy.module.exceptions.interp_exceptions.W_IOError.descr_init",
"pypy.interpreter.gateway.unwrap_spec",
"pypy.interpreter.typedef.interp_attrproperty",
"pypy.interpreter.typedef.generic_new_descr",
"pypy.module.exceptions.interp_exceptions.W_IOError.__init__",
"py... | [((1201, 1325), 'pypy.interpreter.gateway.unwrap_spec', 'unwrap_spec', ([], {'mode': 'str', 'buffering': 'int', 'encoding': '"""str_or_None"""', 'errors': '"""str_or_None"""', 'newline': '"""str_or_None"""', 'closefd': 'bool'}), "(mode=str, buffering=int, encoding='str_or_None', errors=\n 'str_or_None', newline='str... |
import logging
import time
import numpy as np
from param_net.param_fcnet import ParamFCNetRegression
from keras.losses import mean_squared_error
from keras import backend as K
from smac.tae.execute_func import ExecuteTAFuncDict
from smac.scenario.scenario import Scenario
from smac.facade.smac_facade import SMAC
fro... | [
"sklearn.preprocessing.StandardScaler",
"keras.backend.clear_session",
"numpy.maximum",
"param_net.param_fcnet.ParamFCNetRegression",
"mini_autonet.tae.simple_tae.SimpleTAFunc",
"ConfigSpace.util.fix_types",
"numpy.random.RandomState",
"time.time",
"param_net.param_fcnet.ParamFCNetRegression.get_con... | [((784, 812), 'logging.getLogger', 'logging.getLogger', (['"""AutoNet"""'], {}), "('AutoNet')\n", (801, 812), False, 'import logging\n'), ((1006, 1022), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (1020, 1022), False, 'from sklearn.preprocessing import StandardScaler\n'), ((1046, 1062), ... |
# Generated by Django 2.2.24 on 2021-06-23 13:28
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("events", "0001_initial"),
]
operations = [
migrations.AlterModelOptions(name="event", options={},),
]
| [
"django.db.migrations.AlterModelOptions"
] | [((216, 270), 'django.db.migrations.AlterModelOptions', 'migrations.AlterModelOptions', ([], {'name': '"""event"""', 'options': '{}'}), "(name='event', options={})\n", (244, 270), False, 'from django.db import migrations\n')] |
import unittest
import os
import numpy as np
from skimage.io import imsave
import torch
import neural_renderer as nr
current_dir = os.path.dirname(os.path.realpath(__file__))
data_dir = os.path.join(current_dir, 'data')
class TestCore(unittest.TestCase):
def test_tetrahedron(self):
vertices_ref = np.array(
... | [
"unittest.main",
"os.path.realpath",
"neural_renderer.load_obj",
"numpy.array",
"neural_renderer.get_points_from_angles",
"neural_renderer.Renderer",
"os.path.join",
"torch.from_numpy"
] | [((189, 222), 'os.path.join', 'os.path.join', (['current_dir', '"""data"""'], {}), "(current_dir, 'data')\n", (201, 222), False, 'import os\n'), ((150, 176), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (166, 176), False, 'import os\n'), ((2219, 2234), 'unittest.main', 'unittest.main', ([... |
from rest_framework import generics, permissions, status
from rest_framework.response import Response
from django.contrib.auth.models import User
from bucketlist.serializers import BucketlistSerializer, BucketlistItemSerializer, UserRegisterSerializer
from bucketlist.models import Bucketlist, BucketlistItem
class U... | [
"bucketlist.models.Bucketlist.objects.all",
"bucketlist.models.Bucketlist.objects.filter",
"rest_framework.response.Response",
"bucketlist.models.BucketlistItem.objects.filter",
"bucketlist.models.BucketlistItem",
"bucketlist.models.BucketlistItem.objects.all",
"django.contrib.auth.models.User.objects.a... | [((474, 492), 'django.contrib.auth.models.User.objects.all', 'User.objects.all', ([], {}), '()\n', (490, 492), False, 'from django.contrib.auth.models import User\n'), ((1706, 1734), 'bucketlist.models.BucketlistItem.objects.all', 'BucketlistItem.objects.all', ([], {}), '()\n', (1732, 1734), False, 'from bucketlist.mod... |
# dictionaries are 'like' hash-maps:
database = {} # empty dict
database = {"boss": "Foo Bar"} # dict with data
# Add a key value pair to a dictionary:
database["foo"] = "test"
person = {}
name, age, height = "Alice", 23, 1.8
person["age"] = age
person["height"] = height
person["desc... | [
"json.dumps"
] | [((595, 625), 'json.dumps', 'json.dumps', (['database'], {'indent': '(2)'}), '(database, indent=2)\n', (605, 625), False, 'import json\n')] |
# Lint as: python3
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... | [
"lingvo.compat.test.main",
"waymo_open_dataset.label_pb2.Label.Type.Value",
"lingvo.tasks.car.waymo.waymo_ap_metric.WaymoAPMetrics.Params",
"numpy.zeros",
"numpy.ones",
"lingvo.tasks.car.waymo.waymo_ap_metric.BuildWaymoMetricConfig",
"numpy.array",
"lingvo.tasks.car.waymo.waymo_metadata.WaymoMetadata"... | [((5177, 5191), 'lingvo.compat.test.main', 'tf.test.main', ([], {}), '()\n', (5189, 5191), True, 'from lingvo import compat as tf\n'), ((1111, 1141), 'lingvo.tasks.car.waymo.waymo_metadata.WaymoMetadata', 'waymo_metadata.WaymoMetadata', ([], {}), '()\n', (1139, 1141), False, 'from lingvo.tasks.car.waymo import waymo_me... |
from google.appengine.ext import db
from google.appengine.api.datastore_types import Text
__author__ = "<NAME>, <NAME>, and <NAME>"
__copyright__ = "Copyright 2013-2015 UKP TU Darmstadt"
__credits__ = ["<NAME>", "<NAME>", "<NAME>"]
__license__ = "ASL"
class ArgumentationUnit(db.Model):
"""
@author: <NAME>
... | [
"google.appengine.ext.db.StringProperty",
"google.appengine.ext.db.ReferenceProperty",
"google.appengine.ext.db.StringListProperty",
"google.appengine.ext.db.BooleanProperty",
"google.appengine.ext.db.ListProperty",
"google.appengine.ext.db.TextProperty",
"google.appengine.ext.db.IntegerProperty"
] | [((336, 355), 'google.appengine.ext.db.StringProperty', 'db.StringProperty', ([], {}), '()\n', (353, 355), False, 'from google.appengine.ext import db\n'), ((373, 392), 'google.appengine.ext.db.StringProperty', 'db.StringProperty', ([], {}), '()\n', (390, 392), False, 'from google.appengine.ext import db\n'), ((407, 42... |
import os
import shutil
class MakeDirs:
"""
This class will be used to create the directory which are needed to run the program
"""
def __init__(self):
self.current_path = os.getcwd()
self.func_list = [self.create_models, self.create_file_from_db, self.create_raw_files_validated,
... | [
"os.getcwd",
"shutil.rmtree",
"os.path.exists",
"os.makedirs"
] | [((199, 210), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (208, 210), False, 'import os\n'), ((714, 740), 'os.path.exists', 'os.path.exists', (['model_path'], {}), '(model_path)\n', (728, 740), False, 'import os\n'), ((789, 812), 'os.makedirs', 'os.makedirs', (['model_path'], {}), '(model_path)\n', (800, 812), False, '... |
import diceroll
import mentionrouter
import yaml
import random
import re
from slackeventsapi import SlackEventAdapter
from slackclient import SlackClient
def get_config( conf_file ):
with open( conf_file ) as x: conf_str = x.read()
conf = yaml.load( conf_str )
return conf
CONF = get_config( "config.yaml... | [
"yaml.load",
"diceroll.DiceRollHandler",
"slackclient.SlackClient",
"mentionrouter.Router",
"slackeventsapi.SlackEventAdapter"
] | [((347, 420), 'slackeventsapi.SlackEventAdapter', 'SlackEventAdapter', (["CONF['slack_signing_secret']"], {'endpoint': '"""/slack/events"""'}), "(CONF['slack_signing_secret'], endpoint='/slack/events')\n", (364, 420), False, 'from slackeventsapi import SlackEventAdapter\n'), ((446, 482), 'slackclient.SlackClient', 'Sla... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui/_settingsDialog.ui'
#
# Created by: PyQt5 UI code generator 5.12.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_settingsDialog(object):
def setupUi(self, settingsDialo... | [
"PyQt5.QtWidgets.QLabel",
"PyQt5.QtWidgets.QWidget",
"PyQt5.QtWidgets.QHBoxLayout",
"PyQt5.QtWidgets.QLineEdit",
"PyQt5.QtWidgets.QDialog",
"PyQt5.QtGui.QFont",
"PyQt5.QtWidgets.QVBoxLayout",
"PyQt5.QtCore.QMetaObject.connectSlotsByName",
"PyQt5.QtWidgets.QApplication",
"PyQt5.QtWidgets.QDialogBut... | [((2802, 2834), 'PyQt5.QtWidgets.QApplication', 'QtWidgets.QApplication', (['sys.argv'], {}), '(sys.argv)\n', (2824, 2834), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((2856, 2875), 'PyQt5.QtWidgets.QDialog', 'QtWidgets.QDialog', ([], {}), '()\n', (2873, 2875), False, 'from PyQt5 import QtCore, QtGui, QtWi... |
from pyflink.common.serialization import SimpleStringEncoder
from pyflink.common.typeinfo import Types
from pyflink.datastream import StreamExecutionEnvironment, TimeCharacteristic
from pyflink.datastream.connectors import StreamingFileSink
def tutorial():
env = StreamExecutionEnvironment.get_execution_environmen... | [
"pyflink.common.typeinfo.Types.INT",
"pyflink.datastream.StreamExecutionEnvironment.get_execution_environment",
"pyflink.common.serialization.SimpleStringEncoder",
"pyflink.common.typeinfo.Types.STRING"
] | [((269, 323), 'pyflink.datastream.StreamExecutionEnvironment.get_execution_environment', 'StreamExecutionEnvironment.get_execution_environment', ([], {}), '()\n', (321, 323), False, 'from pyflink.datastream import StreamExecutionEnvironment, TimeCharacteristic\n'), ((526, 537), 'pyflink.common.typeinfo.Types.INT', 'Typ... |
"""Databases access: read and write, occasionally sorting query results."""
import os
import re
from . import ROOT_DIR
from tinydb import TinyDB, Query
TEAM_DATABASE = os.path.join(ROOT_DIR, "data/teams.json")
GAME_DATABASE = os.path.join("data/game.json")
POV_DATABASE = os.path.join("data/pov.json")
# Read-only inf... | [
"tinydb.Query",
"tinydb.TinyDB",
"os.path.join"
] | [((170, 211), 'os.path.join', 'os.path.join', (['ROOT_DIR', '"""data/teams.json"""'], {}), "(ROOT_DIR, 'data/teams.json')\n", (182, 211), False, 'import os\n'), ((228, 258), 'os.path.join', 'os.path.join', (['"""data/game.json"""'], {}), "('data/game.json')\n", (240, 258), False, 'import os\n'), ((274, 303), 'os.path.j... |
#!/usr/bin/python
import re
import sys
import getopt
from subprocess import Popen, PIPE
from pprint import pprint as ppr
import os
_python3 = sys.version_info.major == 3
def Usage(s):
print('Usage: {} -t <cstest_path> [-f <file_name.cs>] [-d <directory>]'.format(s))
sys.exit(-1)
def get_report_file(toolpath, fil... | [
"subprocess.Popen",
"getopt.getopt",
"re.finditer",
"os.walk",
"os.sep.join",
"sys.exit"
] | [((273, 285), 'sys.exit', 'sys.exit', (['(-1)'], {}), '(-1)\n', (281, 285), False, 'import sys\n'), ((394, 430), 'subprocess.Popen', 'Popen', (['cmd'], {'stdout': 'PIPE', 'stderr': 'PIPE'}), '(cmd, stdout=PIPE, stderr=PIPE)\n', (399, 430), False, 'from subprocess import Popen, PIPE\n'), ((657, 728), 're.finditer', 're.... |
# -*- coding: UTF-8 -*-
"""
处理数据集 和 标签数据集的代码:(主要是对原始数据集裁剪)
处理方式:分别处理
注意修改 输入 输出目录 和 生成的文件名
output_dir = "./label_temp"
input_dir = "./label"
"""
import cv2
import os
import sys
import time
def get_img(input_dir):
img_paths = []
for (path,dirname,filenames) in os.walk(input_dir):
for fi... | [
"cv2.imread",
"os.walk",
"time.sleep"
] | [((286, 304), 'os.walk', 'os.walk', (['input_dir'], {}), '(input_dir)\n', (293, 304), False, 'import os\n'), ((661, 676), 'time.sleep', 'time.sleep', (['(0.2)'], {}), '(0.2)\n', (671, 676), False, 'import time\n'), ((745, 765), 'cv2.imread', 'cv2.imread', (['img_path'], {}), '(img_path)\n', (755, 765), False, 'import c... |
import numpy as np
import torch
from scipy.special import comb
class Metric:
def __init__(self, **kwargs):
self.requires = ['kmeans_cosine', 'kmeans_nearest_cosine', 'features_cosine', 'target_labels']
self.name = 'c_f1'
def __call__(self, target_labels, computed_cluster_labels_cosine, featur... | [
"scipy.special.comb",
"numpy.zeros",
"numpy.argmin",
"numpy.where",
"numpy.linalg.norm",
"numpy.unique"
] | [((747, 788), 'numpy.unique', 'np.unique', (['computed_cluster_labels_cosine'], {}), '(computed_cluster_labels_cosine)\n', (756, 788), True, 'import numpy as np\n'), ((1046, 1070), 'numpy.unique', 'np.unique', (['target_labels'], {}), '(target_labels)\n', (1055, 1070), True, 'import numpy as np\n'), ((1187, 1205), 'num... |
import json
from glob import glob
import sys
from elmoformanylangs import Embedder
input_path = sys.argv[1] if len(sys.argv) > 1 else 'data/training-dataset-2019-01-23'
with open('{}/collection-info.json'.format(input_path), 'r') as f:
collectioninfo = json.load(f)
converters = {
'en': Embedder('ELMoForMany... | [
"json.load",
"elmoformanylangs.Embedder"
] | [((259, 271), 'json.load', 'json.load', (['f'], {}), '(f)\n', (268, 271), False, 'import json\n'), ((299, 330), 'elmoformanylangs.Embedder', 'Embedder', (['"""ELMoForManyLangs/en"""'], {}), "('ELMoForManyLangs/en')\n", (307, 330), False, 'from elmoformanylangs import Embedder\n'), ((342, 373), 'elmoformanylangs.Embedde... |
#right now, requires source /project/projectdirs/desi/software/desi_environment.sh master
from astropy.table import Table
import numpy as np
import os
import argparse
import fitsio
from desitarget.targetmask import zwarn_mask
parser = argparse.ArgumentParser()
parser.add_argument("--night", help="use this if you want ... | [
"astropy.table.Table.read",
"numpy.sum",
"argparse.ArgumentParser",
"desitarget.targetmask.zwarn_mask.mask",
"numpy.zeros",
"numpy.unique"
] | [((236, 261), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (259, 261), False, 'import argparse\n'), ((472, 600), 'astropy.table.Table.read', 'Table.read', (["('/global/cfs/cdirs/desi/spectro/redux/daily/exposure_tables/' + month +\n '/exposure_table_' + args.night + '.csv')"], {}), "('/glo... |
from ArithmeticDictionary import AD
from collections import defaultdict
import numpy as np
class BoW(AD):
def __init__(self, text):
super().__init__()
self.ad = AD()
if text is not None:
for w in text.split():
self.ad += AD({w: 1})
self.update(self.ad)
... | [
"ArithmeticDictionary.AD"
] | [((183, 187), 'ArithmeticDictionary.AD', 'AD', ([], {}), '()\n', (185, 187), False, 'from ArithmeticDictionary import AD\n'), ((279, 289), 'ArithmeticDictionary.AD', 'AD', (['{w: 1}'], {}), '({w: 1})\n', (281, 289), False, 'from ArithmeticDictionary import AD\n')] |
#!/usr/bin/env python3
import numpy as np
import random
if __name__ == '__main__':
nbViewpoint = 3
nbTileList = [1, 3*2, 6*4]
#nbTileList = [1]
#nbQuality = 4
nbQuality = 3
#nbChunk = 4*60
nbChunk = 256
#nbChunk = 60
nbBandwidth = 1
nbUser = 4
nbProcessedChunk = 32
#nb... | [
"numpy.random.seed",
"random.seed",
"numpy.random.normal"
] | [((3166, 3181), 'random.seed', 'random.seed', (['(42)'], {}), '(42)\n', (3177, 3181), False, 'import random\n'), ((3186, 3204), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (3200, 3204), True, 'import numpy as np\n'), ((6374, 6433), 'numpy.random.normal', 'np.random.normal', (['averageBandwidth', '(... |
# %matplotlib inline
# +
import os, sys
import numpy as np
import random
import copy
import torch
import torch.autograd as autograd
from torch.autograd import Variable
import torch.optim as optim
from torch.utils.data import DataLoader, Dataset, TensorDataset
import torchvision.transforms as transforms
import torchvis... | [
"numpy.random.seed",
"torch.randn",
"torch.set_default_tensor_type",
"torch.full",
"numpy.random.randint",
"numpy.arange",
"torch.device",
"torchvision.transforms.Normalize",
"os.path.join",
"torch.utils.data.DataLoader",
"numpy.savetxt",
"random.seed",
"numpy.loadtxt",
"torchvision.transf... | [((1654, 1692), 'torch.norm', 'torch.norm', (['grad_wrt_image'], {'p': '(2)', 'dim': '(1)'}), '(grad_wrt_image, p=2, dim=1)\n', (1664, 1692), False, 'import torch\n'), ((2455, 2493), 'torch.norm', 'torch.norm', (['grad_wrt_image'], {'p': '(2)', 'dim': '(1)'}), '(grad_wrt_image, p=2, dim=1)\n', (2465, 2493), False, 'imp... |
import sys
from logging import getLogger
from typing import Optional
from thonny import ui_utils
from thonny.plugins.micropython.mp_front import (
BareMetalMicroPythonConfigPage,
BareMetalMicroPythonProxy,
)
from thonny.plugins.micropython.uf2dialog import Uf2FlashingDialog
logger = getLogger(__name__)
VIDS_... | [
"thonny.ui_utils.show_dialog",
"logging.getLogger"
] | [((294, 313), 'logging.getLogger', 'getLogger', (['__name__'], {}), '(__name__)\n', (303, 313), False, 'from logging import getLogger\n'), ((3442, 3467), 'thonny.ui_utils.show_dialog', 'ui_utils.show_dialog', (['dlg'], {}), '(dlg)\n', (3462, 3467), False, 'from thonny import ui_utils\n')] |
import open3d as o3d
import glob, plyfile, numpy as np, multiprocessing as mp, torch
import copy
import numpy as np
import json
import pdb
import os
#CLASS_LABELS = ['cabinet', 'bed', 'chair', 'sofa', 'table', 'door', 'window', 'bookshelf', 'picture', 'counter', 'desk', 'curtain', 'refrigerator', 'shower curtain', 't... | [
"json.load",
"plyfile.PlyData",
"numpy.ones",
"torch.save",
"numpy.array",
"glob.glob",
"numpy.ascontiguousarray",
"multiprocessing.cpu_count"
] | [((613, 698), 'numpy.array', 'np.array', (['[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16, 24, 28, 33, 34, 36, 39]'], {}), '([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16, 24, 28, 33, 34, 36,\n 39])\n', (621, 698), True, 'import numpy as np\n'), ((1322, 1334), 'numpy.ones', 'np.ones', (['(500)'], {}), '(500)\n', (... |
import os
from subprocess import run
#setting up environment
command = ['bash','-c','source ./environment.sh']
res = run(command)
if res.returncode:
raise Exception('set up environment failed!')
try:
github_user = os.environ['GITHUB_USER']
github_passwd = os.environ['GITHUB_PASSWORD']
project_name = os.environ[... | [
"subprocess.run"
] | [((117, 129), 'subprocess.run', 'run', (['command'], {}), '(command)\n', (120, 129), False, 'from subprocess import run\n'), ((795, 870), 'subprocess.run', 'run', (["['pip', 'install', '--upgrade', '--force-reinstall', '--no-deps', '.']"], {}), "(['pip', 'install', '--upgrade', '--force-reinstall', '--no-deps', '.'])\n... |
import numpy as np
import cv2
from skimage.io import imread, imsave
from skimage.io import imshow
# lifted from http://blog.christianperone.com/2015/01/real-time-drone-object-tracking-using-python-and-opencv/
def run_main():
cap = cv2.VideoCapture('upabove.mp4')
# Read the first frame of the video
ret, f... | [
"cv2.putText",
"cv2.cvtColor",
"cv2.calcHist",
"cv2.waitKey",
"cv2.imshow",
"cv2.VideoCapture",
"cv2.rectangle",
"numpy.array",
"cv2.calcBackProject",
"skimage.io.imshow",
"cv2.normalize",
"cv2.destroyAllWindows",
"cv2.meanShift"
] | [((237, 268), 'cv2.VideoCapture', 'cv2.VideoCapture', (['"""upabove.mp4"""'], {}), "('upabove.mp4')\n", (253, 268), False, 'import cv2\n'), ((411, 424), 'skimage.io.imshow', 'imshow', (['frame'], {}), '(frame)\n', (417, 424), False, 'from skimage.io import imshow\n'), ((683, 719), 'cv2.cvtColor', 'cv2.cvtColor', (['roi... |
import re
import logging
from google.appengine.api import urlfetch
from helpers.team_manipulator import TeamManipulator
from models.team import Team
class TeamHelper(object):
"""
Helper to sort teams and stuff
"""
@classmethod
def sortTeams(self, team_list):
"""
Takes a list of T... | [
"logging.info",
"google.appengine.api.urlfetch.fetch",
"helpers.team_manipulator.TeamManipulator.createOrUpdate",
"re.compile"
] | [((658, 706), 're.compile', 're.compile', (['"""tpid=[A-Za-z0-9=&;\\\\-:]*?"><b>\\\\d+"""'], {}), '(\'tpid=[A-Za-z0-9=&;\\\\-:]*?"><b>\\\\d+\')\n', (668, 706), False, 'import re\n'), ((778, 797), 're.compile', 're.compile', (['"""\\\\d+$"""'], {}), "('\\\\d+$')\n", (788, 797), False, 'import re\n'), ((857, 875), 're.co... |
"""
Some Tools For Coder
author: <NAME>
website: https://github.com/IanVzs/Halahayawa
Last edited: 10 03 2021
"""
import time
import json
import hashlib
from datetime import datetime
def json_loads(str_data):
try:
return json.loads(str_data)
except:
return {}
def json_dumps(data, ensure_asc... | [
"hashlib.md5",
"json.loads",
"json.dumps",
"datetime.datetime.strptime",
"datetime.datetime.now"
] | [((2870, 2884), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (2882, 2884), False, 'from datetime import datetime\n'), ((3023, 3037), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (3035, 3037), False, 'from datetime import datetime\n'), ((3239, 3252), 'hashlib.md5', 'hashlib.md5', ([], {}), '(... |
"""
Module to train the DEEPred NN classifier
"""
import torch
from torch.utils.data import RandomSampler
import torch.nn as nn
import torch.optim as optim
from ..models import Model
from ..io.utils import split_batch, shuffle_data
def train(
x_train: torch.Tensor,
y_train: torch.Tensor,
epochs: int... | [
"torch.nn.BCEWithLogitsLoss"
] | [((1737, 1759), 'torch.nn.BCEWithLogitsLoss', 'nn.BCEWithLogitsLoss', ([], {}), '()\n', (1757, 1759), True, 'import torch.nn as nn\n')] |
import math
import numpy as np
from django.shortcuts import get_object_or_404
from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.decorators import api_view
from scipy.spatial import distance
from .models import Person
from .serializers import (
PersonIdSer... | [
"django.shortcuts.get_object_or_404",
"rest_framework.decorators.api_view",
"rest_framework.response.Response"
] | [((2364, 2374), 'rest_framework.decorators.api_view', 'api_view', ([], {}), '()\n', (2372, 2374), False, 'from rest_framework.decorators import api_view\n'), ((2956, 2984), 'rest_framework.response.Response', 'Response', (["{'result': result}"], {}), "({'result': result})\n", (2964, 2984), False, 'from rest_framework.r... |
"""
EfficientNet for ImageNet-1K, implemented in Keras.
Original paper: 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,'
https://arxiv.org/abs/1905.11946.
"""
__all__ = ['efficientnet_model', 'efficientnet_b0', 'efficientnet_b1', 'efficientnet_b2', 'efficientnet_b3',
'... | [
"math.ceil",
"keras.layers.Dropout",
"keras.layers.add",
"numpy.zeros",
"keras.models.Model",
"keras.layers.GlobalAveragePooling2D",
"keras.layers.Dense",
"keras.utils.layer_utils.count_params",
"keras.layers.Input",
"os.path.join"
] | [((1245, 1272), 'math.ceil', 'math.ceil', (['(height / strides)'], {}), '(height / strides)\n', (1254, 1272), False, 'import math\n'), ((1282, 1308), 'math.ceil', 'math.ceil', (['(width / strides)'], {}), '(width / strides)\n', (1291, 1308), False, 'import math\n'), ((9902, 9929), 'keras.layers.Input', 'nn.Input', ([],... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from collections import namedtuple, OrderedDict
import io
import re
from jinja2 import Template
from parametergenerate import utility
try:
#py2
unicode=unicode
except NameError:
#py3
unicode=str
def find_value(target_file, search_para... | [
"jinja2.Template",
"parametergenerate.utility.cast",
"parametergenerate.utility.check_encode",
"parametergenerate.utility.dict_list_marge",
"io.open",
"parametergenerate.utility.path2dict",
"re.compile"
] | [((447, 480), 'parametergenerate.utility.check_encode', 'utility.check_encode', (['target_file'], {}), '(target_file)\n', (467, 480), False, 'from parametergenerate import utility\n'), ((1750, 1795), 'parametergenerate.utility.cast', 'utility.cast', (['v', 'v_type', 'trap_undefined_error'], {}), '(v, v_type, trap_undef... |
import pandas as pd
### デスクトップアプリ作成課題
def kimetsu_search(path, word):
# 検索対象取得
df=pd.read_csv(path)
source=list(df["name"])
# 検索
if word in source:
return True
else:
return False
def add_to_kimetsu(path, word):
# 検索対象取得
df=pd.read_csv("./source.csv")
source=list(df[... | [
"pandas.read_csv",
"pandas.DataFrame"
] | [((91, 108), 'pandas.read_csv', 'pd.read_csv', (['path'], {}), '(path)\n', (102, 108), True, 'import pandas as pd\n'), ((273, 300), 'pandas.read_csv', 'pd.read_csv', (['"""./source.csv"""'], {}), "('./source.csv')\n", (284, 300), True, 'import pandas as pd\n'), ((379, 417), 'pandas.DataFrame', 'pd.DataFrame', (['source... |
import pytest
def test_concat_with_duplicate_columns():
import captivity
import pandas as pd
with pytest.raises(captivity.CaptivityException):
pd.concat(
[pd.DataFrame({"a": [1], "b": [2]}), pd.DataFrame({"c": [0], "b": [3]}),],
axis=1,
)
def test_concat_mismatch... | [
"pandas.DataFrame",
"pytest.raises"
] | [((113, 156), 'pytest.raises', 'pytest.raises', (['captivity.CaptivityException'], {}), '(captivity.CaptivityException)\n', (126, 156), False, 'import pytest\n'), ((390, 433), 'pytest.raises', 'pytest.raises', (['captivity.CaptivityException'], {}), '(captivity.CaptivityException)\n', (403, 433), False, 'import pytest\... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-09-04 06:31
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0002_auto_20160904_1201'),
]
operations = [
migrations.RenameModel(
... | [
"django.db.migrations.RenameModel"
] | [((286, 347), 'django.db.migrations.RenameModel', 'migrations.RenameModel', ([], {'old_name': '"""Battles"""', 'new_name': '"""Battle"""'}), "(old_name='Battles', new_name='Battle')\n", (308, 347), False, 'from django.db import migrations\n')] |
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-t', "--type", help="file to process single file, folder to process a full folder")
parser.add_argument('input', help='source image/ folder that needs to be fully converted')
parser.add_argument('output'... | [
"argparse.ArgumentParser"
] | [((58, 83), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (81, 83), False, 'import argparse\n')] |
from __future__ import print_function
import os
from termcolor import colored
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
import models as Models
import global_vars as Global
from utils.iterative_trainer import IterativeTrainer, IterativeTrainerConfig
from ut... | [
"models.get_ref_model_path",
"utils.iterative_trainer.IterativeTrainer",
"utils.iterative_trainer.IterativeTrainerConfig",
"datasets.MirroredDataset",
"os.path.isfile",
"utils.logger.Logger",
"os.path.join",
"torch.nn.MSELoss",
"torch.utils.data.DataLoader",
"matplotlib.pyplot.close",
"torch.opt... | [((400, 421), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (414, 421), False, 'import matplotlib\n'), ((998, 1108), 'torch.utils.data.DataLoader', 'DataLoader', (['train_ds'], {'batch_size': 'args.batch_size', 'shuffle': '(True)', 'num_workers': 'args.workers', 'pin_memory': '(True)'}), '(train... |
import tornado.ioloop
import tornado.web
from tornado.platform.asyncio import AsyncIOMainLoop
from base_plugin import BasePlugin
from utilities import path
class WebHandler(tornado.web.RequestHandler):
def get(self, *args, **kwargs):
players = [player for player in
self.player_manager.... | [
"tornado.platform.asyncio.AsyncIOMainLoop"
] | [((704, 721), 'tornado.platform.asyncio.AsyncIOMainLoop', 'AsyncIOMainLoop', ([], {}), '()\n', (719, 721), False, 'from tornado.platform.asyncio import AsyncIOMainLoop\n')] |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2021-2022 Valory AG
# 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.... | [
"os.mkdir",
"unittest.mock.patch.object",
"os.getcwd",
"unittest.mock.patch",
"pathlib.Path",
"tempfile.mkdtemp",
"jsonschema.Draft4Validator",
"tests.conftest.CliRunner",
"yaml.safe_load",
"packaging.version.Version",
"shutil.rmtree",
"aea.configurations.data_types.PublicId.from_str",
"os.c... | [((16549, 16614), 'unittest.mock.patch', 'patch', (['"""aea.cli.create.get_or_create_cli_config"""'], {'return_value': '{}'}), "('aea.cli.create.get_or_create_cli_config', return_value={})\n", (16554, 16614), False, 'from unittest.mock import patch\n'), ((2071, 2121), 'jsonschema.Draft4Validator', 'Draft4Validator', ([... |
import click
from click.testing import CliRunner
from aiotasks.actions.cli import worker
import aiotasks.actions.cli
def _launch_aiotasks_worker_in_console(blah, **kwargs):
click.echo("ok")
def test_cli_worker_runs_show_help():
runner = CliRunner()
result = runner.invoke(worker)
assert 'Usage: w... | [
"click.testing.CliRunner",
"click.echo"
] | [((182, 198), 'click.echo', 'click.echo', (['"""ok"""'], {}), "('ok')\n", (192, 198), False, 'import click\n'), ((252, 263), 'click.testing.CliRunner', 'CliRunner', ([], {}), '()\n', (261, 263), False, 'from click.testing import CliRunner\n'), ((567, 578), 'click.testing.CliRunner', 'CliRunner', ([], {}), '()\n', (576,... |
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from .middleware import middleware
from .routers import auth, blog
from .db import init_db
import os
APP_DIR = os.path.dirname(os.path.abspath(__file__))
DEFAULT_DATABASE_URL = "sqlite:///./sql_app.db"
def get_app(config: dict | None = None):
... | [
"os.path.abspath",
"os.path.join",
"fastapi.FastAPI"
] | [((200, 225), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (215, 225), False, 'import os\n'), ((333, 363), 'fastapi.FastAPI', 'FastAPI', ([], {'middleware': 'middleware'}), '(middleware=middleware)\n', (340, 363), False, 'from fastapi import FastAPI\n'), ((583, 614), 'os.path.join', 'os.pat... |
# Copyright (c) ElementAI and its affiliates.
# 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.
"""Script to train DCGAN on MNIST, adaptted from https://github.com/pytorch/examples/blob/master/... | [
"pickle.dump",
"numpy.random.seed",
"argparse.ArgumentParser",
"torch.randn",
"torch.cat",
"torch.nn.InstanceNorm2d",
"torch.nn.GroupNorm",
"torchvision.transforms.Normalize",
"os.path.join",
"random.randint",
"plot_path_tools.plot_eigenvalues",
"torch.load",
"os.path.exists",
"numpy.rando... | [((7565, 7610), 'os.path.join', 'os.path.join', (['config.exp_dir', 'config.exp_name'], {}), '(config.exp_dir, config.exp_name)\n', (7577, 7610), False, 'import os\n'), ((7693, 7729), 'os.path.join', 'os.path.join', (['exp_dir', '"""extra_plots"""'], {}), "(exp_dir, 'extra_plots')\n", (7705, 7729), False, 'import os\n'... |
import logging
from moonreader_tools.parsers.base import BookParser
from moonreader_tools.utils import (
get_book_type,
get_moonreader_files_from_filelist,
get_same_book_files,
title_from_fname,
)
from .drobpox_utils import dicts_from_pairs, extract_book_paths_from_dir_entries
class DropboxDownloade... | [
"moonreader_tools.parsers.base.BookParser",
"logging.exception",
"moonreader_tools.utils.title_from_fname",
"moonreader_tools.utils.get_book_type",
"moonreader_tools.utils.get_moonreader_files_from_filelist",
"moonreader_tools.utils.get_same_book_files"
] | [((1554, 1595), 'moonreader_tools.utils.get_moonreader_files_from_filelist', 'get_moonreader_files_from_filelist', (['files'], {}), '(files)\n', (1588, 1595), False, 'from moonreader_tools.utils import get_book_type, get_moonreader_files_from_filelist, get_same_book_files, title_from_fname\n'), ((1746, 1783), 'moonread... |
import pandas as pd
import numpy as np
import os
import argparse
from des_stacks.utils.gen_tools import get_good_des_chips
good_des_chips = get_good_des_chips()
def parser():
parser = argparse.ArgumentParser()
parser.add_argument('-f','--field',default = 'all')
parser.add_argument('-my','--year',default='n... | [
"pandas.DataFrame",
"argparse.ArgumentParser",
"pandas.read_csv",
"des_stacks.utils.gen_tools.get_good_des_chips",
"os.path.join"
] | [((140, 160), 'des_stacks.utils.gen_tools.get_good_des_chips', 'get_good_des_chips', ([], {}), '()\n', (158, 160), False, 'from des_stacks.utils.gen_tools import get_good_des_chips\n'), ((189, 214), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (212, 214), False, 'import argparse\n'), ((989, 1... |
"""
Tests for the proxy support in pip.
"""
import pip
from tests.lib import SRC_DIR
from tests.lib.path import Path
def test_correct_pip_version():
"""
Check we are importing pip from the right place.
"""
assert Path(pip.__file__).folder.folder.abspath == SRC_DIR
| [
"tests.lib.path.Path"
] | [((233, 251), 'tests.lib.path.Path', 'Path', (['pip.__file__'], {}), '(pip.__file__)\n', (237, 251), False, 'from tests.lib.path import Path\n')] |
# -*- encoding: utf-8 -*-
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase
from django.core.urlresolvers import reverse
from mapentity.factories import UserFactory
from geotrek.common.parsers import Parser
class ViewsTest(TestCase):
def setUp(self):
self.us... | [
"django.core.files.uploadedfile.SimpleUploadedFile",
"django.core.urlresolvers.reverse",
"mapentity.factories.UserFactory.create"
] | [((325, 384), 'mapentity.factories.UserFactory.create', 'UserFactory.create', ([], {'username': '"""homer"""', 'password': '"""<PASSWORD>"""'}), "(username='homer', password='<PASSWORD>')\n", (343, 384), False, 'from mapentity.factories import UserFactory\n'), ((568, 599), 'django.core.urlresolvers.reverse', 'reverse',... |
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
from src.system import System
def plot():
data = {
"hp": {
"cop": 3.0
},
"swhe": {
"pipe": {
"outer-dia": 0.02667,
"inner-dia": 0.0215392,
"... | [
"src.system.System",
"pathlib.Path",
"numpy.arange",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig"
] | [((648, 660), 'src.system.System', 'System', (['data'], {}), '(data)\n', (654, 660), False, 'from src.system import System\n'), ((670, 697), 'numpy.arange', 'np.arange', (['(-3000)', '(3000)', '(200)'], {}), '(-3000, 3000, 200)\n', (679, 697), True, 'import numpy as np\n'), ((866, 880), 'matplotlib.pyplot.subplots', 'p... |
"""
Prim's (also known as Jarník's) algorithm is a greedy algorithm that finds a minimum
spanning tree for a weighted undirected graph. This means it finds a subset of the
edges that forms a tree that includes every vertex, where the total weight of all the
edges in the tree is minimized. The algorithm operates by buil... | [
"typing.TypeVar"
] | [((558, 570), 'typing.TypeVar', 'TypeVar', (['"""T"""'], {}), "('T')\n", (565, 570), False, 'from typing import Generic, Optional, TypeVar\n')] |
import os.path as mod_path
import sys as mod_sys
import subprocess
from typing import *
def assert_in_git_repository() -> None:
success, lines = execute_git('status', output=False)
if not success:
print('Not a git repository!!!')
mod_sys.exit(1)
def execute_command(cmd: Union[str, List[str]]... | [
"subprocess.Popen",
"os.path.exists",
"sys.stdout.flush",
"sys.exit"
] | [((504, 595), 'subprocess.Popen', 'subprocess.Popen', (['command'], {'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.STDOUT', 'bufsize': '(-1)'}), '(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,\n bufsize=-1)\n', (520, 595), False, 'import subprocess\n'), ((3386, 3420), 'os.path.exists', 'mod_path.ex... |
import os
from uuid import uuid4
from django.utils.deconstruct import deconstructible
# rename file with uuid
@deconstructible
class PathAndRename(object):
def __init__(self, sub_path):
self.path = sub_path
def __call__(self, instance, filename):
ext = filename.split('.')[-1]
... | [
"uuid.uuid4",
"os.path.join"
] | [((471, 504), 'os.path.join', 'os.path.join', (['self.path', 'filename'], {}), '(self.path, filename)\n', (483, 504), False, 'import os\n'), ((392, 399), 'uuid.uuid4', 'uuid4', ([], {}), '()\n', (397, 399), False, 'from uuid import uuid4\n')] |
# analyze binom_test to each pair
# for further analyze ANOVA
# gt/-our gt/-nerf -our/gt -our/nerf -nerf/gt nerf/-our
# 40 1 38 77 1 75
# 78 78 78 78 78 78
from scipy import stats
import numpy as np
# choose us, or nerf is no us
choose = [64, 110, 111]
stimuli = ["our-g... | [
"numpy.savetxt",
"scipy.stats.binom_test"
] | [((525, 561), 'numpy.savetxt', 'np.savetxt', (['"""bintest.csv"""', 'binresult'], {}), "('bintest.csv', binresult)\n", (535, 561), True, 'import numpy as np\n'), ((413, 480), 'scipy.stats.binom_test', 'stats.binom_test', (['eachChoose'], {'n': 'total', 'p': '(0.5)', 'alternative': '"""greater"""'}), "(eachChoose, n=tot... |
import re
import string
import stanza
import nltk.data
import unidecode
import copy
import tensorflow_hub as hub
from pythonrouge.pythonrouge import Pythonrouge
import os, os.path
embed = hub.load("/home/dani/Desktop/licenta/use")
# read a file to an array in which each item is a line from that respective file
def ... | [
"pythonrouge.pythonrouge.Pythonrouge",
"unidecode.unidecode",
"tensorflow_hub.load",
"os.walk",
"copy.copy",
"stanza.Pipeline",
"re.sub"
] | [((190, 232), 'tensorflow_hub.load', 'hub.load', (['"""/home/dani/Desktop/licenta/use"""'], {}), "('/home/dani/Desktop/licenta/use')\n", (198, 232), True, 'import tensorflow_hub as hub\n'), ((2010, 2120), 'stanza.Pipeline', 'stanza.Pipeline', ([], {'lang': '"""en"""', 'processors': '"""tokenize,mwt,pos,lemma"""', 'toke... |
# -*- encoding: utf-8 -*-
from django.test import TestCase
from unit_field.units import Unit, UnitValue, get_choices
class UnitTest(TestCase):
def test_attribute_factor(self):
"""
the attribtue "factor" can be set
"""
e = Unit(0.01, 'cm', 'centimetre')
self.assertEqual(e.fac... | [
"unit_field.units.UnitValue",
"unit_field.units.get_choices",
"unit_field.units.Unit"
] | [((259, 289), 'unit_field.units.Unit', 'Unit', (['(0.01)', '"""cm"""', '"""centimetre"""'], {}), "(0.01, 'cm', 'centimetre')\n", (263, 289), False, 'from unit_field.units import Unit, UnitValue, get_choices\n'), ((512, 544), 'unit_field.units.Unit', 'Unit', (['(0.01)', 'u"""cm"""', 'u"""centimetre"""'], {}), "(0.01, u'... |
#!/usr/bin/python
import os
from depp import Model_pl
from depp import default_config
import pkg_resources
import pytorch_lightning as pl
from pytorch_lightning.callbacks.early_stopping import EarlyStopping
from pytorch_lightning.callbacks import ModelCheckpoint
from pytorch_lightning.loggers import TensorBoardLogge... | [
"pytorch_lightning.callbacks.ModelCheckpoint",
"pytorch_lightning.Trainer",
"os.makedirs",
"os.path.isdir",
"depp.Model_pl.model",
"omegaconf.OmegaConf.merge",
"omegaconf.OmegaConf.from_cli",
"omegaconf.OmegaConf.create",
"pytorch_lightning.loggers.TensorBoardLogger",
"pytorch_lightning.callbacks.... | [((457, 504), 'omegaconf.OmegaConf.create', 'OmegaConf.create', (['default_config.default_config'], {}), '(default_config.default_config)\n', (473, 504), False, 'from omegaconf import OmegaConf\n'), ((521, 541), 'omegaconf.OmegaConf.from_cli', 'OmegaConf.from_cli', ([], {}), '()\n', (539, 541), False, 'from omegaconf i... |
from mltoolkit.mldp.steps.transformers import BaseTransformer
from copy import deepcopy
class FieldDuplicator(BaseTransformer):
"""Duplicates fields by giving them new names."""
def __init__(self, old_to_new_fnames, **kwargs):
super(FieldDuplicator, self).__init__(**kwargs)
self.old_to_new_fn... | [
"copy.deepcopy"
] | [((479, 507), 'copy.deepcopy', 'deepcopy', (['data_chunk[old_fn]'], {}), '(data_chunk[old_fn])\n', (487, 507), False, 'from copy import deepcopy\n')] |
import imp
import sys
import os
from ..common import *
class LoaderError(ImportError):
"""
This error is thrown when the module loader encounters an exception or
an unrecoverable state while attempting to load a dynamically located
module.
"""
def __init__(self, msg):
"""
Crea... | [
"os.path.isdir",
"imp.load_compiled",
"os.path.exists",
"imp.load_source",
"os.path.splitext",
"os.path.join"
] | [((1243, 1265), 'os.path.splitext', 'os.path.splitext', (['path'], {}), '(path)\n', (1259, 1265), False, 'import os\n'), ((1350, 1384), 'imp.load_source', 'imp.load_source', (['module_name', 'path'], {}), '(module_name, path)\n', (1365, 1384), False, 'import imp\n'), ((3704, 3742), 'os.path.join', 'os.path.join', (['se... |
"""
Run users examples to check authentication.
"""
from pprint import pprint
from eventstore_grpc.options import base_options
from eventstore_grpc import EventStoreDBClient, JSONEventData
conn_str = "esdb://localhost:2111,localhost:2112,localhost:2113?tls&rootCertificate=./tests/certs/ca/ca.crt"
default_user = {"us... | [
"pprint.pprint",
"eventstore_grpc.EventStoreDBClient",
"eventstore_grpc.options.base_options.as_credentials"
] | [((378, 421), 'eventstore_grpc.options.base_options.as_credentials', 'base_options.as_credentials', ([], {}), '(**default_user)\n', (405, 421), False, 'from eventstore_grpc.options import base_options\n'), ((432, 460), 'eventstore_grpc.EventStoreDBClient', 'EventStoreDBClient', (['conn_str'], {}), '(conn_str)\n', (450,... |
from __future__ import print_function
import html5lib
from unittest import TestCase
from fluent_contents.utils.html import clean_html
class TextPluginTests(TestCase):
"""
Test whether the sanitation works as expected.
"""
HTML1_ORIGINAL = u'<p><img src="/media/image.jpg" alt="" width="460" height="30... | [
"fluent_contents.utils.html.clean_html"
] | [((887, 918), 'fluent_contents.utils.html.clean_html', 'clean_html', (['self.HTML1_ORIGINAL'], {}), '(self.HTML1_ORIGINAL)\n', (897, 918), False, 'from fluent_contents.utils.html import clean_html\n'), ((1455, 1501), 'fluent_contents.utils.html.clean_html', 'clean_html', (['self.HTML1_ORIGINAL'], {'sanitize': '(True)'}... |
import requests
from fidesops.task.filter_results import filter_data_categories
import pytest
import random
from fidesops.graph.graph import DatasetGraph
from fidesops.models.privacy_request import PrivacyRequest
from fidesops.schemas.redis_cache import PrivacyRequestIdentity
from fidesops.task import graph_task
fro... | [
"fidesops.graph.graph.DatasetGraph",
"fidesops.task.graph_task.run_access_request",
"tests.graph.graph_test_util.assert_rows_match",
"fidesops.schemas.redis_cache.PrivacyRequestIdentity",
"fidesops.task.graph_task.get_cached_data_for_erasures",
"random.randint",
"fidesops.task.filter_results.filter_data... | [((849, 907), 'fidesops.schemas.redis_cache.PrivacyRequestIdentity', 'PrivacyRequestIdentity', ([], {}), "(**{'email': sentry_identity_email})\n", (871, 907), False, 'from fidesops.schemas.redis_cache import PrivacyRequestIdentity\n'), ((1091, 1117), 'fidesops.graph.graph.DatasetGraph', 'DatasetGraph', (['merged_graph'... |
import nltk
cor = nltk.corpus.brown.tagged_sents(categories='adventure')[:500]
print(len(cor))
from nltk.util import unique_list
tag_set = unique_list(tag for sent in cor for (word,tag) in sent)
print(len(tag_set))
symbols = unique_list(word for sent in cor for (word,tag) in sent)
print(len(symbols))
print(len(tag_set)... | [
"nltk.util.unique_list",
"nltk.corpus.brown.tagged_sents",
"nltk.tag.HiddenMarkovModelTrainer"
] | [((139, 193), 'nltk.util.unique_list', 'unique_list', (['(tag for sent in cor for word, tag in sent)'], {}), '(tag for sent in cor for word, tag in sent)\n', (150, 193), False, 'from nltk.util import unique_list\n'), ((225, 280), 'nltk.util.unique_list', 'unique_list', (['(word for sent in cor for word, tag in sent)'],... |