code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import argparse
from enum import Enum
import json
import numpy as np
import matplotlib.pyplot as plt
from seqeval.metrics import f1_score
from seqeval.metrics import accuracy_score
from seqeval.metrics import recall_score
from seqeval.metrics import precision_score
from seqeval.metrics import classification_report
fr... | [
"matplotlib.pyplot.title",
"json.load",
"matplotlib.pyplot.show",
"argparse.ArgumentParser",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.gcf",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.savefig"
] | [((1333, 1371), 'matplotlib.pyplot.xticks', 'plt.xticks', (['_X', 'X'], {'rotation': '"""vertical"""'}), "(_X, X, rotation='vertical')\n", (1343, 1371), True, 'import matplotlib.pyplot as plt\n'), ((1547, 1570), 'matplotlib.pyplot.figure', 'plt.figure', (['plot_number'], {}), '(plot_number)\n', (1557, 1570), True, 'imp... |
import os
import requests
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
UP_API_KEY = config.get('API','ACCESS_TOKEN')
UP_ENDPOINT = "https://api.up.com.au/api/v1/"
class APIKeyMissingError(Exception):
pass
if UP_API_KEY is None:
raise APIKeyMissingError(
"All met... | [
"requests.Session",
"configparser.ConfigParser"
] | [((56, 83), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (81, 83), False, 'import configparser\n'), ((565, 583), 'requests.Session', 'requests.Session', ([], {}), '()\n', (581, 583), False, 'import requests\n')] |
from dagster import Field, In, Int, List, configured, job, op
# start_configured_named
@op(
config_schema={
"is_sample": Field(bool, is_required=False, default_value=False),
},
ins={"xs": In(List[Int])},
)
def get_dataset(context, xs):
if context.op_config["is_sample"]:
return xs[:5]
... | [
"dagster.Field",
"dagster.configured",
"dagster.In"
] | [((505, 551), 'dagster.configured', 'configured', (['get_dataset'], {'name': '"""sample_dataset"""'}), "(get_dataset, name='sample_dataset')\n", (515, 551), False, 'from dagster import Field, In, Int, List, configured, job, op\n'), ((588, 632), 'dagster.configured', 'configured', (['get_dataset'], {'name': '"""full_dat... |
import jax
import jax.numpy as jnp
import pytest
from e3nn_jax import Irrep, Irreps, IrrepsData
def test_creation():
Irrep(3, 1)
ir = Irrep("3e")
Irrep(ir)
assert Irrep('10o') == Irrep(10, -1)
assert Irrep("1y") == Irrep("1o")
irreps = Irreps(ir)
Irreps(irreps)
Irreps([(32, (4, -1))])... | [
"e3nn_jax.Irrep",
"e3nn_jax.Irrep.iterator",
"pytest.raises",
"jax.numpy.ones",
"e3nn_jax.Irreps"
] | [((123, 134), 'e3nn_jax.Irrep', 'Irrep', (['(3)', '(1)'], {}), '(3, 1)\n', (128, 134), False, 'from e3nn_jax import Irrep, Irreps, IrrepsData\n'), ((144, 155), 'e3nn_jax.Irrep', 'Irrep', (['"""3e"""'], {}), "('3e')\n", (149, 155), False, 'from e3nn_jax import Irrep, Irreps, IrrepsData\n'), ((160, 169), 'e3nn_jax.Irrep'... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# @id $Id: 895abaacdf9a1c95b3650930a6fc5a820c7b1c9e $
# @rev $Format:%H$ ($Format:%h$)
# @tree $Format:%T$ ($Format:%t$)
# @date $Format:%ci$
# @author $Format:%an$ <$Format:%ae$>
# @copyright Copyright (c) 2019-present, <NAME>... | [
"imp.reload",
"sublime.platform",
"os.environ.copy",
"logging.Formatter",
"os.path.isfile",
"os.path.join",
"sublime.expand_variables",
"subprocess.STARTUPINFO",
"sublime.load_settings",
"os.path.normpath",
"os.access",
"os.chmod",
"os.stat",
"os.path.basename",
"os.path.pathsep.join",
... | [((640, 665), 'logging.getLogger', 'logging.getLogger', (['"""root"""'], {}), "('root')\n", (657, 665), False, 'import logging\n'), ((679, 697), 'sublime.platform', 'sublime.platform', ([], {}), '()\n', (695, 697), False, 'import sublime\n'), ((3204, 3235), 'os.makedirs', 'os.makedirs', (['dst'], {'exist_ok': '(True)'}... |
# -*- coding: utf-8 -*-
from collections import namedtuple
from athenacli.packages.format_utils import format_status, humanize_size
def test_format_status_plural():
assert format_status(rows_length=1) == "1 row in set"
assert format_status(rows_length=2) == "2 rows in set"
def test_format_status_no_results... | [
"athenacli.packages.format_utils.format_status",
"athenacli.packages.format_utils.humanize_size",
"collections.namedtuple"
] | [((436, 526), 'collections.namedtuple', 'namedtuple', (['"""FakeCursor"""', "['engine_execution_time_in_millis', 'data_scanned_in_bytes']"], {}), "('FakeCursor', ['engine_execution_time_in_millis',\n 'data_scanned_in_bytes'])\n", (446, 526), False, 'from collections import namedtuple\n'), ((180, 208), 'athenacli.pac... |
# Process: Global Surface Water (GSW) dataset developed by Pekel et al. (2016): https://global-surface-water.appspot.com/download
# Import required packages
import os, sys, urllib.request, subprocess
# Import helper functions relevant to this script
sys.path.append('E:/mdm123/D/scripts/geo/')
from geo_helpers import ... | [
"sys.path.append",
"subprocess.run",
"os.makedirs",
"os.path.exists",
"geo_helpers.extract_projection_info",
"geo_helpers.create_bounded_geotiff",
"geo_helpers.get_geotiff_projection"
] | [((252, 295), 'sys.path.append', 'sys.path.append', (['"""E:/mdm123/D/scripts/geo/"""'], {}), "('E:/mdm123/D/scripts/geo/')\n", (267, 295), False, 'import os, sys, urllib.request, subprocess\n'), ((2654, 2700), 'os.path.exists', 'os.path.exists', (["(folder_gsw + 'raw/' + filename)"], {}), "(folder_gsw + 'raw/' + filen... |
"""modificacion
Revision ID: 89aa2646be23
Revises: 2975329c1<PASSWORD>
Create Date: 2016-05-20 17:07:56.149371
"""
# revision identifiers, used by Alembic.
revision = '89aa2646be23'
down_revision = '<KEY>'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - p... | [
"alembic.op.drop_column",
"sqlalchemy.Unicode"
] | [((547, 582), 'alembic.op.drop_column', 'op.drop_column', (['"""companies"""', '"""mapa"""'], {}), "('companies', 'mapa')\n", (561, 582), False, 'from alembic import op\n'), ((387, 409), 'sqlalchemy.Unicode', 'sa.Unicode', ([], {'length': '(255)'}), '(length=255)\n', (397, 409), True, 'import sqlalchemy as sa\n')] |
"""
Copyright (c) 2020 Aiven Ltd
See LICENSE for details
Minimal etcdv3 client library on top of httpx
"""
from .utils import AstacusModel, httpx_request
import base64
import json
class KVRangeRequest(AstacusModel):
key: str
range_end: str = ""
def b64encode_to_str(s):
return base64.b64encode(s).de... | [
"base64.b64encode",
"base64.b64decode",
"json.dumps"
] | [((469, 490), 'base64.b64decode', 'base64.b64decode', (['key'], {}), '(key)\n', (485, 490), False, 'import base64\n'), ((492, 515), 'base64.b64decode', 'base64.b64decode', (['value'], {}), '(value)\n', (508, 515), False, 'import base64\n'), ((298, 317), 'base64.b64encode', 'base64.b64encode', (['s'], {}), '(s)\n', (314... |
from flask import Response, request
from flask_jwt_extended import jwt_required, get_jwt_identity
from database.models import Ingredient, User
from flask_restful import Resource
from mongoengine.errors import FieldDoesNotExist, NotUniqueError, DoesNotExist, ValidationError, InvalidQueryError
from resources.errors impor... | [
"database.models.User.objects.get",
"flask_jwt_extended.get_jwt_identity",
"database.models.Ingredient.objects",
"database.models.Ingredient.objects.get",
"flask.Response",
"flask.request.get_json",
"database.models.Ingredient"
] | [((592, 654), 'flask.Response', 'Response', (['ingredients'], {'mimetype': '"""application/json"""', 'status': '(200)'}), "(ingredients, mimetype='application/json', status=200)\n", (600, 654), False, 'from flask import Response, request\n'), ((729, 747), 'flask_jwt_extended.get_jwt_identity', 'get_jwt_identity', ([], ... |
import kfp
with open('curr_time.txt', 'r') as file:
curr_timestamp = file.read().replace('\n', '')
client = kfp.Client(host='http://localhost:8080')
file_name = 'train_targe_image_reco_pipeline.yaml'
tarsan_pipelineid='6304e111-9c28-4436-8be6-007318be64e2'
version_id = file_name+'-'+curr_timestamp
new_... | [
"kfp.Client"
] | [((119, 159), 'kfp.Client', 'kfp.Client', ([], {'host': '"""http://localhost:8080"""'}), "(host='http://localhost:8080')\n", (129, 159), False, 'import kfp\n')] |
import pytest
from loamy.fields import String, Integer, Float, Number
from loamy.exceptions import ValidationError
def test_string_field():
"""Ensure only `bytes` or `str` types pass `String` validation."""
myfield = String()
myfield.value = "mystr"
myfield.validate()
myfield2 = String()
my... | [
"loamy.fields.String",
"loamy.fields.Number",
"loamy.fields.Float",
"loamy.fields.Integer",
"pytest.raises"
] | [((228, 236), 'loamy.fields.String', 'String', ([], {}), '()\n', (234, 236), False, 'from loamy.fields import String, Integer, Float, Number\n'), ((305, 313), 'loamy.fields.String', 'String', ([], {}), '()\n', (311, 313), False, 'from loamy.fields import String, Integer, Float, Number\n'), ((386, 394), 'loamy.fields.St... |
################################################################################################################################
# General setup
################################################################################################################################
# Import libraries
import sys
import nu... | [
"psutil.virtual_memory",
"numpy.floor",
"numpy.ones",
"numpy.isnan",
"numpy.arange",
"numpy.exp",
"scipy.interpolate.interp1d",
"numpy.unique",
"numpy.meshgrid",
"scipy.integrate.romb",
"numpy.append",
"numpy.max",
"numpy.linspace",
"numpy.tensordot",
"numpy.isinf",
"scipy.interpolate.... | [((625, 651), 'numpy.log', 'np.log', (['sys.float_info.min'], {}), '(sys.float_info.min)\n', (631, 651), True, 'import numpy as np\n'), ((652, 662), 'numpy.log', 'np.log', (['(10)'], {}), '(10)\n', (658, 662), True, 'import numpy as np\n'), ((6187, 6294), 'numpy.array', 'np.array', (['[1 / self.max_F_dot, 1 / self.K_ha... |
# -*- coding: UTF-8 -*-
from django.db.models import Q
from rest_framework.response import Response
from rest_framework.views import APIView
from workorder.models.sqlorder import *
from workorder.models.autoorder import *
from workorder.serializers.workorder import *
from user.permissions import CustomerPremission
from... | [
"datetime.date.today",
"django.db.models.Q",
"rest_framework.response.Response",
"datetime.timedelta",
"logging.getLogger"
] | [((504, 532), 'logging.getLogger', 'logging.getLogger', (['"""default"""'], {}), "('default')\n", (521, 532), False, 'import logging\n'), ((1646, 1658), 'rest_framework.response.Response', 'Response', (['re'], {}), '(re)\n', (1654, 1658), False, 'from rest_framework.response import Response\n'), ((5787, 5799), 'rest_fr... |
# coding: utf-8
import numpy as np
import re
import copy
import sys
import networkx as nx
#import matplotlib.pyplot as plt
#import operator
#from collections import defaultdict
#from collections import Counter
#from collections import deque
import time
#from itertools import combinations
# number of combinations for n... | [
"numpy.sort",
"numpy.asarray",
"time.time",
"numpy.insert"
] | [((816, 851), 'numpy.asarray', 'np.asarray', (['input_val'], {'dtype': 'np.int'}), '(input_val, dtype=np.int)\n', (826, 851), True, 'import numpy as np\n'), ((866, 882), 'numpy.sort', 'np.sort', (['numbers'], {}), '(numbers)\n', (873, 882), True, 'import numpy as np\n'), ((950, 974), 'numpy.insert', 'np.insert', (['num... |
"""Dict utility."""
import hashlib
import json
from typing import Any, Union
def get(d: dict, keys: Union[str, list[str]], safe: bool = True) -> Any:
"""Get dict value by keys.
Args:
d (dict): Target dict.
keys (List[str]): Keys.
safe (bool, optional): Safe or not.
Raises:
... | [
"json.dumps"
] | [((2222, 2299), 'json.dumps', 'json.dumps', (['json_dict'], {'ensure_ascii': '(False)', 'sort_keys': 'sort_keys', 'indent': 'indent'}), '(json_dict, ensure_ascii=False, sort_keys=sort_keys, indent=indent)\n', (2232, 2299), False, 'import json\n')] |
import os
import glob
import scipy
import numpy as np
import nibabel as nib
import tensorflow as tf
from tqdm import tqdm
from scipy.ndimage import zoom
from args import TestArgParser
from util import DiceCoefficient
from model import Model
class Interpolator(object):
def __init__(self, modalities, order=3, mode... | [
"numpy.mean",
"tensorflow.sqrt",
"os.path.join",
"args.TestArgParser",
"tensorflow.random.uniform",
"tensorflow.nn.moments",
"tensorflow.pad",
"tensorflow.concat",
"scipy.ndimage.zoom",
"numpy.place",
"numpy.max",
"tensorflow.squeeze",
"numpy.stack",
"nibabel.Nifti1Image",
"tensorflow.re... | [((5779, 5806), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['[res]'], {}), '([res])\n', (5799, 5806), True, 'import tensorflow as tf\n'), ((5819, 5869), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['x.shape[:-1]'], {'dtype': 'tf.int32'}), '(x.shape[:-1], dtype=tf.int32)\n', (5839, 5869), True... |
"""
Created on Apr 14, 2017
@author: sgoldsmith
Copyright (c) <NAME>
All rights reserved.
"""
import os, cv2, numpy, detectbase
class motiondet(detectbase.detectbase):
"""Motion detection image processor.
Uses moving average to determine change percent.
"""
def __init__(self, appCon... | [
"cv2.resize",
"cv2.dilate",
"cv2.cvtColor",
"cv2.accumulateWeighted",
"cv2.threshold",
"numpy.float32",
"cv2.countNonZero",
"cv2.blur",
"cv2.convertScaleAbs",
"numpy.bitwise_and",
"cv2.erode",
"cv2.boundingRect",
"os.path.expanduser",
"cv2.findContours"
] | [((1149, 1222), 'cv2.dilate', 'cv2.dilate', (['image', 'None'], {'iterations': "self.appConfig.motion['dilateAmount']"}), "(image, None, iterations=self.appConfig.motion['dilateAmount'])\n", (1159, 1222), False, 'import os, cv2, numpy, detectbase\n'), ((1352, 1423), 'cv2.erode', 'cv2.erode', (['image', 'None'], {'itera... |
import logging
from . import LoggableObject
from .data.data_loader import DataLoader
from .evaluation import EvaluationMetrics, StepEvaluationMetrics, Evaluator
from .experimentation import Experimentation
from .models import BaseModel
logger = logging.getLogger(__name__)
class ExperimentRunner:
def __init__(
... | [
"logging.getLogger"
] | [((247, 274), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (264, 274), False, 'import logging\n')] |
import jwt
import requests
from datetime import datetime
debug = False
def get_payload(encoded):
failed = False
print(encoded)
try:
print(jwt.get_unverified_header(encoded))
decoded_jwt = jwt.decode(encoded, options={"verify_signature": False}, algorithms=["RS256"])
keys_returned ... | [
"jwt.get_unverified_header",
"datetime.datetime.fromtimestamp",
"requests.post",
"datetime.datetime.now",
"jwt.decode"
] | [((219, 297), 'jwt.decode', 'jwt.decode', (['encoded'], {'options': "{'verify_signature': False}", 'algorithms': "['RS256']"}), "(encoded, options={'verify_signature': False}, algorithms=['RS256'])\n", (229, 297), False, 'import jwt\n'), ((1632, 1754), 'requests.post', 'requests.post', (['"""https://partners.dnaspaces.... |
# -*- coding: utf-8 -*-
from future.moves.urllib.parse import urlparse
import datetime
from ..exceptions import AttributeValueError, TagAttributeError
from ..html.root.tags import TAGS
def validate_tag(tag=None):
"""Validates whether the given tag is supported by korona or not."""
if not tag:
raise ... | [
"future.moves.urllib.parse.urlparse"
] | [((5237, 5254), 'future.moves.urllib.parse.urlparse', 'urlparse', ([], {'url': 'url'}), '(url=url)\n', (5245, 5254), False, 'from future.moves.urllib.parse import urlparse\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright Toolkit Authors
"""Test base statistic calculation script with Pytest."""
import pytest
@pytest.mark.extra
@pytest.mark.ros
def test_base_statistic_calculation():
"""Run the base statistic calculation test."""
import pandas as pd
from pydtk.io ... | [
"pydtk.db.V3DBSearchEngine",
"pydtk.db.V3TimeSeriesCassandraDBSearchEngine",
"pydtk.statistics.BaseStatisticCalculation",
"pydtk.db.V2TimeSeriesDBHandler",
"pydtk.db.V3TimeSeriesCassandraDBHandler",
"time.time",
"pydtk.io.BaseFileReader",
"pydtk.db.v2.TimeSeriesDBHandler",
"pydtk.db.V2TimeSeriesDBSe... | [((475, 491), 'pydtk.io.BaseFileReader', 'BaseFileReader', ([], {}), '()\n', (489, 491), False, 'from pydtk.io import BaseFileReader\n'), ((621, 658), 'pydtk.statistics.BaseStatisticCalculation', 'BaseStatisticCalculation', (['target_span'], {}), '(target_span)\n', (645, 658), False, 'from pydtk.statistics import BaseS... |
from unittest import TestCase
from xsdata.models.xsd import All
class AllTests(TestCase):
def test_get_restrictions(self):
obj = All(min_occurs=1, max_occurs=2)
self.assertEqual({"max_occurs": 2, "min_occurs": 1}, obj.get_restrictions())
| [
"xsdata.models.xsd.All"
] | [((144, 175), 'xsdata.models.xsd.All', 'All', ([], {'min_occurs': '(1)', 'max_occurs': '(2)'}), '(min_occurs=1, max_occurs=2)\n', (147, 175), False, 'from xsdata.models.xsd import All\n')] |
from flask import Blueprint
import marshmallow
from app.extensions import ma
api = Blueprint("member", "member")
upload = Blueprint("upload", "upload")
# Response schema
class MemberSchema(ma.Schema):
""" member API response schema """
class Meta:
# expose only these fields in response
fiel... | [
"marshmallow.fields.Str",
"flask.Blueprint",
"marshmallow.fields.Int",
"marshmallow.fields.Nested"
] | [((85, 114), 'flask.Blueprint', 'Blueprint', (['"""member"""', '"""member"""'], {}), "('member', 'member')\n", (94, 114), False, 'from flask import Blueprint\n'), ((124, 153), 'flask.Blueprint', 'Blueprint', (['"""upload"""', '"""upload"""'], {}), "('upload', 'upload')\n", (133, 153), False, 'from flask import Blueprin... |
import syslog
import datetime
import subprocess
def _notify(summary, body, expire, is_urgent=False):
stack = ['notify-send', summary, body]
if is_urgent:
stack.append('-u')
stack.append('critical')
stack.append('-t')
stack.append(str(expire))
process = subprocess.Popen(stack) # asynchronous call
def... | [
"subprocess.Popen"
] | [((272, 295), 'subprocess.Popen', 'subprocess.Popen', (['stack'], {}), '(stack)\n', (288, 295), False, 'import subprocess\n')] |
r"""A module for handling data from the Deniz lab nanodrop, especially phase diagrams.
Classes
-------
ParseKey
organize information to parse "Sample ID" column
instance parse_rna_peptide is provided
Functions
---------
tidy_data(list_of_files, file_reader=pd.read_csv, file_reader_kwargs=dict(sep="\t"), **kwa... | [
"wrangling.utilities.find_outlier_bounds",
"pandas.testing.assert_index_equal",
"re.escape",
"wrangling.utilities.break_out_date_and_time",
"wrangling.utilities.drop_zeros",
"warnings.warn",
"wrangling.utilities.identify_outliers",
"pandas.concat"
] | [((3797, 3834), 'wrangling.utilities.break_out_date_and_time', 'utilities.break_out_date_and_time', (['df'], {}), '(df)\n', (3830, 3834), True, 'import wrangling.utilities as utilities\n'), ((14429, 14501), 'warnings.warn', 'warnings.warn', (['"""This function moved to utilities.py"""', 'DeprecationWarning'], {}), "('T... |
from re import L
import torch
from .fingerprint import MoleculeFingerPrint
def load_pretrained_fingerprint(cuda=False):
link = "http://192.168.2.130:8000/gsa/pcqm4mv2_pretrained_standard.pt"
model_state_dict = torch.hub.load_state_dict_from_url(link)
new_state_dict = {}
for k, v in model_state_dict.... | [
"torch.hub.load_state_dict_from_url"
] | [((221, 261), 'torch.hub.load_state_dict_from_url', 'torch.hub.load_state_dict_from_url', (['link'], {}), '(link)\n', (255, 261), False, 'import torch\n')] |
import time
class Waiter:
def __init__(self, condition):
self.condition = condition
def wait(self, timeout: float) -> bool:
expires_at = time.time() + timeout
while time.time() < expires_at:
if self.condition():
return True
time.sleep(0.050)
... | [
"time.sleep",
"time.time"
] | [((164, 175), 'time.time', 'time.time', ([], {}), '()\n', (173, 175), False, 'import time\n'), ((200, 211), 'time.time', 'time.time', ([], {}), '()\n', (209, 211), False, 'import time\n'), ((299, 315), 'time.sleep', 'time.sleep', (['(0.05)'], {}), '(0.05)\n', (309, 315), False, 'import time\n')] |
import numpy as np
from sklearn.cluster import KMeans
from tqdm import tqdm
import matplotlib.pyplot as plt
from preliminaries.embedding import aggregateApiSequences
from utils.file import loadJson, dumpIterable, dumpJson
from utils.manager import PathManager
from baselines.alignment import apiCluster
from utils.timer... | [
"numpy.stack",
"numpy.load",
"utils.stat.calBeliefeInterval",
"matplotlib.pyplot.show",
"utils.timer.StepTimer",
"matplotlib.pyplot.plot",
"utils.manager.PathManager",
"utils.magic.nRandom",
"numpy.argmax",
"sklearn.cluster.KMeans",
"numpy.zeros",
"utils.magic.magicSeed",
"numpy.arange",
"... | [((513, 531), 'numpy.load', 'np.load', (['dict_path'], {}), '(dict_path)\n', (520, 531), True, 'import numpy as np\n'), ((695, 732), 'numpy.arange', 'np.arange', (['k_range[0]', '(k_range[1] + 1)'], {}), '(k_range[0], k_range[1] + 1)\n', (704, 732), True, 'import numpy as np\n'), ((735, 755), 'matplotlib.pyplot.plot', ... |
# -*- coding: utf-8 -*-
"""
This script works for foam phantom.
"""
import numpy as np
import glob
import dxchange
import matplotlib.pyplot as plt
import scipy.interpolate
import tomopy
from scipy.interpolate import Rbf
from mpl_toolkits.mplot3d.axes3d import Axes3D
from matplotlib import cm
import matplotlib
from pr... | [
"numpy.set_printoptions",
"numpy.meshgrid",
"matplotlib.pyplot.show",
"tomopy.recon",
"numpy.log",
"dxchange.write_tiff",
"tomopy.angles",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.arange",
"numpy.array",
"numpy.linspace",
"matplotlib.pyplot.rc",
"numpy.squeeze",
"numpy.sqrt"
] | [((429, 470), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'threshold': '"""infinite"""'}), "(threshold='infinite')\n", (448, 470), True, 'import numpy as np\n'), ((648, 672), 'numpy.arange', 'np.arange', (['(0.1)', '(1.1)', '(0.1)'], {}), '(0.1, 1.1, 0.1)\n', (657, 672), True, 'import numpy as np\n'), ((1463... |
# (c) <NAME> 2021
# see embedded licence file
# imelt V1.1
import numpy as np
import torch, time
import h5py
import torch.nn.functional as F
from sklearn.metrics import mean_squared_error
class data_loader():
"""custom data loader for batch training
"""
def __init__(self,path_viscosity,path_raman,path_de... | [
"torch.nn.Dropout",
"numpy.sum",
"numpy.mean",
"numpy.sin",
"numpy.std",
"torch.load",
"torch.FloatTensor",
"torch.Tensor",
"torch.nn.Linear",
"torch.log",
"sklearn.metrics.mean_squared_error",
"numpy.trapz",
"h5py.File",
"numpy.cos",
"torch.set_grad_enabled",
"torch.reshape",
"numpy... | [((43013, 43054), 'numpy.trapz', 'np.trapz', (['y[:, x < lb]', 'x[x < lb]'], {'axis': '(1)'}), '(y[:, x < lb], x[x < lb], axis=1)\n', (43021, 43054), True, 'import numpy as np\n'), ((43060, 43101), 'numpy.trapz', 'np.trapz', (['y[:, x > hb]', 'x[x > hb]'], {'axis': '(1)'}), '(y[:, x > hb], x[x > hb], axis=1)\n', (43068... |
#!/usr/bin/env python
# encoding: utf-8
import os, shutil
from flask import Flask
def create_app(conf=None):
app = Flask(__name__, instance_relative_config=True)
from . import jinja_filters
app.register_blueprint(jinja_filters.bp)
app.logger.debug('Add jinja_filters blueprint')
# check instance... | [
"os.makedirs",
"os.unlink",
"os.path.isdir",
"flask.Flask",
"os.environ.get",
"os.path.isfile",
"os.path.islink",
"shutil.rmtree",
"os.path.join",
"os.listdir",
"logging.getLogger"
] | [((122, 168), 'flask.Flask', 'Flask', (['__name__'], {'instance_relative_config': '(True)'}), '(__name__, instance_relative_config=True)\n', (127, 168), False, 'from flask import Flask\n'), ((335, 367), 'os.path.isdir', 'os.path.isdir', (['app.instance_path'], {}), '(app.instance_path)\n', (348, 367), False, 'import os... |
# -*- coding: utf-8 -*-
from flask import render_template
from utils.jinja import guid_factory
def histogram(value, values, **kwargs):
values = map(str, values)
return render_template('widgets/histogram.html',
value=value, values=values, guids=guid_factory(), **kwargs)
| [
"utils.jinja.guid_factory"
] | [((268, 282), 'utils.jinja.guid_factory', 'guid_factory', ([], {}), '()\n', (280, 282), False, 'from utils.jinja import guid_factory\n')] |
#!/usr/bin/env python3
# =============================================================================
"""
Code Information:
Maintainer: Eng. <NAME>
Mail: <EMAIL>
Kiwi Campus / Computer & Ai Vision Team
"""
# =============================================================================
import time
import sys
imp... | [
"rclpy.spin",
"rclpy.node.Node.__init__",
"utils.python_utils.printlog",
"usr_msgs.msg.Kiwibot",
"rclpy.init",
"rclpy.callback_groups.ReentrantCallbackGroup",
"ctypes.cdll.LoadLibrary",
"time.sleep",
"std_msgs.msg.Int8",
"rclpy.shutdown",
"sys.exc_info",
"os.path.split",
"os.getenv",
"rclp... | [((7546, 7567), 'rclpy.init', 'rclpy.init', ([], {'args': 'args'}), '(args=args)\n', (7556, 7567), False, 'import rclpy\n'), ((7756, 7779), 'rclpy.executors.MultiThreadedExecutor', 'MultiThreadedExecutor', ([], {}), '()\n', (7777, 7779), False, 'from rclpy.executors import MultiThreadedExecutor\n'), ((7939, 7973), 'rcl... |
import pytest
from datetime import datetime
from portal.academy.models import Grade
from portal.academy.services import (
check_graduation_status,
check_complete_specialization,
csvdata,
)
from portal.academy.services import get_last_grade, get_best_grade
from portal.hackathons.models import Attendance
@... | [
"portal.academy.models.Grade.objects.create",
"portal.academy.services.csvdata",
"portal.hackathons.models.Attendance.objects.create",
"portal.academy.services.get_best_grade",
"portal.academy.services.get_last_grade",
"portal.academy.services.check_graduation_status",
"pytest.mark.django_db",
"dateti... | [((3349, 3388), 'pytest.mark.django_db', 'pytest.mark.django_db', ([], {'transaction': '(True)'}), '(transaction=True)\n', (3370, 3388), False, 'import pytest\n'), ((3746, 3785), 'pytest.mark.django_db', 'pytest.mark.django_db', ([], {'transaction': '(True)'}), '(transaction=True)\n', (3767, 3785), False, 'import pytes... |
import bayes
bayes.getTopWords(ny,sf)
| [
"bayes.getTopWords"
] | [((14, 39), 'bayes.getTopWords', 'bayes.getTopWords', (['ny', 'sf'], {}), '(ny, sf)\n', (31, 39), False, 'import bayes\n')] |
import csv
import logging
import os
import shutil
import jinja2
import pdfkit
CSV_EXT = '.csv'
OUTPUT_DIR = 'output'
REPORTS_DIR = 'reports'
GENERATE_HTML = False
ORDERS_TEMPLATE_FILE = "templates/orders-template.html"
ORDERS_TEMPLATE_CSS_FILE = "templates/orders-style-prefix.css"
ITEMS_TEMPLATE_FILE = "templates/... | [
"os.mkdir",
"os.remove",
"logging.warning",
"os.getcwd",
"os.path.exists",
"jinja2.FileSystemLoader",
"jinja2.Environment",
"logging.info",
"pdfkit.from_string",
"os.path.join",
"csv.DictWriter"
] | [((458, 498), 'os.path.join', 'os.path.join', (['OUTPUT_DIR', 'order_filename'], {}), '(OUTPUT_DIR, order_filename)\n', (470, 498), False, 'import os\n'), ((664, 707), 'os.path.join', 'os.path.join', (['order_output_dir', 'REPORTS_DIR'], {}), '(order_output_dir, REPORTS_DIR)\n', (676, 707), False, 'import os\n'), ((105... |
# File: benchmark.py
import json
import os
import string
import logging
import sys
import csv
from pathlib import Path
logging.basicConfig(format='[ %(levelname)s ] %(message)s',level=logging.DEBUG)
from common_demo import banner,terminal_clean,existCheck_downloader,model_info_ckeck
logging.disable(logging.DEBUG)
cur... | [
"logging.error",
"json.load",
"logging.debug",
"csv.writer",
"logging.basicConfig",
"pathlib.Path.home",
"os.getcwd",
"common_demo.model_info_ckeck",
"logging.warning",
"common_demo.existCheck_downloader",
"os.popen",
"common_demo.banner",
"logging.disable",
"os.path.isfile",
"logging.in... | [((120, 205), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""[ %(levelname)s ] %(message)s"""', 'level': 'logging.DEBUG'}), "(format='[ %(levelname)s ] %(message)s', level=logging.DEBUG\n )\n", (139, 205), False, 'import logging\n'), ((285, 315), 'logging.disable', 'logging.disable', (['logging.DE... |
#!/usr/bin/python3
import sys
# hex ed
# n, ne, se, s, sw, nw
# given path child took, calculate fewest steps to reach them.
# 1. remove opposing steps (n<-->s)
# 2. merge two-away steps (n + se = ne, etc)
# 3. remove opposing steps again?
stepOrder = ['n', 'ne', 'se', 's', 'sw', 'nw']
def removeOpposing(path):... | [
"sys.exit",
"sys.stdin.readlines"
] | [((1743, 1764), 'sys.stdin.readlines', 'sys.stdin.readlines', ([], {}), '()\n', (1762, 1764), False, 'import sys\n'), ((1823, 1834), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (1831, 1834), False, 'import sys\n')] |
"""
funcs
"""
from PyGromos.files import coord
from generalutilities.function_libs.gromos.files.blocks import blocks
from pymol import cmd
def write_out_cnf(out_path: str, selection: str = "all") -> str:
"""with this function you can write out interface_Pymol structures to cnf :param
out_path: :pa... | [
"generalutilities.function_libs.gromos.files.blocks.blocks.title_block",
"generalutilities.function_libs.gromos.files.blocks.blocks.atomP",
"PyGromos.files.coord.Cnf",
"pymol.finish_launching",
"generalutilities.function_libs.gromos.files.blocks.blocks.atom_pos_block"
] | [((1151, 1182), 'generalutilities.function_libs.gromos.files.blocks.blocks.atom_pos_block', 'blocks.atom_pos_block', (['pos_list'], {}), '(pos_list)\n', (1172, 1182), False, 'from generalutilities.function_libs.gromos.files.blocks import blocks\n'), ((1196, 1222), 'generalutilities.function_libs.gromos.files.blocks.blo... |
#!/usr/bin/env python
"""
This file uses Theano dense layers for estimating Q values, but uses pre-trained Keras features before the dense layers.
"""
# -*- coding: utf-8 -*-
from __future__ import division
from __future__ import print_function
from vizdoom import *
import itertools as it
from random import sample, r... | [
"layers.FCLayer",
"lasagne.objectives.squared_error",
"numpy.max",
"itertools.product",
"theano.tensor.arange",
"numpy.stack",
"keras.backend.learning_phase",
"tqdm.trange",
"time.sleep",
"random.random",
"theano.tensor.matrix",
"lasagne.updates.rmsprop",
"theano.tensor.vector",
"theano.fu... | [((8092, 8098), 'time.time', 'time', ([], {}), '()\n', (8096, 8098), False, 'from time import time, sleep\n'), ((2530, 2547), 'theano.tensor.matrix', 'T.matrix', (['"""State"""'], {}), "('State')\n", (2538, 2547), True, 'import theano.tensor as T\n'), ((2556, 2589), 'theano.tensor.vector', 'T.vector', (['"""Action"""']... |
import sys, os
from nose.tools import ok_, eq_
import biothings.utils.jsondiff as jsondiff
import biothings.utils.jsonpatch as jsonpatch
import json
class JsonDiffTest(object):
__test__ = True
def test_scalar(self):
left = {"one": 1, "ONE": "111"}
right = {"two": 2, "TWO": "222"}
p... | [
"biothings.utils.jsondiff.make",
"nose.tools.eq_",
"biothings.utils.jsonpatch.apply_patch"
] | [((327, 353), 'biothings.utils.jsondiff.make', 'jsondiff.make', (['left', 'right'], {}), '(left, right)\n', (340, 353), True, 'import biothings.utils.jsondiff as jsondiff\n'), ((373, 407), 'biothings.utils.jsonpatch.apply_patch', 'jsonpatch.apply_patch', (['left', 'patch'], {}), '(left, patch)\n', (394, 407), True, 'im... |
# flake8: noqa
import os
import openml
from openml import datasets
from openml.datasets.functions import DATASETS_CACHE_DIR_NAME
# get all datasets before running app, so that datasets are loaded faster
from openml.utils import _create_cache_directory_for_id
root_dir = os.path.abspath(os.sep)
openml.config.cache_dire... | [
"os.path.abspath",
"openml.datasets.list_datasets",
"os.path.exists",
"openml.utils._create_cache_directory_for_id",
"openml.datasets.get_dataset",
"openml.utils._remove_cache_dir_for_id",
"os.path.join"
] | [((272, 295), 'os.path.abspath', 'os.path.abspath', (['os.sep'], {}), '(os.sep)\n', (287, 295), False, 'import os\n'), ((328, 396), 'os.path.join', 'os.path.join', (['root_dir', '"""public"""', '"""python-cache"""', '""".openml"""', '"""cache"""'], {}), "(root_dir, 'public', 'python-cache', '.openml', 'cache')\n", (340... |
from src.game.object import Object
from src.utils.resource import Resource
class Cell(Object):
def __init__(self, x: int, y: int, size: tuple):
self.size = size
self.image, self.rect = Resource.get_surface(self.size, (0, 0, 0))
super().__init__((self.image, self.rect), self.size)
... | [
"src.utils.resource.Resource.get_surface"
] | [((207, 249), 'src.utils.resource.Resource.get_surface', 'Resource.get_surface', (['self.size', '(0, 0, 0)'], {}), '(self.size, (0, 0, 0))\n', (227, 249), False, 'from src.utils.resource import Resource\n')] |
"""GUI for rejecting epochs"""
# Author: <NAME> <<EMAIL>>
# Document: represents data
# ChangeAction: modifies Document
# Model: creates ChangeActions and applies them to the History
# Frame:
# - visualizaes Document
# - listens to Document changes
# - issues commands to Model
from logging import getLogger
impo... | [
"wx.Dialog.__init__",
"numpy.abs",
"numpy.invert",
"wx.CheckBox",
"numpy.ones",
"numpy.arange",
"wx.RadioBox",
"wx.Choice",
"numpy.logical_not",
"os.path.exists",
"wx.TextCtrl",
"wx.GetApp",
"scipy.spatial.distance.cdist",
"wx.TextEntryDialog",
"wx.BoxSizer",
"math.sqrt",
"math.ceil"... | [((11436, 11458), 'os.path.splitext', 'os.path.splitext', (['path'], {}), '(path)\n', (11452, 11458), False, 'import os\n'), ((11660, 11682), 'os.path.splitext', 'os.path.splitext', (['path'], {}), '(path)\n', (11676, 11682), False, 'import os\n'), ((14903, 14930), 'os.path.splitext', 'os.path.splitext', (['self.path']... |
import numpy as np
import argparse
import os
from PIL import Image
class BackofficeIconConverter:
"""
Icon creator to convert an input file into the correct format needed by
the SAP Commerce Backoffice framework to be used as icon in the
explorer-tree.
"""
#: Side length of a single image (he... | [
"argparse.ArgumentParser",
"numpy.zeros",
"PIL.Image.open",
"PIL.Image.fromarray",
"os.path.split",
"os.path.join"
] | [((3290, 3517), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Convert simple icons to the SAP Commerce Backoffice explorer tree icon format. The icon must be a sprite consist of 5 different color shades of the icon itself."""'}), "(description=\n 'Convert simple ico... |
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
import sys
import io
class Row:
def __init__(self):
self.cols = []
self.type = ''
def append(self, col):
self.cols.append(col)
def clear(self):
self.cols = []
def copy(self):
r = Row()
r.cols = self.cols... | [
"sys.stdin.read",
"io.TextIOWrapper",
"sys.exit"
] | [((2998, 3051), 'io.TextIOWrapper', 'io.TextIOWrapper', (['sys.stdout.buffer'], {'encoding': '"""utf-8"""'}), "(sys.stdout.buffer, encoding='utf-8')\n", (3014, 3051), False, 'import io\n'), ((3069, 3122), 'io.TextIOWrapper', 'io.TextIOWrapper', (['sys.stderr.buffer'], {'encoding': '"""utf-8"""'}), "(sys.stderr.buffer, ... |
import FWCore.ParameterSet.Config as cms
from Validation.RecoEgamma.electronPostValidationSequenceMiniAOD_cff import *
egammaPostValidationMiniAOD = cms.Sequence( electronPostValidationSequenceMiniAOD )
| [
"FWCore.ParameterSet.Config.Sequence"
] | [((151, 202), 'FWCore.ParameterSet.Config.Sequence', 'cms.Sequence', (['electronPostValidationSequenceMiniAOD'], {}), '(electronPostValidationSequenceMiniAOD)\n', (163, 202), True, 'import FWCore.ParameterSet.Config as cms\n')] |
from django.db import models
from tienda.models import Tienda
# Create your models here.
class Producto(models.Model):
nombre = models.CharField(
max_length=150
)
slug = models.SlugField(
blank=True,
null=True,
max_length=150
)
tienda = models.ForeignKey(
Tie... | [
"django.db.models.CharField",
"django.db.models.ForeignKey",
"django.db.models.PositiveIntegerField",
"django.db.models.SlugField",
"django.db.models.DecimalField"
] | [((133, 165), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(150)'}), '(max_length=150)\n', (149, 165), False, 'from django.db import models\n'), ((191, 246), 'django.db.models.SlugField', 'models.SlugField', ([], {'blank': '(True)', 'null': '(True)', 'max_length': '(150)'}), '(blank=True, null... |
# These are control plot used in the NN pipeline
import h5py
import matplotlib as mpl
import numpy as np
import pandas as pd
from modules.BAR_BC_method import calc_BAR_BC, calc_composition, filter_data_mask
from modules.collect_data import resave_Tomas_OL_OPX_mixtures
import matplotlib.pyplot as plt
import matplotlib... | [
"matplotlib.pyplot.title",
"numpy.sum",
"seaborn.heatmap",
"modules.NN_losses_metrics_activations.my_rmse",
"pandas.read_csv",
"modules.NN_losses_metrics_activations.my_quantile",
"modules.NN_losses_metrics_activations.my_sam",
"numpy.ones",
"numpy.shape",
"numpy.argsort",
"matplotlib.pyplot.fig... | [((766, 782), 'matplotlib.use', 'mpl.use', (['"""TkAgg"""'], {}), "('TkAgg')\n", (773, 782), True, 'import matplotlib as mpl\n'), ((858, 888), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {'size': 'TEXT_SIZE'}), "('font', size=TEXT_SIZE)\n", (864, 888), True, 'import matplotlib.pyplot as plt\n'), ((920, 957), 'ma... |
import os
import subprocess
import setuptools
import unittest
import sys
from pathlib import Path
from enum import Enum, auto
from setuptools.command.install import install
from setuptools.command.test import test
from gramtools.version import package_version
with open("./README.md") as fhandle:
readme = fhandl... | [
"os.mkdir",
"unittest.TextTestRunner",
"os.path.exists",
"pathlib.Path",
"subprocess.call",
"enum.auto",
"setuptools.command.install.install.run",
"os.path.join",
"setuptools.find_packages"
] | [((698, 704), 'enum.auto', 'auto', ([], {}), '()\n', (702, 704), False, 'from enum import Enum, auto\n'), ((716, 722), 'enum.auto', 'auto', ([], {}), '()\n', (720, 722), False, 'from enum import Enum, auto\n'), ((1113, 1219), 'subprocess.call', 'subprocess.call', (['f"""CC=gcc CXX=g++ cmake -DCMAKE_BUILD_TYPE={build_ty... |
#!/usr/bin/env python
import os
import logging
import pybert as pb
def merge_schemes(scheme1: pb.DataContainerERT, scheme2: pb.DataContainerERT, tmp_dir: str, remove_tmp_file=True):
""" Merges to schemes while prioritizing the first one.
Utility function to merge to schemes. Electrode positions can differ. ... | [
"pybert.load",
"os.remove",
"logging.info"
] | [((4343, 4360), 'pybert.load', 'pb.load', (['tmp_file'], {}), '(tmp_file)\n', (4350, 4360), True, 'import pybert as pb\n'), ((7197, 7246), 'logging.info', 'logging.info', (['"""Extracting configs from scheme..."""'], {}), "('Extracting configs from scheme...')\n", (7209, 7246), False, 'import logging\n'), ((8318, 8335)... |
import torch
import torch.nn as nn
__all__ = ['HelloWorld', 'helloworld']
class HelloWorld(nn.Module):
def __init__(self, num_classes=10):
super(HelloWorld, self).__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 16, kernel_size=3, stride=1, padding=1, bias=False),
n... | [
"torch.nn.AvgPool2d",
"torch.nn.Conv2d",
"torch.nn.ReLU"
] | [((690, 710), 'torch.nn.AvgPool2d', 'nn.AvgPool2d', (['(32)', '(32)'], {}), '(32, 32)\n', (702, 710), True, 'import torch.nn as nn\n'), ((241, 305), 'torch.nn.Conv2d', 'nn.Conv2d', (['(3)', '(16)'], {'kernel_size': '(3)', 'stride': '(1)', 'padding': '(1)', 'bias': '(False)'}), '(3, 16, kernel_size=3, stride=1, padding=... |
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import statistics
def main():
font = {'font.family' : 'normal',
#'font.weight' : 'bold',
'font.size' : 18}
plt.rcParams.update(font)
blue_patch = mpatches.Patch(color='blue', label='Orig... | [
"pandas.read_csv",
"matplotlib.pyplot.rcParams.update",
"statistics.mean",
"matplotlib.patches.Patch",
"matplotlib.pyplot.subplots"
] | [((232, 257), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (['font'], {}), '(font)\n', (251, 257), True, 'import matplotlib.pyplot as plt\n'), ((280, 326), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': '"""blue"""', 'label': '"""Original"""'}), "(color='blue', label='Original')\n", (294, 3... |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 7 22:48:16 2020
@author: SE
"""
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 28 17:54:20 2020
@author: syful
"""
import re
import pandas as pd
import numpy as np
from collections import Counter
import statistics
df1=pd.read_csv("F:/1_NAIST_Research_SE/SE_meeting/N... | [
"pandas.read_csv",
"statistics.median",
"pandas.DataFrame"
] | [((272, 386), 'pandas.read_csv', 'pd.read_csv', (['"""F:/1_NAIST_Research_SE/SE_meeting/Network-simulators/LDA/01_NS_posts.csv"""'], {'low_memory': '(False)'}), "(\n 'F:/1_NAIST_Research_SE/SE_meeting/Network-simulators/LDA/01_NS_posts.csv',\n low_memory=False)\n", (283, 386), True, 'import pandas as pd\n'), ((38... |
import os
from absl import logging
import numpy as np
import collections
import six
import frozendict
import csv
import ast
import enum
from scipy import (optimize)
from tapas_text_utils import (STRING_NORMALIZATIONS, convert_to_float, to_float32, get_sequence_id, get_question_id)
from interaction_pb2 import (Table, Q... | [
"tapas_wtq_utils.convert",
"interaction_pb2.Question",
"scipy.optimize.linear_sum_assignment",
"tapas_file_utils.list_directory",
"ast.literal_eval",
"interaction_pb2.Table",
"csv.reader",
"csv.DictReader",
"tapas_text_utils.to_float32",
"collections.defaultdict",
"tapas_text_utils.get_sequence_... | [((1414, 1639), 'frozendict.frozendict', 'frozendict.frozendict', (["{SupervisionMode.REMOVE_ALL: ['answer_coordinates', 'float_value',\n 'aggregation_function'], SupervisionMode.REMOVE_ALL_STRICT: [\n 'answer_coordinates', 'float_value', 'aggregation_function']}"], {}), "({SupervisionMode.REMOVE_ALL: ['answer_co... |
# Generated by Django 4.0.2 on 2022-02-14 11:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Task', '0005_alter_summarytask_done'),
]
operations = [
migrations.AddField(
model_name='summarytask',
name='subject... | [
"django.db.models.IntegerField"
] | [((349, 379), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'default': '(5)'}), '(default=5)\n', (368, 379), False, 'from django.db import migrations, models\n'), ((507, 537), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'null': '(True)'}), '(null=True)\n', (526, 537), False, 'from djan... |
# -*- coding: utf-8 -*-
"""Predicting quora answers."""
# Created: 2019-03-06 <NAME> <<EMAIL>>
# Challenge Link
# https://www.hackerrank.com/challenges/quora-answer-classifier/problem
import re
import warnings
from pandas import DataFrame
from sklearn.ensemble import RandomForestClassifier
warnings.filterwarnings('ig... | [
"sklearn.ensemble.RandomForestClassifier",
"re.findall",
"pandas.DataFrame",
"warnings.filterwarnings"
] | [((293, 326), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (316, 326), False, 'import warnings\n'), ((1270, 1294), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {}), '()\n', (1292, 1294), False, 'from sklearn.ensemble import RandomForestClassi... |
from flask import Flask, current_app, request, jsonify
import io
import model
import base64
import logging
from logging.handlers import RotatingFileHandler
from logging import Formatter
app = Flask(__name__)
gunicorn_error_logger = logging.getLogger('gunicorn.error')
app.logger.handlers.extend(gunicorn_error_logger.... | [
"flask.current_app.logger.exception",
"io.BytesIO",
"flask.current_app.logger.error",
"flask.Flask",
"base64.b64decode",
"logging.Formatter",
"flask.jsonify",
"model.predict",
"flask.request.get_json",
"flask.current_app.logger.info",
"logging.handlers.RotatingFileHandler",
"logging.getLogger"... | [((194, 209), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (199, 209), False, 'from flask import Flask, current_app, request, jsonify\n'), ((235, 270), 'logging.getLogger', 'logging.getLogger', (['"""gunicorn.error"""'], {}), "('gunicorn.error')\n", (252, 270), False, 'import logging\n'), ((644, 666), 'b... |
import io
import sys
import os
import json
import base64
import numpy as np
import tensorflow as tf
from PIL import Image
from helpers import download_model
models_url = 'https://www.dropbox.com/s/emee1vxmoch4sbu/models.zip?raw=1'
checkpoint = 'mobilenet_v2_1.0_224'
class syndicai(object):
def __init__(self):
... | [
"os.path.abspath",
"json.load",
"os.getcwd",
"tensorflow.Session",
"base64.b64decode",
"tensorflow.import_graph_def"
] | [((782, 877), 'tensorflow.import_graph_def', 'tf.import_graph_def', (['gd'], {'return_elements': "['input:0', 'MobilenetV2/Predictions/Reshape_1:0']"}), "(gd, return_elements=['input:0',\n 'MobilenetV2/Predictions/Reshape_1:0'])\n", (801, 877), True, 'import tensorflow as tf\n'), ((381, 392), 'os.getcwd', 'os.getcwd... |
# coding:utf-8
from typing import Mapping, Callable, Hashable, Any, Optional
from inspect import Parameter
import collections.abc
from functools import lru_cache
from multipledispatch import Dispatcher
from types import MethodType
Empty = Parameter.empty
class UnregisteredType(TypeError, NotImplementedError):
pa... | [
"functools.lru_cache",
"types.MethodType",
"multipledispatch.Dispatcher"
] | [((1489, 1504), 'functools.lru_cache', 'lru_cache', (['None'], {}), '(None)\n', (1498, 1504), False, 'from functools import lru_cache\n'), ((1326, 1344), 'types.MethodType', 'MethodType', (['f', 'obj'], {}), '(f, obj)\n', (1336, 1344), False, 'from types import MethodType\n'), ((1550, 1581), 'multipledispatch.Dispatche... |
"""Provides helper functions related to datetime operations."""
from datetime import date, datetime, timedelta, timezone
import pandas as pd
import pytz
from chaos_genius.core.utils.constants import SUPPORTED_TIMEZONES
from chaos_genius.settings import TIMEZONE
def get_server_timezone():
"""Get server timezone... | [
"datetime.datetime",
"datetime.datetime.strptime",
"datetime.timedelta",
"pytz.timezone",
"datetime.datetime.now"
] | [((1117, 1173), 'datetime.timedelta', 'timedelta', ([], {'hours': 'utc_offset_hrs', 'minutes': 'utc_offset_mins'}), '(hours=utc_offset_hrs, minutes=utc_offset_mins)\n', (1126, 1173), False, 'from datetime import date, datetime, timedelta, timezone\n'), ((2376, 2450), 'datetime.datetime', 'datetime', ([], {'year': 'date... |
from argparse import Namespace
from pyschism.cmd.fgrid import manning
class FgridCli:
def __init__(self, args: Namespace):
if args.action == 'manning':
manning.ManningsNCli(args)
else:
raise NotImplementedError(f'Unhandled CLI action: {args.action}.')
@staticmethod... | [
"pyschism.cmd.fgrid.manning.add_manning",
"pyschism.cmd.fgrid.manning.ManningsNCli"
] | [((529, 557), 'pyschism.cmd.fgrid.manning.add_manning', 'manning.add_manning', (['actions'], {}), '(actions)\n', (548, 557), False, 'from pyschism.cmd.fgrid import manning\n'), ((181, 207), 'pyschism.cmd.fgrid.manning.ManningsNCli', 'manning.ManningsNCli', (['args'], {}), '(args)\n', (201, 207), False, 'from pyschism.c... |
"""This module provide geometry functionality utils"""
from shapely.geometry import Polygon
def get_polygon_area(coordinates):
"""
This method calculate area
:param coordinates: list of points represented as list [x.y]
:return: float in meters
"""
polygon = process_polygon(coordinates)
are... | [
"shapely.geometry.Polygon"
] | [((1113, 1133), 'shapely.geometry.Polygon', 'Polygon', (['coordinates'], {}), '(coordinates)\n', (1120, 1133), False, 'from shapely.geometry import Polygon\n')] |
from django.db import models
import string
from random import choices
VALID_LETTERS = string.ascii_uppercase
def generate_unique_code(length=6):
while True:
code = "".join(choices(VALID_LETTERS, k=length))
if not Room.objects.filter(code=code):
break
class Room(models.Model):
c... | [
"django.db.models.CharField",
"random.choices",
"django.db.models.BooleanField",
"django.db.models.IntegerField",
"django.db.models.DateTimeField"
] | [((326, 399), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(8)', 'default': 'generate_unique_code', 'unique': '(True)'}), '(max_length=8, default=generate_unique_code, unique=True)\n', (342, 399), False, 'from django.db import models\n'), ((411, 455), 'django.db.models.CharField', 'models.Char... |
#AUTOGENERATED! DO NOT EDIT! File to edit: dev/04_vae.ipynb (unless otherwise specified).
__all__ = ['Encoder', 'Decoder', 'init_weights']
#Cell
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import matplotlib.pyplot as plt
import re
#Cell
class Encoder(nn.Module):
... | [
"torch.nn.Dropout",
"torch.nn.init.kaiming_normal_",
"torch.nn.Tanh",
"torch.nn.ELU",
"torch.nn.init.constant_",
"torch.nn.Linear",
"torch.nn.functional.softplus",
"torch.no_grad",
"torch.nn.Sigmoid"
] | [((598, 624), 'torch.nn.Linear', 'nn.Linear', (['imgsz', 'n_hidden'], {}), '(imgsz, n_hidden)\n', (607, 624), True, 'import torch.nn as nn\n'), ((638, 658), 'torch.nn.ELU', 'nn.ELU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (644, 658), True, 'import torch.nn as nn\n'), ((672, 697), 'torch.nn.Dropout', 'nn.Dropo... |
from CrimeStatisticsMain import *
from pyspark.ml.feature import StringIndexer
from pyspark.ml.feature import VectorAssembler
from pyspark.ml.classification import NaiveBayes
from pyspark.ml import Pipeline
from pyspark.ml.evaluation import MulticlassClassificationEvaluator
if len(sys.argv)<2:
print("P... | [
"pyspark.ml.classification.NaiveBayes",
"pyspark.ml.evaluation.MulticlassClassificationEvaluator",
"pyspark.ml.feature.VectorAssembler",
"pyspark.ml.Pipeline"
] | [((702, 787), 'pyspark.ml.feature.VectorAssembler', 'VectorAssembler', ([], {'inputCols': "['Year', 'LocationDescription']", 'outputCol': '"""features"""'}), "(inputCols=['Year', 'LocationDescription'], outputCol='features'\n )\n", (717, 787), False, 'from pyspark.ml.feature import VectorAssembler\n'), ((899, 949), ... |
# This is your project's main settings file that can be committed to your
# repo. If you need to override a setting locally, use settings_local.py
from funfactory.settings_base import *
SITE_TITLE = 'badg.us'
# Make sure South stays out of the way during testing
#SOUTH_TESTS_MIGRATE = False
#SKIP_SOUTH_TESTS = True
... | [
"django.contrib.auth.models.User.objects.filter"
] | [((1720, 1758), 'django.contrib.auth.models.User.objects.filter', 'User.objects.filter', ([], {'username': 'username'}), '(username=username)\n', (1739, 1758), False, 'from django.contrib.auth.models import User\n')] |
import numpy as np
import tensorflow as tf
tf.reset_default_graph()
sess = tf.InteractiveSession()
def exp():
s_len = 3
N, T = 2, 2
l = np.arange(1, N*T*s_len+1).reshape((N, T, s_len) )
x = tf.convert_to_tensor(l, dtype=tf.float32)
print("x= {}".format(x.eval() ) )
# l = np.arange(1, N*T+1).reshape((N,... | [
"tensorflow.reset_default_graph",
"tensorflow.convert_to_tensor",
"tensorflow.reshape",
"tensorflow.reduce_mean",
"tensorflow.constant",
"tensorflow.shape",
"numpy.random.randint",
"numpy.arange",
"tensorflow.InteractiveSession"
] | [((44, 68), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (66, 68), True, 'import tensorflow as tf\n'), ((76, 99), 'tensorflow.InteractiveSession', 'tf.InteractiveSession', ([], {}), '()\n', (97, 99), True, 'import tensorflow as tf\n'), ((200, 241), 'tensorflow.convert_to_tensor', 'tf.co... |
# -*- coding: utf-8 -*-
import datetime
import time
NAMES = ["Mia", "Emma", "Hannah", "Sofia", "Anna", "Lea", "Ben", "Luca", "Paul", "Jonas", "Finn", "Luis"]
SURNAMES = ["Taake", "Tadlock", "Tappe", "Tappemeyer", "Tappendiek", "Tappmeyer", "Tarner", "Tarras", "Taeulker"]
import random
import itertools
def populate_m... | [
"datetime.datetime",
"time.time",
"random.random",
"random.seed",
"itertools.product"
] | [((635, 646), 'time.time', 'time.time', ([], {}), '()\n', (644, 646), False, 'import time\n'), ((651, 668), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (662, 668), False, 'import random\n'), ((1363, 1374), 'time.time', 'time.time', ([], {}), '()\n', (1372, 1374), False, 'import time\n'), ((700, 734), 'ite... |
# Copyright 2017 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 required by ... | [
"tensorflow.test.main",
"tensorflow.placeholder",
"numpy.array"
] | [((1812, 1826), 'tensorflow.test.main', 'tf.test.main', ([], {}), '()\n', (1824, 1826), True, 'import tensorflow as tf\n'), ((1272, 1319), 'numpy.array', 'np.array', (['[[1.0, 2.0, 3.0], [-1.0, -2.0, -3.0]]'], {}), '([[1.0, 2.0, 3.0], [-1.0, -2.0, -3.0]])\n', (1280, 1319), True, 'import numpy as np\n'), ((1369, 1414), ... |
# pylint: disable=attribute-defined-outside-init,redefined-outer-name
from __future__ import print_function
import argparse
import hashlib
import os
import shutil
import stat
import tarfile
import pkg_resources
import requests
import yaml
import path
import six
from vr.common.paths import (
get_container_name, g... | [
"os.mkdir",
"vr.common.paths.get_app_path",
"argparse.ArgumentParser",
"yaml.safe_dump",
"vr.common.paths.get_lxc_work_path",
"pkg_resources.resource_filename",
"os.path.isfile",
"yaml.safe_load",
"shutil.rmtree",
"os.path.join",
"shutil.copy",
"pkg_resources.get_distribution",
"vr.common.ut... | [((15356, 15422), 'pkg_resources.resource_filename', 'pkg_resources.resource_filename', (['"""vr.runners"""', "('templates/' + name)"], {}), "('vr.runners', 'templates/' + name)\n", (15387, 15422), False, 'import pkg_resources\n'), ((1147, 1172), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (... |
from django.db import models
from django.contrib.auth.models import User
from project.models import Project
from django.conf import settings
import os
class ChangeAttachments(models.Model):
attachment = models.FileField(upload_to='change/attachments/', blank=True)
def delete(self, *args, **kwargs):
... | [
"django.db.models.FileField",
"django.db.models.ManyToManyField",
"django.db.models.CharField",
"django.db.models.ForeignKey",
"django.db.models.FloatField"
] | [((211, 272), 'django.db.models.FileField', 'models.FileField', ([], {'upload_to': '"""change/attachments/"""', 'blank': '(True)'}), "(upload_to='change/attachments/', blank=True)\n", (227, 272), False, 'from django.db import models\n'), ((708, 760), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Project'], {'o... |
# Generated by Django 2.2.12 on 2020-06-11 18:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0002_auto_20200610_1633'),
]
operations = [
migrations.AddField(
model_name='profile',
name='status',
... | [
"django.db.models.CharField"
] | [((334, 378), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(200)'}), '(blank=True, max_length=200)\n', (350, 378), False, 'from django.db import migrations, models\n')] |
from sqlalchemy.inspection import _inspects
from sqlalchemy.orm.base import _inspect_mapped_class
from sqlalchemy.schema import SchemaItem as sSchemaItem
from ming.schema import SchemaItem as mSchemaItem
class InvalidDriver(Exception):
pass
class SameDriverException(InvalidDriver):
pass
def jekyde_inspect... | [
"sqlalchemy.inspection._inspects",
"sqlalchemy.orm.base._inspect_mapped_class"
] | [((332, 346), 'sqlalchemy.inspection._inspects', '_inspects', (['cls'], {}), '(cls)\n', (341, 346), False, 'from sqlalchemy.inspection import _inspects\n'), ((680, 727), 'sqlalchemy.orm.base._inspect_mapped_class', '_inspect_mapped_class', (['cls._models[cls._driver]'], {}), '(cls._models[cls._driver])\n', (701, 727), ... |
#!/usr/bin/python
# _____________________________________________________________________________
# ----------------
# import libraries
# ----------------
# standard libraries
# -----
from itertools import product
from util.launcher import Launcher
from absl import flags, app
from ml_collections.config_flags impor... | [
"absl.app.run",
"ml_collections.config_flags.config_flags.DEFINE_config_file",
"util.launcher.Launcher"
] | [((593, 970), 'util.launcher.Launcher', 'Launcher', ([], {'exp_name': '"""xx1"""', 'python_file': '"""main"""', 'project_name': '"""luna"""', 'base_dir': '"""./save/"""', 'n_exps': 'N_SEEDS', 'joblib_n_jobs': 'JOBLIB_PARALLEL_JOBS', 'n_cores': '(JOBLIB_PARALLEL_JOBS * 1)', 'memory': '(5000)', 'days': '(3)', 'hours': '(... |
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation, rc, patches
import matplotlib.collections as clt
import environment
import scenarios
import trajectory_gen
# Set jshtml default mode for notebook use
rc('animation', html='jshtml')
def plot_one_step(env, x_ref, x_bar, x_opt, x... | [
"matplotlib.rc",
"matplotlib.pyplot.show",
"numpy.arctan2",
"matplotlib.patches.Rectangle",
"matplotlib.pyplot.close",
"trajectory_gen.sample_trajectory",
"numpy.zeros",
"numpy.ones",
"numpy.rad2deg",
"numpy.sin",
"environment.plot_environment",
"environment.Environment",
"numpy.cos",
"mat... | [((242, 272), 'matplotlib.rc', 'rc', (['"""animation"""'], {'html': '"""jshtml"""'}), "('animation', html='jshtml')\n", (244, 272), False, 'from matplotlib import animation, rc, patches\n'), ((436, 487), 'environment.plot_environment', 'environment.plot_environment', (['env'], {'figsize': '(16, 10)'}), '(env, figsize=(... |
from functools import partial
from .io import apply_rules_to_transaction
def apply(rules, transactions):
return list(
map(
partial(
apply_rules_to_transaction,
rules
),
transactions
)
)
def load():
from rules.user impor... | [
"functools.partial"
] | [((150, 192), 'functools.partial', 'partial', (['apply_rules_to_transaction', 'rules'], {}), '(apply_rules_to_transaction, rules)\n', (157, 192), False, 'from functools import partial\n')] |
from turtle import *
import random
speed(0)
class Toile:
def __init__(self):
self.dessineToile()
self.posMouches = []
def dessineToile(self):
tracer(0, 0)
posStart = pos()
for i in range(200):
forward(i / 2)
right(25)
for i in range(... | [
"random.randint"
] | [((518, 543), 'random.randint', 'random.randint', (['(-150)', '(150)'], {}), '(-150, 150)\n', (532, 543), False, 'import random\n'), ((560, 585), 'random.randint', 'random.randint', (['(-200)', '(200)'], {}), '(-200, 200)\n', (574, 585), False, 'import random\n'), ((730, 752), 'random.randint', 'random.randint', (['(0)... |
# /* Copyright (C) 2016 Ion Torrent Systems, Inc. All Rights Reserved */
import pandas as pd
import datetime
import dateutil
import matplotlib.dates as dates
from matplotlib import pyplot as plt
import numpy as np
from time import strptime
import os
# put the date on the same line with the cpu data
os.system("awk 'NR%... | [
"matplotlib.pyplot.subplot",
"os.remove",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.clf",
"pandas.read_csv",
"numpy.datetime64",
"matplotlib.pyplot.legend",
"os.system",
"matplotlib.pyplot.figure",
"time.strptime",
"matplotlib.pyplot.savefig"
] | [((301, 378), 'os.system', 'os.system', (['"""awk \'NR%2{printf "%s ",$0;next;}1\' cpu_util.log > cpu_data.log"""'], {}), '(\'awk \\\'NR%2{printf "%s ",$0;next;}1\\\' cpu_util.log > cpu_data.log\')\n', (310, 378), False, 'import os\n'), ((385, 624), 'pandas.read_csv', 'pd.read_csv', (['"""cpu_data.log"""'], {'names': "... |
from django.conf import settings
from django.db import models
from django.urls import reverse
class BlogPost(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=120, null=True, blank=True)
content = models.TextField(max_length=500... | [
"django.db.models.TextField",
"django.db.models.ForeignKey",
"django.db.models.CharField",
"django.urls.reverse",
"django.db.models.DateTimeField"
] | [((137, 206), 'django.db.models.ForeignKey', 'models.ForeignKey', (['settings.AUTH_USER_MODEL'], {'on_delete': 'models.CASCADE'}), '(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)\n', (154, 206), False, 'from django.db import models\n'), ((219, 274), 'django.db.models.CharField', 'models.CharField', ([], {'max_len... |
# -*- coding: utf-8 -*-
import torch
from model import LatticeLSTM
from load_data import char2idx, idx2char, label2idx, idx2label, word2idx, data_generator
character_size = len(char2idx)
word_size = len(word2idx)
embed_dim = 300
hidden_dim = 128
TEST_DATA_PATH = "./data/test_data" # 测试数据
device = "cuda" if torch.cuda... | [
"torch.load",
"torch.cuda.is_available",
"load_data.data_generator",
"model.LatticeLSTM"
] | [((1248, 1309), 'load_data.data_generator', 'data_generator', (['TEST_DATA_PATH', 'char2idx', 'word2idx', 'label2idx'], {}), '(TEST_DATA_PATH, char2idx, word2idx, label2idx)\n', (1262, 1309), False, 'from load_data import char2idx, idx2char, label2idx, idx2label, word2idx, data_generator\n'), ((310, 335), 'torch.cuda.i... |
# -*- coding: utf-8-*-
import yaml
import logging
import os
from . import dingdangpath
_logger = logging.getLogger(__name__)
_config = {}
def init(config_name='profile.yml'):
# Create config dir if it does not exist yet
if not os.path.exists(dingdangpath.CONFIG_PATH):
try:
os.makedirs(din... | [
"os.makedirs",
"os.path.exists",
"yaml.safe_load",
"os.access",
"logging.getLogger"
] | [((98, 125), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (115, 125), False, 'import logging\n'), ((238, 278), 'os.path.exists', 'os.path.exists', (['dingdangpath.CONFIG_PATH'], {}), '(dingdangpath.CONFIG_PATH)\n', (252, 278), False, 'import os\n'), ((565, 609), 'os.access', 'os.access'... |
import json
import requests
import helpers
BOOK_TITLE = "Physically Based Rendering: From Theory to Implementation, Third Edition"
BOOK_TITLE2 = BOOK_TITLE + "a"
BOOK_AUTHOR = "<NAME>, <NAME>, <NAME>"
def test_book_lifecycle(http_session, base_url):
# CREATE
r = http_session.post(base_url + "/api/v1/books", d... | [
"helpers.assert_in_listing",
"json.dumps"
] | [((858, 930), 'helpers.assert_in_listing', 'helpers.assert_in_listing', (['base_url', '"""/api/v1/books"""', "book['data']['id']"], {}), "(base_url, '/api/v1/books', book['data']['id'])\n", (883, 930), False, 'import helpers\n'), ((324, 426), 'json.dumps', 'json.dumps', (["{'data': {'type': 'book', 'attributes': {'titl... |
from aoc import AOC
aoc = AOC(year=2018, day=13)
data = aoc.load()
path_ids = set(["|", "-"])
curve_ids = set(["\\", "/"])
intersection_ids = set(["+"])
cart_ids = set(["<", ">", "^", "v"])
paths = {}
carts = {}
cart_last_turn = {}
y = 0
next_cart_id = 0
for line in data.lines():
for index, c in enumerate(lin... | [
"aoc.AOC"
] | [((28, 50), 'aoc.AOC', 'AOC', ([], {'year': '(2018)', 'day': '(13)'}), '(year=2018, day=13)\n', (31, 50), False, 'from aoc import AOC\n')] |
# Author: <NAME>
# Version: 0.1
# Date: 22th November 2021
import pywhatkit as pw
txt =""" What is Lorem Ipsum?
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
when an unknown printer took a galley of type ... | [
"pywhatkit.text_to_handwriting"
] | [((762, 789), 'pywhatkit.text_to_handwriting', 'pw.text_to_handwriting', (['txt'], {}), '(txt)\n', (784, 789), True, 'import pywhatkit as pw\n')] |
import os
import h5py
import numpy as np
import pickle as pkl
import tensorflow as tf
from tqdm import tqdm
from gcn.train import train_model
from gcn.utils import load_data_pkl, load_data_h5
# Set random seed
seed = 123
np.random.seed(seed)
tf.set_random_seed(seed)
# Settings
flags = tf.app.flags
FLAGS = flags.FLAG... | [
"os.mkdir",
"pickle.dump",
"numpy.random.seed",
"gcn.utils.load_data_h5",
"gcn.train.train_model",
"gcn.utils.load_data_pkl",
"os.path.exists",
"tensorflow.set_random_seed",
"os.path.join",
"os.listdir"
] | [((223, 243), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (237, 243), True, 'import numpy as np\n'), ((244, 268), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['seed'], {}), '(seed)\n', (262, 268), True, 'import tensorflow as tf\n'), ((1179, 1209), 'os.path.exists', 'os.path.exists', (['F... |
# (c) 2019, NetApp, Inc
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
''' unit tests ONTAP Ansible module: '''
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
import pytest
import sys
from ansible.module_utils import b... | [
"ansible_collections.netapp.aws.tests.unit.compat.mock.patch",
"ansible_collections.netapp.aws.plugins.modules.aws_netapp_cvs_active_directory.AwsCvsNetappActiveDir",
"json.dumps",
"ansible_collections.netapp.aws.tests.unit.compat.mock.patch.multiple",
"pytest.raises",
"pytest.mark.skip",
"ansible.modul... | [((813, 891), 'pytest.mark.skip', 'pytest.mark.skip', (['"""Skipping Unit Tests on 2.6 as requests is not be available"""'], {}), "('Skipping Unit Tests on 2.6 as requests is not be available')\n", (829, 891), False, 'import pytest\n'), ((1014, 1055), 'json.dumps', 'json.dumps', (["{'ANSIBLE_MODULE_ARGS': args}"], {}),... |
#####################################################
#
# Train and test a restricted Boltzmann machine
#
# Copyright (c) 2018 christianb93
# Permission is hereby granted, free of charge, to
# any person obtaining a copy of this software and
# associated documentation files (the "Software"),
# to deal in the Softwar... | [
"pickle.dump",
"argparse.ArgumentParser",
"numpy.ones",
"matplotlib.pyplot.figure",
"pickle.load",
"numpy.random.randint",
"os.path.join",
"numpy.copy",
"numpy.transpose",
"os.path.exists",
"socket.gethostname",
"tempfile.mktemp",
"time.localtime",
"matplotlib.pyplot.show",
"numpy.concat... | [((10345, 10356), 'time.time', 'time.time', ([], {}), '()\n', (10354, 10356), False, 'import time\n'), ((11189, 11200), 'time.time', 'time.time', ([], {}), '()\n', (11198, 11200), False, 'import time\n'), ((15172, 15182), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (15180, 15182), True, 'import matplotlib.p... |
# import sqlite3
from flask import Flask, request, send_from_directory
from .utils import (
build_sql_filter,
get_project_strata,
get_sam_eff_spc_grps,
run_query,
get_substring_sql,
# get_strata_filter_sql,
get_where_sql,
get_field_names,
sort_fields,
)
api = Flask(__name__, static... | [
"flask.send_from_directory",
"flask.Flask"
] | [((298, 372), 'flask.Flask', 'Flask', (['__name__'], {'static_folder': '"""build"""', 'static_url_path': '"""/fish_arc_viewer"""'}), "(__name__, static_folder='build', static_url_path='/fish_arc_viewer')\n", (303, 372), False, 'from flask import Flask, request, send_from_directory\n'), ((15209, 15261), 'flask.send_from... |
import pathlib
from karton.core import Resource, Task
tests_dir = pathlib.Path(__file__).parent
def mock_resource(filename: str, with_name=False) -> Resource:
filepath = tests_dir / "testdata" / filename
return Resource(
filename if with_name else "file", filepath.read_bytes(), sha256="sha256"
)... | [
"karton.core.Task",
"pathlib.Path"
] | [((68, 90), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (80, 90), False, 'import pathlib\n'), ((377, 416), 'karton.core.Task', 'Task', (["{'type': 'sample', 'kind': 'raw'}"], {}), "({'type': 'sample', 'kind': 'raw'})\n", (381, 416), False, 'from karton.core import Resource, Task\n')] |
from crar.utils import compute_eps
class TestEps:
def test_constant_eps(self):
actual = [
compute_eps(k, eps_start=0.5, eps_end=0.5, eps_last_frame=k * 10)
for k in range(10, 5000, 100)
]
expected = [0.5] * len(actual)
assert actual == expected
| [
"crar.utils.compute_eps"
] | [((116, 181), 'crar.utils.compute_eps', 'compute_eps', (['k'], {'eps_start': '(0.5)', 'eps_end': '(0.5)', 'eps_last_frame': '(k * 10)'}), '(k, eps_start=0.5, eps_end=0.5, eps_last_frame=k * 10)\n', (127, 181), False, 'from crar.utils import compute_eps\n')] |
import torch
import torch.nn as nn
from overrides import overrides
from services.arguments.arguments_service_base import ArgumentsServiceBase
from losses.sequence_loss import SequenceLoss
class TransformerSequenceLoss(SequenceLoss):
def __init__(self):
super().__init__()
self._criterion = nn.Cros... | [
"torch.nn.CrossEntropyLoss"
] | [((313, 348), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {'ignore_index': '(0)'}), '(ignore_index=0)\n', (332, 348), True, 'import torch.nn as nn\n')] |
from db_handler.models.crypto_raw import CryptoRaw
class DfToCryptoRawMap:
def __init__(self) -> None:
pass
def create_list_from_df(self, df, process_id):
crypto_records = []
for index, row in df.iterrows():
crypto_records.append(self.__row_to_crypto_raw(row, process_id))
... | [
"db_handler.models.crypto_raw.CryptoRaw"
] | [((419, 2048), 'db_handler.models.crypto_raw.CryptoRaw', 'CryptoRaw', ([], {'tcr_symbol_name': "row['symbol']", 'tcr_status': "row['status']", 'tcr_baseAsset': "row['baseAsset']", 'tcr_baseAssetPrecision': "row['baseAssetPrecision']", 'tcr_quoteAsset': "row['quoteAsset']", 'tcr_quotePrecision': "row['quotePrecision']",... |
from flask import Blueprint
from flask_restplus import abort
from .errors import BadRequest
def add_error_handlers(bp: Blueprint) -> None:
@bp.errorhandler(BadRequest)
def handle_bad_request(error: BadRequest) -> None:
payload = error.payload or {}
abort(error.status, error.message, **payload... | [
"flask_restplus.abort"
] | [((276, 321), 'flask_restplus.abort', 'abort', (['error.status', 'error.message'], {}), '(error.status, error.message, **payload)\n', (281, 321), False, 'from flask_restplus import abort\n')] |
import logging
import gunicorn.glogging
LOG_FORMAT = "%(asctime)s | %(levelname)s | %(name)s | %(module)s | %(lineno)d | %(process)d | %(message)s"
class Logger(gunicorn.glogging.Logger):
error_fmt = LOG_FORMAT
def setup(self, cfg):
super().setup(cfg)
# Make sure the gunicorn master proces... | [
"logging.Formatter"
] | [((406, 439), 'logging.Formatter', 'logging.Formatter', ([], {'fmt': 'LOG_FORMAT'}), '(fmt=LOG_FORMAT)\n', (423, 439), False, 'import logging\n')] |
import tempfile
import os
from pathlib import Path
from common.document_parser.cli import pdf_to_json
from common.tests import PACKAGE_OCR_PDF_PATH
import json
import pytest
import shutil
from dev_tools import REPO_PATH
ORIGINAL_TEST_FILES = dict(
ocr_pdf_file=os.path.join(REPO_PATH,
... | [
"common.document_parser.cli.pdf_to_json",
"json.load",
"pytest.fixture",
"os.path.join",
"shutil.copy"
] | [((1061, 1093), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (1075, 1093), False, 'import pytest\n'), ((1161, 1193), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (1175, 1193), False, 'import pytest\n'), ((1401, 1433), 'p... |
# -*- coding: UTF-8 -*-
"""
Created on Sat Jan 20 10:20:33 2018
@author: <NAME>
"""
import os, re, csv, time, warnings, threading
from pymongo import MongoClient
import pandas as pd
import numpy as np
from scipy.sparse import csr_matrix
from bson.objectid import ObjectId
import Text_Analysis.text_proces... | [
"pymongo.MongoClient",
"pandas.DataFrame",
"sklearn.externals.joblib.dump",
"sklearn.ensemble.RandomForestClassifier",
"os.makedirs",
"bson.objectid.ObjectId",
"warnings.filterwarnings",
"os.getcwd",
"sklearn.svm.SVC",
"os.path.exists",
"sklearn.metrics.classification_report",
"sklearn.externa... | [((665, 755), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'sklearn.exceptions.UndefinedMetricWarning'}), "('ignore', category=sklearn.exceptions.\n UndefinedMetricWarning)\n", (688, 755), False, 'import os, re, csv, time, warnings, threading\n'), ((752, 821), 'warnings.filte... |
from dash import dcc, html, Input, Output, callback, dash_table
import dash_bootstrap_components as dbc
import plotly.express as px
import pandas as pd
import numpy as np
from pages.sas_key import get_df_description
from pages.style import PADDING_STYLE
TEXT_STYLE = {
'textAlign':'center',
'width': '70%',
... | [
"pandas.DataFrame",
"dash.Output",
"numpy.median",
"dash.html.Div",
"dash.dash_table.DataTable",
"dash.dcc.Graph",
"dash.html.P",
"dash.html.H1",
"pages.sas_key.get_df_description",
"dash.Input",
"plotly.express.histogram",
"dash.html.Hr",
"dash.html.H5",
"dash.html.H3"
] | [((8370, 8413), 'dash.Output', 'Output', (['"""factssubredditprinter"""', '"""children"""'], {}), "('factssubredditprinter', 'children')\n", (8376, 8413), False, 'from dash import dcc, html, Input, Output, callback, dash_table\n'), ((8419, 8461), 'dash.Output', 'Output', (['"""subredditdescription"""', '"""children"""'... |
import numpy as np
f8 = np.float64()
i8 = np.int64()
u8 = np.uint64()
f4 = np.float32()
i4 = np.int32()
u4 = np.uint32()
td = np.timedelta64(0, "D")
b_ = np.bool_()
b = bool()
f = float()
i = int()
AR = np.array([1], dtype=np.bool_)
AR.setflags(write=False)
AR2 = np.array([1], dtype=np.timedelta64)
AR2.setflags(w... | [
"numpy.uint32",
"numpy.bool_",
"numpy.uint64",
"numpy.float32",
"numpy.timedelta64",
"numpy.array",
"numpy.int32",
"numpy.int64",
"numpy.float64"
] | [((25, 37), 'numpy.float64', 'np.float64', ([], {}), '()\n', (35, 37), True, 'import numpy as np\n'), ((43, 53), 'numpy.int64', 'np.int64', ([], {}), '()\n', (51, 53), True, 'import numpy as np\n'), ((59, 70), 'numpy.uint64', 'np.uint64', ([], {}), '()\n', (68, 70), True, 'import numpy as np\n'), ((77, 89), 'numpy.floa... |