code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import FWCore.ParameterSet.Config as cms
process = cms.Process("GEOM")
process.load("SimG4CMS.HcalTestBeam.TB2004GeometryXML_cfi")
process.VisConfigurationService = cms.Service("VisConfigurationService",
Views = cms.untracked.vstring('3D Window'),
ContentProxies = cms.untracked.vstring('Simulation/Core',
... | [
"FWCore.ParameterSet.Config.double",
"FWCore.ParameterSet.Config.untracked.int32",
"FWCore.ParameterSet.Config.untracked.uint32",
"FWCore.ParameterSet.Config.Process",
"FWCore.ParameterSet.Config.untracked.vstring",
"FWCore.ParameterSet.Config.Path",
"FWCore.ParameterSet.Config.bool"
] | [((52, 71), 'FWCore.ParameterSet.Config.Process', 'cms.Process', (['"""GEOM"""'], {}), "('GEOM')\n", (63, 71), True, 'import FWCore.ParameterSet.Config as cms\n'), ((806, 825), 'FWCore.ParameterSet.Config.Path', 'cms.Path', (['process.m'], {}), '(process.m)\n', (814, 825), True, 'import FWCore.ParameterSet.Config as cm... |
"""
Regression-based gym environment.
"""
import jax.numpy as jnp
from jax import jit
import haiku as hk
import chex
from gym import Env, spaces
from typing import Callable, Any
from jsl.gym_envs.envs.base import mean_squared_error, sample_gaussian_reg_data
class RegressionEnv(Env):
def __init__(self,
... | [
"jsl.gym_envs.envs.base.mean_squared_error",
"gym.spaces.Box",
"haiku.PRNGSequence",
"jax.jit",
"jsl.gym_envs.envs.base.sample_gaussian_reg_data"
] | [((742, 762), 'haiku.PRNGSequence', 'hk.PRNGSequence', (['key'], {}), '(key)\n', (757, 762), True, 'import haiku as hk\n'), ((1278, 1365), 'gym.spaces.Box', 'spaces.Box', ([], {'low': '(-jnp.inf)', 'high': '(0.0)', 'shape': '(train_batch_size, 1)', 'dtype': 'jnp.float32'}), '(low=-jnp.inf, high=0.0, shape=(train_batch_... |
# Copyright (c) 2020, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
from coremltools.converters.mil.mil import Builder as mb
from coremltools.converters.mil.testing_util... | [
"numpy.prod",
"coremltools.converters.mil.testing_utils.apply_pass_and_basic_check",
"coremltools.converters.mil.testing_utils.get_op_types_in_program",
"coremltools.converters.mil.mil.Builder.TensorSpec",
"coremltools.converters.mil.mil.Builder.tile",
"itertools.product",
"coremltools.converters.mil.mi... | [((1203, 1263), 'coremltools.converters.mil.testing_utils.apply_pass_and_basic_check', 'apply_pass_and_basic_check', (['prog', '"""common::noop_elimination"""'], {}), "(prog, 'common::noop_elimination')\n", (1229, 1263), False, 'from coremltools.converters.mil.testing_utils import assert_model_is_valid, get_op_types_in... |
from blaze.expr import symbol
import numpy as np
from datashape import dshape, isscalar
def test_array_dshape():
x = symbol('x', '5 * 3 * float32')
assert x.shape == (5, 3)
assert x.schema == dshape('float32')
assert len(x) == 5
assert x.ndim == 2
def test_element():
x = symbol('x', '5 * 3 *... | [
"numpy.array",
"datashape.isscalar",
"datashape.dshape",
"blaze.expr.symbol"
] | [((123, 153), 'blaze.expr.symbol', 'symbol', (['"""x"""', '"""5 * 3 * float32"""'], {}), "('x', '5 * 3 * float32')\n", (129, 153), False, 'from blaze.expr import symbol\n'), ((300, 330), 'blaze.expr.symbol', 'symbol', (['"""x"""', '"""5 * 3 * float32"""'], {}), "('x', '5 * 3 * float32')\n", (306, 330), False, 'from bla... |
# Copyright 2021 MosaicML. All Rights Reserved.
import os
from dataclasses import dataclass
from typing import List, Optional, Tuple
import numpy as np
import torch
import torch.utils.data
import yahp as hp
from PIL import Image
from torchvision import transforms
from torchvision.datasets import ImageFolder
from com... | [
"torchvision.transforms.CenterCrop",
"torchvision.transforms.RandomResizedCrop",
"yahp.required",
"numpy.asarray",
"numpy.rollaxis",
"torch.from_numpy",
"torchvision.transforms.RandomHorizontalFlip",
"yahp.optional",
"torch.tensor",
"numpy.resize",
"os.path.join",
"numpy.expand_dims",
"torch... | [((1348, 1412), 'torch.tensor', 'torch.tensor', (['[target[1] for target in batch]'], {'dtype': 'torch.int64'}), '([target[1] for target in batch], dtype=torch.int64)\n', (1360, 1412), False, 'import torch\n'), ((2680, 2706), 'yahp.required', 'hp.required', (['"""resize size"""'], {}), "('resize size')\n", (2691, 2706)... |
from __future__ import unicode_literals
import time
from ..downloader import get_suitable_downloader
from .fragment import FragmentFD
from ..utils import urljoin
class DashSegmentsFD(FragmentFD):
"""
Download segments in a DASH manifest. External downloaders can take over
the fragment downloads by suppo... | [
"time.time"
] | [((650, 661), 'time.time', 'time.time', ([], {}), '()\n', (659, 661), False, 'import time\n')] |
"""
This module is a framework for solving constraint satisfaction problems.
"""
from collections import deque
class ConstraintSatisfactionProblem:
"""
The abstract base class of a constraint satisfaction problem.
Attributes:
variables (dict): A mapping of variable names -> variable objects
... | [
"collections.deque"
] | [((4099, 4106), 'collections.deque', 'deque', ([], {}), '()\n', (4104, 4106), False, 'from collections import deque\n')] |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-29 16:06
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import n_profile.models
class Migration(migrations.Migration):
initial = True
dependenc... | [
"django.db.models.ImageField",
"django.db.models.OneToOneField",
"django.db.migrations.swappable_dependency",
"django.db.models.AutoField"
] | [((336, 393), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (367, 393), False, 'from django.db import migrations, models\n'), ((527, 620), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)... |
#!/usr/bin/env python
##############################################################################
##
# This file is part of Sardana
##
# http://www.sardana-controls.org/
##
# Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
##
# Sardana is free software: you can redistribute it and/or modify
# it under th... | [
"sardana.taurus.qt.qtgui.macrolistener.DynamicPlotManager.__init__",
"taurus.core.util.argparse.get_taurus_parser",
"sardana.taurus.qt.qtgui.macrolistener.DynamicPlotManager.onExpConfChanged",
"taurus.qt.qtgui.application.TaurusApplication",
"sys.exit",
"sardana.taurus.qt.qtgui.macrolistener.DynamicPlotMa... | [((3206, 3225), 'taurus.core.util.argparse.get_taurus_parser', 'get_taurus_parser', ([], {}), '()\n', (3223, 3225), False, 'from taurus.core.util.argparse import get_taurus_parser\n'), ((3297, 3422), 'taurus.qt.qtgui.application.TaurusApplication', 'TaurusApplication', ([], {'app_name': '"""Showscan Online"""', 'org_do... |
import thread
from xl_helper.Utils import Utils
from xl_helper.actions.Installer import Installer
from xl_helper.actions.Server import Server
from xl_helper.artifacts.server.RemoteServerDist import RemoteServerDist
from tests.util.TestWithTempDirs import TestWithTempDirs
class ServerTest(TestWithTempDirs):
def ... | [
"xl_helper.Utils.Utils.wait_until",
"xl_helper.actions.Installer.Installer",
"xl_helper.artifacts.server.RemoteServerDist.RemoteServerDist",
"thread.start_new_thread",
"xl_helper.actions.Server.Server.from_config"
] | [((358, 385), 'xl_helper.actions.Installer.Installer', 'Installer', (['self.test_config'], {}), '(self.test_config)\n', (367, 385), False, 'from xl_helper.actions.Installer import Installer\n'), ((543, 597), 'xl_helper.actions.Server.Server.from_config', 'Server.from_config', ([], {'config': 'self.test_config', 'home':... |
'''
The longest common suffix has following optimal substructure property.
If last characters match, then we reduce both lengths by 1
LCSuff(X, Y, m, n) = LCSuff(X, Y, m-1, n-1) + 1 if X[m-1] = Y[n-1]
If last characters do not match, then result is 0, i.e.,
LCSuff(X, Y, m, n) = 0 if (X[m-1] != Y[n-1])
Now we conside... | [
"sys.stdin.readline"
] | [((1064, 1080), 'sys.stdin.readline', 'stdin.readline', ([], {}), '()\n', (1078, 1080), False, 'from sys import stdin\n')] |
import os
import unittest
import tempfile
import shutil
try:
from catkin_pkg.package_templates import PackageTemplate
except ImportError as impe:
raise ImportError(
'Please adjust your pythonpath before running this test: %s' % str(impe))
import imp
imp.load_source('catkin_create_pkg',
... | [
"catkin_create_pkg.main",
"os.path.join",
"catkin_pkg.package_templates.PackageTemplate._create_package_template",
"os.path.dirname",
"tempfile.mkdtemp",
"shutil.rmtree"
] | [((334, 359), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (349, 359), False, 'import os\n'), ((567, 621), 'catkin_pkg.package_templates.PackageTemplate._create_package_template', 'PackageTemplate._create_package_template', (['"""foopackage"""'], {}), "('foopackage')\n", (607, 621), False, ... |
from setuptools import setup
with open('README.md', 'r', encoding='utf-8') as f:
readme = f.read()
setup(
name='videocr',
packages=['videocr'],
version='0.1.6',
license='MIT',
description='Extract hardcoded subtitles from videos using machine learning',
long_description_content_type='text/... | [
"setuptools.setup"
] | [((105, 810), 'setuptools.setup', 'setup', ([], {'name': '"""videocr"""', 'packages': "['videocr']", 'version': '"""0.1.6"""', 'license': '"""MIT"""', 'description': '"""Extract hardcoded subtitles from videos using machine learning"""', 'long_description_content_type': '"""text/markdown"""', 'long_description': 'readm... |
from office365.runtime.client_result import ClientResult
from office365.runtime.client_value_collection import ClientValueCollection
from office365.runtime.queries.service_operation_query import ServiceOperationQuery
from office365.runtime.resource_path import ResourcePath
from office365.runtime.resource_path_service_o... | [
"office365.runtime.resource_path_service_operation.ResourcePathServiceOperation",
"office365.runtime.resource_path.ResourcePath",
"office365.sharepoint.changes.change_query.ChangeQuery",
"office365.runtime.client_result.ClientResult",
"office365.sharepoint.listitems.listitem.ListItem",
"office365.sharepoi... | [((2543, 2582), 'office365.sharepoint.flows.flow_synchronization_result.FlowSynchronizationResult', 'FlowSynchronizationResult', (['self.context'], {}), '(self.context)\n', (2568, 2582), False, 'from office365.sharepoint.flows.flow_synchronization_result import FlowSynchronizationResult\n'), ((2597, 2692), 'office365.r... |
#from Instrucciones.instruccion import Instruccion
from tytus.parser.fase2.team21.Analisis_Ascendente.Instrucciones.instruccion import Instruccion
#from storageManager.jsonMode import *
from tytus.parser.fase2.team21.Analisis_Ascendente.storageManager.jsonMode import *
#import Tabla_simbolos.TablaSimbolos as ts
import ... | [
"tytus.parser.fase2.team21.Analisis_Ascendente.Tabla_simbolos.TablaSimbolos.Simbolo"
] | [((1002, 1108), 'tytus.parser.fase2.team21.Analisis_Ascendente.Tabla_simbolos.TablaSimbolos.Simbolo', 'TS.Simbolo', (['anterior.categoria', 'alterdatabase.newName', 'anterior.tipo', 'anterior.valor', 'anterior.Entorno'], {}), '(anterior.categoria, alterdatabase.newName, anterior.tipo,\n anterior.valor, anterior.Ento... |
# -*- coding: utf-8 -*-
"""Some invoices will not go to the paid state from the user interface. This scrip helps doing that.
Example of use:
- Change the names variable
- Run the script
"""
from drivers import odoo_connector
from datetime import timedelta, date, datetime
import logging, pprint
#Establish conn... | [
"drivers.odoo_connector.Connection",
"logging.warning"
] | [((333, 360), 'drivers.odoo_connector.Connection', 'odoo_connector.Connection', ([], {}), '()\n', (358, 360), False, 'from drivers import odoo_connector\n'), ((733, 773), 'logging.warning', 'logging.warning', (['"""failed to find record"""'], {}), "('failed to find record')\n", (748, 773), False, 'import logging, pprin... |
from joblib import delayed, Parallel
import os
import sys
import glob
from tqdm import tqdm
import cv2
import argparse
import matplotlib.pyplot as plt
plt.switch_backend('agg')
def str2bool(s):
"""Convert string to bool (in argparse context)."""
if s.lower() not in ['true', 'false']:
raise ValueE... | [
"os.path.exists",
"sys.exit",
"argparse.ArgumentParser",
"os.makedirs",
"os.path.join",
"joblib.Parallel",
"os.path.basename",
"cv2.VideoCapture",
"matplotlib.pyplot.switch_backend",
"joblib.delayed",
"cv2.resize"
] | [((156, 181), 'matplotlib.pyplot.switch_backend', 'plt.switch_backend', (['"""agg"""'], {}), "('agg')\n", (174, 181), True, 'import matplotlib.pyplot as plt\n'), ((623, 660), 'os.path.join', 'os.path.join', (['f_root', 'v_class', 'v_name'], {}), '(f_root, v_class, v_name)\n', (635, 660), False, 'import os\n'), ((740, 7... |
#!/usr/bin/env python
# encoding: utf-8
"""
@author: XuezhiWang
@license:
@contact: <EMAIL>
@software: pycharm
@file: offloading.py
@time: 2021/4/16 下午2:37
@desc:
"""
from tools import make_request
from tools.transfer_files_tool import transfer_array_and_str
from loguru import logger
def send_frame(url, frame, select... | [
"loguru.logger.exception",
"tools.transfer_files_tool.transfer_array_and_str",
"tools.make_request.make_request"
] | [((1016, 1051), 'tools.transfer_files_tool.transfer_array_and_str', 'transfer_array_and_str', (['frame', '"""up"""'], {}), "(frame, 'up')\n", (1038, 1051), False, 'from tools.transfer_files_tool import transfer_array_and_str\n'), ((1574, 1604), 'tools.make_request.make_request', 'make_request.make_request', (['url'], {... |
#!/usr/bin/env python3
########################################################
# PyHQ9+ by <NAME>, 10/10/2021 #
# Python implementation of the esoteric language HQ9+ #
# No pip dependencies, only internal modules. #
# Original HQ9+ concept by <NAME>, 2001 #
# ... | [
"configparser.ConfigParser",
"time.sleep",
"re.search"
] | [((1198, 1212), 'configparser.ConfigParser', 'ConfigParser', ([], {}), '()\n', (1210, 1212), False, 'from configparser import ConfigParser\n'), ((2718, 2737), 're.search', 're.search', (['"""[Q]"""', 'A'], {}), "('[Q]', A)\n", (2727, 2737), False, 'import re\n'), ((2776, 2795), 're.search', 're.search', (['"""[Q]"""', ... |
import pandas as pd
import datetime as dt
import jpholiday as jh
class Tradetime:
def __init__(self, time=None):
self.set_time(time)
def set_time(self, time=None):
if time:
self.time = time
else:
self.time = dt.datetime.now().date()
if not is_busine... | [
"datetime.datetime.now",
"datetime.timedelta",
"datetime.date",
"jpholiday.is_holiday"
] | [((1106, 1125), 'jpholiday.is_holiday', 'jh.is_holiday', (['date'], {}), '(date)\n', (1119, 1125), True, 'import jpholiday as jh\n'), ((1323, 1343), 'datetime.date', 'dt.date', (['(2020)', '(10)', '(1)'], {}), '(2020, 10, 1)\n', (1330, 1343), True, 'import datetime as dt\n'), ((1757, 1777), 'datetime.timedelta', 'dt.ti... |
"""
Last edited: January 22 2020
@author: <NAME>
# here we provide unit tests of our main functions in robustPipelineSizing
"""
from FINE.expansionModules import robustPipelineSizing
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
def test_robustPipelineDesign():
# wr... | [
"pandas.Series",
"FINE.expansionModules.robustPipelineSizing.computePressureEndnodeArc",
"FINE.expansionModules.robustPipelineSizing.networkRefinement",
"FINE.expansionModules.robustPipelineSizing.computeTimeStepFlows",
"pandas.DataFrame",
"numpy.round",
"FINE.expansionModules.robustPipelineSizing.deter... | [((8410, 8437), 'pandas.Series', 'pd.Series', (['data'], {'index': 'keys'}), '(data, index=keys)\n', (8419, 8437), True, 'import pandas as pd\n'), ((8461, 8495), 'pandas.Series', 'pd.Series', (['invalidData'], {'index': 'keys'}), '(invalidData, index=keys)\n', (8470, 8495), True, 'import pandas as pd\n'), ((9606, 9633)... |
import sublime, sublime_plugin, os
from datetime import date
from sublime_lib import ResourcePath
from .method_generator.exceptions import ClassValidationException
from .method_generator.generator import Generator
from .template import Template
class CreateCppClassCommand(sublime_plugin.WindowCommand):
'''
class fo... | [
"sublime_lib.ResourcePath.from_file_path",
"os.path.splitext",
"sublime.error_message",
"sublime.load_settings",
"os.path.join",
"sublime.set_timeout",
"sublime.Region",
"datetime.date.today",
"os.walk"
] | [((755, 812), 'sublime.load_settings', 'sublime.load_settings', (['"""C++ Classhelper.sublime-settings"""'], {}), "('C++ Classhelper.sublime-settings')\n", (776, 812), False, 'import sublime, sublime_plugin, os\n'), ((2901, 2913), 'datetime.date.today', 'date.today', ([], {}), '()\n', (2911, 2913), False, 'from datetim... |
from collections import OrderedDict
import numpy as np
import torch
import torch.optim as optim
from torch import nn as nn
import rlkit.torch.pytorch_util as ptu
from rlkit.core.eval_util import create_stats_ordered_dict
from rlkit.torch.torch_rl_algorithm import TorchTrainer
from rlkit.torch.networks import FlattenM... | [
"uncertainty_modeling.rl_uncertainty.model.RaPP",
"collections.OrderedDict",
"rlkit.torch.networks.FlattenMlp_Dropout",
"numpy.prod",
"torch.max",
"torch.from_numpy",
"torch.min",
"torch.tensor",
"torch.nn.MSELoss",
"rlkit.torch.pytorch_util.get_numpy",
"uncertainty_modeling.rl_uncertainty.model... | [((1308, 1417), 'uncertainty_modeling.rl_uncertainty.model.SWAG', 'SWAG', (['RegNetBase', '*args'], {'subspace_type': '"""pca"""', 'subspace_kwargs': "{'max_rank': 10, 'pca_rank': 10}"}), "(RegNetBase, *args, subspace_type='pca', **kwargs, subspace_kwargs={\n 'max_rank': 10, 'pca_rank': 10})\n", (1312, 1417), False,... |
#!/usr/bin/env python
# coding=utf-8
import json
import urllib
from .libs import rison
from .kibana import KibanaService
class Dashboard(KibanaService):
url_pattern_share = '{url_base}/#/dashboard/{title}?{query}'
def __init__(self, title, id=None, description='', **kwargs):
super(Dashboard, self)... | [
"urllib.urlencode",
"json.dumps"
] | [((782, 805), 'json.dumps', 'json.dumps', (['self.panels'], {}), '(self.panels)\n', (792, 805), False, 'import json\n'), ((1637, 1660), 'urllib.urlencode', 'urllib.urlencode', (['query'], {}), '(query)\n', (1653, 1660), False, 'import urllib\n')] |
from __future__ import absolute_import
from . import backend as K
from .utils.generic_utils import get_from_module
import warnings
class Regularizer(object):
def __call__(self, x):
return 0
def get_config(self):
return {'name': self.__class__.__name__}
def set_param(self, _):
wa... | [
"warnings.warn"
] | [((318, 464), 'warnings.warn', 'warnings.warn', (['"""The `set_param` method on regularizers is deprecated. It no longer does anything, and it will be removed after 06/2017."""'], {}), "(\n 'The `set_param` method on regularizers is deprecated. It no longer does anything, and it will be removed after 06/2017.'\n ... |
#!/usr/bin/env python3
from regions import load_regions, load_subregions, load_aliases
def load_region_wp_urls(region_keys_names):
aliases_wp = load_aliases("data/ALIASES-WP")
urls = {}
for region_key, region_name in region_keys_names.items():
# Apply Wikipedia-specific mappings
region_n... | [
"regions.load_aliases",
"regions.load_subregions",
"regions.load_regions"
] | [((150, 181), 'regions.load_aliases', 'load_aliases', (['"""data/ALIASES-WP"""'], {}), "('data/ALIASES-WP')\n", (162, 181), False, 'from regions import load_regions, load_subregions, load_aliases\n'), ((608, 636), 'regions.load_aliases', 'load_aliases', (['"""data/ALIASES"""'], {}), "('data/ALIASES')\n", (620, 636), Fa... |
""" Solution for simple linear regression example using placeholders
Created by <NAME> (<EMAIL>)
CS20: "TensorFlow for Deep Learning Research"
cs20.stanford.edu
Lecture 03
"""
import os
import time
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import utils
DATA_FILE = 'data/birth_life_... | [
"tensorflow.placeholder",
"matplotlib.pyplot.plot",
"tensorflow.Session",
"utils.read_birth_life_data",
"tensorflow.train.GradientDescentOptimizer",
"tensorflow.global_variables_initializer",
"tensorflow.constant",
"tensorflow.square",
"tensorflow.get_default_graph",
"time.time",
"matplotlib.pyp... | [((391, 428), 'utils.read_birth_life_data', 'utils.read_birth_life_data', (['DATA_FILE'], {}), '(DATA_FILE)\n', (417, 428), False, 'import utils\n'), ((507, 543), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'name': '"""X"""'}), "(tf.float32, name='X')\n", (521, 543), True, 'import tensorflow as tf\n')... |
import networkx as nx
from region.p_regions.azp import AZPBasicTabu
from region.tests.util import region_list_from_array, compare_region_lists
from region.util import dataframe_to_dict
from region.p_regions.tests.data import adj, neighbors_dict, gdf, graph, w, \
attr, attr_dict, attr_str, double_att... | [
"region.tests.util.compare_region_lists",
"region.p_regions.azp.AZPBasicTabu",
"region.util.dataframe_to_dict",
"networkx.set_node_attributes",
"region.tests.util.region_list_from_array"
] | [((575, 603), 'region.p_regions.azp.AZPBasicTabu', 'AZPBasicTabu', ([], {'random_state': '(0)'}), '(random_state=0)\n', (587, 603), False, 'from region.p_regions.azp import AZPBasicTabu\n'), ((691, 737), 'region.tests.util.region_list_from_array', 'region_list_from_array', (['cluster_object.labels_'], {}), '(cluster_ob... |
# Python 3.6.1
# Requires: anytree 2.4.2
import re
from anytree import Node, RenderTree, PostOrderIter
def sum_weights(nodes):
total = 0
for node in nodes:
if hasattr(node, "disc_weight"):
total += node.disc_weight
else:
total += node.weight
return total
# Unuse... | [
"anytree.PostOrderIter",
"anytree.RenderTree",
"anytree.Node",
"re.match"
] | [((1427, 1460), 'anytree.PostOrderIter', 'PostOrderIter', (['nodes[p_name].root'], {}), '(nodes[p_name].root)\n', (1440, 1460), False, 'from anytree import Node, RenderTree, PostOrderIter\n'), ((1251, 1281), 'anytree.Node', 'Node', (['p_name'], {'weight': 'p_info[0]'}), '(p_name, weight=p_info[0])\n', (1255, 1281), Fal... |
"""
Author: <NAME>
Readme:
ParallelUpload
This file consists of a class which uploads files from source to S3 buckets in Parallel.
"""
import boto3
import Config as config
import os
from multiprocessing import Pool
# s3 client
s3 = boto3.client("s3",
aws_access_key_id=config.AWS_ACCESS_KEY_ID,
... | [
"os.listdir",
"boto3.client",
"multiprocessing.Pool"
] | [((236, 354), 'boto3.client', 'boto3.client', (['"""s3"""'], {'aws_access_key_id': 'config.AWS_ACCESS_KEY_ID', 'aws_secret_access_key': 'config.AWS_SECRET_ACCESS_KEY'}), "('s3', aws_access_key_id=config.AWS_ACCESS_KEY_ID,\n aws_secret_access_key=config.AWS_SECRET_ACCESS_KEY)\n", (248, 354), False, 'import boto3\n'),... |
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('', views.WeatherView.as_view(), name='index'),
path('delete/<pk>/', views.delete_location, name='delete')
]
| [
"django.urls.path"
] | [((161, 219), 'django.urls.path', 'path', (['"""delete/<pk>/"""', 'views.delete_location'], {'name': '"""delete"""'}), "('delete/<pk>/', views.delete_location, name='delete')\n", (165, 219), False, 'from django.urls import path\n')] |
# -*- coding: utf-8 -*-
"""
Test helpers to create and manage fixtures for our Superset app
"""
import json
import uuid
import superset
from superset.connectors.sqla.models import SqlaTable
from superset.models.core import Dashboard
from superset.models.slice import Slice
# Inspired by:
# https://github.com/apache/... | [
"superset.db.session.commit",
"superset.security_manager.add_permission_view_menu",
"superset.db.session.delete",
"superset.db.session.query",
"uuid.uuid4",
"superset.db.session.merge",
"superset.security_manager.get_session.commit",
"superset.security_manager.find_permission_view_menu",
"superset.m... | [((2573, 2609), 'superset.db.session.merge', 'superset.db.session.merge', (['dashboard'], {}), '(dashboard)\n', (2598, 2609), False, 'import superset\n'), ((2614, 2642), 'superset.db.session.commit', 'superset.db.session.commit', ([], {}), '()\n', (2640, 2642), False, 'import superset\n'), ((3113, 3145), 'superset.db.s... |
"""
Local workstations as clusters (:mod:`fluiddyn.clusters.local`)
===============================================================
Provides:
.. autoclass:: ClusterLocal
:members:
"""
import datetime
import os
import stat
from shlex import split
from socket import gethostname
import psutil
from . import Cluste... | [
"os.path.exists",
"os.getenv",
"os.path.expandvars",
"shlex.split",
"os.path.splitext",
"os.chmod",
"datetime.datetime.now",
"psutil.cpu_count",
"socket.gethostname",
"os.remove"
] | [((1179, 1192), 'socket.gethostname', 'gethostname', ([], {}), '()\n', (1190, 1192), False, 'from socket import gethostname\n'), ((1217, 1235), 'psutil.cpu_count', 'psutil.cpu_count', ([], {}), '()\n', (1233, 1235), False, 'import psutil\n'), ((1443, 1467), 'os.getenv', 'os.getenv', (['"""VIRTUAL_ENV"""'], {}), "('VIRT... |
from pgvbotLib import *
from params import *
import pywikibot
from copy import deepcopy
import re, os
RECENT_LOG_FILE = "recent_log.txt"
ADMIN_LIST = ["Ideophagous","<NAME>","<NAME>","<NAME>"]
BOT_COMMENT_TAG = "{{تعليق بوتي}}"
TALK_PAGE_TITLE_PART = "نقاش:"
NOTIF_SECTION_TITLE = "== دمج ؤلا توضيح =="
NOTIF_TEMPL... | [
"os.path.exists",
"pywikibot.Site",
"pywikibot.Page"
] | [((2670, 2686), 'pywikibot.Site', 'pywikibot.Site', ([], {}), '()\n', (2684, 2686), False, 'import pywikibot\n'), ((563, 594), 'os.path.exists', 'os.path.exists', (['RECENT_LOG_FILE'], {}), '(RECENT_LOG_FILE)\n', (577, 594), False, 'import re, os\n'), ((1020, 1054), 'pywikibot.Page', 'pywikibot.Page', (['site', 'target... |
"""
Generate samples for a corpus tag and for a submission.
"""
import json
import logging
import numpy as np
from . import db
from . import distribution
from .sample_util import sample_without_replacement
from .counter_utils import normalize
logger = logging.getLogger(__name__)
def sample_document_uniform(corpus_... | [
"logging.getLogger",
"json.dumps",
"numpy.random.seed"
] | [((256, 283), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (273, 283), False, 'import logging\n'), ((1031, 1049), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (1045, 1049), True, 'import numpy as np\n'), ((718, 776), 'json.dumps', 'json.dumps', (["{'type': 'uniform',... |
import requests
from io import BytesIO
from PIL import Image
def get_user_image(url):
response = requests.get(url)
img_file = BytesIO(response.content)
return Image.open(img_file)
def get_user_details(username):
res = requests.get(f'https://api.github.com/users/{username}')
return res.json() if... | [
"PIL.Image.open",
"io.BytesIO",
"requests.get"
] | [((104, 121), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (116, 121), False, 'import requests\n'), ((137, 162), 'io.BytesIO', 'BytesIO', (['response.content'], {}), '(response.content)\n', (144, 162), False, 'from io import BytesIO\n'), ((174, 194), 'PIL.Image.open', 'Image.open', (['img_file'], {}), '(im... |
#Copyright ReportLab Europe Ltd. 2000-2004
#see license.txt for license details
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/rl_config.py
__version__=''' $Id: rl_config.py,v 1.1 2006/05/26 19:19:36 thomas Exp $ '''
allowTableBoundsErrors = 1 # set to 0 to die on too lar... | [
"string.replace",
"string.split",
"os.getcwd",
"os.path.dirname",
"reportlab.lib.utils.rl_isdir",
"os.environ.has_key"
] | [((4397, 4419), 'os.environ.has_key', 'environ.has_key', (['ename'], {}), '(ename)\n', (4412, 4419), False, 'from os import environ\n'), ((5142, 5167), 'string.split', 'string.split', (['sys.version'], {}), '(sys.version)\n', (5154, 5167), False, 'import os, sys, string\n'), ((5663, 5698), 'os.path.dirname', 'os.path.d... |
# Copyright (c) 2019-2021, NVIDIA CORPORATION. All rights reserved.
# Copyright (c) 2020 UT-Battelle, LLC. All rights reserved.
# See file LICENSE for terms.
import array
import asyncio
import gc
import logging
import os
import re
import struct
import weakref
from functools import partial
from os import close as... | [
"logging.getLogger",
"struct.calcsize",
"os.environ.keys",
"asyncio.iscoroutinefunction",
"array.array",
"os.close",
"os.urandom",
"struct.unpack",
"gc.collect",
"asyncio.sleep",
"re.findall",
"asyncio.get_event_loop",
"weakref.ref",
"weakref.finalize"
] | [((589, 613), 'logging.getLogger', 'logging.getLogger', (['"""ucx"""'], {}), "('ucx')\n", (606, 613), False, 'import logging\n'), ((2152, 2181), 'struct.unpack', 'struct.unpack', (['fmt', 'peer_info'], {}), '(fmt, peer_info)\n', (2165, 2181), False, 'import struct\n'), ((2892, 2912), 'struct.calcsize', 'struct.calcsize... |
# -*- coding: utf-8 -*-
import fire
import logging
import sys
import re
from gensim import matutils
from gensim import corpora
from gensim.models.ldamulticore import LdaMulticore
from sklearn.feature_extraction.text import CountVectorizer
# 示例文档
default_documents = [['human', 'interface', 'computer'],
... | [
"logging.basicConfig",
"gensim.matutils.Sparse2Corpus",
"re.split",
"gensim.corpora.Dictionary",
"fire.Fire",
"sklearn.feature_extraction.text.CountVectorizer"
] | [((4175, 4270), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s : %(levelname)s : %(message)s"""', 'level': 'logging.INFO'}), "(format='%(asctime)s : %(levelname)s : %(message)s',\n level=logging.INFO)\n", (4194, 4270), False, 'import logging\n'), ((4281, 4307), 'fire.Fire', 'fire.Fire'... |
import pandas as pd
import numpy as np
import streamlit as st
import pandas as pd
#import matplotlib.pyplot as plt
#import seaborn as sns
from collections import Counter
from hydralit import HydraApp
from hydralit import HydraHeadApp
import apps
import altair as alt
#when we import hydralit, we automatically... | [
"streamlit.form",
"streamlit.markdown",
"streamlit.cache",
"streamlit.sidebar.multiselect",
"pandas.read_csv",
"streamlit.altair_chart",
"streamlit.video",
"hydralit.HydraApp",
"altair.Chart",
"streamlit.write",
"streamlit.sidebar.markdown",
"streamlit.subheader",
"streamlit.info",
"stream... | [((406, 428), 'streamlit.cache', 'st.cache', ([], {'persist': '(True)'}), '(persist=True)\n', (414, 428), True, 'import streamlit as st\n'), ((435, 459), 'pandas.read_csv', 'pd.read_csv', (['"""final.csv"""'], {}), "('final.csv')\n", (446, 459), True, 'import pandas as pd\n'), ((470, 513), 'hydralit.HydraApp', 'hy.Hydr... |
# Compute multivariate ESS using multi_ess function based on eeyore
# %% Load packages
import numpy as np
import torch
from eeyore.stats import multi_ess
# %% Read chains
chains = torch.as_tensor(np.genfromtxt('chain01.csv', delimiter=','))
# %% Compute multivariate ESS using INSE MC covariance estimation
ess_va... | [
"numpy.genfromtxt",
"eeyore.stats.multi_ess"
] | [((324, 341), 'eeyore.stats.multi_ess', 'multi_ess', (['chains'], {}), '(chains)\n', (333, 341), False, 'from eeyore.stats import multi_ess\n'), ((201, 244), 'numpy.genfromtxt', 'np.genfromtxt', (['"""chain01.csv"""'], {'delimiter': '""","""'}), "('chain01.csv', delimiter=',')\n", (214, 244), True, 'import numpy as np\... |
# Start of memory.py.
import ctypes as ct
def addressOffset(x, offset, bt):
return ct.cast(ct.addressof(x.contents)+int(offset), ct.POINTER(bt))
def allocateMem(size):
return ct.cast((ct.c_byte * max(0,size))(), ct.POINTER(ct.c_byte))
# Copy an array if its is not-None. This is important for treating
# Numpy a... | [
"ctypes.addressof",
"ctypes.POINTER",
"ctypes.sizeof"
] | [((133, 147), 'ctypes.POINTER', 'ct.POINTER', (['bt'], {}), '(bt)\n', (143, 147), True, 'import ctypes as ct\n'), ((219, 240), 'ctypes.POINTER', 'ct.POINTER', (['ct.c_byte'], {}), '(ct.c_byte)\n', (229, 240), True, 'import ctypes as ct\n'), ((532, 553), 'ctypes.POINTER', 'ct.POINTER', (['ct.c_byte'], {}), '(ct.c_byte)\... |
from PIL import Image
#-- read pixels
im = Image.open('../images/img001.png').convert('RGB')
width, height = im.size
#-- pixel operation
for y in range(height):
for x in range(width):
r, g, b = im.getpixel((x, y))
gray = int((r + g + b) / 3)
r2 = gray
g2 = gray
b2 = gra... | [
"PIL.Image.open"
] | [((46, 80), 'PIL.Image.open', 'Image.open', (['"""../images/img001.png"""'], {}), "('../images/img001.png')\n", (56, 80), False, 'from PIL import Image\n')] |
# Copyright (c) The Diem Core Contributors
# SPDX-License-Identifier: Apache-2.0
from itertools import chain
from diem_utils.precise_amount import Amount
from diem_utils.sdks.liquidity import LpClient
from diem_utils.types.currencies import DiemCurrency, FiatCurrency
from diem_utils.types.liquidity.currency import Cur... | [
"diem_utils.sdks.liquidity.LpClient",
"diem_utils.types.liquidity.currency.CurrencyPair",
"diem_utils.precise_amount.Amount",
"diem_utils.types.liquidity.currency.Currency"
] | [((1628, 1671), 'diem_utils.types.liquidity.currency.CurrencyPair', 'CurrencyPair', (['base_currency', 'quote_currency'], {}), '(base_currency, quote_currency)\n', (1640, 1671), False, 'from diem_utils.types.liquidity.currency import Currency, CurrencyPair, CurrencyPairs\n'), ((463, 506), 'diem_utils.types.liquidity.cu... |
# encoding: UTF-8
'''
本文件中实现了CTA策略引擎,针对CTA类型的策略,抽象简化了部分底层接口的功能。
关于平今和平昨规则:
1. 普通的平仓OFFSET_CLOSET等于平昨OFFSET_CLOSEYESTERDAY
2. 只有上期所的品种需要考虑平今和平昨的区别
3. 当上期所的期货有今仓时,调用Sell和Cover会使用OFFSET_CLOSETODAY,否则
会使用OFFSET_CLOSE
4. 以上设计意味着如果Sell和Cover的数量超过今日持仓量时,会导致出错(即用户
希望通过一个指令同时平今和平昨)
5. 采用以上设计的原因是考虑到vn.trader的用户主要是对TB、MC和... | [
"vnpy.trader.vtGateway.VtCancelOrderReq",
"re.compile",
"vnpy.trader.vtFunction.todayDate",
"datetime.timedelta",
"copy.copy",
"os.remove",
"os.path.exists",
"json.dumps",
"vnpy.trader.vtGateway.VtOrderReq",
"os.path.isdir",
"os.mkdir",
"vnpy.trader.vtGateway.VtSubscribeReq",
"traceback.prin... | [((1625, 1663), 'vnpy.trader.vtFunction.getJsonPath', 'getJsonPath', (['settingFileName', '__file__'], {}), '(settingFileName, __file__)\n', (1636, 1663), False, 'from vnpy.trader.vtFunction import todayDate, getJsonPath\n'), ((1930, 1941), 'vnpy.trader.vtFunction.todayDate', 'todayDate', ([], {}), '()\n', (1939, 1941)... |
import time
from concurrent.futures import ThreadPoolExecutor
from queue import Queue
from dae.backends.query_runners import QueryResult
from dae.backends.impala.impala_variants import ImpalaQueryRunner
def create_runner(impala_helpers, query, deserializer=None):
runner = ImpalaQueryRunner(
impala_he... | [
"concurrent.futures.ThreadPoolExecutor",
"time.sleep",
"dae.backends.query_runners.QueryResult",
"dae.backends.impala.impala_variants.ImpalaQueryRunner",
"queue.Queue"
] | [((284, 373), 'dae.backends.impala.impala_variants.ImpalaQueryRunner', 'ImpalaQueryRunner', (['impala_helpers._connection_pool', 'query'], {'deserializer': 'deserializer'}), '(impala_helpers._connection_pool, query, deserializer=\n deserializer)\n', (301, 373), False, 'from dae.backends.impala.impala_variants import... |
# pylint: disable=g-bad-file-header
# Copyright 2018 The Bazel 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
... | [
"unittest.main"
] | [((2000, 2015), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2013, 2015), False, 'import unittest\n')] |
from flask import Blueprint, jsonify, request
from flask_login import login_required
from app.models import db, Tag
tag_routes = Blueprint('tags', __name__)
@tag_routes.route('/', methods=['GET', 'POST'])
# @login_required
def tags():
m = request.method
if m == 'GET': # Get a list of all tags
tags... | [
"app.models.Tag",
"app.models.Tag.query.all",
"app.models.db.session.commit",
"app.models.db.session.add",
"app.models.Tag.query.get",
"flask.Blueprint",
"app.models.Tag.query.filter",
"flask.jsonify"
] | [((132, 159), 'flask.Blueprint', 'Blueprint', (['"""tags"""', '__name__'], {}), "('tags', __name__)\n", (141, 159), False, 'from flask import Blueprint, jsonify, request\n'), ((345, 360), 'app.models.Tag.query.all', 'Tag.query.all', ([], {}), '()\n', (358, 360), False, 'from app.models import db, Tag\n'), ((416, 429), ... |
import os
import logging
import discord
from discord.ext import commands
from discord.ext.commands import DefaultHelpCommand
from dotenv import load_dotenv
# logs data to the discord.log file, if this file doesn't exist at runtime it is created automatically
from cogs.utilities import Utilities
logger = logging.get... | [
"logging.getLogger",
"os.getenv",
"discord.ext.commands.DefaultHelpCommand",
"discord.ext.commands.Bot",
"logging.Formatter",
"cogs.utilities.Utilities",
"dotenv.load_dotenv",
"logging.FileHandler",
"discord.Activity",
"logging.error"
] | [((309, 337), 'logging.getLogger', 'logging.getLogger', (['"""discord"""'], {}), "('discord')\n", (326, 337), False, 'import logging\n'), ((462, 533), 'logging.FileHandler', 'logging.FileHandler', ([], {'filename': '"""discord.log"""', 'encoding': '"""utf-8"""', 'mode': '"""w"""'}), "(filename='discord.log', encoding='... |
import pygame
import colors
import Lists
class pointGains(pygame.sprite.Sprite):
def __init__(self,color,x,y,value,startTime,pg):
# Call the parent class (Sprite) constructor
pygame.sprite.Sprite.__init__(self)
# Create an image of the block, and fill it with a color.
# This could... | [
"pygame.sprite.Sprite.__init__",
"pygame.Surface",
"pygame.time.get_ticks",
"Lists.all_sprites_list.add"
] | [((1091, 1128), 'Lists.all_sprites_list.add', 'Lists.all_sprites_list.add', (['newPoints'], {}), '(newPoints)\n', (1117, 1128), False, 'import Lists\n'), ((197, 232), 'pygame.sprite.Sprite.__init__', 'pygame.sprite.Sprite.__init__', (['self'], {}), '(self)\n', (226, 232), False, 'import pygame\n'), ((381, 405), 'pygame... |
#!/usr/bin/env python
# Copyright 2018 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 or ... | [
"google.cloud.vision_v1p4beta1.types.GcsSource",
"google.cloud.storage.Client",
"google.cloud.vision_v1p4beta1.ImageAnnotatorClient",
"argparse.ArgumentParser",
"google.cloud.vision_v1p4beta1.types.AnnotateFileRequest",
"google.cloud.vision_v1p4beta1.types.GcsDestination",
"google.cloud.vision_v1p4beta1... | [((1442, 1471), 'google.cloud.vision_v1p4beta1.ImageAnnotatorClient', 'vision.ImageAnnotatorClient', ([], {}), '()\n', (1469, 1471), True, 'from google.cloud import vision_v1p4beta1 as vision\n'), ((1562, 1597), 'google.cloud.vision_v1p4beta1.types.Image', 'vision.types.Image', ([], {'content': 'content'}), '(content=c... |
#!/usr/bin/env python
"""
@author <NAME>
"""
import roboticstoolbox as rtb
import time
from roboticstoolbox.backends.VPython import VPython
env = VPython()
env.launch()
# PUMA560
puma = rtb.models.DH.Puma560()
env.add(puma)
qt = rtb.tools.trajectory.jtraj(puma.qz, puma.qr, 200)
for q in qt.q:
env.step(0.1)
... | [
"roboticstoolbox.backends.VPython.VPython",
"roboticstoolbox.models.DH.Puma560",
"roboticstoolbox.tools.trajectory.jtraj"
] | [((149, 158), 'roboticstoolbox.backends.VPython.VPython', 'VPython', ([], {}), '()\n', (156, 158), False, 'from roboticstoolbox.backends.VPython import VPython\n'), ((192, 215), 'roboticstoolbox.models.DH.Puma560', 'rtb.models.DH.Puma560', ([], {}), '()\n', (213, 215), True, 'import roboticstoolbox as rtb\n'), ((236, 2... |
# MIT License
#
# Copyright (c) 2020 <NAME>
#
# 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 the rights
# to use, copy, modify, merge,... | [
"logging.getLogger",
"cicd.informatica.executeInfacmd.execute",
"cicd.informatica.infaSettings.get_dis_name",
"supporting.mask_password.mask_password",
"supporting.filehandling.removefile",
"supporting.log",
"supporting.filehandling.convert_content_to_array",
"supporting.filehandling.generate_tmp_file... | [((1508, 1535), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1525, 1535), False, 'import logging\n'), ((1730, 1766), 'supporting.filehandling.generate_tmp_filename', 'filehandling.generate_tmp_filename', ([], {}), '()\n', (1764, 1766), False, 'from supporting import filehandling\n'), (... |
"""
Implicit gradient-enhanced damage model in dolfinx
==================================================
For the theory and the constitutive model, please refer to the dolfin version :ref:`gdm-label`.
Here, you see the "quadrature" approach working in dolfinx without the need of `LocalProject`.
"""
from gdm_constit... | [
"matplotlib.pyplot.ylabel",
"dolfinx.fem.apply_lifting",
"petsc4py.PETSc.ScalarType",
"dolfinx.fem.Constant",
"basix.make_quadrature",
"ufl.split",
"dolfinx.fem.petsc.assemble_matrix",
"dolfinx.fem.Expression",
"matplotlib.pyplot.loglog",
"dolfinx.nls.petsc.NewtonSolver",
"matplotlib.pyplot.xlab... | [((5748, 5767), 'gdm_analytic.PeerlingsAnalytic', 'PeerlingsAnalytic', ([], {}), '()\n', (5765, 5767), False, 'from gdm_analytic import PeerlingsAnalytic\n'), ((5780, 5900), 'dolfinx.mesh.create_rectangle', 'df.mesh.create_rectangle', (['MPI.COMM_WORLD', '[[0, 0], [e.L / 2.0, 1]]', '[n_elements, 1]', 'df.mesh.CellType.... |
from django.contrib.auth.models import User
from django.test import Client, TestCase
from django.urls import reverse
class WebpageTest(TestCase):
def setUp(self):
self.client = Client()
User.objects.create_user('temporary', '<EMAIL>', 'temporary')
def test_webpage(self):
rv = self.cl... | [
"django.urls.reverse",
"django.contrib.auth.models.User.objects.create_user",
"django.test.Client"
] | [((192, 200), 'django.test.Client', 'Client', ([], {}), '()\n', (198, 200), False, 'from django.test import Client, TestCase\n'), ((209, 270), 'django.contrib.auth.models.User.objects.create_user', 'User.objects.create_user', (['"""temporary"""', '"""<EMAIL>"""', '"""temporary"""'], {}), "('temporary', '<EMAIL>', 'temp... |
"""Test the colorlog.colorlog module."""
import sys
import pytest
def test_colored_formatter(create_and_test_logger):
create_and_test_logger()
def test_custom_colors(create_and_test_logger):
"""Disable all colors and check no escape codes are output."""
create_and_test_logger(
log_colors={}, r... | [
"pytest.mark.skipif"
] | [((2000, 2074), 'pytest.mark.skipif', 'pytest.mark.skipif', (['(sys.version_info < (3, 2))'], {'reason': '"""requires python3.2"""'}), "(sys.version_info < (3, 2), reason='requires python3.2')\n", (2018, 2074), False, 'import pytest\n'), ((2219, 2293), 'pytest.mark.skipif', 'pytest.mark.skipif', (['(sys.version_info < ... |
import numpy as np
import pytest
from nlp_profiler.granular_features.numbers import \
NaN, gather_whole_numbers, count_whole_numbers # noqa
text_with_a_number = '2833047 people live in this area'
text_to_return_value_mapping = [
(np.nan, []),
(float('nan'), []),
(None, []),
]
@pytest.mark.parametr... | [
"pytest.mark.parametrize",
"nlp_profiler.granular_features.numbers.gather_whole_numbers",
"nlp_profiler.granular_features.numbers.count_whole_numbers"
] | [((300, 377), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""text,expected_result"""', 'text_to_return_value_mapping'], {}), "('text,expected_result', text_to_return_value_mapping)\n", (323, 377), False, 'import pytest\n'), ((799, 876), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""text,expec... |
from bs4 import BeautifulSoup
import inspect
import os
from pprint import pprint
import sys
# add parent directory to sys path to import relative modules
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
parentdir = os.path.dirname(parentdir... | [
"bs4.BeautifulSoup",
"os.path.dirname",
"sys.path.insert",
"inspect.currentframe"
] | [((255, 282), 'os.path.dirname', 'os.path.dirname', (['currentdir'], {}), '(currentdir)\n', (270, 282), False, 'import os\n'), ((295, 321), 'os.path.dirname', 'os.path.dirname', (['parentdir'], {}), '(parentdir)\n', (310, 321), False, 'import os\n'), ((322, 351), 'sys.path.insert', 'sys.path.insert', (['(0)', 'parentdi... |
"""Helper functions for a standard streaming compression API"""
from bz2 import BZ2File
from gzip import GzipFile
from zipfile import ZipFile
import fsspec.utils
from fsspec.spec import AbstractBufferedFile
def noop_file(file, mode, **kwargs):
return file
# should be functions of the form func(infile, mode=, *... | [
"snappy.StreamCompressor",
"zipfile.ZipFile",
"zstandard.ZstdCompressor",
"gzip.GzipFile",
"snappy.StreamDecompressor",
"zstandard.ZstdDecompressor"
] | [((2099, 2114), 'zipfile.ZipFile', 'ZipFile', (['infile'], {}), '(infile)\n', (2106, 2114), False, 'from zipfile import ZipFile\n'), ((1932, 1967), 'zipfile.ZipFile', 'ZipFile', (['infile'], {'mode': '"""w"""'}), "(infile, mode='w', **kwargs)\n", (1939, 1967), False, 'from zipfile import ZipFile\n'), ((2360, 2389), 'gz... |
# -*- coding: utf-8 -*-
"""Output functions for BEL graphs to Neo4j."""
from six import string_types
from tqdm import tqdm
from ..constants import (
ANNOTATIONS, CITATION, CITATION_REFERENCE, CITATION_TYPE, EVIDENCE, FUSION, MEMBERS, NAMESPACE, OBJECT,
RELATION, SUBJECT, VARIANTS,
)
from ..utils import flatt... | [
"py2neo.Relationship",
"py2neo.Graph",
"tqdm.tqdm",
"py2neo.Node"
] | [((1134, 1162), 'py2neo.Graph', 'py2neo.Graph', (['neo_connection'], {}), '(neo_connection)\n', (1146, 1162), False, 'import py2neo\n'), ((1273, 1298), 'tqdm.tqdm', 'tqdm', (['nodes'], {'desc': '"""nodes"""'}), "(nodes, desc='nodes')\n", (1277, 1298), False, 'from tqdm import tqdm\n'), ((1885, 1920), 'py2neo.Node', 'py... |
from django.db import migrations
INSTANCE_TYPE = 'OpenStackTenant.Instance'
VOLUME_TYPE = 'OpenStackTenant.Volume'
def change_billing_types(apps, schema_editor):
Offering = apps.get_model('marketplace', 'Offering')
OfferingComponent = apps.get_model('marketplace', 'OfferingComponent')
for offering in O... | [
"django.db.migrations.RunPython"
] | [((835, 877), 'django.db.migrations.RunPython', 'migrations.RunPython', (['change_billing_types'], {}), '(change_billing_types)\n', (855, 877), False, 'from django.db import migrations\n')] |
import asyncio
import random
import arrow
import discord
from discord.ext import commands, tasks
from libraries import emoji_literals
from modules import emojis, log, queries, util
logger = log.get_logger(__name__)
command_logger = log.get_command_logger()
class Events(commands.Cog):
"""Event handlers for vari... | [
"modules.queries.save_command_usage",
"modules.util.find_custom_emojis",
"modules.log.get_logger",
"discord.ext.commands.Cog.listener",
"modules.log.get_command_logger",
"asyncio.gather",
"discord.ext.tasks.loop",
"random.randint",
"modules.util.create_goodbye_message",
"libraries.emoji_literals.U... | [((193, 217), 'modules.log.get_logger', 'log.get_logger', (['__name__'], {}), '(__name__)\n', (207, 217), False, 'from modules import emojis, log, queries, util\n'), ((235, 259), 'modules.log.get_command_logger', 'log.get_command_logger', ([], {}), '()\n', (257, 259), False, 'from modules import emojis, log, queries, u... |
from django import forms
from truco.constants import PUNTOS
class NuevaSalaForm(forms.Form):
Nombre = forms.CharField(max_length=50)
Puntos = forms.ChoiceField(widget=forms.RadioSelect,choices=[(15,'15'),(30,'30')])
num_jug = forms.ChoiceField(label='Cantidad de jugadores',choices=[(2,'2'),(4,'4'),(6,'6')]... | [
"django.forms.ChoiceField",
"django.forms.CharField"
] | [((107, 137), 'django.forms.CharField', 'forms.CharField', ([], {'max_length': '(50)'}), '(max_length=50)\n', (122, 137), False, 'from django import forms\n'), ((151, 228), 'django.forms.ChoiceField', 'forms.ChoiceField', ([], {'widget': 'forms.RadioSelect', 'choices': "[(15, '15'), (30, '30')]"}), "(widget=forms.Radio... |
import pytest
from .context import mock, builtin_str
@pytest.fixture(scope='function')
def func():
def dummy(*agrs, **kwargs):
pass
f = mock.create_autospec(spec=dummy, name='fixture_function_to_decorate')
return f
@pytest.fixture(scope='function', autouse=True)
@mock.patch('{builtin}.open'.forma... | [
"pytest.fixture"
] | [((56, 88), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (70, 88), False, 'import pytest\n'), ((239, 285), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""', 'autouse': '(True)'}), "(scope='function', autouse=True)\n", (253, 285), False, 'import pytest... |
#
# Collective Knowledge (individual environment - setup)
#
# See CK LICENSE.txt for licensing details
# See CK COPYRIGHT.txt for copyright details
#
# Developer: <NAME>, <EMAIL>, http://fursin.net
#
import os
##############################################################################
# customize directories to au... | [
"os.path.dirname",
"os.path.join"
] | [((1282, 1301), 'os.path.dirname', 'os.path.dirname', (['fp'], {}), '(fp)\n', (1297, 1301), False, 'import os\n'), ((1326, 1351), 'os.path.join', 'os.path.join', (['p1', '"""lib64"""'], {}), "(p1, 'lib64')\n", (1338, 1351), False, 'import os\n'), ((1614, 1633), 'os.path.dirname', 'os.path.dirname', (['p1'], {}), '(p1)\... |
import numpy as np
import scipy as sp
import scipy.sparse
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.path
import time
plt.ion()
import pybie2d
"""
Demonstrate how to use the pybie2d package to solve an interior Laplace problem
On a complicated domain using a global quadrature
This exam... | [
"numpy.abs",
"numpy.eye",
"numpy.ma.array",
"numpy.linalg.inv",
"matplotlib.pyplot.ion",
"scipy.sparse.csr_matrix",
"numpy.zeros_like",
"matplotlib.pyplot.subplots"
] | [((150, 159), 'matplotlib.pyplot.ion', 'plt.ion', ([], {}), '()\n', (157, 159), True, 'import matplotlib.pyplot as plt\n'), ((2983, 2999), 'numpy.linalg.inv', 'np.linalg.inv', (['A'], {}), '(A)\n', (2996, 2999), True, 'import numpy as np\n'), ((3298, 3321), 'numpy.zeros_like', 'np.zeros_like', (['gridp.xg'], {}), '(gri... |
#!/usr/bin/env python
"""Implementation and improvement of the paper:
Unsupervised learning and segmentation of complex activities from video.
"""
__author__ = '<NAME>'
__date__ = 'June 2019'
import sys
import os
sys.path.append(os.path.abspath('.').split('data_utils')[0])
sys.path.append('/scratch/liju2/unsupervise... | [
"ute.ute_pipeline.temp_embed",
"data_utils.BF_utils.update_argpars.update",
"ute.ute_pipeline.all_actions",
"os.path.abspath",
"sys.path.append"
] | [((277, 367), 'sys.path.append', 'sys.path.append', (['"""/scratch/liju2/unsupervised_AS/unsup_temp_embed_learned_classifier"""'], {}), "(\n '/scratch/liju2/unsupervised_AS/unsup_temp_embed_learned_classifier')\n", (292, 367), False, 'import sys\n'), ((1187, 1195), 'data_utils.BF_utils.update_argpars.update', 'updat... |
# Generated by Django 3.1.12 on 2021-08-19 15:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bills', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='bill',
name='es_similar_bills_dict',
... | [
"django.db.models.JSONField"
] | [((337, 390), 'django.db.models.JSONField', 'models.JSONField', ([], {'blank': '(True)', 'default': 'dict', 'null': '(True)'}), '(blank=True, default=dict, null=True)\n', (353, 390), False, 'from django.db import migrations, models\n')] |
from drltools.utils import dqn_config, trainer
from drltools.agent import DQNAgent
from unityagents import UnityEnvironment
env = UnityEnvironment(file_name="unity_environments/Banana_mac.app", worker_id=1)
config = dqn_config
agent_class = DQNAgent
n_episodes = 2000
max_t = 1000
solved_score = 13
title = 'DQN'
if _... | [
"unityagents.UnityEnvironment",
"drltools.utils.trainer"
] | [((132, 208), 'unityagents.UnityEnvironment', 'UnityEnvironment', ([], {'file_name': '"""unity_environments/Banana_mac.app"""', 'worker_id': '(1)'}), "(file_name='unity_environments/Banana_mac.app', worker_id=1)\n", (148, 208), False, 'from unityagents import UnityEnvironment\n'), ((348, 421), 'drltools.utils.trainer',... |
from flask import Flask, jsonify, request
from flask_jwt import JWT
from flask_restful import Api
from flask_cors import CORS
from helper.formatHelper import formatScore, formatBasic, formatFull
from helper.analyze import getBestFit
from helper.dataHelper import getData, getAll, search
from resource.user import UserRe... | [
"helper.dataHelper.getData",
"helper.dataHelper.search",
"flask_cors.CORS",
"flask_restful.Api",
"flask.Flask",
"helper.formatHelper.formatFull",
"flask_jwt.JWT",
"helper.formatHelper.formatBasic",
"helper.formatHelper.formatScore",
"helper.dataHelper.getAll",
"helper.analyze.getBestFit",
"cre... | [((425, 440), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (430, 440), False, 'from flask import Flask, jsonify, request\n'), ((441, 450), 'flask_cors.CORS', 'CORS', (['app'], {}), '(app)\n', (445, 450), False, 'from flask_cors import CORS\n'), ((484, 492), 'flask_restful.Api', 'Api', (['app'], {}), '(ap... |
# MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from __future__ import unicode_literals
import swapper
from accelerator_abstract.models.base_judging_round import BaseJudgingRound
class JudgingRound(BaseJudgingRound):
class Meta(BaseJudgingRound.Meta):
swappable = swapper.swappable_setting(BaseJu... | [
"swapper.swappable_setting"
] | [((288, 362), 'swapper.swappable_setting', 'swapper.swappable_setting', (['BaseJudgingRound.Meta.app_label', '"""JudgingRound"""'], {}), "(BaseJudgingRound.Meta.app_label, 'JudgingRound')\n", (313, 362), False, 'import swapper\n')] |
import asyncio
import logging
import time
from websockets import WebSocketServerProtocol
logging.basicConfig(level=logging.INFO)
# Code adapted from https://medium.com/better-programming/how-to-create-a-websocket-in-python-b68d65dbd549
class Server:
clients = set()
async def register(self, ws):
sel... | [
"logging.basicConfig",
"logging.info",
"time.time"
] | [((91, 130), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (110, 130), False, 'import logging\n'), ((346, 392), 'logging.info', 'logging.info', (['f"""{ws.remote_address} connects."""'], {}), "(f'{ws.remote_address} connects.')\n", (358, 392), False, 'import lo... |
from fastapi import (
FastAPI,
Depends,
)
from CTFe.config.database import dal
from CTFe.utils import (
validators,
enums,
)
from CTFe.views import (
auth_router,
user_router,
team_router,
challenge_router,
attempt_router,
player_router,
contributor_router,
)
app = FastAPI... | [
"CTFe.utils.validators.validate_user_type",
"fastapi.FastAPI",
"uvicorn.run"
] | [((313, 322), 'fastapi.FastAPI', 'FastAPI', ([], {}), '()\n', (320, 322), False, 'from fastapi import FastAPI, Depends\n'), ((1393, 1461), 'uvicorn.run', 'uvicorn.run', (['"""CTFe.main:app"""'], {'host': '"""0.0.0.0"""', 'port': '(8000)', 'reload': '(True)'}), "('CTFe.main:app', host='0.0.0.0', port=8000, reload=True)\... |
"""class_schedule_card URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')... | [
"django.urls.path"
] | [((977, 1008), 'django.urls.path', 'path', (['"""admin/"""', 'admin.site.urls'], {}), "('admin/', admin.site.urls)\n", (981, 1008), False, 'from django.urls import path\n'), ((1014, 1033), 'django.urls.path', 'path', (['"""home/"""', 'home'], {}), "('home/', home)\n", (1018, 1033), False, 'from django.urls import path\... |
from gensim import corpora, models
import pickle
with open('../../data/doc_list.pk','rb') as f:
doc_list = pickle.load(f)
dictionary = corpora.Dictionary(words_ls)
corpus = [dictionary.doc2bow(words) for words in words_ls]
lda = models.ldamodel.LdaModel(corpus=corpus, id2word=dictionary, num_topics=10)
for topi... | [
"gensim.models.ldamodel.LdaModel",
"pickle.load",
"gensim.corpora.Dictionary"
] | [((140, 168), 'gensim.corpora.Dictionary', 'corpora.Dictionary', (['words_ls'], {}), '(words_ls)\n', (158, 168), False, 'from gensim import corpora, models\n'), ((236, 310), 'gensim.models.ldamodel.LdaModel', 'models.ldamodel.LdaModel', ([], {'corpus': 'corpus', 'id2word': 'dictionary', 'num_topics': '(10)'}), '(corpus... |
import datetime
from django.conf import settings
from django.contrib.auth.models import AbstractUser
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from model_clone import CloneMixin
from django.contrib.postgres.fields import ArrayField
from dataprocessing.models ... | [
"django.core.validators.MinValueValidator",
"django.db.models.TextField",
"django.db.models.ForeignKey",
"django.db.models.IntegerField",
"django.db.models.ManyToManyField",
"django.db.models.BooleanField",
"django.db.models.DateTimeField",
"django.db.models.DecimalField",
"datetime.date.today",
"... | [((1831, 1908), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'editable': '(True)', 'auto_now_add': '(True)', 'blank': '(True)', 'null': '(True)'}), '(editable=True, auto_now_add=True, blank=True, null=True)\n', (1851, 1908), False, 'from django.db import models\n'), ((1931, 1987), 'django.db.models.C... |
from .. import engines
from ..errors import SimError
# 8<----------------- Compatibility layer -----------------
class ExplorationTechniqueMeta(type):
def __new__(mcs, name, bases, attrs):
import inspect
if name != 'ExplorationTechniqueCompat':
if 'step' in attrs and not inspect.getar... | [
"inspect.getargspec"
] | [((307, 340), 'inspect.getargspec', 'inspect.getargspec', (["attrs['step']"], {}), "(attrs['step'])\n", (325, 340), False, 'import inspect\n'), ((447, 482), 'inspect.getargspec', 'inspect.getargspec', (["attrs['filter']"], {}), "(attrs['filter'])\n", (465, 482), False, 'import inspect\n'), ((613, 652), 'inspect.getargs... |
import numpy
n = int(input())
matrix = []
for i in range(n):
matrix.append(list(map(float,input().split())))
print(round(numpy.linalg.det(matrix), 2))
| [
"numpy.linalg.det"
] | [((129, 153), 'numpy.linalg.det', 'numpy.linalg.det', (['matrix'], {}), '(matrix)\n', (145, 153), False, 'import numpy\n')] |
import json
from random import randint
from time import sleep
import redis
if __name__ == "__main__":
fila = redis.Redis(host='queue')
while True:
email = fila.lpop('emails')
if email:
print('worker', email)
email = json.loads(email)
print(f'enviando e-mai... | [
"json.loads",
"random.randint",
"redis.Redis"
] | [((115, 140), 'redis.Redis', 'redis.Redis', ([], {'host': '"""queue"""'}), "(host='queue')\n", (126, 140), False, 'import redis\n'), ((268, 285), 'json.loads', 'json.loads', (['email'], {}), '(email)\n', (278, 285), False, 'import json\n'), ((350, 365), 'random.randint', 'randint', (['(10)', '(50)'], {}), '(10, 50)\n',... |
#!/usr/bin/python3
#
#
#
#
# <NAME> (January 2019), contact: <EMAIL>
import pandas as pd
import re
import sys,os
import numpy as np
import csv
import argparse
from datetime import datetime
def parse_arguments():
parser = argparse.ArgumentParser( description='Assimilate low resolution HLA type data.')
parser... | [
"pandas.isnull",
"argparse.ArgumentParser",
"csv.writer",
"os.path.join",
"re.match",
"os.path.dirname",
"datetime.datetime.now",
"os.path.basename",
"pandas.read_excel",
"os.path.abspath",
"re.sub",
"pandas.ExcelWriter",
"re.search"
] | [((229, 308), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Assimilate low resolution HLA type data."""'}), "(description='Assimilate low resolution HLA type data.')\n", (252, 308), False, 'import argparse\n'), ((588, 625), 'pandas.read_excel', 'pd.read_excel', (['data_file', '"""Main d... |
# -*- coding: utf-8 -*-
# Copyright 2020 The PsiZ 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 r... | [
"tensorflow.pow",
"tensorflow.keras.initializers.serialize",
"psiz.keras.constraints.GreaterEqualThan",
"tensorflow.keras.utils.register_keras_serializable",
"tensorflow.negative",
"tensorflow.keras.initializers.get",
"tensorflow.python.keras.backend.floatx",
"tensorflow.random_uniform_initializer"
] | [((967, 1072), 'tensorflow.keras.utils.register_keras_serializable', 'tf.keras.utils.register_keras_serializable', ([], {'package': '"""psiz.keras.layers"""', 'name': '"""HeavyTailedSimilarity"""'}), "(package='psiz.keras.layers',\n name='HeavyTailedSimilarity')\n", (1009, 1072), True, 'import tensorflow as tf\n'), ... |
#!/usr/bin/python3
import sys
import os.path
import subprocess
gitDir = '/media/HD'
outputFile = '/home/xxx/output.txt'
def pPrint(text):
print('\033[95m' + str(text) + '\033[0m')
def main():
# Checks if a directory was specified in the command line call:
if len(sys.argv) > 1:
global gitDir
gitDir = str(sys... | [
"subprocess.check_output"
] | [((536, 597), 'subprocess.check_output', 'subprocess.check_output', (['"""du -hs ./*"""'], {'shell': '(True)', 'cwd': 'gitDir'}), "('du -hs ./*', shell=True, cwd=gitDir)\n", (559, 597), False, 'import subprocess\n')] |
#
# Author: <NAME>
# Copyright 2015-present, NASA-JPL/Caltech
#
import os
import glob
import logging
import datetime
import numpy as np
import isceobj
import isceobj.Sensor.MultiMode as MultiMode
from isceobj.Planet.Planet import Planet
from isceobj.Alos2Proc.Alos2ProcPublic import runCmd
from isceobj.Alos2Proc.Alos2... | [
"logging.getLogger",
"os.makedirs",
"isceobj.Catalog.createCatalog",
"os.path.join",
"isceobj.Sensor.MultiMode.createSwath",
"os.chdir",
"numpy.array",
"numpy.argsort",
"isceobj.Sensor.MultiMode.createFrame",
"os.path.basename",
"os.path.abspath"
] | [((478, 530), 'logging.getLogger', 'logging.getLogger', (['"""isce.alos2insar.runPreprocessor"""'], {}), "('isce.alos2insar.runPreprocessor')\n", (495, 530), False, 'import logging\n'), ((604, 659), 'isceobj.Catalog.createCatalog', 'isceobj.Catalog.createCatalog', (['self._insar.procDoc.name'], {}), '(self._insar.procD... |
#!/usr/bin/python3
from common import runsql
import os,sys,glob,json
import datetime
import re
server = sys.argv[1]
if os.environ.get("P", None):
os.chdir(os.environ["P"])
else:
os.chdir("/var/lib/docker/containers")
sql = "replace into dockers(server, name, id, starttime, runningtime, memlimit, foldername) val... | [
"os.path.exists",
"json.loads",
"os.environ.get",
"os.chdir",
"os.path.getmtime",
"re.findall",
"common.runsql",
"glob.glob"
] | [((119, 144), 'os.environ.get', 'os.environ.get', (['"""P"""', 'None'], {}), "('P', None)\n", (133, 144), False, 'import os, sys, glob, json\n'), ((357, 372), 'glob.glob', 'glob.glob', (['"""*/"""'], {}), "('*/')\n", (366, 372), False, 'import os, sys, glob, json\n'), ((1431, 1460), 'common.runsql', 'runsql', (['sql[:-... |
import sys
sys.path.extend(["./"])
import numpy as np
import torch
from clustorch.kmeans import KMeans
from src.threat.clustering.constrained_poisoning import ConstrainedAdvPoisoningGlobal
from experiments.utilities import ClusteringWrapper3Dto2D, set_seed
X = np.load("comparison/SEEDS/kme_X_org.npy")
Xadv_s = np.l... | [
"experiments.utilities.ClusteringWrapper3Dto2D",
"experiments.utilities.set_seed",
"torch.from_numpy",
"torch.nonzero",
"numpy.array",
"numpy.zeros",
"sys.path.extend",
"numpy.load",
"clustorch.kmeans.KMeans"
] | [((12, 35), 'sys.path.extend', 'sys.path.extend', (["['./']"], {}), "(['./'])\n", (27, 35), False, 'import sys\n'), ((265, 306), 'numpy.load', 'np.load', (['"""comparison/SEEDS/kme_X_org.npy"""'], {}), "('comparison/SEEDS/kme_X_org.npy')\n", (272, 306), True, 'import numpy as np\n'), ((316, 357), 'numpy.load', 'np.load... |
import heapq
# <NAME>
# Artificial Intelligence Assign 01
# DFS and A* algorithms acting on Node class who's state is represented as a dictionary
# DFS's fringe/frontier is a list and A* is a min-priority queue, using the heapq module
# Since dictionaries aren't hashable, the closed/reached set contains string repres... | [
"heapq.heappop",
"heapq.heappush"
] | [((13805, 13834), 'heapq.heappop', 'heapq.heappop', (['priority_queue'], {}), '(priority_queue)\n', (13818, 13834), False, 'import heapq\n'), ((9497, 9574), 'heapq.heappush', 'heapq.heappush', (['priority_queue', '(new_node.total_cost, state_string, new_node)'], {}), '(priority_queue, (new_node.total_cost, state_string... |
"""Trace treadmill application events.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import os
import socket
import sys
import click
import gevent
from gevent import queue as g_queue
import six... | [
"logging.getLogger",
"treadmill.context.GLOBAL.state_api",
"os.open",
"click.echo",
"sys.exit",
"click.option",
"subprocess.Popen",
"click.command",
"treadmill.utils.sane_execvp",
"click.argument",
"gevent.queue.JoinableQueue",
"os.close",
"os.path.dirname",
"treadmill.restclient.get",
"... | [((703, 730), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (720, 730), False, 'import logging\n'), ((894, 943), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (907, 943), False, 'import socket\n'), ((1856, 1886... |
# (C) Copyright 2005-2021 Enthought, Inc., Austin, TX
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in LICENSE.txt and may be redistributed only under
# the conditions described in the aforementioned license. The license
# is also available online at... | [
"traits.api.Str",
"traits.api.File",
"os.path.join",
"traits.api.Array",
"os.path.dirname",
"traits.api.Tuple",
"datetime.datetime.today",
"traits.api.Date"
] | [((5816, 5841), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (5831, 5841), False, 'import os\n'), ((5854, 5886), 'os.path.join', 'os.path.join', (['this_dir', '"""images"""'], {}), "(this_dir, 'images')\n", (5866, 5886), False, 'import os\n'), ((5898, 5940), 'os.path.join', 'os.path.join', ... |
import komand
import time
from .schema import GetThreatsInput, GetThreatsOutput, Input, Output
# Custom imports below
from datetime import datetime
class GetThreats(komand.Trigger):
def __init__(self):
super(self.__class__, self).__init__(
name='get_threats',
description='... | [
"datetime.datetime.now",
"komand.helper.clean",
"time.sleep"
] | [((862, 876), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (874, 876), False, 'from datetime import datetime\n'), ((1417, 1431), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1429, 1431), False, 'from datetime import datetime\n'), ((1444, 1465), 'time.sleep', 'time.sleep', (['frequency'], {}... |
import tensorflow as tf
import numpy as np
from PIL import Image
import os
import glob
import platform
import argparse
from scipy.io import loadmat,savemat
from preprocess_img import align_img
from utils import *
from face_decoder import Face3D
from options import Option
is_windows = True
def parse_args():
des... | [
"numpy.clip",
"options.Option",
"networks.R_Net",
"os.path.exists",
"tensorflow.Graph",
"argparse.ArgumentParser",
"face_decoder.Face3D",
"tensorflow.placeholder",
"tensorflow.Session",
"tensorflow.trainable_variables",
"preprocess_img.align_img",
"glob.glob",
"tensorflow.device",
"tensorf... | [((364, 405), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': 'desc'}), '(description=desc)\n', (387, 405), False, 'import argparse\n'), ((676, 700), 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (698, 700), True, 'import tensorflow as tf\n'), ((711, 732), 'ten... |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under th... | [
"openstack.placement.v1.resource_class.ResourceClass"
] | [((761, 779), 'openstack.placement.v1.resource_class.ResourceClass', 'rc.ResourceClass', ([], {}), '()\n', (777, 779), True, 'from openstack.placement.v1 import resource_class as rc\n'), ((1370, 1394), 'openstack.placement.v1.resource_class.ResourceClass', 'rc.ResourceClass', ([], {}), '(**FAKE)\n', (1386, 1394), True,... |
import abc
from typing import Dict, List, Optional, TypeVar
import numpy as np
from pydantic import BaseModel
from ..constants import ZEROISH, Dtype
class DatasetMetadata(BaseModel):
id: Optional[int]
name: str = ""
dose_units: str = ""
response_units: str = ""
dose_name: str = ""
response_n... | [
"numpy.max",
"numpy.min",
"typing.TypeVar"
] | [((2869, 2910), 'typing.TypeVar', 'TypeVar', (['"""DatasetType"""'], {'bound': 'DatasetBase'}), "('DatasetType', bound=DatasetBase)\n", (2876, 2910), False, 'from typing import Dict, List, Optional, TypeVar\n'), ((1276, 1294), 'numpy.min', 'np.min', (['self.doses'], {}), '(self.doses)\n', (1282, 1294), True, 'import nu... |
# Copyright 2004-2019 <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 in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish,... | [
"sys.exc_info"
] | [((13880, 13894), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (13892, 13894), False, 'import sys\n')] |
from sklearn.linear_model import LogisticRegression
import numpy as np
from . import AbstractZnormClassifier
class LogisticRegressionClassifier(AbstractZnormClassifier):
"""Classifier which uses regularized logistic regression"""
def __init__(self, C=1, phi=None, degree=3, **kwargs):
# keyword argum... | [
"numpy.swapaxes",
"numpy.arange",
"sklearn.linear_model.LogisticRegression"
] | [((908, 941), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {'C': 'C'}), '(C=C, **kwargs)\n', (926, 941), False, 'from sklearn.linear_model import LogisticRegression\n'), ((1564, 1592), 'numpy.swapaxes', 'np.swapaxes', (['ft_powers', '(0)', '(1)'], {}), '(ft_powers, 0, 1)\n', (1575, 1592), True,... |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# 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 requi... | [
"torch.nn.BatchNorm2d",
"opacus.validators.module_validator.ModuleValidator.validate",
"opacus.validators.module_validator.ModuleValidator.is_valid",
"torch.nn.Bilinear",
"torch.Tensor",
"torch.nn.Conv2d",
"torch.nn.Linear",
"torchvision.models.mobilenet_v3_small",
"opacus.validators.module_validato... | [((948, 968), 'torchvision.models.mobilenet_v3_small', 'mobilenet_v3_small', ([], {}), '()\n', (966, 968), False, 'from torchvision.models import mobilenet_v3_small\n'), ((996, 1036), 'opacus.validators.module_validator.ModuleValidator.fix', 'ModuleValidator.fix', (['self.original_model'], {}), '(self.original_model)\n... |
import numpy as np
v0 = 4.5 # Initial velocity
g = 9.81 # Acceleration of gravity
t = np.linspace(0, 1, 1000) # 1000 points in time interval
y = v0*t - 0.5*g*t**2 # Generate all heights
# Find index where ball approximately has reached y=0
i = 0
while y[i] >= 0... | [
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.linspace",
"matplotlib.pyplot.show"
] | [((131, 154), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(1000)'], {}), '(0, 1, 1000)\n', (142, 154), True, 'import numpy as np\n'), ((580, 594), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'y'], {}), '(t, y)\n', (588, 594), True, 'import matplotlib.pyplot as plt\n'), ((596, 621), 'matplotlib.pyplot.plot', 'plt... |
import networkx as nx
import scipy.optimize
def BPR(x, m, fcoeffs, exo):
return sum([fcoeffs[i]*((x+exo)/m)**i for i in range(len(fcoeffs))])
def BPR_social(x, m, fcoeffs, exo):
return sum([fcoeffs[i]*((x+exo)/m)**i for i in range(len(fcoeffs))]) + sum([fcoeffs[i+1]*(i+1) *((x+exo)/m)**(i) for i in range(len(fcoe... | [
"networkx.shortest_path"
] | [((1520, 1573), 'networkx.shortest_path', 'nx.shortest_path', (['G'], {'source': 's', 'target': 't', 'weight': '"""t_k"""'}), "(G, source=s, target=t, weight='t_k')\n", (1536, 1573), True, 'import networkx as nx\n')] |
import copy
import json
import types
from typing import Dict, NamedTuple
from io import StringIO
from argparse import ArgumentParser
import unittest
from unittest.mock import patch
import sap.adt
import sap.cli.core
class Response:
def __init__(self, text=None, status_code=None, headers=None, content_type=None... | [
"json.loads",
"argparse.ArgumentParser",
"types.SimpleNamespace",
"json.dumps",
"io.StringIO",
"unittest.mock.patch"
] | [((13135, 13185), 'types.SimpleNamespace', 'types.SimpleNamespace', ([], {'RFCLibError': 'TestRFCLibError'}), '(RFCLibError=TestRFCLibError)\n', (13156, 13185), False, 'import types\n'), ((13198, 13245), 'types.SimpleNamespace', 'types.SimpleNamespace', ([], {'_exception': 'mod_exception'}), '(_exception=mod_exception)... |
"""
Django project settings for developer's local environment.
"""
import os
from .base import * # noqa
DEBUG = True
ALLOWED_HOSTS = [
'localhost',
'0.0.0.0',
'127.0.0.1',
'.ngrok.io',
]
INSTALLED_APPS = INSTALLED_APPS + ['debug_toolbar',]
MIDDLEWARE = MIDDLEWARE + [
'debug_toolbar.middleware.De... | [
"os.path.join"
] | [((854, 893), 'os.path.join', 'os.path.join', (['ROOT_DIR', '"""rmp"""', '"""static"""'], {}), "(ROOT_DIR, 'rmp', 'static')\n", (866, 893), False, 'import os\n')] |
from flask_sqlalchemy import SQLAlchemy
from celery import Celery
db = SQLAlchemy()
celery = Celery()
| [
"flask_sqlalchemy.SQLAlchemy",
"celery.Celery"
] | [((73, 85), 'flask_sqlalchemy.SQLAlchemy', 'SQLAlchemy', ([], {}), '()\n', (83, 85), False, 'from flask_sqlalchemy import SQLAlchemy\n'), ((95, 103), 'celery.Celery', 'Celery', ([], {}), '()\n', (101, 103), False, 'from celery import Celery\n')] |