code stringlengths 20 1.04M | apis list | extract_api stringlengths 75 9.94M |
|---|---|---|
"""
Classes holding information on global DOFs and mapping of all DOFs -
equations (active DOFs).
Helper functions for the equation mapping.
"""
import numpy as nm
import scipy.sparse as sp
from sfepy.base.base import assert_, Struct, basestr
from sfepy.discrete.functions import Function
from sfepy.discrete.condition... | [
"sfepy.base.base.Struct",
"sfepy.discrete.conditions.get_condition_value",
"numpy.ravel",
"numpy.empty",
"numpy.zeros",
"sfepy.base.base.Struct.__init__",
"numpy.ones",
"numpy.setdiff1d",
"numpy.nonzero",
"scipy.sparse.coo_matrix",
"numpy.where",
"numpy.arange",
"sfepy.base.base.assert_",
... | [((570, 601), 'numpy.repeat', 'nm.repeat', (['nods', 'n_dof_per_node'], {}), '(nods, n_dof_per_node)\n', (579, 601), True, 'import numpy as nm\n'), ((663, 704), 'numpy.arange', 'nm.arange', (['n_dof_per_node'], {'dtype': 'nm.int32'}), '(n_dof_per_node, dtype=nm.int32)\n', (672, 704), True, 'import numpy as nm\n'), ((27... |
import numpy
from numba import jit
from . import misc_functions as m
#from importlib import reload
#reload(m)
############################################################
############################################################
################ Find best split functions ################
#######################... | [
"numpy.argsort",
"numba.jit",
"numpy.sum",
"numpy.isnan"
] | [((422, 452), 'numba.jit', 'jit', ([], {'cache': '(True)', 'nopython': '(True)'}), '(cache=True, nopython=True)\n', (425, 452), False, 'from numba import jit\n'), ((625, 655), 'numba.jit', 'jit', ([], {'cache': '(True)', 'nopython': '(True)'}), '(cache=True, nopython=True)\n', (628, 655), False, 'from numba import jit\... |
# Generated by Django 3.2.5 on 2021-07-29 23:32
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('contact', '0004_feedback_user'),
]
operations = [
migrations.AlterModelOptions(
name='feedback',
options={'verbose_name_plur... | [
"django.db.migrations.AlterModelOptions"
] | [((222, 317), 'django.db.migrations.AlterModelOptions', 'migrations.AlterModelOptions', ([], {'name': '"""feedback"""', 'options': "{'verbose_name_plural': 'Feedback'}"}), "(name='feedback', options={\n 'verbose_name_plural': 'Feedback'})\n", (250, 317), False, 'from django.db import migrations\n')] |
import logging
import os
import random
from typing import Generator
import numpy as np
import pandas as pd
import tensorflow as tf
from baselines.common import tf_util
from cluster_work import ClusterWork
from kb_learning.envs import MultiObjectDirectControlEnv, NormalizeActionWrapper
from kb_learning.policy_networks... | [
"kb_learning.envs.NormalizeActionWrapper",
"numpy.random.seed",
"numpy.sum",
"baselines.common.tf_util.make_session",
"kb_learning.tools.trpo_tools.ActWrapper.load",
"kb_learning.tools.trpo_tools.traj_segment_generator_ma",
"tensorflow.set_random_seed",
"tensorflow.ConfigProto",
"numpy.mean",
"ran... | [((586, 611), 'logging.getLogger', 'logging.getLogger', (['"""trpo"""'], {}), "('trpo')\n", (603, 611), False, 'import logging\n'), ((1130, 1239), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'allow_soft_placement': '(True)', 'inter_op_parallelism_threads': '(2)', 'intra_op_parallelism_threads': '(1)'}), '(allow_s... |
import matplotlib.pyplot as plt
import numpy as np
import bootstraphistogram
# create histogram
hist = bootstraphistogram.BootstrapHistogram(
bootstraphistogram.axis.Regular(10, -3.0, 3.0), numsamples=10
)
# fill with some random normal data
data = np.random.normal(size=1000)
hist.fill(data)
# plot the median s... | [
"bootstraphistogram.plot.step",
"bootstraphistogram.axis.Regular",
"matplotlib.pyplot.show",
"numpy.random.normal"
] | [((256, 283), 'numpy.random.normal', 'np.random.normal', ([], {'size': '(1000)'}), '(size=1000)\n', (272, 283), True, 'import numpy as np\n'), ((326, 377), 'bootstraphistogram.plot.step', 'bootstraphistogram.plot.step', (['hist'], {'percentile': '(50.0)'}), '(hist, percentile=50.0)\n', (354, 377), False, 'import bootst... |
"""
@version:
@author: DQ
@time: 2021-10-13
@file: main.py
@function:
@modify:
"""
import pygame
import time
from packages import *
WIN_SIZE = (640, 480)
class Main():
def __init__(self):
pygame.init()
window = pygame.display.set_mode(WIN_SIZE)
icon = pygame.image.l... | [
"pygame.display.set_icon",
"pygame.event.get",
"pygame.display.set_mode",
"time.perf_counter",
"pygame.init",
"pygame.display.flip",
"pygame.display.update",
"pygame.image.load",
"pygame.display.set_caption"
] | [((224, 237), 'pygame.init', 'pygame.init', ([], {}), '()\n', (235, 237), False, 'import pygame\n'), ((256, 289), 'pygame.display.set_mode', 'pygame.display.set_mode', (['WIN_SIZE'], {}), '(WIN_SIZE)\n', (279, 289), False, 'import pygame\n'), ((306, 342), 'pygame.image.load', 'pygame.image.load', (['"""files/坦克1素材.png"... |
# Código para obter posição do mouse
import pyautogui
import time
time.sleep(7)
x, y = pyautogui.position()
print ("x = "+str(x)+" y = "+str(y)) | [
"pyautogui.position",
"time.sleep"
] | [((67, 80), 'time.sleep', 'time.sleep', (['(7)'], {}), '(7)\n', (77, 80), False, 'import time\n'), ((88, 108), 'pyautogui.position', 'pyautogui.position', ([], {}), '()\n', (106, 108), False, 'import pyautogui\n')] |
"""
@date: 2021-02-05
@author: HelleDaryd
"""
from datetime import datetime, timezone
import dateutil.parser as dparser
from twisted.plugin import IPlugin
from twisted.words.protocols.irc import assembleFormattedText as colour, attributes as A
from zope.interface import implementer
from desertbot.message import IRC... | [
"twisted.words.protocols.irc.assembleFormattedText",
"zope.interface.implementer",
"dateutil.parser.isoparse",
"datetime.datetime.now",
"jq.compile"
] | [((592, 621), 'zope.interface.implementer', 'implementer', (['IPlugin', 'IModule'], {}), '(IPlugin, IModule)\n', (603, 621), False, 'from zope.interface import implementer\n'), ((783, 1862), 'jq.compile', 'jq.compile', (['"""\n def e(f): if f == "[]" then null else f end;\n [ .data.Catalog.searchStore.ele... |
# Copyright Contributors to the Amundsen project.
# SPDX-License-Identifier: Apache-2.0
import attr
from marshmallow_annotations.ext.attrs import AttrsSchema
@attr.s(auto_attribs=True, kw_only=True)
class Badge:
badge_name: str = attr.ib()
category: str = attr.ib()
class BadgeSchema(AttrsSchema):
class... | [
"attr.s",
"attr.ib"
] | [((162, 201), 'attr.s', 'attr.s', ([], {'auto_attribs': '(True)', 'kw_only': '(True)'}), '(auto_attribs=True, kw_only=True)\n', (168, 201), False, 'import attr\n'), ((237, 246), 'attr.ib', 'attr.ib', ([], {}), '()\n', (244, 246), False, 'import attr\n'), ((267, 276), 'attr.ib', 'attr.ib', ([], {}), '()\n', (274, 276), ... |
# coding=utf-8
# Copyright 2020 The Uncertainty Baselines Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ap... | [
"tensorflow_datasets.core.Version",
"absl.logging.info",
"tensorflow_datasets.core.MetadataDict",
"tensorflow_datasets.builder",
"tensorflow.io.parse_example",
"tensorflow.data.Dataset.list_files",
"tensorflow.io.FixedLenFeature",
"os.path.join",
"tensorflow_datasets.core.ReadInstruction"
] | [((1959, 2016), 'tensorflow.data.Dataset.list_files', 'tf.data.Dataset.list_files', (['glob_dir'], {'shuffle': 'is_training'}), '(glob_dir, shuffle=is_training)\n', (1985, 2016), True, 'import tensorflow as tf\n'), ((3008, 3034), 'tensorflow_datasets.core.Version', 'tfds.core.Version', (['"""0.0.0"""'], {}), "('0.0.0')... |
# 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 t... | [
"keystone.openstack.common.versionutils.deprecated"
] | [((680, 860), 'keystone.openstack.common.versionutils.deprecated', 'versionutils.deprecated', (['versionutils.deprecated.JUNO'], {'in_favor_of': '"""keystone.token.persistence.backends.kvs.Token"""', 'remove_in': '(+1)', 'what': '"""keystone.token.backends.kvs.Token"""'}), "(versionutils.deprecated.JUNO, in_favor_of=\n... |
# (Draft) of a unified agent similar to NARS
from random import seed, randint
import numba
import Debug
# initialize random number generator
seed()
# TODO< sort concepts >
# TODO< add time >
# TODO< add time of events/tasks >
# TODO< feedback of priority after derivation in the attention system >
# TODO< fix per... | [
"Debug.msg",
"TruthValue.TruthValue",
"time.process_time",
"Task.Task",
"random.seed",
"Reasoner.Reasoner",
"Distributed.genRandom"
] | [((144, 150), 'random.seed', 'seed', ([], {}), '()\n', (148, 150), False, 'from random import seed, randint\n'), ((2119, 2129), 'Reasoner.Reasoner', 'Reasoner', ([], {}), '()\n', (2127, 2129), False, 'from Reasoner import Reasoner\n'), ((2286, 2305), 'time.process_time', 'time.process_time', ([], {}), '()\n', (2303, 23... |
from django.contrib import admin
from django.contrib.auth.models import User
from .models import Comment, Post, Subneddit
# Register your models here.
admin.site.register(Subneddit)
admin.site.register(Post)
admin.site.register(Comment)
| [
"django.contrib.admin.site.register"
] | [((157, 187), 'django.contrib.admin.site.register', 'admin.site.register', (['Subneddit'], {}), '(Subneddit)\n', (176, 187), False, 'from django.contrib import admin\n'), ((189, 214), 'django.contrib.admin.site.register', 'admin.site.register', (['Post'], {}), '(Post)\n', (208, 214), False, 'from django.contrib import ... |
# -----------------------------------------------------------------------------
# Copyright (c) 2013-2021, NeXpy Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING, distributed with this software.
# -------------------------------------------------... | [
"nexusformat.nexus.NXdata",
"cctbx.crystal.symmetry",
"numpy.abs",
"nexusformat.nexus.NXsample",
"numpy.arctan2",
"numpy.sum",
"nexusformat.nexus.NXlink",
"pkg_resources.resource_filename",
"numpy.isclose",
"numpy.sin",
"numpy.linalg.norm",
"julia.Julia",
"numpy.arange",
"os.path.join",
... | [((1225, 1234), 'numpy.eye', 'np.eye', (['(3)'], {}), '(3)\n', (1231, 1234), True, 'import numpy as np\n'), ((1313, 1336), 'numpy.cos', 'np.cos', (['(angle * radians)'], {}), '(angle * radians)\n', (1319, 1336), True, 'import numpy as np\n'), ((1346, 1369), 'numpy.sin', 'np.sin', (['(angle * radians)'], {}), '(angle * ... |
import sys
sys.path.append('../src/meta_rule/')
sys.path.append('../dd_lnn/')
import time
import copy
import argparse
from meta_interpretive import BaseMetaPredicate, MetaRule, Project, DisjunctionRule
from train_test import score, align_labels, train
from read import load_data, load_metadata, load_labels
import pand... | [
"sys.path.append",
"meta_interpretive.BaseMetaPredicate",
"copy.deepcopy",
"numpy.set_printoptions",
"read.load_data",
"argparse.ArgumentParser",
"torch.nn.BCEWithLogitsLoss",
"torch.LongTensor",
"train_test.align_labels",
"train_test.score",
"meta_interpretive.Project",
"time.time",
"meta_i... | [((11, 47), 'sys.path.append', 'sys.path.append', (['"""../src/meta_rule/"""'], {}), "('../src/meta_rule/')\n", (26, 47), False, 'import sys\n'), ((48, 77), 'sys.path.append', 'sys.path.append', (['"""../dd_lnn/"""'], {}), "('../dd_lnn/')\n", (63, 77), False, 'import sys\n'), ((586, 597), 'time.time', 'time.time', ([],... |
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
import pandas as pd
import sys
sys.path.append("..")
mpl.use('tkagg') # issues with Big Sur
import matplotlib.pyplot as plt
from strategy.standard_deviation import sd
from backtest import Backtest
from evaluate import SharpeRatio, MaxDrawdown... | [
"sys.path.append",
"pandas.Timestamp",
"strategy.standard_deviation.sd.plot_SD",
"matplotlib.pyplot.show",
"pandas.read_csv",
"strategy.standard_deviation.sd.cal_SD",
"matplotlib.use",
"strategy.standard_deviation.sd"
] | [((107, 128), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (122, 128), False, 'import sys\n'), ((129, 145), 'matplotlib.use', 'mpl.use', (['"""tkagg"""'], {}), "('tkagg')\n", (136, 145), True, 'import matplotlib as mpl\n'), ((345, 472), 'pandas.read_csv', 'pd.read_csv', (['"""../../database/mic... |
from __future__ import print_function
import sys
from runstats import Statistics as FastStatistics
from runstats import Regression as FastRegression
from runstats.core import Statistics as CoreStatistics
from runstats.core import Regression as CoreRegression
from .test_runstats import mean, variance, stddev, skewnes... | [
"runstats.Regression",
"runstats.core.Statistics",
"runstats.core.Regression",
"runstats.Statistics"
] | [((654, 670), 'runstats.Statistics', 'FastStatistics', ([], {}), '()\n', (668, 670), True, 'from runstats import Statistics as FastStatistics\n'), ((1036, 1052), 'runstats.core.Statistics', 'CoreStatistics', ([], {}), '()\n', (1050, 1052), True, 'from runstats.core import Statistics as CoreStatistics\n'), ((1417, 1433)... |
import csv
import dateutil.parser
import os
import splparser.parser
from user import *
from query import *
from logging import getLogger as get_logger
from os import path
from splparser.exceptions import SPLSyntaxError, TerminatingSPLSyntaxError
BYTES_IN_MB = 1048576
LIMIT = 2000*BYTES_IN_MB
logger = get_logger("q... | [
"os.path.abspath",
"csv.DictReader",
"os.path.getsize",
"os.walk",
"logging.getLogger"
] | [((307, 331), 'logging.getLogger', 'get_logger', (['"""queryutils"""'], {}), "('queryutils')\n", (317, 331), True, 'from logging import getLogger as get_logger\n'), ((5770, 5782), 'os.walk', 'os.walk', (['dir'], {}), '(dir)\n', (5777, 5782), False, 'import os\n'), ((776, 800), 'csv.DictReader', 'csv.DictReader', (['dat... |
#!python3
import numpy as np
from magLabUtilities.optimizers.costFunctions import rmsNdNorm
from magLabUtilities.signalutilities.signals import SignalThread, Signal, SignalBundle
if __name__=='__main__':
tThread = SignalThread(np.array([0,1,2], dtype=np.float64))
refM = SignalThread(np.array([0,1,2]... | [
"magLabUtilities.signalutilities.signals.Signal.fromThreadPair",
"magLabUtilities.optimizers.costFunctions.rmsNdNorm",
"numpy.array",
"magLabUtilities.signalutilities.signals.SignalBundle"
] | [((353, 389), 'magLabUtilities.signalutilities.signals.Signal.fromThreadPair', 'Signal.fromThreadPair', (['refM', 'tThread'], {}), '(refM, tThread)\n', (374, 389), False, 'from magLabUtilities.signalutilities.signals import SignalThread, Signal, SignalBundle\n'), ((464, 500), 'magLabUtilities.signalutilities.signals.Si... |
from typing import Dict
import numpy
def likelihood(simulated: Dict[int, int], realdata: Dict[int, int]):
total_simulated = sum(simulated.values())
total_realdata = sum(realdata.values())
res = 0
for size, occur in realdata.items():
if occur == 0:
continue
if size not in simulated:
continue
res += ((... | [
"numpy.log"
] | [((346, 390), 'numpy.log', 'numpy.log', (['(simulated[size] / total_simulated)'], {}), '(simulated[size] / total_simulated)\n', (355, 390), False, 'import numpy\n')] |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the LICENSE
# file in the root directory of this source tree.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_li... | [
"mcrouter.test.MCProcess.Mcrouter"
] | [((788, 864), 'mcrouter.test.MCProcess.Mcrouter', 'Mcrouter', (['self.null_route_config'], {'extra_args': 'self.mcrouter_server_extra_args'}), '(self.null_route_config, extra_args=self.mcrouter_server_extra_args)\n', (796, 864), False, 'from mcrouter.test.MCProcess import Mcrouter\n')] |
# terrascript/azure_preview/r.py
# Automatically generated by tools/makecode.py ()
import warnings
warnings.warn(
"using the 'legacy layout' is deprecated", DeprecationWarning, stacklevel=2
)
import terrascript
class azurepreview_budget(terrascript.Resource):
pass
class azurepreview_subscription(terrascri... | [
"warnings.warn"
] | [((101, 195), 'warnings.warn', 'warnings.warn', (['"""using the \'legacy layout\' is deprecated"""', 'DeprecationWarning'], {'stacklevel': '(2)'}), '("using the \'legacy layout\' is deprecated", DeprecationWarning,\n stacklevel=2)\n', (114, 195), False, 'import warnings\n')] |
#!/usr/bin/env python3
"""This routine parses plain-text parameter files that list runtime
parameters for use in our codes. The general format of a parameter
is:
max_step integer 1
small_dt real 1.d-10
xlo_boundary_type ... | [
"argparse.ArgumentParser",
"os.path.basename",
"os.path.isfile",
"re.findall",
"sys.exit"
] | [((5972, 5983), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (5980, 5983), False, 'import sys\n'), ((20196, 20221), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (20219, 20221), False, 'import argparse\n'), ((3777, 3803), 'os.path.isfile', 'os.path.isfile', (['param_file'], {}), '(param_fil... |
import sys
import os
import time
import imp
import threading
import traceback
from utils import session
from case_ble import def_ble
from datetime import timedelta
from datetime import datetime
from case_ble import cmd_list
import json
g_sock_mobile = None
g_sock_session = None
g_q_mobile_rsp = ['BLEMobileRspQueue',... | [
"threading.Thread",
"utils.session.q",
"traceback.print_exc",
"json.loads",
"utils.session.bind",
"utils.session.do_qinit",
"utils.session.disconnect",
"json.dumps",
"time.sleep",
"utils.session.get_host",
"os._exit",
"utils.session.do_qclr",
"utils.session.connect",
"utils.session.send",
... | [((3096, 3133), 'utils.session.do_qinit', 'session.do_qinit', (['"""BLEMobileRspQueue"""'], {}), "('BLEMobileRspQueue')\n", (3112, 3133), False, 'from utils import session\n'), ((3404, 3431), 'utils.session.bind', 'session.bind', (['"""BLE_SESSION"""'], {}), "('BLE_SESSION')\n", (3416, 3431), False, 'from utils import ... |
import time
import json
import base64
import redis
import sys
class Cloud_Event_Queue():
def __init__(self,redis):
self.redis = redis
def store_event_queue( self, event, data,status ="RED" ):
log_data = {}
log_data["event"] = event
log_data["data"] = data
log_da... | [
"redis.hincrby",
"json.dumps",
"time.time",
"base64.b64encode",
"redis.StrictRedis"
] | [((794, 846), 'redis.StrictRedis', 'redis.StrictRedis', ([], {'host': '"""localhost"""', 'port': '(6379)', 'db': '(0)'}), "(host='localhost', port=6379, db=0)\n", (811, 846), False, 'import redis\n'), ((1097, 1148), 'redis.hincrby', 'redis.hincrby', (['"""CONTROLLER_STATUS"""', '"""system_resets"""'], {}), "('CONTROLLE... |
#!/usr/bin/env python
# coding: utf-8
# # Introduction to matplotlib
# I find matplotlib more confusing than most Python tools, but it is very important to learn, because:
# * matplotlib is the most widely used visualization library in Python. If you are reading someone else's code, there is a good chance you will un... | [
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.close",
"numpy.sin",
"numpy.arange",
"numpy.exp",
"numpy.cos",
"matplotlib.pyplot.subplots"
] | [((3182, 3196), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (3194, 3196), True, 'import matplotlib.pyplot as plt\n'), ((3846, 3860), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (3858, 3860), True, 'import matplotlib.pyplot as plt\n'), ((4176, 4190), 'matplotlib.pyplot.subplots', ... |
from __future__ import annotations
from pathlib import Path
from typing import Optional
import typer
from biteme import pybites
__all__ = ["cli"]
cli = typer.Typer(context_settings={"auto_envvar_prefix": "PYBITES"})
@cli.command()
def info(bite: int) -> None:
bite_info = pybites._bite_info(bite)
typer.... | [
"typer.echo",
"biteme.pybites._bite_info",
"typer.Argument",
"typer.Typer",
"typer.Option",
"biteme.pybites.download_bite"
] | [((159, 222), 'typer.Typer', 'typer.Typer', ([], {'context_settings': "{'auto_envvar_prefix': 'PYBITES'}"}), "(context_settings={'auto_envvar_prefix': 'PYBITES'})\n", (170, 222), False, 'import typer\n'), ((285, 309), 'biteme.pybites._bite_info', 'pybites._bite_info', (['bite'], {}), '(bite)\n', (303, 309), False, 'fro... |
import unittest
from typing import cast, List
import icontract_hypothesis
from icontract import require
from python_by_contract_corpus.common import Lines
from python_by_contract_corpus.correct.ethz_eprog_2019.exercise_02 import problem_02
class TestWithIcontractHypothesis(unittest.TestCase):
def test_functions... | [
"unittest.main",
"icontract_hypothesis.test_with_inferred_strategy",
"typing.cast",
"icontract.require",
"python_by_contract_corpus.correct.ethz_eprog_2019.exercise_02.problem_02.draw"
] | [((1548, 1563), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1561, 1563), False, 'import unittest\n'), ((345, 379), 'icontract.require', 'require', (['(lambda width: width < 100)'], {}), '(lambda width: width < 100)\n', (352, 379), False, 'from icontract import require\n'), ((389, 421), 'icontract.require', 're... |
from timeit import Timer
def bench(reps, setup, test):
Timer(test, setup).timeit(reps)
return int(Timer(test, setup).timeit(reps) * 1000)
| [
"timeit.Timer"
] | [((60, 78), 'timeit.Timer', 'Timer', (['test', 'setup'], {}), '(test, setup)\n', (65, 78), False, 'from timeit import Timer\n'), ((107, 125), 'timeit.Timer', 'Timer', (['test', 'setup'], {}), '(test, setup)\n', (112, 125), False, 'from timeit import Timer\n')] |
import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.optim as optim
from transformers import BertModel
import torch.nn.functional as F
CLS = False
class FT_Match(nn.Module):
def __init__(self, args):
super(FT_Match, self).__init__()
self.BertM = BertM... | [
"torch.nn.Sequential",
"torch.nn.LeakyReLU",
"torch.nn.Linear",
"transformers.BertModel.from_pretrained",
"torch.nn.LSTM"
] | [((315, 361), 'transformers.BertModel.from_pretrained', 'BertModel.from_pretrained', (['"""bert-base-chinese"""'], {}), "('bert-base-chinese')\n", (340, 361), False, 'from transformers import BertModel\n'), ((419, 497), 'torch.nn.LSTM', 'nn.LSTM', ([], {'input_size': '(768)', 'hidden_size': '(768)', 'bidirectional': '(... |
from __future__ import print_function
import os
# this perl command deletes all the comments in iriflip...
# my compiler was having trouble with them, for some reason
cmd = "perl -pi -e 's/![\.|-].*$//g' iriflip.for"
print(cmd)
os.system(cmd)
| [
"os.system"
] | [((229, 243), 'os.system', 'os.system', (['cmd'], {}), '(cmd)\n', (238, 243), False, 'import os\n')] |
# coding=utf-8
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2018
from streamsx.spl import spl
# Only loaded during extraction so spl.extracting()
# should always be set.
if not spl.extracting():
raise ValueError("spl.extacting is not true: " + str(spl.extracting()))
| [
"streamsx.spl.spl.extracting"
] | [((196, 212), 'streamsx.spl.spl.extracting', 'spl.extracting', ([], {}), '()\n', (210, 212), False, 'from streamsx.spl import spl\n'), ((271, 287), 'streamsx.spl.spl.extracting', 'spl.extracting', ([], {}), '()\n', (285, 287), False, 'from streamsx.spl import spl\n')] |
# -*- coding:utf-8 -*-
"""
系统配置Model
"""
from django.db import models
from codelieche.tools.password import Cryptography
# from account.models import User
class Config(models.Model):
CATEGORY_CHOICES = (
('text', '文本'),
('number', '数字'),
('int', '整数'),
('float', '浮点数'),
(... | [
"django.db.models.TextField",
"django.db.models.CharField",
"django.db.models.BooleanField",
"django.db.models.SlugField",
"codelieche.tools.password.Cryptography"
] | [((356, 420), 'django.db.models.SlugField', 'models.SlugField', ([], {'verbose_name': '"""配置"""', 'max_length': '(128)', 'unique': '(True)'}), "(verbose_name='配置', max_length=128, unique=True)\n", (372, 420), False, 'from django.db import models\n'), ((432, 508), 'django.db.models.CharField', 'models.CharField', ([], {... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 26 13:26:40 2021
@author: rdavi
Organize RAVDESS folders according to emotions
"""
# %% Imports
import sys
sys.path.append('..')
import os
import zipfile
import shutil
# %% Extract zip file
def extract_zip():
path_raw = '../../data/raw/'
with zipfile.ZipFile(p... | [
"sys.path.append",
"os.mkdir",
"zipfile.ZipFile",
"os.makedirs",
"os.walk",
"os.path.exists",
"os.replace",
"shutil.rmtree"
] | [((158, 179), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (173, 179), False, 'import sys\n'), ((851, 864), 'os.walk', 'os.walk', (['path'], {}), '(path)\n', (858, 864), False, 'import os\n'), ((1926, 1945), 'shutil.rmtree', 'shutil.rmtree', (['path'], {}), '(path)\n', (1939, 1945), False, 'imp... |
import os
from enum import Enum
from dotenv import load_dotenv
load_dotenv()
API_ID: str = os.getenv("API_ID")
API_HASH: str = os.getenv("API_HASH")
CHAT_NAME: list[str] = os.getenv("CHAT_NAME").split(":")
CHAT_FORWARD_LIST: list[str] = os.getenv("CHAT_FORWARD_LIST").split(",")
class Constants(Enum):
API_ID = A... | [
"dotenv.load_dotenv",
"os.getenv"
] | [((64, 77), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (75, 77), False, 'from dotenv import load_dotenv\n'), ((93, 112), 'os.getenv', 'os.getenv', (['"""API_ID"""'], {}), "('API_ID')\n", (102, 112), False, 'import os\n'), ((129, 150), 'os.getenv', 'os.getenv', (['"""API_HASH"""'], {}), "('API_HASH')\n", (13... |
import json
import httplib
import logging
from urllib2 import build_opener, HTTPHandler, Request
import boto3
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def handler(event, context):
logger.info('REQUEST RECEIVED:\n {}'.format(event))
logger.info('REQUEST RECEIVED:\n {}'.format(context))
# ... | [
"logging.getLogger",
"boto3.client"
] | [((120, 139), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (137, 139), False, 'import logging\n'), ((431, 459), 'boto3.client', 'boto3.client', (['"""codepipeline"""'], {}), "('codepipeline')\n", (443, 459), False, 'import boto3\n')] |
# Copyright 2020 Catalyst Cloud
#
# 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 agre... | [
"oslo_log.log.getLogger",
"time.sleep"
] | [((766, 793), 'oslo_log.log.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (783, 793), True, 'from oslo_log import log as logging\n'), ((2831, 2844), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (2841, 2844), False, 'import time\n'), ((3471, 3484), 'time.sleep', 'time.sleep', (['(5)'], {}),... |
from __future__ import print_function
import boto3
def lambda_handler(event, context):
'''forward all incoming requests to SNS
'''
print(str(event))
boto3.client('sns').publish(
TopicArn='arn:aws:sns:REGION:ACCOUNT_ID:pingonMe',
Message='Check pingon.me!\n\n{0}'.format(str(event))
... | [
"boto3.client"
] | [((167, 186), 'boto3.client', 'boto3.client', (['"""sns"""'], {}), "('sns')\n", (179, 186), False, 'import boto3\n')] |
#!/usr/bin/env python
import argparse
import json
import requests
import sys
import pdpyras
def find_shifts(session, vacationing_user, start, end, schedule_ids):
"""Find all on-call shifts on the specified schedules
between `since` and `until`"""
params = {"since": start, "until": end}
shifts = {} # L... | [
"pdpyras.APISession",
"argparse.ArgumentParser"
] | [((1012, 1308), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""For a given user going on vacation, and another given user who will fill their shoes while away, create overrides on all the vacationing user\'s schedules, such that the replacement user covers all the shifts that the vacatio... |
# coding: utf-8
"""
FreeClimb API
FreeClimb is a cloud-based application programming interface (API) that puts the power of the Vail platform in your hands. FreeClimb simplifies the process of creating applications that can use a full range of telephony features without requiring specialized or on-site teleph... | [
"freeclimb.configuration.Configuration",
"six.iteritems"
] | [((8131, 8164), 'six.iteritems', 'six.iteritems', (['self.openapi_types'], {}), '(self.openapi_types)\n', (8144, 8164), False, 'import six\n'), ((2180, 2195), 'freeclimb.configuration.Configuration', 'Configuration', ([], {}), '()\n', (2193, 2195), False, 'from freeclimb.configuration import Configuration\n')] |
import glob
import os
from pomodoro_timer.configs.main_configs import IMG_TEMP_DIR
def remove_temp_img():
files = glob.glob(os.path.join(IMG_TEMP_DIR, "*"))
for f in files:
os.remove(f)
| [
"os.remove",
"os.path.join"
] | [((131, 162), 'os.path.join', 'os.path.join', (['IMG_TEMP_DIR', '"""*"""'], {}), "(IMG_TEMP_DIR, '*')\n", (143, 162), False, 'import os\n'), ((192, 204), 'os.remove', 'os.remove', (['f'], {}), '(f)\n', (201, 204), False, 'import os\n')] |
# -*- coding: utf-8 -*-
'''
Created on Mar 11, 2012
@author: moloch
Copyright 2012 Root the Box
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/licen... | [
"uuid.uuid4",
"sqlalchemy.types.String",
"models.dbsession.query",
"netaddr.IPAddress",
"sqlalchemy.ForeignKey",
"xml.etree.cElementTree.SubElement"
] | [((1083, 1093), 'sqlalchemy.types.String', 'String', (['(36)'], {}), '(36)\n', (1089, 1093), False, 'from sqlalchemy.types import Integer, String\n'), ((1183, 1203), 'sqlalchemy.ForeignKey', 'ForeignKey', (['"""box.id"""'], {}), "('box.id')\n", (1193, 1203), False, 'from sqlalchemy import Column, ForeignKey\n'), ((1243... |
import pytest
from test import test_common
test_definitions = {
"test/struct_initializer.cu": ['somekernel', 'somekernel2', 'getFooValue', 'getBarValue'],
"test/phiaddressspace.cu": ['mykernel'],
"test/test_local.cu": ['testLocal', 'testLocal2'],
"test/pointerpointer.cu": ['mykernel', 'myte6kernel']
}... | [
"test.test_common.build_kernel",
"pytest.mark.xfail",
"test.test_common.cu_to_cl"
] | [((1295, 1337), 'test.test_common.cu_to_cl', 'test_common.cu_to_cl', (['cu_code', 'mangledname'], {}), '(cu_code, mangledname)\n', (1315, 1337), False, 'from test import test_common\n'), ((1343, 1403), 'test.test_common.build_kernel', 'test_common.build_kernel', (['context', 'cl_code', 'mangledname[:31]'], {}), '(conte... |
# Copyright (c) 2019 <NAME>, <NAME>, <NAME>, <NAME>, <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
... | [
"h5py.File"
] | [((4403, 4428), 'h5py.File', 'h5py.File', (['hdf5_path', '"""r"""'], {}), "(hdf5_path, 'r')\n", (4412, 4428), False, 'import h5py\n')] |
# Module: hibernate
# Description: Hibernates the system
# Usage: !hibernate or !hibernate secondsToHibernation
# Dependencies: time, os
import time, os, asyncio, configs
async def hibernate(ctx, seconds=0):
await ctx.send("Hibernating system.")
if configs.operating_sys == "Windows":
if time != 0:
... | [
"os.system",
"asyncio.sleep",
"time.sleep"
] | [((358, 412), 'os.system', 'os.system', (['"""rundll32.exe PowrProf.dll,SetSuspendState"""'], {}), "('rundll32.exe PowrProf.dll,SetSuspendState')\n", (367, 412), False, 'import time, os, asyncio, configs\n'), ((330, 349), 'time.sleep', 'time.sleep', (['seconds'], {}), '(seconds)\n', (340, 349), False, 'import time, os,... |
import json
import torch
from flask import Flask, request, jsonify
from prometheus_flask_exporter.multiprocess import GunicornInternalPrometheusMetrics
from prometheus_client import Counter
app = Flask(__name__, static_url_path="")
metrics = GunicornInternalPrometheusMetrics(app)
PREDICTION_COUNT = Counter("predicti... | [
"prometheus_flask_exporter.multiprocess.GunicornInternalPrometheusMetrics",
"flask.Flask",
"flask.jsonify",
"prometheus_client.Counter",
"torch.jit.load",
"flask.request.get_json",
"torch.tensor"
] | [((199, 234), 'flask.Flask', 'Flask', (['__name__'], {'static_url_path': '""""""'}), "(__name__, static_url_path='')\n", (204, 234), False, 'from flask import Flask, request, jsonify\n'), ((245, 283), 'prometheus_flask_exporter.multiprocess.GunicornInternalPrometheusMetrics', 'GunicornInternalPrometheusMetrics', (['app... |
import pytest
from pybrary.databrary.types.gender import Gender
from pybrary.databrary.types.ethnicity import Ethnicity
from pybrary.databrary.types.race import Race
from pybrary.databrary.participant import Participant
@pytest.fixture
def expected_participant_dict():
return {
"key": "2631",
"ID"... | [
"pytest.raises",
"pybrary.databrary.participant.Participant.from_databrary",
"pybrary.databrary.participant.Participant"
] | [((1883, 1937), 'pybrary.databrary.participant.Participant.from_databrary', 'Participant.from_databrary', (['databrary_participant_dict'], {}), '(databrary_participant_dict)\n', (1909, 1937), False, 'from pybrary.databrary.participant import Participant\n'), ((2047, 2071), 'pytest.raises', 'pytest.raises', (['Exception... |
import gc
import sys
sys.path.append('taming-transformers')
from omegaconf import OmegaConf
from taming.models import cond_transformer, vqgan
import torch
class VqganHelper:
gumbel: bool
def __init__(self):
self.gumbel = False
def load_vqgan_model(self, config_path, checkpoint_path):
s... | [
"sys.path.append",
"taming.models.cond_transformer.Net2NetTransformer",
"omegaconf.OmegaConf.load",
"taming.models.vqgan.GumbelVQ",
"gc.collect",
"torch.cuda.empty_cache",
"taming.models.vqgan.VQModel"
] | [((22, 60), 'sys.path.append', 'sys.path.append', (['"""taming-transformers"""'], {}), "('taming-transformers')\n", (37, 60), False, 'import sys\n'), ((356, 383), 'omegaconf.OmegaConf.load', 'OmegaConf.load', (['config_path'], {}), '(config_path)\n', (370, 383), False, 'from omegaconf import OmegaConf\n'), ((1345, 1357... |
"""
Distributed under the terms of the BSD 3-Clause License.
The full license is in the file LICENSE, distributed with this software.
Author: <NAME> <<EMAIL>>, <NAME> <<EMAIL>>
Copyright (C) European X-Ray Free-Electron Laser Facility GmbH.
All rights reserved.
"""
from collections import OrderedDict
import json
fr... | [
"PyQt5.QtWidgets.QComboBox",
"PyQt5.QtWidgets.QLabel",
"json.loads",
"PyQt5.QtWidgets.QTableWidget",
"PyQt5.QtWidgets.QGridLayout",
"PyQt5.QtGui.QDoubleValidator",
"PyQt5.QtWidgets.QPushButton",
"PyQt5.QtWidgets.QCheckBox",
"PyQt5.QtWidgets.QFileDialog.getOpenFileName",
"collections.OrderedDict"
] | [((1188, 1279), 'collections.OrderedDict', 'OrderedDict', (["{'EXtra-foam': GeomAssembler.OWN, 'EXtra-geom': GeomAssembler.EXTRA_GEOM}"], {}), "({'EXtra-foam': GeomAssembler.OWN, 'EXtra-geom': GeomAssembler.\n EXTRA_GEOM})\n", (1199, 1279), False, 'from collections import OrderedDict\n'), ((1541, 1552), 'PyQt5.QtWid... |
# Copyright 2015 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... | [
"numpy.ones_like",
"matplotlib.pyplot.legend",
"numpy.array",
"numpy.exp",
"numpy.convolve",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.grid"
] | [((1390, 1411), 'numpy.exp', 'np.exp', (['(-(x / 5) ** 2)'], {}), '(-(x / 5) ** 2)\n', (1396, 1411), True, 'import numpy as np\n'), ((1422, 1438), 'numpy.array', 'np.array', (['values'], {}), '(values)\n', (1430, 1438), True, 'import numpy as np\n'), ((1451, 1471), 'numpy.ones_like', 'np.ones_like', (['values'], {}), '... |
from django.conf import settings
from django.dispatch import receiver
from rosetta.signals import post_save
@receiver(post_save)
def restart_server(sender, **kwargs):
"""
Restart server after rosetta translations fix.
"""
import os
os.system(f"kill -HUP `cat {settings.GUNICORN_PID}`")
| [
"django.dispatch.receiver",
"os.system"
] | [((111, 130), 'django.dispatch.receiver', 'receiver', (['post_save'], {}), '(post_save)\n', (119, 130), False, 'from django.dispatch import receiver\n'), ((255, 308), 'os.system', 'os.system', (['f"""kill -HUP `cat {settings.GUNICORN_PID}`"""'], {}), "(f'kill -HUP `cat {settings.GUNICORN_PID}`')\n", (264, 308), False, ... |
'''
Main python function to utilize MLR (Multiple Linear Regression) on the stock
data being stored in our DB.
First, the user will select a company that they want to analyze. Then, the data
will be transformed, cleaned, and then sent to the MLR for analyzing. From here,
we can check how well the MLR did with predicti... | [
"source.helper.query_data_to_df",
"source.multiple_linear_regression.MultipleLinearRegression",
"source.helper.split_data",
"data.database.StockDB",
"source.helper.df_to_train_dataset"
] | [((782, 791), 'data.database.StockDB', 'StockDB', ([], {}), '()\n', (789, 791), False, 'from data.database import StockDB\n'), ((1006, 1041), 'source.helper.query_data_to_df', 'query_data_to_df', (['stock_information'], {}), '(stock_information)\n', (1022, 1041), False, 'from source.helper import query_data_to_df, spli... |
# Copyright (c) 2013, GPy authors (see AUTHORS.txt).
# Licensed under the BSD 3-clause license (see LICENSE.txt)
import numpy as np
from ..core.mapping import Mapping
class Linear(Mapping):
"""
Mapping based on a linear model.
.. math::
f(\mathbf{x}*) = \mathbf{W}\mathbf{x}^* + \mathbf{b}
:p... | [
"numpy.dot",
"numpy.sqrt",
"numpy.array",
"numpy.random.randn"
] | [((687, 730), 'numpy.array', 'np.array', (['(self.input_dim, self.output_dim)'], {}), '((self.input_dim, self.output_dim))\n', (695, 730), True, 'import numpy as np\n'), ((751, 776), 'numpy.array', 'np.array', (['self.output_dim'], {}), '(self.output_dim)\n', (759, 776), True, 'import numpy as np\n'), ((1316, 1364), 'n... |
# -*- coding: utf-8 -*-
"""
models.meta
~~~~~~~~~~~
Meta models.
"""
from .core import BaseModel, ORMMeta
from schematics.types import ( # NOQA
StringType, BooleanType, DateTimeType, IntType, UUIDType
)
class Declaration(BaseModel, metaclass=ORMMeta):
"""Various declarations of a conflict of i... | [
"schematics.types.StringType"
] | [((417, 458), 'schematics.types.StringType', 'StringType', ([], {'max_length': '(255)', 'required': '(True)'}), '(max_length=255, required=True)\n', (427, 458), False, 'from schematics.types import StringType, BooleanType, DateTimeType, IntType, UUIDType\n'), ((600, 626), 'schematics.types.StringType', 'StringType', ([... |
import numpy as np
from sklearn.datasets import make_classification
from sklearn.mixture import GMM
from sklearn.preprocessing import StandardScaler
from sklearn import svm
def fvecs_read(filename, c_contiguous=True):
fv = np.fromfile(filename, dtype=np.float32)
if fv.size == 0:
return np.zeros((0, 0)... | [
"numpy.sum",
"sklearn.preprocessing.StandardScaler",
"numpy.abs",
"numpy.fromfile",
"sklearn.mixture.GMM",
"sklearn.datasets.make_classification",
"numpy.zeros",
"numpy.isnan",
"numpy.sign",
"sklearn.svm.LinearSVC",
"numpy.dot",
"numpy.sqrt",
"numpy.atleast_2d"
] | [((229, 268), 'numpy.fromfile', 'np.fromfile', (['filename'], {'dtype': 'np.float32'}), '(filename, dtype=np.float32)\n', (240, 268), True, 'import numpy as np\n'), ((826, 844), 'numpy.sum', 'np.sum', (['(xx * xx)', '(1)'], {}), '(xx * xx, 1)\n', (832, 844), True, 'import numpy as np\n'), ((1658, 1675), 'numpy.atleast_... |
"""
Module for keysight devices, like e.g. oscilloscopes.
File name: keysight.py
Author: <NAME>, <NAME>
Date created: 2020/11/11
Python Version: 3.7
"""
from typing import NamedTuple, Tuple, get_type_hints
import re
import pyvisa as visa
import numpy as np
from ._mock.keysight import PyvisaDummy
class Preamble(Name... | [
"pyvisa.ResourceManager",
"numpy.arange",
"re.match",
"typing.get_type_hints"
] | [((8166, 8211), 'numpy.arange', 'np.arange', (['x_min', 'x_max', 'preamble.x_increment'], {}), '(x_min, x_max, preamble.x_increment)\n', (8175, 8211), True, 'import numpy as np\n'), ((1482, 1530), 're.match', 're.match', (['"""^\\\\d+\\\\.\\\\d+\\\\.\\\\d+\\\\.\\\\d+$"""', 'address'], {}), "('^\\\\d+\\\\.\\\\d+\\\\.\\\... |
# Copyright 2014 DreamHost, LLC
#
# Author: DreamHost, 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 applicabl... | [
"django.utils.translation.ugettext",
"django.template.loader.render_to_string",
"logging.getLogger"
] | [((739, 766), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (756, 766), False, 'import logging\n'), ((933, 989), 'django.template.loader.render_to_string', 'template.loader.render_to_string', (['template_name', 'context'], {}), '(template_name, context)\n', (965, 989), False, 'from djang... |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
import os
from sqlalchemy_utils import create_database, database_exists
app = Flask(__name__)
# configure Flask using environment variables
# app.config.from_pyfile("config.py")
# not u... | [
"flask.Flask",
"os.environ.get",
"flask_sqlalchemy.SQLAlchemy",
"flask_bcrypt.Bcrypt",
"flask_login.LoginManager"
] | [((212, 227), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (217, 227), False, 'from flask import Flask\n'), ((414, 444), 'os.environ.get', 'os.environ.get', (['"""DATABASE_URL"""'], {}), "('DATABASE_URL')\n", (428, 444), False, 'import os\n'), ((705, 720), 'flask_sqlalchemy.SQLAlchemy', 'SQLAlchemy', (['... |
import secrets
from typing import Tuple
import cipher_common
import gcd
from sm2_common import *
# inferred from sm2_common.n
_pt_chunk_length = 31
_ct_chunk_length = 96
_byte_int_conversion_endian = 'big'
_p = 265371653
_g = 2
def gen_key() -> Tuple[fp, ECPoint]:
# [0, n - 1) -> [1, n)
x = secrets.randbel... | [
"cipher_common.decrypt_file",
"secrets.randbelow",
"cipher_common.encrypt_file",
"gcd.get_modular_inverse"
] | [((305, 329), 'secrets.randbelow', 'secrets.randbelow', (['(n - 1)'], {}), '(n - 1)\n', (322, 329), False, 'import secrets\n'), ((2113, 2225), 'cipher_common.encrypt_file', 'cipher_common.encrypt_file', (['pt_filename', 'ct_filename', 'pk', '_encrypt_chunk', '_pt_chunk_length', '_ct_chunk_length'], {}), '(pt_filename, ... |
from django.contrib import admin
# Register your models here.
from .models import Music
admin.site.register(Music) | [
"django.contrib.admin.site.register"
] | [((90, 116), 'django.contrib.admin.site.register', 'admin.site.register', (['Music'], {}), '(Music)\n', (109, 116), False, 'from django.contrib import admin\n')] |
from guardian.admin import GuardedModelAdmin
from django.utils.translation import gettext as _
from user.admin import fileshare_site
from permission.models import BigUserObjectPermission
class ObjectAdminPermissions(GuardedModelAdmin):
list_display = ('id', 'object_pk', 'permission')
search_fields = ('objec... | [
"user.admin.fileshare_site.register"
] | [((891, 963), 'user.admin.fileshare_site.register', 'fileshare_site.register', (['BigUserObjectPermission', 'ObjectAdminPermissions'], {}), '(BigUserObjectPermission, ObjectAdminPermissions)\n', (914, 963), False, 'from user.admin import fileshare_site\n')] |
"""entry point to run all tests"""
import distutils.util
import os.path
import sys
import unittest
if __name__ == '__main__':
plat_specifier = 'lib.{0}-{1}'.format(distutils.util.get_platform(),
sys.version[0:3])
tests_dir = os.path.dirname(os.path.abspath(__file__))
... | [
"unittest.main"
] | [((839, 854), 'unittest.main', 'unittest.main', ([], {}), '()\n', (852, 854), False, 'import unittest\n')] |
import librosa
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import os
import time
import multiprocessing
import pickle
import torch
from data_tools import extract_features
def smoothing_v1(label):
smoothed_label = []
# Smooth with 3 consecutive windows
for i in range(2, len(la... | [
"pickle.dump",
"matplotlib.pyplot.figure",
"torch.device",
"os.path.join",
"multiprocessing.cpu_count",
"matplotlib.pyplot.close",
"torch.load",
"matplotlib.pyplot.yticks",
"data_tools.extract_features",
"matplotlib.pyplot.xticks",
"seaborn.set",
"matplotlib.pyplot.show",
"torch.max",
"tor... | [((2057, 2085), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(15, 10)'}), '(figsize=(15, 10))\n', (2067, 2085), True, 'import matplotlib.pyplot as plt\n'), ((2090, 2099), 'seaborn.set', 'sns.set', ([], {}), '()\n', (2097, 2099), True, 'import seaborn as sns\n'), ((2454, 2485), 'matplotlib.pyplot.xlabel',... |
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
from uuid import uuid5
import logging
from pathlib import Path
from nipype.pipeline import engine as pe
from fmriprep import config
from .factory import FactoryContext
from .mriqc... | [
"pathlib.Path",
"uuid.uuid5",
"logging.getLogger"
] | [((704, 733), 'logging.getLogger', 'logging.getLogger', (['"""halfpipe"""'], {}), "('halfpipe')\n", (721, 733), False, 'import logging\n'), ((1217, 1248), 'uuid.uuid5', 'uuid5', (['spec.uuid', 'database.sha1'], {}), '(spec.uuid, database.sha1)\n', (1222, 1248), False, 'from uuid import uuid5\n'), ((2586, 2599), 'pathli... |
# Copyright 2017 QuantRocket - 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 law or ... | [
"quantrocket.houston.houston.raise_for_status_with_json",
"quantrocket.cli.utils.output.json_to_cli"
] | [((1300, 1344), 'quantrocket.houston.houston.raise_for_status_with_json', 'houston.raise_for_status_with_json', (['response'], {}), '(response)\n', (1334, 1344), False, 'from quantrocket.houston import houston\n'), ((1880, 1924), 'quantrocket.houston.houston.raise_for_status_with_json', 'houston.raise_for_status_with_j... |
# coding=utf-8
from django.contrib import admin
from models import Post
# Register your models here.
admin.site.register(Post)
| [
"django.contrib.admin.site.register"
] | [((102, 127), 'django.contrib.admin.site.register', 'admin.site.register', (['Post'], {}), '(Post)\n', (121, 127), False, 'from django.contrib import admin\n')] |
'''
Created on Nov 23, 2021
@author: mballance
'''
import os
import subprocess
from typing import List
from mkdv.job_spec import JobSpec
from mkdv.runners.allure_reporter import AllureReporter
from mkdv.runners.runner import Runner
from mkdv.runners.runner_spec import RunnerSpec
from allure_commons.model2 import Stat... | [
"copy.deepcopy",
"subprocess.Popen",
"mkdv.runners.allure_reporter.AllureReporter",
"os.getcwd",
"os.path.join"
] | [((1235, 1310), 'subprocess.Popen', 'subprocess.Popen', (['cmdline'], {'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.STDOUT'}), '(cmdline, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n', (1251, 1310), False, 'import subprocess\n'), ((2198, 2218), 'mkdv.runners.allure_reporter.AllureReporter', 'AllureReporter... |
import cv2
import os
import pickle
dataset = list()
dataset_test = list()
# dataset = pickle.load(open('/Users/michaelshan/Documents/BUAA/实验室项目/data_yinlie.pkl','rb'))
img_cnt = 0
for root, dirs, files in os.walk('/home/syb/documents/Crack_Image_WSOD/data/cut/0/'):
for file in files:
# for macos
i... | [
"cv2.ximgproc.segmentation.createSelectiveSearchSegmentation",
"cv2.imread",
"os.walk",
"cv2.resize"
] | [((207, 266), 'os.walk', 'os.walk', (['"""/home/syb/documents/Crack_Image_WSOD/data/cut/0/"""'], {}), "('/home/syb/documents/Crack_Image_WSOD/data/cut/0/')\n", (214, 266), False, 'import os\n'), ((2693, 2752), 'os.walk', 'os.walk', (['"""/home/syb/documents/Crack_Image_WSOD/data/cut/1/"""'], {}), "('/home/syb/documents... |
from sklearn.preprocessing import LabelBinarizer, MultiLabelBinarizer
from .BaseEncoder import BaseEncoder
# This is a copy and paste of tfidf_extractor.py with some code moving, testing for the moment
class GenericLabelBinarizer(BaseEncoder):
_is_multiclass = None
_is_multilabel = None
_encoder = None
... | [
"sklearn.preprocessing.LabelBinarizer",
"sklearn.preprocessing.MultiLabelBinarizer"
] | [((1296, 1317), 'sklearn.preprocessing.MultiLabelBinarizer', 'MultiLabelBinarizer', ([], {}), '()\n', (1315, 1317), False, 'from sklearn.preprocessing import LabelBinarizer, MultiLabelBinarizer\n'), ((1624, 1640), 'sklearn.preprocessing.LabelBinarizer', 'LabelBinarizer', ([], {}), '()\n', (1638, 1640), False, 'from skl... |
#Import dependencies
import numpy as np
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
#Use Flask to create your routes.
from flask import Flask, jsonify
#Home page.
engine = create_engine("sqlite:///Resources/hawaii.sq... | [
"numpy.ravel",
"flask.Flask",
"sqlalchemy.orm.Session",
"flask.jsonify",
"sqlalchemy.create_engine",
"sqlalchemy.ext.automap.automap_base"
] | [((276, 326), 'sqlalchemy.create_engine', 'create_engine', (['"""sqlite:///Resources/hawaii.sqlite"""'], {}), "('sqlite:///Resources/hawaii.sqlite')\n", (289, 326), False, 'from sqlalchemy import create_engine, func\n'), ((335, 349), 'sqlalchemy.ext.automap.automap_base', 'automap_base', ([], {}), '()\n', (347, 349), F... |
import time
import asyncio
start = time.time()
def tic():
return 'at %1.1f seconds' % (time.time() - start)
async def gr1():
# Busy waits for a second, but we don't want to stick around...
print('gr1 started work: {}'.format(tic()))
await asyncio.sleep(2)
print('gr1 ended work: {}'.format(tic()... | [
"asyncio.sleep",
"asyncio.get_event_loop",
"asyncio.wait",
"time.time"
] | [((36, 47), 'time.time', 'time.time', ([], {}), '()\n', (45, 47), False, 'import time\n'), ((691, 715), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (713, 715), False, 'import asyncio\n'), ((846, 865), 'asyncio.wait', 'asyncio.wait', (['tasks'], {}), '(tasks)\n', (858, 865), False, 'import asyn... |
#!/usr/bin/python
import re
class Printer:
def __init__(self):
self.r_file = open("ThostFtdcUserApiStruct.h")
self.o_file = open('ThostFtdcUserApiStructPrint.hh', 'wb')
self.struct_status = False
self.stru_name = ''
self.obj_name = ''
def fileHead(self):
self.o... | [
"re.compile"
] | [((2334, 2359), 're.compile', 're.compile', (['"""struct (.*)"""'], {}), "('struct (.*)')\n", (2344, 2359), False, 'import re\n'), ((2394, 2411), 're.compile', 're.compile', (['"""\\\\{"""'], {}), "('\\\\{')\n", (2404, 2411), False, 'import re\n'), ((2446, 2464), 're.compile', 're.compile', (['"""\\\\};"""'], {}), "('\... |
# Copyright (c) 2021 PaddlePaddle 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 appli... | [
"tqdm.tqdm",
"numpy.load",
"sklearn.preprocessing.StandardScaler",
"argparse.ArgumentParser",
"logging.info",
"pathlib.Path",
"jsonlines.open",
"paddlespeech.t2s.datasets.data_table.DataTable",
"operator.itemgetter"
] | [((2270, 2399), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Normalize dumped raw features (See detail in parallel_wavegan/bin/normalize.py)."""'}), "(description=\n 'Normalize dumped raw features (See detail in parallel_wavegan/bin/normalize.py).'\n )\n", (2293, 2399), False, 'i... |
from angr.state_plugins import SimSolver
from archinfo.arch_amd64 import ArchAMD64
import claripy
import copy
import datetime
import itertools
import os
from pathlib import Path
from kalm import utils
from kalm.plugins.sizes import SizesPlugin
from kalm.solver import KalmSolver
from klint import ghostmap... | [
"copy.deepcopy",
"archinfo.arch_amd64.ArchAMD64",
"klint.statistics.work_start",
"klint.statistics.work_end",
"itertools.count",
"kalm.plugins.sizes.SizesPlugin",
"pathlib.Path",
"angr.state_plugins.SimSolver",
"klint.verif.symbex.symbex",
"datetime.datetime.now",
"kalm.solver.KalmSolver"
] | [((1763, 1787), 'itertools.count', 'itertools.count', (['(1000000)'], {}), '(1000000)\n', (1778, 1787), False, 'import itertools\n'), ((2263, 2293), 'klint.statistics.work_start', 'statistics.work_start', (['"""verif"""'], {}), "('verif')\n", (2284, 2293), False, 'from klint import statistics\n'), ((2486, 2553), 'klint... |
#!/usr/bin/env python3
# coding: utf-8
#
# © 2021 Qualcomm Innovation Center, Inc. All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""
Top-level configuration file for Gunyah build system.
This module constructs an instance of AbstractBuildGraph, and passes it to the
real build system which is in tools... | [
"json.dump",
"os.makedirs",
"os.getcwd",
"os.path.dirname",
"runpy.run_path",
"pipes.quote",
"os.path.relpath",
"os.path.normpath",
"os.path.join",
"re.sub",
"re.compile"
] | [((1176, 1206), 'os.path.join', 'os.path.join', (['"""tools"""', '"""build"""'], {}), "('tools', 'build')\n", (1188, 1206), False, 'import os\n'), ((2109, 2146), 're.compile', 're.compile', (['"""\\\\$((\\\\w+)\\\\b|{(\\\\w+)})"""'], {}), "('\\\\$((\\\\w+)\\\\b|{(\\\\w+)})')\n", (2119, 2146), False, 'import re\n'), ((1... |
import torch.nn as nn
def get_loss_function(loss_type: str = "cross_entropy_loss"):
if loss_type == "cross_entropy_loss":
return nn.CrossEntropyLoss()
else:
raise NotImplmentedError(f"loss type: {loss_type} not implemented")
| [
"torch.nn.CrossEntropyLoss"
] | [((144, 165), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (163, 165), True, 'import torch.nn as nn\n')] |
"""
Trains a network-enhanced autoencoder (netAE) for semi-supervised dimensionality
reduction of single-cell RNA-sequencing.
@author: <NAME>
@contact: <EMAIL>
@date: 10/16/2019
"""
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import argparse
# define device
# make sure to conver... | [
"torch.LongTensor",
"torch.optim.lr_scheduler.ReduceLROnPlateau",
"data.Dataset",
"torch.save",
"torch.cuda.is_available",
"torch.no_grad"
] | [((394, 419), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (417, 419), False, 'import torch\n'), ((3801, 3963), 'torch.optim.lr_scheduler.ReduceLROnPlateau', 'optim.lr_scheduler.ReduceLROnPlateau', (['optimizer'], {'mode': '"""min"""', 'factor': 'lr_decay', 'patience': '(5)', 'verbose': '(Tru... |
from __future__ import annotations
import os
import sys
from argparse import ArgumentParser
from pathlib import Path
from typing import Any
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from scipy.stats import exponnorm, gamma, lognorm, norm
from clovars.utils import Qu... | [
"seaborn.lineplot",
"seaborn.kdeplot",
"argparse.ArgumentParser",
"numpy.amin",
"matplotlib.pyplot.ylim",
"pandas.read_csv",
"numpy.roll",
"os.path.exists",
"numpy.amax",
"pandas.read_excel",
"pathlib.Path",
"numpy.histogram",
"matplotlib.pyplot.subplots"
] | [((810, 826), 'pathlib.Path', 'Path', (['input_file'], {}), '(input_file)\n', (814, 826), False, 'from pathlib import Path\n'), ((1332, 1348), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (1346, 1348), False, 'from argparse import ArgumentParser\n'), ((5077, 5109), 'numpy.histogram', 'np.histogram', (... |
from django.urls import path
# from .views import AboutUs, Home
from .views import *
urlpatterns = [
path('', Home, name='home-page'), # http://localhost:8000/
path('about/', AboutUs, name='about-page'), # http://localhost:8000/about/
path('contact/', ContactUs, name='contact-page'),
] | [
"django.urls.path"
] | [((108, 140), 'django.urls.path', 'path', (['""""""', 'Home'], {'name': '"""home-page"""'}), "('', Home, name='home-page')\n", (112, 140), False, 'from django.urls import path\n'), ((172, 214), 'django.urls.path', 'path', (['"""about/"""', 'AboutUs'], {'name': '"""about-page"""'}), "('about/', AboutUs, name='about-page... |
"""
Definition of the :class:`DataAcquisitionViewSet` class.
"""
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.db.models.query import QuerySet
from pylabber.views.defaults import DefaultsMixin
from research.filters.data_acquisition_filter import DataAcquisitionF... | [
"research.utils.data_acquisition_models.get_data_acquisition_models",
"django.contrib.contenttypes.models.ContentType.objects.all"
] | [((797, 822), 'django.contrib.contenttypes.models.ContentType.objects.all', 'ContentType.objects.all', ([], {}), '()\n', (820, 822), False, 'from django.contrib.contenttypes.models import ContentType\n'), ((924, 953), 'research.utils.data_acquisition_models.get_data_acquisition_models', 'get_data_acquisition_models', (... |
import os
from unittest import TestCase
TEST_FILES_DIR = os.path.join(os.path.dirname(__file__), "files")
class BaseTestCase(TestCase):
def _create_file(self, filename, content=""):
self.files.append(filename)
with open(filename, "a") as file_:
file_.write(content)
def setUp(self... | [
"os.path.dirname",
"os.remove"
] | [((71, 96), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (86, 96), False, 'import os\n'), ((367, 392), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (382, 392), False, 'import os\n'), ((500, 519), 'os.remove', 'os.remove', (['filename'], {}), '(filename)\n', (509... |
from django.db import models
from phonenumber_field.modelfields import PhoneNumberField
class CustomerDetails(models.Model):
"""
Stores the information about all the customers
"""
name = models.CharField(max_length=20, unique=True)
first_name = models.CharField(max_length=30)
telephone_number ... | [
"django.db.models.CharField",
"django.db.models.DateTimeField",
"django.db.models.DateField",
"phonenumber_field.modelfields.PhoneNumberField"
] | [((205, 249), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(20)', 'unique': '(True)'}), '(max_length=20, unique=True)\n', (221, 249), False, 'from django.db import models\n'), ((267, 298), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(30)'}), '(max_length=30)\n', (283... |
import pytest
import unipixel
from . import utils
PARAMS = utils.product_dict(**{
"pin": [None],
"n": [16],
"auto_write": [True, False],
"bpp": [3, 4],
"pixel_order": [unipixel.RGB, unipixel.GRB, unipixel.RGBW, unipixel.GRBW, None]
})
@pytest.fixture(params=PARAMS)
def test_strip(request):
p... | [
"unipixel.UniPixel",
"pytest.fixture"
] | [((260, 289), 'pytest.fixture', 'pytest.fixture', ([], {'params': 'PARAMS'}), '(params=PARAMS)\n', (274, 289), False, 'import pytest\n'), ((353, 379), 'unipixel.UniPixel', 'unipixel.UniPixel', ([], {}), '(**param)\n', (370, 379), False, 'import unipixel\n')] |
import numpy as np
from core.ukf import build_ekf, build_ukf, get_QR
class VGraph(object):
""" Simple wrapper for visibility graph """
# TODO : unify dynamic container interface or something.
# (i.e. with Landmarks() )
def __init__(self, cvt, cap0=1024):
# processing handle
self.cvt_ = ... | [
"numpy.random.uniform",
"core.ukf.build_ekf",
"numpy.empty",
"numpy.float32",
"numpy.asarray",
"numpy.argsort",
"numpy.where",
"numpy.linalg.norm",
"numpy.arange",
"numpy.int32",
"core.ukf.get_QR",
"numpy.cos",
"numpy.sin",
"numpy.matmul",
"numpy.unique"
] | [((666, 677), 'core.ukf.build_ekf', 'build_ekf', ([], {}), '()\n', (675, 677), False, 'from core.ukf import build_ekf, build_ukf, get_QR\n'), ((821, 854), 'numpy.empty', 'np.empty', (['(cap0,)'], {'dtype': 'np.int32'}), '((cap0,), dtype=np.int32)\n', (829, 854), True, 'import numpy as np\n'), ((901, 934), 'numpy.empty'... |
from lesion_coder import utils
from lesion_coder.dataset import ImageData
from lesion_coder.model import BaseAutoEncoder
import pandas as pd
import torch
import torch.nn as nn
import argparse
import os
from tqdm import tqdm
import time
from torchvision.utils import save_image
from test import test
import matplotlib.pyp... | [
"matplotlib.pyplot.title",
"lesion_coder.utils.get_train_transform",
"argparse.ArgumentParser",
"lesion_coder.model.BaseAutoEncoder",
"pandas.read_csv",
"time.strftime",
"torch.cat",
"matplotlib.pyplot.figure",
"torch.device",
"torch.no_grad",
"os.path.join",
"pandas.DataFrame",
"torch.nn.MS... | [((490, 504), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (502, 504), True, 'import pandas as pd\n'), ((831, 873), 'lesion_coder.utils.slit_data', 'utils.slit_data', (['df', 'test_split', 'val_split'], {}), '(df, test_split, val_split)\n', (846, 873), False, 'from lesion_coder import utils\n'), ((1286, 1385),... |
import os
import numpy as np
import time
from algs.aecnn.genetic.population import Population, Individual, DenseUnit, ResUnit, PoolUnit
from compute.file import get_algo_local_dir
from comm.log import Log
import platform
from algs.aecnn.genetic.statusupdatetool import StatusUpdateTool
class Utils(object):
@classm... | [
"algs.aecnn.genetic.statusupdatetool.StatusUpdateTool.get_input_size",
"time.strftime",
"algs.aecnn.genetic.population.DenseUnit",
"algs.aecnn.genetic.population.Individual",
"os.path.dirname",
"os.path.exists",
"compute.file.get_algo_local_dir",
"numpy.max",
"algs.aecnn.genetic.statusupdatetool.Sta... | [((1031, 1056), 'os.path.exists', 'os.path.exists', (['file_name'], {}), '(file_name)\n', (1045, 1056), False, 'import os\n'), ((3656, 3690), 'algs.aecnn.genetic.statusupdatetool.StatusUpdateTool.get_init_params', 'StatusUpdateTool.get_init_params', ([], {}), '()\n', (3688, 3690), False, 'from algs.aecnn.genetic.status... |
import hashlib
import time
from Crypto.Cipher import AES
import base64
def user_sign_api(data, private_key):
"""
用户签名+时间戳 md5加密
:param data:
:param private_key:
:return:
"""
api_key = private_key
# 当前时间
now_time = time.time()
client_time = str(now_time).split('.')[0]
# si... | [
"base64.urlsafe_b64encode",
"hashlib.md5",
"Crypto.Cipher.AES.new",
"time.time"
] | [((254, 265), 'time.time', 'time.time', ([], {}), '()\n', (263, 265), False, 'import time\n'), ((333, 346), 'hashlib.md5', 'hashlib.md5', ([], {}), '()\n', (344, 346), False, 'import hashlib\n'), ((645, 674), 'base64.urlsafe_b64encode', 'base64.urlsafe_b64encode', (['src'], {}), '(src)\n', (669, 674), False, 'import ba... |
# -*- coding: utf-8 -*-
import logging
import os
import sys
from logging.config import dictConfig
from scrapy.settings import Settings
from scrapy.utils.log import DEFAULT_LOGGING, TopLevelFormatter
from twisted.python import log
from twisted.python.log import startLoggingWithObserver
from twisted.python.logfile impor... | [
"twisted.python.log.err",
"logging.NullHandler",
"os.path.join",
"twisted.python.log.startLoggingWithObserver",
"logging.FileHandler",
"twisted.python.log.FileLogObserver.emit",
"os.path.exists",
"logging.root.setLevel",
"twisted.python.log.msg",
"scrapy.settings.Settings",
"logging.StreamHandle... | [((906, 937), 'twisted.python.log.err', 'log.err', (['_stuff', '_why'], {}), '(_stuff, _why, **kwargs)\n', (913, 937), False, 'from twisted.python import log\n'), ((3084, 3140), 'twisted.python.log.startLoggingWithObserver', 'startLoggingWithObserver', (['observer.emit'], {'setStdout': '(False)'}), '(observer.emit, set... |
import argparse
import sys
import runpy
from aocd import get_data
parser = argparse.ArgumentParser(description="Process some integers.")
parser.add_argument("--year", "-y", type=int, default=2021)
parser.add_argument("--day", "-d", type=int)
parser.add_argument("--file", "-f", type=argparse.FileType("r"))
args = par... | [
"runpy.importlib.import_module",
"argparse.ArgumentParser",
"aocd.get_data",
"argparse.FileType"
] | [((77, 138), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Process some integers."""'}), "(description='Process some integers.')\n", (100, 138), False, 'import argparse\n'), ((285, 307), 'argparse.FileType', 'argparse.FileType', (['"""r"""'], {}), "('r')\n", (302, 307), False, 'import a... |
"""
Base class for Mask objects. Contains many common utilities used for accessing masks. The mask itself is
represented under the hood as a three dimensional numpy :obj:`ndarray` object. The dimensions are
``[NUM_FREQ, NUM_HOPS, NUM_CHAN]``. Safe accessors for these array indices are in :ref:`constants` as well as
b... | [
"numpy.array_equal",
"numpy.ones",
"numpy.zeros",
"numpy.expand_dims"
] | [((6801, 6838), 'numpy.array_equal', 'np.array_equal', (['self.mask', 'other.mask'], {}), '(self.mask, other.mask)\n', (6815, 6838), True, 'import numpy as np\n'), ((2584, 2637), 'numpy.expand_dims', 'np.expand_dims', (['value'], {'axis': 'constants.STFT_CHAN_INDEX'}), '(value, axis=constants.STFT_CHAN_INDEX)\n', (2598... |
# !/usr/bin/python
# -*- coding: utf-8 -*-
import os
import logging
import hashlib
import pybpodgui_api
from pybpodgui_api.utils.send2trash_wrapper import send2trash
from sca.formats import json
from pybpodgui_api.models.project.project_base import ProjectBase
logger = logging.getLogger(__name__)
class ProjectIO(P... | [
"os.makedirs",
"os.path.basename",
"os.path.exists",
"os.path.isfile",
"pybpodgui_api.utils.send2trash_wrapper.send2trash",
"sca.formats.json.load",
"sca.formats.json.dump",
"os.path.join",
"os.listdir",
"logging.getLogger"
] | [((273, 300), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (290, 300), False, 'import logging\n'), ((876, 906), 'os.path.basename', 'os.path.basename', (['project_path'], {}), '(project_path)\n', (892, 906), False, 'import os\n'), ((1195, 1227), 'os.path.join', 'os.path.join', (['self.p... |
import cv2
import numpy as np
import asyncio
from cursor_func import cursorControl
from unified_detector import Fingertips
from hand_detector.detector import SOLO, YOLO
status = False
hand_detection_method = 'yolo'
if hand_detection_method is 'solo':
hand = SOLO(weights='weights/solo.h5', threshold=0.8)
elif han... | [
"asyncio.get_event_loop",
"hand_detector.detector.SOLO",
"cursor_func.cursorControl",
"cv2.waitKey",
"numpy.asarray",
"cv2.imshow",
"cv2.VideoCapture",
"numpy.mean",
"cv2.rectangle",
"unified_detector.Fingertips",
"cv2.destroyAllWindows",
"hand_detector.detector.YOLO"
] | [((564, 605), 'unified_detector.Fingertips', 'Fingertips', ([], {'weights': '"""weights/classes8.h5"""'}), "(weights='weights/classes8.h5')\n", (574, 605), False, 'from unified_detector import Fingertips\n'), ((613, 632), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (629, 632), False, 'import cv2\n')... |
from PyQt4 import QtGui
import sys
app = QtGui.QApplication(sys.argv)
w = QtGui.QWidget()
w.resize(250, 150)
w.move(300, 300)
w.setWindowTitle('Simple')
w.show()
tuopan = QtGui.QSystemTrayIcon(w)
icon1 = QtGui.QIcon('tuopan.jpg')
tuopan.setIcon(icon1)
tuopan.show()
tuopan.showMessage("haha","content... | [
"PyQt4.QtGui.QSystemTrayIcon",
"PyQt4.QtGui.QIcon",
"PyQt4.QtGui.QApplication",
"PyQt4.QtGui.QWidget"
] | [((45, 73), 'PyQt4.QtGui.QApplication', 'QtGui.QApplication', (['sys.argv'], {}), '(sys.argv)\n', (63, 73), False, 'from PyQt4 import QtGui\n'), ((81, 96), 'PyQt4.QtGui.QWidget', 'QtGui.QWidget', ([], {}), '()\n', (94, 96), False, 'from PyQt4 import QtGui\n'), ((187, 211), 'PyQt4.QtGui.QSystemTrayIcon', 'QtGui.QSystemT... |
from dateutil.parser import parse
from datetime import timedelta
from . import ForecastMixin
class Forecast(ForecastMixin):
url = 'https://opendata.atmo-na.org/api/v1/indice/atmo/'
zone_type = 'insee'
insee_list = ['33063', '79005', '16102', '64102', '64445', '19272', '87085',
'24322', '40088', '17... | [
"dateutil.parser.parse",
"datetime.timedelta"
] | [((538, 549), 'dateutil.parser.parse', 'parse', (['date'], {}), '(date)\n', (543, 549), False, 'from dateutil.parser import parse\n'), ((552, 571), 'datetime.timedelta', 'timedelta', ([], {'hours': '(24)'}), '(hours=24)\n', (561, 571), False, 'from datetime import timedelta\n'), ((878, 918), 'dateutil.parser.parse', 'p... |
#!/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.
"""Unit tests for classes in chromium_utils.py."""
import os
import sys
import tempfile
import unittest
import test_env # pylint... | [
"unittest.main",
"tempfile.NamedTemporaryFile",
"os.remove",
"common.chromium_utils.RunCommand",
"common.chromium_utils.GetBotsFromBuildersFile"
] | [((6900, 6915), 'unittest.main', 'unittest.main', ([], {}), '()\n', (6913, 6915), False, 'import unittest\n'), ((1168, 1254), 'common.chromium_utils.RunCommand', 'chromium_utils.RunCommand', (['mycmd'], {'print_cmd': '(False)', 'parser_func': 'parser.ProcessLine'}), '(mycmd, print_cmd=False, parser_func=parser.\n Pr... |
#!/usr/bin/env python
"""TODO: place all consensus methods here
load_consensus_map
make_consensus_tree
etc...
"""
from t2t.nlevel import RANK_ORDER
from numpy import zeros, where, logical_or, long
def taxa_score(master, reps):
"""Score taxa strings by contradictions observed in reps"""
n_ranks = len(RANK_OR... | [
"numpy.logical_or"
] | [((2013, 2063), 'numpy.logical_or', 'logical_or', (['(rep_hash == master_hash)', '(rep_hash == 0)'], {}), '(rep_hash == master_hash, rep_hash == 0)\n', (2023, 2063), False, 'from numpy import zeros, where, logical_or, long\n')] |
import asyncio
from .protocol import SseServerProtocol
__all__ = ['serve']
@asyncio.coroutine
def serve(sse_handler, host=None, port=None, *, klass=SseServerProtocol,
**kwargs):
return (yield from asyncio.get_event_loop().create_server(
lambda: klass(sse_handler), host, port, **kwargs))
| [
"asyncio.get_event_loop"
] | [((215, 239), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (237, 239), False, 'import asyncio\n')] |
from collections import namedtuple
from typing import NamedTuple
from pybaum.typecheck import get_type
def test_namedtuple_is_discovered():
bla = namedtuple("bla", ["a", "b"])(1, 2)
assert get_type(bla) == namedtuple
def test_typed_namedtuple_is_discovered():
class Blubb(NamedTuple):
a: int
... | [
"pybaum.typecheck.get_type",
"collections.namedtuple"
] | [((153, 182), 'collections.namedtuple', 'namedtuple', (['"""bla"""', "['a', 'b']"], {}), "('bla', ['a', 'b'])\n", (163, 182), False, 'from collections import namedtuple\n'), ((200, 213), 'pybaum.typecheck.get_type', 'get_type', (['bla'], {}), '(bla)\n', (208, 213), False, 'from pybaum.typecheck import get_type\n'), ((3... |
"""
Created: 04 May 2020
Author: <NAME>
"""
from administration.models import ArtistAnalyticsCalculation
# -----------------------------------------------------------------------------
def retrieve_calculation(calculation_name, default=None):
try:
calc = ArtistAnalyticsCalculation.objects.get(name=calcul... | [
"administration.models.ArtistAnalyticsCalculation.objects.get"
] | [((270, 331), 'administration.models.ArtistAnalyticsCalculation.objects.get', 'ArtistAnalyticsCalculation.objects.get', ([], {'name': 'calculation_name'}), '(name=calculation_name)\n', (308, 331), False, 'from administration.models import ArtistAnalyticsCalculation\n')] |
from discord.ext import commands
import dice
class Roll(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def roll(self, ctx, arg):
try:
await ctx.send(dice.roll(arg))
except dice.DiceBaseException as e:
print(e.pretty_print()) | [
"discord.ext.commands.command",
"dice.roll"
] | [((130, 148), 'discord.ext.commands.command', 'commands.command', ([], {}), '()\n', (146, 148), False, 'from discord.ext import commands\n'), ((225, 239), 'dice.roll', 'dice.roll', (['arg'], {}), '(arg)\n', (234, 239), False, 'import dice\n')] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.