code stringlengths 20 1.04M | apis list | extract_api stringlengths 75 9.94M |
|---|---|---|
import pytest
"""
RDMA test cases may require variety of fixtures. This
file currently holds the following fixture(s):
1. prio_dscp_map
2. all_prio_list
3. lossless_prio_list
4. lossy_prio_list
"""
@pytest.fixture(scope="module")
def prio_dscp_map(duthosts, rand_one_dut_hostname):
"""
This fi... | [
"pytest.fixture"
] | [((218, 248), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (232, 248), False, 'import pytest\n'), ((1317, 1347), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (1331, 1347), False, 'import pytest\n'), ((1617, 1647), 'pytest.fixtur... |
import torch.nn as nn
import torch
from torchvision.models.densenet import _DenseLayer
from .arch_32x32 import Bottleneck, BasicBlock, \
ShuffleBottleneck
def save_model(model, path):
if path is None:
return
torch.save(model.state_dict(), path)
def count_parameters(model):
return sum(lay... | [
"torch.nn.Conv2d"
] | [((925, 977), 'torch.nn.Conv2d', 'nn.Conv2d', (['c_i', 'c_o', '(k_h, k_w)'], {'stride': '(1)', 'padding': '(0)'}), '(c_i, c_o, (k_h, k_w), stride=1, padding=0)\n', (934, 977), True, 'import torch.nn as nn\n')] |
from django.conf.urls import include, url
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path("", include("store.urls")),
path('', include("registration.url... | [
"django.urls.path",
"django.urls.include"
] | [((212, 243), 'django.urls.path', 'path', (['"""admin/"""', 'admin.site.urls'], {}), "('admin/', admin.site.urls)\n", (216, 243), False, 'from django.urls import path, include\n'), ((258, 279), 'django.urls.include', 'include', (['"""store.urls"""'], {}), "('store.urls')\n", (265, 279), False, 'from django.urls import ... |
#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Tests for module csv_merger."""
import csv
import csv_merger
import os
import test_utils
import unittest
ACTUAL_OUTPUT_FILENA... | [
"unittest.main",
"os.remove",
"os.path.realpath",
"test_utils.assertCSVs",
"csv_merger.CsvMerger",
"os.path.join"
] | [((1617, 1632), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1630, 1632), False, 'import unittest\n'), ((556, 612), 'os.path.join', 'os.path.join', (['self._test_csv_dir', 'ACTUAL_OUTPUT_FILENAME'], {}), '(self._test_csv_dir, ACTUAL_OUTPUT_FILENAME)\n', (568, 612), False, 'import os\n'), ((679, 709), 'os.remove... |
# Copyright (c) 2013 OpenStack Foundation
# 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 ... | [
"oslo_log.log.getLogger",
"neutron.conf.plugins.ml2.drivers.driver_type.register_ml2_drivers_vxlan_opts"
] | [((979, 1002), 'oslo_log.log.getLogger', 'log.getLogger', (['__name__'], {}), '(__name__)\n', (992, 1002), False, 'from oslo_log import log\n'), ((1004, 1049), 'neutron.conf.plugins.ml2.drivers.driver_type.register_ml2_drivers_vxlan_opts', 'driver_type.register_ml2_drivers_vxlan_opts', ([], {}), '()\n', (1047, 1049), F... |
from test.util_platforms import linux_only_forall
import os
import sys
import pytest
import pickle
import os.path as p
import subprocess as sp
linux_only_forall()
class TestDDPPlugin:
def test_all(self, tmpdir):
test_save_path = str(p.join(tmpdir.make_numbered_dir(), "test.save"))
env = os.envir... | [
"os.path.abspath",
"os.environ.copy",
"pytest.fail",
"test.util_platforms.linux_only_forall",
"pickle.load"
] | [((145, 164), 'test.util_platforms.linux_only_forall', 'linux_only_forall', ([], {}), '()\n', (162, 164), False, 'from test.util_platforms import linux_only_forall\n'), ((312, 329), 'os.environ.copy', 'os.environ.copy', ([], {}), '()\n', (327, 329), False, 'import os\n'), ((1230, 1247), 'os.environ.copy', 'os.environ.c... |
from worms import *
from worms.data import poselib
from worms.vis import showme
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
from concurrent.futures.process import BrokenProcessPool
from time import perf_counter
import sys
try:
import pyrosetta
HAVE_PYROSETTA = True
except ImportError:... | [
"pyrosetta.init",
"sys.stdout.flush",
"time.perf_counter"
] | [((404, 455), 'pyrosetta.init', 'pyrosetta.init', (['"""-corrections:beta_nov16 -mute all"""'], {}), "('-corrections:beta_nov16 -mute all')\n", (418, 455), False, 'import pyrosetta\n'), ((816, 830), 'time.perf_counter', 'perf_counter', ([], {}), '()\n', (828, 830), False, 'from time import perf_counter\n'), ((1581, 159... |
if __name__ == '__main__':
import run_tests
run_tests.main ()
| [
"run_tests.main"
] | [((48, 64), 'run_tests.main', 'run_tests.main', ([], {}), '()\n', (62, 64), False, 'import run_tests\n')] |
#!/usr/bin/env python3
import logging
import argparse
from vcstools.metadb_utils import write_obs_info, get_obs_array_phase, obs_max_min, calc_ta_fwhm,\
get_best_cal_obs, get_common_obs_metadata, files_available, getmeta
from vcstools.beam_calc import field_of_view
logger = logging.g... | [
"vcstools.metadb_utils.get_common_obs_metadata",
"vcstools.metadb_utils.calc_ta_fwhm",
"argparse.ArgumentParser",
"vcstools.metadb_utils.get_best_cal_obs",
"vcstools.beam_calc.field_of_view",
"vcstools.metadb_utils.write_obs_info",
"vcstools.metadb_utils.obs_max_min",
"vcstools.metadb_utils.files_avai... | [((311, 338), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (328, 338), False, 'import logging\n'), ((380, 457), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Returns information on an input Obs ID"""'}), "(description='Returns information on an input Obs... |
from datetime import datetime
from typing import Any, Callable, Dict, List, Optional
from pystac.utils import str_to_datetime
from shapely.geometry import Polygon, mapping # type: ignore
from stactools.core.io import ReadHrefModifier
from stactools.core.io.xml import XmlElement
from stactools.sentinel1.grd.metadata_... | [
"shapely.geometry.Polygon",
"shapely.geometry.mapping",
"datetime.datetime.strptime",
"stactools.core.io.xml.XmlElement.from_file",
"pystac.utils.str_to_datetime"
] | [((573, 631), 'stactools.core.io.xml.XmlElement.from_file', 'XmlElement.from_file', (['links[0][1].href', 'read_href_modifier'], {}), '(links[0][1].href, read_href_modifier)\n', (593, 631), False, 'from stactools.core.io.xml import XmlElement\n'), ((1833, 1858), 'shapely.geometry.Polygon', 'Polygon', (['footprint_point... |
from django.test import TestCase
from casexml.apps.case.sharedmodels import CommCareCaseIndex
from corehq.apps.accounting.models import (
BillingAccount,
DefaultProductPlan,
SoftwarePlanEdition,
Subscription,
SubscriptionAdjustment,
)
from corehq.apps.accounting.tests import BaseAccountingTest
from ... | [
"corehq.apps.reminders.event_handlers.get_message_template_params",
"corehq.apps.sms.mixin.BackendMapping",
"corehq.apps.accounting.models.Subscription.new_domain_subscription",
"corehq.apps.domain.models.Domain",
"corehq.apps.accounting.models.BillingAccount.get_or_create_account_by_domain",
"casexml.app... | [((1067, 1086), 'corehq.apps.domain.models.Domain', 'Domain', ([], {'name': '"""test"""'}), "(name='test')\n", (1073, 1086), False, 'from corehq.apps.domain.models import Domain\n'), ((1180, 1211), 'corehq.apps.domain.models.Domain.get', 'Domain.get', (['self.domain_obj._id'], {}), '(self.domain_obj._id)\n', (1190, 121... |
#! /usr/bin/env python
# The MIT License (MIT)
#
# Copyright (c) 2015, EPFL Reconfigurable Robotics Laboratory,
# <NAME>, <EMAIL>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
#... | [
"numpy.power"
] | [((1863, 1879), 'numpy.power', 'np.power', (['L', '(2.0)'], {}), '(L, 2.0)\n', (1871, 1879), True, 'import numpy as np\n'), ((2011, 2028), 'numpy.power', 'np.power', (['Lm', '(2.0)'], {}), '(Lm, 2.0)\n', (2019, 2028), True, 'import numpy as np\n'), ((2066, 2083), 'numpy.power', 'np.power', (['Lm', '(4.0)'], {}), '(Lm, ... |
#!/usr/bin/env python3
import os
from PyQt5.QtCore import Qt, QEvent, QFileSystemWatcher
from PyQt5.QtWidgets import QMainWindow, QApplication
from observer.calibration_optimizer import CalibrationOptimizer
from observer.core.camera_controller import CameraController
from observer.core.closest_vertex_selector impor... | [
"widget.sidebar_widget.SideBarWidget",
"observer.free_shape_adder.FreeShapeAdder",
"os.path.dirname",
"observer.core.closest_vertex_selector.ClosestVertexSelector",
"observer.core.keyboard_observer.KeyboardObserver",
"observer.event.event_handler.EventHandler",
"observer.layer_manager.LayerManager",
"... | [((1287, 1305), 'observer.event.event_handler.EventHandler', 'EventHandler', (['self'], {}), '(self)\n', (1299, 1305), False, 'from observer.event.event_handler import EventHandler\n'), ((1828, 1852), 'PyQt5.QtCore.QFileSystemWatcher', 'QFileSystemWatcher', (['self'], {}), '(self)\n', (1846, 1852), False, 'from PyQt5.Q... |
import unittest
from knowledge_repo import KnowledgeRepository
class RouteTest(unittest.TestCase):
def setUp(self):
self.repo = KnowledgeRepository.for_uri('tests/test_repo', auto_create=True)
self.app = self.repo.get_app(config='tests/config_server.py').test_client()
self.headers = {}
... | [
"unittest.main",
"knowledge_repo.KnowledgeRepository.for_uri"
] | [((1169, 1184), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1182, 1184), False, 'import unittest\n'), ((144, 208), 'knowledge_repo.KnowledgeRepository.for_uri', 'KnowledgeRepository.for_uri', (['"""tests/test_repo"""'], {'auto_create': '(True)'}), "('tests/test_repo', auto_create=True)\n", (171, 208), False, '... |
import pkg_resources
from sharding.contracts.utils.smc_utils import ( # noqa: F401
get_smc_source_code,
get_smc_json,
)
from sharding.handler.log_handler import ( # noqa: F401
LogHandler,
)
from sharding.handler.shard_tracker import ( # noqa: F401
ShardTracker,
)
from sharding.handler.smc_handler i... | [
"pkg_resources.get_distribution"
] | [((369, 411), 'pkg_resources.get_distribution', 'pkg_resources.get_distribution', (['"""sharding"""'], {}), "('sharding')\n", (399, 411), False, 'import pkg_resources\n')] |
from collections import defaultdict
from datetime import datetime
# Columns:
# transaction date, product name, price,
# payment type, customer name, city,
# state, country, account creation date, last login
FILENAME = './sales.csv'
TRANSACTION_INDEX = 0
PRICE_INDEX = 2
PAYMENT_TYPE_INDEX = 3
CITY_INDEX = 5
COUNTRY_I... | [
"collections.defaultdict",
"datetime.datetime"
] | [((381, 398), 'collections.defaultdict', 'defaultdict', (['dict'], {}), '(dict)\n', (392, 398), False, 'from collections import defaultdict\n'), ((1389, 1430), 'datetime.datetime', 'datetime', ([], {'year': 'year', 'month': 'month', 'day': 'day'}), '(year=year, month=month, day=day)\n', (1397, 1430), False, 'from datet... |
import tensorflow as tf
from tensorflow.keras import layers, Input, Model
def build_dce_net() -> Model:
input_image = Input(shape=[None, None, 3])
conv1 = layers.Conv2D(
32, (3, 3), strides=(1, 1), activation="relu", padding="same"
)(input_image)
conv2 = layers.Conv2D(
32, (3, 3), stri... | [
"tensorflow.keras.Model",
"tensorflow.keras.Input",
"tensorflow.keras.layers.Conv2D",
"tensorflow.keras.layers.Concatenate"
] | [((124, 152), 'tensorflow.keras.Input', 'Input', ([], {'shape': '[None, None, 3]'}), '(shape=[None, None, 3])\n', (129, 152), False, 'from tensorflow.keras import layers, Input, Model\n'), ((1124, 1162), 'tensorflow.keras.Model', 'Model', ([], {'inputs': 'input_image', 'outputs': 'x_r'}), '(inputs=input_image, outputs=... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torch.nn.modules import activation
from torch.nn.modules.pooling import MaxPool1d, MaxPool2d
# Helper function to print dimensions of layer
class PrintSize(nn.Module):
def __init__(self):
super(PrintSize, self).__init__()
... | [
"torch.nn.Dropout",
"torch.nn.ReLU",
"torch.nn.Conv2d",
"torch.nn.Linear",
"torch.nn.BatchNorm2d",
"torch.nn.Softmax",
"torch.rand",
"torch.nn.MaxPool2d",
"torch.nn.Flatten"
] | [((1438, 1466), 'torch.rand', 'torch.rand', (['(1, 3, 256, 256)'], {}), '((1, 3, 256, 256))\n', (1448, 1466), False, 'import torch\n'), ((474, 519), 'torch.nn.Conv2d', 'nn.Conv2d', (['(3)', '(64)', '(3)'], {'stride': '(1)', 'padding': '"""same"""'}), "(3, 64, 3, stride=1, padding='same')\n", (483, 519), True, 'import t... |
import re
from copy import deepcopy
from xml.sax.saxutils import escape
from bs4 import BeautifulSoup, NavigableString
from ..base import (
BaseReader, BaseWriter, CaptionSet, CaptionList, Caption, CaptionNode,
DEFAULT_LANGUAGE_CODE)
from ..exceptions import (
CaptionReadNoCaptions, CaptionReadSyntaxError,... | [
"copy.deepcopy",
"xml.sax.saxutils.escape",
"bs4.BeautifulSoup",
"re.search",
"re.compile"
] | [((9730, 9773), 'bs4.BeautifulSoup', 'BeautifulSoup', (['DFXP_BASE_MARKUP', '"""lxml-xml"""'], {}), "(DFXP_BASE_MARKUP, 'lxml-xml')\n", (9743, 9773), False, 'from bs4 import BeautifulSoup, NavigableString\n'), ((9940, 9961), 'copy.deepcopy', 'deepcopy', (['caption_set'], {}), '(caption_set)\n', (9948, 9961), False, 'fr... |
# Copyright 2018 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 applica... | [
"keras.optimizers.optimizer_v2.adamax.Adamax",
"tensorflow.compat.v2.pow",
"numpy.abs",
"numpy.copy",
"tensorflow.compat.v2.test.main",
"tensorflow.compat.v2.constant",
"tensorflow.compat.v2.gather",
"tensorflow.compat.v2.cast",
"numpy.zeros",
"tensorflow.compat.v2.Graph",
"numpy.array",
"kera... | [((2233, 2267), 'tensorflow.compat.v2.cast', 'tf.cast', (['(opt.iterations + 1)', 'dtype'], {}), '(opt.iterations + 1, dtype)\n', (2240, 2267), True, 'import tensorflow.compat.v2 as tf\n'), ((2339, 2367), 'tensorflow.compat.v2.pow', 'tf.pow', (['beta_1_t', 'local_step'], {}), '(beta_1_t, local_step)\n', (2345, 2367), T... |
# -*- coding: utf-8 -*-
import sys
sys.dont_write_bytecode
import acitoolkit.acitoolkit as aci
def validate_partecipants(course_partecipants):
if course_partecipants < 1:
raise Exception(' !!! The number of course partecipants should be a positive integer! Input value: {} '.format(course_partecipants)... | [
"acitoolkit.acitoolkit.Contract",
"acitoolkit.acitoolkit.EPG",
"acitoolkit.acitoolkit.FilterEntry",
"acitoolkit.acitoolkit.Session",
"acitoolkit.acitoolkit.Credentials",
"acitoolkit.acitoolkit.Context",
"acitoolkit.acitoolkit.BridgeDomain"
] | [((1856, 1892), 'acitoolkit.acitoolkit.Credentials', 'aci.Credentials', (['"""apic"""', 'description'], {}), "('apic', description)\n", (1871, 1892), True, 'import acitoolkit.acitoolkit as aci\n'), ((2090, 2138), 'acitoolkit.acitoolkit.Session', 'aci.Session', (['args.url', 'args.login', 'args.password'], {}), '(args.u... |
import json
from typing import Sequence
import falcon
from people.people_application import DeletePersonObserver
from people.people_application import PeopleApplication, CreatePersonObserver
from people.people_application import PresentPeopleObserver
from people.people_application import PresentPersonObserver
from peo... | [
"json.dumps"
] | [((2303, 2407), 'json.dumps', 'json.dumps', (["{'type': 'person_list', 'data': [{'id': p.identifier, 'name': p.name} for p in\n people]}"], {}), "({'type': 'person_list', 'data': [{'id': p.identifier, 'name': p.\n name} for p in people]})\n", (2313, 2407), False, 'import json\n'), ((2685, 2775), 'json.dumps', 'js... |
from lollipop.compat import iterkeys, itervalues, iteritems
from lollipop.utils import call_with_context, to_camel_case, to_snake_case, \
constant, identity, OpenStruct, DictWithDefault
import pytest
class ObjMethodDummy:
def __init__(self):
self.args = None
def foo(self, a, b, c):
self.a... | [
"lollipop.utils.to_snake_case",
"lollipop.compat.iterkeys",
"lollipop.utils.to_camel_case",
"lollipop.utils.OpenStruct",
"lollipop.utils.call_with_context",
"pytest.raises",
"lollipop.compat.itervalues",
"lollipop.compat.iteritems",
"lollipop.utils.identity",
"lollipop.utils.constant",
"lollipop... | [((1247, 1289), 'lollipop.utils.call_with_context', 'call_with_context', (['func', 'context', '(1)', '"""foo"""'], {}), "(func, context, 1, 'foo')\n", (1264, 1289), False, 'from lollipop.utils import call_with_context, to_camel_case, to_snake_case, constant, identity, OpenStruct, DictWithDefault\n'), ((1746, 1791), 'lo... |
# This script processes a set of images and returns a set of camera poses
# and a point cloud 3D model estimated by Agisoft Metashape.
#
# Desined for Agisoft Metashape Professional 1.6.4
# (may be compatible with other versions: refer to Metashape Python API, https://www.agisoft.com/)
# How to run this script:
# ... | [
"Metashape.app.update",
"Metashape.Document",
"os.makedirs",
"argparse.ArgumentParser",
"PIL.Image.open",
"os.path.join"
] | [((532, 579), 'os.path.join', 'os.path.join', (['args.in_dir', '"""images_undistorted"""'], {}), "(args.in_dir, 'images_undistorted')\n", (544, 579), False, 'import os\n'), ((584, 623), 'os.makedirs', 'os.makedirs', (['frames_path'], {'exist_ok': '(True)'}), '(frames_path, exist_ok=True)\n', (595, 623), False, 'import ... |
## @package transient_data
#
# @brief Read TransientData from CLEERS team
#
# @details Python script to read in CLEERS transient data for
# NH3 storage on Cu-SSZ-13. This script will store the
# orginal data as is and provide other functions to
# redistribute, print, or parse that data as needed.
#
# ... | [
"random.gauss",
"os.makedirs",
"matplotlib.pyplot.plot",
"os.stat",
"math.sqrt",
"matplotlib.pyplot.close",
"matplotlib.pyplot.legend",
"os.path.exists",
"scipy.stats.norm.pdf",
"scipy.optimize.curve_fit",
"matplotlib.pyplot.figure",
"statistics.mean",
"matplotlib.pyplot.ylabel",
"matplotl... | [((8193, 8206), 'os.stat', 'os.stat', (['file'], {}), '(file)\n', (8200, 8206), False, 'import os, sys\n'), ((69386, 69526), 'scipy.optimize.curve_fit', 'curve_fit', (['double_peak_normal', 'xdata', 'ydata', 'p0'], {'bounds': '([xdata[0], 5, 0, xdata[0], 5, 0], [xdata[-1], 15, 10000, xdata[-1], 15, 10000]\n )'}), '(... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import numpy as np
logger = logging.getLogger('causalml')
def synthetic_data(mode=1, n=1000, p=5, sigma=1.0):
''' Synthetic data in <NAME>. and <NAME>. (2018) 'Quasi-Oracle Estimation of H... | [
"numpy.random.uniform",
"numpy.random.binomial",
"numpy.sin",
"numpy.exp",
"numpy.random.normal",
"logging.getLogger",
"numpy.repeat"
] | [((154, 183), 'logging.getLogger', 'logging.getLogger', (['"""causalml"""'], {}), "('causalml')\n", (171, 183), False, 'import logging\n'), ((2802, 2834), 'numpy.random.binomial', 'np.random.binomial', (['(1)', 'e'], {'size': 'n'}), '(1, e, size=n)\n', (2820, 2834), True, 'import numpy as np\n'), ((3932, 3949), 'numpy.... |
# -*- coding: utf-8 -*-
"""
# two DAGs triggering the email error flow
"""
from dag_configuration import default_dag_args
from airflow.operators.python_operator import PythonOperator
from trigger_k8s_cronjob import trigger_k8s_cronjob
from datetime import datetime, timedelta
from airflow import DAG
import os
import sy... | [
"airflow.DAG",
"os.path.basename",
"airflow.operators.python_operator.PythonOperator",
"os.path.dirname",
"datetime.timedelta",
"datetime.datetime.now",
"os.getenv"
] | [((448, 478), 'os.getenv', 'os.getenv', (['"""AIRFLOW_NAMESPACE"""'], {}), "('AIRFLOW_NAMESPACE')\n", (457, 478), False, 'import os\n'), ((707, 803), 'airflow.DAG', 'DAG', (['f"""{DAG_ID}_local_error"""'], {'schedule_interval': 'SCHEDULE_INTERVAL', 'default_args': 'default_args'}), "(f'{DAG_ID}_local_error', schedule_i... |
# Futu Algo: Algorithmic High-Frequency Trading Framework
#
# 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 ap... | [
"pandas.DataFrame",
"util.logger.get_logger"
] | [((1184, 1215), 'util.logger.get_logger', 'logger.get_logger', (['"""macd_cross"""'], {}), "('macd_cross')\n", (1201, 1215), False, 'from util import logger\n'), ((2024, 2082), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['MACD', 'MACD_signal', 'MACD_hist']"}), "(columns=['MACD', 'MACD_signal', 'MACD_hist'])\... |
from nameko.events import event_handler, BROADCAST
import logging, json
logger = logging.getLogger()
class WorkloadGeneratorService(object):
name = 'workload_generator'
@event_handler('emulator', 'codechallenge_checked', handler_type=BROADCAST, reliable_delivery=False)
def codechallenge_checked(self, pa... | [
"nameko.events.event_handler",
"logging.getLogger"
] | [((82, 101), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (99, 101), False, 'import logging, json\n'), ((182, 285), 'nameko.events.event_handler', 'event_handler', (['"""emulator"""', '"""codechallenge_checked"""'], {'handler_type': 'BROADCAST', 'reliable_delivery': '(False)'}), "('emulator', 'codechalle... |
import optuna
for study_name in ['classifier-restaurant', 'classifier-laptop']:
study = optuna.load_study(study_name, storage='sqlite:///optimization.db')
# fig = optuna.visualization.plot_parallel_coordinate(study)
# fig.show()
df = study.trials_dataframe()
complete = df.state == 'COMPLETE'
d... | [
"optuna.load_study"
] | [((93, 159), 'optuna.load_study', 'optuna.load_study', (['study_name'], {'storage': '"""sqlite:///optimization.db"""'}), "(study_name, storage='sqlite:///optimization.db')\n", (110, 159), False, 'import optuna\n')] |
#!/usr/bin/python3
import matplotlib.pyplot as plt
from matplotlib.ticker import NullFormatter
fig, ax = plt.subplots(2, 2)
print(ax, type(ax), len(ax))
x = [10.09950494, 16.43167673, 27.03701167]
ax[0][0].set(title="nSteps", xlabel="sqrt(n_squares)", ylabel="nSteps")
y1 = [15, 36, 185,]
ax[0][0].plot(x, y1, label=... | [
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show"
] | [((107, 125), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(2)'], {}), '(2, 2)\n', (119, 125), True, 'import matplotlib.pyplot as plt\n'), ((1791, 1801), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1799, 1801), True, 'import matplotlib.pyplot as plt\n')] |
import logging
from unittest.mock import Mock, patch
import numpy as np
import pytest
from ophyd.sim import make_fake_device
from pcdsdevices.epics_motor import OffsetMotor
from pcdsdevices.lodcm import (CHI1, CHI2, H1N, H2N, LODCM, Y1, Y2, Dectris,
Diode, Foil, LODCMEnergyC, LODCMEnerg... | [
"pcdsdevices.lodcm.LODCM",
"unittest.mock.Mock",
"pytest.fixture",
"unittest.mock.patch",
"pytest.raises",
"numpy.isclose",
"pytest.mark.timeout",
"ophyd.sim.make_fake_device",
"logging.getLogger"
] | [((415, 442), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (432, 442), False, 'import logging\n'), ((1368, 1400), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (1382, 1400), False, 'import pytest\n'), ((3981, 4013), 'pytest.fixture', 'pyt... |
"""
This is a direct translation of nvvm.h
"""
from __future__ import print_function, absolute_import, division
import sys, logging, re
from ctypes import (c_void_p, c_int, POINTER, c_char_p, c_size_t, byref,
c_char)
import threading
from llvmlite import ir
from numba import config
from .error im... | [
"llvmlite.llvmpy.core.Type.int",
"llvmlite.llvmpy.core.MetaData.get",
"llvmlite.ir.IntType",
"ctypes.c_int",
"ctypes.c_size_t",
"ctypes.byref",
"llvmlite.ir.splitlines",
"llvmlite.llvmpy.core.MetaDataString.get",
"threading.Lock",
"ctypes.POINTER",
"sys.exit",
"logging.getLogger",
"re.compil... | [((426, 453), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (443, 453), False, 'import sys, logging, re\n'), ((1231, 1247), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (1245, 1247), False, 'import threading\n'), ((16889, 16915), 're.compile', 're.compile', (['"""\\\\!\\\\d+\\\\... |
import cattr
from tokopedia.product import CreateProductV3, ResponsesCreateProductV3
def test_create_product_v3():
data = {
"name": "Product Testing V3 1.36",
"condition": "NEW",
"description": "Product Testing Descr V2",
"sku": "TST21",
"price": 10000,
"status": "L... | [
"cattr.structure"
] | [((1058, 1096), 'cattr.structure', 'cattr.structure', (['data', 'CreateProductV3'], {}), '(data, CreateProductV3)\n', (1073, 1096), False, 'import cattr\n'), ((1580, 1627), 'cattr.structure', 'cattr.structure', (['data', 'ResponsesCreateProductV3'], {}), '(data, ResponsesCreateProductV3)\n', (1595, 1627), False, 'impor... |
from __future__ import absolute_import, division, print_function
import pytest
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib.artist import Artist
from numpy.testing import assert_allclose
from matplotlib.backends.backend_agg import FigureCanvasAgg
from glue... | [
"numpy.testing.assert_allclose",
"numpy.zeros",
"matplotlib.patches.Circle",
"matplotlib.pyplot.figure",
"pytest.raises",
"numpy.array",
"pytest.mark.parametrize",
"numpy.testing.assert_array_almost_equal"
] | [((3749, 3873), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (["('color', 'rgb')", "(('red', (1, 0, 0)), ('green', (0, 0.502, 0)), ('orange', (1.0, 0.647, 0.0)))"], {}), "(('color', 'rgb'), (('red', (1, 0, 0)), ('green', (0,\n 0.502, 0)), ('orange', (1.0, 0.647, 0.0))))\n", (3772, 3873), False, 'import pyte... |
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modif... | [
"copy.deepcopy",
"numpy.zeros_like",
"numpy.sum",
"matplotlib.pyplot.show",
"numpy.zeros",
"matplotlib.pyplot.figure",
"numpy.mean",
"matplotlib.pyplot.gca",
"re.search",
"qiskit.QiskitError"
] | [((9987, 10018), 'copy.deepcopy', 'copy.deepcopy', (['new_cal_matrices'], {}), '(new_cal_matrices)\n', (10000, 10018), False, 'import copy\n'), ((13506, 13530), 'numpy.mean', 'np.mean', (['assign_fid_list'], {}), '(assign_fid_list)\n', (13513, 13530), True, 'import numpy as np\n'), ((2710, 2739), 'copy.deepcopy', 'copy... |
import sys
sys.path.append(".")
import torch
from pedrec.configs.pedrec_net_config import PedRecNet50Config
from pedrec.utils.torch_utils.torch_helper import get_device
from pedrec.networks.net_pedrec.pedrec_net import PedRecNet, PedRecNetLossHead
from pedrec.networks.net_pedrec.pedrec_net_mtl_wrapper import PedRecNet... | [
"sys.path.append",
"pedrec.networks.net_pedrec.pedrec_net.PedRecNetLossHead",
"pedrec.networks.net_pedrec.pedrec_net.PedRecNet",
"pedrec.configs.pedrec_net_config.PedRecNet50Config",
"pedrec.utils.torch_utils.torch_helper.get_device",
"torch.load"
] | [((11, 31), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (26, 31), False, 'import sys\n'), ((569, 588), 'pedrec.configs.pedrec_net_config.PedRecNet50Config', 'PedRecNet50Config', ([], {}), '()\n', (586, 588), False, 'from pedrec.configs.pedrec_net_config import PedRecNet50Config\n'), ((602, 618),... |
if __name__ == '__main__':
import ch02_04_mod as mymod
tpt = float(input('輸入攝氏溫度,轉華氏溫度: '))
print('華氏溫度=' + str(mymod.ctof(tpt)))
tpt = float(input('輸入華氏溫度,轉攝氏溫度: '))
print('攝氏溫度=' + str(mymod.ftoc(tpt)))
'''
輸入攝氏溫度,轉華氏溫度: 33
華氏溫度=91.4
輸入華氏溫度,轉攝氏溫度: 91.4
攝氏溫度=33.0
'''
| [
"ch02_04_mod.ftoc",
"ch02_04_mod.ctof"
] | [((134, 149), 'ch02_04_mod.ctof', 'mymod.ctof', (['tpt'], {}), '(tpt)\n', (144, 149), True, 'import ch02_04_mod as mymod\n'), ((218, 233), 'ch02_04_mod.ftoc', 'mymod.ftoc', (['tpt'], {}), '(tpt)\n', (228, 233), True, 'import ch02_04_mod as mymod\n')] |
# https://www.youtube.com/watch?v=-i5YrgqF9Gg
import random
def grade_assignment():
grade = random.randint(70, 100)
return grade
male_superiority = 0
female_superiority = 0
equal_skill = 0
iterations = 100000
progress_marker = 0.05
while male_superiority + female_superiority < iterations:
if (male_sup... | [
"random.randint"
] | [((99, 122), 'random.randint', 'random.randint', (['(70)', '(100)'], {}), '(70, 100)\n', (113, 122), False, 'import random\n')] |
from re import X
import select, socket, sys, util
from banner import Ascii_Banner
READ_BUFFER = 4096
if len(sys.argv) < 2:
print("Usage: Python3 client.py [hostname]", file = sys.stderr)
sys.exit(1)
else:
server_connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_connection.setsockop... | [
"banner.Ascii_Banner.colored_banner",
"socket.socket",
"util.QUIT_STRING.encode",
"select.select",
"sys.stdin.readline",
"sys.exit"
] | [((197, 208), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (205, 208), False, 'import select, socket, sys, util\n'), ((239, 288), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (252, 288), False, 'import select, socket, sys, util\n'), ((665... |
import numpy as np
import random
from collections import namedtuple, deque
# from model import QNetwork
from dynamic_model import QNetwork
import torch
import torch.nn.functional as F
import torch.optim as optim
BUFFER_SIZE = int(1e5) # replay buffer size
BATCH_SIZE = 64 # minibatch size
GAMMA = 0.99 ... | [
"random.sample",
"torch.nn.functional.mse_loss",
"dynamic_model.QNetwork",
"random.random",
"random.seed",
"torch.cuda.is_available",
"collections.namedtuple",
"numpy.arange",
"numpy.vstack",
"torch.no_grad",
"collections.deque",
"torch.from_numpy"
] | [((581, 606), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (604, 606), False, 'import torch\n'), ((1081, 1098), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (1092, 1098), False, 'import random\n'), ((7811, 7844), 'torch.nn.functional.mse_loss', 'F.mse_loss', (['Q_expected', 'Q_ta... |
"""
封装Assert方法
"""
from common import consts
import json
from common.logger import Logger
my_log = Logger(logger='Assertions').get_log()
class Assertions:
def __init__(self):
pass
def assert_code(self, code, expected_code):
"""
验证response状态码
:param code:
:param expec... | [
"common.consts.RESULT_LIST.append",
"common.logger.Logger",
"json.dumps"
] | [((103, 130), 'common.logger.Logger', 'Logger', ([], {'logger': '"""Assertions"""'}), "(logger='Assertions')\n", (109, 130), False, 'from common.logger import Logger\n'), ((1354, 1390), 'json.dumps', 'json.dumps', (['body'], {'ensure_ascii': '(False)'}), '(body, ensure_ascii=False)\n', (1364, 1390), False, 'import json... |
from PreProcessor import PreProcessor, dataset_path
import pandas as pd
def convert_imbd_to_csv(file_lst, output_name):
df = pd.DataFrame(columns=["review_id", "train_or_test", "review_type", "review_number", "sentence"])
for file in file_lst:
with open(file, "r") as f:
detail = file.stem... | [
"pandas.DataFrame",
"PreProcessor.PreProcessor",
"PreProcessor.dataset_path.joinpath"
] | [((1109, 1156), 'PreProcessor.PreProcessor', 'PreProcessor', (['imdb_raw_df', 'common_words', '"""imdb"""'], {}), "(imdb_raw_df, common_words, 'imdb')\n", (1121, 1156), False, 'from PreProcessor import PreProcessor, dataset_path\n'), ((131, 231), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['review_id', 'trai... |
"""
Generate the 1D Laplace spectra for the decane-water data.
@author <NAME>
"""
from scipy.io import loadmat
from scipy.interpolate import interp1d
import theme.colors as thc
import theme.figure_settings as tfs
import os
from matplotlib.pyplot import *
from numpy import squeeze, array, linspace, transpose
# Gene... | [
"os.path.join",
"scipy.io.loadmat",
"theme.figure_settings.make_new_fig",
"numpy.linspace",
"numpy.squeeze",
"theme.figure_settings.setup_environment"
] | [((353, 469), 'theme.figure_settings.setup_environment', 'tfs.setup_environment', ([], {'figsize': 'fsize', 'dpi': '(150)', 'legend_fs': '(9)', 'tick_fs': '(8)', 'label_fs': '(12)', 'ann_fs': '(12)', 'n_legend_points': '(1)'}), '(figsize=fsize, dpi=150, legend_fs=9, tick_fs=8,\n label_fs=12, ann_fs=12, n_legend_poin... |
"""
This module represents the Consumer.
Computer Systems Architecture Course
Assignment 1
March 2021
"""
from threading import Thread
import time
import logging
class Consumer(Thread):
"""
Class that represents a consumer.
"""
def __init__(self, carts, marketplace, retry_wait_time, **kwargs):
... | [
"threading.Thread.__init__",
"time.sleep"
] | [((823, 844), 'threading.Thread.__init__', 'Thread.__init__', (['self'], {}), '(self)\n', (838, 844), False, 'from threading import Thread\n'), ((1551, 1583), 'time.sleep', 'time.sleep', (['self.retry_wait_time'], {}), '(self.retry_wait_time)\n', (1561, 1583), False, 'import time\n')] |
from django.db.models import Q
from .models import Team
class TeamPermissionsBackend(object):
def authenticate(self, username=None, password=None):
return None
def get_team_permissions(self, user_obj, obj=None):
"""
Returns a set of permission strings that this user has through his/... | [
"django.db.models.Q"
] | [((576, 605), 'django.db.models.Q', 'Q', ([], {'memberships__user': 'user_obj'}), '(memberships__user=user_obj)\n', (577, 605), False, 'from django.db.models import Q\n'), ((949, 978), 'django.db.models.Q', 'Q', ([], {'memberships__user': 'user_obj'}), '(memberships__user=user_obj)\n', (950, 978), False, 'from django.d... |
import struct
from typing import Callable
from typing import Iterable
from typing import Optional
from typing import Sequence
from typing import Type
from typing import Union
from pyvisa import constants
from pyvisa import errors
from pyvisa import logger
from pyvisa import util
# This file contains modified versio... | [
"pyvisa.logger.debug",
"pyvisa.errors.InvalidBinaryFormat",
"pyvisa.util.from_binary_block",
"struct.calcsize",
"pyvisa.util.parse_ieee_block_header",
"pyvisa.util.parse_hp_block_header"
] | [((6071, 6106), 'pyvisa.util.parse_ieee_block_header', 'util.parse_ieee_block_header', (['block'], {}), '(block)\n', (6099, 6106), False, 'from pyvisa import util\n'), ((7397, 7487), 'pyvisa.util.from_binary_block', 'util.from_binary_block', (['block', 'offset', 'data_length', 'datatype', 'is_big_endian', 'container'],... |
from rest_framework import viewsets
from .models import StockListModel, StockBinModel
from . import serializers
from utils.page import MyPageNumberPagination
from rest_framework.filters import OrderingFilter
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.response import Response
from ... | [
"rest_framework.response.Response",
"datetime.datetime.now",
"rest_framework.exceptions.APIException",
"django.http.StreamingHttpResponse"
] | [((15864, 15878), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (15876, 15878), False, 'from datetime import datetime\n'), ((16229, 16285), 'django.http.StreamingHttpResponse', 'StreamingHttpResponse', (['renderer'], {'content_type': '"""text/csv"""'}), "(renderer, content_type='text/csv')\n", (16250, 1628... |
# Copyright (c) 2012 NTT DOCOMO, INC.
# Copyright (c) 2011 X.commerce, a business unit of eBay Inc.
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "Lic... | [
"nova.virt.baremetal.db.sqlalchemy.session.get_session",
"uuid.uuid4",
"sqlalchemy.sql.expression.asc",
"nova.openstack.common.timeutils.utcnow",
"nova.virt.baremetal.db.sqlalchemy.models.BareMetalInterface",
"nova.exception.NodeNotFoundByUUID",
"nova.virt.baremetal.db.sqlalchemy.models.BareMetalNode",
... | [((6182, 6204), 'nova.virt.baremetal.db.sqlalchemy.models.BareMetalNode', 'models.BareMetalNode', ([], {}), '()\n', (6202, 6204), False, 'from nova.virt.baremetal.db.sqlalchemy import models\n'), ((7186, 7210), 'nova.virt.baremetal.db.sqlalchemy.session.get_session', 'db_session.get_session', ([], {}), '()\n', (7208, 7... |
# -*- coding: utf-8 -*-
"""
DNS server framework - intended to simplify creation of custom resolvers.
Comprises the following components:
DNSServer - socketserver wrapper (in most cases you should just
need to pass this an appropriate resolver instance
an... | [
"threading.Thread",
"binascii.hexlify",
"time.strftime",
"dnslib.DNSRecord.parse",
"doctest.testmod"
] | [((13874, 13919), 'doctest.testmod', 'doctest.testmod', ([], {'optionflags': 'doctest.ELLIPSIS'}), '(optionflags=doctest.ELLIPSIS)\n', (13889, 13919), False, 'import doctest\n'), ((6317, 6338), 'dnslib.DNSRecord.parse', 'DNSRecord.parse', (['data'], {}), '(data)\n', (6332, 6338), False, 'from dnslib import DNSRecord, D... |
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest
import fieldtrial_util
import os
import tempfile
class FieldTrialUtilUnittest(unittest.TestCase):
def runGenerateArgs(self, config, pla... | [
"unittest.main",
"tempfile.NamedTemporaryFile",
"os.unlink",
"fieldtrial_util.GenerateArgs",
"fieldtrial_util.MergeFeaturesAndFieldTrialsArgs"
] | [((6803, 6818), 'unittest.main', 'unittest.main', ([], {}), '()\n', (6816, 6818), False, 'import unittest\n'), ((753, 794), 'fieldtrial_util.GenerateArgs', 'fieldtrial_util.GenerateArgs', (['""""""', '"""linux"""'], {}), "('', 'linux')\n", (781, 794), False, 'import fieldtrial_util\n'), ((5650, 5701), 'fieldtrial_util.... |
"""Build capnproto from source."""
import logging
import foreman
from g1 import scripts
import shipyard2.rules.bases
LOG = logging.getLogger(__name__)
shipyard2.rules.bases.define_git_repo(
'https://github.com/capnproto/capnproto.git',
'v0.9.1',
)
shipyard2.rules.bases.define_distro_packages([
'autoc... | [
"foreman.rule.depend",
"foreman.get_relpath",
"g1.scripts.make",
"g1.scripts.using_sudo",
"g1.scripts.using_cwd",
"g1.scripts.run",
"logging.getLogger"
] | [((128, 155), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (145, 155), False, 'import logging\n'), ((418, 454), 'foreman.rule.depend', 'foreman.rule.depend', (['"""//bases:build"""'], {}), "('//bases:build')\n", (437, 454), False, 'import foreman\n'), ((456, 488), 'foreman.rule.depend',... |
import enum
import typing as ty
from vkquick.bases.filter import Filter
from vkquick.exceptions import FilterFailedError
@enum.unique
class EventHandlingStatus(enum.Enum):
"""Возможные статусы обработки"""
INCORRECT_EVENT_TYPE = enum.auto()
"""
Тип события не обрабатывается этим хэндлером
"""
... | [
"enum.auto"
] | [((241, 252), 'enum.auto', 'enum.auto', ([], {}), '()\n', (250, 252), False, 'import enum\n'), ((339, 350), 'enum.auto', 'enum.auto', ([], {}), '()\n', (348, 350), False, 'import enum\n'), ((443, 454), 'enum.auto', 'enum.auto', ([], {}), '()\n', (452, 454), False, 'import enum\n'), ((538, 549), 'enum.auto', 'enum.auto'... |
# Generated by Django 2.0.3 on 2018-03-12 17:19
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('game', '0006_auto_20180312_1949'),
]
operations = [
migrations.AddField(
model_name='game',
... | [
"django.db.models.ForeignKey"
] | [((366, 504), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'blank': '(True)', 'null': '(True)', 'on_delete': 'django.db.models.deletion.SET_NULL', 'related_name': '"""leaded_games"""', 'to': '"""game.Player"""'}), "(blank=True, null=True, on_delete=django.db.models.\n deletion.SET_NULL, related_name='le... |
import math
from collections import defaultdict
from typing import Dict, DefaultDict, List
import logging
from bitmex_futures_arbitrage.const import XBTM20, XBTU20
from bitmex_futures_arbitrage.models import Quote, Direction, Order, OrderKind
logger = logging.getLogger()
class PaperOrdersExecutor:
""" dealing w... | [
"collections.defaultdict",
"math.floor",
"logging.getLogger",
"math.ceil"
] | [((254, 273), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (271, 273), False, 'import logging\n'), ((463, 480), 'collections.defaultdict', 'defaultdict', (['dict'], {}), '(dict)\n', (474, 480), False, 'from collections import defaultdict\n'), ((537, 555), 'collections.defaultdict', 'defaultdict', (['floa... |
# Copyright 2016 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 applicable ... | [
"tensorflow.rank",
"tensorflow.greater_equal",
"tensorflow.reshape",
"tensorflow.concat",
"tensorflow.to_int32",
"tensorflow.shape",
"tensorflow.to_float",
"tensorflow.squeeze",
"tensorflow.pack",
"tensorflow.slice",
"tensorflow.greater",
"tensorflow.split",
"tensorflow.expand_dims",
"tens... | [((2080, 2112), 'tensorflow.split', 'tf.split', (['(2)', 'num_channels', 'image'], {}), '(2, num_channels, image)\n', (2088, 2112), True, 'import tensorflow as tf\n'), ((2182, 2204), 'tensorflow.concat', 'tf.concat', (['(2)', 'channels'], {}), '(2, channels)\n', (2191, 2204), True, 'import tensorflow as tf\n'), ((2844,... |
#!/usr/bin/env python -O
# -*- coding: ascii -*-
import argparse
import numpy as np
import os
import signal
import sys
from domains import *
from learners import *
def main(args):
global siginfo_message
all_msve = np.ones((args['num_seeds'], args['num_steps'])) * np.nan
all_lambda = np.copy(all_msve)
... | [
"numpy.save",
"argparse.ArgumentParser",
"numpy.copy",
"numpy.seterr",
"os.path.exists",
"numpy.ones",
"numpy.random.RandomState"
] | [((301, 318), 'numpy.copy', 'np.copy', (['all_msve'], {}), '(all_msve)\n', (308, 318), True, 'import numpy as np\n'), ((2167, 2192), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2190, 2192), False, 'import argparse\n'), ((2934, 3006), 'numpy.seterr', 'np.seterr', ([], {'divide': '"""raise"""... |
#!/usr/bin/env python
import sys
import argparse
import os
import subprocess
import argparse
import json
from typing import Dict
ca_cert = ""
with open("test/cert-ledger-anchor.cert", "r", encoding='utf-8') as ca_encoded:
ca_cert = ca_encoded.read()
with open("test/client.conf.example", "r+", encoding='utf-8') a... | [
"json.loads",
"json.dumps"
] | [((388, 409), 'json.loads', 'json.loads', (['json_data'], {}), '(json_data)\n', (398, 409), False, 'import json\n'), ((511, 544), 'json.dumps', 'json.dumps', (['json_config'], {'indent': '(2)'}), '(json_config, indent=2)\n', (521, 544), False, 'import json\n')] |
#! /usr/bin/env python3
import argparse
import logging
import tqdm
import requests
import pywikibot
import pywikibot.proofreadpage
import utils.range_selection
def main():
parser = argparse.ArgumentParser(description='')
parser.add_argument('-v', '--verbose', action='store_true',
h... | [
"pywikibot.Site",
"tqdm.tqdm",
"logging.debug",
"argparse.ArgumentParser",
"logging.basicConfig",
"pywikibot.proofreadpage.IndexPage",
"pywikibot.FilePage",
"requests.get",
"logging.getLogger"
] | [((191, 230), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '""""""'}), "(description='')\n", (214, 230), False, 'import argparse\n'), ((585, 619), 'pywikibot.Site', 'pywikibot.Site', (['"""en"""', '"""wikisource"""'], {}), "('en', 'wikisource')\n", (599, 619), False, 'import pywikibot\n'),... |
# How to run:
# 1) sudo apt-get install python-pip
# 2) pip install gpyopt
import high_dimensional_sampling as hds
import numpy as np
try:
import GPyOpt as gp
except ImportError:
pass
class GPyOpt(hds.Procedure):
def __init__(self,
initial_design_numdata=5,
aquisition_t... | [
"GPyOpt.methods.BayesianOptimization",
"numpy.array"
] | [((2204, 2465), 'GPyOpt.methods.BayesianOptimization', 'gp.methods.BayesianOptimization', ([], {'f': 'function', 'domain': 'mixed_domain', 'initial_design_numdata': 'self.initial_design_numdata', 'acquisition_type': 'self.aquisition_type', 'exact_feval': 'self.exact_feval', 'de_duplication': 'self.de_duplication', 'num... |
#!/usr/bin/env python
import os
from setuptools import find_packages, setup
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, "README.md"), "rt") as f:
long_description = "\n" + f.read()
version_mod = {}
with open(os.path.join(here, "sqs_workers", "__version__.py")) as f:
exec... | [
"os.path.dirname",
"os.path.join",
"setuptools.find_packages"
] | [((101, 126), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (116, 126), False, 'import os\n'), ((140, 171), 'os.path.join', 'os.path.join', (['here', '"""README.md"""'], {}), "(here, 'README.md')\n", (152, 171), False, 'import os\n'), ((253, 304), 'os.path.join', 'os.path.join', (['here', '"... |
from dassl.modeling import Backbone, BACKBONE_REGISTRY
from torchvision import models
class MyBackbone(Backbone):
def __init__(self):
super().__init__()
# Create layers
self.model = models.resnet18(pretrained=True)
def forward(self, x):
# Extract and return features
re... | [
"torchvision.models.resnet18",
"dassl.modeling.BACKBONE_REGISTRY.register"
] | [((341, 369), 'dassl.modeling.BACKBONE_REGISTRY.register', 'BACKBONE_REGISTRY.register', ([], {}), '()\n', (367, 369), False, 'from dassl.modeling import Backbone, BACKBONE_REGISTRY\n'), ((212, 244), 'torchvision.models.resnet18', 'models.resnet18', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (227, 244), Fal... |
#!/usr/bin/env python3
import adventofcode
import collections
import functools
import itertools
import math
import re
import threading
def exec_assembler(s, input=(), output=()):
if not hasattr(input, 'popleft'):
input = collections.deque(input)
if not hasattr(output, 'append'):
output = list(output)
if isinsta... | [
"adventofcode.run",
"threading.Thread",
"re.fullmatch",
"adventofcode.AttrDict",
"adventofcode.signum",
"math.atan2",
"itertools.permutations",
"itertools.count",
"math.gcd",
"itertools.groupby",
"collections.deque"
] | [((5395, 5412), 'itertools.count', 'itertools.count', ([], {}), '()\n', (5410, 5412), False, 'import itertools\n'), ((6344, 6423), 'adventofcode.AttrDict', 'adventofcode.AttrDict', ([], {'popleft': 'play', 'append': 'get', 'buffer': '[]', 'field': '{}', 'blocks': '[]'}), '(popleft=play, append=get, buffer=[], field={},... |
from sympy.core import Add, Mul, symbols
x,y,z = symbols('xyz')
def timeit_neg():
-x
def timeit_Add_x1():
x+1
def timeit_Add_1x():
1+x
def timeit_Add_x05():
x+0.5
def timeit_Add_xy():
x+y
def timeit_Add_xyz():
Add(*[x,y,z])
def timeit_Mul_xy():
x*y
def timeit_Mul_xyz():
Mul(*[x,... | [
"sympy.core.Mul",
"sympy.core.symbols",
"sympy.core.Add"
] | [((50, 64), 'sympy.core.symbols', 'symbols', (['"""xyz"""'], {}), "('xyz')\n", (57, 64), False, 'from sympy.core import Add, Mul, symbols\n'), ((241, 256), 'sympy.core.Add', 'Add', (['*[x, y, z]'], {}), '(*[x, y, z])\n', (244, 256), False, 'from sympy.core import Add, Mul, symbols\n'), ((312, 327), 'sympy.core.Mul', 'M... |
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | [
"absl.testing.absltest.main",
"functools.partial",
"jax.interpreters.sharded_jit.sharded_jit",
"jax.device_count",
"jax.test_util.device_under_test",
"jax.config.config.parse_flags_with_absl",
"jax.interpreters.sharded_jit.PartitionSpec",
"numpy.prod"
] | [((1023, 1053), 'jax.config.config.parse_flags_with_absl', 'config.parse_flags_with_absl', ([], {}), '()\n', (1051, 1053), False, 'from jax.config import config\n'), ((3629, 3644), 'absl.testing.absltest.main', 'absltest.main', ([], {}), '()\n', (3642, 3644), False, 'from absl.testing import absltest\n'), ((2209, 2216)... |
import logging
import pprint
import sys
import time
import traceback
import _thread
from datetime import datetime
from slack_cleaner import __version__
from slack_cleaner.utils import Colors, Counter, TimeRange
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
client = WebClient()
time_range ... | [
"slack_cleaner.utils.TimeRange",
"traceback.print_exc",
"logging.FileHandler",
"logging.StreamHandler",
"time.sleep",
"pprint.PrettyPrinter",
"slack_cleaner.utils.Counter",
"sys.exit",
"slack_sdk.WebClient",
"datetime.datetime.now",
"logging.getLogger"
] | [((297, 308), 'slack_sdk.WebClient', 'WebClient', ([], {}), '()\n', (306, 308), False, 'from slack_sdk import WebClient\n'), ((344, 374), 'pprint.PrettyPrinter', 'pprint.PrettyPrinter', ([], {'indent': '(4)'}), '(indent=4)\n', (364, 374), False, 'import pprint\n'), ((385, 394), 'slack_cleaner.utils.Counter', 'Counter',... |
"""Support for August camera."""
from datetime import timedelta
import requests
from homeassistant.components.camera import Camera
from . import DATA_AUGUST, DEFAULT_TIMEOUT
DEPENDENCIES = ['august']
SCAN_INTERVAL = timedelta(seconds=5)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""... | [
"datetime.timedelta",
"requests.get"
] | [((221, 241), 'datetime.timedelta', 'timedelta', ([], {'seconds': '(5)'}), '(seconds=5)\n', (230, 241), False, 'from datetime import timedelta\n'), ((1790, 1842), 'requests.get', 'requests.get', (['self._image_url'], {'timeout': 'self._timeout'}), '(self._image_url, timeout=self._timeout)\n', (1802, 1842), False, 'impo... |
"""
ai.py
<NAME>
2021-02-08
AI functionality for 5x5 Tic-Tac-Toe
This module contains the AI functionality for the tictactoe game.
It holds the ai_move function, which is a wrapper for either the
minimax or mcts workhorse function.
"""
from math import inf, sqrt, log
from random import randint
from copy import deepc... | [
"copy.deepcopy",
"random.randint",
"time.time",
"game.check_win",
"math.log"
] | [((1157, 1177), 'copy.deepcopy', 'deepcopy', (['node.board'], {}), '(node.board)\n', (1165, 1177), False, 'from copy import deepcopy\n'), ((3238, 3259), 'game.check_win', 'game.check_win', (['board'], {}), '(board)\n', (3252, 3259), False, 'import game\n'), ((893, 919), 'game.check_win', 'game.check_win', (['node.board... |
from decimal import Decimal
from logging import Logger
from typing import Union
from rdflib import Literal, URIRef
from .consts import SH_datatype, SH_nodeKind, SH_optional, SH_order, SH_path
from .errors import ConstraintLoadError, ReportableRuntimeError
from .shape import Shape
class SHACLParameter(Shape):
__... | [
"decimal.Decimal",
"rdflib.URIRef"
] | [((694, 711), 'rdflib.URIRef', 'URIRef', (['"""http://"""'], {}), "('http://')\n", (700, 711), False, 'from rdflib import Literal, URIRef\n'), ((2784, 2804), 'decimal.Decimal', 'Decimal', (['order.value'], {}), '(order.value)\n', (2791, 2804), False, 'from decimal import Decimal\n')] |
from pyramid.view import view_config, view_defaults
from ecoreleve_server.core.base_view import CRUDCommonView
from .field_activity_resource import FieldActivityResource
@view_defaults(context=FieldActivityResource)
class FieldActivityView(CRUDCommonView):
@view_config(name='protocoleTypes', request_method='GET... | [
"pyramid.view.view_config",
"pyramid.view.view_defaults"
] | [((174, 218), 'pyramid.view.view_defaults', 'view_defaults', ([], {'context': 'FieldActivityResource'}), '(context=FieldActivityResource)\n', (187, 218), False, 'from pyramid.view import view_config, view_defaults\n'), ((266, 362), 'pyramid.view.view_config', 'view_config', ([], {'name': '"""protocoleTypes"""', 'reques... |
from builtins import int
from enum import Enum
from sklearn.neighbors import KernelDensity
def outlier_removal_mean(dataframe, colname, low_cut, high_cut):
"""Replace outliers with the mean on dataframe[colname]"""
col = dataframe[colname]
col_numerics = col.loc[
col.apply(
lambda x... | [
"sklearn.neighbors.KernelDensity"
] | [((3353, 3368), 'sklearn.neighbors.KernelDensity', 'KernelDensity', ([], {}), '()\n', (3366, 3368), False, 'from sklearn.neighbors import KernelDensity\n'), ((4281, 4296), 'sklearn.neighbors.KernelDensity', 'KernelDensity', ([], {}), '()\n', (4294, 4296), False, 'from sklearn.neighbors import KernelDensity\n'), ((7667,... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2020 Tier IV, Inc. 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/LICE... | [
"rclpy.executors.SingleThreadedExecutor",
"lifecycle_msgs.srv.ChangeState.Request",
"rcl_interfaces.srv.SetParameters.Request",
"rclpy.spin_until_future_complete",
"rclpy.shutdown",
"lifecycle_msgs.srv.GetState.Request",
"rcl_interfaces.msg.ParameterValue"
] | [((8473, 8489), 'rclpy.shutdown', 'rclpy.shutdown', ([], {}), '()\n', (8487, 8489), False, 'import rclpy\n'), ((2440, 2482), 'rcl_interfaces.srv.SetParameters.Request', 'rcl_interfaces.srv.SetParameters.Request', ([], {}), '()\n', (2480, 2482), False, 'import rcl_interfaces\n'), ((3727, 3773), 'rclpy.spin_until_future_... |
from contextlib import suppress
from datetime import datetime
from typing import (Any,
Dict)
from aiohttp import ClientSession
from asynctmdb.common import (DATE_FORMAT,
StatusCode)
from asynctmdb.config import API_BASE_URL
from asynctmdb.methods import find
async d... | [
"datetime.datetime.strptime",
"contextlib.suppress"
] | [((2076, 2095), 'contextlib.suppress', 'suppress', (['TypeError'], {}), '(TypeError)\n', (2084, 2095), False, 'from contextlib import suppress\n'), ((2131, 2187), 'datetime.datetime.strptime', 'datetime.strptime', (["record['release_date']", 'format_string'], {}), "(record['release_date'], format_string)\n", (2148, 218... |
# coding: utf-8
import sys
sys.path.append('..')
from common import config
# GPU에서 실행하려면 아래 주석을 해제하세요(CuPy 필요).
# ==============================================
config.GPU = True
# ==============================================
from common.optimizer import SGD
from common.trainer import RnnlmTrainer
from common.util im... | [
"sys.path.append",
"common.util.eval_perplexity",
"dataset.ptb.load_data",
"common.optimizer.SGD",
"common.trainer.RnnlmTrainer",
"grulm.Grulm",
"common.util.to_gpu"
] | [((27, 48), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (42, 48), False, 'import sys\n'), ((581, 603), 'dataset.ptb.load_data', 'ptb.load_data', (['"""train"""'], {}), "('train')\n", (594, 603), False, 'from dataset import ptb\n'), ((623, 643), 'dataset.ptb.load_data', 'ptb.load_data', (['"""v... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
from imwievaluation.utils import clean_string, escape_latex_special_characters
from imwievaluation.utils import filter_dict
from imwievaluation.utils import filter_and_sort_dicts
from imwievaluation.utils import sort_dicts
@pytest.mark.parametrize('test_st... | [
"imwievaluation.utils.escape_latex_special_characters",
"imwievaluation.utils.filter_dict",
"imwievaluation.utils.clean_string",
"imwievaluation.utils.filter_and_sort_dicts",
"imwievaluation.utils.sort_dicts",
"pytest.mark.parametrize"
] | [((288, 414), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""test_string, expected"""', "[('ä12/...', 'a12'), ('äÄöÖüÜß', 'aAoOuUss'), ('{f, 2 asw', 'f 2 asw')]"], {}), "('test_string, expected', [('ä12/...', 'a12'), (\n 'äÄöÖüÜß', 'aAoOuUss'), ('{f, 2 asw', 'f 2 asw')])\n", (311, 414), False, 'import p... |
import argparse
import json
import os
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--config', type=str)
args = parser.parse_args()
with open(args.config) as f:
config = json.load(f)
dataset_dir = config['dataset_dir']
os.makedirs(dataset_dir, exis... | [
"json.dump",
"json.load",
"os.makedirs",
"argparse.ArgumentParser",
"os.system",
"os.path.join"
] | [((79, 104), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (102, 104), False, 'import argparse\n'), ((291, 330), 'os.makedirs', 'os.makedirs', (['dataset_dir'], {'exist_ok': '(True)'}), '(dataset_dir, exist_ok=True)\n', (302, 330), False, 'import os\n'), ((1329, 1373), 'os.path.join', 'os.path... |
import json
import requests
from kiteconnect import KiteConnect
import logging
logging.basicConfig(level=logging.DEBUG)
KITE_LOGIN = 'https://kite.zerodha.com/api/login'
KITE_CONNECT = 'https://kite.trade/connect/login'
KITE_TWOFA = 'https://kite.zerodha.com/api/twofa'
class KiteLogin:
def __init__(self, user_i... | [
"requests.Session",
"kiteconnect.KiteConnect",
"logging.basicConfig",
"json.loads"
] | [((80, 120), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG'}), '(level=logging.DEBUG)\n', (99, 120), False, 'import logging\n'), ((647, 667), 'kiteconnect.KiteConnect', 'KiteConnect', (['api_key'], {}), '(api_key)\n', (658, 667), False, 'from kiteconnect import KiteConnect\n'), ((1376, 139... |
import functools
import tensorflow as tf
import importlib as il
_ac=il.import_module("deepgmap.network_constructors.auc_calc")
ac=_ac.auc_pr
#the code design came from https://gist.github.com/danijar/8663d3bbfd586bffecf6a0094cd116f2
def doublewrap(function):
@functools.wraps(function)
def decorator(*args, **... | [
"tensorflow.reduce_sum",
"tensorflow.abs",
"tensorflow.train.Saver",
"importlib.import_module",
"tensorflow.nn.weighted_cross_entropy_with_logits",
"tensorflow.device",
"tensorflow.variable_scope",
"tensorflow.multiply",
"functools.wraps",
"tensorflow.train.AdamOptimizer"
] | [((69, 127), 'importlib.import_module', 'il.import_module', (['"""deepgmap.network_constructors.auc_calc"""'], {}), "('deepgmap.network_constructors.auc_calc')\n", (85, 127), True, 'import importlib as il\n'), ((267, 292), 'functools.wraps', 'functools.wraps', (['function'], {}), '(function)\n', (282, 292), False, 'imp... |
#! /usr/bin/python3
import sys, os, time
from typing import List, Tuple
from itertools import product
class IntCodeComputer():
def __init__(self, memory: List[int]):
self.memory = list(memory)
self.pointer = 0
self.running = True
def run(self) -> int:
while self.running:
... | [
"os.path.isfile",
"time.perf_counter"
] | [((2061, 2080), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (2078, 2080), False, 'import sys, os, time\n'), ((2154, 2173), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (2171, 2173), False, 'import sys, os, time\n'), ((1764, 1789), 'os.path.isfile', 'os.path.isfile', (['file_path'], {}), '... |
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See https://swift.org/CONTRIBUTORS.txt for the list o... | [
"itertools.chain.from_iterable",
"itertools.imap"
] | [((1896, 1935), 'itertools.chain.from_iterable', 'itertools.chain.from_iterable', (['iterable'], {}), '(iterable)\n', (1925, 1935), False, 'import itertools\n'), ((2547, 2582), 'itertools.imap', 'imap', (['_migrate_swift_sdks_arg', 'args'], {}), '(_migrate_swift_sdks_arg, args)\n', (2551, 2582), False, 'from itertools ... |
from rest_framework.reverse import reverse
from .state import StateListSerializer, StateSerializer
class SpecialElectionListSerializer(StateListSerializer):
def get_url(self, obj):
return reverse(
'electionnight_api_special-election-detail',
request=self.context['request'],
... | [
"rest_framework.reverse.reverse"
] | [((203, 355), 'rest_framework.reverse.reverse', 'reverse', (['"""electionnight_api_special-election-detail"""'], {'request': "self.context['request']", 'kwargs': "{'pk': obj.pk, 'date': self.context['election_date']}"}), "('electionnight_api_special-election-detail', request=self.context[\n 'request'], kwargs={'pk':... |
from socket import htons
from pyroute2.netlink import nla
from pyroute2.netlink.rtnl.tcmsg.act_police import nla_plus_police
from pyroute2.netlink.rtnl.tcmsg.act_police import get_parameters \
as ap_parameters
def fix_msg(msg, kwarg):
msg['info'] = htons(kwarg.get('protocol', 0) & 0xffff) |\
((kwarg.g... | [
"pyroute2.netlink.rtnl.tcmsg.act_police.get_parameters"
] | [((717, 737), 'pyroute2.netlink.rtnl.tcmsg.act_police.get_parameters', 'ap_parameters', (['kwarg'], {}), '(kwarg)\n', (730, 737), True, 'from pyroute2.netlink.rtnl.tcmsg.act_police import get_parameters as ap_parameters\n')] |
import logging
from pumper import Pumper
from dotenv import load_dotenv
def lambda_handler(event, context):
load_dotenv()
logging.basicConfig(format='%(asctime)s [%(levelname)s] %(name)s: %(message)s')
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
Pumper().run()
| [
"dotenv.load_dotenv",
"logging.getLogger",
"pumper.Pumper",
"logging.basicConfig"
] | [((114, 127), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (125, 127), False, 'from dotenv import load_dotenv\n'), ((132, 211), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s [%(levelname)s] %(name)s: %(message)s"""'}), "(format='%(asctime)s [%(levelname)s] %(name)s: %(message)s... |
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.exceptions import NotFittedError
from sklearn.metrics import confusion_matrix
import tensorflow as tf
import numpy as np
import random
from dataset_wave import Dataset
from alsNetHistory import AlsNetHistory
import os
import sys
BASE_DIR = os.path.d... | [
"numpy.argmax",
"tensorflow.get_collection",
"random.sample",
"tensorflow.ConfigProto",
"sklearn.exceptions.NotFittedError",
"pointnet_util.pointnet_fp_module",
"numpy.mean",
"dataset_wave.Dataset",
"alsNetHistory.AlsNetHistory",
"pointnet_util.pointnet_sa_module",
"os.path.join",
"sys.path.ap... | [((311, 336), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (326, 336), False, 'import os\n'), ((337, 362), 'sys.path.append', 'sys.path.append', (['BASE_DIR'], {}), '(BASE_DIR)\n', (352, 362), False, 'import sys\n'), ((379, 413), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""../utils"""... |
from twisted.internet import stdio, reactor
from twisted.internet.protocol import ClientFactory, Protocol
import datetime
class DataWrapper(Protocol):
output = None
def dataReceived(self, data: bytes):
"""
Вывод через канал клиента
:param data:
:return:
"""
if ... | [
"twisted.internet.reactor.run",
"twisted.internet.reactor.callFromThread",
"datetime.datetime.now",
"twisted.internet.stdio.StandardIO"
] | [((2384, 2397), 'twisted.internet.reactor.run', 'reactor.run', ([], {}), '()\n', (2395, 2397), False, 'from twisted.internet import stdio, reactor\n'), ((706, 739), 'twisted.internet.stdio.StandardIO', 'stdio.StandardIO', (['input_forwarder'], {}), '(input_forwarder)\n', (722, 739), False, 'from twisted.internet import... |
from pcpca import PCPCA, CPCA
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_rand_score, silhouette_score
from sklearn.decomposition import PCA
from scipy import stats
from tqdm import tqdm
from scipy.s... | [
"matplotlib.pyplot.title",
"matplotlib.rc",
"pandas.read_csv",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.arange",
"matplotlib.pyplot.tight_layout",
"sklearn.cluster.KMeans",
"pcpca.CPCA",
"numpy.linspace",
"scipy.stats.t.ppf",
"pandas.concat",
"matplotlib.pyplot.show",
"matplotlib.p... | [((720, 742), 'pandas.read_csv', 'pd.read_csv', (['DATA_PATH'], {}), '(DATA_PATH)\n', (731, 742), True, 'import pandas as pd\n'), ((1182, 1241), 'pandas.concat', 'pd.concat', (['[X_df.iloc[:177, :], X_df.iloc[180:, :]]'], {'axis': '(0)'}), '([X_df.iloc[:177, :], X_df.iloc[180:, :]], axis=0)\n', (1191, 1241), True, 'imp... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
from rest_framework import status as http_status
import logging
import functools
from osf.exceptions import ValidationValueError
from framework.exceptions import HTTPError
from framework.analytics import update_counter
from addons.osfstorage i... | [
"framework.exceptions.HTTPError",
"os.path.splitext",
"functools.wraps",
"logging.getLogger",
"framework.analytics.update_counter"
] | [((345, 372), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (362, 372), False, 'import logging\n'), ((2232, 2434), 'framework.exceptions.HTTPError', 'HTTPError', (['http_status.HTTP_503_SERVICE_UNAVAILABLE'], {'data': "{'message_short': 'Upload service unavailable', 'message_long':\n ... |
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import MinMaxScaler
from ml_toolkit.clustering.api import Cluster, Metrics
if __name__ == '__main__':
df = pd.read_csv('s4.txt', header=None, sep=r'\s+')
df.columns = ['x', 'y']
x = MinMaxScaler().fit_trans... | [
"pandas.read_csv",
"sklearn.preprocessing.MinMaxScaler",
"sklearn.ensemble.RandomForestClassifier"
] | [((213, 259), 'pandas.read_csv', 'pd.read_csv', (['"""s4.txt"""'], {'header': 'None', 'sep': '"""\\\\s+"""'}), "('s4.txt', header=None, sep='\\\\s+')\n", (224, 259), True, 'import pandas as pd\n'), ((296, 310), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {}), '()\n', (308, 310), False, 'from sklearn.prep... |
#!/usr/bin/env python
"""Convert fastq inputs into paired inputs with UMIs in read names.
Handles two cases:
- Separate UMI read files (read 1, read 2, UMI)
Usage:
bcbio_fastq_umi_prep.py single <out basename> <read 1 fastq> <read 2 fastq> <umi fastq>
or:
bcbio_fastq_umi_prep.py autopair [<list> <of> <fa... | [
"os.path.commonprefix",
"os.remove",
"bcbio.utils.open_gzipsafe",
"argparse.ArgumentParser",
"os.path.basename",
"bcbio.distributed.multi.run_multicore",
"bcbio.utils.safe_makedir"
] | [((4393, 4423), 'os.remove', 'os.remove', (['transform_json_file'], {}), '(transform_json_file)\n', (4402, 4423), False, 'import os\n'), ((5064, 5095), 'bcbio.utils.safe_makedir', 'utils.safe_makedir', (['args.outdir'], {}), '(args.outdir)\n', (5082, 5095), False, 'from bcbio import utils\n'), ((7121, 7209), 'bcbio.dis... |
# Run Quacky on multiple AWS IAM policies.
# Analyze relative permissiveness.
import argparse as ap
import sys
import os
import re
import math
from utils.Shell import Shell
from utilities import get_abc_result_line
parser = ap.ArgumentParser(description = 'Translate IAM policies to SMT-LIB2 for ABC/Z3')
parser.add_ar... | [
"argparse.ArgumentParser",
"utilities.get_abc_result_line",
"os.fsdecode",
"utils.Shell.Shell",
"os.fsencode",
"os.listdir"
] | [((226, 304), 'argparse.ArgumentParser', 'ap.ArgumentParser', ([], {'description': '"""Translate IAM policies to SMT-LIB2 for ABC/Z3"""'}), "(description='Translate IAM policies to SMT-LIB2 for ABC/Z3')\n", (243, 304), True, 'import argparse as ap\n'), ((1054, 1110), 'os.fsencode', 'os.fsencode', (["('../samples/' + ar... |
# The MIT License (MIT)
#
# Copyright (c) 2015-2016 Massachusetts Institute of Technology.
#
# 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 Software without restriction, including without limitation ... | [
"math.sqrt",
"math.radians",
"math.sin",
"math.cos",
"math.log"
] | [((5910, 5939), 'math.radians', 'math.radians', (['(pt1[0] - pt2[0])'], {}), '(pt1[0] - pt2[0])\n', (5922, 5939), False, 'import math\n'), ((5962, 5991), 'math.radians', 'math.radians', (['(pt1[1] - pt2[1])'], {}), '(pt1[1] - pt2[1])\n', (5974, 5991), False, 'import math\n'), ((6008, 6028), 'math.radians', 'math.radian... |
import rospy
import tensorflow as tf
import numpy as np
from styx_msgs.msg import TrafficLight
MIN_SCORE_THRESHOLD = 0.5
CLASS_DICT = {1: 'Green', 2: 'Red', 3: 'Yellow'}
class TLClassifier(object):
def __init__(self, is_site):
#TODO load classifier
if is_site:
PATH_TO_MODEL = r'light_... | [
"tensorflow.Session",
"numpy.expand_dims",
"rospy.loginfo",
"tensorflow.gfile.GFile",
"tensorflow.Graph",
"numpy.squeeze",
"tensorflow.import_graph_def",
"tensorflow.GraphDef"
] | [((668, 678), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (676, 678), True, 'import tensorflow as tf\n'), ((1494, 1532), 'tensorflow.Session', 'tf.Session', ([], {'graph': 'self.detection_graph'}), '(graph=self.detection_graph)\n', (1504, 1532), True, 'import tensorflow as tf\n'), ((386, 419), 'rospy.loginfo', 'r... |
# -*- coding: UTF-8 -*-
from web3 import Web3, HTTPProvider
import sha3
import binascii
from random import Random
from requests import request
true = True
false = False
config = {
"abi":[
{
"constant": true,
"inputs": [],
"name": "count",
"outputs": [
{
... | [
"web3.HTTPProvider",
"random.Random",
"web3.Web3.toChecksumAddress",
"web3.Web3.toWei"
] | [((7655, 7723), 'web3.Web3.toChecksumAddress', 'Web3.toChecksumAddress', (['"""0x66d30937C5b98000c2e9f77acbf51915A1AacbC9"""'], {}), "('0x66d30937C5b98000c2e9f77acbf51915A1AacbC9')\n", (7677, 7723), False, 'from web3 import Web3, HTTPProvider\n'), ((7737, 7814), 'web3.HTTPProvider', 'HTTPProvider', (['"""https://ropste... |
import asyncio
from functools import wraps
from typing import Callable, Optional, Type, TypeVar, Union
from .timeout import timeout
Number = Union[int, float]
T = TypeVar('T')
# noinspection SpellCheckingInspection
def asyncbackoff(attempt_timeout: Optional[Number],
deadline: Optional[Number],
... | [
"typing.TypeVar",
"asyncio.sleep",
"asyncio.get_event_loop",
"functools.wraps"
] | [((166, 178), 'typing.TypeVar', 'TypeVar', (['"""T"""'], {}), "('T')\n", (173, 178), False, 'from typing import Callable, Optional, Type, TypeVar, Union\n'), ((1342, 1353), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (1347, 1353), False, 'from functools import wraps\n'), ((1414, 1438), 'asyncio.get_event_lo... |
from dataclasses import dataclass, field, fields
from enum import Enum
from flask import current_app as app
from flask import jsonify, request, url_for
class Status(Enum):
"""Body response statuses."""
CREATED = "created"
SUCCESS = "success"
EXPIRED = "expired"
INVALID = "invalid"
ERROR = "e... | [
"dataclasses.field",
"flask.url_for",
"dataclasses.fields",
"flask.request.url_root.rstrip"
] | [((1605, 1622), 'dataclasses.field', 'field', ([], {'init': '(False)'}), '(init=False)\n', (1610, 1622), False, 'from dataclasses import dataclass, field, fields\n'), ((1748, 1776), 'flask.request.url_root.rstrip', 'request.url_root.rstrip', (['"""/"""'], {}), "('/')\n", (1771, 1776), False, 'from flask import jsonify,... |
import pandas as pd
import os
import seaborn_plots as splot
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
def create_age_demographics_example_plot(age_gender_bkts):
usa_demographic = age_gender_bkts[age_gender_bkts['country_destination'] == 'US']
female_demographic = usa_demographi... | [
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show",
"os.getcwd",
"matplotlib.pyplot.legend",
"seaborn.despine",
"numpy.arange",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"seaborn.set"
] | [((993, 1031), 'numpy.arange', 'np.arange', (['female_demographic.shape[0]'], {}), '(female_demographic.shape[0])\n', (1002, 1031), True, 'import numpy as np\n'), ((1036, 1078), 'seaborn.set', 'sns.set', ([], {'style': '"""whitegrid"""', 'font_scale': '(1.5)'}), "(style='whitegrid', font_scale=1.5)\n", (1043, 1078), Tr... |
import subprocess
import sys
class Notifier:
def __init__(self):
pass
def send(self, title, text):
if sys.platform == "win32":
import win10toast
toast = win10toast.ToastNotifier()
toast.show_toast(title, text, duration=5)
elif sys.platform == "linux"... | [
"win10toast.ToastNotifier",
"subprocess.call",
"subprocess.Popen"
] | [((203, 229), 'win10toast.ToastNotifier', 'win10toast.ToastNotifier', ([], {}), '()\n', (227, 229), False, 'import win10toast\n'), ((334, 380), 'subprocess.Popen', 'subprocess.Popen', (["['notify-send', title, text]"], {}), "(['notify-send', title, text])\n", (350, 380), False, 'import subprocess\n'), ((544, 598), 'sub... |
import arfit.arn_posterior as pos
import numpy as np
roots = np.array([-1.0/(3600.0*24.0)+2.0*np.pi*1j/(5.0*3600), -1.0/(3600.0*24.0)-2.0*np.pi*1j/(5.0*3600), -1.0/(10.0*3600)])
sigma = 1e-8
def draw_observations(Tmax):
# Observe once an hour up to Tmax
ts = np.arange(0, Tmax, 3600.0)
# Scatter the obser... | [
"numpy.random.uniform",
"numpy.fmod",
"numpy.array",
"arfit.arn_posterior.generate_data",
"numpy.arange"
] | [((62, 218), 'numpy.array', 'np.array', (['[-1.0 / (3600.0 * 24.0) + 2.0 * np.pi * 1.0j / (5.0 * 3600), -1.0 / (3600.0 *\n 24.0) - 2.0 * np.pi * 1.0j / (5.0 * 3600), -1.0 / (10.0 * 3600)]'], {}), '([-1.0 / (3600.0 * 24.0) + 2.0 * np.pi * 1.0j / (5.0 * 3600), -1.0 /\n (3600.0 * 24.0) - 2.0 * np.pi * 1.0j / (5.0 * ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This module contains a Snips skill that repeats the last message that
your voice assistant has said on the site you are talking to, as well as what
Snips has understood from your last speech message. It can also repeat the
action corresponding to the last intent.
"""
... | [
"json.load",
"importlib.import_module",
"json.dumps",
"toml.load",
"paho.mqtt.client.Client",
"collections.deque"
] | [((1501, 1552), 'importlib.import_module', 'importlib.import_module', (["('translations.' + language)"], {}), "('translations.' + language)\n", (1524, 1552), False, 'import importlib\n'), ((2053, 2066), 'paho.mqtt.client.Client', 'mqtt.Client', ([], {}), '()\n', (2064, 2066), True, 'import paho.mqtt.client as mqtt\n'),... |
import datetime
import typing
import urllib.parse
from onetimepass import settings
from onetimepass.base_model import BaseModel
from onetimepass.db.models import get_params_by_type
from onetimepass.db.models import HOTPParams
from onetimepass.db.models import OTPAlgorithm
from onetimepass.db.models import OTPType
from... | [
"onetimepass.db.models.get_params_by_type",
"datetime.datetime.fromtimestamp"
] | [((1410, 1470), 'datetime.datetime.fromtimestamp', 'datetime.datetime.fromtimestamp', (['(0)'], {'tz': 'datetime.timezone.utc'}), '(0, tz=datetime.timezone.utc)\n', (1441, 1470), False, 'import datetime\n'), ((2142, 2170), 'onetimepass.db.models.get_params_by_type', 'get_params_by_type', (['otp_type'], {}), '(otp_type)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.