code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
"""Support for CO2 sensor connected to a serial port."""
import logging
from datetime import timedelta
import voluptuous as vol
from homeassistant.const import (
ATTR_TEMPERATURE, CONF_NAME, CONF_MONITORED_CONDITIONS, TEMP_FAHRENHEIT)
from homeassistant.helpers.entity import Entity
import homeassistant.helpers.co... | [
"voluptuous.Optional",
"homeassistant.util.temperature.celsius_to_fahrenheit",
"voluptuous.Required",
"datetime.timedelta",
"homeassistant.util.Throttle",
"voluptuous.In",
"logging.getLogger"
] | [((518, 545), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (535, 545), False, 'import logging\n'), ((611, 632), 'datetime.timedelta', 'timedelta', ([], {'seconds': '(10)'}), '(seconds=10)\n', (620, 632), False, 'from datetime import timedelta\n'), ((3965, 3999), 'homeassistant.util.Thro... |
# Generated by Django 3.1 on 2020-09-08 09:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('package', '0003_auto_20200828_1838'),
]
operations = [
migrations.AlterField(
model_name='gaduurpackage',
... | [
"django.db.models.TextField"
] | [((363, 417), 'django.db.models.TextField', 'models.TextField', ([], {'blank': '(True)', 'max_length': '(10)', 'null': '(True)'}), '(blank=True, max_length=10, null=True)\n', (379, 417), False, 'from django.db import migrations, models\n')] |
#!/opt/anaconda3/envs/py37/bin/python
import numpy as np
import twd97
import sys
from cntr_kml import cntr_kml
from pyproj import Proj
import rasterio
fname = sys.argv[1]
img = rasterio.open(fname)
data=np.flip(img.read()[0,:,:],[0])
l,b,r,t=img.bounds[:]
LL=False
if (l+r)/2==img.lnglat()[0]:LL=True
x0,y0=img.xy(0,0)
... | [
"rasterio.open",
"numpy.meshgrid",
"cntr_kml.cntr_kml",
"twd97.towgs84",
"pyproj.Proj"
] | [((178, 198), 'rasterio.open', 'rasterio.open', (['fname'], {}), '(fname)\n', (191, 198), False, 'import rasterio\n'), ((855, 886), 'cntr_kml.cntr_kml', 'cntr_kml', (['data', 'lon', 'lat', 'fname'], {}), '(data, lon, lat, fname)\n', (863, 886), False, 'from cntr_kml import cntr_kml\n'), ((489, 506), 'numpy.meshgrid', '... |
import datetime
import json
import re
from tests.base import SoupTest
from pretix.base.models import Event, Organizer, Team, User
class MailSettingPreviewTest(SoupTest):
def setUp(self):
self.user = User.objects.create_user('<EMAIL>', 'dummy')
self.orga1 = Organizer.objects.create(name='CCC', sl... | [
"re.match",
"pretix.base.models.User.objects.create_user",
"datetime.datetime",
"pretix.base.models.Team.objects.create",
"pretix.base.models.Organizer.objects.create"
] | [((215, 259), 'pretix.base.models.User.objects.create_user', 'User.objects.create_user', (['"""<EMAIL>"""', '"""dummy"""'], {}), "('<EMAIL>', 'dummy')\n", (239, 259), False, 'from pretix.base.models import Event, Organizer, Team, User\n'), ((281, 329), 'pretix.base.models.Organizer.objects.create', 'Organizer.objects.c... |
""" hyperparam search! :)
"""
from ray.tune.schedulers import ASHAScheduler
from ray.tune import CLIReporter
from ray import tune
import numpy as np
from functools import partial
import music_trees as mt
SEEDS = [mt.SEED]
RANDOM_TAXONOMIES = [f'random-taxonomy-{i}' for i in range(10)]
SCRAMBLED_TAXONOMIES = [
f... | [
"argparse.Namespace",
"music_trees.train.train",
"argparse.ArgumentParser",
"ray.tune.CLIReporter",
"ray.tune.grid_search",
"ray.tune.schedulers.ASHAScheduler",
"music_trees.train.get_exp_dir",
"datetime.datetime.now"
] | [((2564, 2592), 'argparse.Namespace', 'argparse.Namespace', ([], {}), '(**kwargs)\n', (2582, 2592), False, 'import argparse\n'), ((2933, 2970), 'music_trees.train.train', 'mt.train.train', (['hparams'], {'use_ray': '(True)'}), '(hparams, use_ray=True)\n', (2947, 2970), True, 'import music_trees as mt\n'), ((3015, 3156)... |
'''Main tests in API'''
import unittest
from bokeh.plotting import figure
from model.charts.line import Line
class LineChartConfigTest():
# class LineChartConfigTest(unittest.TestCase):
''' Test behaviours linked to foundational bar charts capabilities '''
def test_bar_chart_config_no_option(self):
'''... | [
"model.charts.line.Line",
"bokeh.plotting.figure"
] | [((416, 424), 'bokeh.plotting.figure', 'figure', ([], {}), '()\n', (422, 424), False, 'from bokeh.plotting import figure\n'), ((703, 711), 'bokeh.plotting.figure', 'figure', ([], {}), '()\n', (709, 711), False, 'from bokeh.plotting import figure\n'), ((985, 993), 'bokeh.plotting.figure', 'figure', ([], {}), '()\n', (99... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import flt
from frappe.utils import formatdate
from erpnext.controllers.trends import get_period_da... | [
"frappe.utils.flt",
"frappe.utils.formatdate",
"erpnext.controllers.trends.get_period_date_ranges",
"frappe.db.sql",
"frappe.db.get_value",
"datetime.date",
"erpnext.controllers.trends.get_period_month_ranges",
"frappe._dict",
"frappe._"
] | [((511, 577), 'erpnext.controllers.trends.get_period_month_ranges', 'get_period_month_ranges', (["filters['period']", "filters['fiscal_year']"], {}), "(filters['period'], filters['fiscal_year'])\n", (534, 577), False, 'from erpnext.controllers.trends import get_period_date_ranges, get_period_month_ranges\n'), ((1632, 1... |
import os
import sys
import speedtest
import pyfiglet
os.system("clear")
banner = pyfiglet.figlet_format("WifiSpeedTester", font="slant" )
print (banner)
print (" Author : <NAME>(rkt)")
print (" Github : https://github.com/r3k4t")
st = speedtest.Speedtest()
optio... | [
"speedtest.Speedtest",
"os.system",
"pyfiglet.figlet_format"
] | [((59, 77), 'os.system', 'os.system', (['"""clear"""'], {}), "('clear')\n", (68, 77), False, 'import os\n'), ((88, 143), 'pyfiglet.figlet_format', 'pyfiglet.figlet_format', (['"""WifiSpeedTester"""'], {'font': '"""slant"""'}), "('WifiSpeedTester', font='slant')\n", (110, 143), False, 'import pyfiglet\n'), ((289, 310), ... |
import numpy
from sympy import Rational as frac
from sympy import pi, sqrt
from ..helpers import article, fsd, pm, untangle
from ._helpers import Enr2Scheme
citation = article(
authors=["<NAME>", "<NAME>"],
title="Approximate integration formulas for certain spherically symmetric regions",
journal="Math. ... | [
"numpy.full",
"sympy.sqrt",
"sympy.Rational"
] | [((1252, 1266), 'sympy.Rational', 'frac', (['(2)', '(n + 2)'], {}), '(2, n + 2)\n', (1256, 1266), True, 'from sympy import Rational as frac\n'), ((1275, 1304), 'sympy.Rational', 'frac', (['(4 - n)', '(2 * (n + 2) ** 2)'], {}), '(4 - n, 2 * (n + 2) ** 2)\n', (1279, 1304), True, 'from sympy import Rational as frac\n'), (... |
#!/usr/bin/env python3
# Copyright 2010-2021 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | [
"ortools.sat.python.cp_model.CpSolverSolutionCallback.__init__",
"ortools.sat.python.cp_model.CpSolver",
"ortools.sat.python.cp_model.CpModel"
] | [((2301, 2319), 'ortools.sat.python.cp_model.CpModel', 'cp_model.CpModel', ([], {}), '()\n', (2317, 2319), False, 'from ortools.sat.python import cp_model\n'), ((4108, 4127), 'ortools.sat.python.cp_model.CpSolver', 'cp_model.CpSolver', ([], {}), '()\n', (4125, 4127), False, 'from ortools.sat.python import cp_model\n'),... |
import os
import time
import copy
import torch
import matplotlib
import torchvision
import torch.nn as nn
import numpy as np
import torch.optim as optim
import matplotlib.pyplot as plt
from pathlib import Path
from torch.optim import lr_scheduler
from tor... | [
"matplotlib.pyplot.title",
"torch.optim.lr_scheduler.StepLR",
"torchvision.transforms.RandomHorizontalFlip",
"models.trainer_class.TrainModel",
"matplotlib.pyplot.imshow",
"torchvision.transforms.Normalize",
"torch.nn.CrossEntropyLoss",
"numpy.clip",
"pathlib.Path",
"torchvision.transforms.CenterC... | [((657, 681), 'numpy.clip', 'np.clip', (['gridInput', '(0)', '(1)'], {}), '(gridInput, 0, 1)\n', (664, 681), True, 'import numpy as np\n'), ((692, 713), 'matplotlib.pyplot.imshow', 'plt.imshow', (['gridInput'], {}), '(gridInput)\n', (702, 713), True, 'import matplotlib.pyplot as plt\n'), ((718, 734), 'matplotlib.pyplot... |
import colorsys
import copy
import os
import time
import numpy as np
import torch
from PIL import Image, ImageDraw, ImageFont
from nets.frcnn import FasterRCNN
from utils.utils import DecodeBox, get_new_img_size
#--------------------------------------------#
# 使用自己训练好的模型预测需要修改2个参数
# model_path和classes_path都需要修改... | [
"copy.deepcopy",
"colorsys.hsv_to_rgb",
"torch.load",
"numpy.asarray",
"numpy.floor",
"utils.utils.get_new_img_size",
"utils.utils.DecodeBox",
"time.time",
"numpy.shape",
"torch.Tensor",
"numpy.array",
"nets.frcnn.FasterRCNN",
"torch.cuda.is_available",
"PIL.ImageDraw.Draw",
"torch.no_gr... | [((1528, 1576), 'utils.utils.DecodeBox', 'DecodeBox', (['self.std', 'self.mean', 'self.num_classes'], {}), '(self.std, self.mean, self.num_classes)\n', (1537, 1576), False, 'from utils.utils import DecodeBox, get_new_img_size\n'), ((1759, 1796), 'os.path.expanduser', 'os.path.expanduser', (['self.classes_path'], {}), '... |
# Added ICP, and also demonstrated multichannel
import pprint
import nidaqmx
from nidaqmx.constants import (
Edge, TriggerType, AcquisitionType, LineGrouping, Level, TaskMode)
pp = pprint.PrettyPrinter(indent=4)
sample_rate = 1000
number_of_samples = 1000
samp_clk_terminal = ""
task = nidaqmx.Task()
task2 = nida... | [
"nidaqmx.Task",
"pprint.PrettyPrinter"
] | [((186, 216), 'pprint.PrettyPrinter', 'pprint.PrettyPrinter', ([], {'indent': '(4)'}), '(indent=4)\n', (206, 216), False, 'import pprint\n'), ((293, 307), 'nidaqmx.Task', 'nidaqmx.Task', ([], {}), '()\n', (305, 307), False, 'import nidaqmx\n'), ((316, 330), 'nidaqmx.Task', 'nidaqmx.Task', ([], {}), '()\n', (328, 330), ... |
import os
version_info = (0, 22, 0)
__version__ = '.'.join(map(str, version_info))
# This is to make Debian packaging easier, it ignores import
# errors of greenlet so that the packager can still at least
# access the version. Also this makes easy_install a little quieter
if os.environ.get('EVENTLET_IMPORT_VERSION_O... | [
"os.environ.get",
"eventlet.support.wrap_deprecated"
] | [((279, 325), 'os.environ.get', 'os.environ.get', (['"""EVENTLET_IMPORT_VERSION_ONLY"""'], {}), "('EVENTLET_IMPORT_VERSION_ONLY')\n", (293, 325), False, 'import os\n'), ((1931, 1964), 'eventlet.support.wrap_deprecated', 'support.wrap_deprecated', (['old', 'new'], {}), '(old, new)\n', (1954, 1964), False, 'from eventlet... |
from copy import copy
from typing import Optional
import numpy as np
import pandas as pd
from fedot.core.log import Log, default_log
from fedot.core.repository.tasks import Task, TaskTypesEnum
NAME_CLASS_STR = "<class 'str'>"
NAME_CLASS_INT = "<class 'int'>"
NAME_CLASS_FLOAT = "<class 'float'>"
NAME_CLASS_NONE = "<c... | [
"copy.copy",
"numpy.isnan",
"numpy.array",
"pandas.Series",
"numpy.argwhere",
"fedot.core.log.default_log",
"numpy.delete",
"pandas.to_numeric"
] | [((3397, 3451), 'copy.copy', 'copy', (["data.supplementary_data.column_types['features']"], {}), "(data.supplementary_data.column_types['features'])\n", (3401, 3451), False, 'from copy import copy\n'), ((3480, 3532), 'copy.copy', 'copy', (["data.supplementary_data.column_types['target']"], {}), "(data.supplementary_dat... |
"""rv_bis_corr.
Author: <NAME>
Calculate and plot RV vs BIS correlation
"""
import numpy as np
import statsmodels.api as sm
from scipy.stats import pearsonr
import scipy.stats as st
import matplotlib.pyplot as plt
def rv_bis_corr(data, confidence=0.05, name='last'):
"""Calculate RV vs BIS correlation and plot ... | [
"numpy.concatenate",
"statsmodels.api.OLS",
"numpy.power",
"matplotlib.pyplot.legend",
"scipy.stats.pearsonr",
"numpy.array",
"numpy.linspace",
"statsmodels.api.add_constant",
"scipy.stats.t.ppf",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig"
] | [((716, 728), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (724, 728), True, 'import numpy as np\n'), ((737, 749), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (745, 749), True, 'import numpy as np\n'), ((1048, 1062), 'scipy.stats.pearsonr', 'pearsonr', (['x', 'y'], {}), '(x, y)\n', (1056, 1062), False, 'fr... |
# -*- coding: utf-8 -*-
import logging
from .input_validation import validate_cfg
from .run import run_instance
logger = logging.getLogger(__name__)
import multiprocessing as mp
"""Main module."""
def create_dicom(cfg, pools=-1):
"""
Main function for creating DICOM files
:param cfg: dictionary contain... | [
"multiprocessing.cpu_count",
"logging.getLogger",
"multiprocessing.Pool"
] | [((123, 150), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (140, 150), False, 'import logging\n'), ((723, 737), 'multiprocessing.Pool', 'mp.Pool', (['pools'], {}), '(pools)\n', (730, 737), True, 'import multiprocessing as mp\n'), ((629, 643), 'multiprocessing.cpu_count', 'mp.cpu_count',... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
import os
import sys
import json
import argparse
import datetime
import subprocess
# In[ ]:
CONFIG = '/mnt/data/script/config.json'
DUMP = 'pg_dump -O -f {0}'
RESTORE = 'psql -f {0}'
GZIP = 'gzip -f {0}'
GUNZIP = 'gzip -df {0}'
COPY = 'cp -f {0} {1}'
# In[ ]:
de... | [
"os.remove",
"json.load",
"argparse.ArgumentParser",
"datetime.datetime.now",
"os.path.join",
"os.listdir"
] | [((581, 608), 'os.listdir', 'os.listdir', (["param['folder']"], {}), "(param['folder'])\n", (591, 608), False, 'import os\n'), ((833, 918), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Utility to dump/restore postgres database"""'}), "(description='Utility to dump/restore postgres data... |
import setuptools
with open("readME.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="sortdict",
version="0.0.1",
author="<NAME>",
author_email="<EMAIL>",
description="This library is to sort dictionary list given to corresponding keys",
long_description="This packages ... | [
"setuptools.find_packages"
] | [((472, 498), 'setuptools.find_packages', 'setuptools.find_packages', ([], {}), '()\n', (496, 498), False, 'import setuptools\n')] |
"""Test utilities."""
import pickle
import ibis
import ibis.util as util
def assert_equal(left, right):
"""Assert that two ibis objects are equal."""
if util.all_of([left, right], ibis.Schema):
assert left.equals(right), 'Comparing schemas: \n{!r} !=\n{!r}'.format(
left, right
)... | [
"ibis.util.all_of",
"pickle.dumps"
] | [((166, 205), 'ibis.util.all_of', 'util.all_of', (['[left, right]', 'ibis.Schema'], {}), '([left, right], ibis.Schema)\n', (177, 205), True, 'import ibis.util as util\n'), ((601, 618), 'pickle.dumps', 'pickle.dumps', (['obj'], {}), '(obj)\n', (613, 618), False, 'import pickle\n')] |
import torch
import functools
from torch.optim import Adam
from torch.utils.data import DataLoader
import torchvision.transforms as transforms
from torchvision.datasets import MNIST
import tqdm
import numpy as np
from .model import ScoreNet
# @title Set up the SDE
device = None
def marginal_prob_std(t, sigma):
... | [
"functools.partial",
"torch.ones",
"tqdm.tqdm",
"numpy.log",
"torch.randn_like",
"tqdm.trange",
"torch.sqrt",
"torch.randn",
"torch.rand",
"torch.linspace",
"torch.no_grad",
"torch.sum",
"torch.tensor"
] | [((981, 1030), 'functools.partial', 'functools.partial', (['marginal_prob_std'], {'sigma': 'sigma'}), '(marginal_prob_std, sigma=sigma)\n', (998, 1030), False, 'import functools\n'), ((1052, 1099), 'functools.partial', 'functools.partial', (['diffusion_coeff'], {'sigma': 'sigma'}), '(diffusion_coeff, sigma=sigma)\n', (... |
from testlauncher import log_run
def setup_package():
log_run("Inside testlauncher.grouping.setup_package")
def teardown_package():
log_run("Inside testlauncher.grouping.teardown_package")
| [
"testlauncher.log_run"
] | [((59, 112), 'testlauncher.log_run', 'log_run', (['"""Inside testlauncher.grouping.setup_package"""'], {}), "('Inside testlauncher.grouping.setup_package')\n", (66, 112), False, 'from testlauncher import log_run\n'), ((142, 198), 'testlauncher.log_run', 'log_run', (['"""Inside testlauncher.grouping.teardown_package"""'... |
# Copyright 2021 The Flax Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | [
"jax.config.parse_flags_with_absl",
"absl.testing.absltest.main",
"jax.config.enable_omnistaging"
] | [((865, 899), 'jax.config.parse_flags_with_absl', 'jax.config.parse_flags_with_absl', ([], {}), '()\n', (897, 899), False, 'import jax\n'), ((932, 963), 'jax.config.enable_omnistaging', 'jax.config.enable_omnistaging', ([], {}), '()\n', (961, 963), False, 'import jax\n'), ((2452, 2467), 'absl.testing.absltest.main', 'a... |
import boto3
import os
os.environ['AWS_SHARED_CREDENTIALS_FILE'] = './AWS.txt'
s3 = boto3.Session(profile_name='default').client('s3')
for i in range(1, 16):
s3.download_file(Bucket='acmilannesta', Key='model-oof-'+str(i+1)+'.h5', Filename='/wdata/model-oof-'+str(i+1)+'.h5')
| [
"boto3.Session"
] | [((89, 126), 'boto3.Session', 'boto3.Session', ([], {'profile_name': '"""default"""'}), "(profile_name='default')\n", (102, 126), False, 'import boto3\n')] |
# coding: utf-8
import gzip
import io
import six
import mock
import cherrypy
from cherrypy._cpcompat import IncompleteRead, ntob, ntou
europoundUnicode = ntou('£', encoding='utf-8')
sing = ntou("毛泽东: Sing, Little Birdie?", encoding='utf-8')
sing8 = sing.encode('utf-8')
sing16 = sing.encode('utf-16')
from cherry... | [
"io.BytesIO",
"cherrypy.request.params.items",
"cherrypy._cpcompat.ntob",
"mock.patch",
"cherrypy.tree.mount",
"gzip.GzipFile",
"cherrypy.config",
"cherrypy._cpcompat.ntou"
] | [((159, 186), 'cherrypy._cpcompat.ntou', 'ntou', (['"""£"""'], {'encoding': '"""utf-8"""'}), "('£', encoding='utf-8')\n", (163, 186), False, 'from cherrypy._cpcompat import IncompleteRead, ntob, ntou\n'), ((194, 245), 'cherrypy._cpcompat.ntou', 'ntou', (['"""毛泽东: Sing, Little Birdie?"""'], {'encoding': '"""utf-8"""'}),... |
import json
from apistar import test
from app import app
from restpass import redisclient
client = test.TestClient(app)
test_id = {'login': '<EMAIL>', 'password': '<PASSWORD>'}
password_slug = '?p=password<PASSWORD>'
def test_get_ids_list():
redisclient.set_id('test_id', json.dumps(test_id))
response = clien... | [
"apistar.test.TestClient",
"restpass.redisclient.get_id",
"restpass.redisclient.delete_id",
"json.dumps"
] | [((100, 120), 'apistar.test.TestClient', 'test.TestClient', (['app'], {}), '(app)\n', (115, 120), False, 'from apistar import test\n'), ((446, 478), 'restpass.redisclient.delete_id', 'redisclient.delete_id', (['"""test_id"""'], {}), "('test_id')\n", (467, 478), False, 'from restpass import redisclient\n'), ((727, 759),... |
from __future__ import absolute_import
from typing import Any, Callable, Dict, List, Optional, Set, Tuple
from sklearn.feature_extraction.text import VectorizerMixin # type: ignore
from sklearn.pipeline import FeatureUnion # type: ignore
from eli5.base import (
DocWeightedSpans, WeightedSpans, FeatureWeights, F... | [
"eli5.base.FeatureWeights",
"eli5.sklearn._span_analyzers.build_span_analyzer"
] | [((2315, 2344), 'eli5.sklearn._span_analyzers.build_span_analyzer', 'build_span_analyzer', (['doc', 'vec'], {}), '(doc, vec)\n', (2334, 2344), False, 'from eli5.sklearn._span_analyzers import build_span_analyzer\n'), ((6158, 6370), 'eli5.base.FeatureWeights', 'FeatureWeights', ([], {'pos': '[fw for fw in other_items if... |
import pandas as pd
import json
POSITIVE_DETAIL_DATA_PATH = 'data/2019-ncov-japan/Data/positiveDetail.csv'
OUTPUT_JSON_PATH = 'data/created_json/positive_detail.json'
def create_json_file():
header = ('id', 'announcement_date', 'diagnosis_date', 'prefecture', 'residence_prefecture',
'age', 'gender'... | [
"pandas.read_csv"
] | [((555, 625), 'pandas.read_csv', 'pd.read_csv', (['POSITIVE_DETAIL_DATA_PATH'], {'names': 'header', 'encoding': '"""utf-8"""'}), "(POSITIVE_DETAIL_DATA_PATH, names=header, encoding='utf-8')\n", (566, 625), True, 'import pandas as pd\n')] |
from __future__ import absolute_import
import argparse
import os
import logging
import mimetypes
from six import text_type
import apache_beam as beam
from apache_beam.options.pipeline_options import PipelineOptions, SetupOptions
from apache_beam.metrics.metric import Metrics
from sciencebeam_gym.utils.collection im... | [
"sciencebeam_gym.preprocess.preprocessing_utils.get_output_file",
"sciencebeam_gym.beam_utils.main.add_cloud_args",
"argparse.ArgumentParser",
"logging.basicConfig",
"os.path.basename",
"sciencebeam_gym.beam_utils.utils.PreventFusion",
"sciencebeam_gym.beam_utils.main.process_sciencebeam_gym_dep_args",
... | [((1029, 1056), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1046, 1056), False, 'import logging\n'), ((1085, 1112), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1102, 1112), False, 'import logging\n'), ((6019, 6044), 'argparse.ArgumentParser', 'argpar... |
from decimal import Decimal
def test_break_test(get_contract_with_gas_estimation):
break_test = """
@public
def log(n: decimal) -> int128:
c: decimal = n * 1.0
output: int128 = 0
for i in range(400):
c = c / 1.2589
if c < 1.0:
output = i
break
return output
... | [
"decimal.Decimal"
] | [((400, 412), 'decimal.Decimal', 'Decimal', (['"""1"""'], {}), "('1')\n", (407, 412), False, 'from decimal import Decimal\n'), ((436, 448), 'decimal.Decimal', 'Decimal', (['"""2"""'], {}), "('2')\n", (443, 448), False, 'from decimal import Decimal\n'), ((472, 485), 'decimal.Decimal', 'Decimal', (['"""10"""'], {}), "('1... |
# SPDX-License-Identifier: MIT
# Copyright (c) 2019 Intel Corporation
import os
import io
import json
import shutil
import random
import tempfile
import contextlib
from pathlib import Path
from unittest.mock import patch
from typing import List, AsyncIterator, Dict
from dffml.record import Record
from dffml.feature im... | [
"os.unlink",
"dffml.cli.list.List.cli",
"pathlib.Path",
"os.close",
"dffml.cli.ml.Train.cli",
"shutil.rmtree",
"dffml.source.csv.CSVSourceConfig",
"dffml.util.entrypoint.entrypoint",
"dffml.source.json.JSONSource",
"tempfile.mkdtemp",
"dffml.cli.cli.Merge.cli",
"dffml.util.asynctestcase.non_ex... | [((3039, 3057), 'dffml.util.entrypoint.entrypoint', 'entrypoint', (['"""fake"""'], {}), "('fake')\n", (3049, 3057), False, 'from dffml.util.entrypoint import entrypoint\n'), ((1410, 1488), 'dffml.source.file.FileSourceConfig', 'FileSourceConfig', ([], {'filename': 'self.temp_filename', 'readwrite': '(True)', 'allowempt... |
__package__ = 'archivebox.extractors'
from pathlib import Path
from tempfile import NamedTemporaryFile
from typing import Optional
import json
from ..index.schema import Link, ArchiveResult, ArchiveError
from ..system import run, atomic_write
from ..util import (
enforce_types,
download_url,
is_static_fi... | [
"tempfile.NamedTemporaryFile",
"pathlib.Path",
"json.loads"
] | [((1727, 1757), 'pathlib.Path', 'Path', (['(out_dir or link.link_dir)'], {}), '(out_dir or link.link_dir)\n', (1731, 1757), False, 'from pathlib import Path\n'), ((1392, 1411), 'pathlib.Path', 'Path', (['link.link_dir'], {}), '(link.link_dir)\n', (1396, 1411), False, 'from pathlib import Path\n'), ((2234, 2266), 'tempf... |
"""Bayesian Optimization sampler : Defined only for continuous domains.
For discrete inputs define another sampler"""
from verifai.samplers.domain_sampler import DomainSampler
import numpy as np
class BayesOptSampler(DomainSampler):
def __init__(self, domain, BO_params):
try:
import GPyOpt
... | [
"numpy.random.uniform",
"sys.exit",
"numpy.atleast_2d"
] | [((1261, 1300), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)', 'self.dimension'], {}), '(0, 1, self.dimension)\n', (1278, 1300), True, 'import numpy as np\n'), ((390, 449), 'sys.exit', 'sys.exit', (['"""BayesOptSampler requires GPyOpt to be installed"""'], {}), "('BayesOptSampler requires GPyOpt to be ins... |
import unittest
from get_nsu_temp import get_nsu_temp
from get_nsu_temp import message_nsu_temp
class TestStringMethods(unittest.TestCase):
def test_get_nsu_temp_is_str(self):
self.assertTrue(isinstance(get_nsu_temp()[0], str))
def test_get_nsu_temp_is_not_empty(self):
self.assertTrue(len... | [
"unittest.main",
"get_nsu_temp.get_nsu_temp",
"get_nsu_temp.message_nsu_temp"
] | [((496, 511), 'unittest.main', 'unittest.main', ([], {}), '()\n', (509, 511), False, 'import unittest\n'), ((217, 231), 'get_nsu_temp.get_nsu_temp', 'get_nsu_temp', ([], {}), '()\n', (229, 231), False, 'from get_nsu_temp import get_nsu_temp\n'), ((321, 335), 'get_nsu_temp.get_nsu_temp', 'get_nsu_temp', ([], {}), '()\n'... |
import torch.nn as nn
import torch.nn.functional as F
from layer import GraphConvolution
class GCN(nn.Module):
def __init__(self, nfeat, nhid, nclass, dropout):
super(GCN, self).__init__()
self.gc1 = GraphConvolution(nfeat, nhid)
self.gc2 = GraphConvolution(nhid, nclass)
self.dro... | [
"torch.nn.functional.dropout",
"layer.GraphConvolution",
"torch.nn.functional.log_softmax"
] | [((224, 253), 'layer.GraphConvolution', 'GraphConvolution', (['nfeat', 'nhid'], {}), '(nfeat, nhid)\n', (240, 253), False, 'from layer import GraphConvolution\n'), ((273, 303), 'layer.GraphConvolution', 'GraphConvolution', (['nhid', 'nclass'], {}), '(nhid, nclass)\n', (289, 303), False, 'from layer import GraphConvolut... |
# -*- coding: utf-8 -*-
from djangocms_text_ckeditor.models import Text
from cms.api import create_page, add_plugin
from cms.models import Page
from cms.models.placeholdermodel import Placeholder
from cms.models.pluginmodel import CMSPlugin
from cms.tests.test_plugins import PluginsTestBaseCase
from cms.utils.compat.t... | [
"cms.models.pluginmodel.CMSPlugin.objects.all",
"cms.models.placeholdermodel.Placeholder",
"cms.models.pluginmodel.CMSPlugin.objects.update",
"djangocms_text_ckeditor.models.Text.objects.get",
"cms.models.Page.objects.drafts",
"cms.models.placeholdermodel.Placeholder.objects.filter",
"cms.api.create_pag... | [((750, 863), 'cms.models.pluginmodel.CMSPlugin.objects.filter', 'CMSPlugin.objects.filter', ([], {'parent_id': 'parent_id', 'language': 'plugin.language', 'placeholder_id': 'plugin.placeholder_id'}), '(parent_id=parent_id, language=plugin.language,\n placeholder_id=plugin.placeholder_id)\n', (774, 863), False, 'fro... |
#
# Collective Knowledge (individual environment - setup)
#
# See CK LICENSE.txt for licensing details
# See CK COPYRIGHT.txt for copyright details
#
import os
import sys
import json
##############################################################################
def version_cmd(i):
path_with_init_py = i['fu... | [
"json.loads",
"os.path.basename",
"os.path.isdir",
"os.path.dirname",
"os.path.expanduser"
] | [((443, 477), 'os.path.dirname', 'os.path.dirname', (['path_with_init_py'], {}), '(path_with_init_py)\n', (458, 477), False, 'import os\n'), ((510, 548), 'os.path.basename', 'os.path.basename', (['path_without_init_py'], {}), '(path_without_init_py)\n', (526, 548), False, 'import os\n'), ((581, 618), 'os.path.dirname',... |
import copy
from .exceptions import UnknownKeyException
class ExtendedPublicBundle:
"""
This class looks exactly the same as the PublicBundle class, but the types of the
fields are a bit different:
The spk field is not a key, but a dictionary containing the key and the id:
spk = {
"key" :... | [
"copy.deepcopy"
] | [((739, 757), 'copy.deepcopy', 'copy.deepcopy', (['spk'], {}), '(spk)\n', (752, 757), False, 'import copy\n'), ((826, 846), 'copy.deepcopy', 'copy.deepcopy', (['otpks'], {}), '(otpks)\n', (839, 846), False, 'import copy\n')] |
# (C) Datadog, Inc. 2010-2017
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
# stdlib
from urlparse import urljoin
import csv
import time
import threading
import random
import string
import re
# 3rd party
import requests
import json
from nose.plugins.attrib import attr
# project
from che... | [
"threading.Thread.__init__",
"csv.reader",
"random.randint",
"random.choice",
"json.dumps",
"time.sleep",
"urlparse.urljoin",
"time.time",
"requests.get",
"re.search",
"requests.post",
"nose.plugins.attrib.attr",
"tests.checks.common.AgentCheckTest.__init__"
] | [((392, 414), 'nose.plugins.attrib.attr', 'attr', ([], {'requires': '"""couch"""'}), "(requires='couch')\n", (396, 414), False, 'from nose.plugins.attrib import attr\n'), ((416, 441), 'nose.plugins.attrib.attr', 'attr', ([], {'couch_version': '"""1.x"""'}), "(couch_version='1.x')\n", (420, 441), False, 'from nose.plugi... |
#!/usr/bin/env python3
# Copyright (C) 2012-2018 <NAME> <<EMAIL>>
# Copyright (C) 2018 <NAME> <<EMAIL>>
# Copyright (C) 2018 Electrum Technologies GmbH
#
# This file is licensed under the MIT license. See LICENCE file for more information.
#
import math
import re
from typing import Callable, Any
from .uikit_bindings ... | [
"electrum.i18n._"
] | [((3397, 3409), 'electrum.i18n._', '_', (['"""WARNING"""'], {}), "('WARNING')\n", (3398, 3409), False, 'from electrum.i18n import _\n'), ((3436, 3466), 'electrum.i18n._', '_', (['"""Never disclose your seed."""'], {}), "('Never disclose your seed.')\n", (3437, 3466), False, 'from electrum.i18n import _\n'), ((3493, 352... |
from django.db.models import Q
from django.core.cache import cache, caches, InvalidCacheBackendError
from pt_law_parser import analyse, common_managers, observers, ObserverManager, \
from_json, html_toc
from law.models import Document, Type
PLURALS = {'Decreto-Lei': ['Decretos-Leis', 'Decretos-Lei'],
... | [
"law.models.Document.objects.exclude",
"pt_law_parser.analyse",
"django.core.cache.cache.set",
"django.db.models.Q",
"django.core.cache.cache.get",
"pt_law_parser.html_toc",
"law.models.Type.objects.exclude",
"pt_law_parser.from_json"
] | [((660, 663), 'django.db.models.Q', 'Q', ([], {}), '()\n', (661, 663), False, 'from django.db.models import Q\n'), ((1567, 1606), 'pt_law_parser.analyse', 'analyse', (['document.text', 'managers', 'terms'], {}), '(document.text, managers, terms)\n', (1574, 1606), False, 'from pt_law_parser import analyse, common_manage... |
'''
Your job in this exercise is to compute the yearly percent-change of US GDP (Gross Domestic Product) since 2008.
The data has been obtained from the Federal Reserve Bank of St. Louis and is available in the file GDP.csv, which contains quarterly data; you will resample it to annual sampling and then compute the an... | [
"pandas.read_csv"
] | [((498, 556), 'pandas.read_csv', 'pd.read_csv', (['"""GDP.csv"""'], {'parse_dates': '(True)', 'index_col': '"""DATE"""'}), "('GDP.csv', parse_dates=True, index_col='DATE')\n", (509, 556), True, 'import pandas as pd\n')] |
from __future__ import annotations
import logging
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING
import pygame
import pytweening
from scripts.core import utility
from scripts.core.constants import Direction, NodeType, OverworldState, SceneType
from scripts.scenes.overworld.elements.n... | [
"logging.warning",
"logging.info",
"scripts.core.utility.lerp",
"pytweening.easeInQuad"
] | [((4726, 4770), 'pytweening.easeInQuad', 'pytweening.easeInQuad', (['percent_time_complete'], {}), '(percent_time_complete)\n', (4747, 4770), False, 'import pytweening\n'), ((4784, 4841), 'scripts.core.utility.lerp', 'utility.lerp', (['selected.pos[0]', 'target.pos[0]', 'lerp_amount'], {}), '(selected.pos[0], target.po... |
from unittest.mock import patch
from django.test import TestCase
from tests import path, read
class MappingSheetTestCase(TestCase):
url = '/mapping-sheet/'
def assertSuccess(self, method, expected, data):
response = getattr(self.client, method)(self.url, data)
self.assertEqual(response.sta... | [
"unittest.mock.patch",
"tests.path",
"tests.read"
] | [((1110, 1142), 'unittest.mock.patch', 'patch', (['"""default.forms._get_tags"""'], {}), "('default.forms._get_tags')\n", (1115, 1142), False, 'from unittest.mock import patch\n'), ((2562, 2594), 'unittest.mock.patch', 'patch', (['"""default.forms._get_tags"""'], {}), "('default.forms._get_tags')\n", (2567, 2594), Fals... |
"""HACS Startup constrains."""
# pylint: disable=bad-continuation
import os
from .const import CUSTOM_UPDATER_LOCATIONS, CUSTOM_UPDATER_WARNING
from .helpers.misc import version_left_higher_then_right
from custom_components.hacs.globals import get_hacs
MINIMUM_HA_VERSION = "0.110.0"
def check_constrains():
"""... | [
"custom_components.hacs.globals.get_hacs",
"os.path.exists"
] | [((619, 629), 'custom_components.hacs.globals.get_hacs', 'get_hacs', ([], {}), '()\n', (627, 629), False, 'from custom_components.hacs.globals import get_hacs\n'), ((1023, 1033), 'custom_components.hacs.globals.get_hacs', 'get_hacs', ([], {}), '()\n', (1031, 1033), False, 'from custom_components.hacs.globals import get... |
# Generated by Django 3.1.6 on 2022-01-15 10:38
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('scoreboard', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='statistics',
... | [
"django.db.models.DateTimeField"
] | [((370, 425), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'default': 'django.utils.timezone.now'}), '(default=django.utils.timezone.now)\n', (390, 425), False, 'from django.db import migrations, models\n')] |
# Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
# This script aims to replicate the behavior of examples/sir_hmc.py but using
# the high-level components of pyro.contrib.epidemiology. Command line
# arguments and results should be similar.
import argparse
import logging
import math... | [
"matplotlib.pyplot.title",
"pyro.enable_validation",
"pyro.contrib.epidemiology.SimpleSEIRModel",
"argparse.ArgumentParser",
"torch.cat",
"torch.set_default_tensor_type",
"matplotlib.pyplot.figure",
"torch.distributions.constraints.interval",
"torch.set_default_dtype",
"torch.arange",
"matplotli... | [((611, 672), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(message)s"""', 'level': 'logging.INFO'}), "(format='%(message)s', level=logging.INFO)\n", (630, 672), False, 'import logging\n'), ((9323, 9356), 'pyro.enable_validation', 'pyro.enable_validation', (['__debug__'], {}), '(__debug__)\n', (93... |
""" Database interaction class. """
__author__ = "<NAME>"
__date__ = "2020-08-06"
__copyright__ = "Copyright 2020 United Kingdom Research and Innovation"
__license__ = "BSD - see LICENSE file in top-level package directory"
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
CONNECTION_TEM... | [
"sqlalchemy.orm.sessionmaker"
] | [((645, 676), 'sqlalchemy.orm.sessionmaker', 'sessionmaker', ([], {'bind': 'self._engine'}), '(bind=self._engine)\n', (657, 676), False, 'from sqlalchemy.orm import sessionmaker\n')] |
"""Test the K8SDescriptor wrapper."""
import pytest
from kubesplit.k8s_descriptor import K8SDescriptor
data_for_test_get_order_prefix = [
("Namespace"),
("ServiceAccount"),
("ClusterRole"),
("Role"),
("ClusterRoleBinding"),
("RoleBinding"),
("Deployment"),
("Service"),
("Ingress"),
... | [
"pytest.mark.parametrize",
"kubesplit.k8s_descriptor.K8SDescriptor"
] | [((1453, 1516), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""kind"""', 'data_for_test_get_order_prefix'], {}), "('kind', data_for_test_get_order_prefix)\n", (1476, 1516), False, 'import pytest\n'), ((1794, 1857), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""kind"""', 'data_for_test_get_ord... |
#$Id$
from books.model.PageContext import PageContext
class CurrencyList:
"""This class is used to create object for currency list."""
def __init__(self):
"""Initialize parameters for currency list."""
self.currencies = []
self.page_context = PageContext()
def set_currencies(self,... | [
"books.model.PageContext.PageContext"
] | [((277, 290), 'books.model.PageContext.PageContext', 'PageContext', ([], {}), '()\n', (288, 290), False, 'from books.model.PageContext import PageContext\n')] |
#! /usr/bin/env python
# -*- coding: utf8 -*-
'''
Copyright 2018 University of Liège
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 requir... | [
"ccupydo.CFlexInterfaceData.dot",
"ccupydo.CInterfaceMatrix.mult",
"numpy.set_printoptions",
"ccupydo.CFlexInterfaceData.__init__",
"ccupydo.CInterfaceMatrix.__init__",
"numpy.linalg.norm",
"ccupydo.CFlexInterfaceData.norm",
"ccupydo.CFlexInterfaceData.sum"
] | [((947, 989), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'threshold': 'sys.maxsize'}), '(threshold=sys.maxsize)\n', (966, 989), True, 'import numpy as np\n'), ((1397, 1469), 'ccupydo.CFlexInterfaceData.__init__', 'ccupydo.CFlexInterfaceData.__init__', (['self', 'val_nPoint', 'val_nDim', 'mpiComm'], {}), '(s... |
from celery import shared_task
from time import sleep
from django.core.mail import send_mail
from django.conf import settings
@shared_task
def sleepy(duration):
sleep(duration)
print("I'm busy for background working...")
return None
@shared_task
def email_send_our_user():
send_mail(
'Testing... | [
"django.core.mail.send_mail",
"time.sleep"
] | [((167, 182), 'time.sleep', 'sleep', (['duration'], {}), '(duration)\n', (172, 182), False, 'from time import sleep\n'), ((293, 439), 'django.core.mail.send_mail', 'send_mail', (['"""Testing celery working..."""', '"""celery is very awesome asyc task..."""', 'settings.EMAIL_HOST_USER', "['<EMAIL>']"], {'fail_silently':... |
from kafka import KafkaConsumer
from pymongo import MongoClient
from json import loads
if __name__ == "__main__":
# initialize consumer object
consumer = KafkaConsumer('raw_data',
bootstrap_servers=['localhost:9092'],
auto_offset_reset='earliest',
... | [
"pymongo.MongoClient"
] | [((542, 572), 'pymongo.MongoClient', 'MongoClient', (['"""localhost:27017"""'], {}), "('localhost:27017')\n", (553, 572), False, 'from pymongo import MongoClient\n')] |
from __future__ import division
from future.utils import iteritems, itervalues
from builtins import map, zip
import numpy as np
import itertools
import collections
import operator
import copy
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec, GridSpecFromSubplotSpec
from matplotlib import cm
fro... | [
"matplotlib.pyplot.title",
"matplotlib.cm.get_cmap",
"numpy.ones",
"matplotlib.pyplot.figure",
"numpy.arange",
"numpy.exp",
"scipy.special.logsumexp",
"matplotlib.pyplot.gca",
"numpy.atleast_2d",
"pybasicbayes.util.stats.atleast_2d",
"joblib.Parallel",
"matplotlib.pyplot.draw",
"numpy.linspa... | [((2496, 2510), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (2508, 2510), True, 'import matplotlib.pyplot as plt\n'), ((2577, 2678), 'pyhsmm.util.plot.heatmap', 'heatmap', (['tmat', 'states_list', 'states_list'], {'ax': 'ax', 'cmap': '"""Blues"""', 'cbarlabel': '"""Transition probability"""'}), "(tm... |
from aoc_wim.aoc2016 import q16
padding = """\
1 becomes 100.
0 becomes 001.
11111 becomes 11111000000.
111100001010 becomes 1111000010100101011110000.
"""
def test_padding():
for line in padding.splitlines():
left, right = line.rstrip(".").split(" becomes ")
assert q16.pad(left, n=len(right)) =... | [
"aoc_wim.aoc2016.q16.f"
] | [((388, 405), 'aoc_wim.aoc2016.q16.f', 'q16.f', (['data'], {'n': '(12)'}), '(data, n=12)\n', (393, 405), False, 'from aoc_wim.aoc2016 import q16\n'), ((481, 495), 'aoc_wim.aoc2016.q16.f', 'q16.f', (['data', 'n'], {}), '(data, n)\n', (486, 495), False, 'from aoc_wim.aoc2016 import q16\n')] |
from .views import DriverViewSet, VehicleViewSet
from django.urls import include, path
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register('driver', DriverViewSet, basename='driver')
router.register('vehicle', VehicleViewSet, basename='vehicle')
urlpatterns = [
path('', inclu... | [
"rest_framework.routers.DefaultRouter",
"django.urls.include"
] | [((147, 162), 'rest_framework.routers.DefaultRouter', 'DefaultRouter', ([], {}), '()\n', (160, 162), False, 'from rest_framework.routers import DefaultRouter\n'), ((315, 335), 'django.urls.include', 'include', (['router.urls'], {}), '(router.urls)\n', (322, 335), False, 'from django.urls import include, path\n')] |
import os
import tensorflow as tf
import numpy as np
import quaternion
import datetime
import time
def test_linspace():
# tf ops must take float variables
# better use np.linspace instead
x = tf.linspace(0., 3., 4)
print("linspace", x)
def test_gather():
coords = tf.tile(tf.expand_dims(tf.linspa... | [
"time.asctime",
"tensorflow.ones",
"numpy.set_printoptions",
"tensorflow.linspace",
"tensorflow.gather",
"tensorflow.pad",
"tensorflow.constant",
"numpy.sin",
"numpy.linalg.norm",
"quaternion.as_rotation_vector",
"numpy.cos",
"datetime.datetime.now"
] | [((206, 230), 'tensorflow.linspace', 'tf.linspace', (['(0.0)', '(3.0)', '(4)'], {}), '(0.0, 3.0, 4)\n', (217, 230), True, 'import tensorflow as tf\n'), ((442, 468), 'tensorflow.gather', 'tf.gather', (['coords', 'indices'], {}), '(coords, indices)\n', (451, 468), True, 'import tensorflow as tf\n'), ((628, 664), 'tensorf... |
# -*- coding: utf-8 -*-
# *****************************************************************************
# NICOS, the Networked Instrument Control System of the MLZ
# Copyright (c) 2009-2022 by the NICOS contributors (see AUTHORS)
#
# This program is free software; you can redistribute it and/or modify it under
# the t... | [
"nicos.session.getDevice",
"nicos.core.Override",
"nicos.core.Param"
] | [((1416, 1543), 'nicos.core.Param', 'Param', (['"""Device ("dev") or parameter ("dev.param") to return on read"""'], {'type': 'str', 'settable': '(True)', 'unit': '""""""', 'category': '"""general"""'}), '(\'Device ("dev") or parameter ("dev.param") to return on read\', type=\n str, settable=True, unit=\'\', categor... |
# (C) Datadog, Inc. 2018-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import logging
import pytest
import requests
from six import iteritems
from datadog_checks.elastic import ESCheck
from datadog_checks.elastic.config import from_instance
from datadog_checks.elastic.metri... | [
"datadog_checks.elastic.metrics.index_stats_for_version",
"datadog_checks.elastic.config.from_instance",
"pytest.skip",
"datadog_checks.elastic.metrics.health_stats_for_version",
"datadog_checks.elastic.metrics.stats_for_version",
"requests.put",
"datadog_checks.elastic.metrics.pshard_stats_for_version"... | [((581, 614), 'logging.getLogger', 'logging.getLogger', (['"""test_elastic"""'], {}), "('test_elastic')\n", (598, 614), False, 'import logging\n'), ((3141, 3164), 'datadog_checks.elastic.config.from_instance', 'from_instance', (['instance'], {}), '(instance)\n', (3154, 3164), False, 'from datadog_checks.elastic.config ... |
# encoding = utf-8
__author__ = "<NAME>"
import socket
import threading
import datetime
import logging
FORMAT = "%(asctime)s %(threadName)s %(thread)d: %(message)s"
logging.basicConfig(format=FORMAT, level=logging.INFO)
class WeChat:
def __init__(self, ip="0.0.0.0", port=9000):
self.addr = (ip, port)
... | [
"threading.Thread",
"logging.basicConfig",
"threading.enumerate",
"socket.socket",
"logging.info",
"datetime.datetime.now"
] | [((168, 222), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': 'FORMAT', 'level': 'logging.INFO'}), '(format=FORMAT, level=logging.INFO)\n', (187, 222), False, 'import logging\n'), ((341, 356), 'socket.socket', 'socket.socket', ([], {}), '()\n', (354, 356), False, 'import socket\n'), ((560, 596), 'logging.... |
'''
在单元格中放置控件
setItem:将文本放到单元格中
setCellWidget:将控件放到单元格中
setStyleSheet:设置控件的样式(QSS)
'''
import sys
from PyQt5.QtWidgets import (QWidget, QTableWidget, QHBoxLayout, QApplication, QTableWidgetItem, QAbstractItemView,
QComboBox, QPushButton)
class PlaceControlInCell(QWidget):
def __i... | [
"PyQt5.QtWidgets.QComboBox",
"PyQt5.QtWidgets.QTableWidget",
"PyQt5.QtWidgets.QHBoxLayout",
"PyQt5.QtWidgets.QPushButton",
"PyQt5.QtWidgets.QTableWidgetItem",
"PyQt5.QtWidgets.QApplication"
] | [((1312, 1334), 'PyQt5.QtWidgets.QApplication', 'QApplication', (['sys.argv'], {}), '(sys.argv)\n', (1324, 1334), False, 'from PyQt5.QtWidgets import QWidget, QTableWidget, QHBoxLayout, QApplication, QTableWidgetItem, QAbstractItemView, QComboBox, QPushButton\n'), ((517, 530), 'PyQt5.QtWidgets.QHBoxLayout', 'QHBoxLayou... |
import pandas as pd
import numpy as np
import multiprocessing
from multiprocessing import Process, Manager, Queue
import math
from PyProM.src.data.importing import Import
import sys
import os
from PyProM.src.utility.util_profile import Util_Profile
from PyProM.src.utility.util_multiprocessing import Util_Multiprocess... | [
"pandas.read_csv",
"numpy.std",
"multiprocessing.Manager",
"time.time",
"PyProM.src.utility.util_multiprocessing.Util_Multiprocessing.join_dict",
"numpy.mean",
"pandas.to_datetime",
"PyProM.src.data.importing.Import",
"functools.wraps",
"numpy.array_split",
"multiprocessing.Queue",
"multiproce... | [((383, 392), 'functools.wraps', 'wraps', (['fn'], {}), '(fn)\n', (388, 392), False, 'from functools import wraps\n'), ((436, 447), 'time.time', 'time.time', ([], {}), '()\n', (445, 447), False, 'import time\n'), ((486, 497), 'time.time', 'time.time', ([], {}), '()\n', (495, 497), False, 'import time\n'), ((910, 936), ... |
import os
basedir = os.path.abspath(os.path.dirname(__file__))
SQLALCHEMY_ECHO = True
SQLALCHEMY_TRACK_MODIFICATIONS = True
SQLALCHEMY_DATABASE_URI = "postgresql://postgres:password@postgres:5432/case_service"
#SQLALCHEMY_DATABASE_URI = "sqlite:///db.sqlite3" | [
"os.path.dirname"
] | [((37, 62), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (52, 62), False, 'import os\n')] |
"""strategypattern_traditional
Example to show one way of implementing strategy design pattern in Python.
The example shown here resembles a 'traditional' implementation of strategy
pattern in Python (traditional = the one you may implement in languages like
C++). For a more Pythonic approach, see the file strategypa... | [
"sys.exit"
] | [((1729, 1740), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (1737, 1740), False, 'import sys\n')] |
import conllu
from sklearn.metrics import confusion_matrix
gold = conllu.parse(open('cs-ud-test.conllu', 'r').read())
pred = conllu.parse(open('cs-ud-test-pred.conllu', 'r').read())
gold_labels = [t['deprel'] for sent in gold for t in sent]
pred_labels = [t['deprel'] for sent in pred for t in sent]
vocab = sorted(lis... | [
"sklearn.metrics.confusion_matrix"
] | [((412, 468), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['gold_labels', 'pred_labels'], {'labels': 'vocab'}), '(gold_labels, pred_labels, labels=vocab)\n', (428, 468), False, 'from sklearn.metrics import confusion_matrix\n')] |
# Copyright (c) 2021 Graphcore Ltd. All rights reserved.
from popart.ir.tensor import Tensor
from popart.ir.graph import Graph
import popart._internal.ir as _ir
from popart.ir import dtypes
from typing import Optional
def cast_if_needed(t: Tensor, data_type: dtypes.dtype) -> Tensor:
from popart.ir.ops.cast impor... | [
"popart._internal.ir.OptionalFloat",
"popart.ir.ops.cast.cast"
] | [((371, 389), 'popart.ir.ops.cast.cast', 'cast', (['t', 'data_type'], {}), '(t, data_type)\n', (375, 389), False, 'from popart.ir.ops.cast import cast\n'), ((774, 794), 'popart._internal.ir.OptionalFloat', '_ir.OptionalFloat', (['v'], {}), '(v)\n', (791, 794), True, 'import popart._internal.ir as _ir\n'), ((817, 836), ... |
from django.core.exceptions import ValidationError
'''
RowHandler objects
An object inheriting from RowHandler() should be created for each different 'type' of row
(the 'type' being determined by a unique combination of columns)
process_row (input):
row data obtained from the Importer object... | [
"django.core.exceptions.ValidationError"
] | [((1062, 1090), 'django.core.exceptions.ValidationError', 'ValidationError', (['self.errors'], {}), '(self.errors)\n', (1077, 1090), False, 'from django.core.exceptions import ValidationError\n')] |
from datetime import datetime, timedelta
from django.conf import settings
from django.contrib.postgres.search import SearchQuery
from django.db.models import Count
from django.shortcuts import render
from auth.helpers import auth_required
from common.models import group_by, top
from common.pagination import paginate
... | [
"users.models.expertise.UserExpertise.objects.filter",
"django.contrib.postgres.search.SearchQuery",
"users.models.user.User.registered_members",
"users.models.tags.Tag.tags_with_stats",
"common.pagination.paginate",
"users.models.expertise.UserExpertise.objects.all",
"datetime.datetime.utcnow",
"comm... | [((1469, 1490), 'users.models.tags.Tag.tags_with_stats', 'Tag.tags_with_stats', ([], {}), '()\n', (1488, 1490), False, 'from users.models.tags import Tag\n'), ((1513, 1560), 'common.models.group_by', 'group_by', (['tags_with_stats', '"""group"""'], {'todict': '(True)'}), "(tags_with_stats, 'group', todict=True)\n", (15... |
import requests
import xmljson
import xml.etree.ElementTree as elemTree
from json import dump, load
import os
import jsonbender
import json
from collections import OrderedDict
from jsonschema.validators import RefResolver, Draft4Validator
from validate.jsonschema_validator import validate_instance
class FlowRepoClien... | [
"json.dump",
"json.load",
"xml.etree.ElementTree.fromstring",
"jsonbender.bend",
"os.path.dirname",
"jsonbender.S",
"jsonschema.validators.Draft4Validator",
"jsonbender.K",
"jsonbender.OptionalS",
"jsonschema.validators.RefResolver",
"jsonbender.F",
"requests.get",
"requests.request"
] | [((1818, 1851), 'requests.request', 'requests.request', (['"""GET"""', 'full_url'], {}), "('GET', full_url)\n", (1834, 1851), False, 'import requests\n'), ((2816, 2849), 'requests.request', 'requests.request', (['"""GET"""', 'full_url'], {}), "('GET', full_url)\n", (2832, 2849), False, 'import requests\n'), ((8764, 880... |
# -*- coding: utf-8 -*-
import os
import sys
import locale
import platform
import subprocess
import darkdetect
try:
import winreg
except Exception:
pass
from pathlib import Path
from PySide2.QtCore import qVersion
DEFAULT_ENCODING = 'utf-8'
SYSTEM_LANGUAGE = locale.getdefaultlocale()[0]
PYTHON_VERSION = ... | [
"PySide2.QtCore.qVersion",
"locale.getdefaultlocale",
"winreg.OpenKey",
"darkdetect.isDark",
"winreg.QueryValueEx",
"pathlib.Path",
"subprocess.call",
"platform.system",
"os.startfile"
] | [((380, 390), 'PySide2.QtCore.qVersion', 'qVersion', ([], {}), '()\n', (388, 390), False, 'from PySide2.QtCore import qVersion\n'), ((273, 298), 'locale.getdefaultlocale', 'locale.getdefaultlocale', ([], {}), '()\n', (296, 298), False, 'import locale\n'), ((422, 439), 'platform.system', 'platform.system', ([], {}), '()... |
"""
Functions for interacting with the BEAST model
"""
import numpy as np
import h5py
from tqdm import tqdm
__all__ = ["read_lnp_data", "read_noise_data", "read_sed_data", "get_lnp_grid_vals"]
def read_lnp_data(filename, nstars=None, shift_lnp=True):
"""
Read in the sparse lnp for all the stars in the hdf5... | [
"h5py.File",
"tqdm.tqdm",
"numpy.zeros",
"numpy.isfinite",
"numpy.max",
"numpy.array"
] | [((833, 857), 'h5py.File', 'h5py.File', (['filename', '"""r"""'], {}), "(filename, 'r')\n", (842, 857), False, 'import h5py\n'), ((2838, 2862), 'h5py.File', 'h5py.File', (['filename', '"""r"""'], {}), "(filename, 'r')\n", (2847, 2862), False, 'import h5py\n'), ((2939, 2982), 'tqdm.tqdm', 'tqdm', (['param_list'], {'desc... |
import math
import numpy as np
from collections import namedtuple
import random
from cyclopts import cyclopts_io as cycio
from cyclopts.structured_species import data
"""default values and np.dtypes for points making up parameter space"""
Param = namedtuple('Param', ['val', 'dtype'])
class Point(object):
"""A co... | [
"numpy.abs",
"random.uniform",
"numpy.dtype",
"numpy.zeros",
"cyclopts.cyclopts_io.uuid_rows",
"math.floor",
"cyclopts.structured_species.data.append",
"numpy.mean",
"collections.namedtuple",
"numpy.dot",
"cyclopts.structured_species.data.loc"
] | [((249, 286), 'collections.namedtuple', 'namedtuple', (['"""Param"""', "['val', 'dtype']"], {}), "('Param', ['val', 'dtype'])\n", (259, 286), False, 'from collections import namedtuple\n'), ((6197, 6305), 'numpy.dtype', 'np.dtype', (["[('arcid', np.uint32), ('commod', np.uint32), ('pref_c', np.float32), (\n 'pref_l'... |
# 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.
import uuid
import html
import typing as t
import json
from pathlib import Path
import IPython.display
from ipykernel.comm import Comm
from . i... | [
"pathlib.Path",
"uuid.uuid4",
"json.dumps"
] | [((1228, 1244), 'json.dumps', 'json.dumps', (['w_id'], {}), '(w_id)\n', (1238, 1244), False, 'import json\n'), ((1055, 1067), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (1065, 1067), False, 'import uuid\n'), ((4134, 4146), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (4144, 4146), False, 'import uuid\n'), ((828, 84... |
import falcon
import logging
import json
from sikre.models.models import User
class LoginResource(object):
"""
The login resource handles the login from all the
"""
def __init__(self):
self.logger = logging.getLogger('thingsapp.' + __name__)
def on_get(self, request, response):
... | [
"falcon.HTTPError",
"logging.getLogger"
] | [((227, 269), 'logging.getLogger', 'logging.getLogger', (["('thingsapp.' + __name__)"], {}), "('thingsapp.' + __name__)\n", (244, 269), False, 'import logging\n'), ((326, 430), 'falcon.HTTPError', 'falcon.HTTPError', (['falcon.HTTP_405', '"""Client error"""', '"""The GET method is not allowed in this endpoint."""'], {}... |
"""
Carto Waze Lambda Connector
Developed by Geographica, 2017-2018.
"""
import os
class Config:
"""
Configuration parameters:
- Carto API.
- WAZE API
- Traffico
"""
# Carto API
CARTO_API_KEY = os.environ.get('CARTO_API_KEY')
CARTO_USER = os.environ.get('CARTO_USER')... | [
"os.environ.get"
] | [((243, 274), 'os.environ.get', 'os.environ.get', (['"""CARTO_API_KEY"""'], {}), "('CARTO_API_KEY')\n", (257, 274), False, 'import os\n'), ((292, 320), 'os.environ.get', 'os.environ.get', (['"""CARTO_USER"""'], {}), "('CARTO_USER')\n", (306, 320), False, 'import os\n'), ((357, 387), 'os.environ.get', 'os.environ.get', ... |
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from dccw.single_palette_sorter import *
class ComprehensiveSinglePaletteSorter:
def __init__(self, palette, target_spaces):
# palette: ColorPalette Object
# target_space: ['rgb', 'hsl', 'hsv', 'lab', 'lch']
sel... | [
"os.path.dirname"
] | [((69, 94), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (84, 94), False, 'import os\n')] |
# Code generated by lark_sdk_gen. DO NOT EDIT.
import unittest
import pylark
import pytest
from tests.test_conf import app_all_permission, app_no_permission
from tests.test_helper import mock_get_tenant_access_token_failed
def mock(*args, **kwargs):
raise pylark.PyLarkError(scope="scope", func="func", code=1, ms... | [
"pylark.SendUrgentPhoneMessageReq",
"pylark.SendUrgentSmsMessageReq",
"pylark.GetBatchSentMessageReadUserReq",
"pylark.DeleteEphemeralMessageReq",
"pylark.UpdateMessageReq",
"pylark.SendRawMessageOldReq",
"pylark.PyLarkError",
"pylark.SendUrgentAppMessageReq",
"pylark.SendEphemeralMessageReq",
"py... | [((263, 336), 'pylark.PyLarkError', 'pylark.PyLarkError', ([], {'scope': '"""scope"""', 'func': '"""func"""', 'code': '(1)', 'msg': '"""mock-failed"""'}), "(scope='scope', func='func', code=1, msg='mock-failed')\n", (281, 336), False, 'import pylark\n'), ((388, 478), 'pylark.PyLarkError', 'pylark.PyLarkError', ([], {'s... |
from typing import NamedTuple
from urllib.parse import (
urlsplit,
urlunsplit,
)
class URL(NamedTuple):
scheme: str
host: str
path: str
query: str
fragment: str
@classmethod
def from_string(cls, url_string: str) -> 'URL':
split_result = urlsplit(url_string)
return ... | [
"urllib.parse.urlsplit",
"urllib.parse.urlunsplit"
] | [((284, 304), 'urllib.parse.urlsplit', 'urlsplit', (['url_string'], {}), '(url_string)\n', (292, 304), False, 'from urllib.parse import urlsplit, urlunsplit\n'), ((579, 653), 'urllib.parse.urlunsplit', 'urlunsplit', (['(self.scheme, self.host, self.path, self.query, self.fragment)'], {}), '((self.scheme, self.host, sel... |
import pygame
import random
import numpy as np
from collections import deque
import tensorflow as tf # http://blog.topspeedsnail.com/archives/10116
import cv2 # http://blog.topspeedsnail.com/archives/4755
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
SCREEN_SIZE = [320, 400]
BAR_SIZE = [50, 5]
BALL_SIZE = [... | [
"numpy.argmax",
"random.sample",
"tensorflow.reshape",
"pygame.Rect",
"tensorflow.matmul",
"pygame.display.update",
"tensorflow.multiply",
"tensorflow.nn.conv2d",
"collections.deque",
"pygame.display.set_mode",
"tensorflow.placeholder",
"numpy.append",
"numpy.max",
"numpy.reshape",
"tens... | [((3136, 3179), 'tensorflow.placeholder', 'tf.placeholder', (['"""float"""', '[None, 80, 100, 4]'], {}), "('float', [None, 80, 100, 4])\n", (3150, 3179), True, 'import tensorflow as tf\n'), ((3198, 3237), 'tensorflow.placeholder', 'tf.placeholder', (['"""float"""', '[None, output]'], {}), "('float', [None, output])\n",... |
import os
import random
import string
from shapely.geometry import Point, Polygon
from datetime import datetime
from dateutil import parser
def parse_datetime(input_var):
if isinstance(input_var, str):
return parser.parse(input_var).replace(tzinfo=None)
elif input_var is None:
return input_var
... | [
"shapely.geometry.Point",
"dateutil.parser.parse",
"shapely.geometry.Polygon"
] | [((1180, 1196), 'shapely.geometry.Point', 'Point', (['lat', 'long'], {}), '(lat, long)\n', (1185, 1196), False, 'from shapely.geometry import Point, Polygon\n'), ((1231, 1264), 'shapely.geometry.Polygon', 'Polygon', (['[(0, 0), (1, 1), (1, 0)]'], {}), '([(0, 0), (1, 1), (1, 0)])\n', (1238, 1264), False, 'from shapely.g... |
"""
Schema for disclosure objects.
"""
import copy
from .common import sources, extras, identifiers, contact_details,\
fuzzy_datetime_blank, documents
from opencivicdata import common
fuzzy_datetime = copy.deepcopy(fuzzy_datetime_blank)
fuzzy_datetime["blank"] = False
reporting_period_schema = {
"proper... | [
"copy.deepcopy"
] | [((212, 247), 'copy.deepcopy', 'copy.deepcopy', (['fuzzy_datetime_blank'], {}), '(fuzzy_datetime_blank)\n', (225, 247), False, 'import copy\n')] |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import torch
from torch.optim import Optimizer
class QHM(Optimizer):
r"""
Stochastic gradient method with Quasi-Hyperbolic Momentum (QHM):
h(k) = (1 - \beta) * g(k) + \beta * h(k-1)
d(k) = (1 - \nu) * g(k) + \nu * h(k)
... | [
"torch.zeros_like"
] | [((3707, 3726), 'torch.zeros_like', 'torch.zeros_like', (['x'], {}), '(x)\n', (3723, 3726), False, 'import torch\n'), ((4330, 4349), 'torch.zeros_like', 'torch.zeros_like', (['g'], {}), '(g)\n', (4346, 4349), False, 'import torch\n')] |
from urllib import response
from django.shortcuts import render
from django.http import HttpResponseRedirect
from datetime import datetime
from .models import Ventas
from .forms import FormVentas
def eliminar(request,id):
obj = Ventas.objects.get(id_factura=id)
if request.method =="GET":
... | [
"django.shortcuts.render",
"django.http.HttpResponseRedirect",
"datetime.datetime.now"
] | [((358, 395), 'django.http.HttpResponseRedirect', 'HttpResponseRedirect', (['"""/ventas/lista"""'], {}), "('/ventas/lista')\n", (378, 395), False, 'from django.http import HttpResponseRedirect\n'), ((499, 540), 'django.shortcuts.render', 'render', (['request', '"""consulta.html"""', 'context'], {}), "(request, 'consult... |
#!/usr/bin/env python
###############################################################################
# $Id$
#
# Project: GDAL/OGR Test Suite
# Purpose: Test OGR XPlane driver functionality.
# Author: <NAME> <even dot rouault at mines dash paris dot org>
#
##########################################################... | [
"sys.path.append",
"osgeo.ogr.Open",
"gdaltest.setup_run",
"gdaltest.summarize",
"gdaltest.run_tests"
] | [((1594, 1621), 'sys.path.append', 'sys.path.append', (['"""../pymod"""'], {}), "('../pymod')\n", (1609, 1621), False, 'import sys\n'), ((1830, 1854), 'osgeo.ogr.Open', 'ogr.Open', (['"""data/apt.dat"""'], {}), "('data/apt.dat')\n", (1838, 1854), False, 'from osgeo import ogr\n'), ((4028, 4059), 'osgeo.ogr.Open', 'ogr.... |
from collections.abc import Sequence
from dataclasses import fields
import libcst as cst
from buglab.representations.codereprs import PythonCodeRelations
from buglab.utils.cstutils import is_whitespace_node
__all__ = ["AstRelations"]
class AstRelations(cst.CSTVisitor):
def __init__(self, code_relations: Python... | [
"dataclasses.fields",
"buglab.utils.cstutils.is_whitespace_node"
] | [((498, 510), 'dataclasses.fields', 'fields', (['node'], {}), '(node)\n', (504, 510), False, 'from dataclasses import fields\n'), ((902, 926), 'buglab.utils.cstutils.is_whitespace_node', 'is_whitespace_node', (['node'], {}), '(node)\n', (920, 926), False, 'from buglab.utils.cstutils import is_whitespace_node\n'), ((105... |
# noqa: D100
import json
import logging
import os
import subprocess
from typing import List, Optional, Union
import hail as hl
from gnomad.resources.resource_utils import VersionedTableResource
logging.basicConfig(format="%(levelname)s (%(name)s %(lineno)s): %(message)s")
logger = logging.getLogger(__name__)
logger... | [
"hail.default_reference",
"hail.vep",
"logging.getLogger",
"hail.is_missing",
"hail.is_defined",
"hail.eval",
"hail.struct",
"hail.sorted",
"hail.case",
"hail.empty_array",
"subprocess.check_output",
"hail.null",
"json.load",
"hail.hadoop_open",
"logging.basicConfig",
"hail.delimit",
... | [((198, 276), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(levelname)s (%(name)s %(lineno)s): %(message)s"""'}), "(format='%(levelname)s (%(name)s %(lineno)s): %(message)s')\n", (217, 276), False, 'import logging\n'), ((286, 313), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__... |
import os
import json
import random
import re
from datetime import datetime
from discord.ext import commands, tasks
from discord_slash import cog_ext, SlashContext
########
# PICKING A RANDOM PRODUCT FROM THE SCRAPED LIST!
########
def item_pick():
data = []
locations = {
0: "https://www.amazon.com"
}
... | [
"os.listdir",
"json.dump",
"json.load",
"discord.ext.commands.command",
"random.choice",
"os.system",
"discord.ext.commands.Cog.listener",
"datetime.datetime.strptime",
"discord.ext.tasks.loop",
"discord_slash.cog_ext.cog_slash",
"os.path.isfile",
"re.findall",
"os.access",
"datetime.datet... | [((747, 769), 'random.choice', 'random.choice', (['data[0]'], {}), '(data[0])\n', (760, 769), False, 'import random\n'), ((4076, 4100), 'discord.ext.tasks.loop', 'tasks.loop', ([], {'minutes': '(60.0)'}), '(minutes=60.0)\n', (4086, 4100), False, 'from discord.ext import commands, tasks\n'), ((4840, 4977), 'discord.ext.... |
# coding: utf-8
# In[1]:
from cltk.tag.pos.pos_tagger import POSTag
from cltk.tokenize.sentence.tokenize_sentences import TokenizeSentence
import os
import re
# In[2]:
def extract_tlg_work(file_path, regex_match):
abs_path = os.path.expanduser(file_path)
with open(abs_path) as f:
r = f.read()
... | [
"os.path.join",
"os.makedirs",
"os.path.isdir",
"cltk.tag.pos.pos_tagger.POSTag",
"cltk.tokenize.sentence.tokenize_sentences.TokenizeSentence",
"os.path.expanduser",
"re.sub",
"re.compile"
] | [((235, 264), 'os.path.expanduser', 'os.path.expanduser', (['file_path'], {}), '(file_path)\n', (253, 264), False, 'import os\n'), ((324, 347), 're.compile', 're.compile', (['regex_match'], {}), '(regex_match)\n', (334, 347), False, 'import re\n'), ((745, 773), 're.sub', 're.sub', (['"""ι\\\\+"""', '"""ϊ"""', 'tlg_str'... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('comm', '0019_customtextconfig_use_in_report'),
]
operations = [
migrations.AlterModelOptions(
name='service',
... | [
"django.db.models.IntegerField",
"django.db.migrations.AlterModelOptions",
"django.db.models.BooleanField"
] | [((260, 420), 'django.db.migrations.AlterModelOptions', 'migrations.AlterModelOptions', ([], {'name': '"""service"""', 'options': "{'ordering': ['-display_prioirity'], 'verbose_name': 'posługa',\n 'verbose_name_plural': 'posługi'}"}), "(name='service', options={'ordering': [\n '-display_prioirity'], 'verbose_name... |
#!/usr/bin/env python
import os
import sys
import site
ROOT = os.path.dirname(os.path.abspath(__file__))
path = lambda *a: os.path.join(ROOT, *a)
prev_sys_path = list(sys.path)
site.addsitedir(path('vendor'))
site.addsitedir(path('vendor/lib/python'))
site.addsitedir(path('apps'))
site.addsitedir(path('lib'))
site.... | [
"os.path.abspath",
"sys.path.remove",
"django.core.management.execute_manager",
"settings.MIDDLEWARE_CLASSES.remove",
"django.core.management.setup_environ",
"settings.INSTALLED_APPS.remove",
"sys.stderr.write",
"os.path.join"
] | [((1599, 1622), 'django.core.management.setup_environ', 'setup_environ', (['settings'], {}), '(settings)\n', (1612, 1622), False, 'from django.core.management import execute_manager, setup_environ\n'), ((80, 105), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (95, 105), False, 'import os\n')... |
import resources as res
import numpy as np
import nltk
class Feature(object):
dataset = None
def __init__(self, dataset):
self.dataset = dataset
def run(self):
array = []
for text in self.dataset:
bigrams = 0
counter = 0
words = nltk.word_tok... | [
"numpy.matrix",
"nltk.word_tokenize"
] | [((800, 816), 'numpy.matrix', 'np.matrix', (['array'], {}), '(array)\n', (809, 816), True, 'import numpy as np\n'), ((307, 331), 'nltk.word_tokenize', 'nltk.word_tokenize', (['text'], {}), '(text)\n', (325, 331), False, 'import nltk\n')] |
from __future__ import absolute_import
import numpy
import orange, statc
from . import stats
def mean(l):
return float(sum(l))/len(l)
class MA_pearsonCorrelation:
"""
Calling an object of this class computes Pearson correlation of all
attributes against class.
"""
def __call__(self, i, data... | [
"numpy.ma.sum",
"numpy.abs",
"numpy.sum",
"orange.ExampleTable",
"statc.mean",
"numpy.ma.where",
"random.shuffle",
"numpy.ones",
"numpy.clip",
"numpy.ma.log",
"numpy.ma.mean",
"numpy.ma.transpose",
"numpy.linalg.solve",
"numpy.ma.asarray",
"Orange.orng.orngMisc.progressBarMilestones",
... | [((12178, 12231), 'numpy.ma.concatenate', 'ma.concatenate', (['arrays', '(dim if dim is not None else 0)'], {}), '(arrays, dim if dim is not None else 0)\n', (12192, 12231), True, 'import numpy.ma as ma\n'), ((13455, 13480), 'numpy.ma.sum', 'ma.sum', (['observed', '(dim + 1)'], {}), '(observed, dim + 1)\n', (13461, 134... |
from __future__ import print_function
from PIL import Image
import numpy as np
import os
import cv2
import torch
import torch.nn.functional as F
import torchvision
import torchvision.transforms.functional as TF
import math
import pickle
class ImageTransformer(object):
"""
Rescale the image in a sample to a gi... | [
"pickle.dump",
"torchvision.transforms.functional.to_tensor",
"numpy.ones",
"pickle.load",
"shutil.rmtree",
"torch.nn.functional.pad",
"torch.ones",
"os.path.dirname",
"numpy.transpose",
"os.path.exists",
"torch.FloatTensor",
"numpy.max",
"torch.Tensor",
"cv2.resize",
"numpy.repeat",
"... | [((3155, 3188), 'numpy.zeros', 'np.zeros', (['(bs, 4)'], {'dtype': 'np.int32'}), '((bs, 4), dtype=np.int32)\n', (3163, 3188), True, 'import numpy as np\n'), ((3201, 3233), 'numpy.ones', 'np.ones', (['(bs,)'], {'dtype': 'np.float32'}), '((bs,), dtype=np.float32)\n', (3208, 3233), True, 'import numpy as np\n'), ((4872, 4... |
# -*- coding: utf-8 -*-
"""
Profile: http://hl7.org/fhir/StructureDefinition/MedicinalProductUndesirableEffect
Release: R4
Version: 4.0.1
Build ID: 9346c8cc45
Last updated: 2019-11-01T09:29:23.356+11:00
"""
from typing import List as ListType
from pydantic import Field
from . import domainresource, fhirtypes
class ... | [
"pydantic.Field"
] | [((701, 755), 'pydantic.Field', 'Field', (['"""MedicinalProductUndesirableEffect"""'], {'const': '(True)'}), "('MedicinalProductUndesirableEffect', const=True)\n", (706, 755), False, 'from pydantic import Field\n'), ((809, 927), 'pydantic.Field', 'Field', (['None'], {'alias': '"""classification"""', 'title': '"""Classi... |
from datetime import datetime
import boto3
from django.conf import settings
def invalidate_paths(path_list):
if not hasattr(settings, 'ZAPPA_STAGE'):
return
cloudfront = boto3.client('cloudfront')
cloudfront.create_invalidation(
DistributionId=settings.AWS_CLOUD_FRONT_ID,
Invalid... | [
"datetime.datetime.now",
"boto3.client"
] | [((189, 215), 'boto3.client', 'boto3.client', (['"""cloudfront"""'], {}), "('cloudfront')\n", (201, 215), False, 'import boto3\n'), ((511, 525), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (523, 525), False, 'from datetime import datetime\n')] |
from django.forms import ModelForm
from ftft.canzoni.models import canzone
from django import forms
class songform(ModelForm):
gruppo = forms.CharField()
genere = forms.CharField()
def __init__(self, *args, **kwargs):
super(songform, self).__init__(*args, **kwargs)
# Making name required
... | [
"django.forms.CharField"
] | [((141, 158), 'django.forms.CharField', 'forms.CharField', ([], {}), '()\n', (156, 158), False, 'from django import forms\n'), ((169, 186), 'django.forms.CharField', 'forms.CharField', ([], {}), '()\n', (184, 186), False, 'from django import forms\n')] |
# modusite
# Copyright (c) 2006-2010 <NAME>
# http://modu.bubblehouse.org
#
#
from modu.persist import storable, sql
from modusite.model import release
class Project(storable.Storable):
def __init__(self):
super(Project, self).__init__('project')
def get_releases(self):
store = self.get_store()
store.ensure... | [
"modu.persist.sql.RAW"
] | [((439, 467), 'modu.persist.sql.RAW', 'sql.RAW', (['"""IFNULL(%s, 0) = 0"""'], {}), "('IFNULL(%s, 0) = 0')\n", (446, 467), False, 'from modu.persist import storable, sql\n')] |
import random
from game.board import Board
def minimax(board: Board, depth, max_player):
if depth == 0 or board.winner() != 0:
# max_player = True <--- FOX
return evaluate(board), 0 # [(0,0), (0,0)]
moves = all_moves(board, max_player)
random.shuffle(moves)
if max_player:
v... | [
"random.shuffle"
] | [((269, 290), 'random.shuffle', 'random.shuffle', (['moves'], {}), '(moves)\n', (283, 290), False, 'import random\n')] |
import six
from tabulate import tabulate
__all__ = ["dict_to_string", "merge_as_list",
"ask_to_proceed_with_overwrite", "create_table"]
def create_table(small_dict):
"""
Create a small table using the keys of small_dict as headers. This is only
suitable for small dictionaries.
Args:
small_dic... | [
"tabulate.tabulate",
"six.moves.input"
] | [((491, 599), 'tabulate.tabulate', 'tabulate', (['[values]'], {'headers': 'keys', 'tablefmt': '"""pipe"""', 'floatfmt': '""".3f"""', 'stralign': '"""center"""', 'numalign': '"""center"""'}), "([values], headers=keys, tablefmt='pipe', floatfmt='.3f', stralign=\n 'center', numalign='center')\n", (499, 599), False, 'fr... |
# coding: utf-8
from __future__ import unicode_literals
import re
from functools import partial
alphabet_ru = {
'а': 'а',
'б': 'б6',
'в': 'в',
'г': 'г',
'д': 'д',
'е': 'е',
'ё': 'ё',
'ж': 'ж',
'з': 'з',
'и': 'и',
'й': 'й',
'к': 'к',
'л': 'л',
'м': 'м',
'н':... | [
"functools.partial"
] | [((702, 742), 'functools.partial', 'partial', (['variants_of_letter', 'alphabet_ru'], {}), '(variants_of_letter, alphabet_ru)\n', (709, 742), False, 'from functools import partial\n')] |